# Texel: A field guide to 3D techniques > Texel is a field guide to 3D graphics techniques: what each one is, when to choose it, where it runs, and the verified papers, code and presets behind it. Every author, year, venue, license and link was returned by an authority (arXiv, Crossref, doi.org, GitHub or HTTP + Wayback) on a recorded date. License: CC BY 4.0 for Texel's own text and data; cite the original authors. --- id: "2d-gaussian-splatting" title: "2D Gaussian Splatting" aliases: [2DGS] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, desktop-gpu] year_introduced: 2024 inputs: [photos, camera-poses, point-cloud] outputs: [gaussians, mesh, depth] style: "photoreal" dynamic: "static" cost: "medium" authority: "Huang et al., 2024" url: "https://texelatlas.vercel.app/t/2d-gaussian-splatting/" sources_verified_at: "2026-11-29" --- # 2D Gaussian Splatting (Huang et al., 2024) > Replaces 3D ellipsoids with oriented flat 2D Gaussian discs, ray-splat intersection and depth/normal regularisers so that splats form a thin, view-consistent surface that can be meshed. ## Reach for it when - need a clean mesh out of a photo capture quickly - splat scene depth looks inconsistent between viewing angles - want accurate depth and surfaces from photos in minutes - blobby splats don't form a thin solid surface ## How it works Each primitive is an elliptical disc with a well-defined normal, so the field is a collection of surfels instead of volumetric blobs. Rendering intersects each pixel's ray with the disc plane to compute exact local coordinates and evaluate the Gaussian there, avoiding the perspective approximation of 3DGS and giving view-consistent depth. Two regularisers shape geometry: a depth distortion loss pulls overlapping splats along a ray together, and a normal consistency loss aligns each splat's normal with the gradient of the rendered depth. Rendered depth maps from training views are fused with truncated signed distance integration and meshed with marching cubes, yielding surfaces far faster than neural SDF methods. ## When to use it Choose it when you need a mesh or accurate depth from a photo capture in minutes. Prefer [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) when pure view synthesis suffices, [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) for maximum detail if hours of training are acceptable, and [3DGUT (Unscented Transform Gaussian Splatting)](https://texelatlas.vercel.app/t/3dgut.md) when you need fisheye or secondary rays with a similar Gaussian pipeline. ## Cost medium — Training in tens of minutes on one GPU; slightly slower than 3DGS due to the regularisers. Measured GPU Weight: 296.46× baseline (extreme) — 9.1903 ms median / 9.215 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 255.87× baseline (extreme) — 4.0684 ms median (2.26× faster on L4). Ampere A100 scaling: 207.97× baseline (extreme) — 5.9894 ms median (1.53× faster on A100). ## Failure modes - Slightly lower novel-view PSNR than 3DGS due to the surface constraints - Reflective and transparent materials still produce holes or spurious sheets - Thin features like wires can be lost to the regularisers - TSDF fusion adds voxel-resolution smoothing to the final mesh ## Dataflow - Inputs: photos, camera-poses, point-cloud - Outputs: gaussians, mesh, depth - Platforms: cuda, desktop-gpu ## Presets ### 2D Gaussian Splatting — oriented flat elliptical surfel disks (left) vs ray-splat blended surface (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SURFEL_RAD": 0.22, "P_ASPECT": 1.55, "P_ROT_SPEED": 0.7, "P_SPLIT": 0.48 } ``` ```glsl const float P_SURFEL_RAD = 0.22; // P Surfel Disk Size [0.10, 0.34, 0.01] const float P_ASPECT = 1.55; // P Anisotropy Ratio [1.0, 2.5, 0.05] const float P_ROT_SPEED = 0.70; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Disks / 2DGS Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Fibonacci-sphere distribution of 36 flat oriented 2D Gaussian surfels tangent to an egg/vase surface void get2DSurfel(int idx, float spin, float rad, float aspect, out vec3 center, out vec3 tU, out vec3 tV, out vec3 normal, out vec3 col) { float fi = float(idx); float N = 36.0; float y = 1.0 - (fi + 0.5) / N * 2.0; float rHoriz = sqrt(max(1.0 - y * y, 0.0)); float phi = fi * 2.3999632; // golden angle vec3 dir = vec3(cos(phi) * rHoriz, y, sin(phi) * rHoriz); // Sculpted organic surface radius r(dir) float surfR = 0.62 + 0.10 * cos(y * 3.1415926 * 2.0) + 0.05 * cos(phi * 3.0); center = dir * surfR; normal = normalize(dir); // Local orthonormal tangent basis (tU, tV) spanning the flat 2D Gaussian disk! vec3 upRef = (abs(normal.y) < 0.92) ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); vec3 u0 = normalize(cross(upRef, normal)); vec3 v0 = cross(normal, u0); // Rotate shape in world space center.xz = rot2(spin * 0.62) * center.xz; center.yz = rot2(0.32) * center.yz; normal.xz = rot2(spin * 0.62) * normal.xz; normal.yz = rot2(0.32) * normal.yz; u0.xz = rot2(spin * 0.62) * u0.xz; u0.yz = rot2(0.32) * u0.yz; v0.xz = rot2(spin * 0.62) * v0.xz; v0.yz = rot2(0.32) * v0.yz; tU = u0 * (rad * aspect); tV = v0 * (rad / max(aspect, 0.5)); col = 0.52 + 0.42 * cos(phi * 0.5 + y * 2.2 + vec3(0.0, 2.094, 4.188)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isBlended = screenX >= split; float rad = clamp(P_SURFEL_RAD, 0.08, 0.36); float aspect = clamp(P_ASPECT, 1.0, 2.6); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.55)); vec3 bg = mix(vec3(0.022, 0.032, 0.054), vec3(0.064, 0.084, 0.132), smoothstep(-0.55, 0.55, uv.y)); // Exact ray-plane intersection against all 36 oriented flat 2D Gaussian surfels (Huang et al. 2024!) // Sort front-to-back using 4 depth slices so closer surfels occlude back-hemisphere surfels accurately vec3 accum = vec3(0.0); float T = 1.0; float rimOverlay = 0.0; vec3 lDir = normalize(vec3(0.56, 0.80, 0.55)); for (int pass = 0; pass < 4; pass++) { float tMin = 1.30 + float(pass) * 0.42; float tMax = tMin + 0.42; for (int i = 0; i < 36; i++) { vec3 c, tU, tV, n, baseC; get2DSurfel(i, spin, rad, aspect, c, tU, tV, n, baseC); // Exact perspective ray-splat plane intersection: t = dot(c - ro, n) / dot(rd, n) float denom = dot(rd, n); if (abs(denom) < 1e-4) continue; float tHit = dot(c - ro, n) / denom; if (tHit < tMin || tHit >= tMax) continue; if (denom > 0.0) continue; // front-facing surfel culling vec3 pHit = ro + rd * tHit; vec3 rel = pHit - c; // Local tangent-plane Gaussian coordinates (u, v) float uCoord = dot(rel, tU) / max(dot(tU, tU), 1e-5); float vCoord = dot(rel, tV) / max(dot(tV, tV), 1e-5); float r2 = uCoord * uCoord + vCoord * vCoord; if (r2 > 2.8) continue; float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 36.0); vec3 shaded = baseC * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.42; if (!isBlended) { // Left: Crisp flat elliptical surfel disks showing tangent orientation & 1-sigma disk rims float disk = smoothstep(1.05, 0.88, r2); float rim = smoothstep(0.14, 0.02, abs(sqrt(max(r2, 0.0)) - 0.96)); float axes = max(smoothstep(0.08, 0.02, abs(uCoord)), smoothstep(0.08, 0.02, abs(vCoord))) * step(r2, 0.92); vec3 dCol = mix(shaded, vec3(0.96, 0.98, 1.0), axes * 0.35); accum += T * disk * 0.88 * dCol; rimOverlay = max(rimOverlay, rim * T); T *= (1.0 - disk * 0.88); } else { // Right: Smooth 2D Gaussian alpha blending exp(-0.5 * (u^2 + v^2)) with consistent surface normals float g = exp(-1.25 * r2); float alpha = clamp(g * 0.86, 0.0, 0.96); accum += T * alpha * shaded; T *= (1.0 - alpha); } if (T < 0.01) break; } } vec3 col = accum + T * bg; if (!isBlended) { col = mix(col, vec3(0.98, 0.88, 0.38), rimOverlay * 0.78); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combination ideas - [ReSTIR path-traced relighting on 2D Gaussian surfels](https://texelatlas.vercel.app/ideas/surfel-splats-restir-path-tracing/) - [Captured rooms you can bump into](https://texelatlas.vercel.app/ideas/walkable-captured-scenes/) ## Sources 1. [primary] Binbin Huang, Zehao Yu, Anpei Chen, Andreas Geiger, Shenghua Gao (2024) 2D Gaussian Splatting for Geometrically Accurate Radiance Fields. arXiv preprint (cs.CV). https://arxiv.org/abs/2403.17888 (verified via arxiv on 2026-11-29) 2. [implementation] hbb1 (2024) hbb1/2d-gaussian-splatting. https://github.com/hbb1/2d-gaussian-splatting License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "2D Gaussian Splatting." https://texelatlas.vercel.app/t/2d-gaussian-splatting/ (accessed 2026-12-01). --- id: "3d-gaussian-ray-tracing" title: "3D Gaussian Ray Tracing (3DGRT)" aliases: [3DGRT, ray traced Gaussians] domain: "capture" stage: "capture" realtime: "realtime" platforms: [cuda, desktop-gpu] year_introduced: 2024 inputs: [gaussians, camera-poses] outputs: [ldr-image, radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Moenne-Loccoz et al., 2024" url: "https://texelatlas.vercel.app/t/3d-gaussian-ray-tracing/" sources_verified_at: "2026-11-29" --- # 3D Gaussian Ray Tracing (3DGRT) (Moenne-Loccoz et al., 2024) > Renders trained Gaussian particles by tracing rays through a BVH over them instead of projecting and sorting splats, which allows fisheye and rolling-shutter cameras, reflections and refraction. ## Reach for it when - splats need a fisheye or distorted camera - want reflections and refraction on gaussian splat scenes - rolling shutter camera model for splat rendering - render splats without sorting and popping ## How it works Each Gaussian is wrapped in a bounding proxy (a stretched icosahedron) and put in an RTX-accelerated BVH. For each camera ray, a hardware ray tracing pass collects the next k particles along the ray in chunks, each one is evaluated analytically for its maximum response along the ray, and their colour and opacity are alpha-composited front to back in sorted order. Because there is no projection to screen space, any camera model works, and rays can be spawned from hit points for secondary effects such as mirror reflections, refractions and shadows, which the paper does by inserting meshes alongside the particles. Training uses the same differentiable principle with tracing replacing rasterisation. Rasterising and tracing differ in sorting order, so the particle blending is per ray and exact. ## When to use it Choose it when the splat scene must be seen through non-pinhole cameras (fisheye, distorted lenses, rolling shutter), or composed with reflective or refractive meshes. Prefer [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) rasterisation for the fastest standard novel-view rendering, [3DGUT (Unscented Transform Gaussian Splatting)](https://texelatlas.vercel.app/t/3dgut.md) when you want camera distortion handled inside a rasteriser via unscented transforms, and [StopThePop (Sorted Gaussian Splatting)](https://texelatlas.vercel.app/t/stopthepop.md) to fix popping from per-tile sorting. ## Cost heavy — Slower than rasterisation but interactive on RTX-class GPUs per the authors; needs hardware ray tracing and more memory for the BVH. Measured GPU Weight: 15.98× baseline (moderate) — 0.5256 ms median / 0.543 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.6× baseline (moderate) — 0.2163 ms median (2.43× faster on L4). Ampere A100 scaling: 10.43× baseline (moderate) — 0.3005 ms median (1.75× faster on A100). ## Failure modes - Requires hardware ray tracing and CUDA/OptiX, so there is no browser or mobile path - BVH rebuilds are needed when Gaussians move, so highly dynamic scenes lose speed - Proxy-geometry bounds that are too tight clip the tails of Gaussians; too loose causes extra hits and slowdowns - Reflections of splats show the baked-in lighting and floaters of the reconstruction, not true materials ## Dataflow - Inputs: gaussians, camera-poses - Outputs: ldr-image, radiance - Platforms: cuda, desktop-gpu ## Presets ### 3DGRT — rasterized pinhole splats (left) vs ray-traced 3D Gaussians with mirror reflections & fisheye (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FISHEYE": 0.32, "P_SPLAT_R": 0.16, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.46 } ``` ```glsl const float P_FISHEYE = 0.32; // P Lens Distortion [0.0, 0.8, 0.02] const float P_SPLAT_R = 0.16; // P Gaussian Radius [0.08, 0.28, 0.01] const float P_ROT_SPEED = 0.65; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.46; // P Raster / 3DGRT Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Trace a ray through an orbital ring of 16 colored 3D Gaussian particles (exact ray-Gaussian max response) vec4 traceGaussianCloud(vec3 ro, vec3 rd, float spin, float rad) { vec3 acc = vec3(0.0); float T = 1.0; float invR2 = 1.0 / max(rad * rad, 1e-4); for (int i = 0; i < 16; i++) { float fi = float(i); float ang = fi * 6.2831853 / 16.0 + spin * 0.6; float ringR = 0.92 + 0.14 * sin(fi * 3.0); vec3 c = vec3(cos(ang) * ringR, 0.22 * sin(fi * 2.0 + spin), sin(ang) * ringR); vec3 oc = c - ro; float tMax = dot(oc, rd); if (tMax > 0.05) { vec3 perp = oc - rd * tMax; // Anisotropic stretch tangent to orbital ring vec3 tang = normalize(vec3(-sin(ang), 0.15, cos(ang))); float dTang = dot(perp, tang); vec3 dNorm = perp - tang * dTang; float m2 = (dot(dNorm, dNorm) * 1.45 + dTang * dTang * 0.42) * invR2; float g = exp(-m2 * 1.6); if (g > 0.01) { float a = clamp(g * 0.85, 0.0, 0.94); vec3 gCol = 0.52 + 0.48 * cos(fi * 0.42 + vec3(0.0, 2.1, 4.2)); gCol *= (0.85 + 0.45 * g); acc += T * a * gCol; T *= (1.0 - a); if (T < 0.02) break; } } } return vec4(acc, 1.0 - T); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isGRT = screenX >= split; float fish = clamp(P_FISHEYE, 0.0, 0.9); float rad = clamp(P_SPLAT_R, 0.06, 0.30); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.35, 2.55); // 3DGRT natively traces curved fisheye camera rays; pinhole rasterization assumes linear projection vec2 pUV = uv; if (isGRT) { float r2 = dot(uv, uv); pUV = uv * (1.0 + fish * r2 * 0.85); } vec3 rd = normalize(vec3(pUV - vec2(0.0, 0.06), -1.48)); vec3 bg = mix(vec3(0.022, 0.030, 0.052), vec3(0.068, 0.095, 0.155), smoothstep(-0.55, 0.55, rd.y)); // Checkerboard studio floor at y = -0.58 float tFloor = 1e5; if (rd.y < -0.01) { float tf = (-0.58 - ro.y) / rd.y; if (tf > 0.1 && tf < 16.0) tFloor = tf; } // Central mirror-chrome sphere at origin (R = 0.44) float b = dot(ro, rd); float c = dot(ro, ro) - 0.44 * 0.44; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; // Background scene (floor or sky) vec3 sceneCol = bg; if (tFloor < tSph && tFloor < 1e4) { vec3 fp = ro + rd * tFloor; vec2 chk = floor(fp.xz * 2.2); float pat = mod(chk.x + chk.y, 2.0); vec3 fAlb = mix(vec3(0.08, 0.10, 0.15), vec3(0.18, 0.22, 0.30), pat); // Secondary reflected Gaussian glow on floor in 3DGRT mode if (isGRT) { vec3 reflD = reflect(rd, vec3(0.0, 1.0, 0.0)); vec4 rGauss = traceGaussianCloud(fp + vec3(0.0, 0.02, 0.0), reflD, spin, rad * 1.15); fAlb += rGauss.rgb * 0.48; } sceneCol = mix(fAlb, bg, 1.0 - exp(-tFloor * 0.12)); } if (tSph < tFloor && tSph < 1e4) { vec3 hp = ro + rd * tSph; vec3 n = normalize(hp); vec3 lDir = normalize(vec3(0.55, 0.85, 0.45)); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 64.0); float fres = 0.15 + 0.85 * pow(1.0 - max(dot(n, -rd), 0.0), 3.0); if (isGRT) { // Exact secondary ray reflection through the 3D Gaussian BVH! vec3 reflD = reflect(rd, n); vec4 reflG = traceGaussianCloud(hp + n * 0.01, reflD, spin, rad); vec3 env = mix(vec3(0.05, 0.08, 0.14), vec3(0.24, 0.32, 0.46), smoothstep(-0.3, 0.6, reflD.y)); sceneCol = mix(env, reflG.rgb, reflG.a) * (0.45 + 0.55 * fres) + vec3(1.0) * spec * 0.9; } else { // Pinhole rasterizer cannot trace secondary rays into the 3DGS splat buffer float diff = max(dot(n, lDir), 0.0); sceneCol = vec3(0.16, 0.20, 0.28) * (0.35 + 0.65 * diff) + vec3(0.8) * spec * 0.55; } } // Primary ray 3D Gaussian particles composited over scene vec4 primG = traceGaussianCloud(ro, rd, spin, rad); vec3 col = primG.rgb + (1.0 - primG.a) * sceneCol; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combines with - [3DGUT (Unscented Transform Gaussian Splatting)](https://texelatlas.vercel.app/t/3dgut.md): 3DGUT shares the 3dgrut codebase and gives a rasterisation path for distorted cameras that complements the traced one. ## Sources 1. [primary] Nicolas Moenne-Loccoz, Ashkan Mirzaei, Or Perel, Riccardo de Lutio, Janick Martinez Esturo, Gavriel State, Sanja Fidler, Nicholas Sharp, Zan Gojcic (2024) 3D Gaussian Ray Tracing: Fast Tracing of Particle Scenes. arXiv preprint (cs.GR). https://arxiv.org/abs/2407.07090 (verified via arxiv on 2026-11-29) 2. [implementation] nv-tlabs (2025) nv-tlabs/3dgrut. https://github.com/nv-tlabs/3dgrut License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "3D Gaussian Ray Tracing (3DGRT)." https://texelatlas.vercel.app/t/3d-gaussian-ray-tracing/ (accessed 2026-12-01). --- id: "3dgut" title: "3DGUT (Unscented Transform Gaussian Splatting)" aliases: [3D Gaussian Unscented Transform] domain: "capture" stage: "capture" realtime: "realtime" platforms: [cuda, desktop-gpu] year_introduced: 2024 inputs: [photos, camera-poses] outputs: [gaussians] style: "photoreal" dynamic: "static" cost: "medium" authority: "Wu et al., 2024" url: "https://texelatlas.vercel.app/t/3dgut/" sources_verified_at: "2026-11-29" --- # 3DGUT (Unscented Transform Gaussian Splatting) (Wu et al., 2024) > Keeps the fast rasteriser of 3DGS but projects Gaussians with an unscented transform, supporting fisheye, rolling shutter and other distorted cameras and enabling secondary rays in the companion ray tracer. ## Reach for it when - splat training breaks on fisheye or wide-angle footage - rolling shutter distortion ruins my captured scene - drone or car camera captures won't reconstruct cleanly - want one trained scene to rasterise and also ray trace - reflections and refractions inside a trained splat scene ## How it works 3DGS projects each Gaussian through a first-order Jacobian of the camera model, which is only valid for pinhole cameras and breaks with strong lens distortion or time-varying poses. 3DGUT instead pushes a small set of sigma points sampled from each 3D Gaussian through the exact, possibly nonlinear camera projection, then refits a 2D Gaussian from the transformed points, as in the unscented Kalman filter. Because evaluation is point-wise it works for any projection function, including rolling-shutter models. Particle values are evaluated in 3D along the ray rather than in a 2D screen footprint, which also aligns the representation with ray tracing of the same primitives for reflections and refractions, as in the paired 3DGRT work. ## When to use it Choose it for wide-angle, fisheye or rolling-shutter captures (automotive, drones, action cameras) or when you want one trained scene to be rasterised and ray traced. Prefer [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for ordinary pinhole captures with the most mature ecosystem and [gsplat](https://texelatlas.vercel.app/t/gsplat.md) if you want a general library. ## Cost medium — Rasterisation speed is comparable to 3DGS; extra sigma-point projection adds a modest cost. ## Failure modes - Unscented approximation can be inaccurate for very large Gaussians near the camera under extreme distortion - Needs calibrated camera models, wrong distortion coefficients bake into the scene - Reference implementation is CUDA-only - Secondary-ray effects require the ray-tracing path, which is slower than rasterisation ## Dataflow - Inputs: photos, camera-poses - Outputs: gaussians - Platforms: cuda, desktop-gpu ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Sources 1. [primary] Qi Wu, Janick Martinez Esturo, Ashkan Mirzaei, Nicolas Moenne-Loccoz, Zan Gojcic (2024) 3DGUT: Enabling Distorted Cameras and Secondary Rays in Gaussian Splatting. arXiv preprint (cs.GR). https://arxiv.org/abs/2412.12507 (verified via arxiv on 2026-11-29) 2. [implementation] nv-tlabs (2025) nv-tlabs/3dgrut. https://github.com/nv-tlabs/3dgrut License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "3DGUT (Unscented Transform Gaussian Splatting)." https://texelatlas.vercel.app/t/3dgut/ (accessed 2026-12-01). --- id: "4d-gaussian-splatting" title: "4D Gaussian Splatting" aliases: [4DGS, dynamic gaussian splatting] domain: "capture" stage: "capture" realtime: "realtime" platforms: [cuda, desktop-gpu, python] year_introduced: 2023 inputs: [photos, camera-poses] outputs: [gaussians, animation] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Wu et al., 2023" url: "https://texelatlas.vercel.app/t/4d-gaussian-splatting/" sources_verified_at: "2026-11-29" --- # 4D Gaussian Splatting (Wu et al., 2023) > Extends 3D Gaussian splatting to moving scenes by adding time: either a canonical set of Gaussians deformed per timestamp or primitives that are Gaussian in x, y, z and t. ## Reach for it when - splat a scene that has moving people - want free viewpoint video from multi view cameras - reconstructed scene looks frozen when people or objects move - replay captured motion in real time ## How it works There are two main families. Deformation-field methods keep one canonical set of 3D Gaussians and learn a compact network, often a multi-resolution HexPlane over (x, y, z, t) plus a tiny decoder, that predicts per-Gaussian offsets in position, rotation and scale at a query time; the deformed Gaussians then go through the usual splat rasteriser. Native 4D methods instead optimise Gaussians in four dimensions and slice them at time t to get a 3D Gaussian, with spherindrical harmonics for view and time-dependent colour. Training uses multi-view video or monocular video with known poses and the same photometric loss as static splatting, plus regularisers on motion smoothness. Rendering at inference is the standard splat sort and blend, so frame rates stay real time. ## When to use it Choose it to capture and replay people or scenes in motion from synchronised multi-view video with free viewpoint. Prefer [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for static scenes, [Neural Radiance Fields (NeRF)](https://texelatlas.vercel.app/t/nerf.md)-based dynamic methods when memory per frame matters less than a fixed model, and [Web Gaussian Splat Renderers (three.js)](https://texelatlas.vercel.app/t/web-gaussian-splat-viewers.md) for playback in a browser once frames are exported; per-frame static splats are simplest but heavy for long clips. ## Cost heavy — Rendering stays in the real-time range on a desktop GPU per the papers' claims, but training takes tens of minutes per short clip and storage grows with duration. Measured GPU Weight: 103.29× baseline (extreme) — 3.3984 ms median / 3.6849 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 92.82× baseline (extreme) — 1.4758 ms median (2.3× faster on L4). Ampere A100 scaling: 72.07× baseline (extreme) — 2.0756 ms median (1.64× faster on A100). ## Failure modes - Fast, large motion or topology changes get smeared or leave floaters because the deformation is smooth in time - Monocular video is under-constrained, so motion and geometry are ambiguous without additional depth or flow cues - Memory and file size grow with sequence length, hurting streaming or web delivery - Time-slicing artifacts appear when sampled time falls between training frames with sparse temporal coverage ## Dataflow - Inputs: photos, camera-poses - Outputs: gaussians, animation - Platforms: cuda, desktop-gpu, python ## Presets ### 4D Gaussian Splatting — spacetime hexplane velocity trails (left) vs dynamic 4D splats (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TIME_RATE": 1, "P_DEFORM_AMP": 0.75, "P_SPLAT_RAD": 0.12, "P_SPLIT": 0.46 } ``` ```glsl const float P_TIME_RATE = 1.0; // P Temporal Speed [0.0, 2.5, 0.05] const float P_DEFORM_AMP = 0.75; // P 4D Motion Amp [0.1, 1.4, 0.04] const float P_SPLAT_RAD = 0.12; // P Splat Radius [0.05, 0.24, 0.01] const float P_SPLIT = 0.46; // P Trajectories / 4DGS [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Canonical 3D Gaussian i deformed by a smooth HexPlane spatiotemporal displacement field dX(x, t) vec3 eval4DPos(float fi, float t, float amp) { float u = fi / 32.0; float phi = fi * 2.3999632; // golden angle float y0 = (u - 0.5) * 1.15; float r0 = 0.42 * sqrt(max(1.0 - y0 * y0 * 0.9, 0.05)) + 0.14; vec3 base = vec3(cos(phi) * r0, y0, sin(phi) * r0); // HexPlane time-varying shear, wave ripple & flapping wing motion float wave = sin(t * 2.2 + base.y * 4.2 + phi * 0.5); float wing = cos(t * 1.8 - abs(base.x) * 3.5); vec3 dx = vec3( 0.22 * wave * sign(base.x + 1e-4), 0.16 * wing + 0.10 * sin(t * 2.6 + phi), 0.20 * cos(t * 2.0 + base.y * 3.8) ) * amp; vec3 pos = base + dx; pos.xz = rot2(t * 0.42) * pos.xz; return pos; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isTrail = screenX < split; float t = iTime * max(P_TIME_RATE, 0.0); float amp = clamp(P_DEFORM_AMP, 0.05, 1.6); float rad = clamp(P_SPLAT_RAD, 0.04, 0.26); vec3 ro = vec3(0.0, 0.14, 2.35); vec3 rd = normalize(vec3(uv, -1.52)); vec3 bg = mix(vec3(0.020, 0.026, 0.048), vec3(0.055, 0.072, 0.122), smoothstep(-0.55, 0.55, uv.y)); vec3 acc = vec3(0.0); float T = 1.0; for (int i = 0; i < 32; i++) { float fi = float(i); vec3 pNow = eval4DPos(fi, t, amp); vec3 pPrev = eval4DPos(fi, t - 0.14, amp); vec3 vel = pNow - pPrev; float speed = length(vel); vec3 vDir = vel / max(speed, 1e-4); // Current Gaussian response vec3 oc = pNow - ro; float tProj = dot(oc, rd); if (tProj > 0.2) { vec3 perp = oc - rd * tProj; // 4D covariance elongates along instantaneous velocity direction float dV = dot(perp, vDir); vec3 dN = perp - vDir * dV; float stretch = 1.0 + speed * 5.0; float m2 = (dot(dN, dN) + (dV * dV) / (stretch * stretch)) / max(rad * rad, 1e-4); float g = exp(-m2 * 2.1); if (g > 0.012) { float a = clamp(g * 0.78, 0.0, 0.92); vec3 baseCol = mix(vec3(0.14, 0.76, 0.96), vec3(0.98, 0.42, 0.24), fi / 32.0); vec3 velCol = mix(vec3(0.18, 0.42, 0.92), vec3(1.0, 0.86, 0.24), clamp(speed * 7.0, 0.0, 1.0)); vec3 gCol = isTrail ? velCol : baseCol; acc += T * a * gCol * (0.75 + 0.55 * g); T *= (1.0 - a); if (T < 0.02) break; } } // On left side, draw spacetime motion trails (3 past temporal slices) if (isTrail) { for (int s = 1; s <= 3; s++) { float fs = float(s); vec3 pOld = eval4DPos(fi, t - fs * 0.10, amp); vec3 oc2 = pOld - ro; float tp2 = dot(oc2, rd); if (tp2 > 0.2) { vec3 perp2 = oc2 - rd * tp2; float g2 = exp(-dot(perp2, perp2) / max(rad * rad * 0.18, 1e-5)); acc += T * g2 * 0.22 * (1.0 - fs * 0.25) * vec3(0.24, 0.92, 0.88); } } } } vec3 col = acc + T * bg; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): Per-frame or first-frame COLMAP poses initialise the cameras and the canonical Gaussian set. ## Sources 1. [primary] Guanjun Wu, Taoran Yi, Jiemin Fang, Lingxi Xie, Xiaopeng Zhang, Wei Wei, Wenyu Liu, Qi Tian, Xinggang Wang (2023) 4D Gaussian Splatting for Real-Time Dynamic Scene Rendering. arXiv preprint (cs.CV). https://arxiv.org/abs/2310.08528 (verified via arxiv on 2026-11-29) 2. [implementation] hustvl (2023) hustvl/4DGaussians. https://github.com/hustvl/4DGaussians License: Apache-2.0. (verified via github on 2026-11-29) 3. [implementation] LogosIntelligenceLab (2023) LogosIntelligenceLab/4d-gaussian-splatting. https://github.com/LogosIntelligenceLab/4d-gaussian-splatting License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "4D Gaussian Splatting." https://texelatlas.vercel.app/t/4d-gaussian-splatting/ (accessed 2026-12-01). --- id: "4d-stereographic-projection-turning" title: "Pole-Safe 4D Stereographic Projection & Discrete-Cell Rotations" aliases: [4D stereographic ray marching, tesseract stereographic projection, S3 polytope projection] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 1992 inputs: [sdf, material-params] outputs: [radiance, depth, normals] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Hanson & Heng, 1992" url: "https://texelatlas.vercel.app/t/4d-stereographic-projection-turning/" sources_verified_at: "2026-11-30" --- # Pole-Safe 4D Stereographic Projection & Discrete-Cell Rotations (Hanson & Heng, 1992) > Projects 4D polytopes living on the unit 3-sphere S3 into 3D space via conformal stereographic projection, using symmetry folding and pole-safe distance bounds so 4D rotations turn cells inside out without tessellation blowups. ## Reach for it when - visualize 4d polytopes tesseracts or hyperspheres rotating in 3d - avoid flat orthographic crushing when projecting 4d shapes to 3d - render smooth inside-out 4d torus turning and Clifford tori animations - preserve angles and spherical curvature when mapping 4d points to 3d space - build an interactive 4d geometry explorer with intuitive depth cues ## How it works A 4D polytope such as a tesseract (`8-cell`) or `24-cell` can be normalized onto the unit 3-sphere `S^3 ⊂ R^4`, turning straight 4D edges into great-circle arcs. Rotating it with an orthogonal `SO(4)` matrix across the six 4D coordinate planes (`XY, XZ, YZ, XW, YW, ZW`) turns inner and outer 3D cells smoothly inside out. **Stereographic projection** maps `(x, y, z, w) ∈ S^3` from the north pole `(0, 0, 0, 1)` to `R^3` via `p = (x, y, z) / (1 - w)`. Because the map is conformal, great-circle edges arrive in 3D as exact circular arcs or lines. Instead of tessellating arcs that stretch unboundedly near `w → 1`, a **ray-marched SDF** lifts each 3D sample `p` back to `S^3` via `q = (2p, |p|^2 - 1) / (|p|^2 + 1)`, applies the inverse `SO(4)` rotation, and folds coordinates by the polytope's discrete symmetry group, collapsing 32 edges and 16 vertices into a few primitive tests. A **pole-safe step bound** scales spherical distance by the local inverse Jacobian `(|p|^2 + 1) / 2` and computes chords via squared differences `|a - b|^2` to avoid float32 cancellation. ## When to use it Choose it when rendering smooth, curved 4D polytopes, Hopf fibrations, or inside-out hypercube animations where exact circular edges and real-time 4D rotations matter. Prefer [sphere-tracing](sphere-tracing) on standard 3D Euclidean SDFs when no non-Euclidean projection distortion is needed. Prefer explicit 4D-to-3D perspective wireframes or sliced cross-section meshes when you need rasterized triangle geometry or physical 3D-printable models. ## Cost medium — Full-screen per-pixel ray marching with symmetry-folded inverse stereographic SDF evaluation typically runs in 1–3 ms at 1080p on mid-range desktop GPUs, scaling with pixel count and march iterations. ## Failure modes - Geometry passing directly through the projection pole (w → 1) expands toward infinity, requiring pole-safe clamping or discrete-cell rotation framing to avoid screen-filling tubes - Evaluating chord distances via 2 - 2*cos(theta) suffers catastrophic float32 cancellation on distant thin arcs unless rewritten as sums of squared differences - Conformal scale inflation causes Euclidean step sizes to overshoot far from the origin if the inverse Jacobian factor is omitted - Inside-out turning can invert visual depth cues unless shading, ambient occlusion, or color gradients distinguish W-depth ## Dataflow - Inputs: sdf, material-params - Outputs: radiance, depth, normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Combines with - [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md): Advances camera rays through the inverse-stereographic Jacobian-bounded SDF to render exact curved 4D arcs without mesh subdivision. - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): Smoothly joins projected 4D vertices, metaballs, or fractal joints onto the circular edge arcs. ## Sources 1. [primary] Andrew J. Hanson, Pheng A. Heng (1992) Illuminating the fourth dimension. IEEE Computer Graphics and Applications. https://doi.org/10.1109/38.144827 (verified via crossref on 2026-11-30) 2. [secondary] A.J. Hanson, P.A. Heng Visualizing the fourth dimension using geometry and light. Proceeding Visualization '91. https://doi.org/10.1109/visual.1991.175821 (verified via doi.org on 2026-11-30) 3. [implementation] acher249 (2026) acher249/codevember-2026. https://github.com/acher249/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Pole-Safe 4D Stereographic Projection & Discrete-Cell Rotations." https://texelatlas.vercel.app/t/4d-stereographic-projection-turning/ (accessed 2026-12-01). --- id: "aces-tonemapping" title: "ACES filmic tonemapping" aliases: [ACES] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, unreal] year_introduced: 2016 inputs: [hdr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "cheap" authority: "aces-aswf, 2011" url: "https://texelatlas.vercel.app/t/aces-tonemapping/" sources_verified_at: "2026-11-29" --- # ACES filmic tonemapping (aces-aswf, 2011) > Tone curve and gamut handling derived from the Academy Color Encoding System reference rendering transform; real-time shaders use fitted approximations, giving high contrast and saturated highlights. ## Reach for it when - hdr render looks flat and washed out on screen - want a punchy contrasty cinematic film look - bright highlights clip to harsh white or oversaturate - need output matching a vfx color pipeline ## How it works The ACES output pipeline converts scene colour to the ACEScg working space, applies a Reference Rendering Transform (a filmic S-curve with a glow and red modifier) and then an Output Device Transform for the display. The full transform is expensive and uses 3x3 matrices and spline segments, so games use fits. Narkowicz's one-line rational curve is applied per channel on a scaled input, and Hill's fit adds the input and output matrices so hue behaviour is closer to the original. The per-channel curve is what gives ACES its look: bright saturated colours shift toward white and hues skew. ## When to use it Choose it when you want a punchy, contrasty cinematic look and compatibility with film or VFX pipelines that use ACES. Prefer [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md) or [Khronos PBR Neutral tone mapper](https://texelatlas.vercel.app/t/khronos-pbr-neutral.md) when hue stability and accurate product colours matter, or [Reinhard photographic tone reproduction](https://texelatlas.vercel.app/t/reinhard-tonemapping.md) for a simple, predictable curve. Choose [Hable filmic (Uncharted 2) tonemapping](https://texelatlas.vercel.app/t/hable-filmic-tonemapping.md) for a tuneable shoulder. ## Cost cheap — A few arithmetic operations per pixel, and optionally two 3x3 matrix multiplies. Measured GPU Weight: 1.21× baseline (feather) — 0.0397 ms median / 0.042 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.01× baseline (feather) — 0.016 ms median (2.48× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.38× faster on A100). ## Failure modes - Hue skews: saturated blues turn purple and bright oranges slide toward yellow - Highlights desaturate abruptly to white (path to white), which can crush emissive colours - Fitted curves drift from the true RRT and ODT, especially at extreme values - Product colours do not match their reference, so brand or albedo shifts ## Engine support - babylonjs: builtin — `scene.imageProcessingConfiguration.toneMappingType = BABYLON.ImageProcessingConfiguration.TONEMAPPING_ACES` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/imageProcessingConfiguration.pure.ts, checked 2026-12-01) - blender: builtin — `Properties > Render > Color Management > View Transform = ACES 1.3 (or ACES 2.0)` (evidence: https://docs.blender.org/manual/en/5.2/render/color_management/displays_views.html, checked 2026-12-01) — ACES view transforms via OpenColorIO, not the Narkowicz curve fit. - godot: builtin — `Environment.tonemap_mode = Environment.TONE_MAPPER_ACES` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - threejs: builtin — `renderer.toneMapping = THREE.ACESFilmicToneMapping` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Post-processing > Tonemapping > Mode = ACES (URP and HDRP)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/Tonemapping.cs, checked 2026-12-01) — URP and HDRP; ACES is a close approximation of the reference transform. - unreal: builtin — `Project Settings > Rendering > Default Settings > Use Filmic Tonemapper (ACES-based filmic tonemapper); Post Process Volume > Film` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/color-grading-and-the-filmic-tonemapper-in-unreal-engine, checked 2026-12-01) — Filmic tonemapper matches the ACES standard. ## Dataflow - Inputs: hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, unreal ## Presets ### three.js ACESFilmic tone mapping, exposure 1.0 (three-tonemap; rendered 2026-11-29) ```json { "toneMapping": "ACESFilmic", "exposure": 1 } ``` Attribution: written for this index ## Lineage - extends [Hable filmic (Uncharted 2) tonemapping](https://texelatlas.vercel.app/t/hable-filmic-tonemapping.md) - extended by [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md) - extended by [Khronos PBR Neutral tone mapper](https://texelatlas.vercel.app/t/khronos-pbr-neutral.md) ## Combines with - [Auto exposure from luminance histogram](https://texelatlas.vercel.app/t/auto-exposure-histogram.md): Exposure from the histogram feeds the curve. - [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md): Tonemapped output is often graded with a 3D LUT. ## Sources 1. [primary] aces-aswf (2011) aces-aswf/aces-core. https://github.com/aces-aswf/aces-core License: Apache-2.0. (verified via github on 2026-11-29) 2. [tutorial] Krzysztof Narkowicz ACES Filmic Tone Mapping Curve. knarkowicz.wordpress.com. https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve (verified via http on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "ACES filmic tonemapping." https://texelatlas.vercel.app/t/aces-tonemapping/ (accessed 2026-12-01). --- id: "acoustic-raytraced-echolocation-point-cloud" title: "Multi-Bounce Acoustic Ray-Traced Echolocation Point-Cloud Visualization" aliases: [acoustic echolocation rendering, sonar point-cloud visualization, geometrical acoustic ray mapping] domain: "npr" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 1968 inputs: [mesh, camera-poses] outputs: [point-cloud, hdr-image] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Krokstad et al., 1968" url: "https://texelatlas.vercel.app/t/acoustic-raytraced-echolocation-point-cloud/" sources_verified_at: "2026-11-30" --- # Multi-Bounce Acoustic Ray-Traced Echolocation Point-Cloud Visualization (Krokstad et al., 1968) > Visualizes otherwise invisible 3D architecture by casting multi-bounce acoustic rays from a sound pulse and depositing time-delayed, decaying luminous points where expanding sound waves strike surfaces. ## Reach for it when - visualize hidden dark environments using expanding sonar or echolocation pings - trace multi-bounce sound rays to stamp time-of-flight glowing surface dots - create stylized lidar or bat-sonar scanning effects that reveal rooms over time - decay and animate acoustic hit points according to physical travel distance - render minimalist atmospheric point-cloud navigation in pitch-black levels ## How it works Geometrical room acoustics models sound propagation as energetic rays traveling at the finite speed of sound `c` (~343 m/s), reflecting specularly or diffusely off room boundaries while losing energy to distance spreading and surface absorption. Turning this acoustic simulation into an NPR visualization reveals a pitch-black 3D scene exclusively through **delayed echo impressions**. Whenever a vocal call, clap, or synthetic sonar ping is emitted, thousands of rays are distributed over the sphere (or forward cone) and traced through the scene's BVH for multiple bounces. Each ray hit records its 3D world position, surface normal, accumulated **path travel distance** `d`, bounce order, and remaining acoustic energy—often feeding a matching spatialized audio impulse response at the same time. Instead of illuminating hits instantaneously, each recorded point stays dormant until simulation time reaches `t_emit + d / c`, so rings of glowing dots sweep physically outward along corridors, turn corners via secondary reflections, and silhouette moving entities as acoustic shadows. After activation, points decay exponentially over a few seconds, leaving a ghostly, transient point cloud that fades back into darkness until the next pulse. ## When to use it Choose it for horror, exploration, sensory-substitution, or architectural-acoustics visualizations where space should be revealed dynamically by finite-speed sound waves and multi-bounce reflections rather than direct light. Prefer [screen-space-edge-outline](screen-space-edge-outline) or [jump-flood-outline](jump-flood-outline) when you want a cheap, instantaneous wireframe/sonar pulse without real multi-bounce occlusion. Prefer [path-tracing](path-tracing) when simulating optical illumination rather than finite-speed acoustic wavefronts. ## Cost medium — Ray tracing occurs only in bursts on sound emission (a few thousand multi-bounce BVH rays per pulse); per-frame rendering draws a persistent ring buffer of instanced or point-sprite echo dots. Measured GPU Weight: 25.53× baseline (heavy) — 0.8399 ms median / 0.85 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.18× baseline (heavy) — 0.4321 ms median (1.94× faster on L4). Ampere A100 scaling: 17.25× baseline (moderate) — 0.4967 ms median (1.69× faster on A100). ## Failure modes - Sparse ray sampling leaves wide gaps on distant walls or large open rooms where angular ray density falls off quadratically - Moving objects cast stale point clouds after stepping away unless dynamic entities are stamped with shorter lifetimes or continuously re-tested - Geometrical ray tracing ignores low-frequency wave diffraction around sharp corners, making acoustic shadows sharper than real sound - Unbounded point buffers can saturate fill rate or memory if pulses fire rapidly without a ring-buffer cap and decay eviction ## Dataflow - Inputs: mesh, camera-poses - Outputs: point-cloud, hdr-image - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Acoustic Ray-Traced Echolocation Point Cloud — dark vaulted geometry (left) vs multi-bounce time-delayed echo point pulses (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PULSE_RATE": 0.75, "P_WAVE_WIDTH": 0.55, "P_POINT_DENS": 1, "P_SPLIT": 0.34 } ``` ```glsl const float P_PULSE_RATE = 0.75; // P Acoustic Pulse Rate [0.2, 1.8, 0.05] const float P_WAVE_WIDTH = 0.55; // P Echo Decay Tail [0.2, 1.2, 0.05] const float P_POINT_DENS = 1.00; // P Point Cloud Grid [0.5, 1.8, 0.05] const float P_SPLIT = 0.34; // P Solid / Echolocation [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); } 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); } // Vaulted architectural corridor with pillars & archway revealed by expanding acoustic pulses vec2 mapVault(vec3 p) { // Inverted corridor walls + arched ceiling float dFloor = p.y + 0.62; float dWalls = 1.25 - abs(p.x); float dCeil = 1.05 - length(vec2(p.x * 0.75, p.y - 0.15)); float dBack = p.z + 2.45; float dShell = min(min(dFloor, dWalls), min(dCeil, dBack)); vec2 res = vec2(dShell, 1.0); // Repeating ribbed colonnade piers along the corridor for (int i = 0; i < 3; i++) { float z = -0.35 - float(i) * 0.85; float dL = sdBox(p - vec3(-0.78, -0.05, z), vec3(0.14, 0.58, 0.14)); float dR = sdBox(p - vec3(0.78, -0.05, z), vec3(0.14, 0.58, 0.14)); float dP = min(dL, dR); if (dP < res.x) res = vec2(dP, 2.0); } // Central floating acoustic sculpture float dSculpt = length(p - vec3(0.0, -0.14, -0.75)) - 0.28; if (dSculpt < res.x) res = vec2(dSculpt, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapVault(p + e.xyy).x - mapVault(p - e.xyy).x, mapVault(p + e.yxy).x - mapVault(p - e.yxy).x, mapVault(p + e.yyx).x - mapVault(p - e.yyx).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float rate = clamp(P_PULSE_RATE, 0.15, 2.0); float tail = clamp(P_WAVE_WIDTH, 0.15, 1.4); float pDens = clamp(P_POINT_DENS, 0.4, 2.0); vec3 ro = vec3(0.18 * sin(iTime * 0.35), 0.02, 1.38); vec3 rd = normalize(vec3(uv.x, uv.y - 0.02, -1.35)); vec3 col = vec3(0.006, 0.009, 0.015); float dist = 0.04; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 68; i++) { vec2 h = mapVault(ro + rd * dist); if (h.x < 0.0025) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 6.5) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); // Sound pulse originates slightly ahead of listener vec3 pulseOrig = vec3(0.0, -0.05, 0.85); float d1 = length(p - pulseOrig); // Second-bounce acoustic path via central sphere / opposite wall reflection! vec3 mirrorOrig = vec3(0.0, -0.14, -0.75); float d2 = length(mirrorOrig - pulseOrig) + length(p - mirrorOrig); // Repeating expanding acoustic wave fronts (finite speed of sound c) float wavePhase = fract(iTime * rate * 0.38); float waveDist = wavePhase * 5.2; // 1st-bounce direct echo envelope (cyan-white leading edge, rapid decay behind wavefront) float lag1 = waveDist - d1; float env1 = step(0.0, lag1) * exp(-lag1 / max(0.55 * tail, 0.08)) / (0.35 + d1 * 0.55); // 2nd-bounce delayed reflection envelope (warm amber secondary echo!) float lag2 = waveDist - d2; float env2 = step(0.0, lag2) * exp(-lag2 / max(0.75 * tail, 0.10)) / (0.55 + d2 * 0.45); if (screenX < split) { // Left: Dim ambient solid architecture for spatial reference vec3 lDir = normalize(vec3(0.3, 0.6, 0.8)); float ndl = max(dot(n, lDir), 0.0); vec3 baseCol = (hit.y > 2.5) ? vec3(0.34, 0.42, 0.52) : vec3(0.20, 0.24, 0.30); col = baseCol * (0.20 + 0.55 * ndl) * exp(-hit.x * 0.22); // Faint acoustic wave ring sweeping across reference geometry float ring1 = exp(-abs(lag1) * 18.0); col += vec3(0.18, 0.88, 1.0) * ring1 * 0.45; } else { // Right: Pure pitch-black NPR echolocation point-cloud deposited strictly where acoustic rays strike! float gridScale = 14.0 * pDens; vec3 cell = floor(p * gridScale); vec3 local = fract(p * gridScale) - 0.5; // Jittered luminous point inside each 3D surface cell vec3 jit = (vec3(hash31(cell), hash31(cell + 17.3), hash31(cell + 41.9)) - 0.5) * 0.68; float ptDist = length(local - jit); float dotMask = smoothstep(0.24, 0.06, ptDist); // Edge-curvature boost deposits denser silhouette highlight points on corners/pillars float edgeBoost = (hit.y > 1.5) ? 1.45 : 1.0; float waveCrest1 = exp(-abs(lag1) * 14.0) * 1.4; float waveCrest2 = exp(-abs(lag2) * 12.0) * 1.1; vec3 echo1Col = vec3(0.18, 0.92, 1.0) * (env1 * 1.45 + waveCrest1) * dotMask * edgeBoost; vec3 echo2Col = vec3(1.0, 0.56, 0.18) * (env2 * 1.35 + waveCrest2) * dotMask * edgeBoost; // Subtle floor ripple lines along advancing wavefront float crestRing = exp(-abs(lag1) * 28.0) * 0.22; col += echo1Col + echo2Col + vec3(0.25, 0.82, 0.96) * crestRing; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): Accelerates multi-bounce acoustic ray-triangle queries per sound pulse at interactive frame rates. - [Physically Modeled NTSC Composite / VHS Tape & CRT Electron-Beam Emulation](https://texelatlas.vercel.app/t/ntsc-composite-vhs-crt-signal-emulation.md): Passes the decaying echolocation point-cloud output through analog tape noise and CRT phosphor glow. ## Combination ideas - [Sonar echolocation point clouds on analog VHS-CRT](https://texelatlas.vercel.app/ideas/echolocation-pointcloud-ntsc-vhs-crt/) ## Sources 1. [primary] A. Krokstad, S. Strom, S. Sørsdal (1968) Calculating the acoustical room response by the use of a ray tracing technique. Journal of Sound and Vibration. https://doi.org/10.1016/0022-460x(68)90198-3 (verified via crossref on 2026-11-30) 2. [survey] Lauri Savioja, U. Peter Svensson (2015) Overview of geometrical room acoustic modeling techniques. The Journal of the Acoustical Society of America. https://doi.org/10.1121/1.4926438 (verified via crossref on 2026-11-30) 3. [implementation] spite (2026) spite/codevember-2026. https://github.com/spite/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Multi-Bounce Acoustic Ray-Traced Echolocation Point-Cloud Visualization." https://texelatlas.vercel.app/t/acoustic-raytraced-echolocation-point-cloud/ (accessed 2026-12-01). --- id: "agx-tonemapping" title: "AgX" domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender] year_introduced: 2022 inputs: [hdr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "cheap" authority: "sobotka, 2022" url: "https://texelatlas.vercel.app/t/agx-tonemapping/" sources_verified_at: "2026-11-29" --- # AgX (sobotka, 2022) > A display transform by Troy Sobotka that maps scene-referred values through a log encoding and sigmoid in a rotated primaries space. Highlights roll off to white without hue skews or ACES-style saturation. ## Reach for it when - bright saturated lights turn orange or cyan at highlights - highlights shift hue instead of rolling off to white - want a neutral camera-like look for hdr renders - emissive colours look garish after tone mapping ## How it works AgX first applies an inset matrix that moves colours slightly toward the neutral axis so extreme values can desaturate gracefully. The result is encoded as log2 between a fixed black and white relative exposure (about minus 12 to plus 4 stops) and normalised, then a sigmoid, fitted as a polynomial, applies the contrast curve. An outset matrix restores most chroma, and an optional look adds slope, power and saturation tweaks for punchier or flatter results. The shaders in Blender and three.js are small enough to run per fragment. The result reaches white with an even desaturation, so a bright blue light does not flip to purple. ## When to use it Choose it when you want predictable, neutral highlights and a camera-like rendering, especially for saturated emissive content. Prefer [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) when you need ACES compatibility and the punchy look. Prefer [Khronos PBR Neutral tone mapper](https://texelatlas.vercel.app/t/khronos-pbr-neutral.md) for product viewers where albedo colours must not shift. ## Cost cheap — Two matrix multiplies and a polynomial per pixel. Measured GPU Weight: 1.18× baseline (feather) — 0.0387 ms median / 0.0411 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1× baseline (feather) — 0.0159 ms median (2.43× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.34× faster on A100). ## Failure modes - Flat, low-contrast default look unless a contrast look is chosen - Slightly desaturated mid-tones compared with ACES or Neutral - Several incompatible implementations (Blender, three.js, Filament) differ in constants - Fully saturated primaries cannot reach display boundaries because of the inset ## Engine support - blender: builtin — `Properties > Render > Color Management > View Transform = AgX` (evidence: https://docs.blender.org/manual/en/5.2/render/color_management/displays_views.html, checked 2026-12-01) - godot: builtin — `Environment.tonemap_mode = Environment.TONE_MAPPER_AGX` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - threejs: builtin — `renderer.toneMapping = THREE.AgXToneMapping` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender ## Presets ### three.js AgX tone mapping, exposure 1.0 (three-tonemap; rendered 2026-11-29) ```json { "toneMapping": "AgX", "exposure": 1 } ``` Attribution: written for this index ### AgX inset-matrix HDR tonemapper (WGSL) (webgpu-wgsl; WebGPU WGSL runtime) ```json { "EXPOSURE": 1, "PUNCH": 1.15 } ``` ```wgsl // WebGPU WGSL fragment specimen: AgX log-encoding + sigmoid look curve const EXPOSURE: f32 = 1.0000; // P const PUNCH: f32 = 1.1500; // P fn agx_map(x_in: vec3f) -> vec3f { let m = mat3x3f( vec3f(0.842479, 0.042328, 0.042376), vec3f(0.078434, 0.878469, 0.078434), vec3f(0.079224, 0.079166, 0.879143) ); let x = max(m * max(x_in * EXPOSURE, vec3f(1e-5)), vec3f(1e-5)); let lv = clamp((log2(x) + 12.47393) / 16.5, vec3f(0.0), vec3f(1.0)); let s = lv * lv * (3.0 - 2.0 * lv); return pow(clamp(s, vec3f(0.0), vec3f(1.0)), vec3f(PUNCH)); } @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f { let uv = (pos.xy - 0.5 * u.resolution) / u.resolution.y; var col = vec3f(0.05, 0.055, 0.065); var hues = array( vec3f(1.0, 0.22, 0.12), vec3f(1.0, 0.76, 0.12), vec3f(0.18, 0.82, 0.42), vec3f(0.12, 0.54, 1.0), vec3f(0.70, 0.30, 1.0) ); for (var i: i32 = 0; i < 5; i = i + 1) { let c = vec2f((f32(i) - 2.0) * 0.30, -0.06); let d = uv - c; let r2 = dot(d, d); if (r2 < 0.018) { let n = normalize(vec3f(d.x, -d.y, sqrt(0.018 - r2))); let l = max(dot(n, normalize(vec3f(0.4, 0.6, 0.7))), 0.12); col = hues[i] * (l * 0.75 + pow(2.0, f32(i) - 0.4)); } } if (uv.y > 0.20 && uv.y < 0.34 && abs(uv.x) < 0.72) { let ev = mix(-3.0, 5.0, (uv.x + 0.72) / 1.44); col = vec3f(pow(2.0, ev)); } return vec4f(agx_map(col), 1.0); } ``` Attribution: written for this index ## Lineage - extends [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) ## Combines with - [Auto exposure from luminance histogram](https://texelatlas.vercel.app/t/auto-exposure-histogram.md): Exposure feeds the log encoding range. - [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md): AgX is commonly followed by a LUT-based look. ## Sources 1. [primary] sobotka (2022) sobotka/AgX. https://github.com/sobotka/AgX (verified via github on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "AgX." https://texelatlas.vercel.app/t/agx-tonemapping/ (accessed 2026-12-01). --- id: "alchemy-ambient-obscurance" title: "Alchemy screen-space ambient obscurance" aliases: [Alchemy AO, AlchemyAO, SAO precursor] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2011 inputs: [depth, normals] outputs: [visibility-mask] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "McGuire et al., 2011" url: "https://texelatlas.vercel.app/t/alchemy-ambient-obscurance/" sources_verified_at: "2026-11-29" --- # Alchemy screen-space ambient obscurance (McGuire et al., 2011) > A cheap one-pass screen-space AO estimator that sums, over a few random samples, how much each nearby point rises above the tangent plane, giving a closed-form obscurance with controlled falloff. ## Reach for it when - want cheap contact darkening in creases on mobile - screen space ambient occlusion too slow for my target - ambient occlusion shows dark halos around foreground objects - need simple one pass ao that works in webgl - corners and crevices look too bright and flat ## How it works For a shaded point with position P and normal n, the pass picks about a dozen sample points in a screen-space disk, reconstructs their view-space positions from depth, and forms vectors v from P to each. Each sample contributes the term max(0, v·n - bias·depth) divided by (v·v + epsilon), which is large when the occluder lies above the surface and close, and decays with squared distance to avoid halos from far geometry. The sum is normalised by the sample count and mapped to visibility with a power and an intensity scale, e.g. (1 - 2σ/s·sum)^k. Samples are placed on a spiral with per-pixel rotation, followed by an edge-aware bilateral blur. The squared-distance denominator and the simple per-sample formula avoid the explicit horizon search of later methods. A derivative, scalable ambient obscurance, adds a depth MIP chain for large radii. ## When to use it Choose it for a low-cost, easy-to-port AO on mobile and WebGL where compute-style horizon methods are too heavy. Prefer [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) or [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) for more accurate horizon-based occlusion at slightly higher cost, [N8AO](https://texelatlas.vercel.app/t/n8ao.md) for a ready three.js implementation, [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) or [SDF Ambient Occlusion](https://texelatlas.vercel.app/t/sdf-ambient-occlusion.md) when you can afford exactness, and [Multi-Bounce Ambient Occlusion Approximation](https://texelatlas.vercel.app/t/multi-bounce-ambient-occlusion.md) as a cheap albedo-dependent brightening on top. ## Cost cheap — One full-resolution pass with about a dozen depth taps plus a separable blur; cost grows with radius because of cache misses unless a depth MIP chain is used. Measured GPU Weight: 43.63× baseline (heavy) — 1.4353 ms median / 1.4535 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 43.1× baseline (heavy) — 0.6853 ms median (2.09× faster on L4). Ampere A100 scaling: 28.1× baseline (heavy) — 0.8092 ms median (1.77× faster on A100). ## Failure modes - Halos and dark rings around foreground silhouettes when the radius exceeds object thickness - Noise and banding patterns when samples per pixel are few and the blur is too small or too large - View-dependent darkening at screen borders and missing occluders that are off-screen or behind surfaces - Over-darkened concave corners compared with a ground-truth reference, requiring intensity tuning - Flat or tiny-scale geometry shimmer under camera motion unless the noise is temporally resolved ## Engine support - unity: builtin — `URP Renderer > Add Renderer Feature > Screen Space Ambient Occlusion (implements McGuire 2011 Alchemy AO in SSAO.hlsl)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/ShaderLibrary/SSAO.hlsl, checked 2026-12-01) — URP SSAO uses Alchemy ambient obscurance; HDRP uses GTAO. ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: direct lighting only. Right: Alchemy Ambient Obscurance (McGuire 2011) crevice darkening (glsl-fragment; rendered 2026-11-30) ```json { "AO_RADIUS": 0.48, "AO_INTENSITY": 2.4, "AO_BIAS": 0.025, "SAMPLES": 16 } ``` ```glsl const float AO_RADIUS = 0.48; // P const float AO_INTENSITY = 2.4; // P const float AO_BIAS = 0.025; // P const int SAMPLES = 16; // P 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); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } // Sculpted geometric niche with deep concave corners, flutes and nested forms float mapScene(vec3 p) { float floorD = p.y + 0.9; float backWall = p.z + 1.45; // Recessed stepped frame float frame = max(sdBox(p - vec3(0.0, 0.15, -1.1), vec3(1.65, 1.25, 0.35)), -sdBox(p - vec3(0.0, 0.15, -0.95), vec3(1.22, 0.88, 0.42))); // Rotated central sculpture (interlocking torus + sphere + ribbed pedestal) vec3 q = p - vec3(0.0, -0.1, -0.15); float a = iTime * 0.35; mat2 r = mat2(cos(a), -sin(a), sin(a), cos(a)); q.xz = r * q.xz; float ped = sdBox(p - vec3(0.0, -0.72, -0.15), vec3(0.58, 0.18, 0.58)); float sp = length(q - vec3(0.0, 0.12, 0.0)) - 0.38; float tor = sdTorus(q.xzy - vec3(0.0, 0.0, 0.12), vec2(0.52, 0.14)); float cols = sdBox(vec3(abs(p.x) - 0.92, p.y + 0.05, p.z + 0.72), vec3(0.18, 0.95, 0.18)); float flute = sin(p.y * 28.0) * 0.012; float d = min(floorD, min(backWall, frame)); d = min(d, min(ped, min(sp, min(tor, cols + flute)))); return d; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy) - mapScene(p - e.xyy), mapScene(p + e.yxy) - mapScene(p - e.yxy), mapScene(p + e.yyx) - mapScene(p - e.yyx) )); } float raymarch(vec3 ro, vec3 rd, float tMax) { float t = 0.05; for (int i = 0; i < 60; i++) { float d = mapScene(ro + rd * t); if (d < 0.0025) return t; t += d; if (t > tMax) break; } return -1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float splitX = 0.0; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { splitX = (iMouse.x - 0.5 * iResolution.xy.x) / iResolution.y; } vec3 ro = vec3(0.0, 0.25, 2.35); vec3 rd = normalize(vec3(uv.x, uv.y - 0.06, -1.45)); float t = raymarch(ro, rd, 10.0); vec3 col = vec3(0.12, 0.14, 0.18); if (t > 0.0) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 lDir = normalize(vec3(0.55, 0.78, 0.45)); float nl = max(dot(n, lDir), 0.0); vec3 alb = vec3(0.84, 0.82, 0.79); vec3 direct = alb * (0.28 + 0.85 * nl); // McGuire 2011 Alchemy Ambient Obscurance estimator on spiral tangent-disk samples float ao = 1.0; if (uv.x > splitX) { int nSamp = clamp(SAMPLES, 4, 32); float rad = max(AO_RADIUS, 0.02); float bias = max(AO_BIAS, 0.0); float eps = 0.015; float spin = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453) * 6.2831853; vec3 up = abs(n.y) < 0.9 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); vec3 tx = normalize(cross(up, n)); vec3 ty = cross(n, tx); float sumObs = 0.0; for (int i = 0; i < 32; i++) { if (i >= nSamp) break; float alpha = (float(i) + 0.5) / float(nSamp); float ang = alpha * 7.0 * 6.2831853 + spin; vec2 disk = vec2(cos(ang), sin(ang)) * (alpha * rad); // Reconstruct nearby surface sample point via short projection onto SDF vec3 probe = p + tx * disk.x + ty * disk.y + n * (0.35 * rad * alpha); float dist = mapScene(probe); vec3 q = probe - n * dist; vec3 v = q - p; float vv = dot(v, v); float vn = dot(v, n); float f = max(rad * rad - vv, 0.0) / (rad * rad); sumObs += f * f * max(0.0, vn - bias * t) / (vv + eps); } float rawA = max(0.0, 1.0 - (2.0 * max(AO_INTENSITY, 0.0) / float(nSamp)) * sumObs * 0.24); ao = pow(clamp(rawA, 0.0, 1.0), 1.35); } col = direct * mix(0.18, 1.0, ao) * (uv.x > splitX ? mix(vec3(0.86, 0.90, 0.98), vec3(1.0), ao) : vec3(1.0)); } if (abs(uv.x - splitX) < 0.0025) col = vec3(1.0, 0.85, 0.35); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) ## Combines with - [Multi-Bounce Ambient Occlusion Approximation](https://texelatlas.vercel.app/t/multi-bounce-ambient-occlusion.md): The obscurance value is brightened per albedo by the multi-bounce fit to avoid overly dark light-coloured surfaces. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Per-pixel rotated samples are noisy; TAA integrates them over frames in place of a wide blur. ## Sources 1. [primary] Morgan McGuire, Brian Osman, Michael Bukowski, Padraic Hennessy (2011) The alchemy screen-space ambient obscurance algorithm. Proceedings of the ACM SIGGRAPH Symposium on High Performance Graphics. https://doi.org/10.1145/2018323.2018327 (verified via crossref on 2026-11-29) 2. [implementation] N8python (2023) N8python/n8ao. https://github.com/N8python/n8ao License: CC0-1.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Alchemy screen-space ambient obscurance." https://texelatlas.vercel.app/t/alchemy-ambient-obscurance/ (accessed 2026-12-01). --- id: "anamorphic-sightline-halfspace-slicing" title: "Sweet-Spot Anamorphic Geometry & Sutherland-Hodgman Sightline Clipping" aliases: [anamorphic perspective slicing, sweet-spot impossible sculpture, sightline half-space splitting] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, cpu, desktop-gpu, blender, houdini] year_introduced: 1974 inputs: [mesh, camera-poses] outputs: [mesh] style: "stylized" dynamic: "both" cost: "cheap" authority: "Sutherland & Hodgman, 1974" url: "https://texelatlas.vercel.app/t/anamorphic-sightline-halfspace-slicing/" sources_verified_at: "2026-11-30" --- # Sweet-Spot Anamorphic Geometry & Sutherland-Hodgman Sightline Clipping (Sutherland & Hodgman, 1974) > Splits a 3D figure along planes containing the viewing rays of a chosen sweet-spot camera using Sutherland-Hodgman clipping, then scales fragments along those rays so separated depths weld into an impossible figure from one viewpoint. ## Reach for it when - build a 3d optical illusion that snaps into an image from one camera angle - slice layered 3d sculpture geometry along perspective sightlines - create fragmented spatial typography legible only at a sweet spot - clip arbitrary meshes against a 2d silhouette frustum from a target vantage - design anamorphic installations and kirigami reveals in 3d ## How it works Optical illusions such as Penrose triangles, Escher cubes, and split architectural sculptures rely on **projective invariance**: any vertex scaled along its sightline from a fixed camera origin `C` by a depth factor `s > 0` (`p' = C + s * (p - C)`) projects to the exact same screen pixel. Under orthographic projection, shifting along the view axis achieves the same invariance without scaling. To turn an impossible junction into physically realizable, non-intersecting solid pieces, the algorithm defines one or more **sightline cutting planes** passing through the camera origin `C` and the apparent seam line on screen. Each polygon of the sculpture is clipped against both half-spaces of the plane using the **Sutherland-Hodgman reentrant polygon clipping** algorithm, and new coplanar cap faces are closed across the cut cross-section so each half remains a watertight solid. The separated pieces are then pushed apart in depth along their sweet-spot rays (with perspective radial scaling `s` preserving identical screen silhouettes). From the sweet spot, the fragments fuse seamlessly into the impossible geometry; orbiting away immediately reveals the staggered 3D blocks and gaps. ## When to use it Choose it when constructing interactive impossible-object sculptures, forced-perspective environmental puzzles, or multi-view anamorphic installations designed around one or a few canonical viewpoints. Prefer [planar-reflections-oblique-clipping](planar-reflections-oblique-clipping) when you only need GPU frustum clipping during rendering rather than generating permanent physical split meshes. Prefer [visual-hull](visual-hull) when reconstructing a single carved volume that matches arbitrary silhouettes from many viewpoints simultaneously. ## Cost cheap — Sutherland-Hodgman half-space clipping and ray scaling execute once on the CPU in under a millisecond for typical sculptural meshes, adding zero per-frame rendering overhead. ## Failure modes - Cast shadows and ambient occlusion immediately betray depth splits at the sweet spot unless lighting is aligned or softened across the seam - Sutherland-Hodgman clipping assumes convex clipping regions and requires clean cap triangulation when slicing non-convex polyhedra - Extreme depth separation under perspective projection scales distant fragments dramatically, risking near/far clip-plane or shadow-map precision loss - Moving even slightly off the sweet spot breaks alignment rapidly when pieces are separated by large depth ratios ## Dataflow - Inputs: mesh, camera-poses - Outputs: mesh - Platforms: webgl2, webgpu, cpu, desktop-gpu, blender, houdini ## Combines with - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Crisp silhouette ink outlines help depth-separated fragments visually fuse across sightline seams at the sweet spot. - [Manifold Mesh Booleans](https://texelatlas.vercel.app/t/mesh-boolean-manifold.md): Ensures watertight solid capping when slicing complex non-convex figures along multiple intersecting sightline planes. ## Combination ideas - [Anamorphic kirigami nets that lock into one sightline](https://texelatlas.vercel.app/ideas/anamorphic-projected-kirigami-nets/) ## Sources 1. [primary] Ivan E. Sutherland, Gary W. Hodgman (1974) Reentrant polygon clipping. Communications of the ACM. https://doi.org/10.1145/360767.360802 (verified via crossref on 2026-11-30) 2. [primary] Niloy J. Mitra, Mark Pauly (2009) Shadow art. ACM Transactions on Graphics. https://doi.org/10.1145/1618452.1618502 (verified via crossref on 2026-11-30) 3. [secondary] Kai-Wen Hsiao, Jia-Bin Huang, Hung-Kuo Chu (2018) Multi-view wire art. ACM Transactions on Graphics. https://doi.org/10.1145/3272127.3275070 (verified via crossref on 2026-11-30) 4. [implementation] spite (2026) spite/codevember-2026. https://github.com/spite/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Sweet-Spot Anamorphic Geometry & Sutherland-Hodgman Sightline Clipping." https://texelatlas.vercel.app/t/anamorphic-sightline-halfspace-slicing/ (accessed 2026-12-01). --- id: "anisotropic-ggx" title: "Anisotropic GGX" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2012 inputs: [material-params, normals, uv-atlas] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Burley" url: "https://texelatlas.vercel.app/t/anisotropic-ggx/" sources_verified_at: "2026-11-29" --- # Anisotropic GGX (Burley) > GGX with separate roughness along tangent and bitangent, producing stretched highlights on brushed metal, hair, vinyl records and satin. Requires a tangent frame and orientation map. ## Reach for it when - highlights on brushed metal should stretch along one direction - records, cds and satin need streaky specular - hair cards look flat with round highlights - need direction-dependent roughness on micro-grooved surfaces ## How it works Replace the isotropic roughness a by two values ax and ay, one along the tangent t and one along the bitangent b. The normal distribution becomes D(h) = 1 / (pi ax ay ((h.t/ax)^2 + (h.b/ay)^2 + (h.n)^2)^2), and the Smith Lambda gains an anisotropic form based on the projected roughness along each direction. Burley's principled model exposes this with an anisotropic parameter in [0,1] that skews roughness by aspect = sqrt(1 - 0.9 anisotropic); ax = roughness^2 / aspect and ay = roughness^2 * aspect. A tangent map or per-vertex tangents rotate the frame so the stretch follows the brushing direction. Heitz 2014 gives the matching anisotropic Smith masking function. ## When to use it Choose it for brushed metal, CDs, hair cards, satin and anything with directional micro-grooves. Prefer a baked normal map when the groove pattern is coarse enough to resolve. For fine stretched glints in scratched surfaces see [Real-time glints (distributed binomial laws)](https://texelatlas.vercel.app/t/real-time-glints.md). For simple fabrics prefer [Charlie sheen (Estevez-Kulla)](https://texelatlas.vercel.app/t/charlie-sheen.md). ## Cost cheap — Slightly more math than isotropic GGX plus a tangent-frame fetch. Measured GPU Weight: 1.87× baseline (feather) — 0.0614 ms median / 0.0627 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.63× baseline (feather) — 0.0259 ms median (2.37× faster on L4). Ampere A100 scaling: 1.26× baseline (feather) — 0.0362 ms median (1.7× faster on A100). ## Failure modes - Tangent discontinuities at UV seams show up as visible breaks in the highlight direction - Interpolated tangents on low-poly meshes twist the highlight - Specular antialiasing for anisotropic lobes is rarely handled, so minified brushed textures sparkle - Environment-map IBL ignores anisotropy unless bent-normal tricks are used, so reflections look isotropic ## Engine support - babylonjs: builtin — `pbrMaterial.anisotropy.isEnabled = true (PBRAnisotropicConfiguration)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrAnisotropicConfiguration.ts, checked 2026-12-01) - blender: builtin — `Principled BSDF > Specular > Anisotropic (and Anisotropic Rotation)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/glossy.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.anisotropy_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: builtin — `material.anisotropy = 1 (MeshPhysicalMaterial)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshPhysicalMaterial.js, checked 2026-12-01) - unity: builtin — `HDRP Lit > Surface Options > Material Type = Anisotropic` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/snippets/shader-properties/surface-options/anisotropy-stacklit.md, checked 2026-12-01) — HDRP Lit/StackLit; URP Complex Lit has none. - unreal: builtin — `Substrate material: Slab > Anisotropy input (Project Settings > Rendering > Substrate)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-substrate-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals, uv-atlas - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Brushed aluminium (three-material; rendered 2026-11-29) ```json { "color": "#f5f6f6", "roughness": 0.35, "metalness": 1, "anisotropy": 0.8 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 2 ## Lineage - extends [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) ## Combination ideas - [Neural materials that filter like EWA](https://texelatlas.vercel.app/ideas/footprint-filtered-neural-materials/) ## Sources 1. [primary] Brent Burley Physically Based Shading at Disney. SIGGRAPH 2012 Course. https://disneyanimation.com/publications/physically-based-shading-at-disney (verified via http on 2026-11-29) 2. [primary] Eric Heitz Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs. JCGT 2014. https://jcgt.org/published/0003/02/03 (verified via http on 2026-11-29) 3. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Anisotropic GGX." https://texelatlas.vercel.app/t/anisotropic-ggx/ (accessed 2026-12-01). --- id: "anisotropic-kuwahara" title: "Anisotropic Kuwahara filter" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2009 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "heavy" authority: "Kyprianidis et al., 2009" url: "https://texelatlas.vercel.app/t/anisotropic-kuwahara/" sources_verified_at: "2026-11-29" --- # Anisotropic Kuwahara filter (Kyprianidis et al., 2009) > Kuwahara filtering with elliptical, direction-aligned sectors driven by a structure tensor, producing smooth painterly strokes that follow image features instead of axis-aligned blocks. ## Reach for it when - want an oil painting look from a rendered frame - blocky artifacts in painterly image filter - stylize a scene so strokes follow edges and shapes - photo abstraction that keeps edges crisp but smooths regions ## How it works First, a structure tensor is estimated per pixel from Sobel gradients and smoothed with a Gaussian. Its eigenvectors give the local feature orientation and its eigenvalues give anisotropy. Each pixel then samples an ellipse oriented along that direction, divided into eight sectors weighted by a smooth polynomial or Gaussian rather than a hard window. For each sector it computes a weighted mean and variance, and blends the sector means with weights that favour low-variance sectors, instead of a hard winner-take-all choice. The soft weighting removes the discontinuities of the classic filter, and the oriented ellipses make edges follow brush-like curves. A multi-scale extension further preserves large-scale structure. ## When to use it Choose it when you want convincing oil-paint or watercolour-like abstraction from a rendered frame and can budget two or three passes. Prefer [Kuwahara filter](https://texelatlas.vercel.app/t/kuwahara-filter.md) for the cheapest option. Prefer [Painterly rendering with curved brush strokes](https://texelatlas.vercel.app/t/painterly-curved-brush-strokes.md) when you need visible individual brush strokes with direction and texture rather than a smooth filter. ## Cost heavy — Structure tensor passes plus a heavy sector-sampling pass; medium to heavy depending on radius. Measured GPU Weight: 171.01× baseline (extreme) — 5.6263 ms median / 5.7956 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 113.45× baseline (extreme) — 1.8038 ms median (3.12× faster on L4). Ampere A100 scaling: 56.08× baseline (heavy) — 1.6151 ms median (3.48× faster on A100). ## Failure modes - Flickers on animated scenes because the structure tensor changes frame to frame - Over-smoothing removes small details and faces unless strength is limited - Orientation is unstable in flat regions, causing swirls - Expensive at large radius without separable approximation or mip-based tricks ## Engine support - blender: builtin — `Compositor > Add > Creative > Kuwahara > Variation = Anisotropic` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/creative/kuwahara.html, checked 2026-12-01) ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: noisy source. Right: anisotropic Kuwahara, 8 elliptical sectors oriented by the structure tensor (glsl-fragment; rendered 2026-11-29) ```json { "RAD": 10, "QEXP": 4, "ALPHA": 1 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } const float RAD=10.0; // P const float QEXP=4.0; // P const float ALPHA=1.0; // P vec3 src(vec2 p){return img(p)+(hash(floor(p*512.))-.5)*.16;} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col; if(!R) col=src(q); else{ float px=1./512.,E=0.,F=0.,G=0.; for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++){vec2 o=q+vec2(float(i),float(j))*4.*px; float gx=lum(img(o+vec2(2.*px,0.)))-lum(img(o-vec2(2.*px,0.))),gy=lum(img(o+vec2(0.,2.*px)))-lum(img(o-vec2(0.,2.*px))); E+=gx*gx;F+=gx*gy;G+=gy*gy;} float th=.5*atan(2.*F,E-G),r=sqrt((E-G)*(E-G)+4.*F*F),A=r/(E+G+1e-6); vec2 g=vec2(cos(th),sin(th)),f=vec2(-g.y,g.x); float a=RAD*(ALPHA+A)/ALPHA,b=RAD*ALPHA/(ALPHA+A); vec3 m[8],s[8];float w[8]; for(int k=0;k<8;k++){m[k]=vec3(0.);s[k]=vec3(0.);w[k]=0.;} for(int j=-4;j<=4;j++)for(int i=-4;i<=4;i++){ vec2 u=vec2(float(i),float(j))/4.;float l2=dot(u,u);if(l2>1.)continue; vec3 c=src(q+(u.x*a*f+u.y*b*g)*px);float wt=exp(-2.5*l2); int k=int(clamp(floor((atan(u.y,u.x)/6.2831853+.5)*8.),0.,7.)); m[k]+=c*wt;s[k]+=c*c*wt;w[k]+=wt;} vec3 acc=vec3(0.);float ws=0.; for(int k=0;k<8;k++){if(w[k]<1e-4)continue;vec3 mu=m[k]/w[k];vec3 v=max(s[k]/w[k]-mu*mu,0.); float wk=1./(1.+pow(20.*sqrt(v.x+v.y+v.z),QEXP));acc+=mu*wk;ws+=wk;} col=acc/ws; } if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Lineage - extends [Kuwahara filter](https://texelatlas.vercel.app/t/kuwahara-filter.md) ## Combines with - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Painterly colour regions from the filter, lines from depth/normal edges. ## Sources 1. [primary] Jan Eric Kyprianidis, Henry Kang, Jürgen Döllner (2009) Image and Video Abstraction by Anisotropic Kuwahara Filtering. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2009.01574.x (verified via crossref on 2026-11-29) 2. [primary] Jan Eric Kyprianidis (2011) Image and video abstraction by multi-scale anisotropic Kuwahara filtering. Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Non-Photorealistic Animation and Rendering. https://doi.org/10.1145/2024676.2024686 (verified via crossref on 2026-11-29) 3. [implementation] GarrettGunnell (2022) GarrettGunnell/Post-Processing. https://github.com/GarrettGunnell/Post-Processing License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Anisotropic Kuwahara filter." https://texelatlas.vercel.app/t/anisotropic-kuwahara/ (accessed 2026-12-01). --- id: "ascii-rendering" title: "ASCII / character-cell rendering" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu] inputs: [ldr-image, depth] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Harri" url: "https://texelatlas.vercel.app/t/ascii-rendering/" sources_verified_at: "2026-11-29" --- # ASCII / character-cell rendering (Harri) > Divides the frame into character cells and replaces each with the glyph whose shape best matches the average brightness (and optionally edge direction) of that cell. ## Reach for it when - want my 3d scene drawn with text characters - need a terminal or hacker style look - turn frame brightness into letters and symbols - retro console aesthetic made of glyph cells ## How it works The scene is rendered, then downsampled so each pixel represents one character cell. For each cell, a luminance value picks a glyph from a ramp ordered by ink coverage, for instance a space, a dot, a colon, and a hash. A font atlas texture stores the glyph images, and the final shader samples the atlas using the glyph index and the within-cell coordinates. Better variants compare the cell's shape with each glyph's shape vector and pick the best match, or use edge orientation from a Sobel pass to choose `/`, `|`, `\`, `-` for contours. Colour can tint the glyph with the cell average. ## When to use it Choose it for terminal, hacker or retro aesthetics. Prefer [Halftone screens](https://texelatlas.vercel.app/t/halftone-screen.md) or [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) when you want a fine pattern rather than readable glyphs, and [Pixel-art 3D rendering](https://texelatlas.vercel.app/t/pixel-art-3d-rendering.md) for blocky pixel look. ## Cost cheap — One downsample and one atlas lookup pass; cheap. Measured GPU Weight: 1.84× baseline (feather) — 0.0606 ms median / 0.0644 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.28× baseline (feather) — 0.0204 ms median (2.97× faster on L4). Ampere A100 scaling: 1.24× baseline (feather) — 0.0356 ms median (1.7× faster on A100). ## Failure modes - Flicker in cells whose brightness hovers near a glyph threshold - Low resolution loses small features entirely - Glyph shape ignored by a brightness-only ramp gives soft, mushy structure - Temporal instability when camera motion shifts content across cell boundaries ## Engine support - babylonjs: official — `new BABYLON.AsciiArtPostProcess('a', camera, {font:'40px Monospace'}) from @babylonjs/post-processes` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/postProcesses/src/asciiArt/asciiArtPostProcess.ts, checked 2026-12-01) - threejs: official — `import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/effects/AsciiEffect.js, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, depth - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu ## Presets ### Left: source image. Right: 8px character cells, glyph density chosen from cell brightness (glsl-fragment; rendered 2026-11-29) ```json { "CELL": 8 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } const float CELL=8.0; // P float glyph(vec2 g,int lv){ if(lv==1)return step(length(g-vec2(0.,-.55)),.22); if(lv==2)return max(step(length(g-vec2(0.,-.55)),.22),step(length(g-vec2(0.,.15)),.22)); if(lv==3)return step(abs(g.y),.16)*step(abs(g.x),.6); if(lv==4)return max(step(abs(g.y),.14)*step(abs(g.x),.7),step(abs(g.x),.14)*step(abs(g.y),.7)); if(lv==5)return max(step(abs(abs(g.x)-.4),.14)*step(abs(g.y),.85),step(abs(abs(g.y)-.35),.14)*step(abs(g.x),.85)); if(lv>=6)return step(abs(g.x),.8)*step(abs(g.y),.85)*(1.-.6*step(length(g),.35)); return 0.;} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col; if(!R) col=img(q); else{ vec2 cc=(floor(fragCoord/CELL)+.5)*CELL,cu=(cc-.5*iResolution.xy)/iResolution.y; float L=lum(img(vec2(cu.x-.25,cu.y))); int lv=int(clamp(floor(L*7.),0.,6.)); vec2 g=(fract(fragCoord/CELL)-.5)*2.; col=vec3(.04,.06,.05)+vec3(.45,1.,.6)*glyph(g,lv)*(.55+.45*L); } if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Combines with - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Edge directions choose line-drawing glyphs along contours. ## Sources 1. [primary] Alex Harri ASCII rendering. alexharri.com. https://alexharri.com/blog/ascii-rendering (verified via http on 2026-11-29) 2. [implementation] kb173 (2020) kb173/godot-ascii-shader. https://github.com/kb173/godot-ascii-shader License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "ASCII / character-cell rendering." https://texelatlas.vercel.app/t/ascii-rendering/ (accessed 2026-12-01). --- id: "atomic-fixed-point-compute-point-rasterization" title: "Compute-Shader Atomic Fixed-Point Sub-Pixel Point Rasterization" aliases: [compute point rasterization, atomic software point splatting, fixed-point compute point accumulation] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgpu, desktop-gpu, cuda] year_introduced: 2021 inputs: [point-cloud, particles, depth, camera-poses] outputs: [hdr-image, depth] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Schütz et al., 2021" url: "https://texelatlas.vercel.app/t/atomic-fixed-point-compute-point-rasterization/" sources_verified_at: "2026-11-30" --- # Compute-Shader Atomic Fixed-Point Sub-Pixel Point Rasterization (Schütz et al., 2021) > Bypasses hardware primitive rasterization by projecting points or sub-pixel particles in a compute shader and writing depth-tested colors or fixed-point additive radiance directly into a screen-sized storage buffer using GPU atomics. ## Reach for it when - drawing millions of tiny 1-pixel points or particles bottlenecks hardware rasterizer - avoid 2x2 pixel quad overshading waste on dense lidar or spore point clouds - software rasterize sub-pixel points in compute with lock-free depth testing - pack depth and color into 64-bit atomics for fast compute point visibility - composite massive compute-driven particle fields cleanly against scene depth ## How it works Hardware graphics pipelines are optimized for multi-pixel triangles; feeding them millions of single-pixel points or sub-pixel dust particles wastes 2×2 pixel-quad shader lanes and bottlenecks fixed-function primitive assembly. Compute-shader software point rasterization sidesteps the raster pipeline altogether by running one compute thread per point. Each thread transforms its point into clip space, frustum-culls it, and computes the integer pixel coordinate `(x, y)` in a flat screen-sized `uint32` or `uint64` storage buffer. Two atomic accumulation variants serve different visual regimes: - **Opaque point clouds**: pack quantized depth in the upper bits and color or point ID in the lower bits of a 64-bit integer (or use early depth-buffer rejection followed by `atomicMin` on depth), resolving the nearest point per pixel up to an order of magnitude faster than `GL_POINTS`. - **Additive / translucent micro-particles**: test against the scene depth buffer, convert linear RGB radiance to **fixed-point unsigned integers** (e.g., 16 fractional bits per channel to preserve dim colors), and accumulate via `atomicAdd` into RGB storage channels, yielding deterministic, order-independent energy conservation. A fullscreen resolve pass unpacks the storage buffer into the final HDR framebuffer and clears it for the next frame. ## When to use it Choose it when rendering millions of lidar points, dense particle clouds, or tiny single-pixel spores/sparks where hardware quad-overshading and primitive setup dominate frame time. Prefer [gpu-particle-systems](gpu-particle-systems) using instanced billboard quads whenever particles grow larger than a few pixels or require textured soft sprites and depth-of-field bokeh. Prefer [nanite-virtualized-geometry](nanite-virtualized-geometry) for dense connected triangle surfaces. Prefer [chaotic-attractor-density-rendering](chaotic-attractor-density-rendering) specifically for iterative strange-attractor histogram accumulation. ## Cost cheap — Schütz et al. (2021, 2022) report rendering hundreds of millions to over 1 billion points in real time on desktop GPUs, substantially outperforming hardware GL_POINTS; performance depends on memory coherence and atomic contention. Measured GPU Weight: 145.24× baseline (extreme) — 4.7784 ms median / 4.8419 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 153.47× baseline (extreme) — 2.4402 ms median (1.96× faster on L4). Ampere A100 scaling: 108.84× baseline (extreme) — 3.1345 ms median (1.52× faster on A100). ## Failure modes - Severe atomic contention stalls when millions of points project onto the exact same pixel (e.g., distant dense clusters without LOD or Morton ordering) - Fixed-point 32-bit additive accumulators can overflow and wrap around if extreme particle densities stack without clamping or rescaling - Points larger than 1–2 pixels lose efficiency rapidly compared to hardware triangle rasterization and appear as sparse pinholes up close - 64-bit integer atomics are unavailable in core WebGPU WGSL, requiring split 32-bit depth/color passes or additive fixed-point RGB channels ## Dataflow - Inputs: point-cloud, particles, depth, camera-poses - Outputs: hdr-image, depth - Platforms: webgpu, desktop-gpu, cuda ## Presets ### Atomic Fixed-Point Compute Point Rasterization — hardware 2x2 quad overdraw waste (left) vs sub-pixel fixed-point atomic radiance cloud (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DENSITY": 1, "P_EXPOSURE": 1.15, "P_SPIN": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_DENSITY = 1.00; // P Point Density [0.4, 1.6, 0.05] const float P_EXPOSURE = 1.15; // P Additive Radiance [0.4, 2.2, 0.05] const float P_SPIN = 0.55; // P Orbit Speed [0.0, 1.8, 0.05] const float P_SPLIT = 0.48; // P 2x2 Quad / Atomic [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float dens = clamp(P_DENSITY, 0.35, 1.8); float expo = clamp(P_EXPOSURE, 0.3, 2.5); float t = iTime * max(P_SPIN, 0.0); vec3 bg = mix(vec3(0.02, 0.03, 0.06), vec3(0.06, 0.09, 0.16), smoothstep(-0.5, 0.5, uv.y)); // Subtle screen-space compute tile grid (8x8 workgroup overlay on right, 2x2 pixel-quad grid on left) float quadGrid = step(0.86, max(fract(fragCoord.x * 0.125), fract(fragCoord.y * 0.125))); vec3 col = bg + vec3(0.04, 0.07, 0.12) * quadGrid * 0.45; // Project 120 3D points along a rotating trefoil torus-knot particle stream vec3 atomicAcc = vec3(0.0); float quadHits = 0.0; float zNearest = 10.0; vec3 nearestCol = vec3(0.0); // Quantized 2x2 hardware quad cell for left side overdraw-waste demonstration vec2 quadUv = (floor(fragCoord / 4.0) * 4.0 + 2.0 - 0.5 * iResolution.xy) / iResolution.y; for (int i = 0; i < 120; i++) { float fi = float(i); float u = (fi / 120.0) * 6.2831853; float rMaj = 0.34 + 0.13 * cos(3.0 * u + t * 0.4); vec3 p3 = vec3( rMaj * cos(2.0 * u), 0.16 * sin(3.0 * u) + 0.07 * sin(fi * 7.3), rMaj * sin(2.0 * u) ); // Add radial sub-pixel dust halo offset p3 += vec3(cos(fi * 19.7), sin(fi * 13.1), cos(fi * 29.3)) * 0.055; p3.xz = rot2(p3.xz, t * 0.65); p3.yz = rot2(p3.yz, 0.42 + 0.15 * sin(t * 0.5)); float zCam = 1.65 - p3.z; vec2 proj = p3.xy / max(zCam * 0.72, 0.25); vec3 ptCol = mix(vec3(0.16, 0.78, 1.0), vec3(1.0, 0.52, 0.18), 0.5 + 0.5 * sin(u * 2.0 + p3.y * 4.0)); ptCol *= 0.8 + 0.4 * exp(-max(zCam - 1.0, 0.0)); if (screenX < split) { // Left: Hardware rasterizer forces 2x2 pixel-quad invocations even for 1px points -> overdraw heatmap! vec2 dq = abs(quadUv - proj); if (max(dq.x, dq.y) < 0.022 * dens) { quadHits += 1.0; if (zCam < zNearest) { zNearest = zCam; nearestCol = ptCol; } } } else { // Right: Compute-shader atomic fixed-point additive radiance + depth-packed crisp sub-pixel splat float d = length(uv - proj); float core = exp(-(d * d) / max(0.00016 * dens * dens, 1e-6)); float halo = exp(-(d * d) / max(0.0014 * dens * dens, 1e-5)) * 0.22; // Simulate fixed-point 16-bit integer atomicAdd quantization steps subtly vec3 contrib = ptCol * (core + halo) * expo; atomicAcc += floor(contrib * 64.0 + 0.5) / 64.0; } } if (screenX < split) { // Visualize wasted 2x2 helper-lane quad coverage (amber/magenta heat for overlapping quads) if (quadHits > 0.5) { float heat = clamp(quadHits / 6.0, 0.0, 1.0); vec3 overdrawCol = mix(vec3(0.20, 0.55, 0.95), vec3(1.0, 0.24, 0.36), heat); // Show active pixel (1 of 4) vs 3 wasted helper lanes inside each 2x2 quad vec2 subQ = mod(floor(fragCoord / 2.0), 2.0); float helperLane = step(0.5, subQ.x + subQ.y); col = mix(nearestCol * 1.15, overdrawCol * 0.55, helperLane * 0.72); } } else { col += atomicAcc * 0.65; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md): Renders GPU-simulated micro-particles directly from storage buffers with order-independent fixed-point atomic radiance accumulation. - [Scatter-as-gather bokeh depth of field](https://texelatlas.vercel.app/t/depth-of-field-scatter-as-gather.md): Splits in-focus sub-pixel particles onto the fast atomic compute path while sending larger defocused bokeh sprites to normal rasterization. ## Combination ideas - [Meshlet foliage with compute-rasterized atomic spores](https://texelatlas.vercel.app/ideas/meshlet-foliage-atomic-spore-raster/) ## Sources 1. [primary] Markus Schütz, Bernhard Kerbl, Michael Wimmer (2021) Rendering Point Clouds with Compute Shaders and Vertex Order Optimization. Computer Graphics Forum. https://doi.org/10.1111/cgf.14345 (verified via crossref on 2026-11-30) 2. [primary] Markus Schütz, Bernhard Kerbl, Michael Wimmer (2022) Software Rasterization of 2 Billion Points in Real Time. Proceedings of the ACM on Computer Graphics and Interactive Techniques. https://doi.org/10.1145/3543863 (verified via crossref on 2026-11-30) 3. [implementation] m-schuetz (2019) m-schuetz/compute_rasterizer. https://github.com/m-schuetz/compute_rasterizer License: NOASSERTION. (verified via github on 2026-11-30) 4. [implementation] mrdoob (2026) mrdoob/codevember-2026. https://github.com/mrdoob/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Compute-Shader Atomic Fixed-Point Sub-Pixel Point Rasterization." https://texelatlas.vercel.app/t/atomic-fixed-point-compute-point-rasterization/ (accessed 2026-12-01). --- id: "atrous-wavelet-filter" title: "Edge-avoiding a-trous wavelet filter" aliases: [a-trous filter, edge-avoiding wavelet, A-trous denoiser, à-trous] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, mobile-gpu] year_introduced: 2010 inputs: [radiance, gbuffer, normals, depth] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Dammertz et al." url: "https://texelatlas.vercel.app/t/atrous-wavelet-filter/" sources_verified_at: "2026-11-29" --- # Edge-avoiding a-trous wavelet filter (Dammertz et al.) > A cascade of small sparse blur kernels whose taps double in spacing each pass, weighted by normal, depth and colour similarity, so large smooth areas blur broadly while edges survive. ## Reach for it when - need a cheap large radius blur that keeps object edges - noisy ambient occlusion needs an edge aware cleanup - build my own denoiser from normals and depth guides - bilateral blur too slow for big radius - blur noisy lighting without bleeding across silhouettes ## How it works The à-trous ('with holes') scheme approximates a wide blur using a fixed small kernel, typically the 5x5 cubic B-spline [1 4 6 4 1]/16 outer product. In iteration i the same kernel is applied with taps spaced 2^i pixels apart (inserting 'holes'), so five or six iterations cover a radius of tens of pixels at constant cost per pass. Each tap weight is multiplied by edge-stopping terms from guide buffers: a Gaussian-like function of the difference in colour or luminance, one of normal similarity (typically a clamped dot product raised to a power), and one of depth or position difference. After normalising by the weight sum, the result is used as input to the next pass. Iterating this is a wavelet-like decomposition without actually storing detail coefficients, and it maps well to compute or fragment shaders with ping-pong textures. ## When to use it Choose it as the spatial stage of a hand-built denoiser, for filtering noisy lighting such as ray-traced AO, shadows or GI with a G-buffer guide, or as a cheap large-radius edge-aware smoother for SSAO. It is the building block inside [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md), and the spatial half of [NVIDIA Real-time Denoisers (ReBLUR, ReLAX)](https://texelatlas.vercel.app/t/nvidia-nrd-relax-reblur.md). Prefer [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md) when you also need temporal accumulation and variance guidance, [Intel Open Image Denoise (OIDN)](https://texelatlas.vercel.app/t/open-image-denoise.md) for final offline frames, and a bilateral or [Bilateral Normal Integration](https://texelatlas.vercel.app/t/bilateral-normal-integration.md)-style filter only when a single small radius suffices. ## Cost cheap — Each iteration is one 25-tap (or 9-tap) full-screen pass; five iterations are typically a small fraction of a frame at 1080p, with bandwidth the main cost. Measured GPU Weight: 771.81× baseline (extreme) — 25.3924 ms median / 25.6691 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 585.06× baseline (extreme) — 9.3025 ms median (2.73× faster on L4). Ampere A100 scaling: 571.73× baseline (extreme) — 16.4659 ms median (1.54× faster on A100). ## Failure modes - Blotchy, low-frequency residual noise when the guide buffers do not capture lighting discontinuities - Grid or ringing patterns from sparse taps at large steps on high-frequency input - Light bleeding across thin features whose depth and normal are similar to their surroundings - Over-smoothed texture detail when applied to final colour instead of demodulated irradiance - Shadow and contact detail lost at big steps unless the colour/luminance term gates the weights ## Dataflow - Inputs: radiance, gbuffer, normals, depth - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, cuda, mobile-gpu ## Presets ### 3-pass edge-avoiding a-trous denoise (noisy | filtered) (glsl-fragment; rendered 2026-11-29) ```json { "steps": [ 1, 2, 4 ], "kernel": "3x3 [1 2 1]/4", "sigma_color": 0.15 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Left half: noisy image. Right half: three edge-avoiding a-trous passes (steps 1,2,4) // evaluated analytically by nesting the filter, guided by the clean "albedo/normal" image. const float SIGMA_C = 0.15; // colour edge-stopping strength on the guide const float SIGMA_N = 0.9; // noise amplitude vec3 clean(vec2 p) { vec2 q = p / iResolution.y; vec3 bg = mix(vec3(0.15, 0.25, 0.45), vec3(0.85, 0.75, 0.55), q.y); float d1 = length(q - vec2(0.45, 0.5)) - 0.22; float d2 = length(q - vec2(1.0, 0.45)) - 0.18; vec3 col = bg; col = mix(vec3(0.9, 0.3, 0.2), col, smoothstep(-0.003, 0.003, d1)); col = mix(vec3(0.2, 0.8, 0.4), col, smoothstep(-0.003, 0.003, d2)); return col; } float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); } vec3 noisy(vec2 p) { vec2 c = floor(p) + 0.5; float n = hash12(c) - 0.5; float m = hash12(c + 17.0) - 0.5; return clean(c) * (1.0 + SIGMA_N * n) + vec3(0.0, 0.0, 0.0) * m; } float kern(int i) { return i == 0 ? 0.5 : 0.25; } float edgeW(vec2 p, vec2 q) { vec3 d = clean(p) - clean(q); return exp(-dot(d, d) / (SIGMA_C * SIGMA_C)); } vec3 level1(vec2 p, float s) { vec3 sum = vec3(0.0); float ws = 0.0; for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { vec2 q = p + vec2(float(x), float(y)) * s; float w = kern(abs(x)) * kern(abs(y)) * edgeW(p, q); sum += w * noisy(q); ws += w; } return sum / ws; } vec3 level2(vec2 p, float s) { vec3 sum = vec3(0.0); float ws = 0.0; for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { vec2 q = p + vec2(float(x), float(y)) * s * 2.0; float w = kern(abs(x)) * kern(abs(y)) * edgeW(p, q); sum += w * level1(q, s); ws += w; } return sum / ws; } vec3 level3(vec2 p, float s) { vec3 sum = vec3(0.0); float ws = 0.0; for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { vec2 q = p + vec2(float(x), float(y)) * s * 4.0; float w = kern(abs(x)) * kern(abs(y)) * edgeW(p, q); sum += w * level2(q, s); ws += w; } return sum / ws; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec3 col = (uv.x < 0.5) ? noisy(fragCoord) : level3(fragCoord, 1.0); if (abs(uv.x - 0.5) < 0.003) col = vec3(1.0); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; algorithm follows the cited paper, analytic nesting used so the demo needs no buffers; basis: 0 ## Lineage - extended by [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md) ## Combines with - [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md): SVGF drives the à-trous cascade with variance from temporal moments; the filter is the spatial half. - [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md): Noisy per-pixel-rotated AO is cleaned by an edge-aware à-trous pass using depth and normals. ## Sources 1. [primary] Dammertz, Sewtz, Hanika, Lensch Edge-Avoiding A-Trous Wavelet Transform for fast Global Illumination Filtering. jo.dreggn.org. https://jo.dreggn.org/home/2010_atrous.pdf (verified via http on 2026-11-29) 2. [implementation] NVIDIAGameWorks (2017) NVIDIAGameWorks/Falcor. https://github.com/NVIDIAGameWorks/Falcor License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Edge-avoiding a-trous wavelet filter." https://texelatlas.vercel.app/t/atrous-wavelet-filter/ (accessed 2026-12-01). --- id: "auto-exposure-histogram" title: "Auto exposure from luminance histogram" aliases: [eye adaptation] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2016 inputs: [hdr-image] outputs: [hdr-image] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Opsenica" url: "https://texelatlas.vercel.app/t/auto-exposure-histogram/" sources_verified_at: "2026-11-29" --- # Auto exposure from luminance histogram (Opsenica) > Builds a luminance histogram of the HDR frame in a compute pass, discards outliers, averages the rest in log space, and smoothly adapts exposure over time, giving a stable eye-adaptation response. ## Reach for it when - scene is too dark then blown out when moving between rooms - need eye adaptation that ignores tiny bright lights - exposure pumps and flickers when a bright pixel enters view - want smooth automatic brightness adjustment over time - average luminance gets skewed by outliers ## How it works A compute shader bins every pixel's log2 luminance into a histogram of around 256 buckets, with a small weight toward the screen centre if desired. A second dispatch walks the histogram, trims the darkest and brightest percentiles so tiny lights and black borders do not skew the result, and computes the weighted mean log luminance. That mean maps to a target exposure through an exposure compensation and key value, for example mapping the mean to mid grey. The scene exposure is blended toward the target with an exponential filter, using different rates for brightening and darkening, which mimics pupil adaptation. The exposure is then applied before the tonemapper. ## When to use it Choose it when scene brightness varies a lot and you want eye-adaptation with outlier rejection. Prefer a simple log-average mip chain when compute is unavailable, as in WebGL2. Choose fixed exposure for photographic or art-directed shots. Feed the result into the tonemappers, for example [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md). ## Cost cheap — One histogram compute pass and one tiny reduction; cost dominated by memory bandwidth of reading the frame. Measured GPU Weight: 1.2× baseline (feather) — 0.0396 ms median / 0.0409 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.09× baseline (feather) — 0.0174 ms median (2.28× faster on L4). Ampere A100 scaling: 21.24× baseline (heavy) — 0.6118 ms median (0.06× faster on A100). ## Failure modes - Pumping or oscillation if the adaptation rate is too fast or the metering follows moving lights - Wrong exposure when the frame contains huge bright skies or pure black letterboxing without percentile trimming - Temporal lag causes overexposed frames on cuts unless exposure is reset - Needs compute shaders, so WebGL2 requires a fallback ## Engine support - godot: builtin — `CameraAttributes.auto_exposure_enabled (exposure adaptation from scene luminance)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/CameraAttributes.xml, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Exposure > Mode = Automatic Histogram` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-override-exposure.md, checked 2026-12-01) — HDRP only. URP has no automatic exposure in Unity 6.3. - unreal: builtin — `Post Process Volume > Exposure > Metering Mode = Auto Exposure Histogram` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/auto-exposure-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Dim room with a bright window. Left: fixed exposure. Right: exposure from a luminance histogram with 10% tails discarded (glsl-fragment; rendered 2026-11-29) ```json { "GN": 16, "NB": 24, "LO": 0.1, "HI": 0.9 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const int GN=16; // P const int NB=24; // P const float LO=0.1; // P const float HI=0.9; // P vec3 hdr(vec2 p){ vec3 c=vec3(.02,.025,.03)*(1.+(p.y+.5)*.8); if(p.y<-.3)c=vec3(.05,.035,.025)*(.6+.8*step(.5,fract((p.x+p.y)*12.))); if(length(p-vec2(-.1,-.1))<.09)c=vec3(.5,.2,.1)*.12; if(abs(p.x-.08)<.1&&p.y>.1&&p.y<.4)c=vec3(1.,.95,.85)*18.; return c;} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); float cnt[24];for(int b=0;b0.?1.:0.;sum+=k*(-8.+(float(b)+.5)/float(NB)*14.);ws+=k;acc=a1;mx=max(mx,cnt[b]);} float expo=.18/exp2(sum/max(ws,1e-3)); vec3 c=hdr(q)*(R?expo:1.); vec3 col=gam(c/(1.+c)); if(R&&uv.y<-.3&&uv.x>.03&&uv.x<.47){ int b=int(floor((uv.x-.03)/.44*float(NB)));float h=cnt[b]/mx*.17; col*=.35; if(uv.y+.5.5?vec3(.3,.9,.5):vec3(.6,.3,.3); } if(abs(uv.x)<.0015)col=vec3(1.); fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Combines with - [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md): Exposure scales scene-referred values before the tone curve. ## Combination ideas - [1-bit rendering that meters like a camera](https://texelatlas.vercel.app/ideas/histogram-steered-dithering/) ## Sources 1. [primary] Bruno Opsenica Automatic Exposure. bruop.github.io. https://bruop.github.io/exposure (verified via http on 2026-11-29) 2. [implementation] EmbarkStudios (2021) EmbarkStudios/kajiya. https://github.com/EmbarkStudios/kajiya License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Auto exposure from luminance histogram." https://texelatlas.vercel.app/t/auto-exposure-histogram/ (accessed 2026-12-01). --- id: "basis-universal-ktx2" title: "Basis Universal / KTX2 supercompression" aliases: [Basis Universal, KTX2, UASTC] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2019 inputs: [texture] outputs: [texture] style: "both" dynamic: "both" cost: "cheap" authority: "BinomialLLC, 2019" url: "https://texelatlas.vercel.app/t/basis-universal-ktx2/" sources_verified_at: "2026-11-29" --- # Basis Universal / KTX2 supercompression (BinomialLLC, 2019) > A supercompressed texture format stored in KTX2 that transcodes at load time into whichever GPU format the device supports, such as BC7, ASTC or ETC2. ## Reach for it when - textures too large to download in a web app - one texture file must work on desktop and mobile gpus - gltf textures eat vram and load slowly - don't know which gpu compressed format the device supports ## How it works The encoder writes an intermediate format, either ETC1S for small files or UASTC for high quality, then compresses it further with Zstandard in a KTX2 container. At load, a small WebAssembly or native transcoder converts blocks directly into the target GPU block format with little work per block, and the result uploads without decoding to RGBA. One asset therefore ships to browsers and devices with different texture support, giving small download sizes and small video memory use at once. ## When to use it Choose it for web and cross-platform delivery where the target format is unknown, for example glTF with KHR_texture_basisu. Prefer [Block texture compression (BC7 / ASTC)](https://texelatlas.vercel.app/t/block-texture-compression.md) pre-encoded per platform when you control the device set and want the best quality. Prefer PNG or JPEG for size-insensitive small textures. ## Cost cheap — Runtime cost is transcoding at load; GPU cost equals that of the chosen block format. Measured GPU Weight: 3.53× baseline (light) — 0.1162 ms median / 0.1167 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.03× baseline (light) — 0.0482 ms median (2.41× faster on L4). Ampere A100 scaling: 2.53× baseline (light) — 0.0729 ms median (1.59× faster on A100). ## Failure modes - ETC1S shows blocky colour and loses fine detail, especially on normals - Transcoding adds load-time latency without a worker - Quality at a given size is below a dedicated encoder per format - Alpha and HDR need extra care ## Engine support - babylonjs: builtin — `KhronosTextureContainer2 / KHR_texture_basisu loader (KTX2 Basis transcoding)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Misc/khronosTextureContainer2.ts, checked 2026-12-01) - godot: builtin — `Import dock > Compress > Mode = Basis Universal (stores KTX2/UASTC/ETC1S)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/CompressedTexture2D.xml, checked 2026-12-01) - threejs: official — `import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/loaders/KTX2Loader.js, checked 2026-12-01) - unity: official — `Package Manager > KTX for Unity (com.unity.cloud.ktx)` (evidence: https://docs.unity3d.com/Packages/com.unity.cloud.ktx@3.0/manual/index.html, checked 2026-12-01) — Official Unity package (KTX 2.0 / Basis Universal). ## Dataflow - Inputs: texture - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Basis Universal / KTX2 — 4x4 ETC1S codebook endpoint quantization (left) vs transcoded UASTC/BC7 PBR shading (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BLOCK_SCALE": 6, "P_QUANT_LEVELS": 0.55, "P_GRID_VIS": 0.5, "P_SPLIT": 0.48 } ``` ```glsl const float P_BLOCK_SCALE = 6.00; // P 4x4 Block Scale [2.0, 12.0, 0.5] const float P_QUANT_LEVELS = 0.55; // P Endpoint Quant [0.15, 1.0, 0.05] const float P_GRID_VIS = 0.50; // P Block Grid Vis [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P ETC1S / UASTC [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Rich multi-frequency PBR surface albedo + micro-normal texture mapped onto sphere vec3 evalTexAlbedo(vec2 tuv) { vec2 p = tuv * 5.0; float wave = sin(p.x * 3.0 + sin(p.y * 2.4) * 1.6) * 0.5 + 0.5; float rings = smoothstep(0.35, 0.65, sin(length(fract(p * 0.5) - 0.5) * 28.0)); vec3 cA = vec3(0.14, 0.52, 0.78); vec3 cB = vec3(0.94, 0.44, 0.18); vec3 cC = vec3(0.92, 0.86, 0.68); vec3 base = mix(cA, cB, wave); return mix(base, cC, rings * 0.42); } float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } // Simulate 4x4 GPU block compression (ETC1S single-color-endpoint + 2-bit intensity modifier per texel) vec3 encodeETC1SBlock(vec2 tuv, float blocksPerUnit, float quantStr) { vec2 bCoord = tuv * blocksPerUnit; vec2 bId = floor(bCoord); vec2 sub = floor(fract(bCoord) * 4.0) / 4.0; vec2 blockCenter = (bId + 0.5) / blocksPerUnit; // Compute block mean chroma endpoint (ETC1S shares one base RGB555 endpoint per 4x4 block!) vec3 c0 = evalTexAlbedo((bId + vec2(0.25, 0.25)) / blocksPerUnit); vec3 c1 = evalTexAlbedo((bId + vec2(0.75, 0.25)) / blocksPerUnit); vec3 c2 = evalTexAlbedo((bId + vec2(0.25, 0.75)) / blocksPerUnit); vec3 c3 = evalTexAlbedo((bId + vec2(0.75, 0.75)) / blocksPerUnit); vec3 baseEp = (c0 + c1 + c2 + c3) * 0.25; float bits = mix(14.0, 4.0, quantStr); baseEp = floor(baseEp * bits + 0.5) / bits; // Per-texel 2-bit selector modifies only luminance around the shared block endpoint vec3 texVal = evalTexAlbedo((bId + sub + 0.125) / blocksPerUnit); float dL = luma(texVal) - luma(baseEp); float sel = floor(clamp(dL * 5.0 + 2.0, 0.0, 3.0)) - 1.5; return clamp(baseEp + vec3(sel * 0.10), 0.0, 1.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float bScale = clamp(P_BLOCK_SCALE, 2.0, 14.0); float qStr = clamp(P_QUANT_LEVELS, 0.1, 1.0); float gVis = clamp(P_GRID_VIS, 0.0, 1.0); vec3 ro = vec3(0.0, 0.22, 2.15); vec3 rd = normalize(vec3(uv.x, uv.y - 0.05, -1.48)); vec3 lDir = normalize(vec3(0.58, 0.72, 0.52)); vec3 col = mix(vec3(0.05, 0.07, 0.11), vec3(0.14, 0.19, 0.28), smoothstep(-0.5, 0.5, uv.y)); // Textured floor swatch showing flat 4x4 KTX2 texel blocks clearly float tMin = 1e5; int hitId = 0; vec3 hp = vec3(0.0); vec3 hn = vec3(0.0, 1.0, 0.0); vec2 tuv = vec2(0.0); if (rd.y < -0.005) { float tf = (-0.54 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { tMin = tf; hitId = 1; hp = ro + rd * tf; hn = vec3(0.0, 1.0, 0.0); tuv = hp.xz * 0.42 + vec2(iTime * 0.05, 0.0); } } // Hero rotating PBR sphere showcasing transcoded KTX2 texture fidelity vec3 sc = vec3(0.0, 0.02, 0.0); vec3 oc = ro - sc; float b = dot(oc, rd), d = b * b - (dot(oc, oc) - 0.54 * 0.54); if (d > 0.0) { float ts = -b - sqrt(d); if (ts > 0.05 && ts < tMin) { tMin = ts; hitId = 2; hp = ro + rd * ts; hn = normalize(hp - sc); vec3 rn = hn; rn.xz = rot2(rn.xz, iTime * 0.35); tuv = vec2(atan(rn.z, rn.x) / 6.2831853 + 0.5, acos(clamp(rn.y, -1.0, 1.0)) / 3.1415926); } } if (hitId > 0) { float blocks = bScale * (hitId == 2 ? 4.5 : 3.2); vec3 alb; float gridLine = 0.0; if (screenX < split) { // Left: Low-bitrate ETC1S supercompressed 4x4 block endpoints + block boundary grid alb = encodeETC1SBlock(tuv, blocks, qStr); vec2 bf = fract(tuv * blocks); gridLine = smoothstep(0.06, 0.015, min(min(bf.x, 1.0 - bf.x), min(bf.y, 1.0 - bf.y))); } else { // Right: High-quality UASTC -> BC7/ASTC GPU-native transcoded texture with crisp micro-details alb = evalTexAlbedo(tuv); } float ndl = max(dot(hn, lDir), 0.0); float spec = (hitId == 2) ? pow(max(dot(reflect(-lDir, hn), -rd), 0.0), 36.0) * 0.72 : 0.0; float fres = (hitId == 2) ? pow(1.0 - max(dot(hn, -rd), 0.0), 4.0) * 0.45 : 0.0; vec3 shaded = alb * (0.24 + 0.96 * ndl) + vec3(0.85, 0.92, 1.0) * (spec + fres); shaded = mix(shaded, vec3(0.18, 0.94, 1.0), gridLine * gVis * 0.55); col = (hitId == 1) ? mix(col, shaded, exp(-tMin * 0.14)) : shaded; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Block texture compression (BC7 / ASTC)](https://texelatlas.vercel.app/t/block-texture-compression.md) ## Combines with - [Draco mesh compression](https://texelatlas.vercel.app/t/draco-mesh-compression.md): Both shrink glTF delivery size: one compresses geometry, the other textures. ## Sources 1. [primary] BinomialLLC (2019) BinomialLLC/basis_universal. https://github.com/BinomialLLC/basis_universal License: Apache-2.0. (verified via github on 2026-11-29) 2. [primary] Mark Callow KTX File Format Specification Version 2.0. registry.khronos.org. https://registry.khronos.org/KTX/specs/2.0/ktxspec.v2.html (verified via http on 2026-11-29) 3. [implementation] KhronosGroup (2013) KhronosGroup/KTX-Software. https://github.com/KhronosGroup/KTX-Software License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Basis Universal / KTX2 supercompression." https://texelatlas.vercel.app/t/basis-universal-ktx2/ (accessed 2026-12-01). --- id: "bent-normals" title: "Bent Normals" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2002 inputs: [normals, depth] outputs: [normals] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Jimenez et al." url: "https://texelatlas.vercel.app/t/bent-normals/" sources_verified_at: "2026-11-29" --- # Bent Normals (Jimenez et al.) > Stores or computes the mean unoccluded direction at a surface point, then uses it instead of the geometric normal to sample diffuse and specular lighting. ## Reach for it when - probe lighting makes occlusion look flat and directionless - ambient light leaks into creases when using environment maps - diffuse environment lighting ignores which way is open - darkening from occlusion doesn't follow the open direction ## How it works A bent normal is the average direction of unblocked rays over the hemisphere, so it leans away from nearby occluders. When irradiance is fetched from an environment map or probe using that direction, light appears to come mainly from open sky and crevices darken in a directional, not just scalar, way. They can be baked offline into a texture, computed from an SDF or ray traces, or produced by horizon-based screen-space AO at little extra cost. The bent normal is also paired with the AO value to define a visibility cone for specular occlusion. ## When to use it Choose it when your lighting is image-based or probe-based and uniform AO produces flat, direction-less darkening. Prefer plain AO when lighting is a single dominant directional light, and [Visibility Bitmask Ambient Occlusion](https://texelatlas.vercel.app/t/visibility-bitmask-ssao.md) when you want directional visibility information in screen space. ## Cost cheap — Free if baked; a small ALU addition inside a horizon-based AO pass otherwise. Measured GPU Weight: 45.85× baseline (heavy) — 1.5084 ms median / 1.5388 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 37.58× baseline (heavy) — 0.5976 ms median (2.52× faster on L4). Ampere A100 scaling: 30.11× baseline (heavy) — 0.8673 ms median (1.74× faster on A100). ## Failure modes - Incorrect when computed from a single-layer depth buffer behind thin occluders - Texture-space bent normals break under deformation or tiling - Blending with the geometric normal needs tuning to avoid leaks - Not defined for dynamic lighting that depends on global visibility ## Engine support - blender: builtin — `Shader node: Ambient Occlusion (Cycles/EEVEE AO & normal-guided occlusion)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/input/ao.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.bent_normal_enabled = true; assign BaseMaterial3D.bent_normal_texture` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - unity: builtin — `HDRP Lit > Surface Inputs > Bent Normal Map; Specular Occlusion Mode = From Bent Normal` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Features.md, checked 2026-12-01) — HDRP only (Lit and StackLit specular occlusion from bent normals). - unreal: builtin — `Material > Bent Normal Custom Output / bent normal maps` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/bent-normal-maps-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: normals, depth - Outputs: normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: AO times sky lookup along the normal. Right: same AO, sky looked up along the bent normal (glsl-fragment; rendered 2026-11-29) ```json { "NR": 48, "MAXD": 0.8 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const int NR=48; // P const float MAXD=0.8; // P void aoBent(vec3 P,vec3 N,vec2 uv,out float ao,out vec3 bent){ vec3 T=normalize(abs(N.y)<.9?cross(N,vec3(0.,1.,0.)):cross(N,vec3(1.,0.,0.))),B=cross(N,T); float ph=rnd2(uv,5.).x*6.2831853,vis=0.;vec3 sum=vec3(0.); for(int i=0;iMAXD){sum+=d;vis+=1.;}} ao=vis/float(NR);bent=normalize(sum+N*.001);} vec3 env(vec3 d){return vec3(.18,.2,.26)+vec3(1.,.85,.6)*1.6*pow(max(dot(d,normalize(vec3(.8,.5,-.3))),0.),3.);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao;vec3 b;aoBent(P,n,uv,ao,b); col=mix(alb(P)*env(R?b:n)*ao*1.3,sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Sources 1. [primary] Jorge Jimenez, Xian-Chun Wu, Angelo Pesce, Adrian Jarabo Practical Real-Time Strategies for Accurate Indirect Occlusion. SIGGRAPH 2016 Course: Physically Based Shading in Theory and Practice. https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Bent Normals." https://texelatlas.vercel.app/t/bent-normals/ (accessed 2026-12-01). --- id: "bidirectional-path-tracing" title: "Bidirectional Path Tracing" aliases: [BDPT, BPT] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda] year_introduced: 1993 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Veach & Guibas, 1995" url: "https://texelatlas.vercel.app/t/bidirectional-path-tracing/" sources_verified_at: "2026-11-29" --- # Bidirectional Path Tracing (Veach & Guibas, 1995) > Traces one random walk from the camera and one from a light, then connects every pair of vertices with a shadow ray. Each connection is a different path-sampling strategy, merged with multiple importance sampling. ## Reach for it when - interior lit by a lamp inside a diffuser is full of noise - light only reaches the room through a small gap - camera paths rarely find the light source - fireflies in scenes with enclosed emitters - indirect-lit interiors converge too slowly ## How it works A path from a light to the eye can be built many ways: by extending from the eye, from the light, or from both and joining in the middle. BDPT does all of them in one pass. It generates an **eye subpath** and a **light subpath**, each a short random walk, and for every pair of vertices `(i, j)` it tests visibility and evaluates the connecting segment's throughput. A path of length `k` is therefore sampled by `k+1` different strategies. Strategies differ wildly in quality per path type, so contributions are combined with [multiple-importance-sampling](multiple-importance-sampling). The weights need the pdf each other strategy would have used, which is where most implementation bugs live: reversed-direction pdfs, non-symmetric BSDFs and the area measure for vertices. Light subpaths that reach the camera lens (the `t = 1` case) deposit into the image as a **light tracing** splat, so the framebuffer needs atomic or per-thread accumulation. ## When to use it Choose it for scenes lit mostly indirectly through small gaps, lamps enclosed in diffusers, or interiors with a lot of diffuse interreflection and hard-to-reach emitters, where the camera walk rarely finds a light. Prefer [path-tracing](path-tracing) for open scenes, outdoor lighting or when the extra complexity is not worth it; BDPT is slower per sample and does not help much there. Prefer [vertex-connection-and-merging](vertex-connection-and-merging) or [progressive-photon-mapping](progressive-photon-mapping) when specular-diffuse-specular caustics dominate, because plain connections cannot sample a specular vertex. Prefer [metropolis-light-transport](metropolis-light-transport) for very constrained light paths. ## Cost offline — Roughly several times the cost per sample of unidirectional path tracing because of the connection rays and MIS weight computation; image splatting makes GPU implementations awkward. Measured GPU Weight: 19.98× baseline (moderate) — 0.6575 ms median / 0.7245 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.29× baseline (heavy) — 0.3226 ms median (2.04× faster on L4). Ampere A100 scaling: 12.68× baseline (moderate) — 0.3651 ms median (1.8× faster on A100). ## Failure modes - Specular vertices cannot be connected, so caustics through glass still fall back to unlikely random hits - Subtle MIS pdf bugs create slightly wrong brightness that is hard to spot without a reference - Light-tracing splats outside the pixel footprint create sparse speckle and need a separate buffer or atomics - Memory and bandwidth for storing subpaths make wavefront GPU versions heavy ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda ## Presets ### Bidirectional Path Tracing (BDPT) — unidirectional path noise (left) vs MIS eye+light subpath connections (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MIS_WEIGHT": 1, "P_INDIRECT": 1.15, "P_LIGHT_SWAY": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_MIS_WEIGHT = 1.0; // P BDPT MIS Gain [0.2, 1.5, 0.05] const float P_INDIRECT = 1.15; // P Indirect Bounce [0.2, 2.0, 0.05] const float P_LIGHT_SWAY = 0.65; // P Lamp Swing [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P PT / BDPT Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Classic shielded-lamp Cornell Box (hard for unidirectional PT because direct light is blocked by ceiling baffle!) vec2 mapBox(vec3 p) { // Room interior walls: x in [-1, 1], y in [-1, 1], z in [-1.2, 1.4] float dFloor = p.y + 0.95; float dCeil = 0.95 - p.y; float dLeft = p.x + 1.05; float dRight = 1.05 - p.x; float dBack = p.z + 1.15; vec2 res = vec2(dFloor, 1.0); // white floor if (dCeil < res.x) res = vec2(dCeil, 1.0); if (dBack < res.x) res = vec2(dBack, 1.0); if (dLeft < res.x) res = vec2(dLeft, 2.0); // red left wall if (dRight < res.x) res = vec2(dRight, 3.0); // cyan-green right wall // Opaque shade baffle beneath the upward-pointing ceiling lamp (forces indirect bounce!) vec3 pb = abs(p - vec3(0.0, 0.56, -0.15)) - vec3(0.36, 0.035, 0.36); float dBaffle = length(max(pb, 0.0)) + min(max(pb.x, max(pb.y, pb.z)), 0.0); if (dBaffle < res.x) res = vec2(dBaffle, 4.0); // Diffuse matte sphere + glossy tall block inside room float dSph = length(p - vec3(-0.36, -0.58, -0.20)) - 0.37; if (dSph < res.x) res = vec2(dSph, 5.0); vec3 pt = abs(p - vec3(0.42, -0.38, -0.35)) - vec3(0.24, 0.57, 0.24); float dTall = length(max(pt, 0.0)) + min(max(pt.x, max(pt.y, pt.z)), 0.0); if (dTall < res.x) res = vec2(dTall, 6.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapBox(p + e.xyy).x - mapBox(p - e.xyy).x, mapBox(p + e.yxy).x - mapBox(p - e.yxy).x, mapBox(p + e.yyx).x - mapBox(p - e.yyx).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isBDPT = screenX >= split; float misGain = clamp(P_MIS_WEIGHT, 0.15, 1.6); float indGain = clamp(P_INDIRECT, 0.15, 2.2); float sway = sin(iTime * 0.75 * max(P_LIGHT_SWAY, 0.0)) * 0.22; vec3 ro = vec3(0.0, 0.02, 2.15); vec3 rd = normalize(vec3(uv, -1.38)); float t = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapBox(ro + rd * t); if (h.x < 0.0025) { hit = vec2(t, h.y); break; } t += h.x; if (t > 6.5) break; } vec3 col = vec3(0.02, 0.025, 0.04); if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 alb = vec3(0.76, 0.75, 0.72); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.84, 0.16, 0.14); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.14, 0.74, 0.56); else if (hit.y > 3.5 && hit.y < 4.5) alb = vec3(0.14, 0.16, 0.20); else if (hit.y > 4.5 && hit.y < 5.5) alb = vec3(0.88, 0.84, 0.78); else if (hit.y > 5.5) alb = vec3(0.78, 0.74, 0.68); // Upward-pointing ceiling lamp at (sway, 0.68, -0.15) bounces cleanly off ceiling into room! vec3 lampPos = vec3(sway, 0.68, -0.15); vec3 vplCeil1 = vec3(sway - 0.35, 0.92, -0.15); vec3 vplCeil2 = vec3(sway + 0.35, 0.92, -0.15); vec3 vplLeft = vec3(-1.02, 0.12, -0.20); vec3 vplRight = vec3(1.02, 0.12, -0.20); // Clean multi-bounce indirect irradiance via BDPT light subpath vertices connected to camera vertex vec3 toC1 = vplCeil1 - p; vec3 toC2 = vplCeil2 - p; float wC1 = max(dot(n, normalize(toC1)), 0.0) / (0.45 + dot(toC1, toC1)); float wC2 = max(dot(n, normalize(toC2)), 0.0) / (0.45 + dot(toC2, toC2)); // Soft occlusion by the lamp baffle & objects float occ = smoothstep(-0.2, 0.3, length(p.xz - vec2(0.0, -0.15)) - 0.15 * step(p.y, 0.56)); vec3 ceilBounce = vec3(1.0, 0.92, 0.78) * (wC1 + wC2) * 0.95 * (0.45 + 0.55 * occ); // Secondary wall color bleeding from red left & teal right walls vec3 toL = vplLeft - p; vec3 toR = vplRight - p; vec3 bleedL = vec3(0.86, 0.16, 0.12) * max(dot(n, normalize(toL)), 0.0) / (0.65 + dot(toL, toL)) * 0.55; vec3 bleedR = vec3(0.12, 0.78, 0.58) * max(dot(n, normalize(toR)), 0.0) / (0.65 + dot(toR, toR)) * 0.55; // Bright emissive ceiling pool right above the shielded lamp float ceilGlow = smoothstep(0.55, 0.05, length(p.xz - lampPos.xz)) * smoothstep(0.86, 0.94, p.y); vec3 cleanGI = alb * (ceilBounce + (bleedL + bleedR) * indGain + vec3(0.04)) + vec3(2.8, 2.4, 1.9) * ceilGlow; if (isBDPT) { // Right: BDPT with MIS balances (s, t) light+eye subpaths -> smooth, firefly-free indirect lighting! col = cleanGI * misGain; // Subtle glowing MIS connection arcs near the lamp ceiling bounce float arc = exp(-abs(length(uv - vec2(sway * 0.35, 0.34)) - 0.14) * 48.0) * 0.25; col += vec3(0.24, 0.90, 0.98) * arc; } else { // Left: Unidirectional path tracing struggles to hit shielded light -> heavy Monte Carlo speckle & fireflies! vec2 pix = floor(fragCoord * 0.75); float frame = floor(iTime * 10.0) * 0.13; float r1 = hash21(pix + vec2(frame * 17.3, 3.1)); float r2 = hash21(pix * 1.41 + vec2(7.7, frame * 23.1)); float noiseMult = mix(0.25, 1.65, r1); float firefly = smoothstep(0.965, 0.999, r2) * 5.2; col = cleanGI * noiseMult + alb * vec3(1.0, 0.92, 0.76) * firefly * (1.0 - ceilGlow); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Vertex Connection and Merging](https://texelatlas.vercel.app/t/vertex-connection-and-merging.md) ## Combines with - [Multiple Importance Sampling](https://texelatlas.vercel.app/t/multiple-importance-sampling.md): Weights the k+1 strategies that can build each path. ## Sources 1. [primary] Eric Veach, Leonidas Guibas (1995) Bidirectional Estimators for Light Transport. Photorealistic Rendering Techniques. https://doi.org/10.1007/978-3-642-87825-1_11 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Bidirectional Path Tracing (Physically Based Rendering, 3rd edition). pbr-book.org. https://pbr-book.org/3ed-2018/Light_Transport_III_Bidirectional_Methods/Bidirectional_Path_Tracing (verified via http on 2026-11-29) 3. [implementation] mmp (2015) mmp/pbrt-v3. https://github.com/mmp/pbrt-v3 License: BSD-2-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "Bidirectional Path Tracing." https://texelatlas.vercel.app/t/bidirectional-path-tracing/ (accessed 2026-12-01). --- id: "bilateral-normal-integration" title: "Bilateral Normal Integration" aliases: [BNI] domain: "capture" stage: "capture" realtime: "offline" platforms: [python, cpu] year_introduced: 2022 inputs: [normals] outputs: [depth, mesh] style: "photoreal" dynamic: "static" cost: "offline" authority: "Cao et al., 2022" url: "https://texelatlas.vercel.app/t/bilateral-normal-integration/" sources_verified_at: "2026-11-29" --- # Bilateral Normal Integration (Cao et al., 2022) > Integrates a normal map into a depth surface while preserving depth discontinuities, using a bilateral weighting that is optimised iteratively in a sparse linear least-squares loop. ## Reach for it when - turn a normal map into a depth surface - integrating normals smears over sharp depth steps - photometric stereo normals need to become a mesh - recover height from estimated normals keeping discontinuities ## How it works Classic normal integration assumes the surface is smooth, so it smears across steps and occlusion boundaries. This method writes the integration as a sparse system relating neighbouring pixels' log-depth through the normals, but weights each pixel pair with a bilateral term that tells it whether the pair lies across a discontinuity. The weights are unknown, so they are estimated from the current solution and the system is re-solved in an alternating scheme, which is a form of iteratively reweighted least squares with a robust cost. Orthographic and perspective camera models are both supported. The result is a depth map that keeps sharp silhouettes and creases. Pixels outside a mask are ignored. ## When to use it Choose it to turn normal maps from photometric stereo, monocular normal estimators or [MoGe (Monocular Geometry Estimation)](https://texelatlas.vercel.app/t/moge.md) into usable depth or meshes with sharp steps. Prefer a simple Poisson or Frankot-Chellappa integrator when the surface is genuinely smooth and speed matters. Prefer multi-view [NeuS](https://texelatlas.vercel.app/t/neus.md) when you can supply many views instead of a single normal map. ## Cost offline — Sparse solves per iteration; seconds for megapixel normal maps on CPU in the reference implementation. Measured GPU Weight: 274.63× baseline (extreme) — 9.0353 ms median / 9.1495 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 235.94× baseline (extreme) — 3.7514 ms median (2.41× faster on L4). Ampere A100 scaling: 206.33× baseline (extreme) — 5.9423 ms median (1.52× faster on A100). ## Failure modes - Normals with low-frequency bias integrate into a globally warped surface regardless of weighting - Wrong discontinuity decisions split or merge surface patches, producing cliffs at the wrong places - Depth scale is only defined up to the camera model assumptions, so absolute size needs another cue - Mask errors bleed background depth into the object boundary ## Dataflow - Inputs: normals - Outputs: depth, mesh - Platforms: python, cpu ## Presets ### Bilateral Normal Integration — blurred Poisson integration (left) vs discontinuity-preserving bilateral relief (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DISCONT_K": 0.88, "P_RELIEF_H": 0.72, "P_LIGHT_SPIN": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_DISCONT_K = 0.88; // P Bilateral Sharpness [0.1, 1.0, 0.02] const float P_RELIEF_H = 0.72; // P Relief Height [0.2, 1.2, 0.04] const float P_LIGHT_SPIN = 0.65; // P Light Sweep [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Poisson / Bilateral [0.0, 1.0, 0.02] // Ground-truth stepped architectural bas-relief heightfield with sharp depth discontinuities! float exactRelief(vec2 p) { // Concentric stepped Aztec/classical relief terraces + domed medallions float dBox = max(abs(p.x), abs(p.y)); float h = 0.0; h += 0.22 * step(dBox, 0.42); h += 0.18 * step(length(p), 0.30); // 4 carved corner medallions with sharp cliffs vec2 q = abs(p) - vec2(0.28, 0.28); h += 0.20 * step(length(q), 0.105); // Central spherical relief dome float rC = length(p); if (rC < 0.20) h += 0.22 * sqrt(max(1.0 - (rC / 0.20) * (rC / 0.20), 0.0)); return h; } // Smooth (Poisson-integrated) version: continuous integrability smears across jump discontinuities! float poissonRelief(vec2 p) { float h = 0.0; float wSum = 0.0; for (int dy = -2; dy <= 2; dy++) { for (int dx = -2; dx <= 2; dx++) { vec2 off = vec2(float(dx), float(dy)) * 0.022; float w = exp(-dot(off, off) * 750.0); h += exactRelief(p + off) * w; wSum += w; } } return h / max(wSum, 1e-5); } // Bilateral-integrated version: sigmoid discontinuity weight k keeps step cliffs razor sharp float bilateralRelief(vec2 p, float kSharp) { return mix(poissonRelief(p), exactRelief(p), smoothstep(0.05, 0.95, kSharp)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isBilateral = screenX >= split; float kSharp = clamp(P_DISCONT_K, 0.05, 1.0); float relH = clamp(P_RELIEF_H, 0.15, 1.4); float spin = iTime * max(P_LIGHT_SPIN, 0.0); // Oblique 3D camera inspecting the reconstructed heightfield surface vec3 ro = vec3(0.0, 0.92, 1.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.48, -1.25)); vec3 col = mix(vec3(0.025, 0.032, 0.052), vec3(0.065, 0.082, 0.128), smoothstep(-0.5, 0.5, uv.y)); // Raymarch the integrated heightfield y = h(x, z) float t = 0.4; bool hit = false; for (int i = 0; i < 60; i++) { vec3 p = ro + rd * t; float h = isBilateral ? bilateralRelief(p.xz, kSharp) : poissonRelief(p.xz); float d = p.y - h * relH; if (d < 0.004) { hit = true; break; } t += max(d * 0.48, 0.012); if (t > 4.5) break; } if (hit) { vec3 p = ro + rd * t; float e = 0.006; float hC = isBilateral ? bilateralRelief(p.xz, kSharp) : poissonRelief(p.xz); float hX = isBilateral ? bilateralRelief(p.xz + vec2(e, 0.0), kSharp) : poissonRelief(p.xz + vec2(e, 0.0)); float hZ = isBilateral ? bilateralRelief(p.xz + vec2(0.0, e), kSharp) : poissonRelief(p.xz + vec2(0.0, e)); vec3 n = normalize(vec3((hC - hX) * relH / e, 1.0, (hC - hZ) * relH / e)); vec3 lDir = normalize(vec3(cos(spin * 0.7) * 0.72, 0.78, sin(spin * 0.7) * 0.72)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 36.0); // Subtle elevation contour lines & discontinuity edge glow float discEdge = clamp(length(vec2(hC - hX, hC - hZ)) * 18.0, 0.0, 1.0); vec3 marble = mix(vec3(0.22, 0.30, 0.42), vec3(0.92, 0.88, 0.82), smoothstep(0.02, 0.58, hC)); float contour = smoothstep(0.06, 0.01, abs(fract(hC * 12.0) - 0.5)); marble = mix(marble, vec3(0.16, 0.80, 0.94), contour * 0.24); col = marble * (0.28 + 0.84 * diff) + vec3(1.0, 0.96, 0.90) * spec * 0.38; if (isBilateral) { // Highlight crisp detected bilateral discontinuity creases in gold col += vec3(0.98, 0.68, 0.22) * discEdge * 0.45; } else { // Highlight Poisson ramp-blurring error in magenta col += vec3(0.94, 0.24, 0.52) * discEdge * 0.45; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Universal Photometric Stereo (SDM-UniPS)](https://texelatlas.vercel.app/t/universal-photometric-stereo.md): UniPS outputs normals; BNI integrates them into depth with preserved discontinuities. ## Combination ideas - [Drawings to relief via generated relighting](https://texelatlas.vercel.app/ideas/relit-drawings-to-relief/) ## Sources 1. [primary] Xu Cao, Hiroaki Santo, Boxin Shi, Fumio Okura, Yasuyuki Matsushita (2022) Bilateral Normal Integration. Lecture Notes in Computer Science. https://doi.org/10.1007/978-3-031-19769-7_32 (verified via crossref on 2026-11-29) 2. [implementation] xucao-42 (2022) xucao-42/bilateral_normal_integration. https://github.com/xucao-42/bilateral_normal_integration License: GPL-3.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Bilateral Normal Integration." https://texelatlas.vercel.app/t/bilateral-normal-integration/ (accessed 2026-12-01). --- id: "bit-packed-3d-morphological-voxels" title: "32-Bit Word-Packed 3D Mathematical Morphology & Open-Face Indirect Emission" aliases: [bit-packed 3D morphology, word-packed voxel erosion, bitmask voxel sculpting] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgpu, desktop-gpu, cuda] year_introduced: 2019 inputs: [voxels, sdf] outputs: [voxels, mesh] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Dantas & Leal, 2019" url: "https://texelatlas.vercel.app/t/bit-packed-3d-morphological-voxels/" sources_verified_at: "2026-11-30" --- # 32-Bit Word-Packed 3D Mathematical Morphology & Open-Face Indirect Emission (Dantas & Leal, 2019) > Stores a binary 3D voxel volume at 1 bit per cell inside 32-bit GPU words, running bitwise erosion and dilation in compute shaders and emitting only exposed boundary faces via indirect draw buffers. ## Reach for it when - 3d voxel erosion or dilation uses too much vram and bandwidth - need fast gpu morphological opening closing or smoothing on voxel masks - pack 64 binary voxels per word for single-instruction neighbor stencils - sculpt and clean up noisy voxel occupancy grids at interactive rates - compute bitwise 3d flood fill and bevel masks in compute shaders ## How it works Binary 3D mathematical morphology—erosion, dilation, opening, and closing—normally stalls on memory bandwidth when stored at one byte or float per voxel. Packing **32 consecutive cells along X into a single `uint32`** cuts storage and memory traffic by 32×, allowing grids of `256³` to `472³` voxels to reside comfortably in a few megabytes of GPU storage buffers. Each compute pass reads a destination word together with its neighbor words across the structuring element's footprint (such as a 6-connected cross or spherical brush). Along the packed axis, shifted neighbor bits are assembled in registers via bitwise shifts and masks (`(curr >> 1) | (next << 31)`), so **erosion** reduces to bitwise `AND` over the neighborhood while **dilation** reduces to bitwise `OR`—updating 32 voxels per word operation. For rendering without full-volume ray marching or CPU readbacks, a second compute pass computes the **6 open-face bitmasks** per word (`solid & ~neighbor_solid`) along `±X, ±Y, ±Z`. Threads iterate over set bits with count-trailing-zeros (`ctz`) and atomically append exposed quad coordinates to a flat face buffer, writing the exact vertex count into an indirect draw argument buffer for a single instanced GPU draw call. ## When to use it Choose it when you need interactive sculpting, real-time morphological erosion/growth, or destruction on high-resolution dense binary voxel grids on compute-capable GPUs. Prefer [greedy-voxel-meshing](greedy-voxel-meshing) when chunks are mostly static and minimizing triangle count for rasterization matters more than per-frame rebuild speed. Prefer [nanovdb](nanovdb) when the volume is huge and sparse or needs floating-point densities rather than binary occupancy. Prefer [marching-cubes](marching-cubes) when you want smooth isosurfaces instead of crisp cubical voxel faces. ## Cost cheap — 32× bit-packing keeps morphological compute passes and open-face emission under 1 ms for 128³–256³ grids and a few milliseconds up to 472³ on desktop WebGPU, though dense face counts still depend on surface complexity. ## Failure modes - Fixed dense 3D allocation scales cubically with resolution, limiting maximum world extent compared to sparse trees - Repeated erosion followed by dilation (morphological opening) permanently rounds corners and deletes thin tendrils smaller than the structuring element - Worst-case porous or checkerboard volumes can overflow fixed-capacity indirect face buffers if no budget cap or multi-pass compaction is enforced - Binary occupancy stores no sub-voxel surface normals, requiring screen-space shading, AO, or dual-grid smoothing to avoid stair-stepped lighting ## Dataflow - Inputs: voxels, sdf - Outputs: voxels, mesh - Platforms: webgpu, desktop-gpu, cuda ## Combines with - [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md): Indirect draw arguments populated by the open-face emitter let the GPU render dynamically changing face counts without CPU synchronization. - [Greedy meshing for voxel worlds](https://texelatlas.vercel.app/t/greedy-voxel-meshing.md): Coplanar exposed faces from stable regions can be merged into larger quads to reduce rasterization overhead. ## Sources 1. [primary] Daniel Oliveira Dantas, Helton Danilo Passos Leal (2019) Fast multidimensional binary image processing with OpenCL. 2019 International Conference on High Performance Computing & Simulation (HPCS). https://doi.org/10.1109/hpcs48598.2019.9188210 (verified via doi.org on 2026-11-30) 2. [implementation] acher249 (2026) acher249/codevember-2026. https://github.com/acher249/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "32-Bit Word-Packed 3D Mathematical Morphology & Open-Face Indirect Emission." https://texelatlas.vercel.app/t/bit-packed-3d-morphological-voxels/ (accessed 2026-12-01). --- id: "blend-shapes-morph-targets" title: "Blend shapes / morph targets and pose-space deformation" aliases: [morph targets, blendshapes, shape keys, PSD] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, unreal, godot] year_introduced: 1987 inputs: [mesh] outputs: [mesh, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Lewis et al., 2000" url: "https://texelatlas.vercel.app/t/blend-shapes-morph-targets/" sources_verified_at: "2026-11-29" --- # Blend shapes / morph targets and pose-space deformation (Lewis et al., 2000) > Deform a mesh as a weighted sum of stored per-vertex offsets from a neutral shape; pose-space deformation extends this by driving corrective shapes from joint angles. ## Reach for it when - face needs expressions and lip sync driven by sliders - elbow or shoulder collapses when the joint bends - want sculpted corrective shapes triggered by joint pose - need weighted per-vertex deltas from a neutral mesh ## How it works The artist sculpts target meshes that share the neutral mesh's topology. Only the per-vertex deltas are stored. At runtime the final position is the neutral position plus the sum over active targets of weight times delta, usually computed in the vertex shader or a compute pass; normals and tangents are blended the same way. Sparse storage keeps only vertices that move, which matters for faces with dozens of targets. Pose-space deformation uses scattered-data interpolation, typically radial basis functions, in the space of joint angles: example poses with sculpted corrections become anchors, and any new pose gets a smoothly interpolated correction layered on top of skinning, repairing joint collapse and muscle bulges that linear skinning cannot produce. Facial rigs commonly mix both: FACS-style expression targets from capture plus corrective shapes triggered by combinations. ## When to use it Choose it for facial animation, lip sync, muscle bulges and any shape change that is hand-authored and weight-driven; it is also the core of glTF morph targets. Prefer [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md) or [Dual quaternion skinning](https://texelatlas.vercel.app/t/dual-quaternion-skinning.md) for bone-driven body deformation, and combine them with correctives. Prefer [Vertex animation textures (VAT) and GPU crowds](https://texelatlas.vercel.app/t/vertex-animation-textures.md) for baked, non-editable playback of many instances. Prefer [Shape matching (meshless deformation)](https://texelatlas.vercel.app/t/shape-matching-deformation.md) or [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) when the shape should come from physics instead of authored targets. ## Cost cheap — Cost grows with the number of simultaneously active targets; GPU implementations cap active targets (often 4 to 8) or use sparse compute. ## Failure modes - Linear blend of targets cuts corners: combining two large opposing shapes shrinks the mesh instead of following an arc - Sums of many targets overshoot or interpenetrate, needing combination (corrective) shapes - Vertex-count mismatch or reordering breaks the targets silently - Active-target limits in GPU vertex streams force pre-selection or compute-based blending - RBF correctives can ring or extrapolate wildly outside the sampled pose range ## Engine support - babylonjs: builtin — `mesh.morphTargetManager = new MorphTargetManager(scene); manager.addTarget(MorphTarget)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Morph/morphTargetManager.ts, checked 2026-12-01) - blender: builtin — `Object Data > Shape Keys panel` (evidence: https://docs.blender.org/manual/en/5.2/animation/shape_keys/introduction.html, checked 2026-12-01) — Corrective shape keys with drivers give pose-space deformation. - godot: builtin — `MeshInstance3D.set_blend_shape_value(index, value); import via glTF/ImporterMesh` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/MeshInstance3D.xml, checked 2026-12-01) - threejs: builtin — `mesh.morphTargetInfluences[i] = w (geometry.morphAttributes)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/objects/Mesh.js, checked 2026-12-01) - unity: builtin — `SkinnedMeshRenderer.SetBlendShapeWeight(index, weight); import blend shapes with the model` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SkinnedMeshRenderer.SetBlendShapeWeight.html, checked 2026-12-01) - unreal: builtin — `Skeletal Mesh Editor > Morph Target Previewer; Pose Driver node in the Animation Blueprint for pose-space deformation` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/skeletal-mesh-editor-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh, animation - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, unreal, godot ## Combines with - [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md): Skinning supplies the joint-driven pose and blend shapes add expression and corrective deltas on the rest mesh before skinning. ## Sources 1. [primary] J. P. Lewis, Matt Cordner, Nickson Fong (2000) Pose space deformation. Proceedings of the 27th annual conference on Computer graphics and interactive techniques - SIGGRAPH '00. https://doi.org/10.1145/344779.344862 (verified via crossref on 2026-11-29) 2. [primary] Peter-Pike J. Sloan, Charles F. Rose, Michael F. Cohen (2001) Shape by example. Proceedings of the 2001 symposium on Interactive 3D graphics. https://doi.org/10.1145/364338.364382 (verified via crossref on 2026-11-29) 3. [tutorial] Lorach GPU Gems 3, Chapter 3: DirectX 10 Blend Shapes: Breaking the Limits. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-3-directx-10-blend-shapes-breaking-limits (verified via http on 2026-11-29) 4. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Blend shapes / morph targets and pose-space deformation." https://texelatlas.vercel.app/t/blend-shapes-morph-targets/ (accessed 2026-12-01). --- id: "blenderalchemy" title: "BlenderAlchemy" domain: "genai" stage: "generation" realtime: "offline" platforms: [blender, python] year_introduced: 2024 inputs: [text-prompt, ldr-image, graph] outputs: [graph, material-params] style: "both" dynamic: "static" cost: "offline" authority: "Huang et al., 2024" url: "https://texelatlas.vercel.app/t/blenderalchemy/" sources_verified_at: "2026-11-29" --- # BlenderAlchemy (Huang et al., 2024) > Uses a vision-language model to edit Blender material node graphs and procedural parameters, searching over edit sequences with a generator, a visual evaluator and "imagined" reference images. ## Reach for it when - tweaking blender materials by hand to match a reference is tedious - want an ai to edit shader node graphs toward a target image - automate procedural parameter tuning against a visual goal - need to adjust materials from a text or image description ## How it works The system represents the starting scene as a Python program (material graph or procedural setup). A VLM edit generator proposes program edits given the user's intent, and a VLM state evaluator scores or compares renders of candidates against the goal, in a tree-search style loop that keeps the best candidates and refines them. To ground abstract goals such as "make it look rustier" the system also asks an image generator for reference images and compares candidates against them. The final product is a modified Blender setup, not a learned asset. ## When to use it Choose it to automate repetitive material and procedural-parameter editing against a visual target inside Blender. Prefer [LL3M (Large Language 3D Modelers)](https://texelatlas.vercel.app/t/ll3m.md) to create new assets from text, [BlenderGym](https://texelatlas.vercel.app/t/blendergym.md) to measure such systems, and a plain node-graph preset when the edit is known in advance. ## Cost offline — Many VLM and render calls per edit; hours per task are possible with API models. ## Failure modes - Evaluator VLM drifts or approves visually plausible but off-target results - Search depth is limited, so complex multi-step edits get stuck in local optima - Generated reference images may not match what Blender can render - Official repo has no declared licence ## Dataflow - Inputs: text-prompt, ldr-image, graph - Outputs: graph, material-params - Platforms: blender, python ## Combination ideas - [Words to portable node materials](https://texelatlas.vercel.app/ideas/vlm-edited-portable-materials/) ## Sources 1. [primary] Ian Huang, Guandao Yang, Leonidas Guibas (2024) BlenderAlchemy: Editing 3D Graphics with Vision-Language Models. arXiv preprint (cs.CV). https://arxiv.org/abs/2404.17672 (verified via arxiv on 2026-11-29) 2. [implementation] ianhuang0630 (2024) ianhuang0630/BlenderAlchemyOfficial. https://github.com/ianhuang0630/BlenderAlchemyOfficial (verified via github on 2026-11-29) ## Cite this entry Texel. "BlenderAlchemy." https://texelatlas.vercel.app/t/blenderalchemy/ (accessed 2026-12-01). --- id: "blendergym" title: "BlenderGym" domain: "genai" stage: "generation" realtime: "offline" platforms: [blender, python] year_introduced: 2025 inputs: [text-prompt, ldr-image, graph] outputs: [graph] style: "both" dynamic: "static" cost: "offline" authority: "Gu et al., 2025" url: "https://texelatlas.vercel.app/t/blendergym/" sources_verified_at: "2026-11-29" --- # BlenderGym (Gu et al., 2025) > A benchmark that measures how well vision-language-model systems can edit a Blender scene by writing code until its render matches a target, covering geometry, materials, lighting and procedural edits. ## Reach for it when - how to measure whether an llm can edit a blender scene - need a benchmark for agents writing scene-editing code - compare vision-language models on matching a target render - evaluate my blender automation agent objectively ## How it works Each task gives a start scene as a Blender file (with its Python script) and a goal image rendered from an edited version. A system, typically a VLM driving a verifier loop, must produce code edits so that a render of the result matches the goal. Scoring compares renders to the target (perceptual and pixel-level metrics) rather than comparing code, and tasks are grouped by skill: object placement, procedural geometry, lighting, materials and blend-shape-like adjustments. The paper uses it to compare systems and to study how much extra inference-time compute with generator-plus-verifier loops helps. ## When to use it Choose it to evaluate or tune an LLM-in-Blender agent for editing tasks. Prefer [BlenderAlchemy](https://texelatlas.vercel.app/t/blenderalchemy.md) when you want a method rather than a benchmark, and [LL3M (Large Language 3D Modelers)](https://texelatlas.vercel.app/t/ll3m.md) for text-to-asset generation rather than editing. It is not a rendering technique, so use it as a measurement tool only. ## Cost offline — Cost is dominated by VLM calls and Blender renders per task. ## Failure modes - Image-space scoring can reward a visually similar but structurally wrong edit - Tasks are limited to the supplied scene families and Blender version - VLM spatial reasoning errors dominate results - Repository metadata lists no licence for the open-source code ## Dataflow - Inputs: text-prompt, ldr-image, graph - Outputs: graph - Platforms: blender, python ## Sources 1. [primary] Yunqi Gu, Ian Huang, Jihyeon Je, Guandao Yang, Leonidas Guibas (2025) BlenderGym: Benchmarking Foundational Model Systems for Graphics Editing. arXiv preprint (cs.GR). https://arxiv.org/abs/2504.01786 (verified via arxiv on 2026-11-29) 2. [implementation] richard-guyunqi (2025) richard-guyunqi/BlenderGym-Open. https://github.com/richard-guyunqi/BlenderGym-Open (verified via github on 2026-11-29) ## Cite this entry Texel. "BlenderGym." https://texelatlas.vercel.app/t/blendergym/ (accessed 2026-12-01). --- id: "blinn-phong-reflection" title: "Phong and Blinn-Phong shading" aliases: [Phong reflection, Blinn-Phong] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender] year_introduced: 1975 inputs: [normals, material-params] outputs: [radiance] style: "both" dynamic: "both" cost: "cheap" authority: "Blinn, 1977" url: "https://texelatlas.vercel.app/t/blinn-phong-reflection/" sources_verified_at: "2026-11-29" --- # Phong and Blinn-Phong shading (Blinn, 1977) > The classic empirical shading pair: ambient plus Lambert diffuse plus a specular lobe from a cosine raised to a shininess power, using the reflection vector (Phong) or the half vector (Blinn). Cheap, intuitive, not energy conserving. ## Reach for it when - need a simple specular highlight without pbr - shiny plastic look on a low-end mobile shader - want a shininess slider artists understand - highlight looks wrong at grazing angles with reflect vector - prototyping lighting quickly in a toy renderer ## How it works Phong computes the mirror direction R of the light about the normal and takes pow(max(dot(R, V), 0), s) as the specular term, where V points to the viewer and s is a shininess exponent. Blinn replaced R with the half vector H = normalize(L + V) and used pow(max(dot(N, H), 0), s'). That avoids a reflect() call, stays well behaved when the light and eye are far from the normal, and gives a rounder highlight at grazing angles; matching Phong's width needs roughly s' = 4s. The final colour is ka + kd*max(dot(N,L),0) + ks*spec, each scaled by light colour. Nothing links the exponent to physical roughness, there is no Fresnel term and no normalisation, so brightness changes as the highlight narrows. Normalised variants multiply the lobe by (s+8)/(8*pi) to restore energy balance, which is the usual bridge to microfacet models. ## When to use it Choose it for prototypes, teaching, low-end mobile, retro or stylised looks and any place a designer wants a direct 'shininess' dial. Prefer [Cook-Torrance microfacet BRDF](https://texelatlas.vercel.app/t/cook-torrance-brdf.md) with [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) when assets need consistent response under many lights or image-based lighting. Prefer [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) when artists should author roughness/metalness. For toon looks start from the diffuse and specular thresholds in [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md). ## Cost cheap — A handful of dot products and one pow per light. Measured GPU Weight: 1.09× baseline (feather) — 0.0359 ms median / 0.0384 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 0.98× baseline (feather) — 0.0156 ms median (2.3× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.25× faster on A100). ## Failure modes - Highlights do not narrow with energy conservation, so shiny surfaces look too dim and rough ones too bright - No Fresnel, so grazing-angle reflections never strengthen and edges look plastic - Phong's R.V term goes to zero beyond 90 degrees and produces a visible cut-off on the lit side of the terminator - Blinn highlights are elliptical on flat planes at grazing view angles, unlike Phong's circular spot - Exponent has no physical mapping, so values cannot be reused across lighting setups or ported to PBR ## Engine support - babylonjs: builtin — `new BABYLON.StandardMaterial(...) (specularPower)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/standardMaterial.pure.ts, checked 2026-12-01) - threejs: builtin — `new THREE.MeshPhongMaterial({ shininess })` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshPhongMaterial.js, checked 2026-12-01) - unity: builtin — `URP > Shader "Universal Render Pipeline/Simple Lit"` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl, checked 2026-12-01) — URP Simple Lit shader. ## Dataflow - Inputs: normals, material-params - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender ## Presets ### Blinn-Phong lit sphere (glsl-fragment; rendered 2026-11-29) ```json { "SHININESS": 64, "KS": 0.8 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Blinn-Phong on an analytic sphere. const float SHININESS = 64.0; const float KS = 0.8; const vec3 ALBEDO = vec3(0.7, 0.2, 0.15); void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 3.0); vec3 rd = normalize(vec3(uv, -1.5)); vec3 col = vec3(0.04, 0.05, 0.08) + 0.12 * (uv.y + 0.5); float b = dot(ro, rd); float h = b * b - (dot(ro, ro) - 1.0); if (h > 0.0) { vec3 p = ro + rd * (-b - sqrt(h)); vec3 n = normalize(p); vec3 l = normalize(vec3(cos(iTime), 0.6, 0.8)); vec3 v = -rd; vec3 hv = normalize(l + v); float nl = max(dot(n, l), 0.0); float spec = pow(max(dot(n, hv), 0.0), SHININESS) * step(0.0, dot(n, l)); col = ALBEDO * (0.08 + nl) + KS * spec; } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md): Normal maps perturb N before the dot products, giving cheap surface detail under the same lighting equation. ## Sources 1. [primary] James F. Blinn (1977) Models of light reflection for computer synthesized pictures. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/965141.563893 (verified via crossref on 2026-11-29) 2. [primary] Bui Tuong Phong (1975) Illumination for computer generated pictures. Communications of the ACM. https://doi.org/10.1145/360825.360839 (verified via crossref on 2026-11-29) 3. [tutorial] Joey de Vries Advanced Lighting. learnopengl.com. https://learnopengl.com/Advanced-Lighting/Advanced-Lighting (verified via http on 2026-11-29) ## Cite this entry Texel. "Phong and Blinn-Phong shading." https://texelatlas.vercel.app/t/blinn-phong-reflection/ (accessed 2026-12-01). --- id: "block-texture-compression" title: "Block texture compression (BC7 / ASTC)" aliases: [BC7, ASTC, BCn, Block Compression, BC5, VRAM Texture Compression] domain: "performance" stage: "performance" realtime: "offline" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2012 inputs: [texture] outputs: [texture] style: "both" dynamic: "both" cost: "cheap" authority: "2014" url: "https://texelatlas.vercel.app/t/block-texture-compression/" sources_verified_at: "2026-11-29" --- # Block texture compression (BC7 / ASTC) (2014) > Fixed-rate GPU block formats such as BC7 on desktop and ASTC on mobile keep textures compressed in video memory, shrinking bandwidth and footprint at some quality loss. ## Reach for it when - texture memory is too high on the gpu - bandwidth bound from sampling big uncompressed textures - need gpu-native compressed textures for fast sampling - color banding or blockiness after compressing textures ## How it works Images are split into small blocks, 4x4 for BC7 and variable sizes from 4x4 to 12x12 for ASTC. Each block stores two or more endpoint colours, optional partition choices and per-texel weights. The GPU decodes blocks on the fly during sampling, so memory use and fetch bandwidth drop by 4x to over 10x with random access preserved. Encoders search partitions, modes and weights per block to minimise error; slower settings give better quality. Data is lossy and offline-encoded, with separate handling for normals, HDR and alpha. ## When to use it Choose BC7 for high-quality desktop colour and ASTC where mobile support is needed or flexible bitrates help. Prefer [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md) when one file must transcode to whichever format the device supports. Prefer uncompressed or lossless only for lookup tables and tiny UI. ## Cost cheap — Decoding is free in hardware; encoding is the offline cost. Measured GPU Weight: 18.14× baseline (moderate) — 0.5623 ms median / 0.5796 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 15.28× baseline (moderate) — 0.243 ms median (2.31× faster on L4). Ampere A100 scaling: 11.72× baseline (moderate) — 0.3375 ms median (1.67× faster on A100). ## Failure modes - Block artifacts and colour banding on smooth gradients - Normals suffer without a dedicated two-channel layout - Hardware support differs: ASTC absent on many desktop GPUs, BC7 absent on most mobile - Chroma bleeding at sharp colour edges within a block ## Engine support - babylonjs: builtin — `KTX2 / DDS compressed texture loaders (BCn/ASTC/ETC2 via KhronosTextureContainer2)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Misc/khronosTextureContainer2.ts, checked 2026-12-01) - godot: builtin — `Project import: Compress > Mode = VRAM Compressed (BPTC/S3TC/ETC2/ASTC); Image.compress()` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Image.xml, checked 2026-12-01) - metal: builtin — `MTLPixelFormat.bc7_rgbaUnorm (macOS) / .astc_4x4_ldr (Apple GPUs)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlpixelformat.json, checked 2026-12-01) — ASTC on Apple silicon, BC on Mac GPUs; ETC2 also listed. - threejs: builtin — `new THREE.CompressedTexture(...) with RGBA_ASTC_4x4_Format / RGBA_BPTC_Format` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) — Transcode via KTX2Loader. - unity: builtin — `Texture Import Settings > Compression / Format (BC7, ASTC)` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/texture-choose-format-by-platform.html, checked 2026-12-01) — Platform-dependent texture compression at import. - unreal: builtin — `Texture Editor > Compression > Compression Settings (TC_Default DXT1/DXT5, TC_BC7, TC_Normalmap, platform ASTC/ETC2)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/TextureCompressionSettings, checked 2026-12-01) - webgpu: builtin — `requiredFeatures: ['texture-compression-bc'] or ['texture-compression-astc']; formats bc7-rgba-unorm, astc-4x4-unorm` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — BC, ASTC and ETC2 are optional device features; availability varies by GPU. ## Dataflow - Inputs: texture - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Block Texture Compression (BC7/ASTC) — 4x4 endpoint quantization & partitions (left) vs uncompressed (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BLOCK_PX": 10, "P_PARTITIONS": 1, "P_ERROR_VIS": 0, "P_SPLIT": 0.5 } ``` ```glsl const float P_BLOCK_PX = 10.0; // P Block Size px [4.0, 22.0, 1.0] const float P_PARTITIONS = 1.0; // P Dual Partition [0.0, 1.0, 1.0] const float P_ERROR_VIS = 0.0; // P Error Heat Mode [0.0, 1.0, 0.05] const float P_SPLIT = 0.50; // P Compressed / Source [0.0, 1.0, 0.02] // High-frequency colorful test chart combining sharp diagonal color edges, smooth gradients & fine rings vec3 sourceTexture(vec2 uv, float t) { vec2 p = uv; float r = length(p - vec2(0.0, 0.02)); float a = atan(p.y - 0.02, p.x); // Smooth chromatic gradient backdrop vec3 bg = 0.5 + 0.45 * cos(vec3(0.0, 2.094, 4.188) + p.x * 2.6 + p.y * 1.9 + t * 0.35); // Sharp contrasting diagonal color bar (classic worst-case for 1-subset BC1/DXT1, solved by BC7 2-subset partitions!) float diag = p.x * 0.78 + p.y * 0.62 - 0.08 * sin(t * 0.6); vec3 stripeCol = (diag > 0.0) ? vec3(0.98, 0.34, 0.14) : vec3(0.08, 0.78, 0.88); float band = smoothstep(0.16, 0.15, abs(diag)); vec3 col = mix(bg * 0.68, stripeCol, band * 0.85); // Concentric high-contrast metallic rings float ring = smoothstep(0.024, 0.014, abs(fract(r * 6.5 - t * 0.18) - 0.5)); float inner = smoothstep(0.38, 0.36, r); vec3 ringCol = mix(vec3(0.96, 0.86, 0.24), vec3(0.86, 0.22, 0.72), 0.5 + 0.5 * sin(a * 4.0)); col = mix(col, ringCol, ring * inner * 0.92); // Fine checker patch at bottom-left to stress 4x4 block endpoint interpolation if (p.x < -0.15 && p.y < -0.12) { float chk = mod(floor(p.x * 26.0) + floor(p.y * 26.0), 2.0); col = mix(vec3(0.10, 0.14, 0.22), vec3(0.95, 0.90, 0.78), chk); } return clamp(col, 0.0, 1.0); } // Quantize a single 4x4 block subset along its principal min/max color line (4 levels = 2-bit BC index) vec3 compressSubset(vec2 blockOrigin, vec2 blockSize, vec2 texelUV, int subsetId, bool dualPart, float t) { vec3 cMin = vec3(1e5); vec3 cMax = vec3(-1e5); vec3 cSum = vec3(0.0); float count = 0.0; // Sample 4x4 texels inside the block to fit the endpoint pair (E0, E1) for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { vec2 local = (vec2(float(x), float(y)) + 0.5) * 0.25; int sid = (dualPart && (local.x + local.y > 1.0)) ? 1 : 0; if (sid != subsetId) continue; vec3 c = sourceTexture(blockOrigin + local * blockSize, t); cMin = min(cMin, c); cMax = max(cMax, c); cSum += c; count += 1.0; } } if (count < 0.5) return sourceTexture(texelUV, t); // 5-6-5 / 7-bit endpoint quantization float qSteps = dualPart ? 31.0 : 15.0; vec3 e0 = floor(cMin * qSteps + 0.5) / qSteps; vec3 e1 = floor(cMax * qSteps + 0.5) / qSteps; // Project current texel onto endpoint line segment (e0 -> e1) and quantize to 2-bit index {0, 1/3, 2/3, 1} vec3 cur = sourceTexture(texelUV, t); vec3 axis = e1 - e0; float denom = dot(axis, axis); float alpha = (denom > 1e-5) ? clamp(dot(cur - e0, axis) / denom, 0.0, 1.0) : 0.0; float idx = floor(alpha * 3.0 + 0.5) / 3.0; return mix(e0, e1, idx); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSource = screenX >= split; float blockPx = clamp(floor(P_BLOCK_PX + 0.5), 4.0, 24.0); bool dualPart = P_PARTITIONS > 0.5; float errVis = clamp(P_ERROR_VIS, 0.0, 1.0); vec3 orig = sourceTexture(uv, iTime); vec3 col = orig; if (!isSource) { // Snap to 4x4 texel block coordinates in screen space float blockWorld = (blockPx * 4.0) / max(iResolution.y, 1.0); vec2 bId = floor(uv / blockWorld); vec2 bLocal = fract(uv / blockWorld); vec2 bOrigin = bId * blockWorld; // Quantize current fragment to its 4x4 texel center vec2 texCenter = (floor(bLocal * 4.0) + 0.5) * 0.25; vec2 texUV = bOrigin + texCenter * blockWorld; int sid = (dualPart && (texCenter.x + texCenter.y > 1.0)) ? 1 : 0; vec3 decoded = compressSubset(bOrigin, vec2(blockWorld), texUV, sid, dualPart, iTime); // Optional amplified RMS compression error heatmap (shows why 2-subset BC7 beats 1-subset BC1!) float err = length(decoded - orig) * 4.2; vec3 errCol = mix(vec3(0.05, 0.14, 0.30), vec3(1.0, 0.36, 0.12), clamp(err, 0.0, 1.0)); errCol = mix(errCol, vec3(1.0, 0.96, 0.45), smoothstep(0.75, 1.4, err)); col = mix(decoded, errCol, errVis); // Crisp 4x4 block boundary overlay & diagonal partition line if dual-subset active float bEdge = smoothstep(0.035, 0.008, min(min(bLocal.x, 1.0 - bLocal.x), min(bLocal.y, 1.0 - bLocal.y))); col = mix(col, vec3(0.04, 0.06, 0.10), bEdge * 0.42); if (dualPart) { float pLine = smoothstep(0.025, 0.005, abs(bLocal.x + bLocal.y - 1.0)); col = mix(col, vec3(0.95, 0.98, 1.0), pLine * 0.18); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md) ## Combines with - [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md): Supercompressed KTX2 transcodes at load time into BC7 or ASTC for the device. ## Combination ideas - [Block-compressed tile streaming inside a hardware-filtered virtual texture cache](https://texelatlas.vercel.app/ideas/block-compressed-virtual-texture-cache/) ## Sources 1. [primary] (2014) Adaptive Scalable Texture Compression. GPU Pro 5. https://doi.org/10.1201/b16721-26 (verified via crossref on 2026-11-29) 2. [implementation] ARM-software (2015) ARM-software/astc-encoder. https://github.com/ARM-software/astc-encoder License: Apache-2.0. (verified via github on 2026-11-29) 3. [implementation] richgel999 (2021) richgel999/bc7enc_rdo. https://github.com/richgel999/bc7enc_rdo License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Block texture compression (BC7 / ASTC)." https://texelatlas.vercel.app/t/block-texture-compression/ (accessed 2026-12-01). --- id: "blue-noise-dithering" title: "Blue-noise dithering" aliases: [Dithering, Color Banding Dithering, Screen-Space Dithering] domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, cpu] year_introduced: 1993 inputs: [ldr-image, hdr-image, texture] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Ulichney, 1993" url: "https://texelatlas.vercel.app/t/blue-noise-dithering/" sources_verified_at: "2026-11-29" --- # Blue-noise dithering (Ulichney, 1993) > Dithers by comparing against a tiled blue-noise texture, whose energy sits in high frequencies, giving an even grain without the visible grid of Bayer patterns. ## Reach for it when - dithering shows a visible grid pattern - want organic grain-like dither without matrix structure - banding in gradients but ordered dither looks too regular - need stable cheap dithering that looks even ## How it works A blue-noise texture is a threshold image in which neighbouring values are anti-correlated, so any thresholded slice produces evenly spaced dots with no low-frequency clumps. It can be generated offline with the void-and-cluster algorithm, which repeatedly swaps pixels between the tightest cluster and the largest void until a rank is assigned to every pixel. At runtime it is used exactly like a Bayer matrix: sample the tiling texture at pixel coordinates, add to the quantizer input, then floor. Free tileable textures exist in many sizes and channel counts. For animation, add a golden-ratio offset per frame to create temporally decorrelated sequences. ## When to use it Choose it when you want grain-like dithering that looks organic and does not show matrix structure. Prefer [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) for a deliberately retro lattice, and [Error-diffusion dithering (Floyd-Steinberg)](https://texelatlas.vercel.app/t/error-diffusion-dithering.md) when output quality matters more than stability or parallelism. ## Cost cheap — One texture fetch and compare per pixel. Measured GPU Weight: 1.57× baseline (feather) — 0.0515 ms median / 0.0531 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.24× baseline (feather) — 0.0197 ms median (2.61× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.79× faster on A100). ## Failure modes - Texture tiling shows as repeating patches at small texture sizes - Screen-fixed grain slides over moving objects without per-frame offset - Poorly generated textures with low-frequency leaks reintroduce clumps - Texture must be sampled with nearest filtering, or thresholds blur ## Dataflow - Inputs: ldr-image, hdr-image, texture - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, cpu ## Presets ### A 1-bit vertical ramp thresholded by white noise (left) and by high-pass (blue-like) noise (right) (glsl-fragment; rendered 2026-11-29) ```json { "GAINB": 7 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float GAINB=7.0; // P float wn(vec2 c){return hash(c+17.);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec2 p=floor(fragCoord);float v=clamp(uv.y+.5,0.,1.),thr; if(!R) thr=wn(p); else{float nb=0.; for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++)if(i!=0||j!=0)nb+=wn(p+vec2(float(i),float(j))); float n=wn(p)-nb/8.;thr=1./(1.+exp(-n*GAINB));} vec3 col=vec3(v>thr?.95:.05); if(abs(uv.x)<.0015)col=vec3(.5,.5,1.); fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Lineage - extends [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) - extended by [1-bit dithered 3D rendering (Obra Dinn style)](https://texelatlas.vercel.app/t/obra-dinn-1bit-dithered-3d.md) ## Combination ideas - [1-bit rendering that meters like a camera](https://texelatlas.vercel.app/ideas/histogram-steered-dithering/) ## Sources 1. [primary] Robert A. Ulichney (1993) <title>Void-and-cluster method for dither array generation</title>. SPIE Proceedings. https://doi.org/10.1117/12.152707 (verified via crossref on 2026-11-29) 2. [tutorial] Christoph Peters Free blue noise textures. momentsingraphics.de. https://momentsingraphics.de/BlueNoise.html (verified via http on 2026-11-29) 3. [implementation] MomentsInGraphics (2017) MomentsInGraphics/BlueNoise. https://github.com/MomentsInGraphics/BlueNoise License: CC0-1.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Blue-noise dithering." https://texelatlas.vercel.app/t/blue-noise-dithering/ (accessed 2026-12-01). --- id: "blue-noise-screen-space-sampler" title: "Blue-noise error distribution sampler" aliases: [Heitz blue-noise sampler, screen-space blue noise sampling, ranking and scrambling tiles] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, unreal, unity] year_introduced: 2019 inputs: [texture] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Heitz et al., 2019" url: "https://texelatlas.vercel.app/t/blue-noise-screen-space-sampler/" sources_verified_at: "2026-11-29" --- # Blue-noise error distribution sampler (Heitz et al., 2019) > A low-discrepancy sampler whose per-pixel randomisation is optimised so the remaining Monte Carlo error across the screen looks like blue noise. At one to a few samples per pixel it is far less ugly and far easier to denoise. ## Reach for it when - one sample per pixel noise looks ugly and clumpy - denoiser struggles with white noise from ray tracing - want noise that is easy to blur away in screen space - stochastic shadows or ao look grainy at low ray counts ## How it works Sampling many pixels at low counts leaves error that depends on how sample sets are assigned. If neighbouring pixels have uncorrelated sets, the error is white noise, which has clumps and is hard to filter. The sampler picks assignments so neighbouring pixels have maximally different sets, pushing error energy into high frequencies where blur and denoising remove it easily. It works with a small fixed tile of precomputed data. Each pixel looks up a rank for each pair of dimensions and a scrambling value from a tile indexed by pixel coordinates modulo the tile size. The rank reorders the points of a Sobol sequence per pixel and the scramble randomises them with an XOR; both are optimised offline by simulated annealing so differences between neighbours of the error image are blue. At runtime this is a handful of texture or buffer reads and XORs per dimension. It is typically animated over time with golden-ratio offsets so the pattern changes each frame without losing the screen-space property, which also helps temporal accumulation. ## When to use it Choose it for real-time ray-traced or stochastic effects at one to four samples per pixel: shadows, ambient occlusion, reflections and DDGI-style noise that a denoiser or [temporal-anti-aliasing](temporal-anti-aliasing) will clean up. Prefer [owen-scrambled-sobol-sampling](owen-scrambled-sobol-sampling) for offline and high-sample-count rendering, where asymptotic convergence matters more than screen-space error. Prefer [blue-noise-dithering](blue-noise-dithering) for plain quantisation or alpha-test dithering, which uses a single blue-noise texture instead of per-dimension ranking tiles. Prefer [restir-gi](restir-gi) resampling when you want the sampler to be reused across pixels rather than just improving the noise spectrum. ## Cost cheap — A few table fetches and XORs per sample dimension; tile data is small enough to sit in a single texture. Measured GPU Weight: 18.67× baseline (moderate) — 0.6143 ms median / 0.6354 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.11× baseline (moderate) — 0.2561 ms median (2.4× faster on L4). Ampere A100 scaling: 12.12× baseline (moderate) — 0.3492 ms median (1.76× faster on A100). ## Failure modes - Tile repetition becomes visible as a pattern when the tile is small and the image is smooth - Blue-noise property degrades after reprojection or when the denoiser blurs differently across pixels - Ranking tile is optimised for a fixed number of dimensions, so exceeding it reuses correlated dimensions - Temporal offsets that are not decorrelated (a fixed shift) produce crawling dither instead of fresh noise - Gain over white noise shrinks as sample count rises and the error stops being the dominant artifact ## Engine support - blender: builtin — `Render Properties > Sampling > Advanced > Pattern = Blue-Noise` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/sampling.html, checked 2026-12-01) — Cycles blue-noise sampling pattern. - unity: builtin — `HDRP Ray Tracing / Path Tracing (GetBNDSequenceSample in RaytracingSampling.hlsl implements Heitz et al. blue-noise error distribution)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingSampling.hlsl, checked 2026-12-01) — HDRP-only ray tracing and path tracing sampler. ## Dataflow - Inputs: texture - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, cuda, unreal, unity ## Presets ### Blue-noise screen-space sampler — white noise vs high-frequency blue-noise 1-SPP shadows (glsl-fragment; rendered 2026-11-30) ```json { "P_SAMPLE_SPREAD": 1, "P_TEMPORAL_SPIN": 0.65, "P_NOISE_GAIN": 1, "P_SPLIT": 0.46 } ``` ```glsl const float P_SAMPLE_SPREAD = 1.0; // P Penumbra Spread [0.2, 2.2, 0.05] const float P_TEMPORAL_SPIN = 0.65; // P R2 Animate [0.0, 2.0, 0.05] const float P_NOISE_GAIN = 1.0; // P Noise Contrast [0.2, 1.8, 0.05] const float P_SPLIT = 0.46; // P White/Blue Split [0.0, 1.0, 0.02] // Uncorrelated white noise hash (clumpy low-frequency energy) float whiteNoise(vec2 px) { vec3 p3 = fract(vec3(px.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); } // High-frequency screen-space blue-noise approximation via Jimenez Interleaved Gradient Noise // paired with golden-ratio R2 plastic-constant temporal offset float blueNoiseIGN(vec2 px, float framePhase) { vec2 p = px + vec2(framePhase * 5.588238, framePhase * 7.123105); return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); } // Second independent blue-noise channel via rotated IGN lattice float blueNoiseIGN2(vec2 px, float framePhase) { vec2 p = px.yx + vec2(framePhase * 3.247179, framePhase * 9.414213); return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); } float mapScene(vec3 p) { float dFloor = p.y + 0.72; float dS1 = length(p - vec3(-0.38, -0.22, 0.08)) - 0.50; float dS2 = length(p - vec3(0.42, -0.34, -0.18)) - 0.38; float dS3 = length(p - vec3(0.02, 0.34, -0.58)) - 0.32; return min(min(dFloor, dS1), min(dS2, dS3)); } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy) - mapScene(p - e.xyy), mapScene(p + e.yxy) - mapScene(p - e.yxy), mapScene(p + e.yyx) - mapScene(p - e.yyx) )); } float traceHardShadow(vec3 ro, vec3 rd) { float t = 0.03; for (int i = 0; i < 24; i++) { float h = mapScene(ro + rd * t); if (h < 0.004) return 0.0; t += h; if (t > 4.5) break; } return 1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; float splitX = clamp(P_SPLIT, 0.0, 1.0); bool useBlue = (screenUV.x >= splitX); float frameIdx = floor(iTime * 12.0 * max(P_TEMPORAL_SPIN, 0.0)); vec2 qCoord = floor(fragCoord * 0.5); // 2x2 pixel blocks make noise distribution crystal clear float u1 = useBlue ? blueNoiseIGN(qCoord, frameIdx) : whiteNoise(qCoord + frameIdx * 13.7); float u2 = useBlue ? blueNoiseIGN2(qCoord, frameIdx) : whiteNoise(qCoord + vec2(41.3, 19.1) + frameIdx * 7.3); vec3 ro = vec3(0.0, 0.42, 2.55); vec3 rd = normalize(vec3(uv, -1.52)); // Soft studio backdrop vec3 col = mix(vec3(0.09, 0.11, 0.14), vec3(0.24, 0.27, 0.32), smoothstep(-0.5, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapScene(ro + rd * t); if (d < 0.002) { hit = true; break; } t += d; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Area light disk centered overhead-right; jittered by 1-SPP stochastic sample float spread = clamp(P_SAMPLE_SPREAD, 0.15, 2.5) * 0.36; float ang = u1 * 6.2831853; float rad = sqrt(max(u2, 0.0)) * spread; vec3 lBase = normalize(vec3(0.65, 0.92, 0.48)); vec3 lTan = normalize(cross(lBase, vec3(0.0, 1.0, 0.0))); vec3 lBit = cross(lBase, lTan); vec3 lDir = normalize(lBase + (cos(ang) * lTan + sin(ang) * lBit) * rad); // 1-SPP stochastic area shadow ray + 1-SPP stochastic hemisphere AO ray float sh = traceHardShadow(p + n * 0.015, lDir); vec3 nTan = normalize(abs(n.y) < 0.9 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0))); vec3 nBit = cross(n, nTan); float aoPhi = u2 * 6.2831853; float aoR = sqrt(max(u1, 0.0)); vec3 aoDir = normalize(n * sqrt(max(1.0 - aoR * aoR, 0.05)) + (cos(aoPhi) * nTan + sin(aoPhi) * nBit) * aoR); float aoVis = traceHardShadow(p + n * 0.015, aoDir); float ndl = max(dot(n, lBase), 0.0); float nGain = clamp(P_NOISE_GAIN, 0.1, 2.0); float shEff = mix(0.5, sh, clamp(nGain, 0.0, 1.0)); float aoEff = mix(0.65, aoVis, clamp(nGain * 0.75, 0.0, 1.0)); vec3 alb = (p.y < -0.70) ? vec3(0.74, 0.73, 0.71) : vec3(0.86, 0.82, 0.76); vec3 direct = alb * vec3(1.65, 1.48, 1.28) * ndl * shEff; vec3 ambient = alb * vec3(0.24, 0.30, 0.42) * (0.28 + 0.72 * aoEff); col = direct + ambient; } // Bottom strip inset: direct visualization of the raw White-Noise vs Blue-Noise mask thresholded at 0.5 if (screenUV.y < 0.19) { float maskVal = step(0.5, u1); vec3 mCol = useBlue ? mix(vec3(0.05, 0.11, 0.18), vec3(0.45, 0.85, 1.0), maskVal) : mix(vec3(0.14, 0.08, 0.08), vec3(0.96, 0.62, 0.45), maskVal); col = mix(mCol, col, smoothstep(0.178, 0.19, screenUV.y)); if (abs(screenUV.y - 0.19) < 0.004) col = vec3(0.92, 0.94, 0.98); } // Crisp vertical divider line between White Noise (left) and Blue Noise (right) if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(0.35, 0.88, 1.0); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md): One ray per pixel with blue-noise directions gives AO whose residual noise a small spatial filter removes. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Animated blue-noise offsets give each frame a fresh sample set that history accumulation integrates. - [ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting](https://texelatlas.vercel.app/t/restir-di.md): Initial candidates for resampling are drawn with the sampler so the unresampled error already has a good spectrum. ## Sources 1. [primary] Eric Heitz, Laurent Belcour, V. Ostromoukhov, David Coeurjolly, Jean-Claude Iehl (2019) A low-discrepancy sampler that distributes monte carlo errors as a blue noise in screen space. ACM SIGGRAPH 2019 Talks. https://doi.org/10.1145/3306307.3328191 (verified via crossref on 2026-11-29) 2. [implementation] Calinou (2019) Calinou/free-blue-noise-textures. https://github.com/Calinou/free-blue-noise-textures License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Blue-noise error distribution sampler." https://texelatlas.vercel.app/t/blue-noise-screen-space-sampler/ (accessed 2026-12-01). --- id: "boids" title: "Boids flocking" domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity, unreal, godot] year_introduced: 1987 inputs: [particles] outputs: [particles, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Reynolds, 1987" url: "https://texelatlas.vercel.app/t/boids/" sources_verified_at: "2026-11-29" --- # Boids flocking (Reynolds, 1987) > Emergent flocking from three local steering rules per agent: separation, alignment and cohesion, computed from neighbours within a view radius. ## Reach for it when - want birds or fish to move together as a believable group - crowd of agents needs natural swarming motion - individual agents collide or scatter instead of flocking - emergent group movement from simple local rules - cheap schooling behaviour for ambient creatures ## How it works Each agent looks at neighbours within a radius and field of view. Separation steers away from nearby neighbours, alignment steers toward their average heading, and cohesion steers toward their centre. The three steering vectors are weighted, summed and clamped to a maximum acceleration, then integrated into velocity and position with a speed limit. Obstacle avoidance, goal seeking and predator flee are extra steering terms. Neighbour lookups use a spatial hash or grid; on the GPU the algorithm maps to one thread per boid with a sorted-cell neighbour search. Orientation is set from velocity with a banking term for believable flight. ## When to use it Choose it for birds, fish, swarms and crowds where plausible group motion matters more than individual intent. Prefer [Physarum agent transport networks](https://texelatlas.vercel.app/t/physarum-transport-networks.md) when agents should leave trails and form networks, [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md) for physically linked groups, and navmesh/path planning libraries when individuals need to reach distinct goals. ## Cost cheap — Cheap with spatial hashing; naive O(n^2) breaks past a few thousand agents. Measured GPU Weight: 354.76× baseline (extreme) — 11.6716 ms median / 11.798 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 322.14× baseline (extreme) — 5.122 ms median (2.28× faster on L4). Ampere A100 scaling: 246.54× baseline (extreme) — 7.1004 ms median (1.64× faster on A100). ## Failure modes - O(n^2) neighbour search unless a grid or hash is used - Flocks split or collapse into a ball with badly balanced weights - Jitter and oscillation when separation and cohesion fight at fixed radius - Agents pass through concave obstacles unless explicit avoidance is added ## Engine support - blender: builtin — `Particle Properties > Physics > Boids` (evidence: https://docs.blender.org/manual/en/5.2/physics/particles/emitter/physics/boids.html, checked 2026-12-01) - threejs: official — `examples/webgpu_compute_birds.html` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/webgpu_compute_birds.html, checked 2026-12-01) — Official GPU flocking example; not a library. - unreal: builtin — `Niagara GPU neighbor-grid & flocking particle modules` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-niagara-effects-for-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: particles - Outputs: particles, animation - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity, unreal, godot ## Presets ### Boids flocking — separation, alignment & cohesion murmuration with wake trails (glsl-fragment; rendered 2026-11-30) ```json { "P_SPEED": 1, "P_COHESION": 0.85, "P_SEPARATION": 0.65, "P_TRAIL_LENGTH": 0.75 } ``` ```glsl const float P_SPEED = 1.0; // P Speed [0.0, 2.5, 0.05] const float P_COHESION = 0.85; // P Cohesion [0.1, 2.0, 0.05] const float P_SEPARATION = 0.65; // P Separation [0.1, 2.0, 0.05] const float P_TRAIL_LENGTH = 0.75; // P Trail Length [0.0, 1.8, 0.05] vec2 hash21(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // Compute smooth murmuration trajectory with cohesive flock ribbon + local separation offset vec2 boidPos(int idx, float t, vec2 attr) { float fi = float(idx); vec2 h = hash21(fi * 17.3 + 3.1); float flockId = step(0.5, fract(fi * 0.5)); float phase = t * (0.65 + 0.12 * h.x) + fi * 0.24 + flockId * 3.14159; // Ribbon guide path driven by cohesion toward moving attractor float coh = clamp(P_COHESION, 0.1, 2.2); float spread = mix(0.42, 0.11, clamp((coh - 0.1) / 1.8, 0.0, 1.0)); vec2 guide = vec2( 0.46 * sin(phase * 0.78 + flockId * 1.4) + 0.18 * cos(phase * 1.55), 0.34 * cos(phase * 0.92) + 0.16 * sin(phase * 1.38 + flockId) ); guide = mix(guide, attr * 0.75, 0.25 * clamp(coh, 0.0, 1.5)); // Separation micro-orbit around ribbon center float sep = max(P_SEPARATION, 0.05) * spread; float ang = fi * 2.39996 + t * (1.2 + 0.6 * h.y); vec2 offset = vec2(cos(ang), sin(ang)) * sep * (0.45 + 0.55 * h.y); offset += 0.05 * sep * vec2(sin(t * 2.1 + fi), cos(t * 1.9 - fi * 1.3)); vec2 p = guide + offset; // Soft obstacle avoidance around center beacon vec2 dObs = p - vec2(0.0, 0.0); float distObs = length(dObs) + 1e-4; float avoid = smoothstep(0.24, 0.08, distObs); p += (dObs / distObs) * avoid * 0.14; return p; } float sdDart(vec2 p, vec2 dir, float size) { vec2 n = normalize(dir + vec2(1e-5, 0.0)); vec2 perp = vec2(-n.y, n.x); vec2 q = vec2(dot(p, n), dot(p, perp)) / size; // Sleek swept-wing boid silhouette float body = max(abs(q.y) - mix(0.42, 0.02, clamp((q.x + 0.65) / 1.65, 0.0, 1.0)), abs(q.x - 0.15) - 0.85); float notch = -(q.x + 0.45 - abs(q.y) * 0.85); return max(body, -notch) * size; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / iResolution.y; float t = iTime * max(P_SPEED, 0.0); vec2 attr = vec2(0.28 * cos(t * 0.45), 0.22 * sin(t * 0.62)); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { attr = (iMouse.xy - 0.5 * iResolution.xy) / iResolution.y; } // Deep twilight radar backdrop with subtle spatial-hash grid vec3 bg = mix(vec3(0.025, 0.045, 0.085), vec3(0.06, 0.11, 0.19), smoothstep(-0.55, 0.55, uv.y)); vec2 g = abs(fract(uv * 8.0 - 0.5) - 0.5) / (8.0 * px); float gridLine = smoothstep(1.4, 0.0, min(g.x, g.y)); bg += vec3(0.04, 0.09, 0.14) * gridLine * 0.32; // Obstacle beacon at origin float rObs = length(uv); bg += vec3(0.16, 0.24, 0.34) * smoothstep(0.012, 0.0, abs(rObs - 0.13)) * 0.45; bg += vec3(0.05, 0.09, 0.15) * smoothstep(0.13, 0.0, rObs); vec3 col = bg; float trailLen = max(P_TRAIL_LENGTH, 0.0); for (int i = 0; i < 32; i++) { vec2 p0 = boidPos(i, t, attr); vec2 pPrev = boidPos(i, t - 0.04, attr); vec2 vel = p0 - pPrev; float speed = length(vel) + 1e-4; vec2 dir = vel / speed; float flockId = step(0.5, fract(float(i) * 0.5)); vec3 boidTint = mix(vec3(0.32, 0.85, 1.0), vec3(1.0, 0.64, 0.28), flockId); // Cohesion/alignment wake trail (4 trail segments) if (trailLen > 0.01) { vec2 a = p0; for (int s = 1; s <= 4; s++) { float fs = float(s); vec2 b = boidPos(i, t - fs * 0.055 * trailLen, attr); vec2 pa = uv - a, ba = b - a; float h = clamp(dot(pa, ba) / (dot(ba, ba) + 1e-5), 0.0, 1.0); float dSeg = length(pa - ba * h); float fade = (1.0 - fs * 0.22); col += boidTint * exp(-dSeg * 115.0) * 0.18 * fade * min(trailLen, 1.2); a = b; } } // Leader perception & separation radius rings for first two agents if (i < 2) { float dRing = length(uv - p0); float perceive = smoothstep(2.0 * px, 0.0, abs(dRing - 0.12)); float sepRing = smoothstep(2.0 * px, 0.0, abs(dRing - 0.048 * max(P_SEPARATION, 0.2))); col += boidTint * perceive * 0.28; col += vec3(1.0, 0.35, 0.35) * sepRing * 0.25; } // Crisp anti-aliased dart silhouette + subtle glow float d = sdDart(uv - p0, dir, 0.024); float mask = smoothstep(1.5 * px, -1.5 * px, d); float glow = exp(-max(d, 0.0) * 85.0) * 0.26; col += boidTint * glow; col = mix(col, mix(boidTint, vec3(1.0), 0.45), mask); } col *= 1.0 - 0.25 * dot(uv, uv); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combination ideas - [Brush strokes that flock](https://texelatlas.vercel.app/ideas/flocking-brush-strokes/) ## Sources 1. [primary] Craig W. Reynolds (1987) Flocks, herds and schools: A distributed behavioral model. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/37402.37406 (verified via crossref on 2026-11-29) 2. [tutorial] Craig Reynolds Boids (Flocks, Herds, and Schools: a Distributed Behavioral Model). red3d.com. http://www.red3d.com/cwr/boids (verified via http on 2026-11-29) ## Cite this entry Texel. "Boids flocking." https://texelatlas.vercel.app/t/boids/ (accessed 2026-12-01). --- id: "bsp-dungeon-generation" title: "BSP Dungeon Generation" aliases: [binary space partition dungeon, room-and-corridor generation] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [cpu, python, unity, unreal, godot] year_introduced: 1998 outputs: [layout, graph] style: "stylized" dynamic: "static" cost: "cheap" authority: "RogueBasin" url: "https://texelatlas.vercel.app/t/bsp-dungeon-generation/" sources_verified_at: "2026-11-29" --- # BSP Dungeon Generation (RogueBasin) > Recursively split a rectangle into smaller rectangles, place a room in each leaf and connect sibling subtrees with corridors, which gives connected room-and-corridor maps with no overlap. ## Reach for it when - generate roguelike dungeon rooms that never overlap - need random room layouts connected by corridors - procedurally partition a map into rooms - want a simple dungeon generator with guaranteed connectivity ## How it works Start with the full map rectangle as the root. Recursively split a node horizontally or vertically (biased by aspect ratio) at a random ratio until the leaves reach a minimum size. In each leaf, carve a room with random size and offset that stays inside the leaf with a margin. Walk back up the tree: for each internal node, connect a room from the left subtree to one in the right subtree with an L- or Z-shaped corridor. Since every sibling pair is joined, the whole dungeon is connected, and the tree gives a natural hierarchy for placing keys, stairs and boss rooms. Extra loops can be added by connecting random non-sibling rooms. ## When to use it Choose it for roguelikes, level blockout and room layouts where guaranteed connectivity and no overlap are required. Prefer [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) when you want an example-driven look with local tile adjacency, [MarkovJunior (Rewrite-Rule Generation)](https://texelatlas.vercel.app/t/markov-junior-rewrite-rules.md) for organic cave or maze growth, and [MAP-Elites (Quality-Diversity Search)](https://texelatlas.vercel.app/t/map-elites.md) to explore many parameter settings along descriptors like room count or loops. ## Cost cheap — Linear in number of leaves; microseconds to milliseconds. Measured GPU Weight: 7.96× baseline (moderate) — 0.2619 ms median / 0.2686 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.97× baseline (moderate) — 0.1108 ms median (2.36× faster on L4). Ampere A100 scaling: 5.1× baseline (light) — 0.147 ms median (1.78× faster on A100). ## Failure modes - Boxy, grid-aligned look with rooms resembling each other - Pure tree connectivity makes dead-end rooms with no loops, so navigation is linear - Corridors can cross unrelated rooms unless routed with collision checks - Split ratios near 0 or 1 create tiny leaves that cannot fit a room, leaving sparse regions ## Dataflow - Inputs: — - Outputs: layout, graph - Platforms: cpu, python, unity, unreal, godot ## Presets ### BSP dungeon plate: recursive splits, one room per leaf, L-shaped corridors between siblings (glsl-fragment; rendered 2026-11-29) ```json { "DEPTH": 4, "SEED": 3, "CORRIDOR_W": 0.009 } ``` ```glsl // BSP dungeon: recursive rectangle split, one room per leaf, corridors join sibling subtrees. const int DEPTH = 4; const float SEED = 3.0; const float CORRIDOR_W = 0.009; float h(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7)) + SEED) * 43758.5453); } void splitR(vec2 lo, vec2 hi, int i, out bool v, out float c) { vec2 s = hi - lo; v = s.x > s.y; float r = 0.4 + 0.2 * h(lo * 7.0 + float(i)); c = v ? lo.x + s.x * r : lo.y + s.y * r; } vec2 leafC(vec2 lo, vec2 hi, int i) { for (int k = 0; k < DEPTH; k++) { if (k < i) continue; bool v; float c; splitR(lo, hi, k, v, c); if (v) hi.x = c; else hi.y = c; } return 0.5 * (lo + hi); } float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 lo = vec2(0.03), hi = vec2(0.97); float cor = 1e9, split = 1e9; for (int i = 0; i < DEPTH; i++) { bool v; float c; splitR(lo, hi, i, v, c); vec2 loA = lo, hiA = hi, loB = lo, hiB = hi; if (v) { hiA.x = c; loB.x = c; } else { hiA.y = c; loB.y = c; } vec2 a = leafC(loA, hiA, i + 1), b = leafC(loB, hiB, i + 1); vec2 m = vec2(b.x, a.y); cor = min(cor, min(segd(uv, a, m), segd(uv, m, b))); split = min(split, v ? abs(uv.x - c) : abs(uv.y - c)); bool up = v ? uv.x > c : uv.y > c; if (up) { lo = loB; hi = hiB; } else { lo = loA; hi = hiA; } } vec3 col = vec3(0.07, 0.08, 0.11) + 0.05 * h(floor(lo * 40.0)); vec2 ctr = 0.5 * (lo + hi), hs = (hi - lo) * (0.28 + 0.14 * h(lo * 3.0 + 1.0)); vec2 q = abs(uv - ctr) - hs; float room = max(q.x, q.y); vec3 rc = mix(vec3(0.75, 0.55, 0.30), vec3(0.45, 0.62, 0.70), h(lo * 5.0)); col = mix(col, vec3(0.35, 0.37, 0.42), smoothstep(0.004, 0.0, split - 0.002) * 0.6); col = mix(col, vec3(0.55, 0.50, 0.42), smoothstep(CORRIDOR_W, CORRIDOR_W - 0.003, cor)); col = mix(col, rc * (0.85 + 0.15 * sin(uv.x * 200.0) * sin(uv.y * 200.0)), smoothstep(0.003, -0.003, room)); col = mix(col, vec3(0.1, 0.08, 0.06), smoothstep(0.004, 0.0, abs(room)) * 0.9); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] RogueBasin Basic BSP Dungeon generation. roguebasin.com. https://www.roguebasin.com/index.php/Basic_BSP_Dungeon_generation (verified via http on 2026-11-29) ## Cite this entry Texel. "BSP Dungeon Generation." https://texelatlas.vercel.app/t/bsp-dungeon-generation/ (accessed 2026-12-01). --- id: "cascaded-shadow-maps" title: "Cascaded Shadow Maps" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2006 inputs: [mesh, depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Zhang et al., 2006" url: "https://texelatlas.vercel.app/t/cascaded-shadow-maps/" sources_verified_at: "2026-11-29" --- # Cascaded Shadow Maps (Zhang et al., 2006) > Splits the camera frustum into depth slices and gives each slice its own shadow map, so near surfaces get high texel density without exploding total resolution. ## Reach for it when - shadows look blocky or pixelated far from the camera - one shadow map can't cover a large outdoor scene - sun shadows lose resolution in big open worlds - near shadows blurry while the view distance is huge ## How it works The view frustum is divided along depth into typically three to five cascades, with split planes chosen logarithmically, uniformly or by a blend of both (practical split scheme). For each slice an orthographic light-space projection is fitted around that sub-frustum and rendered into one layer of an array texture or atlas. At shading time the fragment's view depth selects a cascade, and the result is blended across a transition band to hide seams. Stabilisation snaps the projection to texel increments so shadows do not shimmer as the camera rotates, and tight depth-range fitting or sample-distribution analysis (SDSM) shrinks each map further. ## When to use it Choose it for sun or moon light in open scenes with a long view distance. Prefer [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md) when you need uniform sharp detail across the whole view with massive geometry, [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) with a single map for small enclosed scenes, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) if hardware ray tracing replaces the sun map entirely. ## Cost medium — Each cascade re-renders casters, so draw cost is roughly cascade count times the caster pass, mitigated by culling per cascade and updating far cascades less often. Measured GPU Weight: 65.4× baseline (extreme) — 2.1515 ms median / 2.211 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 64.86× baseline (extreme) — 1.0312 ms median (2.09× faster on L4). Ampere A100 scaling: 41.89× baseline (heavy) — 1.2063 ms median (1.78× faster on A100). ## Failure modes - Visible seams or resolution jumps at cascade borders - Shadow swimming and shimmering when the fit is not stabilised - Wasted resolution in the nearest cascade for oblique light directions - Peter-panning near the camera from large biases chosen for far cascades ## Engine support - babylonjs: builtin — `new BABYLON.CascadedShadowGenerator(1024, directionalLight); csm.numCascades = 4` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Shadows/cascadedShadowGenerator.pure.ts, checked 2026-12-01) — DirectionalLight only. - godot: builtin — `DirectionalLight3D.directional_shadow_mode = DirectionalLight3D.SHADOW_PARALLEL_4_SPLITS` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/DirectionalLight3D.xml, checked 2026-12-01) - threejs: official — `import { CSM } from 'three/addons/csm/CSM.js' (WebGPU: CSMShadowNode)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/csm/CSM.js, checked 2026-12-01) - unity: builtin — `URP Asset > Shadows > Cascade Count; HDRP Volume > Shadows > Cascade Count` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Shadows-in-HDRP.md, checked 2026-12-01) — Directional light cascades in URP and HDRP. - unreal: builtin — `Directional Light > Cascaded Shadow Maps category (Dynamic Shadow Distance, Num Dynamic Shadow Cascades)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/directional-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### 4-cascade Practical Split Scheme shadows — quantized cascade texel footprints and PCF (glsl-fragment; rendered 2026-11-30) ```json { "SPLIT_LAMBDA": 0.65, "PCF_RADIUS": 1.25, "CASCADE_TINT": 0.38, "SUN_ANGLE": 0.72 } ``` ```glsl const float SPLIT_LAMBDA = 0.65; // P const float PCF_RADIUS = 1.25; // P const float CASCADE_TINT = 0.38; // P const float SUN_ANGLE = 0.72; // P 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); } float mapCasters(vec3 p) { // Receding rows of architectural monoliths and lintel arches vec3 q = p; q.z = mod(q.z + 1.8, 3.6) - 1.8; float pL = sdBox(vec3(p.x + 1.55, p.y - 1.05, q.z), vec3(0.32, 1.05, 0.32)); float pR = sdBox(vec3(p.x - 1.55, p.y - 1.05, q.z), vec3(0.32, 1.05, 0.32)); float arch = sdBox(vec3(p.x, p.y - 2.05, q.z), vec3(1.88, 0.22, 0.28)); // Center obelisk row with varying heights float id = floor((p.z + 1.8) / 3.6); float h = 0.55 + 0.35 * sin(id * 1.9); float ob = sdBox(vec3(p.x - 0.35 * sin(id * 2.3), p.y - h, q.z - 0.8), vec3(0.22, h, 0.22)); return min(min(pL, pR), min(arch, ob)); } float mapScene(vec3 p) { return min(p.y, mapCasters(p)); } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.004, 0.0); return normalize(vec3( mapScene(p + e.xyy) - mapScene(p - e.xyy), mapScene(p + e.yxy) - mapScene(p - e.yxy), mapScene(p + e.yyx) - mapScene(p - e.yyx) )); } // Shadow test snapped to cascade light-space texel grid float traceCaster(vec3 ro, vec3 rd) { float t = 0.04; for (int i = 0; i < 28; i++) { float d = mapCasters(ro + rd * t); if (d < 0.006) return 0.0; t += max(d, 0.04); if (t > 14.0) break; } return 1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 2.35, 3.2); vec3 rd = normalize(vec3(uv.x, uv.y - 0.24, -1.25)); float sunAz = SUN_ANGLE + 0.35 * sin(iTime * 0.4); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { sunAz = (iMouse.x / iResolution.x) * 2.4 - 0.5; } vec3 sunDir = normalize(vec3(cos(sunAz), 0.72, sin(sunAz) * 0.65)); vec3 lRight = normalize(cross(sunDir, vec3(0.0, 1.0, 0.0))); vec3 lUp = cross(lRight, sunDir); float t = 0.1; bool hit = false; for (int i = 0; i < 72; i++) { float d = mapScene(ro + rd * t); if (d < 0.004) { hit = true; break; } t += d; if (t > 38.0) break; } vec3 sky = mix(vec3(0.68, 0.78, 0.90), vec3(0.18, 0.36, 0.68), clamp(uv.y + 0.35, 0.0, 1.0)); vec3 col = sky; if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Practical split scheme (Zhang et al. 2006) across 4 cascades in [zNear, zFar] float zNear = 1.2, zFar = 34.0; float lam = clamp(SPLIT_LAMBDA, 0.0, 1.0); float s1 = mix(zNear + (zFar - zNear) * 0.25, zNear * pow(zFar / zNear, 0.25), lam); float s2 = mix(zNear + (zFar - zNear) * 0.50, zNear * pow(zFar / zNear, 0.50), lam); float s3 = mix(zNear + (zFar - zNear) * 0.75, zNear * pow(zFar / zNear, 0.75), lam); float viewZ = -dot(p - ro, vec3(0.0, 0.0, -1.0)); int casc = (viewZ < s1) ? 0 : (viewZ < s2) ? 1 : (viewZ < s3) ? 2 : 3; float texel = (casc == 0) ? 0.045 : (casc == 1) ? 0.11 : (casc == 2) ? 0.24 : 0.48; vec3 cTint = (casc == 0) ? vec3(0.28, 0.92, 0.58) : (casc == 1) ? vec3(0.32, 0.72, 1.0) : (casc == 2) ? vec3(1.0, 0.78, 0.28) : vec3(0.98, 0.42, 0.38); // Quantize light-space coordinates to cascade texel size + 4-tap PCF vec3 pOff = p + n * (0.015 + texel * 0.25); vec2 luv = vec2(dot(pOff, lRight), dot(pOff, lUp)); vec2 qBase = (floor(luv / texel) + 0.5) * texel; float pcfR = max(PCF_RADIUS, 0.0) * texel; float vis = 0.0; vec2 offs[4]; offs[0] = vec2(-0.5, -0.5); offs[1] = vec2(0.5, -0.5); offs[2] = vec2(-0.5, 0.5); offs[3] = vec2(0.5, 0.5); for (int k = 0; k < 4; k++) { vec2 tap = qBase + offs[k] * pcfR; vec3 sp = pOff + lRight * (tap.x - luv.x) + lUp * (tap.y - luv.y); vis += traceCaster(sp, sunDir); } vis *= 0.25; // Subtle border line at exact cascade split planes float dSplit = min(min(abs(viewZ - s1), abs(viewZ - s2)), abs(viewZ - s3)); float splitLine = smoothstep(0.14, 0.02, dSplit) * clamp(CASCADE_TINT, 0.0, 1.0); vec2 tile = floor(p.xz * 1.25); float chk = mod(tile.x + tile.y, 2.0); vec3 baseAlb = (p.y < 0.01) ? mix(vec3(0.42, 0.44, 0.46), vec3(0.62, 0.63, 0.64), chk) : vec3(0.74, 0.71, 0.67); vec3 alb = mix(baseAlb, baseAlb * cTint * 1.35, clamp(CASCADE_TINT, 0.0, 1.0)); float nl = max(dot(n, sunDir), 0.0); vec3 lit = alb * (vec3(0.16, 0.22, 0.34) + vec3(1.55, 1.42, 1.22) * nl * vis); lit = mix(lit, vec3(1.0), splitLine * 0.65); col = mix(lit, sky, 1.0 - exp(-0.022 * t)); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) - extended by [Sample Distribution Shadow Maps (SDSM)](https://texelatlas.vercel.app/t/sample-distribution-shadow-maps.md) ## Sources 1. [primary] Fan Zhang, Hanqiu Sun, Leilei Xu, Lee Kit Lun (2006) Parallel-split shadow maps for large-scale virtual environments. Proceedings of the 2006 ACM international conference on Virtual reality continuum and its applications. https://doi.org/10.1145/1128923.1128975 (verified via crossref on 2026-11-29) 2. [tutorial] Rouslan Dimitrov Cascaded Shadow Maps. developer.download.nvidia.com. https://developer.download.nvidia.com/SDK/10.5/opengl/src/cascaded_shadow_maps/doc/cascaded_shadow_maps.pdf (verified via http on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Cascaded Shadow Maps." https://texelatlas.vercel.app/t/cascaded-shadow-maps/ (accessed 2026-12-01). --- id: "catmull-clark-subdivision" title: "Catmull-Clark Subdivision" aliases: [CC subdivision, subdiv] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, webgpu, webgl2, desktop-gpu, blender, unity, unreal] year_introduced: 1978 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "both" cost: "medium" authority: "Catmull & Clark, 1978" url: "https://texelatlas.vercel.app/t/catmull-clark-subdivision/" sources_verified_at: "2026-11-29" --- # Catmull-Clark Subdivision (Catmull & Clark, 1978) > Refines a quad-dominant control cage by inserting face, edge and vertex points each level, converging to a bicubic B-spline surface almost everywhere. The standard smooth-surface representation in film and modelling tools. ## Reach for it when - low-poly cage should become a smooth surface - character model looks faceted and blocky - need smooth limit surface from quad modelling - want to sculpt with a coarse mesh and get a smooth result - hard-surface model needs smoothing without losing edge flow ## How it works Each step adds a point at every face centroid and a point on every edge (average of the two end points and the two adjacent face points), then moves each original vertex using a weighted blend of its old position, the average of adjacent face points and the average of adjacent edge midpoints, with weights depending on valence. Every face is replaced by quads, so after the first step the mesh is all quads. Regular regions (valence 4) become uniform bicubic B-spline patches; extraordinary vertices remain, with C1 continuity only. Production systems avoid explicit refinement: they evaluate patches directly with feature-adaptive subdivision, isolating extraordinary vertices over a few levels and drawing B-spline patches via tessellation hardware. ## When to use it Choose it for authored characters and hard-surface models where a coarse cage drives a smooth limit surface and you want subdivision-friendly edge flow. Prefer [Loop Subdivision](https://texelatlas.vercel.app/t/loop-subdivision.md) for pure triangle meshes, [Semi-Sharp Creases](https://texelatlas.vercel.app/t/semi-sharp-creases.md) as an add-on when only some edges must stay crisp, and [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md) plus normal maps when you need a game-ready low-poly rather than a smooth limit. ## Cost medium — Cost grows 4x in faces per level. Real-time engines evaluate the limit surface in tessellation or compute with adaptive patch counts. Measured GPU Weight: 35.64× baseline (heavy) — 1.1191 ms median / 1.1678 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 37.14× baseline (heavy) — 0.5868 ms median (1.91× faster on L4). Ampere A100 scaling: 22.73× baseline (heavy) — 0.6547 ms median (1.71× faster on A100). ## Failure modes - Pinching and curvature spikes at extraordinary vertices, particularly valence 3 and 5 with poor edge flow - Shrinkage: the limit surface sits inside the cage, so tight features need extra loops - Non-quad inputs produce triangles that make extraordinary points on the first step - UV seams need dedicated face-varying rules or texture stretching and cracks appear on boundaries ## Engine support - blender: builtin — `Add Modifier > Generate > Subdivision Surface > Catmull-Clark` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/generate/subdivision_surface.html, checked 2026-12-01) — OpenSubdiv backend. - unreal: official — `Geometry Script plugin: Apply PolyGroup Catmull Clark Subd` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/geometry-scripting-reference-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, webgpu, webgl2, desktop-gpu, blender, unity, unreal ## Presets ### Catmull-Clark subdivision — coarse quad control cage morphing into C2 limit surface with zebra stripes (glsl-fragment; rendered 2026-11-30) ```json { "P_SUBDIV_LEVEL": 2.2, "P_CAGE_WIRE": 0.85, "P_ZEBRA_STRIPE": 0.65, "P_ROT_SPEED": 1 } ``` ```glsl const float P_SUBDIV_LEVEL = 2.2; // P Subdiv Level [0.0, 3.0, 0.05] const float P_CAGE_WIRE = 0.85; // P Control Cage [0.0, 1.5, 0.05] const float P_ZEBRA_STRIPE = 0.65; // P Curvature Zebra [0.0, 1.0, 0.02] const float P_ROT_SPEED = 1.0; // P Spin Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } // Smooth minimum (polynomial smin) modeling Catmull-Clark B-spline corner & crease smoothing float smin(float a, float b, float k) { if (k <= 1e-4) return min(a, b); float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // 3-axis quad cross control polyhedron (18-quad genus-0 cage) -> C2 limit surface as subdiv increases float mapSubdiv(vec3 p, float level, float spin) { vec3 q = p; q.xz = rot2(spin * 0.42) * q.xz; q.yz = rot2(0.38 + 0.12 * sin(spin * 0.5)) * q.yz; float tSmooth = clamp(level / 3.0, 0.0, 1.0); // Catmull-Clark shrinkage + bevel radius converge exponentially (1 - 2^-level) toward limit surface float bevel = 0.012 + 0.24 * (1.0 - exp(-level * 1.15)); float shrink = 1.0 - 0.14 * tSmooth; float kBlend = 0.01 + 0.28 * (1.0 - exp(-level * 1.1)); float dX = sdBox(q, vec3(0.86 * shrink, 0.30, 0.30) - vec3(bevel)) - bevel; float dY = sdBox(q, vec3(0.30, 0.86 * shrink, 0.30) - vec3(bevel)) - bevel; float dZ = sdBox(q, vec3(0.30, 0.30, 0.86 * shrink) - vec3(bevel)) - bevel; return smin(smin(dX, dY, kBlend), dZ, kBlend) * 0.88; } // Distance to edges of the unsubdivided Level-0 quad control cage (wireframe hull) float mapControlCage(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.42) * q.xz; q.yz = rot2(0.38 + 0.12 * sin(spin * 0.5)) * q.yz; float dX = sdBox(q, vec3(0.86, 0.30, 0.30)); float dY = sdBox(q, vec3(0.30, 0.86, 0.30)); float dZ = sdBox(q, vec3(0.30, 0.30, 0.86)); float dUnion = min(dX, min(dY, dZ)); // Extract sharp outer cage edges where two coordinate planes of a box meet vec3 a = abs(q); float eX = min(max(abs(a.y - 0.30), abs(a.z - 0.30)), max(abs(a.x - 0.86), min(abs(a.y - 0.30), abs(a.z - 0.30)))); float eY = min(max(abs(a.x - 0.30), abs(a.z - 0.30)), max(abs(a.y - 0.86), min(abs(a.x - 0.30), abs(a.z - 0.30)))); float eZ = min(max(abs(a.x - 0.30), abs(a.y - 0.30)), max(abs(a.z - 0.86), min(abs(a.x - 0.30), abs(a.y - 0.30)))); float wire = min(eX, min(eY, eZ)); return max(abs(dUnion) - 0.014, wire - 0.011); } vec3 calcNormal(vec3 p, float level, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSubdiv(p + e.xyy, level, spin) - mapSubdiv(p - e.xyy, level, spin), mapSubdiv(p + e.yxy, level, spin) - mapSubdiv(p - e.yxy, level, spin), mapSubdiv(p + e.yyx, level, spin) - mapSubdiv(p - e.yyx, level, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float spin = iTime * max(P_ROT_SPEED, 0.0); float level = clamp(P_SUBDIV_LEVEL, 0.0, 3.0); float cageVis = clamp(P_CAGE_WIRE, 0.0, 1.6); float zebraAmt = clamp(P_ZEBRA_STRIPE, 0.0, 1.0); vec3 ro = vec3(0.0, 0.12, 2.55); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.032, 0.042, 0.068), vec3(0.095, 0.118, 0.170), smoothstep(-0.55, 0.55, uv.y)); vec2 bgG = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.045) * smoothstep(0.03, 0.0, min(bgG.x, bgG.y)); // Raymarch subdivided Catmull-Clark surface float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSubdiv(ro + rd * t, level, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, level, spin); // Object-space coordinates for subdivided quad grid overlay (density doubles at each subdivision level!) vec3 objP = p; objP.xz = rot2(spin * 0.42) * objP.xz; objP.yz = rot2(0.38 + 0.12 * sin(spin * 0.5)) * objP.yz; float quadFreq = 3.33 * pow(2.0, floor(level + 0.35)); vec3 gf = abs(fract(objP * quadFreq - 0.5) - 0.5); // Project out the coordinate most aligned with normal to get clean surface quad-loop wireframes vec3 an = abs(n); float qEdge = (an.x > an.y && an.x > an.z) ? min(gf.y, gf.z) : ((an.y > an.z) ? min(gf.x, gf.z) : min(gf.x, gf.y)); float quadLine = smoothstep(0.055, 0.012, qEdge); // Reflection zebra stripes (classic CAD C2 continuity diagnostic!) vec3 rDir = reflect(rd, n); float zebra = smoothstep(-0.12, 0.12, sin(rDir.y * 22.0 + rDir.x * 8.0)); vec3 l1 = normalize(vec3(0.62, 0.84, 0.58)); vec3 l2 = normalize(vec3(-0.72, -0.25, 0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 48.0) * 0.58; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 2.8) * 0.34; vec3 clayAlb = vec3(0.24, 0.62, 0.86); vec3 zebraAlb = mix(vec3(0.09, 0.12, 0.18), vec3(0.94, 0.96, 0.99), zebra); vec3 alb = mix(clayAlb, zebraAlb, zebraAmt * 0.72); col = alb * (0.26 + 0.84 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.78, 1.0) * rim; col = mix(col, vec3(0.10, 0.92, 0.82), quadLine * 0.42); } // Transparently overlay the coarse Level-0 quad control cage wireframe in bright amber if (cageVis > 0.01) { float tc = 0.2; for (int i = 0; i < 48; i++) { float dc = mapControlCage(ro + rd * tc, spin); if (dc < 0.004) { float occFade = (!hit || tc < t + 0.04) ? 1.0 : 0.32; col = mix(col, vec3(1.0, 0.74, 0.22), 0.82 * occFade * min(cageVis, 1.2)); break; } tc += max(dc * 0.75, 0.012); if (tc > 6.5) break; } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [Semi-Sharp Creases](https://texelatlas.vercel.app/t/semi-sharp-creases.md) ## Combines with - [Semi-Sharp Creases](https://texelatlas.vercel.app/t/semi-sharp-creases.md): Crease sharpness tags per edge guide the subdivision rules for hard edges. ## Sources 1. [primary] E. Catmull, J. Clark (1978) Recursively generated B-spline surfaces on arbitrary topological meshes. Computer-Aided Design. https://doi.org/10.1016/0010-4485(78)90110-0 (verified via crossref on 2026-11-29) 2. [implementation] PixarAnimationStudios (2012) PixarAnimationStudios/OpenSubdiv. https://github.com/PixarAnimationStudios/OpenSubdiv License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Catmull-Clark Subdivision." https://texelatlas.vercel.app/t/catmull-clark-subdivision/ (accessed 2026-12-01). --- id: "cdlod-terrain" title: "CDLOD terrain" aliases: [Continuous Distance-Dependent LOD, CDLOD] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal] year_introduced: 2010 inputs: [heightfield] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "Strugar, 2009" url: "https://texelatlas.vercel.app/t/cdlod-terrain/" sources_verified_at: "2026-11-29" --- # CDLOD terrain (Strugar, 2009) > Select quadtree nodes by distance to the camera, draw each as the same small grid mesh, and morph vertices in the shader so every LOD change is continuous. ## Reach for it when - terrain lod seams and cracks between chunks - heightmap quadtree lod without popping - smooth morphing between terrain detail levels - render large terrain with few draw calls - distance based terrain tessellation without hardware tessellation ## How it works The heightmap is covered by a quadtree. Each frame, the tree is traversed from the root: a node is drawn at its level if the camera lies beyond that level's range, otherwise it splits into four children. Ranges are chosen per level, usually doubling, and nodes are also frustum-culled using min/max height bounds stored per node. Every selected node renders one shared grid mesh, scaled and offset to the node. In the vertex shader the morph factor, derived from distance within the level's transition band, slides odd vertices onto the coarser grid, so geometry is identical to the parent's LOD at the boundary and no popping or stitching meshes are needed. Neighboring nodes at different levels agree at their shared edges because the morph reaches full by the range edge, which also removes T-junction cracks. ## When to use it Choose it for heightfield terrain where you want a simple, robust LOD with no seam geometry and adaptive node selection, with ranges tunable per level. Prefer [Geometry clipmaps](https://texelatlas.vercel.app/t/geometry-clipmaps-terrain.md) when you want toroidal update of the height data and a fixed, flatter workload. Prefer [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) for non-heightfield terrain. Use [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) or [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md) output as the input heightmap. ## Cost cheap — Node selection on CPU is tiny; GPU cost is a few hundred instanced grid draws with texture-fetched heights. Measured GPU Weight: 457.8× baseline (extreme) — 14.375 ms median / 14.5044 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 412.48× baseline (extreme) — 6.5172 ms median (2.21× faster on L4). Ampere A100 scaling: 330.47× baseline (extreme) — 9.5176 ms median (1.51× faster on A100). ## Failure modes - Heightfield only: no overhangs or caves - Range settings that do not cover the morph band cause visible LOD swimming near transitions - Very distant flat areas still draw full-resolution nodes unless ranges are tuned - Per-node min/max bounds must be recomputed if terrain is edited at runtime, or culling becomes wrong - Texture and normal maps sampled at one LOD while the mesh morphs can show slight shading slide ## Dataflow - Inputs: heightfield - Outputs: mesh - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal ## Presets ### CDLOD terrain — continuous distance-dependent quadtree morphing & LOD ring visualization (glsl-fragment; rendered 2026-11-30) ```json { "P_LOD_BIAS": 1, "P_MORPH_BAND": 0.42, "P_GRID_OVERLAY": 0.82, "P_FLY_SPEED": 1 } ``` ```glsl const float P_LOD_BIAS = 1.0; // P LOD Bias [0.4, 2.2, 0.05] const float P_MORPH_BAND = 0.42; // P Morph Band [0.1, 0.85, 0.02] const float P_GRID_OVERLAY = 0.82; // P Quadtree Grid [0.0, 1.5, 0.04] const float P_FLY_SPEED = 1.0; // P Fly Speed [0.0, 2.5, 0.05] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } // Multi-octave alpine ridge heightfield with smooth LOD truncation float terrainHeight(vec2 p, float lodFloat) { float h = 0.0; float amp = 1.05; float freq = 0.24; mat2 rot = mat2(0.8, 0.6, -0.6, 0.8); vec2 q = p; for (int i = 0; i < 6; i++) { float fi = float(i); // Smoothly attenuate high-frequency octaves according to continuous CDLOD level float octWeight = clamp(1.0 - max(lodFloat - (4.5 - fi), 0.0), 0.0, 1.0); float n = 1.0 - abs(vnoise(q * freq) * 2.0 - 1.0); h += n * n * amp * octWeight; q = rot * q; freq *= 2.06; amp *= 0.48; } return h - 0.55; } // Continuous morph between snapped coarse grid and fine grid float cdlodHeight(vec2 p, vec2 camXZ, float lodBias, float morphBand, out float lodLevel, out float morphAmt) { float d = max(length(p - camXZ), 0.35); float rawLod = log2(d * 0.45 * lodBias); lodLevel = clamp(floor(rawLod), 0.0, 4.0); float fracLod = clamp(rawLod - lodLevel, 0.0, 1.0); morphAmt = smoothstep(1.0 - morphBand, 1.0, fracLod); // Sample fine grid & morphed coarse grid coordinates (exact CDLOD vertex-morph principle) float stepFine = 0.16 * pow(2.0, lodLevel); float stepCoarse = stepFine * 2.0; vec2 snapFine = floor(p / stepFine + 0.5) * stepFine; vec2 snapCoarse = floor(p / stepCoarse + 0.5) * stepCoarse; vec2 pMorph = mix(p, mix(snapFine, snapCoarse, morphAmt), 0.28); float hFine = terrainHeight(pMorph, lodLevel); float hCoarse = terrainHeight(pMorph, lodLevel + 1.0); return mix(hFine, hCoarse, morphAmt); } vec3 lodColor(float lvl) { if (lvl < 0.5) return vec3(0.12, 0.92, 0.82); if (lvl < 1.5) return vec3(0.28, 0.88, 0.36); if (lvl < 2.5) return vec3(0.98, 0.78, 0.20); if (lvl < 3.5) return vec3(0.96, 0.36, 0.24); return vec3(0.76, 0.32, 0.96); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float tAnim = iTime * max(P_FLY_SPEED, 0.0); float lodBias = clamp(P_LOD_BIAS, 0.35, 2.5); float morphBand = clamp(P_MORPH_BAND, 0.08, 0.9); float gridVis = clamp(P_GRID_OVERLAY, 0.0, 1.6); vec3 ro = vec3(tAnim * 0.7, 2.25 + 0.18 * sin(tAnim * 0.4), -tAnim * 1.15); vec3 ta = ro + vec3(0.6 * sin(tAnim * 0.22), -0.95, -3.2); vec3 fw = normalize(ta - ro); vec3 rt = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(rt, fw); vec3 rd = normalize(fw * 1.45 + rt * uv.x + up * uv.y); // Atmospheric mountain sky vec3 sunDir = normalize(vec3(0.65, 0.42, -0.62)); float sunAmt = max(dot(rd, sunDir), 0.0); vec3 sky = mix(vec3(0.54, 0.68, 0.82), vec3(0.14, 0.28, 0.54), pow(clamp(rd.y * 2.2 + 0.1, 0.0, 1.0), 0.65)); sky += vec3(1.0, 0.82, 0.55) * pow(sunAmt, 10.0) * 0.55; vec3 col = sky; // Raymarch terrain heightfield float t = 0.2; bool hit = false; float lodLvl = 0.0; float morph = 0.0; for (int i = 0; i < 68; i++) { vec3 p = ro + rd * t; float h = cdlodHeight(p.xz, ro.xz, lodBias, morphBand, lodLvl, morph); float diff = p.y - h; if (diff < 0.008 * t) { // Binary refine hit t -= diff * 0.5; hit = true; break; } t += max(diff * 0.48, 0.035 + t * 0.022); if (t > 28.0) break; } if (hit) { vec3 p = ro + rd * t; float lDummy, mDummy; float eps = 0.04 + t * 0.008; float hC = cdlodHeight(p.xz, ro.xz, lodBias, morphBand, lodLvl, morph); float hX = cdlodHeight(p.xz + vec2(eps, 0.0), ro.xz, lodBias, morphBand, lDummy, mDummy); float hZ = cdlodHeight(p.xz + vec2(0.0, eps), ro.xz, lodBias, morphBand, lDummy, mDummy); vec3 n = normalize(vec3(hC - hX, eps, hC - hZ)); // Biome shading: rocky cliff, alpine moss, snow peaks float slope = 1.0 - n.y; vec3 rock = vec3(0.28, 0.26, 0.25); vec3 moss = vec3(0.22, 0.34, 0.18); vec3 snow = vec3(0.86, 0.90, 0.96); vec3 alb = mix(moss, rock, smoothstep(0.18, 0.48, slope)); alb = mix(alb, snow, smoothstep(0.32, 0.72, p.y - slope * 0.45)); float diffL = max(dot(n, sunDir), 0.0); float amb = 0.24 + 0.18 * n.y; vec3 shaded = alb * (amb * vec3(0.65, 0.78, 1.0) + diffL * vec3(1.15, 0.98, 0.80)); // CDLOD Quadtree patch grid & morphed sub-grid lines float nodeSize = 0.65 * pow(2.0, lodLvl); vec2 qf = abs(fract(p.xz / nodeSize - 0.5) - 0.5); float nodeEdge = smoothstep(0.045, 0.012, min(qf.x, qf.y)); vec2 subF = abs(fract(p.xz / (nodeSize * 0.25) - 0.5) - 0.5); float subEdge = smoothstep(0.055, 0.015, min(subF.x, subF.y)) * (1.0 - morph * 0.75); vec3 tierCol = lodColor(lodLvl); vec3 nextTierCol = lodColor(min(lodLvl + 1.0, 4.0)); vec3 activeTint = mix(tierCol, nextTierCol, morph); // Subtle LOD tint + crisp quadtree borders + morph transition highlight shaded = mix(shaded, shaded * (0.65 + 0.55 * activeTint), 0.28 * min(gridVis, 1.0)); shaded = mix(shaded, activeTint * 1.25, nodeEdge * 0.68 * min(gridVis, 1.2)); shaded += activeTint * subEdge * 0.22 * gridVis; // Glowing white-gold ribbon showing the active vertex-morph transition zone float morphGlow = smoothstep(0.05, 0.5, morph) * smoothstep(1.0, 0.5, morph); shaded += vec3(0.95, 0.92, 0.78) * morphGlow * 0.22 * gridVis; float fog = 1.0 - exp(-t * 0.048); col = mix(shaded, sky, fog); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Geometry clipmaps](https://texelatlas.vercel.app/t/geometry-clipmaps-terrain.md) ## Combines with - [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md): Eroded heightmaps produced on the GPU are streamed straight into the node height textures. ## Sources 1. [primary] Filip Strugar (2009) Continuous Distance-Dependent Level of Detail for Rendering Heightmaps. Journal of Graphics, GPU, and Game Tools. https://doi.org/10.1080/2151237x.2009.10129287 (verified via crossref on 2026-11-29) 2. [implementation] fstrugar (2017) fstrugar/CDLOD. https://github.com/fstrugar/CDLOD License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "CDLOD terrain." https://texelatlas.vercel.app/t/cdlod-terrain/ (accessed 2026-12-01). --- id: "cellular-automata-cave-generation" title: "Cellular automata cave generation" aliases: [CA caves, cave smoothing rule, 4-5 rule] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [cpu, webgl2, python, unity, unreal, godot] year_introduced: 2010 inputs: [layout] outputs: [layout, voxels] style: "stylized" dynamic: "static" cost: "cheap" authority: "Johnson et al., 2010" url: "https://texelatlas.vercel.app/t/cellular-automata-cave-generation/" sources_verified_at: "2026-11-29" --- # Cellular automata cave generation (Johnson et al., 2010) > Fills a grid with random walls, then repeatedly replaces each cell by a majority-style rule over its neighbours, which erodes noise into organic cave chambers and tunnels. ## Reach for it when - want organic cave layouts from simple rules - random noise grid to cave chambers - roguelike map generator with few parameters - generated caves are disconnected rooms ## How it works Initialise a 2D or 3D grid with each cell wall with probability around 45 percent. Run a few smoothing iterations where every cell counts its wall neighbours in the 8-cell or 26-cell neighbourhood: a cell becomes a wall if it has at least a threshold number of wall neighbours and otherwise open (a common choice is the 4-5 rule, with an early-stage variant that also fills isolated pockets). Noise collapses into blobs and the blobs merge into cave-like caverns. Afterwards, flood-fill to label connected open regions, drop tiny ones, and connect the survivors with tunnels or keep only the largest. Border cells are forced solid. Convert to a mesh with [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) or [Surface Nets](https://texelatlas.vercel.app/t/surface-nets.md) for smooth cave walls, or to blocks for voxel games. An infinite variant processes chunks with a window of neighbours and seed-hash initialisation. ## When to use it Choose it for quick organic caves and island-like shapes in grids where you want few knobs and no authored layout. Prefer [BSP Dungeon Generation](https://texelatlas.vercel.app/t/bsp-dungeon-generation.md) for rooms and corridors, [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) or [Model Synthesis](https://texelatlas.vercel.app/t/model-synthesis.md) when adjacency rules and authored tiles matter, [MarkovJunior (Rewrite-Rule Generation)](https://texelatlas.vercel.app/t/markov-junior-rewrite-rules.md) for rule-based tile rewriting, and [Worley (Cellular) Noise](https://texelatlas.vercel.app/t/worley-noise.md) or [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) thresholds when you need continuous, unbounded fields. ## Cost cheap — A few passes over the grid; trivial on the CPU for 2D, moderate for 3D volumes and chunked infinite worlds. Measured GPU Weight: 71.56× baseline (extreme) — 2.3542 ms median / 2.4307 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 70.81× baseline (extreme) — 1.1259 ms median (2.09× faster on L4). Ampere A100 scaling: 52.46× baseline (heavy) — 1.5109 ms median (1.56× faster on A100). ## Failure modes - Disconnected caverns unless a flood-fill and tunnel-carving pass joins them - Result looks uniformly blobby with no large-scale structure or guaranteed path length - Chunked generation shows seams at borders because each chunk smooths without the neighbours' cells - Parameters are brittle: a small change to the initial wall density flips between solid rock and one open void ## Dataflow - Inputs: layout - Outputs: layout, voxels - Platforms: cpu, webgl2, python, unity, unreal, godot ## Presets ### Cellular automata caves — B5678/S45678 Moore-neighborhood cavern carving (glsl-fragment; rendered 2026-11-30) ```json { "P_FILL_DENSITY": 0.48, "P_SMOOTHING": 1, "P_CELL_SCALE": 26, "P_WATER_LEVEL": 0.42 } ``` ```glsl const float P_FILL_DENSITY = 0.48; // P Fill Density [0.25, 0.72, 0.01] const float P_SMOOTHING = 1.0; // P CA Smoothing [0.0, 2.0, 0.05] const float P_CELL_SCALE = 26.0; // P Cell Scale [10.0, 48.0, 1.0] const float P_WATER_LEVEL = 0.42; // P Aquifer Glow [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } // Initial random rock fill with gentle macro cavern bias float initCell(vec2 cell, float fill) { float h = hash21(cell); // Subtle macro room seed so connected caverns emerge reliably float macro = 0.5 + 0.5 * sin(cell.x * 0.22 + 0.7) * cos(cell.y * 0.21 - 0.4); float thresh = clamp(fill + (macro - 0.5) * 0.18, 0.15, 0.85); return step(1.0 - thresh, h); } // Pass 1: 3x3 Moore neighborhood count (birth/survival >= 5 of 9 cells) float caPass1(vec2 c, float fill) { float sum = 0.0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { sum += initCell(c + vec2(float(dx), float(dy)), fill); } } return smoothstep(4.2, 5.2, sum); } // Pass 2: second smoothing generation over Pass 1 float caPass2(vec2 c, float fill) { float sum = 0.0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { sum += caPass1(c + vec2(float(dx), float(dy)), fill); } } return sum / 9.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float scale = clamp(P_CELL_SCALE, 8.0, 56.0); vec2 pan = vec2(iTime * 0.45, sin(iTime * 0.22) * 1.4); vec2 gPos = uv * scale + pan; vec2 cell = floor(gPos); vec2 f = fract(gPos); float fill = clamp(P_FILL_DENSITY, 0.2, 0.8); float sm = clamp(P_SMOOTHING, 0.0, 2.0); // Bilinearly sample smoothed CA field across 4 neighboring cells for crisp organic walls vec2 w = f * f * (3.0 - 2.0 * f); float s00 = mix(caPass1(cell, fill), caPass2(cell, fill), clamp(sm, 0.0, 1.0)); float s10 = mix(caPass1(cell + vec2(1.0, 0.0), fill), caPass2(cell + vec2(1.0, 0.0), fill), clamp(sm, 0.0, 1.0)); float s01 = mix(caPass1(cell + vec2(0.0, 1.0), fill), caPass2(cell + vec2(0.0, 1.0), fill), clamp(sm, 0.0, 1.0)); float s11 = mix(caPass1(cell + vec2(1.0, 1.0), fill), caPass2(cell + vec2(1.0, 1.0), fill), clamp(sm, 0.0, 1.0)); float field = mix(mix(s00, s10, w.x), mix(s01, s11, w.x), w.y); // Blend between crisp tile-level CA and interpolated smooth cave wall float rawCell = caPass2(cell, fill); float caveVal = mix(rawCell, field, clamp(sm * 0.55, 0.0, 1.0)); // Gradient for rim bevel & top-left torch lighting vec2 grad = vec2( mix(s10 - s00, s11 - s01, w.y), mix(s01 - s00, s11 - s10, w.x) ); vec3 nrm = normalize(vec3(-grad * 4.5, 1.0)); vec2 torchPos = vec2(0.28 * cos(iTime * 0.6), 0.22 * sin(iTime * 0.48)); vec3 lDir = normalize(vec3(torchPos - uv, 0.35)); float torchAtt = 1.0 / (1.0 + 3.8 * dot(torchPos - uv, torchPos - uv)); // Wall vs open floor mask float isWall = smoothstep(0.46, 0.54, caveVal); float wallRim = smoothstep(0.12, 0.0, abs(caveVal - 0.5)); // Stratified cavern limestone coloring float strata = 0.5 + 0.5 * sin(gPos.y * 1.4 + sin(gPos.x * 0.45) * 1.6); float grain = hash21(floor(gPos * 4.0)); vec3 rockCol = mix(vec3(0.14, 0.12, 0.11), vec3(0.32, 0.27, 0.23), strata * 0.65 + 0.35 * grain); float ndl = max(dot(nrm, lDir), 0.0); rockCol *= (0.35 + 1.15 * ndl * torchAtt); rockCol += vec3(0.55, 0.42, 0.28) * wallRim * (0.4 + 0.9 * torchAtt); // Open cavern floor with subtle pebble texture and glowing turquoise aquifer pools float depth = clamp((0.48 - caveVal) * 2.5, 0.0, 1.0); vec3 floorCol = mix(vec3(0.08, 0.085, 0.095), vec3(0.04, 0.055, 0.07), depth); floorCol *= (0.5 + 1.4 * torchAtt); float waterMask = smoothstep(0.58 - 0.42 * P_WATER_LEVEL, 0.78 - 0.42 * P_WATER_LEVEL, depth); float ripple = 0.5 + 0.5 * sin(gPos.x * 2.6 + iTime * 2.2) * cos(gPos.y * 2.4 - iTime * 1.8); vec3 waterCol = vec3(0.06, 0.46, 0.58) * (0.75 + 0.45 * ripple) + vec3(0.18, 0.85, 0.92) * pow(ripple, 5.0) * 0.45; floorCol = mix(floorCol, waterCol, waterMask * clamp(P_WATER_LEVEL * 1.2, 0.0, 1.0)); // Subtle tile-grid overlay to reveal underlying cellular lattice vec2 cellEdge = abs(f - 0.5); float tileLine = smoothstep(0.45, 0.5, max(cellEdge.x, cellEdge.y)); vec3 col = mix(floorCol, rockCol, isWall); col = mix(col, col * 0.72 + vec3(0.03, 0.04, 0.05), tileLine * 0.35); // Warm moving explorer torch aura col += vec3(1.0, 0.68, 0.32) * exp(-length(uv - torchPos) * 7.5) * 0.35; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Surface Nets](https://texelatlas.vercel.app/t/surface-nets.md): Treating the wall mask as a scalar field and meshing it with surface nets gives smooth organic cave walls from the blocky automaton output. ## Sources 1. [primary] Lawrence Johnson, Georgios N. Yannakakis, Julian Togelius (2010) Cellular automata for real-time generation of infinite cave levels. Proceedings of the 2010 Workshop on Procedural Content Generation in Games. https://doi.org/10.1145/1814256.1814266 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Cellular automata cave generation." https://texelatlas.vercel.app/t/cellular-automata-cave-generation/ (accessed 2026-12-01). --- id: "cga-shape-grammar" title: "CGA Shape Grammar (Procedural Buildings)" aliases: [CGA shape, shape grammar for buildings, CityEngine rules] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, houdini, blender] year_introduced: 2006 inputs: [layout] outputs: [mesh] style: "both" dynamic: "static" cost: "medium" authority: "Müller et al., 2006" url: "https://texelatlas.vercel.app/t/cga-shape-grammar/" sources_verified_at: "2026-11-29" --- # CGA Shape Grammar (Procedural Buildings) (Müller et al., 2006) > A grammar of 3D shapes with scope-aware operations (split, repeat, extrude, component split) that turns a building footprint and a few parameters into a detailed, textured facade and mass model. ## Reach for it when - generate detailed building facades procedurally - need to populate a city with many varied buildings - model architecture from rules instead of by hand - make variations of a building style from a few parameters ## How it works A shape is a labelled 3D scope (position, orientation, size) plus geometry. Rules rewrite a shape symbol into others: split divides the scope along an axis into slices with relative or absolute sizes (floors, tiles), repeat tiles an element to fill a range, comp splits a volume into faces, extrude and taper make masses, and insert replaces a scope by an asset. Rules apply in sequence from a lot footprint through mass model, floors, facade tiles and windows, with stochastic selection among alternatives for variety and context queries (occlusion, snapping) to avoid collisions. The grammar's output is a hierarchy of terminal shapes meshed into the final model. It excels at structured, regular architecture and keeps all design logic as editable rules. ## When to use it Choose it for city blocks and facades where rules (floors, bays, windows) express the style, and for large crowds of varied buildings from a handful of rules. Prefer [Model Synthesis](https://texelatlas.vercel.app/t/model-synthesis.md) or [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) when you want to imitate an example rather than author rules, [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) for organic growth, and [Procedural Kit Modeling with Verification (procgen-kit)](https://texelatlas.vercel.app/t/procedural-kit-modeling.md) when modules must be parametric, closed and collision-verified. ## Cost medium — Rule derivation is fast per building (milliseconds to seconds) but generating a whole city is a batch job; resulting meshes need LOD. Measured GPU Weight: 1.55× baseline (feather) — 0.0511 ms median / 0.053 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.33× baseline (feather) — 0.0212 ms median (2.41× faster on L4). Ampere A100 scaling: 1.11× baseline (feather) — 0.0321 ms median (1.59× faster on A100). ## Failure modes - Rules are brittle with irregular footprints: splits on odd lot shapes give slivers or overlapping scopes - Grammar authoring is an expertise barrier; subtle rule errors yield mismatched facades - Repeated rules make uniform, clone-like facades unless stochastic variation is added - Output mesh topology is not guaranteed manifold or watertight - Complex designs (organic, historical) are hard to express and require many custom operations ## Engine support - unreal: official — `Enable the PCG plugin; PCG graph shape grammar nodes` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/using-shape-grammar-with-pcg-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: layout - Outputs: mesh - Platforms: cpu, houdini, blender ## Presets ### Facade produced by a CGA-style split/repeat rule chain (glsl-fragment; rendered 2026-11-29) ```json { "FLOORS": 5, "TILE_W": 0.11, "GROUND_H": 0.17, "ROOF_H": 0.06 } ``` ```glsl // Facade from a CGA-style rule chain: split(y){ground | floor~ | roof}, repeat(x){wall | window | wall}, with a door on the ground floor. const int FLOORS = 5; const float TILE_W = 0.11; const float GROUND_H = 0.17; const float ROOF_H = 0.06; float h(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } float box(vec2 p, vec2 b) { vec2 q = abs(p) - b; return max(q.x, q.y); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec3 sky = mix(vec3(0.85, 0.65, 0.5), vec3(0.2, 0.3, 0.55), uv.y); vec3 col = sky; vec2 lo = vec2(0.12, 0.06), hi = vec2(0.88, 0.94); if (uv.x > lo.x && uv.x < hi.x && uv.y > lo.y && uv.y < hi.y) { float H = hi.y - lo.y, y = (uv.y - lo.y) / H * (1.0 - 0.0); float gh = GROUND_H, rh = ROOF_H, fh = (1.0 - gh / 1.0 * 0.0); float yy = uv.y - lo.y; float totalH = H, floorsH = totalH - GROUND_H - ROOF_H; float fl = floorsH / float(FLOORS); vec3 wall = vec3(0.72, 0.62, 0.52); float tx = (uv.x - lo.x) / TILE_W; float nTiles = floor((hi.x - lo.x) / TILE_W); float ti = floor(tx); vec2 tl = vec2(fract(tx) - 0.5, 0.0); col = wall * (0.9 + 0.1 * h(floor(uv * 90.0))); if (yy < GROUND_H) { // ground: shopfront band with a door in the middle tile col = wall * 0.75; vec2 q = vec2(fract(tx) - 0.5, yy / GROUND_H - 0.5); bool mid = abs(ti - floor(nTiles * 0.5)) < 0.5; float d = box(q, mid ? vec2(0.3, 0.42) : vec2(0.36, 0.28)); vec3 gl = mid ? vec3(0.25, 0.15, 0.1) : vec3(0.3, 0.45, 0.55); col = mix(col, gl, smoothstep(0.03, -0.01, d)); } else if (yy > totalH - ROOF_H) { col = vec3(0.35, 0.18, 0.15) * (0.8 + 0.2 * sin(uv.x * 220.0)); col = mix(col, wall * 0.5, step(totalH - ROOF_H * 0.22, yy)); } else { float fy = (yy - GROUND_H) / fl; float fi = floor(fy); vec2 q = vec2(fract(tx) - 0.5, fract(fy) - 0.5); float d = box(q, vec2(0.2, 0.28)); float lit = step(0.5, h(vec2(ti, fi))); vec3 gl = mix(vec3(0.22, 0.32, 0.45), vec3(1.0, 0.8, 0.45), lit) * (0.7 + 0.5 * (0.5 - q.y)); col = mix(col, gl, smoothstep(0.02, -0.01, d)); col = mix(col, wall * 0.45, smoothstep(0.02, 0.0, abs(d - 0.04)) * step(0.0, d) * 0.5); col *= 1.0 - 0.25 * smoothstep(0.03, 0.0, abs(fract(fy) - 0.0)); } col = mix(col, vec3(0.08), smoothstep(0.004, 0.0, min(uv.x - lo.x, hi.x - uv.x)) * 0.5); } else if (uv.y < lo.y) col = vec3(0.15, 0.15, 0.17); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) ## Combines with - [Procedural City Generation (L-system Road Networks)](https://texelatlas.vercel.app/t/procedural-city-roads.md): Road networks produce the lots and footprints that the shape grammar extrudes into buildings. ## Combination ideas - [Overgrown grammar cities](https://texelatlas.vercel.app/ideas/ivy-on-grammar-architecture/) - [Cities wired by slime mould](https://texelatlas.vercel.app/ideas/slime-mould-road-networks/) ## Sources 1. [primary] Pascal Müller, Peter Wonka, Simon Haegler, Andreas Ulmer, Luc Van Gool (2006) Procedural modeling of buildings. ACM Transactions on Graphics. https://doi.org/10.1145/1141911.1141931 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "CGA Shape Grammar (Procedural Buildings)." https://texelatlas.vercel.app/t/cga-shape-grammar/ (accessed 2026-12-01). --- id: "chaotic-attractor-density-rendering" title: "Chaotic attractor density rendering" aliases: [Lorenz attractor, strange attractor rendering] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 1963 inputs: [particles] outputs: [ldr-image, volume-density] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Lorenz, 1963" url: "https://texelatlas.vercel.app/t/chaotic-attractor-density-rendering/" sources_verified_at: "2026-11-29" --- # Chaotic attractor density rendering (Lorenz, 1963) > Visualises Lorenz-style strange attractors by integrating many trajectories and accumulating them into a density image or fibre set, tone-mapped for glow. ## Reach for it when - want to visualise a lorenz-style chaotic system - draw glowing swirling trajectories as a density image - generate abstract scientific art from differential equations - need a procedural backdrop of looping curves ## How it works Integrate an ODE system such as Lorenz (`dx=sigma(y-x)`, `dy=x(rho-z)-y`, `dz=xy-beta z`) with RK2 or RK4 from many starting points after a burn-in period so points lie on the attractor. Each sample is projected and splatted into a floating-point accumulation buffer (additive blending, or atomic adds in compute); the result is log or exponential tone-mapped and colourised by velocity, age or Lyapunov-style divergence. Alternatives draw the trajectory as tube or ribbon geometry, or accumulate in a 3D density texture for volume rendering. For buffer-free shaders the per-pixel loop integrates a trajectory and sums Gaussian splats, which is exact but costs O(steps) per pixel. ## When to use it Choose it for scientific/artistic visualisation of chaotic systems and procedural backgrounds. Prefer [Boids flocking](https://texelatlas.vercel.app/t/boids.md) for agent flocks, [Physarum agent transport networks](https://texelatlas.vercel.app/t/physarum-transport-networks.md) for network textures, and [Gray-Scott reaction-diffusion](https://texelatlas.vercel.app/t/gray-scott-reaction-diffusion.md) for PDE-based patterns; use volume density rendering when you need 3D depth cues. ## Cost medium — Cost is points x splat size; compute-shader accumulation is cheap, per-pixel loops are heavy. Measured GPU Weight: 781.29× baseline (extreme) — 25.7044 ms median / 26.1186 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 577.92× baseline (extreme) — 9.1889 ms median (2.8× faster on L4). Ampere A100 scaling: 546.2× baseline (extreme) — 15.7307 ms median (1.63× faster on A100). ## Failure modes - Sparse sampling gives dotted trails rather than smooth densities - Fixed-step Euler drifts off the attractor on stiff systems; use RK4 or small dt - Float accumulation saturates: needs log tone-mapping or HDR buffers - Different attractor families need re-tuned scale/offset to fit the viewport ## Dataflow - Inputs: particles - Outputs: ldr-image, volume-density - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Lorenz attractor density splat (glsl-fragment; rendered 2026-11-29) ```json { "STEPS": 1400, "DT": 0.0105, "SIGMA": 10, "RHO": 28, "BETA": 2.6667 } ``` ```glsl // GLSL ES 3.0 - Lorenz attractor density splat; written for this index const int STEPS = 1400; // trajectory samples const float DT = 0.0105; // integration step const float SIGMA = 10.0; const float RHO = 28.0; const float BETA = 8.0 / 3.0; const float SPLAT = 0.0009; // splat variance in view space const float GAIN = 0.045; vec3 lorenz(vec3 p) { return vec3(SIGMA * (p.y - p.x), p.x * (RHO - p.z) - p.y, p.x * p.y - BETA * p.z); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float ang = 0.4 * iTime; float c = cos(ang), s = sin(ang); vec3 p = vec3(1.0, 1.0, 1.0); for (int i = 0; i < 200; i++) { vec3 k1 = lorenz(p); vec3 k2 = lorenz(p + 0.5 * DT * k1); p += DT * k2; } float dens = 0.0; float hue = 0.0; for (int i = 0; i < STEPS; i++) { vec3 k1 = lorenz(p); vec3 k2 = lorenz(p + 0.5 * DT * k1); p += DT * k2; vec3 q = p - vec3(0.0, 0.0, 25.0); vec2 v = vec2(c * q.x - s * q.y, q.z) * 0.032; vec2 d = uv - v; float w = exp(-dot(d, d) / SPLAT); dens += w; hue += w * float(i) / float(STEPS); } float l = 1.0 - exp(-GAIN * dens * 4.0); float h = hue / max(dens, 1e-4); vec3 col = mix(vec3(0.1, 0.35, 0.9), vec3(1.0, 0.55, 0.2), h); col = col * l + vec3(0.01, 0.015, 0.03); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Combination ideas - [Strange attractors as lit clouds](https://texelatlas.vercel.app/ideas/attractor-clouds-delta-tracked/) ## Sources 1. [primary] Edward N. Lorenz (1963) Deterministic Nonperiodic Flow. Journal of the Atmospheric Sciences. https://doi.org/10.1175/1520-0469(1963)020<0130:dnf>2.0.co;2 (verified via crossref on 2026-11-29) 2. [tutorial] Paul Bourke Lorenz Attractor. paulbourke.net. https://paulbourke.net/fractals/lorenz (verified via http on 2026-11-29) ## Cite this entry Texel. "Chaotic attractor density rendering." https://texelatlas.vercel.app/t/chaotic-attractor-density-rendering/ (accessed 2026-12-01). --- id: "charlie-sheen" title: "Charlie sheen (Estevez-Kulla)" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2017 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Estevez & Kulla" url: "https://texelatlas.vercel.app/t/charlie-sheen/" sources_verified_at: "2026-11-29" --- # Charlie sheen (Estevez-Kulla) (Estevez & Kulla) > A microfacet-style sheen lobe using an inverted-Gaussian-like 'Charlie' distribution, for velvet and cloth where highlights brighten near grazing angles. Production-friendly, with an analytic visibility term and LUT-based energy compensation. ## Reach for it when - velvet looks like plastic or plain diffuse - cloth should brighten at grazing angles - need fuzzy rim glow on fabric or peach fuzz - dusty or felt surfaces lack a soft sheen - want a production cloth lobe that conserves energy ## How it works Velvet-like fabrics scatter light from fibres sticking out of the surface, giving retro-reflection and rim brightening that GGX cannot produce. Estevez and Kulla define a distribution D(h) = (2 + 1/alpha) sin(theta_h)^(1/alpha) / (2 pi), which peaks at grazing facet normals instead of at the surface normal. Shadowing uses a simplified analytic visibility rather than Smith, tuned to avoid dark fringes. A small precomputed table gives directional albedo so the sheen can be energy-balanced against the base layer (the base is scaled by 1 - max(sheenColor) * E_sheen). Filament, the glTF KHR_materials_sheen extension and OpenPBR's fuzz layer all use variants of it. ## When to use it Choose it for velvet, satin, felt and dusty or peach-fuzz looks. Prefer [Oren-Nayar rough diffuse](https://texelatlas.vercel.app/t/oren-nayar.md) for plain rough cloth that lacks rim brightening. Prefer fibre or hair BSDFs for yarn closeups. Layer under [Clearcoat layer](https://texelatlas.vercel.app/t/clearcoat-layer.md) only if the fabric is coated. ## Cost cheap — One extra lobe with a pow and a small LUT lookup. Measured GPU Weight: 2.03× baseline (light) — 0.0669 ms median / 0.0685 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.8× baseline (feather) — 0.0286 ms median (2.34× faster on L4). Ampere A100 scaling: 1.37× baseline (feather) — 0.0394 ms median (1.7× faster on A100). ## Failure modes - Energy compensation LUT mismatches cause visible darkening of the base around the sheen rim - Sheen colour with no base-layer coupling looks pasted-on - No dependence on weave direction, so satin and twill look wrong without anisotropic variants - IBL sheen needs its own pre-filtered cubemap or it looks like a generic specular ## Engine support - babylonjs: builtin — `pbrMaterial.sheen.isEnabled = true (PBRSheenConfiguration)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrSheenConfiguration.ts, checked 2026-12-01) - blender: builtin — `Principled BSDF > Sheen > Distribution = Microfiber (or Ashikhmin)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) - threejs: builtin — `material.sheen = 1; material.sheenRoughness (MeshPhysicalMaterial)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshPhysicalMaterial.js, checked 2026-12-01) - unity: builtin — `HDRP Lit/Fabric > Material Type = Fabric (Cotton/Wool)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/Fabric.hlsl, checked 2026-12-01) — HDRP Fabric uses the Charlie distribution for cotton/wool. - unreal: builtin — `Material > Shading Model = Cloth (Fuzz Color / Cloth) or Substrate Slab BSDF Fuzz inputs` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/substrate-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Red velvet (three-material; rendered 2026-11-29) ```json { "color": "#4a0a12", "roughness": 0.7, "metalness": 0, "sheen": 1, "sheenColor": "#d44b5b" } ``` Attribution: written for this index; sensible defaults, not measured ## Sources 1. [primary] Alejandro Conty Estevez, Christopher Kulla Production Friendly Microfacet Sheen BRDF. SIGGRAPH 2017 Course. https://fpsunflower.github.io/ckulla/data/s2017_pbs_imageworks_sheen.pdf (verified via http on 2026-11-29) 2. [tutorial] Romain Guy, Mathias Agopian Filament: Physically based rendering (image based lights section). google.github.io. https://google.github.io/filament/Filament.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Charlie sheen (Estevez-Kulla)." https://texelatlas.vercel.app/t/charlie-sheen/ (accessed 2026-12-01). --- id: "christensen-burley-sss" title: "Christensen-Burley diffusion profile" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2015 inputs: [material-params, mesh] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Christensen, 2015" url: "https://texelatlas.vercel.app/t/christensen-burley-sss/" sources_verified_at: "2026-11-29" --- # Christensen-Burley diffusion profile (Christensen, 2015) > A cheap analytic reflectance profile that approximates Monte Carlo subsurface scattering, used with a per-channel scattering distance in Pixar's RenderMan and Disney's Hyperion. Importance-samples nicely and replaces expensive dipole or multipole models. ## Reach for it when - skin looks like hard plastic or wax - cheap subsurface scattering for production rendering - light should bleed softly through skin and marble - need a diffusion profile that is fast to sample ## How it works Subsurface scattering needs a diffusion profile R(r): how much light entering at one surface point exits at distance r. Christensen and Burley fit a sum of two exponentials, which is the shape produced by Monte Carlo reference with albedo-inversion and is easy to normalise and sample analytically. The profile depends on a shape parameter and a scattering distance d per colour channel; an artist-friendly mapping from surface albedo to d keeps the final albedo matched. Rendering uses either point-cloud/diffusion integration or probabilistic sampling of nearby surface points (disk sampling around the shading point projected on geometry). The approach is far cheaper than dipoles for production and more faithful to Monte Carlo ground truth, particularly at short mean free paths. ## When to use it Choose it for offline or high-fidelity skin, wax, marble and jade where a path tracer or ray-traced sample gather is available. Prefer [Separable subsurface scattering](https://texelatlas.vercel.app/t/separable-sss.md) for real-time screen-space SSS on characters. For a quick glass-like approximation use a transmission preset. ## Cost offline — Production path-traced use; real-time ports need screen-space approximation. Measured GPU Weight: 1.96× baseline (feather) — 0.0645 ms median / 0.066 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.78× baseline (feather) — 0.0283 ms median (2.28× faster on L4). Ampere A100 scaling: 1.34× baseline (feather) — 0.0386 ms median (1.67× faster on A100). ## Failure modes - Sampling points on the geometry fails for thin features like ears where light passes through, unless thin-slab transmission is added - Approximate profile deviates at very long scattering distances compared to a full volumetric simulation - Red channel's long scattering distance can bleed across geometry seams - Requires a ray or surface-sampling query, which a rasterizer lacks ## Engine support - babylonjs: builtin — `pbrMaterial.subSurface.isScatteringEnabled = true; scene.enableSubSurfaceForPrePass()` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrSubSurfaceConfiguration.ts, checked 2026-12-01) — Screen-space normalized Burley diffusion profile. - blender: builtin — `Principled BSDF or Subsurface Scattering node > Method = Christensen-Burley` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) - unity: builtin — `HDRP Lit > Subsurface Scattering; Diffusion Profile asset` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfile.hlsl, checked 2026-12-01) — HDRP only; Burley normalized diffusion profiles. - unreal: builtin — `Subsurface Profile asset > Burley Normalized; Material > Shading Model = Subsurface Profile` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, mesh - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Marble (colour and IOR only) (three-material; rendered 2026-11-29) ```json { "color": "#ebe6e1", "roughness": 0.25, "metalness": 0, "ior": 1.5 } ``` Attribution: written for this index; marble colour and IOR from physicallybased.info (CC0), roughness chosen here; the dataset's subsurface radius has no MeshPhysicalMaterial equivalent so it is not applied; basis: 2 ## Lineage - extends [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) ## Sources 1. [primary] Per H. Christensen (2015) An approximate reflectance profile for efficient subsurface scattering. ACM SIGGRAPH 2015 Talks. https://doi.org/10.1145/2775280.2792555 (verified via crossref on 2026-11-29) 2. [primary] Per Christensen, Brent Burley An Approximate Reflectance Profile for Efficient Subsurface Scattering. pixar.com. https://www.pixar.com/technology-libraries (verified via http on 2026-11-29) 3. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Christensen-Burley diffusion profile." https://texelatlas.vercel.app/t/christensen-burley-sss/ (accessed 2026-12-01). --- id: "chromatic-aberration" title: "Chromatic aberration and vignette" domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2010 inputs: [hdr-image, ldr-image] outputs: [ldr-image] style: "both" dynamic: "both" cost: "cheap" authority: "Unity-Technologies, 2016" url: "https://texelatlas.vercel.app/t/chromatic-aberration/" sources_verified_at: "2026-11-29" --- # Chromatic aberration and vignette (Unity-Technologies, 2016) > Cheap lens-imperfection pass: sample red, green and blue at slightly different radial scales to fake lateral colour fringing, then darken toward the corners with a smooth radial falloff. ## Reach for it when - image looks too clean and digital - want colour fringing at screen edges like a real lens - need cheap crt or cheap-lens look - darken the corners to draw focus to the centre ## How it works Lateral chromatic aberration is the wavelength-dependent magnification of a real lens. The shader computes the vector from the screen centre to the pixel, then reads the red channel at a slightly larger scale and the blue channel at a slightly smaller one, with green at the original position. The offset grows with distance from the centre, so the centre stays clean and fringes appear at edges. For smoother fringes, take several taps across the spectrum and weight them with a hue ramp. A vignette multiplies the result by a smooth function of the squared distance from centre, which can be aspect corrected and softened with a power or smoothstep. Both effects are applied late, in display space, after bloom and before grain. ## When to use it Choose it for a subtle photographic or CRT feel, or to add edge-weighted attention. Prefer a physically based lens flare or full lens simulation when accuracy matters. Apply before [Film grain synthesis](https://texelatlas.vercel.app/t/film-grain-synthesis.md) so the grain stays unaffected. ## Cost cheap — One pass with three or a few more fetches. Measured GPU Weight: 2.73× baseline (light) — 0.0897 ms median / 0.0923 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.19× baseline (light) — 0.0348 ms median (2.58× faster on L4). Ampere A100 scaling: 1.87× baseline (feather) — 0.0538 ms median (1.67× faster on A100). ## Failure modes - Too much looks like a cheap filter and softens fine UI or text - Colour fringes on bright points exceed gamut after tonemapping if applied on HDR - Aspect-ratio errors produce elliptical vignette - Fringing becomes jaggy when the scene is not filtered or anti-aliased first ## Engine support - babylonjs: builtin — `pipeline.chromaticAberrationEnabled = true; imageProcessing.vignetteEnabled = true` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.pure.ts, checked 2026-12-01) - blender: builtin — `Compositor > Add > Camera Lens Effects > Chromatic Aberration (and Vignette)` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/camera_lens_effects/chromatic_aberration.html, checked 2026-12-01) — Compositor nodes, applied after rendering. - threejs: official — `import { chromaticAberration } from 'three/addons/tsl/display/ChromaticAberrationNode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/ChromaticAberrationNode.js, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Post-processing > Chromatic Aberration (and Vignette)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Post-Processing-Chromatic-Aberration.md, checked 2026-12-01) — URP and HDRP. - unreal: builtin — `Post Process Volume > Lens > Chromatic Aberration > Intensity` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image, ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Radial fringing and vignette on a test pattern (glsl-fragment; rendered 2026-11-29) ```json { "CA_STRENGTH": 0.03, "VIG_STRENGTH": 0.55 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style const float CA_STRENGTH = 0.03; const float VIG_STRENGTH = 0.55; vec3 scene(vec2 p) { vec2 g = floor(p * 4.0); float chk = mod(g.x + g.y, 2.0); vec3 col = mix(vec3(0.12, 0.14, 0.18), vec3(0.85, 0.82, 0.74), chk); float d = length(p - vec2(0.25 * sin(iTime), 0.0)); col = mix(col, vec3(1.0, 0.25, 0.15), smoothstep(0.42, 0.40, d)); float ring = abs(length(p) - 0.8); col = mix(col, vec3(0.1, 0.6, 1.0), smoothstep(0.03, 0.02, ring)); col = mix(col, vec3(1.0), smoothstep(0.012, 0.008, abs(p.x))); return col; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 p = (uv - 0.5) * 2.0; p.x *= iResolution.x / iResolution.y; float r2 = dot(p, p); float k = CA_STRENGTH * r2; vec3 col; col.r = scene(p * (1.0 + k)).r; col.g = scene(p).g; col.b = scene(p * (1.0 - k)).b; vec2 q = uv - 0.5; float vig = 1.0 - VIG_STRENGTH * smoothstep(0.15, 0.75, dot(q, q) * 2.0); col *= vig; fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Film grain synthesis](https://texelatlas.vercel.app/t/film-grain-synthesis.md): The lens pass runs first and grain is layered on top at the end. ## Sources 1. [primary] Unity-Technologies (2016) Unity-Technologies/PostProcessing. https://github.com/Unity-Technologies/PostProcessing License: NOASSERTION. (verified via github on 2026-11-29) 2. [implementation] pmndrs (2015) pmndrs/postprocessing. https://github.com/pmndrs/postprocessing License: Zlib. (verified via github on 2026-11-29) 3. [implementation] mattdesl (2015) mattdesl/three-vignette-background. https://github.com/mattdesl/three-vignette-background License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Chromatic aberration and vignette." https://texelatlas.vercel.app/t/chromatic-aberration/ (accessed 2026-12-01). --- id: "clay" title: "CLAY" domain: "genai" stage: "generation" realtime: "offline" platforms: [cuda, python] year_introduced: 2024 inputs: [text-prompt, ldr-image] outputs: [mesh, material-params] style: "both" dynamic: "static" cost: "offline" authority: "Zhang et al., 2024" url: "https://texelatlas.vercel.app/t/clay/" sources_verified_at: "2026-11-29" --- # CLAY (Zhang et al., 2024) > A large controllable 3D generator that trains a multi-resolution geometry VAE and a diffusion transformer on 3D data, then adds a material-diffusion stage for PBR textures. ## Reach for it when - generate high quality 3d assets with pbr textures from text - want a native 3d diffusion model with material output - need reference for large controllable 3d generators - generated geometry should come with roughness and metallic maps ## How it works Geometry is encoded from sampled surface points into a compact latent with a VAE, and a diffusion transformer learns to generate that latent from text, images, point clouds, voxels or bounding boxes, giving several control channels. After the shape is decoded and meshed, a second diffusion model that works on multi-view renders generates PBR material maps (albedo, roughness, metallic) and projects them into UV space. The paper stresses a data-curation and scale recipe: the quality gain comes from large cleaned 3D data and model capacity rather than a new loss. ## When to use it Choose it as the reference for native-3D latent diffusion with PBR output, noting that I found a paper but no public repository or weights. Prefer open pipelines [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md), [TRELLIS.2 (O-Voxel structured latents)](https://texelatlas.vercel.app/t/trellis-2.md) or [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) when you need runnable code. ## Cost offline — No public weights or repository found, so no inference cost data. Measured GPU Weight: 15.81× baseline (moderate) — 0.5202 ms median / 0.5426 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.56× baseline (moderate) — 0.2156 ms median (2.41× faster on L4). Ampere A100 scaling: 10.85× baseline (moderate) — 0.3126 ms median (1.66× faster on A100). ## Failure modes - Cannot be reproduced locally: closed model and data - PBR maps are inferred from images and can contradict the real material - Mesh topology is dense and unstructured - Prompt control is coarse for fine part-level edits ## Dataflow - Inputs: text-prompt, ldr-image - Outputs: mesh, material-params - Platforms: cuda, python ## Presets ### CLAY — noisy 3D DiT latent geometry (left) vs denoised PBR-textured hero asset (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DENOISE": 0.76, "P_PBR_METAL": 0.65, "P_ROT_SPEED": 0.55, "P_SPLIT": 0.46 } ``` ```glsl const float P_DENOISE = 0.76; // P DiT Denoise [0.05, 1.0, 0.02] const float P_PBR_METAL = 0.65; // P PBR Metallic [0.0, 1.0, 0.02] const float P_ROT_SPEED = 0.55; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.46; // P Latent / PBR Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } // Multi-resolution sculpted armored helmet/relic generated by CLAY DiT float mapRelic(vec3 p, float spin, float noiseAmt) { vec3 q = p; q.xz = rot2(spin * 0.48) * q.xz; float dome = length(q * vec3(1.0, 0.85, 1.05)) - 0.56; float visor = sdBox(q - vec3(0.0, 0.06, 0.42), vec3(0.36, 0.11, 0.25)) - 0.04; float crest = sdBox(q - vec3(0.0, 0.54, 0.0), vec3(0.07, 0.24, 0.44)) - 0.03; float d = min(max(dome, -visor), crest); // Multi-resolution DiT denoising perturbation (vanishes as P_DENOISE -> 1) float n = sin(q.x * 13.0) * cos(q.y * 13.0) * sin(q.z * 13.0) + 0.5 * sin(q.x * 23.0 + q.z * 19.0); return (d + n * 0.085 * noiseAmt) * 0.78; } vec3 calcNormal(vec3 p, float spin, float noiseAmt) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRelic(p + e.xyy, spin, noiseAmt) - mapRelic(p - e.xyy, spin, noiseAmt), mapRelic(p + e.yxy, spin, noiseAmt) - mapRelic(p - e.yxy, spin, noiseAmt), mapRelic(p + e.yyx, spin, noiseAmt) - mapRelic(p - e.yyx, spin, noiseAmt) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isPBR = screenX >= split; float denoise = clamp(P_DENOISE, 0.0, 1.0); float metal = clamp(P_PBR_METAL, 0.0, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0); // Left shows coarse/noisy latent stage; right shows denoised PBR stage float noiseAmt = isPBR ? (1.0 - denoise) * 0.25 : (1.15 - 0.65 * denoise); vec3 ro = vec3(0.0, 0.10, 2.28); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.028, 0.032, 0.048), vec3(0.072, 0.082, 0.118), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapRelic(ro + rd * t, spin, noiseAmt); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin, noiseAmt); vec3 objP = p; objP.xz = rot2(spin * 0.48) * objP.xz; vec3 l1 = normalize(vec3(0.60, 0.80, 0.55)); vec3 l2 = normalize(vec3(-0.75, 0.15, 0.45)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 h1 = normalize(l1 - rd); float spec = pow(max(dot(n, h1), 0.0), isPBR ? 56.0 : 12.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 4.0); if (!isPBR) { // Left: CLAY untextured clay-geometry latent + DiT token lattice lines vec3 clayCol = vec3(0.68, 0.65, 0.62) * (0.28 + 0.72 * diff1 + 0.22 * diff2); vec3 tokGrid = abs(fract(objP * 8.0) - 0.5); float tokLine = smoothstep(0.06, 0.015, min(tokGrid.x, min(tokGrid.y, tokGrid.z))); clayCol = mix(clayCol, vec3(0.28, 0.82, 0.98), tokLine * 0.42); col = clayCol + vec3(0.85) * spec * 0.18; } else { // Right: Stage-2 PBR material diffusion (anodized dark bronze + brushed gold crest + glowing visor) float isCrest = smoothstep(0.36, 0.48, objP.y) * smoothstep(0.16, 0.08, abs(objP.x)); float isVisor = smoothstep(0.14, 0.08, abs(objP.y - 0.06)) * smoothstep(0.28, 0.36, objP.z); vec3 baseAlb = mix(vec3(0.24, 0.28, 0.36), vec3(0.92, 0.68, 0.26), isCrest); vec3 f0 = mix(vec3(0.04), baseAlb, metal); vec3 F = f0 + (1.0 - f0) * fres; vec3 envRef = mix(vec3(0.12, 0.22, 0.36), vec3(0.95, 0.85, 0.72), smoothstep(-0.3, 0.6, reflect(rd, n).y)); col = baseAlb * (1.0 - metal * 0.65) * (0.24 + 0.78 * diff1 + 0.25 * diff2) + F * (envRef * 0.58 + vec3(1.0, 0.95, 0.88) * spec * 1.15); col = mix(col, vec3(0.18, 0.92, 1.0) * 1.45, isVisor); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Longwen Zhang, Ziyu Wang, Qixuan Zhang, Qiwei Qiu, Anqi Pang, Haoran Jiang, Wei Yang, Lan Xu, Jingyi Yu (2024) CLAY: A Controllable Large-scale Generative Model for Creating High-quality 3D Assets. ACM Transactions on Graphics. https://doi.org/10.1145/3658146 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "CLAY." https://texelatlas.vercel.app/t/clay/ (accessed 2026-12-01). --- id: "clearcoat-layer" title: "Clearcoat layer" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2012 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Burley" url: "https://texelatlas.vercel.app/t/clearcoat-layer/" sources_verified_at: "2026-11-29" --- # Clearcoat layer (Burley) > A second, thin dielectric specular lobe on top of a base material, used for car paint, lacquered wood and carbon fibre. Cheaply approximated as an extra GGX lobe with fixed IOR 1.5 and energy-weighted base. ## Reach for it when - car paint needs a glossy layer over a base color - second sharper highlight on top of rough surface - lacquered wood or carbon fiber looks single layered - varnish reflections independent of underlying bump detail ## How it works A clearcoat models a thin transparent coating over the base layer. The coat uses its own roughness and its own, usually unperturbed, geometric normal, and a dielectric Fresnel with F0 about 0.04. The base layer is attenuated by the energy the coat reflects: base *= (1 - F_coat), plus optionally tinted by absorption through the coat for long path lengths at grazing angles. Disney added it as a fixed secondary GGX lobe with limited gloss range; Filament and glTF's KHR_materials_clearcoat follow the same idea, while OpenPBR defines a physically stacked coat with refraction of the base lobe and inter-layer scattering. Environment lighting samples a separate reflection probe lookup for the coat roughness. ## When to use it Choose it for automotive paint, varnished wood, wet or lacquered surfaces and carbon fibre. Prefer [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) when you need physically correct layering with colour and transmission, and [Thin-film iridescence](https://texelatlas.vercel.app/t/thin-film-iridescence.md) for coloured interference coatings. Prefer plain roughness changes when the coat is not visibly separate. ## Cost cheap — One extra specular lobe and a second IBL fetch per pixel. Measured GPU Weight: 2.21× baseline (light) — 0.0727 ms median / 0.0738 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.91× baseline (feather) — 0.0304 ms median (2.39× faster on L4). Ampere A100 scaling: 1.42× baseline (feather) — 0.041 ms median (1.77× faster on A100). ## Failure modes - Cheap implementations ignore refraction of base light through the coat, so the base looks too bright and saturated - Coat sharing the base normal map shows flake or texture detail through a surface that should be smooth - Double IBL lookups raise bandwidth on mobile - Energy conservation is approximate when the coat tint or roughness is high ## Engine support - babylonjs: builtin — `pbrMaterial.clearCoat.isEnabled = true (PBRClearCoatConfiguration)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrClearCoatConfiguration.ts, checked 2026-12-01) - blender: builtin — `Principled BSDF > Coat (Weight, Roughness, IOR, Tint)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.clearcoat_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: builtin — `material.clearcoat = 1 (MeshPhysicalMaterial)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshPhysicalMaterial.js, checked 2026-12-01) - unity: builtin — `Lit > Surface Options > Clear Coat` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/snippets/shader-properties/surface-options/clear-coat.md, checked 2026-12-01) — HDRP Lit and URP Complex Lit. - unreal: builtin — `Material > Shading Model = Clear Coat (or Substrate Slab Haziness/second specular)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/shading-models-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Red car paint, glossy coat (three-material; rendered 2026-11-29) ```json { "color": "#8a0b0b", "roughness": 0.4, "metalness": 0.6, "clearcoat": 1, "clearcoatRoughness": 0.05 } ``` Attribution: written for this index; sensible defaults, not measured ## Combination ideas - [Dual-normal varnished surfaces from photometric stereo capture](https://texelatlas.vercel.app/ideas/photometric-micro-normals-clearcoat/) ## Sources 1. [primary] Brent Burley Physically Based Shading at Disney. SIGGRAPH 2012 Course. https://disneyanimation.com/publications/physically-based-shading-at-disney (verified via http on 2026-11-29) 2. [tutorial] Romain Guy, Mathias Agopian Filament: Physically based rendering (image based lights section). google.github.io. https://google.github.io/filament/Filament.html (verified via http on 2026-11-29) 3. [implementation] google (2018) google/filament. https://github.com/google/filament License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Clearcoat layer." https://texelatlas.vercel.app/t/clearcoat-layer/ (accessed 2026-12-01). --- id: "climbing-plants-simulation" title: "Interactive Climbing Plant Modeling" aliases: [ivy growth, vine simulation] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, desktop-gpu] year_introduced: 2017 inputs: [mesh] outputs: [curves, mesh] style: "photoreal" dynamic: "both" cost: "offline" authority: "Hädrich et al., 2017" url: "https://texelatlas.vercel.app/t/climbing-plants-simulation/" sources_verified_at: "2026-11-29" --- # Interactive Climbing Plant Modeling (Hädrich et al., 2017) > Simulates climbing vines such as ivy growing over scene geometry, using a physically motivated stem model with attachment, free-hanging behaviour and user guidance. ## Reach for it when - need ivy to grow across buildings and ruins - vines should follow and cling to existing geometry - dress sculptures with hanging creepers - hand-placing vines on walls takes forever ## How it works Each plant is a tree of stem segments that grow at their tips toward light-like or user-chosen goals. A tip senses the scene surface; when it touches geometry it attaches and follows the surface, while tips that lose contact may hang under gravity or search for a new support. Stem mechanics treat the plant as a flexible rod with bending resistance so free segments sag and swing. The authors expose artist controls (growth seeds, directional hints, painting areas to cover) and keep the simulation interactive so the user can steer growth on complex scenes, then instantiate leaves along stems. It is an agent-based growth model constrained by collision with the scene. ## When to use it Choose it for dressing buildings, ruins and sculptures with convincing ivy or vines, where coverage should depend on the actual geometry. Prefer [Space Colonization Tree Modeling](https://texelatlas.vercel.app/t/space-colonization-trees.md) for free-standing trees, [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) for stylised plants, and [Plant Ecosystem Distribution Simulation](https://texelatlas.vercel.app/t/ecosystem-plant-distribution.md) when you need to place many plants across a landscape rather than grow one on a wall. ## Cost offline — Per-step collision and attachment queries against scene geometry; interactive in the paper's setup, minutes for dense coverage of large scenes. Measured GPU Weight: 98.12× baseline (extreme) — 3.2283 ms median / 3.5529 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 82.64× baseline (extreme) — 1.314 ms median (2.46× faster on L4). Ampere A100 scaling: 63.66× baseline (extreme) — 1.8335 ms median (1.76× faster on A100). ## Failure modes - Stems penetrate thin geometry or clump in concave corners - Dense leaf instancing is expensive and often needs LOD or impostors - Result depends on the seed placement and guidance, so unguided runs can leave bare areas - Reference code is not widely available, so replicating the exact behaviour requires reimplementation ## Dataflow - Inputs: mesh - Outputs: curves, mesh - Platforms: cpu, desktop-gpu ## Presets ### Climbing Plant Simulation — clinging vine tendrils & anchor nodes (left) vs sunlit ivy foliage on stone pillar (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VINE_GROW": 0.86, "P_LEAF_DENS": 0.9, "P_ROT_SPEED": 0.48, "P_SPLIT": 0.46 } ``` ```glsl const float P_VINE_GROW = 0.86; // P Climb Height [0.2, 1.0, 0.02] const float P_LEAF_DENS = 0.90; // P Leaf Density [0.1, 1.3, 0.04] const float P_ROT_SPEED = 0.48; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.46; // P Stems / Ivy Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Evaluate helical thigmotropic vine clinging to stone column (radius 0.42) // Returns vec3(distToVineStem, distToLeafBlade, climbMask) vec3 evalClimbingVine(vec3 p, float growH, float leafDens) { float r = length(p.xz); float ang = atan(p.z, p.x); float yMax = mix(-0.62, 0.72, growH); float grown = smoothstep(yMax + 0.08, yMax - 0.08, p.y); // 3 phototropic climbing primary vines spiraling upward around the cylinder surface float dStem = 1e5; float dLeaf = 1e5; for (int v = 0; v < 3; v++) { float fv = float(v); float phase = fv * 2.094395 + p.y * (3.8 + fv * 0.45) + 0.25 * sin(p.y * 5.0 + fv); float dAng = atan(sin(ang - phase), cos(ang - phase)); float arcD = abs(dAng) * 0.42; float radD = abs(r - 0.432); float dV = length(vec2(arcD, radD)) - 0.018; dStem = min(dStem, dV); // Alternating botanical ivy leaves sprouting off the clinging vine stem! float leafRow = floor(p.y * 11.0 + fv * 3.1); float yLocal = fract(p.y * 11.0 + fv * 3.1) - 0.5; float side = (mod(leafRow, 2.0) > 0.5) ? 1.0 : -1.0; float leafAngOff = dAng - side * 0.16; vec2 lUV = vec2(leafAngOff * 0.42, yLocal / 11.0); // Heart/ivy-lobe leaf silhouette float rL = length(lUV * vec2(1.0, 1.25)); float lobe = 0.052 * (0.78 + 0.22 * cos(atan(lUV.y, lUV.x) * 3.0)) * leafDens; float dL = max(rL - lobe, abs(r - 0.455) - 0.018); dLeaf = min(dLeaf, dL); } return vec3(dStem, dLeaf, grown); } // Combined scene SDF: stone column (mat=1), vine stem (mat=2), ivy leaves (mat=3) vec2 mapScene(vec3 p, float growH, float leafDens, bool withLeaves) { // Fluted ancient stone column + capital float ang = atan(p.z, p.x); float dCol = max(length(p.xz) - (0.42 - 0.01 * cos(ang * 12.0)), abs(p.y) - 0.78); vec2 res = vec2(dCol, 1.0); vec3 vine = evalClimbingVine(p, growH, leafDens); if (vine.z > 0.05) { float dS = mix(1.0, vine.x, vine.z); if (dS < res.x) res = vec2(dS, 2.0); if (withLeaves) { float dL = mix(1.0, vine.y, vine.z); if (dL < res.x) res = vec2(dL, 3.0); } } return vec2(res.x * 0.78, res.y); } vec3 calcNormal(vec3 p, float growH, float leafDens, bool withLeaves) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy, growH, leafDens, withLeaves).x - mapScene(p - e.xyy, growH, leafDens, withLeaves).x, mapScene(p + e.yxy, growH, leafDens, withLeaves).x - mapScene(p - e.yxy, growH, leafDens, withLeaves).x, mapScene(p + e.yyx, growH, leafDens, withLeaves).x - mapScene(p - e.yyx, growH, leafDens, withLeaves).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool withLeaves = screenX >= split; float growH = clamp(P_VINE_GROW, 0.15, 1.0); float leafDens = clamp(P_LEAF_DENS, 0.1, 1.4); float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.45; vec3 ro = vec3(0.0, 0.08, 2.22); vec3 rd = normalize(vec3(uv, -1.52)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 col = mix(vec3(0.032, 0.042, 0.062), vec3(0.085, 0.115, 0.165), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; vec2 hit = vec2(1e5, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t, growH, leafDens, withLeaves); if (h.x < 0.0022) { hit = vec2(t, h.y); break; } t += h.x; if (t > 5.0) break; } if (hit.x < 1e4) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p, growH, leafDens, withLeaves); vec3 l1 = normalize(vec3(0.62, 0.78, 0.52)); vec3 l2 = normalize(vec3(-0.68, 0.18, -0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 28.0); vec3 alb; if (hit.y < 1.5) { // Limestone column float grain = 0.5 + 0.5 * sin(p.y * 18.0 + sin(p.x * 12.0)); alb = mix(vec3(0.60, 0.56, 0.50), vec3(0.76, 0.72, 0.64), grain); } else if (hit.y < 2.5) { // Woody climbing stem + bright cyan thigmotropic anchor nodes on left side! alb = vec3(0.30, 0.24, 0.14); if (!withLeaves) { float anchor = smoothstep(0.78, 0.96, sin(p.y * 42.0)); alb = mix(vec3(0.24, 0.86, 0.58), vec3(0.98, 0.82, 0.24), anchor); } } else { // Lush translucent sunlit ivy leaves float leafVar = 0.5 + 0.5 * sin(p.y * 24.0 + p.x * 18.0); alb = mix(vec3(0.12, 0.42, 0.14), vec3(0.42, 0.72, 0.18), leafVar); } col = alb * (0.24 + 0.84 * diff1 + 0.24 * diff2) + vec3(0.96, 0.98, 0.90) * spec * (hit.y > 2.5 ? 0.36 : 0.14); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Overgrown grammar cities](https://texelatlas.vercel.app/ideas/ivy-on-grammar-architecture/) ## Sources 1. [primary] Torsten Hädrich, Bedrich Benes, Oliver Deussen, Sören Pirk (2017) Interactive Modeling and Authoring of Climbing Plants. Computer Graphics Forum. https://doi.org/10.1111/cgf.13106 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Interactive Climbing Plant Modeling." https://texelatlas.vercel.app/t/climbing-plants-simulation/ (accessed 2026-12-01). --- id: "cloth-simulation-filter" title: "Cloth Simulation Filter (CSF) for LiDAR Ground Filtering" aliases: [CSF] domain: "capture" stage: "capture" realtime: "offline" platforms: [cpu, python] year_introduced: 2016 inputs: [point-cloud] outputs: [point-cloud, heightfield] style: "photoreal" dynamic: "static" cost: "offline" authority: "Zhang et al., 2016" url: "https://texelatlas.vercel.app/t/cloth-simulation-filter/" sources_verified_at: "2026-11-29" --- # Cloth Simulation Filter (CSF) for LiDAR Ground Filtering (Zhang et al., 2016) > Separates ground from non-ground points in an airborne LiDAR cloud by inverting the cloud and draping a simulated cloth over it; points near the cloth are ground. ## Reach for it when - separate ground points from trees and buildings in lidar - need a terrain model from an airborne point cloud - remove objects to get bare earth from scan data - classify ground versus non-ground in photogrammetry points - ground extraction with few parameters to tune ## How it works The point cloud is flipped upside down, and a regular grid of cloth particles, connected by springs, is dropped onto it. Each particle moves under gravity until it would touch a LiDAR point beneath it, at which point it stops. Neighbouring particles are pulled toward each other by internal forces that depend on the cloth rigidness, which stops the cloth from falling into small gaps or following buildings and trees. After a fixed number of iterations the cloth approximates the terrain surface. Original points are classified as ground when their distance to the cloth is below a threshold. Only a few parameters are needed: grid resolution, rigidness, time step and the distance threshold. ## When to use it Choose it when you need a ground/non-ground split of airborne or terrestrial LiDAR or photogrammetric point clouds, for DTM extraction or object removal. Prefer progressive morphological or TIN-densification filters for dense, steep, urban terrain with hand-tuned parameters, and learned segmenters when labels exist. ## Cost offline — Roughly linear in number of points and grid cells; runs on CPU in seconds to minutes for tiles. Measured GPU Weight: 10.16× baseline (moderate) — 0.3344 ms median / 0.3355 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.32× baseline (moderate) — 0.1323 ms median (2.53× faster on L4). Ampere A100 scaling: 7.57× baseline (moderate) — 0.2179 ms median (1.53× faster on A100). ## Failure modes - Steep slopes and terraces get classified as non-ground if rigidness is too high - Low vegetation and cars are retained as ground when the distance threshold is too loose - Large flat roofs may be partly absorbed as ground with a soft cloth - Grid resolution too coarse smooths away small terrain features like ditches ## Dataflow - Inputs: point-cloud - Outputs: point-cloud, heightfield - Platforms: cpu, python ## Presets ### CSF default parameters (json-params; parameter preset) ```json { "cloth_resolution": 0.5, "rigidness": 3, "time_step": 0.65, "class_threshold": 0.5, "iterations": 500, "slope_smooth": true } ``` Attribution: Parameter names follow jianboqi/CSF (Apache-2.0); values are the library's commonly used defaults, written for this index. ### Cloth Simulation Filter (CSF) — inverted LiDAR cloth drape (left) vs classified ground & objects (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RIGIDNESS": 0.72, "P_CLASS_THRESH": 0.07, "P_SWEEP": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_RIGIDNESS = 0.72; // P Cloth Rigidness [0.1, 1.0, 0.02] const float P_CLASS_THRESH = 0.07; // P Ground Threshold [0.02, 0.16, 0.005] const float P_SWEEP = 0.45; // P Scan Pan [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Inverted CSF / Class [0.0, 1.0, 0.02] float hash11(float x) { x = fract(x * 0.1031); x *= x + 33.33; x *= x + x; return fract(x); } // True rolling ground elevation y_ground(x) float groundY(float x) { return -0.18 + 0.09 * sin(x * 3.2) + 0.045 * cos(x * 6.5 + 0.7); } // Airborne LiDAR surface height including buildings & tree crowns above the ground float lidarTopY(float x) { float g = groundY(x); // Building 1 if (abs(x + 0.42) < 0.13) return g + 0.28; // Building 2 (stepped roof) if (abs(x - 0.36) < 0.15) return g + 0.24 + 0.06 * step(0.32, x); // Tree canopy 1 float t1 = abs(x + 0.08); if (t1 < 0.11) return g + 0.22 * sqrt(max(1.0 - (t1 / 0.11) * (t1 / 0.11), 0.0)) + 0.05 * sin(x * 80.0); // Tree canopy 2 float t2 = abs(x - 0.66); if (t2 < 0.09) return g + 0.19 * sqrt(max(1.0 - (t2 / 0.09) * (t2 / 0.09), 0.0)); return g; } // Simulated draped cloth height over inverted LiDAR (stiff cloth bridges over inverted buildings/trees!) float clothY(float x, float rigid) { float g = groundY(x); // Low rigidness lets cloth sag slightly into building/tree pits; high rigidness stays tightly bridged on ground float sag = (1.0 - rigid) * 0.12; float b1 = smoothstep(0.14, 0.0, abs(x + 0.42)) * sag; float b2 = smoothstep(0.16, 0.0, abs(x - 0.36)) * sag; float tr = smoothstep(0.12, 0.0, abs(x + 0.08)) * sag * 0.8; return g + (b1 + b2 + tr); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isInverted = screenX < split; float rigid = clamp(P_RIGIDNESS, 0.05, 1.0); float thresh = clamp(P_CLASS_THRESH, 0.015, 0.20); float pan = sin(iTime * 0.45 * max(P_SWEEP, 0.0)) * 0.16; // Blueprint engineering grid backdrop vec3 col = mix(vec3(0.024, 0.034, 0.056), vec3(0.054, 0.072, 0.112), smoothstep(-0.5, 0.5, uv.y)); vec2 g1 = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.044) * smoothstep(0.035, 0.008, min(g1.x, g1.y)); // Left half shows the INVERTED LiDAR cloud (y -> -y) with gravity cloth draping down from above! // Right half shows the UPRIGHT classified point cloud (cyan = ground, amber/green = non-ground) float xWorld = uv.x + pan; float yEval = isInverted ? -uv.y : uv.y; float cY = clothY(xWorld, rigid); float dCloth = abs(yEval - cY); // Draw threshold tolerance band around the simulated cloth surface float inBand = smoothstep(thresh + 0.004, thresh - 0.004, abs(yEval - cY)); col = mix(col, vec3(0.12, 0.52, 0.68), inBand * 0.22); // Draw the cloth curve + cloth particle nodes float clothLine = smoothstep(0.008, 0.002, dCloth); float nodeX = fract(xWorld * 18.0 + 0.5) - 0.5; float dNode = length(vec2(nodeX / 18.0, yEval - cY)); float clothNode = smoothstep(0.012, 0.005, dNode); vec3 clothCol = isInverted ? vec3(0.98, 0.78, 0.24) : vec3(0.24, 0.88, 0.96); col = mix(col, clothCol, max(clothLine * 0.9, clothNode)); // Render discrete airborne LiDAR return points sampled along x float stepX = 0.022; float ix = floor(xWorld / stepX); for (int k = -1; k <= 1; k++) { float cx = (ix + float(k) + 0.5) * stepX; float topY = lidarTopY(cx); float gY = groundY(cx); float clY = clothY(cx, rigid); // Primary LiDAR top return point float jit = (hash11(ix + float(k) * 1.7) - 0.5) * 0.012; float py = topY + jit; float distPt = length(vec2(xWorld - cx, yEval - py)); float ptMask = smoothstep(0.012, 0.004, distPt); bool isGroundPt = abs(py - clY) < thresh; vec3 ptCol = isGroundPt ? vec3(0.18, 0.90, 0.86) // Ground point : (py - gY > 0.23 ? vec3(0.98, 0.44, 0.22) : vec3(0.42, 0.92, 0.34)); // Building vs tree col = mix(col, ptCol * 1.15, ptMask); // Vertical wall / trunk returns for buildings & canopies if (topY - gY > 0.08) { for (int r = 1; r <= 3; r++) { float ry = mix(gY + 0.03, topY - 0.02, float(r) / 4.0) + (hash11(cx * 31.0 + float(r)) - 0.5) * 0.015; float dR = length(vec2(xWorld - cx, yEval - ry)); float mR = smoothstep(0.009, 0.003, dR); bool rGrd = abs(ry - clY) < thresh; vec3 rCol = rGrd ? vec3(0.18, 0.90, 0.86) : vec3(0.95, 0.58, 0.22); col = mix(col, rCol, mR * 0.85); } } } // Gravity arrow indicator on left inverted side if (isInverted) { vec2 aP = uv - vec2(-0.34, 0.30); float shaft = smoothstep(0.005, 0.001, abs(aP.x)) * smoothstep(0.07, 0.06, abs(aP.y)); float head = smoothstep(0.006, 0.001, abs(abs(aP.x) - (aP.y + 0.075) * 0.65)) * step(aP.y, -0.02) * step(-0.08, aP.y); col += vec3(0.98, 0.78, 0.24) * max(shaft, head) * 0.85; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md): Dense photogrammetric point clouds are filtered by CSF to extract a terrain model. ## Combination ideas - [Regrow a photographed site](https://texelatlas.vercel.app/ideas/captured-site-revegetation/) ## Sources 1. [primary] Wuming Zhang, Jianbo Qi, Peng Wan, Hongtao Wang, Donghui Xie, Xiaoyan Wang, Guangjian Yan (2016) An Easy-to-Use Airborne LiDAR Data Filtering Method Based on Cloth Simulation. Remote Sensing. https://doi.org/10.3390/rs8060501 (verified via crossref on 2026-11-29) 2. [implementation] jianboqi (2016) jianboqi/CSF. https://github.com/jianboqi/CSF License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Cloth Simulation Filter (CSF) for LiDAR Ground Filtering." https://texelatlas.vercel.app/t/cloth-simulation-filter/ (accessed 2026-12-01). --- id: "clustered-forward-shading" title: "Clustered forward shading" aliases: [clustered shading, clustered forward] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity] year_introduced: 2012 inputs: [depth, mesh] outputs: [radiance] style: "both" dynamic: "both" cost: "medium" authority: "Olsson et al., 2012" url: "https://texelatlas.vercel.app/t/clustered-forward-shading/" sources_verified_at: "2026-11-29" --- # Clustered forward shading (Olsson et al., 2012) > Divide the view frustum into a 3D grid of clusters, assign each light to the clusters it overlaps, and let each shaded fragment loop only over its cluster's lights. ## Reach for it when - too many dynamic lights tank the frame rate - forward renderer needs hundreds of point lights - need transparent objects lit by many lights - deferred g-buffer is too heavy for msaa or vr ## How it works The frustum is sliced into screen tiles and depth slices, usually exponential in depth. A compute pass tests each light's bounding volume against cluster bounds and writes light indices into per-cluster lists, optionally restricted to clusters containing visible geometry. In the fragment shader, the pixel's position and depth give its cluster id; the shader reads that list and accumulates lighting. Unlike 2D tiling, depth splits mean far-apart surfaces at the same pixel do not share a long list, which handles depth discontinuities and transparent objects. ## When to use it Choose it for many dynamic lights with forward rendering, MSAA or transparencies. Prefer [Tiled deferred shading](https://texelatlas.vercel.app/t/tiled-deferred-shading.md) when deferred is already in place and depth ranges per tile are tight. Prefer a handful of per-object lights when light count stays small. ## Cost medium — Cost depends on lights per cluster and cluster count; the build pass is cheap relative to shading. Measured GPU Weight: 9.75× baseline (moderate) — 0.3208 ms median / 0.3384 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 9.94× baseline (moderate) — 0.1581 ms median (2.03× faster on L4). Ampere A100 scaling: 6.44× baseline (moderate) — 0.1855 ms median (1.73× faster on A100). ## Failure modes - Large lights fall in many clusters, bloating lists and overflowing fixed list capacity - Lights near cluster boundaries cause popping if bounds are too tight - Slice distribution mismatched to scene depth leaves clusters under- or over-populated - Per-fragment light loops diverge across a wavefront ## Engine support - babylonjs: builtin — `new BABYLON.ClusteredLightContainer('c', lights, scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Clustered/clusteredLightContainer.ts, checked 2026-12-01) - godot: builtin — `Project Settings > Rendering > Renderer > Rendering Method = forward_plus` (evidence: https://github.com/godotengine/godot-docs/blob/master/tutorials/rendering/renderers.rst, checked 2026-12-01) - threejs: official — `import { ClusteredLighting } from 'three/addons/lighting/ClusteredLighting.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/lighting/ClusteredLighting.js, checked 2026-12-01) — WebGPURenderer. - unity: builtin — `URP Renderer > Rendering Path = Forward+` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs, checked 2026-12-01) — URP Forward+; HDRP uses its own tiled/cluster light list. - unreal: builtin — `Project Settings > Rendering > Forward Renderer > Forward Shading (with MSAA support)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/forward-shading-renderer-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, mesh - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity ## Presets ### Toy top-down frustum clusters with per-cluster light counts (glsl-fragment; rendered 2026-11-29) ```json { "LIGHTS": 14, "SLICES": 8, "BINS": 8, "HALF_FOV_TAN": 0.8 } ``` ```glsl // Toy top-down view of a frustum cut into clusters (angular bins x exponential depth slices); colour = lights overlapping each cluster. const int LIGHTS = 14; const int SLICES = 8; const int BINS = 8; const float NEAR = 0.1, FAR = 10.0; const float HALF_FOV_TAN = 0.8; void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 v = vec2((uv.x - 0.5) * 2.0 * 3.2, 0.0); // view-space x float z = 0.02 + uv.y * 0.0; // placeholder, set below // map screen y to depth with exponential spacing so slice cells look equal height float sl = uv.y * float(SLICES); z = NEAR * pow(FAR / NEAR, sl / float(SLICES)); v.x = (uv.x - 0.5) * 2.0 * z * HALF_FOV_TAN; float bin = floor(uv.x * float(BINS)); float s = floor(sl); float z0 = NEAR * pow(FAR / NEAR, s / float(SLICES)), z1 = NEAR * pow(FAR / NEAR, (s + 1.0) / float(SLICES)); float t0 = (bin / float(BINS) - 0.5) * 2.0 * HALF_FOV_TAN, t1 = ((bin + 1.0) / float(BINS) - 0.5) * 2.0 * HALF_FOV_TAN; vec2 lo = vec2(min(min(t0 * z0, t0 * z1), min(t1 * z0, t1 * z1)), z0); vec2 hi = vec2(max(max(t0 * z0, t0 * z1), max(t1 * z0, t1 * z1)), z1); int cnt = 0; float lit = 0.0; float dm = 1e9; for (int i = 0; i < LIGHTS; i++) { float f = float(i); float lz = NEAR * pow(FAR / NEAR, fract(f * 0.381 + 0.1 * sin(iTime * 0.5 + f)) * 0.95 + 0.03); float lx = lz * HALF_FOV_TAN * (2.0 * fract(f * 0.618 + 0.2) - 1.0) * 0.9; float r = 0.35 * lz + 0.1; vec2 c = vec2(lx, lz); if (distance(clamp(c, lo, hi), c) < r) cnt++; lit += smoothstep(r, 0.0, distance(vec2(v.x, z), c)); dm = min(dm, abs(distance(vec2(v.x, z), c) - r) / z); } float x = float(cnt) / 5.0; vec3 heat = clamp(vec3(1.5 * x, 1.5 - abs(3.0 * x - 1.5), 1.5 - 1.5 * x), 0.0, 1.0); vec3 col = mix(vec3(0.04, 0.05, 0.08), heat * 0.6, cnt > 0 ? 1.0 : 0.0); col += vec3(1.0, 0.9, 0.7) * lit * 0.15; vec2 g = fract(vec2(uv.x * float(BINS), sl)); col = mix(col, vec3(0.0), (g.x < 0.03 || g.y < 0.03) ? 0.6 : 0.0); col = mix(col, vec3(1.0), smoothstep(0.012, 0.004, dm) * 0.8); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Tiled deferred shading](https://texelatlas.vercel.app/t/tiled-deferred-shading.md) ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): A depth pre-pass used for cluster culling also feeds the pyramid used for object culling. ## Sources 1. [primary] Ola Olsson, Markus Billeter, Ulf Assarsson (2012) Tiled and clustered forward shading. ACM SIGGRAPH 2012 Posters on - SIGGRAPH '12. https://doi.org/10.1145/2343045.2343095 (verified via crossref on 2026-11-29) 2. [implementation] pezcode (2019) pezcode/Cluster. https://github.com/pezcode/Cluster License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Clustered forward shading." https://texelatlas.vercel.app/t/clustered-forward-shading/ (accessed 2026-12-01). --- id: "coacd-convex-decomposition" title: "CoACD Approximate Convex Decomposition" aliases: [CoACD, convex decomposition] domain: "geometry" stage: "geometry" realtime: "offline" platforms: [cpu, python, blender, unity] year_introduced: 2022 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "offline" authority: "Wei et al., 2022" url: "https://texelatlas.vercel.app/t/coacd-convex-decomposition/" sources_verified_at: "2026-11-29" --- # CoACD Approximate Convex Decomposition (Wei et al., 2022) > Splits a concave mesh into a small set of convex pieces for physics, choosing cuts by a collision-aware concavity measure and a tree search, so thin or interlocking parts stay faithful. ## Reach for it when - concave mesh collides badly in physics engine - need collision shapes for a complex rigid body - thin or interlocking parts lose shape in collision hulls - generated assets need physics proxies automatically ## How it works A concavity score measures how far a piece is from its convex hull, but unlike older volumetric measures it is computed from the boundary samples and checks whether the hull would collide with the other pieces (collision-aware). The mesh is recursively cut by planes: a Monte-Carlo tree search proposes planes among candidates, evaluates the concavity of the two resulting parts and picks the sequence of cuts that minimises a global score. Cuts stop once each part's concavity is below a threshold or a part count limit is reached. After cutting, small pieces can be merged if the merged hull remains within tolerance, and a hull simplification step reduces vertex count. The result is a set of convex hulls with limited overlap suitable for rigid body engines. ## When to use it Choose it to generate collision proxies for dynamic rigid bodies in physics engines, for robotics grasping and for generated assets. Prefer V-HACD style voxel methods when quick, noisy hulls suffice, a single [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md) triangle query for static scene queries, and hand-authored primitives when exactness matters (wheels, boxes). ## Cost offline — Search over cut planes takes seconds to minutes per mesh depending on quality settings. Measured GPU Weight: 31.24× baseline (heavy) — 0.9683 ms median / 1.0214 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 28.26× baseline (heavy) — 0.4493 ms median (2.16× faster on L4). Ampere A100 scaling: 19.2× baseline (moderate) — 0.553 ms median (1.75× faster on A100). ## Failure modes - Parts count explodes on organic or noisy meshes unless a limit is set - Convex hulls are fatter than the shape; thin walls and interior cavities are lost - Non-watertight inputs produce unreliable concavity estimates - Result depends on random tree search unless seeded ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, python, blender, unity ## Presets ### CoACD Convex Decomposition — single outer hull (left) vs collision-aware convex pieces (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_EXPLODE": 0.12, "P_HULL_ALPHA": 0.55, "P_ROT_SPEED": 0.7, "P_SPLIT": 0.48 } ``` ```glsl const float P_EXPLODE = 0.12; // P Piece Explode [0.0, 0.35, 0.01] const float P_HULL_ALPHA = 0.55; // P Outer Hull Leak [0.1, 0.9, 0.05] const float P_ROT_SPEED = 0.70; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Single Hull / CoACD [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } // Concave mechanical arch/table composed of 6 clean CoACD convex hull components! vec2 mapCoACD(vec3 p, float explode, float spin) { vec3 q = p; q.xz = rot2(spin * 0.58) * q.xz; q.yz = rot2(0.32) * q.yz; vec2 res = vec2(1e5, 0.0); // Piece 1: Top arch beam float d1 = sdBox(q - vec3(0.0, 0.38 + explode * 1.1, 0.0), vec3(0.68, 0.14, 0.24)) - 0.025; if (d1 < res.x) res = vec2(d1, 1.0); // Piece 2: Left pillar float d2 = sdBox(q - vec3(-0.54 - explode, -0.08, 0.0), vec3(0.14, 0.36, 0.24)) - 0.025; if (d2 < res.x) res = vec2(d2, 2.0); // Piece 3: Right pillar float d3 = sdBox(q - vec3(0.54 + explode, -0.08, 0.0), vec3(0.14, 0.36, 0.24)) - 0.025; if (d3 < res.x) res = vec2(d3, 3.0); // Piece 4: Left angled brace vec3 bL = q - vec3(-0.28 - explode * 0.5, 0.14 + explode * 0.4, 0.0); bL.xy = rot2(0.785) * bL.xy; float d4 = sdBox(bL, vec3(0.24, 0.08, 0.18)) - 0.02; if (d4 < res.x) res = vec2(d4, 4.0); // Piece 5: Right angled brace vec3 bR = q - vec3(0.28 + explode * 0.5, 0.14 + explode * 0.4, 0.0); bR.xy = rot2(-0.785) * bR.xy; float d5 = sdBox(bR, vec3(0.24, 0.08, 0.18)) - 0.02; if (d5 < res.x) res = vec2(d5, 5.0); // Piece 6: Lower base plinths (left & right feet) float d6 = sdBox(q - vec3(0.0, -0.48 - explode * 0.9, 0.0), vec3(0.76, 0.10, 0.30)) - 0.02; // Cut center gap so base itself is concave -> split into piece 6 (left foot) and piece 7 (right foot)! float dFootL = sdBox(q - vec3(-0.52 - explode, -0.48 - explode * 0.7, 0.0), vec3(0.24, 0.09, 0.30)) - 0.02; float dFootR = sdBox(q - vec3(0.52 + explode, -0.48 - explode * 0.7, 0.0), vec3(0.24, 0.09, 0.30)) - 0.02; if (dFootL < res.x) res = vec2(dFootL, 6.0); if (dFootR < res.x) res = vec2(dFootR, 7.0); return res; } // Single naive outer convex hull wrapping the entire concave arch (blocks the hollow archway!) float mapOuterHull(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.58) * q.xz; q.yz = rot2(0.32) * q.yz; return sdBox(q - vec3(0.0, -0.02, 0.0), vec3(0.76, 0.56, 0.30)) - 0.03; } vec3 calcNormal(vec3 p, float explode, float spin) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapCoACD(p + e.xyy, explode, spin).x - mapCoACD(p - e.xyy, explode, spin).x, mapCoACD(p + e.yxy, explode, spin).x - mapCoACD(p - e.yxy, explode, spin).x, mapCoACD(p + e.yyx, explode, spin).x - mapCoACD(p - e.yyx, explode, spin).x )); } vec3 pieceColor(float id) { if (id < 1.5) return vec3(0.18, 0.78, 0.88); if (id < 2.5) return vec3(0.96, 0.52, 0.22); if (id < 3.5) return vec3(0.24, 0.86, 0.54); if (id < 4.5) return vec3(0.96, 0.80, 0.22); if (id < 5.5) return vec3(0.72, 0.44, 0.96); if (id < 6.5) return vec3(0.94, 0.34, 0.58); return vec3(0.34, 0.62, 0.98); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isCoACD = screenX >= split; float explode = isCoACD ? clamp(P_EXPLODE, 0.0, 0.38) : 0.0; float hullAlpha = clamp(P_HULL_ALPHA, 0.1, 0.92); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.08, 2.68); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.025, 0.035, 0.056), vec3(0.068, 0.088, 0.138), smoothstep(-0.55, 0.55, uv.y)); // Trace concave mesh / CoACD convex pieces float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapCoACD(ro + rd * t, explode, spin); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, explode, spin); vec3 l1 = normalize(vec3(0.58, 0.84, 0.52)); vec3 l2 = normalize(vec3(-0.70, -0.25, 0.50)); float diff = max(dot(n, l1), 0.0) * 0.85 + max(dot(n, l2), 0.0) * 0.25; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 46.0); vec3 alb = isCoACD ? pieceColor(matId) : vec3(0.58, 0.64, 0.74); col = alb * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.45; } // On left side: overlay the single coarse convex hull wrapping & blocking the concavity! if (!isCoACD) { float tH = 0.0; bool hitH = false; for (int i = 0; i < 56; i++) { float dh = mapOuterHull(ro + rd * tH, spin); if (dh < 0.0025) { hitH = true; break; } tH += dh; if (tH > 8.0) break; } if (hitH) { vec3 ph = ro + rd * tH; vec2 e = vec2(0.003, 0.0); vec3 nh = normalize(vec3( mapOuterHull(ph + e.xyy, spin) - mapOuterHull(ph - e.xyy, spin), mapOuterHull(ph + e.yxy, spin) - mapOuterHull(ph - e.yxy, spin), mapOuterHull(ph + e.yyx, spin) - mapOuterHull(ph - e.yyx, spin) )); float fres = 0.25 + 0.75 * pow(1.0 - max(dot(nh, -rd), 0.0), 2.5); // Concavity error volume (where hull exists in front of empty archway!) glows warning red-orange bool isErrorGap = !hit || (tH < t - 0.05); vec3 hullCol = isErrorGap ? vec3(0.98, 0.22, 0.24) : vec3(0.95, 0.65, 0.22); float hatch = smoothstep(0.35, 0.65, sin((ph.x + ph.y) * 34.0)); col = mix(col, hullCol * (0.75 + 0.35 * hatch), clamp(hullAlpha * (0.45 + 0.55 * fres), 0.18, 0.85)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Manifold Mesh Booleans](https://texelatlas.vercel.app/t/mesh-boolean-manifold.md): Boolean cuts split the mesh along candidate planes. ## Combination ideas - [Concavity-aware deformable clusters via CoACD and shape matching](https://texelatlas.vercel.app/ideas/coacd-cluster-shape-matching/) - [Captured rooms you can bump into](https://texelatlas.vercel.app/ideas/walkable-captured-scenes/) ## Sources 1. [primary] Xinyue Wei, Minghua Liu, Zhan Ling, Hao Su (2022) Approximate convex decomposition for 3D meshes with collision-aware concavity and tree search. ACM Transactions on Graphics. https://doi.org/10.1145/3528223.3530103 (verified via doi.org on 2026-11-29) 2. [implementation] SarahWeiii (2022) SarahWeiii/CoACD. https://github.com/SarahWeiii/CoACD License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "CoACD Approximate Convex Decomposition." https://texelatlas.vercel.app/t/coacd-convex-decomposition/ (accessed 2026-12-01). --- id: "contact-shadows" title: "Screen-Space Contact Shadows" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2016 inputs: [depth, normals] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Tamás & Heisenberger, 2018" url: "https://texelatlas.vercel.app/t/contact-shadows/" sources_verified_at: "2026-11-29" --- # Screen-Space Contact Shadows (Tamás & Heisenberger, 2018) > A short depth-buffer ray march toward the light that adds crisp occlusion in the small gaps shadow maps miss, such as feet on ground or small props. ## Reach for it when - character's feet float above the ground in shadows - small props lose their shadow contact with surfaces - shadow map bias detaches shadows from objects - need crisp tiny-gap occlusion near the light - shadows miss small details like fingers or foliage ## How it works For each pixel, step a ray from its view-space position toward the light for a short distance (typically centimetres to a metre) and compare each step's depth with the depth buffer; a hit with a thickness test means occlusion. The result is combined with the regular shadow term with a min or multiply, and the ray length is faded out at screen edges. The march is stepped uniformly with jitter, or by a hierarchical scheme, and works on any opaque rendered object including alpha-tested and skinned meshes whose shadow-map bias would otherwise leave a gap. Because it samples only what is on screen it ignores off-screen and back-facing occluders. ## When to use it Choose it as a supplement to [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) or [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) when large biases detach shadows from contact points, especially on characters and foliage. Prefer [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) when you can trace actual geometry, [SDF Soft Shadows](https://texelatlas.vercel.app/t/sdf-soft-shadows.md) for cheap soft world-space occlusion, and [Shadow Volumes](https://texelatlas.vercel.app/t/shadow-volumes.md) for exact hard edges. ## Cost cheap — A small fixed number of depth taps per pixel along the light direction; fast, sometimes tiled for efficiency. Measured GPU Weight: 10.73× baseline (moderate) — 0.353 ms median / 0.3691 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.28× baseline (moderate) — 0.1316 ms median (2.68× faster on L4). Ampere A100 scaling: 6.62× baseline (moderate) — 0.1907 ms median (1.85× faster on A100). ## Failure modes - Screen-space limits: missing occluders that are off-screen or hidden behind other geometry - Thickness ambiguity causes false shadows behind thin objects - Banding or noise from low step counts - Halos at depth discontinuities if the ray length is too long ## Engine support - blender: builtin — `EEVEE > Render Properties > Raytracing (screen-space raytraced contact shadows)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/raytracing.html, checked 2026-12-01) - threejs: official — `import { sss } from 'three/addons/tsl/display/SSSNode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SSSNode.js, checked 2026-12-01) — WebGPURenderer / TSL post-processing. - unity: builtin — `Volume > Add Override > Shadowing > Contact Shadows` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Contact-Shadows.md, checked 2026-12-01) — HDRP only. - unreal: builtin — `Light > Advanced > Contact Shadow Length` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/contact-shadows-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: coarse shadow map (gap at contact). Right: plus a short depth-buffer ray march toward the light (glsl-fragment; rendered 2026-11-29) ```json { "RES": 32, "BIAS": 1.1, "NC": 24, "CL": 1.3, "THICK": 0.5 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float EXT=3.2; vec3 lU(){return normalize(cross(vec3(0.,1.,0.),LD));} vec3 lV(){return cross(LD,lU());} vec2 toL(vec3 P){return vec2(dot(P,lU()),dot(P,lV()));} float recv(vec3 P){return 10.-dot(P,LD);} float smTex(vec2 st,float res){float tx=2.*EXT/res;vec2 c=(floor(st/tx)+.5)*tx;vec3 n; return isect(LD*10.+lU()*c.x+lV()*c.y,-LD,n);} float vis1(vec3 P,vec3 N,vec2 st,vec2 o,float res,float b){float tx=2.*EXT/res;vec2 cc=(floor((st+o)/tx)+.5)*tx;vec3 q; float d=isect(LD*10.+lU()*cc.x+lV()*cc.y,-LD,q);vec2 e=cc-st; float zr=recv(P)+(e.x*dot(N,lU())+e.y*dot(N,lV()))/max(dot(N,LD),.15); return zr-b>d?0.:1.;} vec3 shadeV(vec3 P,vec3 N,float vis){return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*vis*1.3);} const float RES=32.0; // P const float BIAS=1.1; // P const int NC=24; // P const float CL=1.3; // P const float THICK=0.5; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t; float vis=vis1(P,n,toL(P),vec2(0.),RES,BIAS); if(R){ vec3 o=P+n*.01; for(int i=1;i<=NC;i++){vec3 v=o+LD*(float(i)/float(NC)*CL)-RO;float zs=zbuf(proj(v)); if(zs Samples continuous visible wavelengths along refractive paths—either as a multi-wavelength hero bundle or a single wavelength when dispersion splits rays—so glass, prisms, and gemstones render smooth rainbow caustics without discrete RGB banding. ## Reach for it when - rgb rendering misses rainbow prism dispersion through glass and diamonds - three-channel caustics show ugly red green blue banding instead of spectra - need physically accurate glass chromatic dispersion in a path tracer - sample continuous visible wavelengths with hero wavelength weighting - convert spectral radiance cleanly to linear rgb without color bias ## How it works Dispersive dielectrics such as crystal glass and diamonds refract short blue wavelengths more strongly than long red wavelengths, governed by a wavelength-dependent index of refraction `n(λ)` (commonly parameterized via Cauchy or Sellmeier equations and an Abbe number). Splitting rays into only three fixed R, G, and B channels produces stark three-color stair-stepping instead of a smooth spectrum. **Hero Wavelength Spectral Sampling** (Wilkie et al. 2014) transports a stratified tuple of `N` continuous wavelengths (often 4) together along every non-dispersive path segment, using one randomly selected **hero wavelength** `λ_h` to drive directional BSDF sampling and weighting all `N` companion wavelengths via balance-heuristic multiple importance sampling. Whenever a path encounters a dispersive specular interface where Snell's law depends on `λ`, companion wavelengths cannot share the refracted direction, so their throughput collapses to zero and the path continues purely at the hero wavelength `λ_h`. Lightweight RGB path tracers adopt a **single-wavelength dispersion** variant on demand: camera paths carry RGB until they hit a dispersive material, at which point a continuous wavelength `λ ∈ [400, 700]` nm is importance-sampled from a CIE color-matching inverse CDF table, refracted using `n(λ)`, and weighted back into linear sRGB so white light integrates neutrally on average. ## When to use it Choose it in physically based path tracers whenever glass, prisms, crystal chandeliers, camera lenses, or gemstones must exhibit smooth rainbow dispersion and spectral caustics without discrete R/G/B fringes. Prefer [chromatic-aberration](chromatic-aberration) post-processing when you only want cheap screen-space lens fringing in a real-time rasterizer. Prefer [thin-film-iridescence](thin-film-iridescence) for wave-interference soap bubbles and oil slicks where phase shift rather than bulk refraction drives color separation. Pair with [spectral-upsampling-sigmoid](spectral-upsampling-sigmoid) when running a full spectral renderer on RGB textures. ## Cost medium — Hero-wavelength bundles add SIMD-friendly per-bounce spectral arithmetic; on-demand single-wavelength dispersion incurs near-zero overhead on non-dispersive paths but introduces chromatic Monte Carlo noise that needs extra samples or denoising. Measured GPU Weight: 24.91× baseline (heavy) — 0.8197 ms median / 0.8307 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.69× baseline (moderate) — 0.2813 ms median (2.91× faster on L4). Ampere A100 scaling: 15.76× baseline (moderate) — 0.454 ms median (1.81× faster on A100). ## Failure modes - Single-wavelength collapse after dispersive refraction introduces high-frequency rainbow color noise that converges more slowly than luminance noise - RGB-embedded continuous-wavelength dispersion clamps out-of-gamut spectral XYZ values into sRGB, sacrificing strict colorimetric accuracy for saturated rainbows - Smooth spectral caustics still suffer high variance under unidirectional path tracing unless combined with caustic photon mapping, light tracing, or manifold sampling - Incorrect Abbe number parameterization or negative Cauchy terms can produce unphysical refractive indices outside the visible band ## Dataflow - Inputs: material-params, radiance - Outputs: radiance - Platforms: webgpu, webgl2, desktop-gpu, cuda, cpu ## Presets ### Continuous-Wavelength Spectral Dispersion — 3-band RGB dispersion (left) vs continuous hero-wavelength Cauchy spectrum (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DISPERSION": 0.14, "P_IOR_BASE": 1.62, "P_ROT_SPEED": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_DISPERSION = 0.14; // P Cauchy Dispersion [0.02, 0.28, 0.01] const float P_IOR_BASE = 1.62; // P Base Glass IOR [1.35, 2.15, 0.02] const float P_ROT_SPEED = 0.55; // P Prism Spin [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P RGB / Spectral Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Smooth CIE-inspired spectral wavelength-to-linear-RGB response for lambda in [0, 1] (400nm -> 700nm) vec3 spectralRGB(float t) { vec3 c = clamp(vec3( 1.5 - abs(t - 0.78) * 3.6 + 0.35 * exp(-pow((t - 0.12) * 5.0, 2.0)), 1.45 - abs(t - 0.48) * 3.4, 1.5 - abs(t - 0.18) * 3.6 ), 0.0, 1.0); return c * c; } // Faceted octagonal crystal gem / optical prism SDF float mapCrystal(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.52) * q.xz; q.yz = rot2(0.32) * q.yz; vec3 aq = abs(q); float d1 = max(aq.x + aq.z * 0.414, aq.z + aq.x * 0.414) - 0.58; float d2 = (aq.x + aq.y * 0.85 + aq.z) * 0.68 - 0.66; float d3 = aq.y - 0.72; return max(max(d1, d2), d3) * 0.88; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapCrystal(p + e.xyy, spin) - mapCrystal(p - e.xyy, spin), mapCrystal(p + e.yxy, spin) - mapCrystal(p - e.yxy, spin), mapCrystal(p + e.yyx, spin) - mapCrystal(p - e.yyx, spin) )); } // High-contrast studio lightbox environment so chromatic dispersion fringes read crisply vec3 studioEnv(vec3 d) { vec3 bg = mix(vec3(0.02, 0.03, 0.05), vec3(0.10, 0.14, 0.22), smoothstep(-0.4, 0.6, d.y)); float strip1 = smoothstep(0.08, 0.02, abs(d.x - 0.38)) * smoothstep(-0.3, 0.5, d.y); float strip2 = smoothstep(0.10, 0.02, abs(d.x + 0.45)) * smoothstep(-0.2, 0.6, d.y); float keyOrb = pow(max(dot(d, normalize(vec3(0.55, 0.72, -0.45))), 0.0), 42.0); float horizonBand = exp(-abs(d.y + 0.08) * 16.0) * (0.4 + 0.6 * step(0.0, sin(atan(d.z, d.x) * 6.0))); return bg + vec3(2.8, 2.75, 2.65) * (strip1 + strip2 * 0.8 + keyOrb * 1.8) + vec3(0.9, 0.95, 1.0) * horizonBand * 0.85; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isContinuous = screenX >= split; float disp = clamp(P_DISPERSION, 0.01, 0.32); float iorBase = clamp(P_IOR_BASE, 1.2, 2.3); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.10, 2.35); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.018, 0.022, 0.036), vec3(0.052, 0.062, 0.095), smoothstep(-0.55, 0.55, uv.y)); // Soft caustic spectral fan cast behind the prism onto backdrop float causticAngle = atan(uv.y + 0.12, uv.x + 0.02); float causticBeam = exp(-abs(uv.y + 0.24 - uv.x * 0.18) * 14.0) * smoothstep(0.18, 0.65, abs(uv.x)); if (isContinuous) { float wl = clamp(0.5 + (uv.y + 0.24 - uv.x * 0.18) * 3.8, 0.0, 1.0); col += spectralRGB(wl) * causticBeam * 0.38; } else { float dY = uv.y + 0.24 - uv.x * 0.18; vec3 rgbBand = vec3(exp(-pow((dY - 0.04) * 34.0, 2.0)), exp(-pow(dY * 34.0, 2.0)), exp(-pow((dY + 0.04) * 34.0, 2.0))); col += rgbBand * causticBeam * 0.42; } float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapCrystal(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 reflD = reflect(rd, n); float ndv = max(dot(n, -rd), 0.0); float f0 = pow((iorBase - 1.0) / (iorBase + 1.0), 2.0); float fres = f0 + (1.0 - f0) * pow(1.0 - ndv, 5.0); vec3 transCol = vec3(0.0); if (!isContinuous) { // Left: Discrete 3-channel RGB refraction (produces distinct red/green/blue chromatic split!) for (int c = 0; c < 3; c++) { float fc = float(c); float ior = iorBase + (fc - 1.0) * disp * 1.15; vec3 rIn = refract(rd, n, 1.0 / ior); // Approximate second exit refraction through opposite crystal wall vec3 pExit = p + rIn * 0.72; vec3 nExit = -calcNormal(pExit, spin); vec3 rOut = refract(rIn, nExit, ior); if (length(rOut) < 0.01) rOut = reflect(rIn, nExit); vec3 s = studioEnv(normalize(rOut)); if (c == 0) transCol.r = s.r; else if (c == 1) transCol.g = s.g; else transCol.b = s.b; } } else { // Right: Continuous 12-wavelength hero spectral quadrature using Cauchy n(lambda) = A + B/lambda^2 vec3 normW = vec3(0.0); for (int k = 0; k < 12; k++) { float wl = (float(k) + 0.5) / 12.0; // 0 = 400nm violet, 1 = 700nm red float lam = mix(0.40, 0.70, wl); float cauchy = (1.0 / (lam * lam) - 1.0 / (0.55 * 0.55)) * 0.24; float ior = iorBase + cauchy * disp * 1.45; vec3 rIn = refract(rd, n, 1.0 / max(ior, 1.05)); vec3 pExit = p + rIn * 0.72; vec3 nExit = -calcNormal(pExit, spin); vec3 rOut = refract(rIn, nExit, max(ior, 1.05)); if (length(rOut) < 0.01) rOut = reflect(rIn, nExit); vec3 wRGB = spectralRGB(wl); float envLum = dot(studioEnv(normalize(rOut)), vec3(0.28, 0.54, 0.18)); transCol += wRGB * envLum; normW += wRGB; } transCol /= max(normW, vec3(1e-4)); } vec3 reflCol = studioEnv(reflD); col = mix(transCol * 1.25, reflCol, clamp(fres * 1.1, 0.08, 0.92)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Spectral upsampling with sigmoid polynomials](https://texelatlas.vercel.app/t/spectral-upsampling-sigmoid.md): Converts RGB albedo textures into smooth continuous reflectance spectra evaluated at each hero and companion wavelength. - [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md): Drives wavelength-dependent dielectric refraction directly from OpenPBR's transmission dispersion scale and Abbe number parameters. ## Combination ideas - [Dispersive manifold caustics denoised with joint NLM](https://texelatlas.vercel.app/ideas/spectral-mnee-jnlm-caustics/) ## Sources 1. [primary] A. Wilkie, S. Nawaz, M. Droske, A. Weidlich, J. Hanika (2014) Hero Wavelength Spectral Sampling. Computer Graphics Forum. https://doi.org/10.1111/cgf.12419 (verified via crossref on 2026-11-30) 2. [implementation] pissang (2026) pissang/mutracer. https://github.com/pissang/mutracer License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Continuous-Wavelength Hero and Single-Wavelength Spectral Dispersion." https://texelatlas.vercel.app/t/continuous-wavelength-spectral-dispersion/ (accessed 2026-12-01). --- id: "contrast-adaptive-sharpening" title: "Contrast Adaptive Sharpening" aliases: [CAS] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2019 inputs: [ldr-image] outputs: [ldr-image] style: "both" dynamic: "both" cost: "cheap" authority: "GPUOpen-Effects, 2020" url: "https://texelatlas.vercel.app/t/contrast-adaptive-sharpening/" sources_verified_at: "2026-11-29" --- # Contrast Adaptive Sharpening (GPUOpen-Effects, 2020) > A cheap sharpening filter that scales its strength per pixel by local contrast, so already-crisp edges are not over-sharpened while soft areas are lifted, avoiding most of the halos of a plain unsharp mask. ## Reach for it when - image looks soft after upscaling or taa - sharpen the frame without halos or noise boosting - cheap sharpening pass that avoids ringing on edges - taa blur makes the image mushy ## How it works CAS reads a plus-shaped neighbourhood of five pixels. It computes the per-channel min and max of the neighbourhood and derives a sharpening amount inversely related to the headroom between those extremes and the representable range: a pixel with plenty of headroom sharpens more, a pixel near 0 or 1 sharpens less. This amount sets a negative lobe weight for the four neighbours, and the output is the normalised weighted sum of the centre and neighbours, clamped to the neighbourhood range. Because the weight adapts to local contrast, the filter stays stable in high-contrast regions where a fixed kernel would ring. It operates on LDR display-referred values and can be fused with upscaling. ## When to use it Choose it as a final pass after TAA or an upscaler to restore crispness lost to history blur. Prefer built-in sharpening inside [AMD FidelityFX Super Resolution](https://texelatlas.vercel.app/t/fidelityfx-super-resolution.md) or [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) when those already apply one, to avoid double sharpening. Prefer no sharpening for stylized flat-shaded content. ## Cost cheap — One full-screen pass with five fetches; negligible next to TAA. Measured GPU Weight: 14.58× baseline (moderate) — 0.4796 ms median / 0.4924 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 11.23× baseline (moderate) — 0.1785 ms median (2.69× faster on L4). Ampere A100 scaling: 9.21× baseline (moderate) — 0.2653 ms median (1.81× faster on A100). ## Failure modes - Amplifies noise and film grain if applied after grain - Halos remain around very high-contrast edges at high strength - Sharpening after tonemapping clips highlights in already bright regions - Exaggerates aliasing in unfiltered scenes ## Engine support - godot: builtin — `Viewport.scaling_3d_mode = SCALING_3D_MODE_FSR (FSR 1.0 RCAS sharpening via fsr_sharpness)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Viewport.xml, checked 2026-12-01) - threejs: official — `import { sharpen } from 'three/addons/tsl/display/SharpenNode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SharpenNode.js, checked 2026-12-01) — Implements RCAS, the FidelityFX CAS derivative. - unity: builtin — `HDRP Asset > Dynamic Resolution > Upscale Filter = Contrast Adaptive Sharpen (CAS)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Dynamic-Resolution.md, checked 2026-12-01) — HDRP only, as a dynamic-resolution upscale filter. - unreal: builtin — `Temporal Super Resolution (TSR) and r.Tonemapper.Sharpen post-upscaling sharpening` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/temporal-super-resolution-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Left: softened image. Right: CAS, a 5-tap cross whose strength is scaled by local min/max contrast (glsl-fragment; rendered 2026-11-29) ```json { "SHARP": 1 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } const float SHARP=1.0; // P vec3 soft(vec2 p){float e=2.2/512.;return .25*(img(p+vec2(e,e))+img(p+vec2(-e,e))+img(p+vec2(e,-e))+img(p+vec2(-e,-e)));} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=soft(q); if(R){float e=1./512.; vec3 b=soft(q+vec2(0.,e)),d=soft(q-vec2(e,0.)),f=soft(q+vec2(e,0.)),h=soft(q-vec2(0.,e)),c=col; vec3 mn=min(min(min(d,c),min(f,b)),h),mx=max(max(max(d,c),max(f,b)),h); vec3 amp=sqrt(clamp(min(mn,1.-mx)/max(mx,1e-3),0.,1.)); vec3 w=-amp/mix(8.,5.,SHARP); col=(w*(b+d+f+h)+c)/(1.+4.*w);} if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Combines with - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Run after the TAA resolve to counter its blur. ## Sources 1. [primary] GPUOpen-Effects (2020) GPUOpen-Effects/FidelityFX-CAS. https://github.com/GPUOpen-Effects/FidelityFX-CAS License: MIT. (verified via github on 2026-11-29) 2. [tutorial] AMD GPUOpen FidelityFX Contrast Adaptive Sharpening. gpuopen.com. https://gpuopen.com/fidelityfx-cas (verified via http on 2026-11-29) ## Cite this entry Texel. "Contrast Adaptive Sharpening." https://texelatlas.vercel.app/t/contrast-adaptive-sharpening/ (accessed 2026-12-01). --- id: "cook-torrance-brdf" title: "Cook-Torrance microfacet BRDF" aliases: [Cook-Torrance, GGX Microfacet BRDF, GGX Smith Specular] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 1982 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Cook & Torrance, 1982" url: "https://texelatlas.vercel.app/t/cook-torrance-brdf/" sources_verified_at: "2026-11-29" --- # Cook-Torrance microfacet BRDF (Cook & Torrance, 1982) > The original microfacet specular model: reflectance as D*F*G / (4 n.l n.v), with a facet-normal distribution D, Fresnel F and a geometric shadowing/masking term G. Nearly every modern PBR shader is a variant of this skeleton. ## Reach for it when - need a physically based specular shader from scratch - debugging which factor causes a specular artifact - highlights should depend on roughness and viewing angle - want to understand how pbr specular is built ## How it works Cook and Torrance model a rough surface as a sea of tiny perfect mirrors. Only facets whose normal equals the half vector between light and view direction can reflect light from l into v, so the BRDF is proportional to the density of such facets, D(h). Fresnel F(v.h) says how much of that light each facet reflects, and G accounts for facets hiding or shadowing their neighbours. The product is divided by 4(n.l)(n.v), the Jacobian converting facet-space measure to outgoing-direction measure. The 1982 paper used a Beckmann distribution and a V-groove G; later work swapped each factor (GGX for D, Smith for G, Schlick for F) while keeping the structure. Diffuse is added separately, typically Lambert weighted by (1-F) and (1-metalness). ## When to use it Choose it as the conceptual template when you write or debug any microfacet shader, or when you need to reason about which factor causes an artifact. For production, use the modern factor choices: [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) for D and [Smith masking-shadowing function](https://texelatlas.vercel.app/t/smith-masking-shadowing.md) for G. Prefer [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) or [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) when you need an artist-facing parameter set rather than a bare specular lobe. Prefer [Oren-Nayar rough diffuse](https://texelatlas.vercel.app/t/oren-nayar.md) when the surface is rough diffuse with no specular lobe. ## Cost cheap — A few dot products, one pow/exp and one divide per light; negligible next to texture fetches. Measured GPU Weight: 1.88× baseline (feather) — 0.062 ms median / 0.0688 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.65× baseline (feather) — 0.0263 ms median (2.36× faster on L4). Ampere A100 scaling: 1.26× baseline (feather) — 0.0364 ms median (1.7× faster on A100). ## Failure modes - Beckmann D has short tails, so highlights look too tight and lack the soft halo seen on real materials - Energy is lost at high roughness because single-scattering G ignores light that bounces between facets (see kulla-conty-multiscatter) - Division by n.l n.v blows up at grazing angles unless clamped or folded into a visibility term - Original V-groove G is not height-correlated with D, so energy conservation is only approximate ## Engine support - babylonjs: builtin — `new BABYLON.PBRMaterial('m', scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBaseMaterial.pure.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Shader > Glossy BSDF (Distribution = GGX / Multiscatter GGX) or Principled BSDF` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/glossy.html, checked 2026-12-01) — GGX microfacet specular model. - godot: builtin — `StandardMaterial3D default specular BRDF (SPECULAR_SCHLICK_GGX)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: builtin — `MeshStandardMaterial / MeshPhysicalMaterial` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/functions/BSDF/BRDF_GGX.js, checked 2026-12-01) - unity: builtin — `Lit shaders in URP and HDRP` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl, checked 2026-12-01) — Lit shaders use a GGX microfacet specular BRDF. - unreal: builtin — `Material > Shading Model = Default Lit (Cook-Torrance microfacet specular BRDF)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Gold, medium-rough (three-material; rendered 2026-11-29) ```json { "color": "#ffe496", "roughness": 0.3, "metalness": 1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 2 ### Copper, brushed-looking (three-material; rendered 2026-11-29) ```json { "color": "#f7cfbf", "roughness": 0.4, "metalness": 1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 2 ## Lineage - extended by [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) ## Combines with - [Kulla-Conty multiple-scattering compensation](https://texelatlas.vercel.app/t/kulla-conty-multiscatter.md): Adds back the energy the single-scatter Cook-Torrance lobe loses at high roughness. ## Sources 1. [primary] R. L. Cook, K. E. Torrance (1982) A Reflectance Model for Computer Graphics. ACM Transactions on Graphics. https://doi.org/10.1145/357290.357293 (verified via crossref on 2026-11-29) 2. [tutorial] Joey de Vries PBR Theory. learnopengl.com. https://learnopengl.com/PBR/Theory (verified via http on 2026-11-29) 3. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Cook-Torrance microfacet BRDF." https://texelatlas.vercel.app/t/cook-torrance-brdf/ (accessed 2026-12-01). --- id: "cube-sphere-mapping" title: "Cube-Sphere Planet Mapping" aliases: [spherified cube, quadrilateralized spherical cube, planet cube mapping] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity, unreal, godot] year_introduced: 2013 outputs: [mesh, heightfield, texture] style: "both" dynamic: "static" cost: "cheap" authority: "Wittens" url: "https://texelatlas.vercel.app/t/cube-sphere-mapping/" sources_verified_at: "2026-11-29" --- # Cube-Sphere Planet Mapping (Wittens) > Map a cube's six faces onto a sphere so a planet can be built from six square quadtrees: far less polar distortion than lat-long grids, uniform tiles for LOD, and trivial cube-map lookups. ## Reach for it when - pole pinching ruins my planet texture - uv sphere has distorted triangles near the poles - building a planet from tiles with level of detail - need even tile sizes for streaming planetary terrain - sky or planet lookup without polar distortion ## How it works A point on a cube face is normalised to the sphere, or better mapped with an equal-area correction (tan warping or the 'spherified cube' formula) that reduces the shrinking of cells toward face centres. Each face carries a quadtree of square tiles that subdivide with camera proximity, each tile evaluating a 3D noise or heightmap sampled at the sphere position, which avoids seams because noise is a function of 3D position, not 2D face uv. Matching edge vertices (stitching or skirts) between neighbouring tiles at different LODs prevents cracks. Because each face is regular, cube maps and per-face texture atlases work directly, unlike a UV sphere, which pinches at poles. ## When to use it Choose it for planetary terrain with LOD streaming, procedural planet generation and sky/cube-map lookups. Prefer lat-long UV spheres only for small, static globes, an icosphere when you need near-uniform triangles with no faces to stitch, and [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) sampled in 3D as the height source on whichever mesh you use. ## Cost cheap — Mapping is a few arithmetic operations per vertex; cost depends on LOD scheme and noise octaves. Measured GPU Weight: 1.86× baseline (feather) — 0.0613 ms median / 0.0655 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.48× baseline (feather) — 0.0236 ms median (2.6× faster on L4). Ampere A100 scaling: 1.24× baseline (feather) — 0.0358 ms median (1.71× faster on A100). ## Failure modes - Naive normalisation squashes cells toward cube corners and stretches them toward face centres, giving uneven texel density - Cracks along face and LOD boundaries unless skirts or stitching are used - 2D noise per face produces visible seams at cube edges; sample 3D noise on the sphere position instead - Floating-point precision at planetary scale needs camera-relative or origin-shifted rendering ## Dataflow - Inputs: — - Outputs: mesh, heightfield, texture - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity, unreal, godot ## Presets ### Cube-sphere mapping: plain cube faces (left) vs tangent-warped faces (right) (glsl-fragment; rendered 2026-11-29) ```json { "GRID": 6 } ``` ```glsl // Cube-to-sphere mapping: left sphere = plain gnomonic cube faces, right = tangent-warped faces. const float GRID = 6.0; float warp(float u, bool on) { return on ? tan(u * 0.7853982) : u; } float unwarp(float u, bool on) { return on ? atan(u) * 1.2732395 : u; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; bool right = uv.x > 0.0; vec2 p = uv - vec2(right ? 0.5 : -0.5, 0.0); vec3 col = vec3(0.06, 0.07, 0.09) + 0.05 * uv.y; float r2 = dot(p, p), R = 0.44; if (r2 < R * R) { float z = sqrt(R * R - r2); vec3 n = normalize(vec3(p, z)); float a = iTime * 0.0 + 0.6; mat2 rot = mat2(cos(a), -sin(a), sin(a), cos(a)); n.xz = rot * n.xz; n.yz = mat2(cos(0.5), -sin(0.5), sin(0.5), cos(0.5)) * n.yz; vec3 an = abs(n); vec2 f; vec3 base; if (an.x > an.y && an.x > an.z) { f = n.yz / an.x; base = vec3(0.85, 0.35, 0.3); } else if (an.y > an.z) { f = n.xz / an.y; base = vec3(0.35, 0.8, 0.4); } else { f = n.xy / an.z; base = vec3(0.35, 0.5, 0.9); } vec2 g = vec2(unwarp(f.x, right), unwarp(f.y, right)) * 0.5 + 0.5; vec2 cell = fract(g * GRID); float line = min(min(cell.x, 1.0 - cell.x), min(cell.y, 1.0 - cell.y)); vec2 id = floor(g * GRID); float chk = mod(id.x + id.y, 2.0); vec3 c = base * (0.55 + 0.35 * chk); c = mix(vec3(0.05), c, smoothstep(0.0, 0.07, line)); vec3 sn = normalize(vec3(p, z)); float dif = max(dot(sn, normalize(vec3(-0.4, 0.6, 0.7))), 0.0); col = c * (0.25 + 0.85 * dif); } col = mix(col, vec3(0.9), smoothstep(0.004, 0.0, abs(uv.x))); fragColor = vec4(pow(col, vec3(0.45)), 1.0); } ``` Attribution: written for this index ## Combines with - [Simplex Noise](https://texelatlas.vercel.app/t/simplex-noise.md): 3D noise sampled at the sphere position gives seamless planetary heights across cube faces. ## Combination ideas - [Planets with rivers across cube seams](https://texelatlas.vercel.app/ideas/drainage-consistent-planets/) ## Sources 1. [primary] Steven Wittens Making Worlds 1 - Of Spheres and Cubes. acko.net. https://acko.net/blog/making-worlds-1-of-spheres-and-cubes (verified via http on 2026-11-29) ## Cite this entry Texel. "Cube-Sphere Planet Mapping." https://texelatlas.vercel.app/t/cube-sphere-mapping/ (accessed 2026-12-01). --- id: "curl-noise-flow" title: "Curl noise for procedural fluid motion" aliases: [curl noise, divergence-free noise, pseudo-fluid flow] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity, unreal, godot, houdini, blender] year_introduced: 2007 inputs: [particles] outputs: [particles, volume-density] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Bridson et al., 2007" url: "https://texelatlas.vercel.app/t/curl-noise-flow/" sources_verified_at: "2026-11-29" --- # Curl noise for procedural fluid motion (Bridson et al., 2007) > Take the curl of a smooth noise potential to get a velocity field with zero divergence, so advected particles swirl like fluid without bunching up or draining away. ## Reach for it when - particles bunch up or drain away under plain noise motion - want swirling smoke motion without running a fluid solver - need divergence free turbulence for cheap pseudo fluid - dust and embers should flow around in believable eddies ## How it works Pick a smooth scalar noise potential psi(x, y) in 2D, or a vector potential of three noise functions in 3D. The velocity is its curl: in 2D v = (dpsi/dy, -dpsi/dx), in 3D v = curl of the vector potential. Because the divergence of a curl is identically zero, the field is incompressible: advected points neither pile up nor spread out in a net way. Derivatives come analytically from gradient noise or by central differences of a few samples. Boundaries are handled by ramping the potential toward zero near an obstacle, or by blending with the distance-based gradient so the flow becomes tangent to the surface and goes around it. Animating the potential over time, or offsetting noise octaves, changes the flow and adds turbulence at several scales. The result is evaluated per particle each step with no neighbour search, and a few octaves already read as smoke or ink in water. ## When to use it Choose it for cheap, art-directable turbulence for smoke, dust, embers, magic and ambient flow where real fluid dynamics is unnecessary. Prefer [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md), [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) or [Lattice Boltzmann fluids](https://texelatlas.vercel.app/t/lattice-boltzmann-fluids.md) when the flow must respond to moving objects, buoyancy or vorticity from real physics. Prefer [Domain Warping](https://texelatlas.vercel.app/t/domain-warping.md) for static texture patterns, and plain [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) or [Simplex Noise](https://texelatlas.vercel.app/t/simplex-noise.md) offsets when divergence does not matter. Use it as the force input to [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md) and as a wind source for [Procedural foliage wind animation](https://texelatlas.vercel.app/t/foliage-wind-animation.md). ## Cost cheap — Four to six noise samples per particle per step in 2D, more in 3D; multiple octaves multiply it. Measured GPU Weight: 424.94× baseline (extreme) — 13.9804 ms median / 14.1352 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 358.88× baseline (extreme) — 5.7062 ms median (2.45× faster on L4). Ampere A100 scaling: 300.16× baseline (extreme) — 8.6446 ms median (1.62× faster on A100). ## Failure modes - No true dynamics: flow ignores obstacles and sources unless the potential is explicitly modified near them - Boundary ramping produces visible stagnation or ring artefacts around colliders - Low-frequency potentials give long coherent loops that look mechanical - Finite-difference step too large or too small causes visible blockiness or noise in the derivative - Streams in 3D can spiral into tubes and closed orbits, so particles keep circling instead of dispersing ## Engine support - godot: builtin — `GPUParticles3D > ParticleProcessMaterial.turbulence_enabled = true (evaluates 3D curl_3d noise field)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/scene/resources/particle_process_material.cpp, checked 2026-12-01) - threejs: official — `import { curlNoise } from 'three/addons/tsl/math/curlNoise.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/math/curlNoise.js, checked 2026-12-01) - unity: official — `VFX Graph > Operator > Perlin Curl Noise (also Cellular/Value); Turbulence block` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.visualeffectgraph/Documentation~/Operator-PerlinCurlNoise.md, checked 2026-12-01) — Requires the Visual Effect Graph package. - unreal: builtin — `Material graph: VectorNoise (Function = VNF_CURL_ALU); Niagara: Curl Noise Force module` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/VectorNoiseFunction, checked 2026-12-01) ## Dataflow - Inputs: particles - Outputs: particles, volume-density - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity, unreal, godot, houdini, blender ## Presets ### Curl-noise flow visualised with line integral convolution (glsl-fragment; rendered 2026-11-29) ```json { "freq": 2.5, "steps": 18, "step_len": 0.006, "grain_density": 110, "drift": 0.15 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Curl of a scalar noise potential, drawn as line-integral-convolution streaks. const float FREQ = 2.5; // spatial frequency of the potential const int STEPS = 18; // integration steps each way const float STEP = 0.006; // step length in uv units const float DENSITY = 110.0; // grain resolution of the smeared noise const float DRIFT = 0.15; // potential animation speed float hash21(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); } float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p); f = f * f * f * (f * (f * 6.0 - 15.0) + 10.0); return mix(mix(hash21(i), hash21(i + vec2(1, 0)), f.x), mix(hash21(i + vec2(0, 1)), hash21(i + vec2(1, 1)), f.x), f.y); } float potential(vec2 p) { vec2 q = p * FREQ + vec2(iTime * DRIFT, 0.0); return vnoise(q) + 0.5 * vnoise(q * 2.0 + 7.3); } vec2 curl(vec2 p) { // divergence-free by construction const float e = 0.01; float dx = potential(p + vec2(e, 0)) - potential(p - vec2(e, 0)); float dy = potential(p + vec2(0, e)) - potential(p - vec2(0, e)); return vec2(dy, -dx) / (2.0 * e); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sum = 0.0, wsum = 0.0; for (int dir = 0; dir < 2; dir++) { vec2 p = uv; float s = dir == 0 ? 1.0 : -1.0; for (int i = 0; i < STEPS; i++) { vec2 v = curl(p); p += s * STEP * v / (length(v) + 1e-4); float w = 1.0 - float(i) / float(STEPS); sum += w * hash21(floor(p * DENSITY)); wsum += w; } } float g = sum / wsum; vec2 v = curl(uv); vec3 tint = 0.5 + 0.5 * cos(atan(v.y, v.x) + vec3(0.0, 2.1, 4.2)); fragColor = vec4(mix(vec3(g), tint * g * 1.6, 0.55), 1.0); } ``` Attribution: written for this index ## Combines with - [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md): Each particle samples the curl field as its velocity or acceleration, giving swirling motion without neighbour interaction. - [Procedural foliage wind animation](https://texelatlas.vercel.app/t/foliage-wind-animation.md): The curl field acts as a divergence-free wind source sampled at each vertex's world position. ## Sources 1. [primary] Robert Bridson, Jim Houriham, Marcus Nordenstam (2007) Curl-noise for procedural fluid flow. ACM SIGGRAPH 2007 papers. https://doi.org/10.1145/1275808.1276435 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Curl noise for procedural fluid motion." https://texelatlas.vercel.app/t/curl-noise-flow/ (accessed 2026-12-01). --- id: "curvature-map-baking" title: "Curvature map generation for edge wear and masking" aliases: [curvature baking, convexity and concavity map, edge wear mask] domain: "materials" stage: "material" realtime: "interactive" platforms: [blender, cpu, desktop-gpu, webgl2, python, houdini] year_introduced: 2004 inputs: [mesh, normals] outputs: [texture] style: "both" dynamic: "static" cost: "offline" authority: "Rusinkiewicz" url: "https://texelatlas.vercel.app/t/curvature-map-baking/" sources_verified_at: "2026-11-29" --- # Curvature map generation for edge wear and masking (Rusinkiewicz) > Computes per-vertex or per-texel mean curvature to tell convex edges from concave cavities, then bakes it to a texture. Texture artists use it to drive edge wear, dirt in crevices and highlights. ## Reach for it when - need edge wear mask from a mesh - dirt should collect in crevices and creases - separate convex and concave areas for procedural texturing - painted wear on corners without hand painting - curvature map looks noisy or blocky ## How it works Mean curvature measures how quickly the normal changes across the surface: positive on convex ridges, negative in creases. On a triangle mesh one fits the shape operator per face from the differences of vertex normals across each edge, as Rusinkiewicz does, then averages onto vertices with area or angle weights to get principal curvatures. A cheaper estimate uses the cotangent Laplacian of positions or the angle between neighbouring vertex normals. For texture-space baking, the vertex values are rasterised into the UV atlas, or computed in the pixel shader by comparing a normal map with its blurred neighbour (the screen-space Laplacian trick). Radius control comes from smoothing before measuring. The map is remapped by a ramp to produce an edge mask, which is multiplied into procedural wear, rust or paint chipping layers. Output can be signed or split into convex and concave masks. ## When to use it Choose it to drive procedural wear, dirt accumulation and edge highlighting in a texturing workflow, or to feed [Weathering simulation (weathered stone)](https://texelatlas.vercel.app/t/weathering-simulation.md) and masks in material graphs. Prefer ambient occlusion bakes (see [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md)) for crevice darkening that depends on surroundings rather than local shape. Prefer [Pre-integrated skin shading](https://texelatlas.vercel.app/t/pre-integrated-skin-shading.md) when the curvature is used at runtime in a skin LUT. The baker is typically part of [High-to-low-poly normal map baking](https://texelatlas.vercel.app/t/normal-map-baking.md) tools. ## Cost offline — Per-vertex estimate is fast on CPU; baking to texels is a standard rasterisation pass. Measured GPU Weight: 11.12× baseline (moderate) — 0.3659 ms median / 0.3878 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.55× baseline (moderate) — 0.1359 ms median (2.69× faster on L4). Ampere A100 scaling: 6.88× baseline (moderate) — 0.1982 ms median (1.85× faster on A100). ## Failure modes - Noisy per-vertex curvature on irregular triangulation, giving speckled wear masks - Low-poly bevels give a single hard edge instead of a smooth falloff, so the mask looks blocky - Normal-map-derived curvature depends on texture resolution and compression artefacts - Mirrored or overlapping UVs bake mismatched values - Sign convention differs between tools, inverting edge and cavity masks ## Engine support - blender: builtin — `Shader node: Geometry > Pointiness, baked via an Emission bake` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/input/geometry.html, checked 2026-12-01) — Per-vertex curvature approximation; Cycles only. - unreal: builtin — `Modeling Mode > Bake > Bake Mesh Attribute Maps > Curvature (or GeometryScript_Bake)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/GeometryScript_Bake, checked 2026-12-01) ## Dataflow - Inputs: mesh, normals - Outputs: texture - Platforms: blender, cpu, desktop-gpu, webgl2, python, houdini ## Presets ### SDF-Laplacian curvature visualisation (glsl-fragment; rendered 2026-11-29) ```json { "EPS": 0.02, "GAIN": 0.25 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Convex (warm) vs concave (cool) tint from the SDF Laplacian. const float EPS = 0.02; const float GAIN = 0.25; mat2 rot(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float map(vec3 p) { p.xz = rot(iTime * 0.5) * p.xz; float s = length(p - vec3(0.0, 0.55, 0.0)) - 0.55; vec3 q = abs(p - vec3(0.0, -0.35, 0.0)) - vec3(0.8, 0.3, 0.8); float b = length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - 0.08; float k = 0.2; float hh = clamp(0.5 + 0.5 * (b - s) / k, 0.0, 1.0); return mix(b, s, hh) - k * hh * (1.0 - hh); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.5, 3.2); vec3 rd = normalize(vec3(uv, -1.6)); vec3 col = vec3(0.05, 0.06, 0.09); float t = 0.0; bool hit = false; for (int i = 0; i < 90; i++) { float d = map(ro + rd * t); if (d < 0.001) { hit = true; break; } t += d; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec2 e = vec2(EPS, 0.0); vec3 n = normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx))); float lap = (map(p + e.xyy) + map(p - e.xyy) + map(p + e.yxy) + map(p - e.yxy) + map(p + e.yyx) + map(p - e.yyx) - 6.0 * map(p)) / (EPS * EPS); float c = clamp(lap * GAIN, -1.0, 1.0); vec3 base = vec3(0.45); vec3 tint = c > 0.0 ? mix(base, vec3(1.0, 0.65, 0.2), c) : mix(base, vec3(0.1, 0.3, 0.8), -c); float diff = 0.25 + 0.75 * max(dot(n, normalize(vec3(0.5, 0.8, 0.6))), 0.0); col = tint * diff; } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Weathering simulation (weathered stone)](https://texelatlas.vercel.app/t/weathering-simulation.md): Curvature masks decide where edge wear and cavity dirt accumulate. - [High-to-low-poly normal map baking](https://texelatlas.vercel.app/t/normal-map-baking.md): Both bake from the same high-poly mesh and share UVs and cage settings. ## Sources 1. [primary] S. Rusinkiewicz Estimating curvatures and their derivatives on triangle meshes. Proceedings. 2nd International Symposium on 3D Data Processing, Visualization and Transmission, 2004. 3DPVT 2004.. https://doi.org/10.1109/tdpvt.2004.1335277 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Curvature map generation for edge wear and masking." https://texelatlas.vercel.app/t/curvature-map-baking/ (accessed 2026-12-01). --- id: "ddgi" title: "Dynamic Diffuse Global Illumination (DDGI)" aliases: [RTXGI probes, irradiance fields] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, unreal, unity] year_introduced: 2019 inputs: [mesh, irradiance-probes] outputs: [irradiance-probes, radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Majercik et al." url: "https://texelatlas.vercel.app/t/ddgi/" sources_verified_at: "2026-11-29" --- # Dynamic Diffuse Global Illumination (DDGI) (Majercik et al.) > A grid of light probes updated every frame with a few ray-traced samples each, storing octahedrally mapped irradiance and distance so lookups avoid light leaking. Gives dynamic diffuse GI with stable cost. ## Reach for it when - dynamic global illumination without baking lightmaps - indirect light must react to moving lights and objects - light leaking and flicker in probe based gi - diffuse bounce lighting on hardware ray tracing ## How it works A regular 3D grid of probes covers the scene. Each frame every probe fires a modest number of rays (tens to a couple hundred) with hardware ray tracing or another fast tracer. The ray hits are shaded with direct light plus the previous frame's probe lookups, so each frame effectively adds one more bounce. Each probe stores two small **octahedral maps**: irradiance, and a mean and mean-squared distance to the nearest surface per direction. New results are blended into the old with a temporal hysteresis factor, so light changes propagate over a few frames but noise is averaged away. At shading time the pixel interpolates the eight surrounding probes trilinearly. Weights are modulated by a normal-based term, a **Chebyshev visibility test** using the stored distance moments (a probe that cannot see the point contributes less), and a smooth-backface term. That visibility term is the main reason the technique avoids the bright leaking of earlier irradiance-volume systems. ## When to use it Choose it for fully dynamic diffuse GI with predictable cost on ray-tracing-capable hardware, when low-frequency indirect light is enough and you want temporal stability rather than per-pixel noise. Prefer [lumen-gi](lumen-gi) or [surfel-gi](surfel-gi) when you need finer spatial detail or large scenes without placing grids by hand. Prefer [radiance-cascades](radiance-cascades) when you need sharper shadows from indirect light in screen-space or 2D. Prefer [irradiance-volumes](irradiance-volumes) or [lightmap-baking](lightmap-baking) when everything is static or you target hardware without ray tracing. Prefer [restir-gi](restir-gi) for high-frequency per-pixel indirect. ## Cost medium — Ray count scales with probes times rays per probe, plus a probe-sampling pass in shading; the JCGT follow-up reports production-scale tuning. Measured GPU Weight: 53.97× baseline (heavy) — 1.7757 ms median / 1.8663 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 51.73× baseline (heavy) — 0.8225 ms median (2.16× faster on L4). Ampere A100 scaling: 34.72× baseline (heavy) — 0.9999 ms median (1.78× faster on A100). ## Failure modes - Light leaking through thin walls when probes sit on the wrong side and the distance moments cannot separate them - Slow response to lighting changes because of temporal hysteresis, visible as lag on moving lights - Low spatial resolution: contact shadows and small-scale indirect detail are missing, so it is paired with SSAO or ray-traced AO - Probe placement and cascade layout must be authored or streamed to cover large worlds, and probes inside geometry need classification ## Dataflow - Inputs: mesh, irradiance-probes - Outputs: irradiance-probes, radiance - Platforms: desktop-gpu, unreal, unity ## Presets ### Dynamic Diffuse GI (DDGI) — trilinear irradiance probe lattice & Chebyshev visibility (glsl-fragment; rendered 2026-11-30) ```json { "P_PROBE_SCALE": 1, "P_GI_BOUNCE": 1.35, "P_CHEBYSHEV": 0.88, "P_SUN_SWEEP": 1 } ``` ```glsl const float P_PROBE_SCALE = 1.0; // P Probe Spheres [0.0, 2.0, 0.05] const float P_GI_BOUNCE = 1.35; // P Probe GI Gain [0.0, 2.5, 0.05] const float P_CHEBYSHEV = 0.88; // P Leak Guard [0.0, 1.0, 0.02] const float P_SUN_SWEEP = 1.0; // P Sun Sweep [0.0, 2.5, 0.05] 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); } // Room with central divider wall + vibrant colored bounce walls to demonstrate DDGI Chebyshev leak prevention vec2 mapScene(vec3 p) { vec2 res = vec2(1.05 + p.y, 1.0); // floor float ceilD = 1.05 - p.y; if (ceilD < res.x) res = vec2(ceilD, 1.0); float backD = 1.55 + p.z; if (backD < res.x) res = vec2(backD, 1.0); float leftD = 1.55 + p.x; if (leftD < res.x) res = vec2(leftD, 2.0); // warm crimson wall float rightD = 1.55 - p.x; if (rightD < res.x) res = vec2(rightD, 3.0); // azure blue wall // Central thin divider baffle wall (classic DDGI light-leak test geometry) float dWall = sdBox(p - vec3(-0.08, -0.35, -0.25), vec3(0.08, 0.72, 0.58)); if (dWall < res.x) res = vec2(dWall, 4.0); // Foreground matte display block on right side float dBlk = sdBox(p - vec3(0.72, -0.68, -0.15), vec3(0.32, 0.37, 0.32)) - 0.02; if (dBlk < res.x) res = vec2(dBlk, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Evaluate directional octahedral irradiance stored in a DDGI probe at world position probePos vec3 evalProbeIrradiance(vec3 probePos, vec3 dir, vec3 sunPatch) { // Analytical bounce contributions from red left wall, blue right wall, and moving sunlit floor patch vec3 toLeft = normalize(vec3(-1.55, probePos.y, probePos.z) - probePos); vec3 toRight = normalize(vec3(1.55, probePos.y, probePos.z) - probePos); vec3 toPatch = sunPatch - probePos; float patchDist = length(toPatch) + 1e-4; vec3 patchDir = toPatch / patchDist; float wLeft = pow(max(dot(dir, toLeft) * 0.5 + 0.5, 0.0), 1.8) / (0.65 + pow(probePos.x + 1.55, 2.0)); float wRight = pow(max(dot(dir, toRight) * 0.5 + 0.5, 0.0), 1.8) / (0.65 + pow(1.55 - probePos.x, 2.0)); float wPatch = pow(max(dot(dir, patchDir) * 0.5 + 0.5, 0.0), 2.2) / (0.35 + patchDist * patchDist); // Baffle wall blocks cross-room probe bounce between left (x < -0.08) and right (x > -0.08) float sameSidePatch = smoothstep(-0.2, 0.2, (probePos.x + 0.08) * (sunPatch.x + 0.08)); vec3 irr = vec3(0.05, 0.06, 0.08); irr += vec3(1.35, 0.22, 0.14) * wLeft * (0.45 + 0.55 * step(probePos.x, 0.1)); irr += vec3(0.16, 0.48, 1.35) * wRight * (0.45 + 0.55 * step(-0.2, probePos.x)); irr += vec3(2.4, 1.85, 1.15) * wPatch * mix(0.25, 1.0, sameSidePatch); return irr; } // Trilinear DDGI probe grid lookup with smooth-backface & Chebyshev distance-visibility weighting vec3 sampleDDGIGrid(vec3 p, vec3 n, vec3 sunPatch, float chebStrength) { vec3 spacing = vec3(0.95, 0.78, 0.95); vec3 origin = vec3(-0.95, -0.58, -0.95); vec3 gridCoord = (p - origin) / spacing; vec3 baseCell = clamp(floor(gridCoord), vec3(0.0), vec3(1.0)); vec3 alpha = clamp(gridCoord - baseCell, 0.0, 1.0); vec3 sumIrr = vec3(0.0); float sumW = 0.0; for (int i = 0; i < 8; i++) { vec3 off = vec3( mod(float(i), 2.0), mod(floor(float(i) * 0.5), 2.0), floor(float(i) * 0.25) ); vec3 probePos = origin + (baseCell + off) * spacing; vec3 trilin = mix(1.0 - alpha, alpha, off); float w = trilin.x * trilin.y * trilin.z; vec3 toProbe = probePos - p; float dProbe = length(toProbe) + 1e-4; vec3 dirToProbe = toProbe / dProbe; // Smooth backface weight: ((dot(N, dirToProbe) + 1) / 2)^2 float wrap = 0.5 * dot(n, dirToProbe) + 0.5; w *= wrap * wrap + 0.04; // Chebyshev visibility test across baffle wall: attenuate probes on opposite side of divider float midD = mapScene(0.5 * (p + probePos)).x; float vis = smoothstep(-0.02, 0.12, midD); w *= mix(1.0, max(vis, 0.02), chebStrength); sumIrr += evalProbeIrradiance(probePos, n, sunPatch) * w; sumW += w; } return sumIrr / max(sumW, 1e-4); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.14, 2.55); vec3 rd = normalize(vec3(uv, -1.38)); float sweep = iTime * 0.65 * max(P_SUN_SWEEP, 0.0); vec3 sunPatch = vec3(0.85 * sin(sweep), -0.95, -0.35 + 0.35 * cos(sweep * 0.8)); vec3 sunOrigin = vec3(sunPatch.x * 0.65, 0.98, 0.25); // Raymarch room geometry float t = 0.0; float matId = 1.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 9.0) break; } vec3 col = vec3(0.02); if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = vec3(0.78, 0.77, 0.75); if (matId > 1.5 && matId < 2.5) alb = vec3(0.86, 0.18, 0.14); else if (matId > 2.5 && matId < 3.5) alb = vec3(0.14, 0.44, 0.88); // Direct spotlight sweeping across the room vec3 toL = sunOrigin - p; float dL = length(toL) + 1e-4; vec3 lDir = toL / dL; vec3 spotDir = normalize(sunPatch - sunOrigin); float spot = smoothstep(0.62, 0.88, dot(-lDir, spotDir)); float sh = 1.0; float ts = 0.04; for (int s = 0; s < 18; s++) { float dh = mapScene(p + n * 0.015 + lDir * ts).x; sh = min(sh, clamp(6.0 * dh / ts, 0.0, 1.0)); ts += max(dh, 0.05); if (ts > dL - 0.08) break; } vec3 direct = alb * vec3(3.4, 2.75, 1.9) * max(dot(n, lDir), 0.0) * spot * sh / (0.35 + 0.45 * dL * dL); vec3 gi = sampleDDGIGrid(p, n, sunPatch, clamp(P_CHEBYSHEV, 0.0, 1.0)) * max(P_GI_BOUNCE, 0.0); col = direct + alb * gi; } // Overlay visible 3D DDGI irradiance probe spheres on a 3x2x2 world lattice float pRad = 0.085 * clamp(P_PROBE_SCALE, 0.0, 2.2); if (pRad > 0.005) { float bestT = hit ? t : 100.0; for (int ix = 0; ix < 3; ix++) { for (int iy = 0; iy < 2; iy++) { for (int iz = 0; iz < 2; iz++) { vec3 pc = vec3(-0.95 + float(ix) * 0.95, -0.35 + float(iy) * 0.82, -0.75 + float(iz) * 0.92); vec3 oc = ro - pc; float b = dot(oc, rd); float c = dot(oc, oc) - pRad * pRad; float disc = b * b - c; if (disc > 0.0) { float pt = -b - sqrt(disc); if (pt > 0.05 && pt < bestT) { bestT = pt; vec3 pn = normalize(ro + rd * pt - pc); vec3 probeCol = evalProbeIrradiance(pc, pn, sunPatch) * 1.45; float rim = pow(1.0 - max(dot(pn, -rd), 0.0), 3.0); col = probeCol + vec3(0.85, 0.92, 1.0) * rim * 0.35; } } } } } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ### DDGI starting layout (json-params; parameter preset) ```json { "probe_spacing_m": 2, "grid_dims": [ 22, 22, 22 ], "rays_per_probe": 192, "irradiance_texels": 8, "distance_texels": 16, "hysteresis": 0.97, "normal_bias_m": 0.1, "view_bias_m": 0.1 } ``` Attribution: written for this index; sensible starting values, tune per scene ## Combines with - [ReSTIR GI: Path Resampling for Real-Time Path Tracing](https://texelatlas.vercel.app/t/restir-gi.md): Probes supply stable low-frequency indirect while resampling handles high-frequency detail. - [Neural Radiance Caching](https://texelatlas.vercel.app/t/neural-radiance-caching.md): Probe lookups can terminate long paths in the same way a cache does. ## Sources 1. [primary] Zander Majercik, Jean-Philippe Guertin, Derek Nowrouzezahrai, Morgan McGuire Dynamic Diffuse Global Illumination with Ray-Traced Irradiance Fields. JCGT 2019. https://jcgt.org/published/0008/02/01 (verified via http on 2026-11-29) 2. [primary] Zander Majercik et al. Scaling Probe-Based Real-Time Dynamic Global Illumination for Production. JCGT 2021. https://jcgt.org/published/0010/02/01 (verified via http on 2026-11-29) 3. [implementation] NVIDIA-RTX (2024) NVIDIA-RTX/RTXGI. https://github.com/NVIDIA-RTX/RTXGI License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Dynamic Diffuse Global Illumination (DDGI)." https://texelatlas.vercel.app/t/ddgi/ (accessed 2026-12-01). --- id: "deep-shadow-maps" title: "Deep shadow maps" aliases: [DSM, transmittance function shadow maps, deep shadows] domain: "volumes" stage: "visibility" realtime: "offline" platforms: [cpu, houdini, cuda] year_introduced: 2000 inputs: [particles, volume-density, mesh] outputs: [visibility-mask] style: "photoreal" dynamic: "both" cost: "offline" authority: "Lokovic & Veach, 2000" url: "https://texelatlas.vercel.app/t/deep-shadow-maps/" sources_verified_at: "2026-11-29" --- # Deep shadow maps (Lokovic & Veach, 2000) > Instead of one depth per light pixel, store a piecewise-linear transmittance curve along the light ray. It shadows hair, smoke and semi-transparent fuzzy objects with soft partial occlusion that ordinary shadow maps cannot represent. ## Reach for it when - hair and fur shadows look hard or aliased - smoke needs soft self shadowing in an offline render - shadow map cannot handle semi transparent fuzzy objects - partial occlusion from fibres or clouds is missing ## How it works A standard shadow map stores the nearest depth, so a pixel is either lit or shadowed. A deep shadow map stores, for each light-space pixel, a function giving how much light survives at each depth along the ray. The light renders the scene with all semi-transparent samples (hair fibres, volume slices, particles). For each pixel the samples are sorted by depth and accumulated into a transmittance function: starting at one, each opacity reduces the value. The curve is stored compactly as piecewise linear data with a bounded error, and neighbouring pixels are filtered by averaging functions rather than single depths, which gives soft shadows without noise. At shading time the renderer transforms a point into light space, finds the function and evaluates it at the point's depth. Visibility is the evaluated transmittance. Because the function is filtered across a pixel footprint, thin hair strands produce stable partial shadow instead of aliasing. ## When to use it Choose it in offline renderers for hair, fur, smoke, clouds and dense particle effects where self-shadowing must be smooth and film-quality. Prefer [shadow-mapping](shadow-mapping) or [percentage-closer-filtering](percentage-closer-filtering) for opaque geometry. Prefer [variance-shadow-maps](variance-shadow-maps) or [moment-shadow-maps](moment-shadow-maps) for real-time soft shadows of opaque or alpha-tested objects. Prefer [froxel-volumetric-fog](froxel-volumetric-fog) and [volume-ray-marching](volume-ray-marching) in real time for fog and clouds, which compute transmittance directly. Prefer [ray-traced-shadows](ray-traced-shadows) or [delta-tracking](delta-tracking) when a path tracer can estimate transmittance per shading point. ## Cost offline — Build time and memory scale with the number of semi-transparent samples per light pixel; lookup is a search along one stored function. Measured GPU Weight: 508.83× baseline (extreme) — 16.7405 ms median / 17.1646 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 470.59× baseline (extreme) — 7.4824 ms median (2.24× faster on L4). Ampere A100 scaling: 405.19× baseline (extreme) — 11.6695 ms median (1.43× faster on A100). ## Failure modes - Memory grows with depth complexity, so dense hair or volumes need aggressive compression of the transmittance curves - Light bleeding and wrong shadows if the compression tolerance is too coarse for thin dense layers - Resolution tied to the light's pixel grid, so close-up views need higher resolution or tiling - One map per light, which makes many-light scenes expensive - Moving objects require rebuilding the map every frame - Surface and volume samples need consistent opacity conventions, otherwise self-shadow offsets show as dark bands ## Dataflow - Inputs: particles, volume-density, mesh - Outputs: visibility-mask - Platforms: cpu, houdini, cuda ## Presets ### Deep Shadow Maps — hard binary single-depth shadow map (left) vs piecewise volumetric transmittance curve (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_OPTICAL_DEPTH": 1.65, "P_LIGHT_ANGLE": 0.55, "P_PLUME_TURB": 0.72, "P_SPLIT": 0.48 } ``` ```glsl const float P_OPTICAL_DEPTH = 1.65; // P Optical Depth [0.4, 3.2, 0.1] const float P_LIGHT_ANGLE = 0.55; // P Light Elevation [0.15, 1.2, 0.05] const float P_PLUME_TURB = 0.72; // P Cloud Wisps [0.2, 1.4, 0.05] const float P_SPLIT = 0.48; // P Binary / Deep SM Split [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * vec3(127.1, 311.7, 74.7)); p += dot(p, p.yzx + 19.19); return fract((p.x + p.y) * p.z); } float noise3(vec3 p) { vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(mix(hash31(i), hash31(i + vec3(1.0, 0.0, 0.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 0.0)), hash31(i + vec3(1.0, 1.0, 0.0)), f.x), f.y), mix(mix(hash31(i + vec3(0.0, 0.0, 1.0)), hash31(i + vec3(1.0, 0.0, 1.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 1.0)), hash31(i + vec3(1.0, 1.0, 1.0)), f.x), f.y), f.z ); } float fbm3(vec3 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 4; i++) { v += a * noise3(p); p *= 2.04; a *= 0.5; } return v; } // Semi-transparent swirling volumetric plume hovering above a stone floor float evalCloudDensity(vec3 p, float turb) { vec3 c = p - vec3(0.0, 0.24, -0.18); float r = length(c * vec3(0.85, 1.18, 0.92)); if (r > 0.92) return 0.0; float n = fbm3(c * 2.8 + vec3(iTime * 0.22, -iTime * 0.14, 0.0)); float base = smoothstep(0.82, 0.16, r) + (n - 0.5) * turb * 0.85; return clamp(base, 0.0, 1.0) * smoothstep(0.88, 0.52, r); } // Integrate transmittance along light ray from p toward lDir (Deep Shadow Map T(z) vs Binary single-depth threshold!) float evalLightTrans(vec3 p, vec3 lDir, float optD, float turb, bool useDSM) { float acc = 0.0; bool hitBinary = false; float ds = 0.085; for (int i = 0; i < 14; i++) { vec3 q = p + lDir * (float(i) + 0.5) * ds; float d = evalCloudDensity(q, turb); if (d > 0.22) hitBinary = true; acc += d * ds; } if (useDSM) { // Deep Shadow Map: smooth continuous Beer-Lambert transmittance function T(z) = exp(-sigma * integral) return exp(-acc * optD * 2.8); } // Standard single-depth shadow map: binary 0/1 cutoff at alpha-test depth threshold! return hitBinary ? 0.06 : 1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useDSM = sx >= split; float optD = clamp(P_OPTICAL_DEPTH, 0.2, 4.0); float lAng = clamp(P_LIGHT_ANGLE, 0.1, 1.4); float turb = clamp(P_PLUME_TURB, 0.1, 1.6); vec3 lDir = normalize(vec3(cos(lAng) * 0.65, sin(lAng) + 0.45, 0.48)); vec3 ro = vec3(0.25 * sin(iTime * 0.24), 0.36, 2.25); vec3 ta = vec3(0.0, -0.06, -0.15); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.42 + ri * uv.x + up * uv.y); vec3 sky = mix(vec3(0.64, 0.74, 0.88), vec3(0.16, 0.32, 0.62), smoothstep(-0.08, 0.55, rd.y)); vec3 col = sky; // Floor plane y = -0.62 catching cast volumetric shadow float tMax = 6.0; if (rd.y < -0.005) { float tf = (-0.62 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { tMax = tf; vec3 fp = ro + rd * tf; vec2 tile = floor(fp.xz * 2.2); vec3 alb = mix(vec3(0.58, 0.56, 0.52), vec3(0.72, 0.70, 0.66), mod(tile.x + tile.y, 2.0)); float sh = evalLightTrans(fp + vec3(0.0, 0.02, 0.0), lDir, optD, turb, useDSM); col = alb * (vec3(1.25, 1.12, 0.94) * max(lDir.y, 0.1) * sh + vec3(0.20, 0.26, 0.38)); col = mix(col, sky, 1.0 - exp(-tf * 0.08)); } } // Raymarch the floating wispy cloud volume with self-shadowing from Binary SM vs Deep Shadow Map! float t0 = max(0.75, 0.05); float t1 = min(tMax, 3.55); if (t1 > t0) { float trans = 1.0; vec3 volCol = vec3(0.0); const int STEPS = 32; float dt = (t1 - t0) / float(STEPS); float hg = 0.25 + 0.75 * pow(max(dot(rd, lDir), 0.0), 4.0); for (int i = 0; i < STEPS; i++) { vec3 mp = ro + rd * (t0 + (float(i) + 0.5) * dt); float d = evalCloudDensity(mp, turb); if (d > 0.01) { float lTrans = evalLightTrans(mp, lDir, optD, turb, useDSM); vec3 lit = vec3(1.45, 1.24, 0.96) * lTrans * (0.6 + 0.75 * hg) + vec3(0.24, 0.34, 0.52) * (0.5 + 0.5 * mp.y); float ext = d * optD * 2.2; float stepT = exp(-ext * dt); volCol += trans * lit * (1.0 - stepT); trans *= stepT; if (trans < 0.02) break; } } col = col * trans + volCol; } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) ## Combines with - [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md): Volume density grids are sampled along light rays to generate the transmittance functions. - [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md): The marcher reads the deep shadow map to attenuate in-scattered light at each step. ## Sources 1. [primary] Tom Lokovic, Eric Veach (2000) Deep shadow maps. Proceedings of the 27th annual conference on Computer graphics and interactive techniques - SIGGRAPH '00. https://doi.org/10.1145/344779.344958 (verified via crossref on 2026-11-29) 2. [primary] Jon Jansen, Louis Bavoil (2010) Fourier opacity mapping. Proceedings of the 2010 ACM SIGGRAPH symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/1730804.1730831 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Deep shadow maps." https://texelatlas.vercel.app/t/deep-shadow-maps/ (accessed 2026-12-01). --- id: "deepsdf-neural-sdf" title: "DeepSDF (neural signed distance functions)" aliases: [DeepSDF, auto-decoder SDF, neural SDF] domain: "geometry" stage: "geometry" realtime: "offline" platforms: [cuda, python] year_introduced: 2019 inputs: [sdf, point-cloud] outputs: [sdf, mesh] style: "both" dynamic: "static" cost: "offline" authority: "Park et al., 2019" url: "https://texelatlas.vercel.app/t/deepsdf-neural-sdf/" sources_verified_at: "2026-11-29" --- # DeepSDF (neural signed distance functions) (Park et al., 2019) > A network that takes a 3D point and a per-shape latent code and returns signed distance, so a whole shape category lives in one decoder and shapes are recovered by optimising their latent code. ## Reach for it when - want a neural network that outputs a shape from a latent code - complete a partial scan into a full shape - interpolate between two shapes smoothly - learn a shape prior for a whole object category ## How it works Train a single MLP f(z, x) whose output is the signed distance at point x for the shape described by code z. Training data is sampled SDF values near and far from each training shape's surface, with the output clamped near the surface to focus capacity. There is no encoder: every training shape owns a learnable latent vector, and codes and decoder weights are optimised together (an auto-decoder). At test time, with the weights fixed, you fit a new latent code by gradient descent so predicted distances match observed samples, which may be sparse or partial. Interpolating between codes morphs shapes. Extract the surface by evaluating on a grid and running [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md), or by sphere tracing the field. Shape completion from partial scans works because the decoder encodes a prior over plausible shapes. ## When to use it Choose it as the reference design for learned SDF shape priors, shape completion from partial depth, and latent-space interpolation within a category. Prefer [Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/poisson-surface-reconstruction.md) when you have dense oriented points and no prior is wanted, [NeuS](https://texelatlas.vercel.app/t/neus.md) or [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) when the supervision is multi-view photos, and [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md)-style hash grids when a single scene must be fit fast rather than a category generalised. ## Cost offline — Training takes hours on a GPU for a category; inference per point is one MLP forward pass, so a dense grid is slow compared with classic meshing. Measured GPU Weight: 27.55× baseline (heavy) — 0.8539 ms median / 0.8728 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 25.31× baseline (heavy) — 0.4025 ms median (2.12× faster on L4). Ampere A100 scaling: 17.25× baseline (moderate) — 0.4967 ms median (1.72× faster on A100). ## Failure modes - Fine detail and thin structures are lost because one MLP and a small code must cover the whole category - Out-of-category inputs decode to a blobby average shape - Latent-code fitting on partial data has local minima and needs good initialisation - The SDF is not guaranteed to be a true distance field, which breaks sphere-tracing step sizes and gradient-norm assumptions ## Dataflow - Inputs: sdf, point-cloud - Outputs: sdf, mesh - Platforms: cuda, python ## Presets ### DeepSDF Neural Implicit — latent-space shape interpolation & signed-distance iso-contour slice (glsl-fragment; rendered 2026-11-30) ```json { "P_LATENT_Z": 0.5, "P_SLICE_Y": -0.22, "P_ISO_FREQ": 14, "P_ROT_SPEED": 0.65 } ``` ```glsl const float P_LATENT_Z = 0.50; // P Latent Code z [0.0, 1.0, 0.02] const float P_SLICE_Y = -0.22; // P SDF Slice Height [-0.55, 0.45, 0.02] const float P_ISO_FREQ = 14.0; // P Iso-Ring Density [6.0, 26.0, 1.0] const float P_ROT_SPEED = 0.65; // P Spin Speed [0.0, 2.0, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } // Latent-conditioned implicit shape f_theta(x, z) smoothly morphing across a 3-shape manifold float evalDeepSDF(vec3 p, float zCode) { // Shape 0: Chamfered architectural chair/frame float dSeat = sdBox(p - vec3(0.0, -0.10, 0.0), vec3(0.42, 0.09, 0.42)) - 0.04; float dBack = sdBox(p - vec3(0.0, 0.28, -0.34), vec3(0.42, 0.34, 0.08)) - 0.04; float dLegs = sdBox(vec3(abs(p.x) - 0.32, p.y + 0.36, abs(p.z) - 0.32), vec3(0.07, 0.24, 0.07)) - 0.02; float sChair = min(min(dSeat, dBack), dLegs); // Shape 1: Smooth torus-sphere sculpture float sTorus = min(sdTorus(p.xzy, vec2(0.42, 0.16)), length(p) - 0.26); // Shape 2: Hollowed rounded cube with cylindrical cutouts float sCube = max(sdBox(p, vec3(0.46)) - 0.06, -(min(min(length(p.xy), length(p.yz)), length(p.xz)) - 0.27)); float u = clamp(zCode, 0.0, 1.0) * 2.0; float d = (u < 1.0) ? mix(sChair, sTorus, smoothstep(0.0, 1.0, u)) : mix(sTorus, sCube, smoothstep(0.0, 1.0, u - 1.0)); // Subtle neural MLP sinusoidal smoothness characteristic of continuous latent decoding return d + 0.012 * sin(p.x * 7.0) * sin(p.y * 7.0) * sin(p.z * 7.0) * sin(zCode * 3.1415926); } vec3 calcNormal(vec3 p, float zCode, float spin) { vec2 e = vec2(0.0022, 0.0); vec3 qx1 = p + e.xyy; qx1.xz = rot2(spin) * qx1.xz; vec3 qx0 = p - e.xyy; qx0.xz = rot2(spin) * qx0.xz; vec3 qy1 = p + e.yxy; qy1.xz = rot2(spin) * qy1.xz; vec3 qy0 = p - e.yxy; qy0.xz = rot2(spin) * qy0.xz; vec3 qz1 = p + e.yyx; qz1.xz = rot2(spin) * qz1.xz; vec3 qz0 = p - e.yyx; qz0.xz = rot2(spin) * qz0.xz; return normalize(vec3( evalDeepSDF(qx1, zCode) - evalDeepSDF(qx0, zCode), evalDeepSDF(qy1, zCode) - evalDeepSDF(qy0, zCode), evalDeepSDF(qz1, zCode) - evalDeepSDF(qz0, zCode) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.55; // Blend user latent code with gentle automatic latent-space traversal float zCode = clamp(fract(P_LATENT_Z + 0.18 * sin(iTime * 0.45)), 0.0, 1.0); float sliceY = clamp(P_SLICE_Y, -0.58, 0.48); float isoFreq = clamp(P_ISO_FREQ, 5.0, 28.0); vec3 ro = vec3(0.0, 0.72, 2.38); vec3 ta = vec3(0.0, -0.06, 0.0); vec3 fwd = normalize(ta - ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.55 + right * uv.x + up * uv.y); vec3 col = mix(vec3(0.024, 0.034, 0.056), vec3(0.070, 0.092, 0.144), smoothstep(-0.55, 0.55, uv.y)); // Intersect horizontal SDF iso-contour inspection plane at y = sliceY float tPlane = (abs(rd.y) > 0.001) ? ((sliceY - ro.y) / rd.y) : 1e5; if (tPlane < 0.0) tPlane = 1e5; // Raymarch the zero-level set f_theta(x, z) = 0 float tHit = 0.0; bool hitShape = false; for (int i = 0; i < 68; i++) { vec3 p = ro + rd * tHit; vec3 q = p; q.xz = rot2(spin) * q.xz; float d = evalDeepSDF(q, zCode); if (d < 0.002) { hitShape = true; break; } tHit += d * 0.85; if (tHit > 7.5) break; } // Render translucent SDF slice plane first if behind or intersecting if (tPlane < 7.5 && (!hitShape || tPlane < tHit)) { vec3 sp = ro + rd * tPlane; if (length(sp.xz) < 1.38) { vec3 sq = sp; sq.xz = rot2(spin) * sq.xz; float sdf = evalDeepSDF(sq, zCode); // Classic positive (cool blue) / negative (warm orange) signed-distance contour map vec3 sCol = (sdf > 0.0) ? vec3(0.14, 0.58, 0.92) : vec3(0.96, 0.44, 0.18); sCol *= 0.82 - exp(-4.5 * abs(sdf)) * 0.42; float rings = 0.72 + 0.28 * cos(sdf * isoFreq * 6.2831853); sCol *= rings; // Crisp white zero-level set contour f(x,z) = 0 sCol = mix(sCol, vec3(0.98, 0.99, 1.0), smoothstep(0.022, 0.004, abs(sdf))); float diskMask = smoothstep(1.38, 1.24, length(sp.xz)); col = mix(col, sCol, diskMask * 0.78); } } // Render neural implicit surface (above slice plane or in front of it) if (hitShape) { vec3 p = ro + rd * tHit; vec3 n = calcNormal(p, zCode, spin); vec3 l1 = normalize(vec3(0.55, 0.85, 0.52)); vec3 l2 = normalize(vec3(-0.70, -0.25, 0.48)); float diff = max(dot(n, l1), 0.0) * 0.85 + max(dot(n, l2), 0.0) * 0.26; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 52.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = mix(vec3(0.24, 0.76, 0.86), vec3(0.88, 0.62, 0.96), zCode); vec3 surfCol = alb * (0.24 + 0.85 * diff) + vec3(0.98) * spec * 0.58 + vec3(0.48, 0.80, 1.0) * rim * 0.34; // Highlight intersection seam where slice plane cuts the zero-level surface float cutRing = smoothstep(0.022, 0.004, abs(p.y - sliceY)); surfCol = mix(surfCol, vec3(1.0, 0.94, 0.46), cutRing * 0.90); if (tPlane < tHit && length((ro + rd * tPlane).xz) < 1.38) { col = mix(surfCol, col, 0.38); } else { col = surfCol; } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): Evaluating the decoder on a grid gives sampled distances that marching cubes turns into a triangle mesh. ## Combination ideas - [Crack-free latent morphing via DeepSDF and Marching Tetrahedra](https://texelatlas.vercel.app/ideas/deepsdf-isosurface-marching-tetrahedra/) ## Sources 1. [primary] Jeong Joon Park, Peter Florence, Julian Straub, Richard Newcombe, Steven Lovegrove (2019) DeepSDF: Learning Continuous Signed Distance Functions for Shape Representation. arXiv preprint (cs.CV). https://arxiv.org/abs/1901.05103 (verified via arxiv on 2026-11-29) 2. [implementation] facebookresearch (2019) facebookresearch/DeepSDF. https://github.com/facebookresearch/DeepSDF License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "DeepSDF (neural signed distance functions)." https://texelatlas.vercel.app/t/deepsdf-neural-sdf/ (accessed 2026-12-01). --- id: "deferred-and-projected-decals" title: "Deferred and projected decals" aliases: [box decals, screen-space decals, decal volumes] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2010 inputs: [depth, gbuffer, texture] outputs: [gbuffer] style: "both" dynamic: "dynamic" cost: "medium" authority: "" url: "https://texelatlas.vercel.app/t/deferred-and-projected-decals/" sources_verified_at: "2026-11-29" --- # Deferred and projected decals > Stamps textures such as bullet holes, grime and road markings onto existing surfaces by rendering a box volume and reprojecting scene depth into the box's local space, without generating extra mesh. ## Reach for it when - need bullet holes or dirt on arbitrary surfaces - stamp textures onto geometry at runtime without new meshes - decal stretches on surfaces at steep angles - road markings and graffiti on uneven ground - placing grime on level geometry from the editor ## How it works A decal is an oriented box with a transform, a texture set and a blend mode. The box is rasterised (back faces or front faces with depth test off) so every covered screen pixel runs a shader. That shader reads the depth buffer, reconstructs the world position, transforms it into decal space and uses the xy of the result as UVs; pixels whose local position falls outside the box are discarded. Albedo, normal, roughness or emissive are then blended into the G-buffer (deferred) or accumulated into a decal buffer applied in the forward pass. Tangent frames can come from the decal or from screen-space derivatives of the reconstructed position. An angle fade using the surface normal against the projection axis prevents stretching on perpendicular surfaces, and a layer or stencil mask restricts which meshes receive decals. ## When to use it Choose it for dynamic details placed by gameplay or tooling: impacts, blood, tyre tracks, dirt and signage on arbitrary geometry. Prefer baked texture detail or [Lightmap Baking](https://texelatlas.vercel.app/t/lightmap-baking.md) for static, authored detail. Prefer mesh decals when a surface needs real depth or the platform cannot afford a depth read. Use [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md) for terrain-style blending without a box. Works naturally with [Tiled deferred shading](https://texelatlas.vercel.app/t/tiled-deferred-shading.md), and in forward renderers with [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md) through a decal buffer. ## Cost medium — Cost scales with overdraw of decal volumes and G-buffer bandwidth; culling by cluster or tile keeps it manageable. Measured GPU Weight: 24.54× baseline (heavy) — 0.8075 ms median / 0.8612 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 24.61× baseline (heavy) — 0.3913 ms median (2.06× faster on L4). Ampere A100 scaling: 17.23× baseline (moderate) — 0.4963 ms median (1.63× faster on A100). ## Failure modes - Stretching on surfaces nearly parallel to the projection direction unless an angle fade is used - Decals bleed onto objects behind or in front of the intended surface because the box depth range is too thick - Projected normals blend incorrectly with the underlying normal map, producing flat or inverted lighting - Moving or skinned meshes smear the stamp because the projection is in world space - Transparent surfaces and particles have no depth entry, so decals appear on the surface behind them - Texture mips sample wrong levels when derivatives are reconstructed from a projected UV on depth discontinuities ## Engine support - babylonjs: builtin — `MeshBuilder.CreateDecal(); material.decalMap` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/Builders/decalBuilder.pure.ts, checked 2026-12-01) — Mesh-projected decals; not deferred volumes. - godot: builtin — `Add a Decal node (Decal.texture_albedo, normal, ORM)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Decal.xml, checked 2026-12-01) — Projected box decals; works in Forward+ and Mobile. - threejs: official — `import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/geometries/DecalGeometry.js, checked 2026-12-01) — Projects a box onto mesh geometry; not a deferred/screen-space decal. - unity: builtin — `HDRP: Decal Projector; URP: Renderer > Add Renderer Feature > Decal` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/decals.md, checked 2026-12-01) - unreal: builtin — `Place a Decal Actor; decal material with Material Domain = Deferred Decal, Blend Mode Translucent or Alpha Composite` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/decal-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, gbuffer, texture - Outputs: gbuffer - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Deferred & Projected Decals — OBB projection volumes & local UVs (left) vs normal-blended stamped surface decals (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DECAL_SCALE": 1, "P_ANGLE_FADE": 0.45, "P_WEAR": 0.35, "P_SPLIT": 0.48 } ``` ```glsl const float P_DECAL_SCALE = 1.00; // P Decal Scale [0.5, 1.8, 0.05] const float P_ANGLE_FADE = 0.45; // P Normal Cutoff [0.1, 0.9, 0.05] const float P_WEAR = 0.35; // P Grime Wear [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P OBB / Stamped Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); float a = hash21(i); float b = hash21(i + vec2(1.0, 0.0)); float c = hash21(i + vec2(0.0, 1.0)); float d = hash21(i + vec2(1.0, 1.0)); return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); } float fbm(vec2 p) { float s = 0.0; float a = 0.5; for (int i = 0; i < 4; i++) { s += a * vnoise(p); p *= 2.07; a *= 0.5; } return s; } 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); } vec2 mapScene(vec3 p) { float dFloor = p.y + 0.65; float dWall = p.z + 0.85; vec2 res = vec2(dFloor, 1.0); if (dWall < res.x) res = vec2(dWall, 2.0); // Curved architectural concrete pillar meeting the wall and floor float dCyl = length(p.xz - vec2(-0.25, -0.45)) - 0.36; dCyl = max(dCyl, abs(p.y - 0.15) - 0.85); if (dCyl < res.x) res = vec2(dCyl, 3.0); // Stepped concrete curb block float dCurb = sdBox(p - vec3(0.48, -0.42, -0.32), vec3(0.38, 0.24, 0.32)); if (dCurb < res.x) res = vec2(dCurb, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } mat3 rotY(float a) { float c = cos(a), s = sin(a); return mat3(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c); } mat3 rotX(float a) { float c = cos(a), s = sin(a); return mat3(1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c); } // Analytical ray-OBB intersection for wireframe volume overlay vec2 intersectBox(vec3 ro, vec3 rd, vec3 rad) { vec3 m = 1.0 / (rd + vec3(1e-6)); vec3 n = m * ro; vec3 k = abs(m) * rad; vec3 t1 = -n - k; vec3 t2 = -n + k; float tN = max(max(t1.x, t1.y), t1.z); float tF = min(min(t2.x, t2.y), t2.z); if (tN > tF || tF < 0.0) return vec2(-1.0); return vec2(tN, tF); } float boxWire(vec3 lp, vec3 rad) { vec3 d = abs(abs(lp) - rad); float e1 = max(d.x, d.y); float e2 = max(d.y, d.z); float e3 = max(d.z, d.x); return smoothstep(0.025, 0.006, min(e1, min(e2, e3))); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showStamped = sx >= split; float dScale = clamp(P_DECAL_SCALE, 0.4, 2.0); float angCut = clamp(P_ANGLE_FADE, 0.05, 0.95); float wear = clamp(P_WEAR, 0.0, 1.0); vec3 ro = vec3(0.32 * sin(iTime * 0.28), 0.34, 2.18); vec3 ta = vec3(0.05, -0.18, -0.42); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.42 + ri * uv.x + up * uv.y); vec3 col = mix(vec3(0.09, 0.11, 0.14), vec3(0.22, 0.27, 0.34), smoothstep(-0.3, 0.6, rd.y)); float t = 0.05; float hitId = 0.0; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hitId = h.y; break; } t += h.x; if (t > 9.0) break; } // Two oriented decal projector boxes: // Box A: emblem + hazard stencil projected onto curved pillar & back wall vec3 boxACenter = vec3(-0.14 + 0.12 * sin(iTime * 0.55), -0.02, -0.45); mat3 boxARot = rotY(0.24) * rotX(0.18); vec3 boxARad = vec3(0.56, 0.56, 0.52) / dScale; // Box B: top-down road/floor hazard stripe decal projected over curb & floor vec3 boxBCenter = vec3(0.42, -0.42, -0.22); mat3 boxBRot = rotY(-0.32); vec3 boxBRad = vec3(0.55, 0.45, 0.48) / dScale; if (hitId > 0.5) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 v = -rd; vec3 sunDir = normalize(vec3(0.62, 0.78, 0.52)); // Base procedural concrete G-buffer float grain = fbm(p.xy * 6.5 + p.zy * 5.0); vec3 baseAlb = mix(vec3(0.36, 0.38, 0.40), vec3(0.54, 0.55, 0.53), grain); float baseRough = mix(0.62, 0.85, grain); vec3 surfN = n; // Reproject world position p into Decal Box A local space vec3 lpA = transpose(boxARot) * (p - boxACenter); vec3 boxAProjDir = boxARot * vec3(0.0, 0.0, 1.0); float inA = step(max(abs(lpA.x) / boxARad.x, max(abs(lpA.y) / boxARad.y, abs(lpA.z) / boxARad.z)), 1.0); float facingA = smoothstep(angCut, min(angCut + 0.25, 0.99), dot(n, boxAProjDir)); vec2 uvA = lpA.xy / (2.0 * boxARad.xy) + 0.5; // Reproject world position p into Decal Box B local space (top-down along +Y) vec3 lpB = transpose(boxBRot) * (p - boxBCenter); vec3 boxBProjDir = boxBRot * vec3(0.0, 1.0, 0.0); float inB = step(max(abs(lpB.x) / boxBRad.x, max(abs(lpB.y) / boxBRad.y, abs(lpB.z) / boxBRad.z)), 1.0); float facingB = smoothstep(angCut, min(angCut + 0.25, 0.99), dot(n, boxBProjDir)); vec2 uvB = lpB.xz / (2.0 * boxBRad.xz) + 0.5; if (showStamped) { // Decal A: Stenciled emblem ring + radial ticks + weathered paint mask if (inA > 0.5) { vec2 c = uvA - 0.5; float r = length(c); float ang = atan(c.y, c.x); float ring = smoothstep(0.045, 0.028, abs(r - 0.34)); float innerRing = smoothstep(0.032, 0.018, abs(r - 0.21)); float crossBar = smoothstep(0.03, 0.015, abs(c.y)) * step(0.11, abs(c.x)) * step(abs(c.x), 0.42); float ticks = step(0.55, cos(ang * 12.0)) * smoothstep(0.04, 0.015, abs(r - 0.28)); float mask = clamp(ring + innerRing + crossBar + ticks, 0.0, 1.0); float chip = smoothstep(wear * 0.72, wear * 0.72 + 0.16, fbm(uvA * 14.0 + 3.1)); float alphaA = mask * chip * facingA; vec3 decalColA = mix(vec3(0.95, 0.34, 0.12), vec3(0.98, 0.78, 0.18), innerRing); baseAlb = mix(baseAlb, decalColA, alphaA); baseRough = mix(baseRough, 0.28, alphaA); // Subtle paint thickness edge bump vec3 dN = normalize(n + vec3(cos(ang), sin(ang), 0.0) * (ring * 0.22 * alphaA)); surfN = normalize(mix(surfN, dN, alphaA)); } // Decal B: Diagonal safety stripes & oil grime if (inB > 0.5) { vec2 e = abs(uvB - 0.5); float frame = step(max(e.x, e.y), 0.46) * (1.0 - step(max(e.x, e.y), 0.34)); float stripes = smoothstep(0.05, -0.05, sin((uvB.x + uvB.y) * 28.0)); float chipB = smoothstep(wear * 0.65, wear * 0.65 + 0.18, fbm(uvB * 12.0 + 9.4)); float alphaB = frame * chipB * facingB; vec3 stripeCol = mix(vec3(0.08, 0.09, 0.10), vec3(0.96, 0.76, 0.12), stripes); baseAlb = mix(baseAlb, stripeCol, alphaB); baseRough = mix(baseRough, 0.34, alphaB); } } else { // Left: Show local projected UV coordinates inside each box volume if (inA > 0.5) { vec2 grid = abs(fract(uvA * 6.0) - 0.5); float gl = smoothstep(0.06, 0.02, min(0.5 - grid.x, 0.5 - grid.y)); vec3 uvVis = vec3(uvA.x, uvA.y, 0.25) * (0.4 + 0.6 * facingA); baseAlb = mix(baseAlb, uvVis + vec3(0.95, 0.5, 0.15) * gl * 0.45, 0.75 * facingA + 0.15); } if (inB > 0.5) { vec2 grid = abs(fract(uvB * 6.0) - 0.5); float gl = smoothstep(0.06, 0.02, min(0.5 - grid.x, 0.5 - grid.y)); vec3 uvVis = vec3(0.18, uvB.x, uvB.y) * (0.4 + 0.6 * facingB); baseAlb = mix(baseAlb, uvVis + vec3(0.2, 0.92, 0.98) * gl * 0.45, 0.75 * facingB + 0.15); } } // Soft shadow ray float sh = 1.0; float ts = 0.03; for (int s = 0; s < 18; s++) { float ds = mapScene(p + sunDir * ts).x; if (ds < 0.002) { sh = 0.0; break; } sh = min(sh, 8.0 * ds / max(ts, 1e-4)); ts += max(ds, 0.03); if (ts > 3.5) break; } sh = clamp(sh, 0.0, 1.0); vec3 h = normalize(sunDir + v); float ndl = max(dot(surfN, sunDir), 0.0); float ndh = max(dot(surfN, h), 0.0); float a2 = max(baseRough * baseRough, 0.04); float spec = pow(ndh, mix(8.0, 96.0, 1.0 - baseRough)) * (1.0 - baseRough * 0.75); vec3 skyFill = mix(vec3(0.16, 0.20, 0.26), vec3(0.36, 0.48, 0.68), 0.5 + 0.5 * surfN.y); col = baseAlb * (vec3(1.15, 1.08, 0.96) * ndl * sh + skyFill * 0.48) + vec3(1.0, 0.95, 0.88) * spec * sh * 0.55; } // Left side: draw crisp translucent OBB projector box wireframes in 3D space if (!showStamped) { vec3 roA = transpose(boxARot) * (ro - boxACenter); vec3 rdA = transpose(boxARot) * rd; vec2 hitA = intersectBox(roA, rdA, boxARad); if (hitA.y > 0.0) { float wNear = (hitA.x > 0.0 && hitA.x < t) ? boxWire(roA + rdA * hitA.x, boxARad) : 0.0; float wFar = (hitA.y < t) ? boxWire(roA + rdA * hitA.y, boxARad) : 0.0; col += vec3(1.0, 0.52, 0.16) * (wNear * 0.95 + wFar * 0.35 + 0.05); } vec3 roB = transpose(boxBRot) * (ro - boxBCenter); vec3 rdB = transpose(boxBRot) * rd; vec2 hitB = intersectBox(roB, rdB, boxBRad); if (hitB.y > 0.0) { float wNear = (hitB.x > 0.0 && hitB.x < t) ? boxWire(roB + rdB * hitB.x, boxBRad) : 0.0; float wFar = (hitB.y < t) ? boxWire(roB + rdB * hitB.y, boxBRad) : 0.0; col += vec3(0.22, 0.88, 1.0) * (wNear * 0.95 + wFar * 0.35 + 0.05); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Reoriented normal map blending (detail normals)](https://texelatlas.vercel.app/t/reoriented-normal-mapping.md): Decal normals are blended over the existing surface normal with reoriented blending to keep detail intact. - [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md): Clusters let a forward renderer look up only the decals overlapping each pixel. ## Sources 1. [primary] Using Decals. docs.godotengine.org. https://docs.godotengine.org/en/stable/tutorials/3d/using_decals.html (verified via http on 2026-11-29) 2. [secondary] Decal Renderer Feature. docs.unity3d.com. https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@14.0/manual/renderer-feature-decal.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Deferred and projected decals." https://texelatlas.vercel.app/t/deferred-and-projected-decals/ (accessed 2026-12-01). --- id: "deferred-shading" title: "Deferred shading (G-buffer)" aliases: [deferred rendering, G-buffer rendering] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1988 inputs: [mesh, material-params] outputs: [gbuffer, radiance] style: "both" dynamic: "dynamic" cost: "medium" authority: "Saito & Takahashi, 1990" url: "https://texelatlas.vercel.app/t/deferred-shading/" sources_verified_at: "2026-11-29" --- # Deferred shading (G-buffer) (Saito & Takahashi, 1990) > Rasterize geometry once into several screen-sized attribute targets, then run lighting as a separate screen-space pass so shading cost scales with pixels and lights, not with overdraw. ## Reach for it when - many dynamic lights make forward rendering too slow - pixel shader cost explodes with overdraw and lights - need normals and depth for screen-space effects for free - thousands of small point lights in a scene - lighting cost should scale with pixels not geometry ## How it works Pass one renders every opaque mesh into a set of render targets, the G-buffer, storing per-pixel what lighting later needs: depth, a packed normal, albedo, roughness, metalness, sometimes emissive and a material id. No lighting is evaluated here, so overdraw only costs attribute writes. Pass two reads those targets and evaluates lighting per pixel. Each light is drawn as a proxy (full-screen quad, sphere, cone) or batched by tiles, and its contribution is accumulated additively into an HDR target, with position reconstructed from depth. Because each visible pixel is shaded once per light, hundreds of small lights become affordable. Transparent surfaces, which have no single attribute set per pixel, are handled in a separate forward pass afterwards. ## When to use it Choose it when a scene has many dynamic lights and mostly opaque surfaces, and you want screen-space effects (SSAO, SSR, decals) that need normals and depth anyway. Prefer [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md) when you need MSAA, many transparents, or tight bandwidth on mobile. Prefer [Tiled deferred shading](https://texelatlas.vercel.app/t/tiled-deferred-shading.md) as the scaling step once the light count makes per-light proxies expensive. Prefer [Visibility buffer rendering](https://texelatlas.vercel.app/t/visibility-buffer.md) when G-buffer bandwidth or material-count fragmentation is the bottleneck. ## Cost medium — Dominated by G-buffer bandwidth (4-6 targets at full resolution) rather than ALU; qualitative, no source-specific numbers. Measured GPU Weight: 66.6× baseline (extreme) — 2.1913 ms median / 2.284 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 61.6× baseline (extreme) — 0.9795 ms median (2.24× faster on L4). Ampere A100 scaling: 42× baseline (heavy) — 1.2096 ms median (1.81× faster on A100). ## Failure modes - Hardware MSAA is awkward: multisampled G-buffers multiply bandwidth, so engines fall back to post-process AA and get shimmering sub-pixel edges - Transparency, hair and foliage with alpha need a second forward path with different lighting, so the two look slightly different - Packing normals and material data into few channels causes banding in smooth gradients and limits material variety (one BRDF per pass) - Bandwidth blows up on tile-based mobile GPUs unless the G-buffer stays in on-chip memory - Light proxy overdraw becomes the new bottleneck with large overlapping lights ## Engine support - blender: builtin — `EEVEE Next default opaque lighting runs through DeferredPipeline with multi-layer G-buffer closures` (evidence: https://github.com/blender/blender/blob/main/source/blender/draw/engines/eevee/eevee_pipeline.cc, checked 2026-12-01) - unity: builtin — `HDRP Asset > Lit Shader Mode = Deferred (or Both); URP Renderer > Rendering Path = Deferred` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Forward-And-Deferred-Rendering.md, checked 2026-12-01) - unreal: builtin — `Default renderer is deferred; optional Forward Shading Renderer in Project Settings > Rendering` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/forward-shading-renderer-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `GPURenderPassDescriptor.colorAttachments (up to maxColorAttachments=8 MRT targets in one pass)` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Hardware MRT G-buffer output is native; lighting pass is authored in WGSL. ## Dataflow - Inputs: mesh, material-params - Outputs: gbuffer, radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Deferred shading — G-buffer (albedo, normals, depth) split vs multi-light pass (glsl-fragment; rendered 2026-11-30) ```json { "P_LIGHT_COUNT": 12, "P_LIGHT_RADIUS": 1.4, "P_SPECULAR": 0.8, "P_GBUF_SPLIT": 0.44 } ``` ```glsl const float P_LIGHT_COUNT = 12.0; // P Point Lights [2.0, 16.0, 1.0] const float P_LIGHT_RADIUS = 1.4; // P Light Radius [0.4, 2.8, 0.05] const float P_SPECULAR = 0.8; // P Specular Gain [0.0, 2.0, 0.05] const float P_GBUF_SPLIT = 0.44; // P G-Buffer Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } 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); } // Returns vec2(distance, materialId) vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); // Floor // Central sculpted torus vec3 q = p - vec3(0.0, 0.05, 0.0); q.xy = rot2(iTime * 0.35) * q.xy; q.yz = rot2(0.55) * q.yz; float dT = sdTorus(q, vec2(0.68, 0.24)); if (dT < res.x) res = vec2(dT, 2.0); // Orbiting chrome spheres for (int i = 0; i < 4; i++) { float a = float(i) * 1.5708 + iTime * 0.4; vec3 sp = vec3(cos(a) * 1.45, -0.45 + 0.18 * sin(iTime * 1.2 + float(i)), sin(a) * 1.45); float dS = length(p - sp) - 0.32; if (dS < res.x) res = vec2(dS, 3.0); } // Architectural rear pillars vec3 rp = p - vec3(0.0, 0.0, -2.2); rp.x = mod(rp.x + 1.2, 2.4) - 1.2; float dP = sdBox(rp, vec3(0.28, 2.0, 0.28)) - 0.04; if (dP < res.x) res = vec2(dP, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } vec3 hsv2rgb(float h, float s, float v) { vec3 p = abs(fract(vec3(h) + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0); return v * mix(vec3(1.0), clamp(p - 1.0, 0.0, 1.0), s); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; vec3 ro = vec3(0.0, 0.85, 3.6); vec3 ta = vec3(0.0, -0.1, 0.0); vec3 ww = normalize(ta - ro); vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.45 * ww); // Geometry pass: populate G-buffer (albedo, world normal, linear depth, roughness) float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 16.0) break; } vec3 gAlbedo = vec3(0.03, 0.04, 0.06); vec3 gNormal = vec3(0.0, 0.0, 1.0); float gRough = 0.5; float gDepth = clamp(t / 12.0, 0.0, 1.0); vec3 lit = vec3(0.02, 0.025, 0.04); if (hit) { vec3 p = ro + rd * t; gNormal = calcNormal(p); if (matId < 1.5) { vec2 chk = floor(p.xz * 1.4); float m = mod(chk.x + chk.y, 2.0); gAlbedo = mix(vec3(0.18, 0.19, 0.22), vec3(0.46, 0.48, 0.52), m); gRough = mix(0.28, 0.52, m); } else if (matId < 2.5) { gAlbedo = vec3(0.84, 0.78, 0.72); gRough = 0.22; } else if (matId < 3.5) { gAlbedo = vec3(0.75, 0.82, 0.88); gRough = 0.14; } else { gAlbedo = vec3(0.48, 0.50, 0.56); gRough = 0.58; } // Lighting pass: accumulate N deferred point lights solely from G-buffer attributes lit = gAlbedo * vec3(0.06, 0.07, 0.11); int nLights = int(clamp(P_LIGHT_COUNT, 1.0, 16.0)); float lRad = max(P_LIGHT_RADIUS, 0.25); float specGain = max(P_SPECULAR, 0.0); vec3 v = -rd; for (int i = 0; i < 16; i++) { if (i >= nLights) break; float fi = float(i); float ang = fi * 0.3927 * 1.6 + iTime * (0.45 + 0.05 * mod(fi, 3.0)); float rOrbit = 0.85 + 0.95 * sin(fi * 1.9 + iTime * 0.3); vec3 lPos = vec3(cos(ang) * rOrbit, -0.35 + 0.75 * abs(sin(fi * 1.3 + iTime * 0.7)), sin(ang) * rOrbit); vec3 lCol = hsv2rgb(fract(fi * 0.13 + 0.05), 0.82, 1.0); vec3 toL = lPos - p; float dist = length(toL) + 1e-4; vec3 l = toL / dist; float att = pow(clamp(1.0 - dist / (lRad * 2.2), 0.0, 1.0), 2.0) / (0.18 + dist * dist); float ndl = max(dot(gNormal, l), 0.0); vec3 h = normalize(l + v); float shininess = mix(96.0, 10.0, gRough); float spec = pow(max(dot(gNormal, h), 0.0), shininess) * specGain; lit += lCol * att * (gAlbedo * ndl * 1.5 + vec3(spec) * 1.2); } } // Visualize light volumes as subtle glowing sprites in the deferred composite int nLightsVis = int(clamp(P_LIGHT_COUNT, 1.0, 16.0)); for (int i = 0; i < 16; i++) { if (i >= nLightsVis) break; float fi = float(i); float ang = fi * 0.3927 * 1.6 + iTime * (0.45 + 0.05 * mod(fi, 3.0)); float rOrbit = 0.85 + 0.95 * sin(fi * 1.9 + iTime * 0.3); vec3 lPos = vec3(cos(ang) * rOrbit, -0.35 + 0.75 * abs(sin(fi * 1.3 + iTime * 0.7)), sin(ang) * rOrbit); vec3 toL = lPos - ro; float proj = dot(toL, rd); if (proj > 0.0 && (!hit || proj < t)) { float perp = length(toL - rd * proj); vec3 lCol = hsv2rgb(fract(fi * 0.13 + 0.05), 0.78, 1.0); lit += lCol * exp(-perp * 26.0) * 1.1; } } // Split G-buffer diagnostic panel on the left: top = World Normals, middle = Albedo, bottom = Depth float splitX = clamp(P_GBUF_SPLIT, 0.0, 1.0); vec3 col = aces(lit); if (screenUV.x < splitX) { if (screenUV.y > 0.666) { col = hit ? (gNormal * 0.5 + 0.5) : vec3(0.08, 0.09, 0.14); } else if (screenUV.y > 0.333) { col = hit ? gAlbedo : vec3(0.06, 0.07, 0.09); } else { float dVis = hit ? pow(1.0 - gDepth, 1.8) : 0.0; col = vec3(dVis * 0.9, dVis * 0.95, dVis); } // Thin horizontal dividers between G-buffer rows if (abs(screenUV.y - 0.666) < 0.004 || abs(screenUV.y - 0.333) < 0.004) col = vec3(0.95); } if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) col = vec3(0.98, 0.86, 0.45); fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [Tiled deferred shading](https://texelatlas.vercel.app/t/tiled-deferred-shading.md) - extended by [Visibility buffer rendering](https://texelatlas.vercel.app/t/visibility-buffer.md) ## Combines with - [Tiled deferred shading](https://texelatlas.vercel.app/t/tiled-deferred-shading.md): Deferred's G-buffer is exactly what the tile light-culling pass reads depth from before accumulating lights. - [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md): The depth and normal targets written by the geometry pass feed screen-space AO with no extra rendering. ## Sources 1. [primary] Takafumi Saito, Tokiichiro Takahashi (1990) Comprehensible rendering of 3-D shapes. Proceedings of the 17th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/97879.97901 (verified via crossref on 2026-11-29) 2. [primary] Michael Deering, Stephanie Winner, Bic Schediwy, Chris Duffy, Neil Hunt (1988) The triangle processor and normal vector shader. Proceedings of the 15th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/54852.378468 (verified via crossref on 2026-11-29) 3. [talk] Shawn Hargreaves, Mark Harris Deferred Shading (GDC 2004). GDC 2004. https://www.nvidia.com/en-us/page-not-found (verified via http on 2026-11-29) ## Cite this entry Texel. "Deferred shading (G-buffer)." https://texelatlas.vercel.app/t/deferred-shading/ (accessed 2026-12-01). --- id: "delta-tracking" title: "Delta (Woodcock) Tracking" aliases: [Woodcock tracking, null-collision tracking, ratio tracking] domain: "volumes" stage: "volume" realtime: "offline" platforms: [cpu, cuda, desktop-gpu, blender, houdini] year_introduced: 1965 inputs: [volume-density] outputs: [radiance, hdr-image] style: "photoreal" dynamic: "both" cost: "offline" authority: "Kutz et al., 2017" url: "https://texelatlas.vercel.app/t/delta-tracking/" sources_verified_at: "2026-11-29" --- # Delta (Woodcock) Tracking (Kutz et al., 2017) > An unbiased way to sample free-flight distance in heterogeneous media by adding fictitious null collisions until the medium looks homogeneous with a constant majorant. ## Reach for it when - path-traced smoke or clouds need unbiased results - heterogeneous volume sampling without a step size setting - ray-march banding in offline volume renders - sample scattering distances in a varying density medium ## How it works Sampling a distance proportional to transmittance is easy only when density is constant. Delta tracking picks a majorant sigma_max that bounds the true extinction everywhere along the ray, draws tentative step lengths from an exponential with rate sigma_max, and at each tentative point accepts a real collision with probability sigma_t(x) over sigma_max; otherwise it treats it as a null collision and continues in the same direction. Because only the density value, not an integral, is needed, it works with any procedural or voxel density. Variants include ratio tracking for estimating transmittance along shadow rays (multiplying by one minus the acceptance probability), residual tracking with a control medium, and spectral and decomposition tracking for chromatic media. A coarse majorant grid (often a DDA over a low-resolution max grid) keeps the null-collision count small. ## When to use it Choose it in a path tracer for clouds, smoke or explosions where you need unbiased heterogeneous transmittance and scattering without a step-size parameter. Prefer [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) for real-time, deterministic cost, and biased but cheap results. Prefer [Multiple-Scattering Approximation by Octaves](https://texelatlas.vercel.app/t/multiple-scattering-octaves.md) when you only want a plausible interactive multi-scatter look. Use [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md) or [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md) as the density store with a majorant grid. ## Cost offline — Number of null collisions depends on how tight the majorant is; a loose majorant over a sparse medium makes it very slow. Measured GPU Weight: 406.27× baseline (extreme) — 13.3662 ms median / 13.527 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 341.69× baseline (extreme) — 5.4328 ms median (2.46× faster on L4). Ampere A100 scaling: 302.49× baseline (extreme) — 8.7117 ms median (1.53× faster on A100). ## Failure modes - Loose majorants produce huge numbers of null collisions and long render times - High variance in thin media with an unlucky single sample, producing fireflies in direct lighting through ratio tracking - Chromatic media (different sigma per channel) bias or noise unless handled by spectral tracking - Lighting from small light sources in dense media needs next-event estimation or noise explodes - Majorant grid cells that do not cover the density interpolation kernel cause energy loss ## Engine support - blender: builtin — `Properties > Render > Volumes > Biased (leave disabled, the default) in Cycles` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/volumes.html, checked 2026-12-01) — The default (non-Biased) mode is based on null scattering, the generalisation of delta tracking. ## Dataflow - Inputs: volume-density - Outputs: radiance, hdr-image - Platforms: cpu, cuda, desktop-gpu, blender, houdini ## Presets ### Delta (Woodcock) tracking — heterogeneous volume free-flight & null-collision scatter (glsl-fragment; rendered 2026-11-30) ```json { "P_MAJORANT": 2.8, "P_DENSITY": 1.5, "P_ANISOTROPY": 0.62, "P_SCATTER_STEPS": 28 } ``` ```glsl const float P_MAJORANT = 2.8; // P Majorant SigmaMax [0.8, 5.0, 0.1] const float P_DENSITY = 1.5; // P Cloud Density [0.2, 3.2, 0.05] const float P_ANISOTROPY = 0.62; // P Phase g [0.0, 0.9, 0.02] const float P_SCATTER_STEPS = 28.0; // P Tracking Steps [8.0, 44.0, 1.0] float hash31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); } float noise3(vec3 p) { vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f); float n000 = hash31(i + vec3(0.0, 0.0, 0.0)); float n100 = hash31(i + vec3(1.0, 0.0, 0.0)); float n010 = hash31(i + vec3(0.0, 1.0, 0.0)); float n110 = hash31(i + vec3(1.0, 1.0, 0.0)); float n001 = hash31(i + vec3(0.0, 0.0, 1.0)); float n101 = hash31(i + vec3(1.0, 0.0, 1.0)); float n011 = hash31(i + vec3(0.0, 1.0, 1.0)); float n111 = hash31(i + vec3(1.0, 1.0, 1.0)); return mix( mix(mix(n000, n100, f.x), mix(n010, n110, f.x), f.y), mix(mix(n001, n101, f.x), mix(n011, n111, f.x), f.y), f.z ); } float fbm(vec3 p) { float v = 0.0, a = 0.52; for (int i = 0; i < 4; i++) { v += a * noise3(p); p = p * 2.04 + vec3(13.1, 7.7, 5.3); a *= 0.5; } return v; } // Heterogeneous extinction sigma_t(p) bounded inside sphere of radius 1.15 float evalSigmaT(vec3 p) { float r = length(p); if (r > 1.15) return 0.0; float fall = smoothstep(1.15, 0.28, r); vec3 q = p * 1.9 + vec3(iTime * 0.22, -iTime * 0.14, iTime * 0.18); float d = fbm(q) - 0.34; // Swirling filament structure float swirl = fbm(q * 1.6 + vec3(d * 1.5, -d, d * 0.8)); float dens = max(0.0, d * 1.45 + (swirl - 0.42) * 0.85) * fall; return dens * max(P_DENSITY, 0.05) * 2.2; } float hgPhase(float cosTheta, float g) { float g2 = g * g; return (1.0 - g2) / (12.56637 * pow(max(1.0 + g2 - 2.0 * g * cosTheta, 0.05), 1.5)); } vec2 intersectSphere(vec3 ro, vec3 rd, float rad) { float b = dot(ro, rd); float c = dot(ro, ro) - rad * rad; float h = b * b - c; if (h < 0.0) return vec2(-1.0); h = sqrt(h); return vec2(-b - h, -b + h); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float camAng = iTime * 0.25; vec3 ro = vec3(sin(camAng) * 2.85, 0.35, cos(camAng) * 2.85); vec3 ww = normalize(-ro); vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.45 * ww); vec3 sunDir = normalize(vec3(cos(iTime * 0.45 + 0.6), 0.52, sin(iTime * 0.45 + 0.6))); vec3 bg = mix(vec3(0.025, 0.04, 0.075), vec3(0.09, 0.14, 0.24), clamp(rd.y * 0.5 + 0.5, 0.0, 1.0)); bg += vec3(1.0, 0.78, 0.48) * pow(max(dot(rd, sunDir), 0.0), 48.0) * 1.4; vec2 hit = intersectSphere(ro, rd, 1.15); vec3 col = bg; if (hit.y > 0.0) { float t = max(hit.x, 0.0); float tEnd = hit.y; float sigmaMax = max(P_MAJORANT, 0.5); int maxSteps = int(clamp(P_SCATTER_STEPS, 6.0, 44.0)); float g = clamp(P_ANISOTROPY, 0.0, 0.92); // Ratio/Delta tracking estimator with null-collision free-flight sampling float seed = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453); float T = 1.0; vec3 L = vec3(0.0); float phase = hgPhase(dot(rd, sunDir), g); for (int i = 0; i < 44; i++) { if (i >= maxSteps || t >= tEnd || T < 0.015) break; float xi = fract(seed + float(i) * 0.61803398875); // Exponential free-flight step drawn from majorant sigmaMax float dt = -log(max(1.0 - xi * 0.96, 0.04)) / sigmaMax; dt = min(dt, (tEnd - t) + 0.01); t += dt; if (t >= tEnd) break; vec3 p = ro + rd * t; float sigmaT = evalSigmaT(p); // Ratio-tracking null-collision probability: 1 - sigmaT / sigmaMax float realProb = clamp(sigmaT / sigmaMax, 0.0, 1.0); if (realProb > 0.001) { // Short shadow transmittance ray toward sun via ratio tracking float Tsun = 1.0; for (int s = 1; s <= 5; s++) { vec3 sp = p + sunDir * (float(s) * 0.24); Tsun *= exp(-evalSigmaT(sp) * 0.24); } vec3 sunCol = vec3(2.8, 2.05, 1.35) * Tsun * (0.28 + 3.8 * phase); vec3 ambCol = mix(vec3(0.14, 0.24, 0.45), vec3(0.55, 0.68, 0.88), clamp(p.y * 0.5 + 0.5, 0.0, 1.0)) * 0.55; vec3 albedo = mix(vec3(0.95, 0.72, 0.52), vec3(0.92, 0.96, 1.0), clamp(Tsun, 0.0, 1.0)); L += T * realProb * albedo * (sunCol + ambCol); T *= (1.0 - realProb); } } // Subtle wireframe majorant bounding sphere rim to highlight the tracking domain float rim = pow(clamp(1.0 - abs(dot(normalize(ro + rd * max(hit.x, 0.0)), rd)), 0.0, 1.0), 4.0); col = L + bg * T + vec3(0.28, 0.62, 0.95) * rim * 0.22; } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md): Supplies density and a hierarchical max-grid that bounds the majorant along each ray. ## Combination ideas - [Strange attractors as lit clouds](https://texelatlas.vercel.app/ideas/attractor-clouds-delta-tracked/) ## Sources 1. [primary] Peter Kutz, Ralf Habel, Yining Karl Li, Jan Novák (2017) Spectral and decomposition tracking for rendering heterogeneous volumes. ACM Transactions on Graphics. https://doi.org/10.1145/3072959.3073665 (verified via crossref on 2026-11-29) 2. [primary] Jan Novák, Iliyan Georgiev, Johannes Hanika, Wojciech Jarosz (2018) Monte Carlo Methods for Volumetric Light Transport Simulation. Computer Graphics Forum. https://doi.org/10.1111/cgf.13383 (verified via crossref on 2026-11-29) 3. [implementation] mitsuba-renderer (2021) mitsuba-renderer/mitsuba3. https://github.com/mitsuba-renderer/mitsuba3 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Delta (Woodcock) Tracking." https://texelatlas.vercel.app/t/delta-tracking/ (accessed 2026-12-01). --- id: "depth-anything-v2" title: "Depth Anything V2" domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python, webgpu] year_introduced: 2024 inputs: [photos] outputs: [depth] style: "both" dynamic: "both" cost: "medium" authority: "Yang et al., 2024" url: "https://texelatlas.vercel.app/t/depth-anything-v2/" sources_verified_at: "2026-11-29" --- # Depth Anything V2 (Yang et al., 2024) > A monocular relative-depth model trained on synthetic labels plus pseudo-labelled real images, giving sharp, fine-detail depth maps from a single RGB image at several model sizes. ## Reach for it when - need depth from a single photo quickly - want parallax effect from one image - depth prior to condition a diffusion model - monocular depth maps look blurry and lose fine detail - get a depth guide for splat training without extra sensors ## How it works Depth Anything V2 uses a DINOv2-based encoder with a DPT decoder. Its main contribution is the training recipe: a large teacher is first trained only on accurate synthetic depth, avoiding the noisy labels of real-world depth sensors, then used to pseudo-label millions of unlabelled real images. Smaller student models are trained on these pseudo labels, which transfers synthetic sharpness to real images. Output is affine-invariant relative inverse depth, not metric, so scale and shift must be recovered separately if needed; fine-tuned metric variants exist. It handles thin structures, transparency and reflective surfaces better than earlier V1 and MiDaS-style models. ## When to use it Choose it for fast per-frame relative depth, depth conditioning for diffusion, parallax effects or depth priors for splat training. Prefer [Depth Pro](https://texelatlas.vercel.app/t/depth-pro.md) or [MoGe (Monocular Geometry Estimation)](https://texelatlas.vercel.app/t/moge.md) when you need metric scale or intrinsics, and [VGGT (Visual Geometry Grounded Transformer)](https://texelatlas.vercel.app/t/vggt.md) when multiple views are available and consistency matters. ## Cost medium — Small variants run in real time on modern GPUs; large ones are interactive. Only the small model carries a permissive Apache-2.0 licence. Measured GPU Weight: 34.92× baseline (heavy) — 1.1488 ms median / 1.2269 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 34.72× baseline (heavy) — 0.5521 ms median (2.08× faster on L4). Ampere A100 scaling: 23.1× baseline (heavy) — 0.6653 ms median (1.73× faster on A100). ## Failure modes - Output is relative, so depth scale and shift are inconsistent across frames in video (flicker) - Sky and far regions can be unreliable - Edges are sharp visually but not metrically accurate for geometry - Metric conversion needs fine-tuned variants or external scale ## Dataflow - Inputs: photos - Outputs: depth - Platforms: cuda, python, webgpu ## Presets ### Depth Anything V2 — single RGB input view (left) vs fine-detail monocular relative depth (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DEPTH_CONT": 1, "P_CAM_SWAY": 0.75, "P_EDGE_SHARP": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_DEPTH_CONT = 1.0; // P Depth Contrast [0.4, 1.8, 0.05] const float P_CAM_SWAY = 0.75; // P Camera Sway [0.0, 2.0, 0.05] const float P_EDGE_SHARP = 1.0; // P Fine Structure [0.2, 1.5, 0.05] const float P_SPLIT = 0.48; // P RGB / Depth Split [0.0, 1.0, 0.02] 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); } // Architectural colonnade with thin foreground railings, mid-ground arch, and distant tower vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); // stone floor // Foreground thin railing posts & handrail (showcases Depth Anything V2 fine thin-structure fidelity!) float rx = mod(p.x + 0.25, 0.5) - 0.25; float post = sdBox(vec3(rx, p.y + 0.42, p.z - 0.15), vec3(0.022, 0.42, 0.022)); float rail = sdBox(p - vec3(0.0, -0.02, 0.15), vec3(2.4, 0.025, 0.03)); float dRail = min(post, rail); if (dRail < res.x) res = vec2(dRail, 2.0); // Midground colonnade pillars & floating bronze sphere float colL = sdBox(p - vec3(-0.78, 0.05, -1.15), vec3(0.18, 0.90, 0.18)); float colR = sdBox(p - vec3(0.78, 0.05, -1.15), vec3(0.18, 0.90, 0.18)); float lintel = sdBox(p - vec3(0.0, 0.82, -1.15), vec3(1.15, 0.14, 0.22)); float dArch = min(min(colL, colR), lintel); if (dArch < res.x) res = vec2(dArch, 3.0); float dOrb = length(p - vec3(0.02, -0.18, -1.10)) - 0.34; if (dOrb < res.x) res = vec2(dOrb, 4.0); // Distant monumental obelisk / tower float dTower = sdBox(p - vec3(-0.18, 0.35, -3.45), vec3(0.36, 1.25, 0.36)); if (dTower < res.x) res = vec2(dTower, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Inferno-like perceptual disparity colormap (bright yellow-white = near, crimson = mid, deep indigo = far) vec3 infernoRamp(float d) { float t = clamp(d, 0.0, 1.0); vec3 c0 = vec3(0.03, 0.02, 0.14); vec3 c1 = vec3(0.36, 0.07, 0.44); vec3 c2 = vec3(0.84, 0.26, 0.24); vec3 c3 = vec3(0.98, 0.68, 0.16); vec3 c4 = vec3(0.99, 0.97, 0.68); if (t < 0.25) return mix(c0, c1, t * 4.0); if (t < 0.50) return mix(c1, c2, (t - 0.25) * 4.0); if (t < 0.75) return mix(c2, c3, (t - 0.50) * 4.0); return mix(c3, c4, (t - 0.75) * 4.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isDepth = screenX >= split; float cont = clamp(P_DEPTH_CONT, 0.3, 2.0); float sway = clamp(P_CAM_SWAY, 0.0, 2.0); float sharp = clamp(P_EDGE_SHARP, 0.1, 1.6); vec3 ro = vec3(sin(iTime * 0.55 * sway) * 0.36, 0.24, 1.65); vec3 rd = normalize(vec3(uv.x - sin(iTime * 0.55 * sway) * 0.08, uv.y - 0.06, -1.35)); float t = 0.05; vec2 hit = vec2(12.0, 0.0); for (int i = 0; i < 60; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.003) { hit = vec2(t, h.y); break; } t += h.x; if (t > 12.0) break; } vec3 col; if (!isDepth) { // Left: Standard monocular RGB camera view vec3 sky = mix(vec3(0.86, 0.66, 0.50), vec3(0.24, 0.44, 0.74), smoothstep(-0.08, 0.52, rd.y)); col = sky; if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 lDir = normalize(vec3(0.58, 0.78, 0.48)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 32.0); vec3 alb = vec3(0.76, 0.72, 0.66); if (hit.y < 1.5) { vec2 tile = floor(p.xz * 2.0); alb = mix(vec3(0.32, 0.30, 0.28), vec3(0.52, 0.48, 0.44), mod(tile.x + tile.y, 2.0)); } else if (hit.y < 2.5) alb = vec3(0.16, 0.20, 0.26); else if (hit.y < 3.5) alb = vec3(0.82, 0.74, 0.64); else if (hit.y < 4.5) alb = vec3(0.88, 0.46, 0.22); else alb = vec3(0.46, 0.52, 0.62); col = alb * (0.28 + 0.85 * diff) + vec3(1.0) * spec * (hit.y > 3.5 && hit.y < 4.5 ? 0.55 : 0.16); col = mix(col, sky, 1.0 - exp(-hit.x * 0.08)); } } else { // Right: Crisp affine-invariant inverse-depth disparity (1/z) predicted by Depth Anything V2 float invZ = (hit.y > 0.5) ? (1.28 / max(hit.x, 0.35)) : 0.02; float disp = clamp(pow(clamp(invZ, 0.0, 1.0), 0.85 / cont), 0.0, 1.0); // Subtle iso-depth contours to reveal smooth continuous metric gradient float iso = 0.90 + 0.10 * cos(disp * 42.0 * sharp); col = infernoRamp(disp) * iso; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md): Monocular depth priors regularise Gaussian training in sparse-view settings. ## Combination ideas - [Light shafts for any photo](https://texelatlas.vercel.app/ideas/photo-depth-god-rays/) ## Sources 1. [primary] Lihe Yang, Bingyi Kang, Zilong Huang, Zhen Zhao, Xiaogang Xu, Jiashi Feng, Hengshuang Zhao (2024) Depth Anything V2. arXiv preprint (cs.CV). https://arxiv.org/abs/2406.09414 (verified via arxiv on 2026-11-29) 2. [implementation] DepthAnything (2024) DepthAnything/Depth-Anything-V2. https://github.com/DepthAnything/Depth-Anything-V2 License: Apache-2.0. (verified via github on 2026-11-29) 3. [tutorial] Yang et al. Depth Anything V2 project page. depth-anything-v2.github.io. https://depth-anything-v2.github.io/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Depth Anything V2." https://texelatlas.vercel.app/t/depth-anything-v2/ (accessed 2026-12-01). --- id: "depth-of-field-scatter-as-gather" title: "Scatter-as-gather bokeh depth of field" aliases: [DoF] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2014 inputs: [hdr-image, depth] outputs: [hdr-image] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Jimenez" url: "https://texelatlas.vercel.app/t/depth-of-field-scatter-as-gather/" sources_verified_at: "2026-11-29" --- # Scatter-as-gather bokeh depth of field (Jimenez) > Depth of field from a circle of confusion buffer: far and near fields are split, blurred with a gather kernel that emulates scatter of bright points into bokeh discs, then composited with the sharp focus layer. ## Reach for it when - blurry foreground leaks sharp edges around subject - bokeh blur looks wrong near depth discontinuities - realistic camera focus blur in real time - near field blur must spread over in-focus objects ## How it works A circle-of-confusion value is computed per pixel from depth, focus distance, aperture and focal length. The image is split into a near-field layer (which must bleed over the in-focus region) and a far-field layer, each premultiplied by its CoC weight and downsampled. A gather pass samples in a disc pattern around each pixel, but instead of taking all samples equally it keeps a sample only if its own CoC is large enough to reach the centre pixel, which approximates scattering each sample as a bokeh disc. Tap positions follow a spiral or Poisson pattern and the bokeh shape is controlled by the kernel. A small post-blur removes undersampling noise, and the layers are composited with the full-resolution in-focus layer using the CoC as alpha. ## When to use it Choose it when you want convincing bokeh with highlights that read as discs and correct near-field bleeding at interactive cost. Prefer a cheap Gaussian or Kawase blur when you only need a soft background and have no budget. Prefer [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md) when you want glow rather than a lens model. ## Cost medium — Gather with tens of taps at half or quarter resolution, plus composite; qualitative. Measured GPU Weight: 111.02× baseline (extreme) — 3.6526 ms median / 3.867 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 96.15× baseline (extreme) — 1.5288 ms median (2.39× faster on L4). Ampere A100 scaling: 70.84× baseline (extreme) — 2.0403 ms median (1.79× faster on A100). ## Failure modes - Disocclusion artifacts: sharp objects cannot blur over the background that they hide - Visible tap patterns or noise when undersampled - Sharp silhouettes with halos around in-focus objects against blurred backgrounds - Transparent objects and particles lack depth and stay sharp ## Engine support - babylonjs: builtin — `DefaultRenderingPipeline.depthOfFieldEnabled (DepthOfFieldEffect)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/depthOfFieldEffect.ts, checked 2026-12-01) - blender: builtin — `EEVEE Render Properties > Depth of Field (gather/scatter bokeh blur driven by Camera Aperture)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/depth_of_field.html, checked 2026-12-01) - godot: builtin — `CameraAttributesPractical > dof_blur_far_enabled / dof_blur_near_enabled (gather-based bokeh depth of field)` (evidence: https://github.com/godotengine/godot/blob/4.4-stable/scene/resources/camera_attributes.cpp, checked 2026-12-01) - threejs: official — `import { dof } from 'three/addons/tsl/display/DepthOfFieldNode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/DepthOfFieldNode.js, checked 2026-12-01) - unreal: builtin — `Post Process Volume or Cine Camera > Lens > Depth of Field (Cinematic Diaphragm bokeh DOF)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/cinematic-depth-of-field-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image, depth - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Left: pinhole. Right: gather DoF, each tap weighted by whether its own circle of confusion reaches the pixel (glsl-fragment; rendered 2026-11-29) ```json { "RM": 0.05, "FOCUS": 0.5, "NT": 96 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float RM=0.05; // P const float FOCUS=0.5; // P const int NT=96; // P vec4 scn(vec2 p){ vec3 c=mix(vec3(.04,.05,.1),vec3(.14,.09,.2),p.y+.5);float z=1.; vec2 g=p*13.,id=floor(g);float h=hash(id); vec2 cp=(id+.5+(vec2(hash(id+3.),hash(id+7.))-.5)*.5)/13.; if(h>.45)c+=vec3(1.,.75+.2*hash(id+1.),.45+.5*hash(id+2.))*6.*smoothstep(.002,-.002,length(p-cp)-.011); float r=length(p-vec2(0.,-.02)); if(abs(r-.14)<.026){c=vec3(.9,.85,.7)*(.35+.65*step(.5,fract(atan(p.y,p.x)*3.8197)));z=.5;} if(length(p-vec2(.18,-.3))<.07){c=vec3(.2,.7,.4)*(.6+.4*sin(p.x*120.));z=.12;} return vec4(c,z);} float coc(float z){return clamp(abs(z-FOCUS)*2.,0.,1.);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col; if(!R) col=scn(q).rgb; else{vec4 c0=scn(q);vec3 acc=c0.rgb*.001;float ws=.001; for(int i=0;ic0.w+.01)w*=smoothstep(0.,.35,coc(c0.w));acc+=s.rgb*w;ws+=w;} col=acc/ws;} col=col/(1.+col*.6); if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Combines with - [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md): HDR highlights drive both bokeh shape and glow; share the downsampled buffers. ## Sources 1. [primary] Jorge Jimenez Next Generation Post Processing in Call of Duty: Advanced Warfare. SIGGRAPH 2014 Advances in Real-Time Rendering. https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare (verified via http on 2026-11-29) 2. [implementation] pmndrs (2015) pmndrs/postprocessing. https://github.com/pmndrs/postprocessing License: Zlib. (verified via github on 2026-11-29) ## Cite this entry Texel. "Scatter-as-gather bokeh depth of field." https://texelatlas.vercel.app/t/depth-of-field-scatter-as-gather/ (accessed 2026-12-01). --- id: "depth-pro" title: "Depth Pro" domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [photos] outputs: [depth] style: "photoreal" dynamic: "both" cost: "heavy" authority: "Bochkovskii et al., 2024" url: "https://texelatlas.vercel.app/t/depth-pro/" sources_verified_at: "2026-11-29" --- # Depth Pro (Bochkovskii et al., 2024) > A monocular model producing sharp metric depth maps at high resolution without needing camera intrinsics, plus a focal length estimate, in about a second per image. ## Reach for it when - need metric depth from one photo without calibration - depth maps are too blurry at object edges - don't know camera focal length for a single image - place ar content at real scale from a single picture ## How it works A multi-scale ViT applies a shared patch encoder to image crops at several scales, merging the features into a high-resolution feature pyramid, with a DPT-style decoder producing a canonical inverse depth map. This keeps global context while capturing fine boundaries. Training uses a two-stage curriculum with a mix of real and synthetic data, with losses that explicitly reward boundary sharpness, and the model additionally has a separate focal-length head, allowing metric output without EXIF intrinsics. Outputs are in metres with a field-of-view estimate. The authors also propose boundary-accuracy metrics based on matting and segmentation datasets. ## When to use it Choose it when you need metric depth from a single image with no calibration, e.g. for AR placement or to scale an SfM-free pipeline. Prefer [Depth Anything V2](https://texelatlas.vercel.app/t/depth-anything-v2.md) for speed or video-friendly relative depth, [MoGe (Monocular Geometry Estimation)](https://texelatlas.vercel.app/t/moge.md) when you need a point map with intrinsics, and [VGGT (Visual Geometry Grounded Transformer)](https://texelatlas.vercel.app/t/vggt.md) for multi-view consistency. ## Cost heavy — Around a second per megapixel-class image on a GPU as claimed by the authors; not suited to per-frame real time. ## Failure modes - Metric scale is a learned prior, so it errs on unusual scenes (miniatures, abstract renders) - Focal length estimate can be wrong for crops or lens-distorted images - Per-frame prediction flickers in video - Sample code licence is restrictive, check repo before commercial use ## Dataflow - Inputs: photos - Outputs: depth - Platforms: cuda, python ## Sources 1. [primary] Aleksei Bochkovskii, Amaël Delaunoy, Hugo Germain, Marcel Santos, Yichao Zhou, Stephan R. Richter, Vladlen Koltun (2024) Depth Pro: Sharp Monocular Metric Depth in Less Than a Second. arXiv preprint (cs.CV). https://arxiv.org/abs/2410.02073 (verified via arxiv on 2026-11-29) 2. [implementation] apple-aiml-research (2024) apple-aiml-research/ml-depth-pro. https://github.com/apple-aiml-research/ml-depth-pro License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Depth Pro." https://texelatlas.vercel.app/t/depth-pro/ (accessed 2026-12-01). --- id: "directional-voxel-sky-ao-volumes" title: "Local-Frame 6-Axis Directional Voxel Sky-Visibility Volumes" aliases: [directional voxel AO volume, 6-axis voxel sky visibility, per-building voxel AO volume] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu] year_introduced: 2026 inputs: [voxels, normals] outputs: [visibility-mask, texture] style: "both" dynamic: "static" cost: "cheap" authority: "Leonxlnx, 2026" url: "https://texelatlas.vercel.app/t/directional-voxel-sky-ao-volumes/" sources_verified_at: "2026-11-30" --- # Local-Frame 6-Axis Directional Voxel Sky-Visibility Volumes (Leonxlnx, 2026) > Precomputes sky visibility along six local-frame cardinal lobes (±X, ±Y, ±Z) inside a coarse per-structure voxel grid packed into two RGBA8 3D textures, giving architectural interiors view-independent directional AO with zero screen-space passes. ## Reach for it when - need soft sky occlusion and bounce tint inside voxel caves - screen space ao misses overhanging arches and off-screen roofs - want directional ambient lighting for destructible voxel worlds - uniform ambient term makes voxel overhangs look flat and ungrounded - cheap prefiltered sky visibility lookup for dynamic block terrain ## How it works Screen-space ambient occlusion fails inside deep architectural recesses, colonnades, and overhangs because off-screen roofs and walls are invisible in the depth buffer. A **local-frame 6-axis directional voxel sky-visibility volume** bakes large-scale occlusion directly around each building or modular structure in its own local coordinate frame. First, simplified proxy primitives (boxes, cylinders, prisms, or implicit predicates) rasterize into a coarse binary occupancy grid enclosing the structure. Only empty voxels within a small band of solid cells need evaluation. From each near-surface voxel, Fibonacci-sphere rays are marched through the voxel grid up to a cutoff distance to test whether they escape to the sky or strike an occluder (with a small floor value to emulate ambient bounce). Rather than collapsing visibility to a single scalar, ray hits are cosine-weighted onto the six axis-aligned directional lobes (`+X`, `-X`, `+Y`, `-Y`, `+Z`, `-Z`) and packed into two compact `RGBA8` 3D textures. At shade time, world positions and normals transform into the structure's local frame, offset slightly along the surface normal (`P + N * cell`) to prevent self-occlusion, and blend the three positive or negative lobe channels matching the normal's sign using squared normal weights. ## When to use it Choose it for architectural exteriors and semi-enclosed spaces—temples, porticoes, bridges, and modular buildings—where you want stable, view-independent directional sky occlusion that survives camera cuts and instanced building rotations without UV lightmaps. Prefer [ground-truth-ambient-occlusion](ground-truth-ambient-occlusion) or [hbao](hbao) for fine contact creases and dynamic characters. Prefer [sdf-ambient-occlusion](sdf-ambient-occlusion) when the entire scene already has a continuous signed distance field. Prefer [voxel-cone-tracing](voxel-cone-tracing) when dynamic geometry and multi-bounce color bleeding are required. ## Cost cheap — Runtime evaluation is two hardware trilinear 3D texture fetches per shaded fragment; CPU baking a coarse architectural grid takes milliseconds to a fraction of a second. Measured GPU Weight: 71.06× baseline (extreme) — 2.3379 ms median / 2.4713 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 75.4× baseline (extreme) — 1.1988 ms median (1.95× faster on L4). Ampere A100 scaling: 46.55× baseline (heavy) — 1.3407 ms median (1.74× faster on A100). ## Failure modes - Coarse voxel cell size misses sub-cell crevices, moldings, and thin brackets unless layered with screen-space AO - Thin walls narrower than one voxel can leak sky visibility across interior and exterior rooms if the normal offset crosses the wall - Static local occupancy does not react to moving doors, dynamic props, or nearby neighboring buildings outside the local volume bounds - Axis-aligned 6-lobe basis smooths out sharp diagonal occlusion openings compared to higher-order spherical harmonics or ray-traced AO ## Dataflow - Inputs: voxels, normals - Outputs: visibility-mask, texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu ## Presets ### Local-Frame 6-Axis Directional Voxel Sky-AO — 6-lobe coarse voxel sky visibility (left) vs trilinear directional sky AO lighting (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VOXEL_SIZE": 6, "P_AO_POWER": 1.25, "P_SUN_ANGLE": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_VOXEL_SIZE = 6.00; // P Voxel Grid Res [3.0, 12.0, 1.0] const float P_AO_POWER = 1.25; // P Sky AO Strength [0.2, 2.2, 0.05] const float P_SUN_ANGLE = 0.55; // P Sun Motion [0.0, 1.8, 0.05] const float P_SPLIT = 0.48; // P 6-Axis Voxels / AO [0.0, 1.0, 0.02] 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); } // Deep architectural colonnade with heavy overhanging roof (classic SSAO failure case!) vec2 mapColonnade(vec3 p) { float dFloor = p.y + 0.62; vec2 res = vec2(dFloor, 1.0); // Heavy overhanging cantilevered roof slab (off-screen sky occluder!) float dRoof = sdBox(p - vec3(0.0, 0.58, -0.35), vec3(1.15, 0.10, 0.85)); if (dRoof < res.x) res = vec2(dRoof, 2.0); // Back recessed colonnade wall float dBack = sdBox(p - vec3(0.0, 0.0, -1.15), vec3(1.20, 0.65, 0.12)); if (dBack < res.x) res = vec2(dBack, 3.0); // Four square colonnade pillars supporting the overhang for (int i = 0; i < 4; i++) { float x = -0.82 + float(i) * 0.546; float dPil = sdBox(p - vec3(x, -0.02, 0.25), vec3(0.10, 0.60, 0.10)); if (dPil < res.x) res = vec2(dPil, 4.0); } // Center recessed sculptural pedestal inside the dark colonnade float dSph = length(p - vec3(0.0, -0.34, -0.35)) - 0.28; if (dSph < res.x) res = vec2(dSph, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapColonnade(p + e.xyy).x - mapColonnade(p - e.xyy).x, mapColonnade(p + e.yxy).x - mapColonnade(p - e.yxy).x, mapColonnade(p + e.yyx).x - mapColonnade(p - e.yyx).x )); } // Evaluate sky visibility along one of the 6 local-frame cardinal lobes (+X,-X,+Y,-Y,+Z,-Z) float traceSkyLobe(vec3 p, vec3 dir) { float vis = 1.0; float t = 0.08; for (int i = 0; i < 8; i++) { float h = mapColonnade(p + dir * t).x; vis = min(vis, clamp(h / max(t * 0.65, 0.05), 0.0, 1.0)); t += max(h, 0.14); } return clamp(vis, 0.05, 1.0); } // Compute 6-axis directional sky visibility volume value for position p & normal n float evalDirectionalVoxelAO(vec3 p, vec3 n) { float visX = (n.x >= 0.0) ? traceSkyLobe(p, vec3(1.0, 0.35, 0.0)) : traceSkyLobe(p, vec3(-1.0, 0.35, 0.0)); float visY = (n.y >= 0.0) ? traceSkyLobe(p, vec3(0.0, 1.0, 0.0)) : traceSkyLobe(p, vec3(0.0, -0.25, 0.95)); float visZ = (n.z >= 0.0) ? traceSkyLobe(p, vec3(0.0, 0.35, 1.0)) : traceSkyLobe(p, vec3(0.0, 0.35, -1.0)); vec3 w = n * n; return w.x * visX + w.y * visY + w.z * visZ; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float vRes = clamp(floor(P_VOXEL_SIZE + 0.5), 3.0, 12.0); float aoPow = clamp(P_AO_POWER, 0.2, 2.5); float t = iTime * max(P_SUN_ANGLE, 0.0); vec3 ro = vec3(0.28 * sin(t * 0.45), 0.06, 2.15); vec3 rd = normalize(vec3(uv.x, uv.y - 0.04, -1.42)); vec3 sky = mix(vec3(0.68, 0.78, 0.90), vec3(0.18, 0.42, 0.78), smoothstep(-0.1, 0.6, rd.y)); vec3 col = sky; float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapColonnade(ro + rd * dist); if (h.x < 0.0025) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 8.0) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 sunDir = normalize(vec3(0.55 * cos(t * 0.4), 0.42, 0.72)); // Direct sun shadow float sh = 1.0; float ts = 0.04; for (int s = 0; s < 18; s++) { float ds = mapColonnade(p + sunDir * ts).x; if (ds < 0.004) { sh = 0.0; break; } ts += max(ds, 0.04); if (ts > 3.2) break; } vec3 alb = vec3(0.80, 0.76, 0.70); if (hit.y > 4.5) alb = vec3(0.88, 0.56, 0.28); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.74, 0.68, 0.62); if (screenX < split) { // Left: Raw quantized local-frame 6-axis voxel sky-visibility volume + directional axis color coding vec3 vPos = (floor(p * vRes) + 0.5) / vRes; float voxAO = pow(evalDirectionalVoxelAO(vPos, n), aoPow); vec3 fracV = abs(fract(p * vRes) - 0.5); float vEdge = smoothstep(0.055, 0.015, min(min(0.5 - fracV.x, 0.5 - fracV.y), 0.5 - fracV.z)); vec3 axisTint = abs(n) * vec3(0.95, 0.85, 0.98) + vec3(0.25); col = mix(vec3(0.05, 0.08, 0.14), vec3(0.45, 0.84, 1.0) * axisTint, voxAO); col = mix(col, vec3(0.95, 0.98, 1.0), vEdge * 0.28); } else { // Right: Smooth trilinear 6-axis directional sky AO illuminating deep recesses under the overhanging roof! float skyVis = pow(evalDirectionalVoxelAO(p + n * 0.03, n), aoPow); vec3 direct = alb * vec3(1.18, 1.02, 0.84) * max(dot(n, sunDir), 0.0) * sh; vec3 skyAmb = alb * mix(vec3(0.26, 0.36, 0.52), vec3(0.46, 0.68, 0.96), 0.5 + 0.5 * n.y) * skyVis * 0.95; col = direct + skyAmb; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md): Modulates physically based ambient sky irradiance with directional sky visibility so shaded ceilings and colonnades receive realistic skylight falloff. - [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md): Supplies soft ambient sky occlusion in shadowed recesses where direct sunlight from the shadow map is blocked. ## Sources 1. [primary] Leonxlnx (2026) Leonxlnx/athenaion. https://github.com/Leonxlnx/athenaion License: MIT. (verified via github on 2026-11-30) 2. [secondary] Morgan McGuire (2010) Ambient occlusion volumes. Proceedings of the 2010 ACM SIGGRAPH symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/1730804.1730984 (verified via crossref on 2026-11-30) 3. [secondary] Cyril Crassin, Fabrice Neyret, Miguel Sainz, Simon Green, Elmar Eisemann (2011) Interactive Indirect Illumination Using Voxel Cone Tracing. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2011.02063.x (verified via crossref on 2026-11-30) ## Cite this entry Texel. "Local-Frame 6-Axis Directional Voxel Sky-Visibility Volumes." https://texelatlas.vercel.app/t/directional-voxel-sky-ao-volumes/ (accessed 2026-12-01). --- id: "discrete-elastic-rods" title: "Discrete elastic rods (hair and rope simulation)" aliases: [DER, Cosserat rods, elastic rod model] domain: "simulation" stage: "simulation" realtime: "interactive" platforms: [cpu, cuda, houdini, python] year_introduced: 2008 inputs: [curves] outputs: [curves, animation] style: "both" dynamic: "dynamic" cost: "offline" authority: "Bergou et al., 2008" url: "https://texelatlas.vercel.app/t/discrete-elastic-rods/" sources_verified_at: "2026-11-29" --- # Discrete elastic rods (hair and rope simulation) (Bergou et al., 2008) > Treat hair, rope or cable as a chain of edges with a material frame per edge; bending and twisting energies come from curvature and twist of the discrete curve, giving physically meaningful stiffness. ## Reach for it when - hair or rope needs real bending and twist stiffness - curly strands coil naturally and hold their shape - cable simulation with physically meaningful material parameters - thin elastic strands blow up under stiff explicit integration ## How it works A rod is a polyline of vertices with an orthonormal material frame attached to every edge. The state is vertex positions plus one twist angle per edge. Energies are written discretely: stretching from edge length, bending from the curvature binormal at each interior vertex computed in the two adjacent material frames, and twisting from the change in angle between consecutive frames after a parallel transport of the reference frame along the curve. Because the reference frame is propagated by parallel transport (the idea behind [Rotation-Minimizing Frames](https://texelatlas.vercel.app/t/rotation-minimizing-frames.md)), twist is measured as a scalar, avoiding frame singularities. Forces and Hessians follow by differentiating the energies; the system is integrated with implicit Euler or a variational scheme, and Newton iterations on a banded system keep the cost linear in segment count. Collisions, friction and contact with a body are handled with penalty or constraint terms around this core. ## When to use it Choose it when physical fidelity of thin elastic structures matters: hair curls, coiling ropes, cables, sutures and sweaters at offline or interactive rates, where bending and twist stiffness have to be real material parameters. Prefer [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md) or [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) strands when stability, speed and artistic control matter more than physical units, and [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) for large hair counts in games. Prefer [Implicit cloth integration (Baraff-Witkin)](https://texelatlas.vercel.app/t/implicit-cloth-integration.md) for two-dimensional sheets. ## Cost offline — Linear per rod with implicit integration, but production hair counts and contact handling keep it offline or interactive-only. Measured GPU Weight: 161.22× baseline (extreme) — 5.0622 ms median / 5.202 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 147.99× baseline (extreme) — 2.3383 ms median (2.16× faster on L4). Ampere A100 scaling: 106.68× baseline (extreme) — 3.0725 ms median (1.65× faster on A100). ## Failure modes - Stiff systems need implicit integration; explicit steps explode at realistic bending stiffness - Frame twisting near straight segments loses the reference frame if parallel transport is not handled with care - Self-collision between strands is expensive and often left to a separate contact model - Newton solves can fail to converge at large timesteps or under strong contact - Per-edge frames add state that game engines rarely store, complicating export ## Dataflow - Inputs: curves - Outputs: curves, animation - Platforms: cpu, cuda, houdini, python ## Presets ### Discrete elastic rods — 3D Bishop-frame twisted helices, material-frame twist stripes & bend energy (glsl-fragment; rendered 2026-11-30) ```json { "P_TWIST_RATE": 3.2, "P_BEND_AMP": 0.42, "P_ROD_RADIUS": 0.085, "P_ANIM_SPEED": 1 } ``` ```glsl const float P_TWIST_RATE = 3.2; // P Material Twist [0.5, 7.0, 0.1] const float P_BEND_AMP = 0.42; // P Helical Buckling [0.1, 0.75, 0.02] const float P_ROD_RADIUS = 0.085; // P Rod Thickness [0.04, 0.14, 0.005] const float P_ANIM_SPEED = 1.0; // P Wave Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Centerline of a buckled elastic rod parametrized by arc parameter s in [-1.4, 1.4] vec3 rodCenter(float s, float rodId, float t, float bendAmp) { float ph = rodId * 2.094395 + t * 0.85; // Buckling envelope strongest in middle, clamped at endpoints float env = cos(clamp(s * 0.95, -1.5708, 1.5708)); float rHelix = bendAmp * (0.35 + 0.65 * env * env); float freq = 3.2 + 0.45 * sin(t * 0.5 + rodId); return vec3( s * 0.92, rHelix * cos(s * freq + ph), rHelix * sin(s * freq + ph) ); } // Evaluate distance to 3 intertwined elastic rods + return (dist, rodId, arcS, frameAngle) vec4 mapRods(vec3 p, float t, float bendAmp, float rodRad) { vec3 q = p; q.xz = rot2(t * 0.25) * q.xz; q.yz = rot2(0.28) * q.yz; float bestD = 1e5; float bestId = 0.0; float bestS = 0.0; float bestPhi = 0.0; for (int r = 0; r < 3; r++) { float fr = float(r); // Approximate nearest arc-length parameter s via 2-step Newton projection from q.x float s = clamp(q.x / 0.92, -1.35, 1.35); for (int k = 0; k < 2; k++) { vec3 c0 = rodCenter(s, fr, t, bendAmp); vec3 c1 = rodCenter(s + 0.015, fr, t, bendAmp); vec3 tang = normalize(c1 - c0); float ds = dot(q - c0, tang) * 0.62; s = clamp(s + ds, -1.35, 1.35); } vec3 c = rodCenter(s, fr, t, bendAmp); vec3 cNext = rodCenter(s + 0.02, fr, t, bendAmp); vec3 T = normalize(cNext - c); // Parallel-transported Bishop reference frame (U, V) orthogonal to tangent T vec3 upRef = vec3(0.0, 1.0, 0.0); vec3 U = normalize(cross(T, upRef) + vec3(0.0, 0.0, 1e-4)); vec3 V = cross(T, U); vec3 rel = q - c; float d = length(rel) - rodRad; if (d < bestD) { bestD = d; bestId = fr; bestS = s; bestPhi = atan(dot(rel, V), dot(rel, U)); } } return vec4(bestD * 0.78, bestId, bestS, bestPhi); } vec3 calcNormal(vec3 p, float t, float bendAmp, float rodRad) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRods(p + e.xyy, t, bendAmp, rodRad).x - mapRods(p - e.xyy, t, bendAmp, rodRad).x, mapRods(p + e.yxy, t, bendAmp, rodRad).x - mapRods(p - e.yxy, t, bendAmp, rodRad).x, mapRods(p + e.yyx, t, bendAmp, rodRad).x - mapRods(p - e.yyx, t, bendAmp, rodRad).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float tAnim = iTime * max(P_ANIM_SPEED, 0.0); float twist = clamp(P_TWIST_RATE, 0.2, 8.0); float bendAmp = clamp(P_BEND_AMP, 0.08, 0.85); float rodRad = clamp(P_ROD_RADIUS, 0.035, 0.16); vec3 ro = vec3(0.0, 0.08, 2.55); vec3 rd = normalize(vec3(uv, -1.55)); // Studio slate background vec3 col = mix(vec3(0.03, 0.04, 0.068), vec3(0.09, 0.115, 0.165), smoothstep(-0.55, 0.55, uv.y)); vec2 bgG = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.045) * smoothstep(0.03, 0.0, min(bgG.x, bgG.y)); float t = 0.0; vec4 hitRes = vec4(0.0); bool hit = false; for (int i = 0; i < 68; i++) { vec4 h = mapRods(ro + rd * t, tAnim, bendAmp, rodRad); if (h.x < 0.002) { hit = true; hitRes = h; break; } t += h.x; if (t > 8.5) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, tAnim, bendAmp, rodRad); float rodId = hitRes.y; float s = hitRes.z; float phi = hitRes.w; // Material frame angle theta(s) rotates relative to the twist-free Bishop frame! float matAngle = phi - s * twist * 2.2 - tAnim * 1.4; float twistStripe = smoothstep(-0.12, 0.12, sin(matAngle * 2.0)); // Discrete vertex segment rings along the elastic rod polyline float segRing = smoothstep(0.075, 0.015, abs(fract(s * 6.5) - 0.5)); // Curvature energy glow highest near high-buckling midspan float bendEnergy = cos(clamp(s * 0.95, -1.5708, 1.5708)); bendEnergy = bendEnergy * bendEnergy * clamp(bendAmp * 1.8, 0.0, 1.0); vec3 baseA, baseB; if (rodId < 0.5) { baseA = vec3(0.16, 0.62, 0.92); baseB = vec3(0.96, 0.82, 0.32); } else if (rodId < 1.5) { baseA = vec3(0.92, 0.34, 0.28); baseB = vec3(0.96, 0.92, 0.86); } else { baseA = vec3(0.18, 0.82, 0.58); baseB = vec3(0.14, 0.24, 0.38); } vec3 alb = mix(baseA, baseB, twistStripe); alb = mix(alb, vec3(0.06, 0.08, 0.12), segRing * 0.45); vec3 l1 = normalize(vec3(0.62, 0.85, 0.58)); vec3 l2 = normalize(vec3(-0.75, -0.22, 0.52)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 46.0) * 0.65; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 2.8) * 0.38; col = alb * (0.24 + 0.86 * diff1 + 0.25 * diff2) + vec3(spec) + vec3(0.55, 0.78, 1.0) * rim; col += vec3(1.0, 0.52, 0.18) * bendEnergy * 0.16; } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Rotation-Minimizing Frames](https://texelatlas.vercel.app/t/rotation-minimizing-frames.md): Parallel-transported reference frames along the rod give the twist measure the elastic energy needs. ## Sources 1. [primary] Miklós Bergou, Max Wardetzky, Stephen Robinson, Basile Audoly, Eitan Grinspun (2008) Discrete elastic rods. ACM Transactions on Graphics. https://doi.org/10.1145/1360612.1360662 (verified via crossref on 2026-11-29) 2. [primary] Miklós Bergou, Basile Audoly, Etienne Vouga, Max Wardetzky, Eitan Grinspun (2010) Discrete viscous threads. ACM Transactions on Graphics. https://doi.org/10.1145/1778765.1778853 (verified via crossref on 2026-11-29) 3. [tutorial] Bergou, Wardetzky, Robinson, Audoly, Grinspun Discrete Elastic Rods project page (Columbia Computer Graphics Group). cs.columbia.edu. http://www.cs.columbia.edu/cg/rods (verified via http on 2026-11-29) 4. [implementation] jpanetta (2019) jpanetta/ElasticRods. https://github.com/jpanetta/ElasticRods License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Discrete elastic rods (hair and rope simulation)." https://texelatlas.vercel.app/t/discrete-elastic-rods/ (accessed 2026-12-01). --- id: "disney-hair-bsdf" title: "Disney / Chiang hair and fur BSDF" aliases: [Chiang hair BSDF, Hair and fur model for production path tracing] domain: "materials" stage: "material" realtime: "interactive" platforms: [cpu, cuda, blender, houdini, desktop-gpu] year_introduced: 2016 inputs: [curves, material-params] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Chiang et al., 2016" url: "https://texelatlas.vercel.app/t/disney-hair-bsdf/" sources_verified_at: "2026-11-29" --- # Disney / Chiang hair and fur BSDF (Chiang et al., 2016) > An artist-controllable hair BSDF built on the R, TT and TRT lobes but parameterised by melanin, roughness and tint, with a far-field azimuthal approximation that is cheap to evaluate and sample in a path tracer. ## Reach for it when - artist friendly hair colour from melanin sliders - path traced hair that samples efficiently - fur and hair shader for production renderer - need hair roughness and tint without tuning absorption - blond hair looks too dark in path tracer ## How it works The model keeps the Marschner decomposition into longitudinal and azimuthal terms but redesigns both for production. Longitudinal roughness uses a numerically stable approximation of a Gaussian-like distribution on the sphere, with separate widths per lobe. The azimuthal term is replaced by a closed-form function of the exit angle derived from the geometry of a circular cross-section, avoiding root finding and allowing importance sampling. Colour comes from an absorption coefficient computed from melanin (eumelanin/pheomelanin ratio) and a tint, so artists choose a hair colour like they would for a person rather than tuning RGB absorption. Higher-order internal bounces beyond TRT are folded into one residual lobe to conserve energy. The result is a physically plausible BSDF with a handful of sliders that works inside a path tracer, and is the basis of hair shaders in several renderers. ## When to use it Choose it for path-traced or look-dev hair and fur where the artists must dial in colour and roughness without understanding scattering. Prefer [Marschner hair scattering model](https://texelatlas.vercel.app/t/marschner-hair-scattering.md) when you need the original formulation or are validating against it. Prefer [Kajiya-Kay hair shading](https://texelatlas.vercel.app/t/kajiya-kay-hair-shading.md) for real-time hair cards. Combine with [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md) plus a dual-scattering or brute-force path depth for blond hair where multiple scattering dominates. ## Cost offline — Closed-form evaluation and sampling per hit; real cost is hair geometry and path depth. Measured GPU Weight: 7.04× baseline (moderate) — 0.2315 ms median / 0.2526 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.39× baseline (light) — 0.0857 ms median (2.7× faster on L4). Ampere A100 scaling: 4.45× baseline (light) — 0.1282 ms median (1.81× faster on A100). ## Failure modes - Light hair needs many bounces between fibres, so low path depth makes it dark and flat - Radial roughness and longitudinal roughness are coupled in the parameterisation, so some looks are hard to reach - Far-field assumption breaks for very thick fibres or extreme close-ups - Fur on animals requires the medulla term that this base model omits, so it can look too translucent or too dark - Tangent direction errors flip the highlights in the same way as for any strand shader ## Engine support - blender: builtin — `Shader node: Principled Hair BSDF > Model = Chiang` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/hair_principled.html, checked 2026-12-01) — Cycles only. - unreal: builtin — `Material > Shading Model = Hair paired with Groom Hair Strands (implements Chiang/Marschner multi-lobe strand scattering)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/shading-models-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: curves, material-params - Outputs: radiance - Platforms: cpu, cuda, blender, houdini, desktop-gpu ## Presets ### Disney / Chiang hair BSDF — Marschner R, TT & TRT melanin-absorbed dual-lobe fibers (glsl-fragment; rendered 2026-11-30) ```json { "P_MELANIN": 0.42, "P_ROUGHNESS": 0.26, "P_CUTICLE_TILT": 0.08, "P_GLINT_BOOST": 1.3 } ``` ```glsl const float P_MELANIN = 0.42; // P Melanin [0.05, 1.2, 0.02] const float P_ROUGHNESS = 0.26; // P Longitudinal Rough [0.08, 0.75, 0.02] const float P_CUTICLE_TILT = 0.08; // P Cuticle Tilt [0.0, 0.22, 0.01] const float P_GLINT_BOOST = 1.3; // P TRT Glint [0.0, 2.5, 0.05] float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); } // Gaussian longitudinal scattering lobe M_p float lobeM(float thetaH, float shift, float beta) { float d = thetaH - shift; return exp(-0.5 * d * d / (beta * beta + 1e-4)) / (2.5066 * beta + 1e-4); } // Fresnel reflectance for hair keratin (IOR ~ 1.55) float fresnelHair(float cosI) { float f0 = 0.0465; return f0 + (1.0 - f0) * pow(clamp(1.0 - cosI, 0.0, 1.0), 5.0); } // Chiang melanin absorption coefficient sigma_a -> transmittance T vec3 hairAbsorption(float melanin, float redness) { vec3 eu = vec3(0.419, 0.697, 1.37); vec3 pheo = vec3(0.187, 0.40, 1.05); float c = melanin * melanin * 3.8; return c * mix(eu, pheo, redness); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; // Ray-intersect a sculpted 3D hair swatch cylinder + gentle S-wave drape vec3 ro = vec3(0.0, 0.0, 2.55); vec3 rd = normalize(vec3(uv, -1.65)); // Studio dark velvet backdrop vec3 col = mix(vec3(0.035, 0.03, 0.04), vec3(0.09, 0.08, 0.10), clamp(uv.y + 0.5, 0.0, 1.0)); col += vec3(0.18, 0.14, 0.11) * exp(-length(uv - vec2(0.32, 0.35)) * 2.5); // Intersect slightly tapered hair bundle sphere/ellipsoid vec3 sc = vec3(0.86, 1.08, 0.86); vec3 roS = ro / sc; vec3 rdS = rd / sc; float a = dot(rdS, rdS); float b = dot(roS, rdS); float c = dot(roS, roS) - 1.0; float disc = b * b - a * c; if (disc > 0.0) { float t = (-b - sqrt(disc)) / a; vec3 p = ro + rd * t; vec3 nBase = normalize(p / (sc * sc)); vec3 v = -rd; // Strand coordinates along curved draped locks float wave = 0.14 * sin(p.y * 4.2 + iTime * 0.8 + p.x * 1.6); float phi = atan(p.x, p.z) + wave; float strandCoord = phi * 58.0; float strandId = floor(strandCoord); float strandFrac = fract(strandCoord) - 0.5; float hRand = hash11(strandId * 13.7); float hRand2 = hash11(strandId * 29.3 + 5.1); // Individual cylindrical fiber micro-normal and tangent T along vertical wave float waveDeriv = 0.14 * 4.2 * cos(p.y * 4.2 + iTime * 0.8 + p.x * 1.6); vec3 bitan = normalize(cross(vec3(0.0, 1.0, 0.0), nBase)); vec3 T = normalize(cross(nBase, bitan) + bitan * waveDeriv * 0.45); vec3 N = normalize(nBase + bitan * (strandFrac * 1.15)); // Animated key light + warm rim backlight to showcase R, TT, TRT float lAng = 0.65 * sin(iTime * 0.55) + 0.45; vec3 lKey = normalize(vec3(sin(lAng), 0.55, cos(lAng))); vec3 lRim = normalize(vec3(-0.75, 0.45, -0.62)); float mel = clamp(P_MELANIN + (hRand - 0.5) * 0.14, 0.04, 1.5); float betaR = clamp(P_ROUGHNESS, 0.07, 0.8); float alpha = clamp(P_CUTICLE_TILT, 0.0, 0.25); vec3 sigmaA = hairAbsorption(mel, 0.42 + 0.25 * hRand2); vec3 trans = exp(-sigmaA * (1.35 + 0.4 * hRand)); vec3 accum = vec3(0.0); for (int li = 0; li < 2; li++) { vec3 L = (li == 0) ? lKey : lRim; vec3 lCol = (li == 0) ? vec3(2.3, 2.15, 1.95) : vec3(2.8, 1.75, 1.15); float sinTi = clamp(dot(T, L), -0.99, 0.99); float sinTo = clamp(dot(T, v), -0.99, 0.99); float ti = asin(sinTi); float to = asin(sinTo); float thetaH = 0.5 * (ti + to); float thetaD = 0.5 * (to - ti); float cosTd = max(cos(thetaD), 0.05); // Azimuthal angle difference in normal plane perpendicular to T vec3 lp = normalize(L - T * sinTi + 1e-5); vec3 vp = normalize(v - T * sinTo + 1e-5); float cosPhi = clamp(dot(lp, vp), -1.0, 1.0); float cosHalfPhi = sqrt(max(0.5 + 0.5 * cosPhi, 0.0)); float F = fresnelHair(cosTd * cosHalfPhi); // R lobe: cuticle primary specular (uncolored, shifted by +alpha) float MR = lobeM(thetaH, -alpha, betaR); float NR = 0.25 * cosHalfPhi; vec3 R = vec3(F * MR * NR) * 0.9; // TT lobe: forward transmission through fiber (strong backlit glow, shifted -alpha/2) float MTT = lobeM(thetaH, 0.5 * alpha, betaR * 0.55); float NTT = exp(-3.2 * (1.0 + cosPhi)); vec3 TT = (1.0 - F) * (1.0 - F) * trans * MTT * NTT * 2.2; // TRT lobe: secondary internal reflection with caustic glint (shifted +1.5*alpha) float MTRT = lobeM(thetaH, 1.5 * alpha, betaR * 1.85); float glint = exp(-18.0 * pow(abs(cosPhi - 0.55), 2.0)) * max(P_GLINT_BOOST, 0.0); vec3 TRT = (1.0 - F) * (1.0 - F) * F * trans * trans * MTRT * (0.65 + 1.8 * glint) * 2.4; // Multiple-scattering residual diffuse wrap for natural body volume float wrap = max(dot(N, L) * 0.65 + 0.35, 0.0); vec3 ms = trans * trans * wrap * 0.22; float selfOcc = smoothstep(-0.35, 0.65, dot(nBase, L)); float shadowTerm = (li == 0) ? (0.25 + 0.75 * selfOcc) : (0.35 + 0.65 * pow(1.0 - max(dot(nBase, v), 0.0), 1.6)); accum += lCol * (R + TT + TRT + ms) * shadowTerm; } // Fine per-fiber groove micro-occlusion float fiberShade = 0.72 + 0.28 * cos(strandFrac * 6.28318); float microStrand = 0.85 + 0.15 * sin(phi * 180.0 + p.y * 6.0); col = accum * fiberShade * microStrand; } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Marschner hair scattering model](https://texelatlas.vercel.app/t/marschner-hair-scattering.md) ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Closed-form sampling of the lobes lets each hair hit be importance sampled inside a standard path tracer. ## Sources 1. [primary] Matt Jen‐Yuan Chiang, Benedikt Bitterli, Chuck Tappan, Brent Burley (2016) A Practical and Controllable Hair and Fur Model for Production Path Tracing. Computer Graphics Forum. https://doi.org/10.1111/cgf.12830 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Disney / Chiang hair and fur BSDF." https://texelatlas.vercel.app/t/disney-hair-bsdf/ (accessed 2026-12-01). --- id: "disney-principled-brdf" title: "Disney principled BRDF" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2012 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Burley" url: "https://texelatlas.vercel.app/t/disney-principled-brdf/" sources_verified_at: "2026-11-29" --- # Disney principled BRDF (Burley) > Burley's art-directable BRDF: about ten intuitive 0-1 parameters (base colour, metallic, roughness, specular, sheen, clearcoat...) layered into one model. It set the vocabulary now shared by glTF, Unreal and OpenPBR. ## Reach for it when - artists need a simple set of sliders for materials - want one shader that covers metal, plastic and cloth - material parameters across tools are inconsistent - need a template for an art-friendly material model - importing assets authored with metallic and roughness sliders ## How it works The model keeps parameters perceptual and mostly orthogonal so artists never need to think in physical units. Metallic blends between a dielectric (diffuse plus a coloured-white specular at F0 around 0.04) and a conductor tinted by base colour. Roughness drives a GGX specular lobe and a diffuse term with retro-reflection at grazing angles that depends on roughness, replacing pure Lambert. Extra lobes are added on top: anisotropic specular, sheen with tint, a second fixed-IOR GGX clearcoat lobe, and a subsurface hack that flattens the diffuse look. Burley derived the design by fitting against measured MERL materials in a custom BRDF explorer, then pruned parameters that did not help artists. The 2015 extension added BSDF and thin-surface transmission. ## When to use it Choose it as a template when designing an art-facing parameter set or when importing assets authored for it. Prefer [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) as the current open standard with proper layering and energy conservation. Prefer the leaner glTF metallic-roughness model plus [Frostbite physically based rendering](https://texelatlas.vercel.app/t/frostbite-pbr.md) practices for mobile or engine-agnostic assets. Choose [Cook-Torrance microfacet BRDF](https://texelatlas.vercel.app/t/cook-torrance-brdf.md) directly when you only need a single lobe. ## Cost cheap — Several lobes cost more ALU than a single GGX lobe, but remain far below texture and lighting cost. Measured GPU Weight: 2.14× baseline (light) — 0.0703 ms median / 0.0759 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.76× baseline (feather) — 0.028 ms median (2.51× faster on L4). Ampere A100 scaling: 1.35× baseline (feather) — 0.0389 ms median (1.81× faster on A100). ## Failure modes - The lobes are added, not physically layered, so energy conservation is only approximate, particularly clearcoat over a bright base - Retro-reflective diffuse can brighten edges unexpectedly when combined with image-based lighting that was baked assuming Lambert - The subsurface parameter is a diffuse hack and cannot replace real SSS for skin or wax - No Fresnel-weighted energy transfer between layers, so stacks of lobes can exceed albedo 1 ## Engine support - babylonjs: builtin — `new BABYLON.OpenPBRMaterial(...) or PBRMaterial (Burley diffuse + GGX + clearcoat + sheen + anisotropy)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/openpbrMaterial.pure.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Shader > Principled BSDF` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) — Based on OpenPBR Surface, with Disney-compatible parameters. - godot: builtin — `BaseMaterial3D supports Burley diffuse (DIFFUSE_BURLEY) with Schlick-GGX specular, metallic, roughness, clearcoat, anisotropy, and rim` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl, checked 2026-12-01) - unity: builtin — `HDRP Lit material (DisneyDiffuse in BSDF.hlsl paired with GGX specular, clear coat, anisotropy, iridescence, and subsurface)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl, checked 2026-12-01) — Used by HDRP Lit; URP Lit uses Lambert diffuse with GGX specular. - unreal: builtin — `Material > Shading Model = Default Lit (Disney principled Base Color, Metallic, Specular, Roughness workflow)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Copper with light clearcoat (three-material; rendered 2026-11-29) ```json { "color": "#f7cfbf", "roughness": 0.35, "metalness": 1, "clearcoat": 0.4, "clearcoatRoughness": 0.1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 2 ## Lineage - extends [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) - extends [Schlick Fresnel approximation](https://texelatlas.vercel.app/t/fresnel-schlick-approximation.md) - extended by [Christensen-Burley diffusion profile](https://texelatlas.vercel.app/t/christensen-burley-sss.md) - extended by [Frostbite physically based rendering](https://texelatlas.vercel.app/t/frostbite-pbr.md) - extended by [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) ## Combines with - [Kulla-Conty multiple-scattering compensation](https://texelatlas.vercel.app/t/kulla-conty-multiscatter.md): Fixes the energy loss of the principled model's single-scatter specular at high roughness. ## Sources 1. [primary] Brent Burley Physically Based Shading at Disney. SIGGRAPH 2012 Course. https://disneyanimation.com/publications/physically-based-shading-at-disney (verified via http on 2026-11-29) 2. [implementation] wdas (2011) wdas/brdf. https://github.com/wdas/brdf License: NOASSERTION. (verified via github on 2026-11-29) 3. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Disney principled BRDF." https://texelatlas.vercel.app/t/disney-principled-brdf/ (accessed 2026-12-01). --- id: "dlss" title: "NVIDIA DLSS" aliases: [Deep Learning Super Sampling] domain: "post" stage: "post" realtime: "realtime" platforms: [desktop-gpu, unreal, unity] year_introduced: 2018 inputs: [ldr-image, depth, gbuffer] outputs: [ldr-image] style: "both" dynamic: "dynamic" cost: "medium" authority: "NVIDIA, 2021" url: "https://texelatlas.vercel.app/t/dlss/" sources_verified_at: "2026-11-29" --- # NVIDIA DLSS (NVIDIA, 2021) > NVIDIA's proprietary neural upscaler and denoiser running on RTX tensor cores. It consumes low-resolution colour, depth, motion vectors and jitter and outputs a temporally stable high-resolution frame. ## Reach for it when - game runs too slow at native 4k - render at lower resolution but keep sharp image - need temporal upscaling on nvidia rtx hardware - frame rate too low with ray tracing enabled ## How it works DLSS Super Resolution is a learned temporal reconstruction. The engine renders at reduced resolution with sub-pixel jitter and hands the SDK colour, depth, motion vectors, exposure and camera data. A network trained offline on high-quality references decides per pixel how to combine the reprojected history and the new samples, replacing the hand-written heuristics of TAA. Later generations add Ray Reconstruction, which denoises path-traced lighting inside the same network, and Frame Generation, which synthesises intermediate frames using optical flow. Integration is through the NVIDIA SDK or the Streamline layer, and it needs an RTX GPU. ## When to use it Choose it when the target is RTX hardware and you want the best upscaling image quality per millisecond, especially with ray tracing. Prefer [AMD FidelityFX Super Resolution](https://texelatlas.vercel.app/t/fidelityfx-super-resolution.md) when you need cross-vendor coverage. Prefer [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) when shipping to non-RTX hardware or WebGL, since this SDK is native only. ## Cost medium — Fixed per-frame network cost that scales with output resolution; a net win versus native when the scale factor is 2x or more. Qualitative. Measured GPU Weight: 20.91× baseline (heavy) — 0.6879 ms median / 0.7137 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 19.21× baseline (moderate) — 0.3054 ms median (2.25× faster on L4). Ampere A100 scaling: 14.95× baseline (moderate) — 0.4306 ms median (1.6× faster on A100). ## Failure modes - Ghosting or smearing on objects with wrong or missing motion vectors - Proprietary closed-source model, locked to NVIDIA hardware - Particle and transparent effects flicker without reactive masks - Occasional hallucinated detail on thin repeating patterns ## Engine support - unity: builtin — `HDRP Asset > Dynamic Resolution > Enable DLSS; Camera > Allow DLSS` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/deep-learning-super-sampling-in-hdrp.md, checked 2026-12-01) — HDRP only (DX11/DX12/Vulkan, NVIDIA RTX). Not in URP. - unreal: plugin — `NVIDIA DLSS plugin (third-party, distributed by NVIDIA); plugs into the temporal upscaler interface` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/temporal-upscalers-in-unreal-engine, checked 2026-12-01) — Docs list DLSS as a third-party distributed plugin. ## Dataflow - Inputs: ldr-image, depth, gbuffer - Outputs: ldr-image - Platforms: desktop-gpu, unreal, unity ## Presets ### NVIDIA DLSS — aliased low-res input with shimmer (left) vs motion-compensated temporal super-resolution (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RENDER_SCALE": 0.42, "P_SHARPNESS": 0.65, "P_MOTION": 0.6, "P_SPLIT": 0.48 } ``` ```glsl const float P_RENDER_SCALE = 0.42; // P Low-Res Scale [0.20, 0.75, 0.02] const float P_SHARPNESS = 0.65; // P Detail Sharpen [0.0, 1.2, 0.05] const float P_MOTION = 0.60; // P Camera Motion [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Low-Res / DLSS [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // High-frequency architectural scene (thin cables, louver fins, metallic tower, checker plaza) // ideal for exposing low-res aliasing vs temporal super-resolution reconstruction. vec3 evalScene(vec2 uv, float t) { vec3 ro = vec3(0.32 * sin(t * 0.7), 0.38 + 0.06 * cos(t * 0.9), 2.35); vec3 rd = normalize(vec3(uv.x, uv.y - 0.07, -1.55)); rd.xz = rot2(rd.xz, 0.12 * sin(t * 0.5)); // Dusk twilight gradient sky vec3 col = mix(vec3(0.08, 0.12, 0.20), vec3(0.35, 0.48, 0.68), smoothstep(-0.15, 0.65, rd.y)); vec3 sunDir = normalize(vec3(0.55, 0.48, -0.68)); col += vec3(1.5, 0.92, 0.48) * pow(max(dot(rd, sunDir), 0.0), 48.0); float tMin = 1e5; int matId = 0; vec3 hitP = vec3(0.0); vec3 hitN = vec3(0.0, 1.0, 0.0); // Ground plane with fine high-frequency perspective grid if (rd.y < -0.005) { float tg = (-0.52 - ro.y) / rd.y; if (tg > 0.05 && tg < 26.0) { tMin = tg; matId = 1; hitP = ro + rd * tg; hitN = vec3(0.0, 1.0, 0.0); } } // Hero chrome & louvered architectural sphere vec3 sc = vec3(0.0, -0.04, 0.0); vec3 oc = ro - sc; float b = dot(oc, rd); float c = dot(oc, oc) - 0.48 * 0.48; float d = b * b - c; if (d > 0.0) { float ts = -b - sqrt(d); if (ts > 0.05 && ts < tMin) { tMin = ts; matId = 2; hitP = ro + rd * ts; hitN = normalize(hitP - sc); } } // Thin architectural louver tower behind sphere vec3 bc = vec3(-0.78, 0.15, -0.85); vec3 br = vec3(0.28, 0.72, 0.28); vec3 invR = 1.0 / (rd + vec3(1e-6)); vec3 t0 = (bc - br - ro) * invR; vec3 t1 = (bc + br - ro) * invR; vec3 tNearV = min(t0, t1); vec3 tFarV = max(t0, t1); float tn = max(max(tNearV.x, tNearV.y), tNearV.z); float tf = min(min(tFarV.x, tFarV.y), tFarV.z); if (tf > max(tn, 0.05) && tn < tMin) { tMin = tn; matId = 3; hitP = ro + rd * tn; vec3 lp = (hitP - bc) / br; vec3 ap = abs(lp); hitN = (ap.x > ap.y && ap.x > ap.z) ? vec3(sign(lp.x), 0.0, 0.0) : (ap.y > ap.z ? vec3(0.0, sign(lp.y), 0.0) : vec3(0.0, 0.0, sign(lp.z))); } // Second fine-ribbed pylon on the right vec3 bc2 = vec3(0.82, 0.05, -0.65); vec3 br2 = vec3(0.24, 0.62, 0.24); vec3 u0 = (bc2 - br2 - ro) * invR; vec3 u1 = (bc2 + br2 - ro) * invR; vec3 uNear = min(u0, u1); vec3 uFar = max(u0, u1); float un = max(max(uNear.x, uNear.y), uNear.z); float uf = min(min(uFar.x, uFar.y), uFar.z); if (uf > max(un, 0.05) && un < tMin) { tMin = un; matId = 4; hitP = ro + rd * un; vec3 lp = (hitP - bc2) / br2; vec3 ap = abs(lp); hitN = (ap.x > ap.y && ap.x > ap.z) ? vec3(sign(lp.x), 0.0, 0.0) : (ap.y > ap.z ? vec3(0.0, sign(lp.y), 0.0) : vec3(0.0, 0.0, sign(lp.z))); } if (matId == 1) { vec2 gx = hitP.xz * 4.5; float chk = mod(floor(gx.x) + floor(gx.y), 2.0); float fineLine = step(0.90, max(fract(gx.x * 2.0), fract(gx.y * 2.0))); vec3 alb = mix(vec3(0.12, 0.14, 0.18), vec3(0.74, 0.78, 0.84), chk); alb = mix(alb, vec3(0.18, 0.88, 0.96), fineLine * 0.55); float sh = smoothstep(0.32, 0.72, length(hitP.xz - vec2(0.0, 0.0))); float fog = exp(-tMin * 0.09); col = mix(col, alb * (0.28 + 0.82 * sh), fog); } else if (matId == 2) { vec3 v = -rd; vec3 r = reflect(-v, hitN); // Fine diagonal machined micro-stripes on metallic sphere float stripe = step(0.0, sin((hitN.x * 26.0 + hitN.y * 34.0 + hitN.z * 18.0))); vec3 baseCol = mix(vec3(0.18, 0.24, 0.32), vec3(0.92, 0.74, 0.36), stripe); float ndl = max(dot(hitN, sunDir), 0.0); float spec = pow(max(dot(r, sunDir), 0.0), 42.0); float fres = pow(1.0 - max(dot(hitN, v), 0.0), 4.0); vec3 envC = mix(vec3(0.12, 0.18, 0.30), vec3(0.86, 0.92, 1.0), smoothstep(-0.2, 0.6, r.y)); col = baseCol * (0.22 + 0.95 * ndl) + envC * fres * 0.75 + vec3(1.4, 1.25, 1.0) * spec; } else if (matId == 3 || matId == 4) { // High-frequency horizontal louvers & glowing cyan/amber window slits float band = fract(hitP.y * 18.0); float slit = step(0.55, band); vec3 accent = (matId == 3) ? vec3(0.18, 0.92, 1.0) : vec3(1.0, 0.58, 0.20); float ndl = max(dot(hitN, sunDir), 0.0); col = mix(vec3(0.10, 0.12, 0.16), vec3(0.52, 0.58, 0.66) * (0.35 + 0.8 * ndl), 1.0 - slit * 0.65); col += accent * step(0.80, band) * 0.95; } // Thin diagonal architectural suspension cables across upper sky (brutal sub-pixel aliasing test!) for (int k = 0; k < 4; k++) { float fk = float(k); float yLine = 0.28 + fk * 0.085 - uv.x * (0.14 + fk * 0.04) + 0.02 * sin(t * 0.6 + fk); float wire = smoothstep(0.0045, 0.0012, abs(uv.y - yLine)); col = mix(col, vec3(0.95, 0.97, 1.0), wire * 0.85); } return col; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float t = iTime * max(P_MOTION, 0.0); float scale = clamp(P_RENDER_SCALE, 0.18, 0.80); float sharp = clamp(P_SHARPNESS, 0.0, 1.4); vec3 col = vec3(0.0); if (screenX < split) { // Left: Low internal render resolution (point-sampled with sub-pixel jitter shimmer) float cell = max(1.0 / scale, 1.5); vec2 jitter = vec2(hash21(vec2(floor(iTime * 24.0), 1.7)), hash21(vec2(3.1, floor(iTime * 24.0)))) - 0.5; vec2 lowCoord = (floor(fragCoord / cell) + 0.5 + jitter * 0.45) * cell; vec2 uvLow = (lowCoord - 0.5 * iResolution.xy) / iResolution.y; col = evalScene(uvLow, t); } else { // Right: DLSS-style multi-frame Halton-jittered temporal accumulation + neural-like edge sharpening vec3 acc = vec3(0.0); vec3 cMin = vec3(1e5); vec3 cMax = vec3(-1e5); vec2 px = 1.0 / max(iResolution.y, 1.0) * vec2(1.0); // 8 sub-pixel Halton offsets simulating converged temporal history reprojection for (int i = 0; i < 8; i++) { float fi = float(i); vec2 hOff = vec2(fract(fi * 0.5 + 0.25), fract(fi * 0.3333 + 0.1667)) - 0.5; vec2 uvS = (fragCoord + hOff * 0.95 - 0.5 * iResolution.xy) / iResolution.y; vec3 c = evalScene(uvS, t); acc += c; cMin = min(cMin, c); cMax = max(cMax, c); } vec3 resolved = acc * 0.125; // Mild unsharp detail reconstruction clamped to neighborhood gamut (zero ringing) vec2 uvC = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 center = evalScene(uvC, t); vec3 detail = center - resolved; col = clamp(resolved + detail * sharp * 0.45, cMin * 0.92, cMax * 1.08); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) ## Combines with - [Contrast Adaptive Sharpening](https://texelatlas.vercel.app/t/contrast-adaptive-sharpening.md): Optional post-sharpen after upscaling. ## Sources 1. [primary] NVIDIA (2021) NVIDIA/DLSS. https://github.com/NVIDIA/DLSS License: NOASSERTION. (verified via github on 2026-11-29) 2. [implementation] NVIDIA-RTX (2022) NVIDIA-RTX/Streamline. https://github.com/NVIDIA-RTX/Streamline License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "NVIDIA DLSS." https://texelatlas.vercel.app/t/dlss/ (accessed 2026-12-01). --- id: "domain-warping" title: "Domain Warping" aliases: [noise warping, warped fBm, flow-distorted noise] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, unity, unreal, godot] year_introduced: 2002 outputs: [texture, heightfield, volume-density] style: "both" dynamic: "both" cost: "cheap" authority: "Quilez" url: "https://texelatlas.vercel.app/t/domain-warping/" sources_verified_at: "2026-11-29" --- # Domain Warping (Quilez) > Feed the output of one noise function back into the coordinates of another, f(p + w(p)), so the pattern is bent into swirls, folds and marble-like flows that plain fBm cannot make. ## Reach for it when - noise looks too uniform and blobby - want swirling marble or smoke patterns - fractal terrain lacks flowing or folded structure - need lava or strata looking organic swirls cheaply ## How it works Instead of evaluating a field f at p, you first displace p by a vector field w, built from independent noise samples (typically two offset fBm calls for x and y). Nesting the idea, f(p + a*g(p + b*h(p))) gives progressively more organic structure; each level multiplies cost by the complexity of the inner evaluation. The displacement amplitude controls how far features travel, and animating one of the offset constants or adding time to the inner noise yields convincing liquid motion. Intermediate values (the warp vectors, the magnitude of the displacement) are free by-products that can be used to colour the pattern, so the result is often both a height and a palette index. The technique is general: any coordinate-based function (noise, Voronoi, SDF) can be warped. ## When to use it Choose it when you need organic swirls, marble, smoke, lava, strata, or want to break the regularity of [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) terrain cheaply (for example to fake flow-aligned ridges). Prefer [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) or [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) for physically plausible drainage, and [Reaction-Diffusion Textures (Turk)](https://texelatlas.vercel.app/t/reaction-diffusion-textures.md) for self-organising stripes and spots. ## Cost cheap — Multiplicative in nesting depth: two levels of warp with 5 fBm calls each is about 15 noise stacks per pixel. Measured GPU Weight: 34.16× baseline (heavy) — 1.1237 ms median / 1.151 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 29.82× baseline (heavy) — 0.4741 ms median (2.37× faster on L4). Ampere A100 scaling: 23.94× baseline (heavy) — 0.6895 ms median (1.63× faster on A100). ## Failure modes - Large warp amplitude folds the domain over itself, causing discontinuous seams or smeared detail - Differentiation is hard: finite-difference normals through nested warps are noisy and expensive - Each nesting level multiplies the cost, so mobile or per-vertex use needs a baked texture - Using the same noise for warp and base creates visible diagonal correlation instead of independent swirls ## Engine support - blender: builtin — `Noise Texture > Distortion input` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/noise.html, checked 2026-12-01) — Distortion offsets the lookup coordinates by noise. - godot: builtin — `FastNoiseLite > domain_warp_enabled = true (Simplex and BasicGrid coordinate warping)` (evidence: https://github.com/godotengine/godot/blob/4.4-stable/modules/noise/fastnoise_lite.cpp, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: texture, heightfield, volume-density - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, unity, unreal, godot ## Presets ### Two-level domain-warped fBm (glsl-fragment; rendered 2026-11-29) ```json { "warp_strength": 4, "octaves": 5 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. f(p + 4*q + 4*r) with animated warp fields. const int OCTAVES = 5; const float WARP = 4.0; float hash21(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } float vnoise(vec2 p){ vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix(mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y); } float fbm(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < OCTAVES; i++) { s += a * vnoise(p); p = mat2(1.6, 1.2, -1.2, 1.6) * p; a *= 0.5; } return s; } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y * 3.0; float t = iTime * 0.15; vec2 q = vec2(fbm(p + vec2(0.0, 0.0)), fbm(p + vec2(5.2, 1.3))); vec2 r = vec2(fbm(p + WARP * q + vec2(1.7, 9.2) + t), fbm(p + WARP * q + vec2(8.3, 2.8) - t)); float f = fbm(p + WARP * r); vec3 col = mix(vec3(0.10, 0.12, 0.30), vec3(0.85, 0.35, 0.15), smoothstep(0.2, 0.8, f)); col = mix(col, vec3(0.95, 0.90, 0.75), clamp(length(r) * 0.8, 0.0, 1.0) * f); col = mix(col, vec3(0.02, 0.05, 0.12), clamp(q.x * q.x * 2.0, 0.0, 1.0) * 0.5); fragColor = vec4(col * (0.3 + 1.1 * f), 1.0); } ``` Attribution: written for this index. Technique described by Inigo Quilez; code is original. ### Multi-octave FBM domain warping (WGSL) (webgpu-wgsl; WebGPU WGSL runtime) ```json { "WARP": 3.2, "OCTAVES": 5 } ``` ```wgsl // WebGPU WGSL fragment specimen: iterated f(p + WARP * q + WARP * r) domain warping const WARP: f32 = 3.2000; // P const OCTAVES: i32 = 5; // P fn hash21(p_in: vec2f) -> f32 { var p = fract(p_in * vec2f(123.34, 456.21)); p = p + dot(p, p + 45.32); return fract(p.x * p.y); } fn vnoise(p: vec2f) -> f32 { let i = floor(p); let f = fract(p); let u = f * f * (3.0 - 2.0 * f); let a = hash21(i); let b = hash21(i + vec2f(1.0, 0.0)); let c = hash21(i + vec2f(0.0, 1.0)); let d = hash21(i + vec2f(1.0, 1.0)); return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); } fn fbm(p_in: vec2f) -> f32 { var p = p_in; var acc: f32 = 0.0; var amp: f32 = 0.5; let rot = mat2x2f(vec2f(0.8, 0.6), vec2f(-0.6, 0.8)); for (var i: i32 = 0; i < OCTAVES; i = i + 1) { acc = acc + amp * vnoise(p); p = rot * p * 2.02; amp = amp * 0.5; } return acc; } @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f { let uv = (pos.xy / u.resolution.y) * 2.6; let t = u.time * 0.14; let q = vec2f(fbm(uv + vec2f(0.0, t)), fbm(uv + vec2f(5.2, 1.3 - t))); let r = vec2f(fbm(uv + WARP * q + vec2f(1.7, 9.2)), fbm(uv + WARP * q + vec2f(8.3, 2.8))); let f = fbm(uv + WARP * r); var col = mix(vec3f(0.09, 0.18, 0.24), vec3f(0.68, 0.48, 0.30), clamp(f * 1.4, 0.0, 1.0)); col = mix(col, vec3f(0.94, 0.92, 0.86), smoothstep(0.55, 0.92, length(q) * 0.75 + f * 0.4)); return vec4f(col, 1.0); } ``` Attribution: written for this index ## Lineage - extends [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) ## Sources 1. [primary] Inigo Quilez Domain Warping. iquilezles.org. https://iquilezles.org/articles/warp (verified via http on 2026-11-29) 2. [tutorial] Patricio Gonzalez Vivo The Book of Shaders: Fractal Brownian Motion. thebookofshaders.com. https://thebookofshaders.com/13 (verified via http on 2026-11-29) 3. [implementation] Gökay Aydoğan (2026) gokayfem/glsl-studies. https://github.com/gokayfem/glsl-studies License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Domain Warping." https://texelatlas.vercel.app/t/domain-warping/ (accessed 2026-12-01). --- id: "draco-mesh-compression" title: "Draco mesh compression" aliases: [Draco, KHR_draco_mesh_compression] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, cpu] year_introduced: 2017 inputs: [mesh, point-cloud] outputs: [mesh] style: "both" dynamic: "static" cost: "medium" authority: "google, 2016" url: "https://texelatlas.vercel.app/t/draco-mesh-compression/" sources_verified_at: "2026-11-29" --- # Draco mesh compression (google, 2016) > Google's open library that compresses mesh connectivity and quantized attributes into a small stream, decoded on the CPU at load time. ## Reach for it when - mesh files are too big to download - need smaller static models for the web - point cloud transfer size is too large - reduce geometry bandwidth with quantisation - gltf models take too long to load over network ## How it works Positions, normals and UVs are quantized to a chosen number of bits. Connectivity is encoded with an edgebreaker-style traversal, and attributes are predicted from already decoded neighbours, with the small residuals entropy coded. The decoder, often WebAssembly, rebuilds vertex and index arrays that go straight into GPU buffers. The result is much smaller than uncompressed or gzip glTF, but decoding happens on load and the vertex order may change, so it is a delivery format and not a runtime format. ## When to use it Choose it to cut download size of static meshes and point clouds. Prefer [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md) encoding when fast decoding and vertex-cache order matter or when animation and morph targets are present. Prefer neither for tiny meshes where decoder size outweighs saved bytes. ## Cost medium — Decoding cost sits on the CPU at load and grows with mesh size. Measured GPU Weight: 15.8× baseline (moderate) — 0.5199 ms median / 0.5385 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 14.26× baseline (moderate) — 0.2267 ms median (2.29× faster on L4). Ampere A100 scaling: 10.34× baseline (moderate) — 0.2978 ms median (1.75× faster on A100). ## Failure modes - Quantization causes visible cracks between separately compressed meshes at seams - Changed vertex order hurts cache efficiency unless reoptimized - Decoding stalls the main thread without a worker - Weak fit for animated or morph-target data ## Engine support - babylonjs: builtin — `BABYLON.DracoCompression (used automatically by glTF KHR_draco_mesh_compression)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/Compression/dracoCompression.ts, checked 2026-12-01) - blender: official — `Properties on export: File > Export > glTF 2.0 > Data > Compression (Draco)` (evidence: https://docs.blender.org/manual/en/5.2/addons/scene_gltf2.html, checked 2026-12-01) — Bundled glTF 2.0 add-on. - threejs: official — `import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/loaders/DRACOLoader.js, checked 2026-12-01) - unity: official — `Package Manager > Draco for Unity (com.unity.cloud.draco)` (evidence: https://docs.unity3d.com/Packages/com.unity.cloud.draco@5.0/manual/index.html, checked 2026-12-01) — Official Unity package. - unreal: official — `Interchange glTF Importer (glTF 2.0 / GLB mesh import & decompression)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/importing-gltf-files-into-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, point-cloud - Outputs: mesh - Platforms: webgl2, webgpu, cpu ## Presets ### Draco Mesh Compression — low-bit quantized geometry & edgebreaker facets (left) vs 14-bit decoded smooth mesh (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_QUANT_BITS": 5, "P_WIRE_VIS": 0.55, "P_ROT_SPEED": 0.5, "P_SPLIT": 0.48 } ``` ```glsl const float P_QUANT_BITS = 5.00; // P Position Quant Bits [3.0, 9.0, 1.0] const float P_WIRE_VIS = 0.55; // P Edgebreaker Mesh [0.0, 1.0, 0.05] const float P_ROT_SPEED = 0.50; // P Turntable Speed [0.0, 1.6, 0.05] const float P_SPLIT = 0.48; // P Low-Bit / Decoded [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Sculpted organic torus-knot-like blob for exposing vertex quantization & normal oct-encoding artifacts float mapSculpture(vec3 p, float t) { p.xz = rot2(p.xz, t * 0.55); p.xy = rot2(p.xy, 0.25 * sin(t * 0.4)); vec2 q = vec2(length(p.xz) - 0.36, p.y); float torus = length(q) - 0.19; float ribs = 0.032 * sin(atan(p.z, p.x) * 6.0 + p.y * 8.0) * cos(p.y * 10.0); float core = length(p) - 0.26; return min(torus + ribs, core); } vec3 calcNormal(vec3 p, float t) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSculpture(p + e.xyy, t) - mapSculpture(p - e.xyy, t), mapSculpture(p + e.yxy, t) - mapSculpture(p - e.yxy, t), mapSculpture(p + e.yyx, t) - mapSculpture(p - e.yyx, t) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float bits = clamp(floor(P_QUANT_BITS + 0.5), 3.0, 10.0); float wireVis = clamp(P_WIRE_VIS, 0.0, 1.0); float t = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.28, 2.05); vec3 rd = normalize(vec3(uv.x, uv.y - 0.07, -1.48)); vec3 lDir = normalize(vec3(0.62, 0.78, 0.55)); vec3 col = mix(vec3(0.06, 0.08, 0.13), vec3(0.16, 0.22, 0.34), smoothstep(-0.4, 0.5, uv.y)); float dist = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { float h = mapSculpture(ro + rd * dist, t); if (h < 0.002) { hit = true; break; } dist += h * 0.85; if (dist > 6.0) break; } if (hit) { vec3 p = ro + rd * dist; vec3 n = calcNormal(p, t); // Rotate into object-local coordinates so quantization grid is rigidly locked to mesh vertices vec3 pObj = p; pObj.xz = rot2(pObj.xz, t * 0.55); pObj.xy = rot2(pObj.xy, 0.25 * sin(t * 0.4)); if (screenX < split) { // Left: Low-bit Draco spatial quantization grid + coarse octahedral normal snapping + edgebreaker strip lines float qSteps = pow(2.0, bits) * 0.38; vec3 pQuant = floor(pObj * qSteps + 0.5) / qSteps; vec3 errVec = pObj - pQuant; // Quantized faceted normal (coarse oct-encoding) float nSteps = max(qSteps * 0.32, 2.0); vec3 nQuant = normalize(floor(n * nSteps + 0.5) / nSteps + vec3(1e-4)); // Edgebreaker traversal triangle-strip grid in object space vec3 cellF = fract(pObj * qSteps); float edgeDist = min(min(min(cellF.x, 1.0 - cellF.x), min(cellF.y, 1.0 - cellF.y)), abs(cellF.x + cellF.y - 1.0)); float wire = smoothstep(0.08, 0.015, edgeDist); // Color-code quantization prediction residual error magnitude float errMag = clamp(length(errVec) * qSteps * 1.6, 0.0, 1.0); vec3 alb = mix(vec3(0.24, 0.68, 0.88), vec3(0.98, 0.46, 0.18), errMag); float ndl = max(dot(nQuant, lDir), 0.0); float spec = pow(max(dot(reflect(-lDir, nQuant), -rd), 0.0), 18.0); col = alb * (0.24 + 0.90 * ndl) + vec3(0.9, 0.95, 1.0) * spec * 0.55; col = mix(col, vec3(0.96, 0.98, 1.0), wire * wireVis * 0.65); } else { // Right: High-precision 14-bit Draco-decoded smooth metallic ceramic mesh float ndl = max(dot(n, lDir), 0.0); float spec = pow(max(dot(reflect(-lDir, n), -rd), 0.0), 48.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 4.0); vec3 alb = mix(vec3(0.22, 0.64, 0.86), vec3(0.84, 0.88, 0.94), 0.5 + 0.5 * n.y); col = alb * (0.22 + 0.92 * ndl) + vec3(1.1, 1.05, 0.98) * spec * 0.95 + vec3(0.32, 0.64, 0.96) * fres * 0.65; } } else if (rd.y < -0.005) { float tf = (-0.52 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { vec3 fp = ro + rd * tf; float sh = smoothstep(0.28, 0.68, length(fp.xz)); vec2 gf = abs(fract(fp.xz * 2.5) - 0.5); float grid = smoothstep(0.04, 0.01, min(gf.x, gf.y)); vec3 fl = mix(vec3(0.11, 0.13, 0.18), vec3(0.24, 0.30, 0.40), grid) * (0.35 + 0.65 * sh); col = mix(col, fl, exp(-tf * 0.16)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md): A compressed glTF can pair Draco geometry with KTX2 textures to cut both streams. ## Sources 1. [primary] google (2016) google/draco. https://github.com/google/draco License: Apache-2.0. (verified via github on 2026-11-29) 2. [primary] KHR_draco_mesh_compression. github.com. https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_draco_mesh_compression (verified via http on 2026-11-29) ## Cite this entry Texel. "Draco mesh compression." https://texelatlas.vercel.app/t/draco-mesh-compression/ (accessed 2026-12-01). --- id: "dreamgaussian" title: "DreamGaussian" aliases: [DreamGaussian text/image-to-3D] domain: "genai" stage: "generation" realtime: "interactive" platforms: [python, cuda] year_introduced: 2023 inputs: [photos, text-prompt] outputs: [gaussians, mesh, texture] style: "both" dynamic: "static" cost: "heavy" authority: "Tang et al., 2023" url: "https://texelatlas.vercel.app/t/dreamgaussian/" sources_verified_at: "2026-11-29" --- # DreamGaussian (Tang et al., 2023) > Generates a 3D asset from one image or a prompt by optimising Gaussian splats with score distillation, then extracting a textured mesh, finishing in about a couple of minutes instead of the hour-scale of NeRF-based pipelines. ## Reach for it when - turn a single image into a 3d model in a couple of minutes - need fast text to 3d prototype with a mesh export - previous score distillation pipelines take an hour per asset - want gaussian splat output from one photo - generated 3d asset needs a textured mesh not just splats ## How it works Stage one initialises a few thousand random 3D Gaussians and optimises them with score distillation sampling (see [Score Distillation Sampling (DreamFusion)](https://texelatlas.vercel.app/t/score-distillation-sampling.md)): renders from random cameras are scored by a pretrained multi-view or image-conditioned diffusion model (Zero-1-to-3 style for image input), while the input view is also supervised directly. Gaussian splatting converges quickly and its densification schedule is adapted to the stochastic SDS loss, which makes this stage far faster than implicit fields. Stage two converts the splats to a mesh by querying a local density grid with block-wise marching cubes (see [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md)), computes UVs, back-projects colour from splats into a texture, and refines the texture with an image-to-image diffusion loss on rendered views, using multiview-consistent denoising. Output is a standard textured mesh ready for game engines. ## When to use it Choose it for quick single-image or prompt prototyping where a coarse textured mesh in a minute or two beats waiting for a heavy pipeline. Prefer feed-forward image-to-3D such as [TripoSR](https://texelatlas.vercel.app/t/triposr.md), [InstantMesh](https://texelatlas.vercel.app/t/instantmesh.md) or [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) when you need seconds and more reliable geometry, [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) for higher-fidelity production assets, and [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) reconstruction when you have real multi-view photos. ## Cost heavy — Minutes per asset on a single modern GPU; optimisation-based, so not interactive per frame. Measured GPU Weight: 28.63× baseline (heavy) — 0.9419 ms median / 0.9653 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.16× baseline (heavy) — 0.3206 ms median (2.94× faster on L4). Ampere A100 scaling: 19.72× baseline (moderate) — 0.568 ms median (1.66× faster on A100). ## Failure modes - Janus (multi-face) problem and flat or hollow backs because SDS has no strong 3D prior - Over-saturated, blurry textures typical of score distillation guidance - Floaters and noisy geometry in the splat stage that survive into the extracted mesh - Texture seams and smearing after UV back-projection on thin parts - Single-view ambiguity: occluded sides are hallucinated and may not match intent ## Dataflow - Inputs: photos, text-prompt - Outputs: gaussians, mesh, texture - Platforms: python, cuda ## Presets ### DreamGaussian — Stage-1 generative 3D Gaussian splats (left) vs Stage-2 UV-textured mesh (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SPLAT_SIZE": 0.14, "P_REFINE": 0.85, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_SPLAT_SIZE = 0.14; // P Splat Radius [0.06, 0.26, 0.01] const float P_REFINE = 0.85; // P Stage-2 Detail [0.1, 1.0, 0.02] const float P_ROT_SPEED = 0.65; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Splats / Mesh Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash31(float x) { vec3 p = fract(vec3(x) * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yzx + 33.33); return fract((p.xxy + p.yzz) * p.zyx); } // Sculpted stylized crystal-urn creature (smooth union of body, wings, and crown) float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } float mapAsset(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.52) * q.xz; float body = length(q * vec3(1.0, 0.78, 1.0) - vec3(0.0, -0.06, 0.0)) - 0.44; float head = length(q - vec3(0.0, 0.46, 0.06)) - 0.24; vec3 wq = vec3(abs(q.x), q.y, q.z); float wing = length((wq - vec3(0.42, 0.06, -0.08)) * vec3(0.7, 1.25, 2.1)) - 0.26; float d = smin(body, head, 0.14); d = smin(d, wing, 0.12); return d * 0.85; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapAsset(p + e.xyy, spin) - mapAsset(p - e.xyy, spin), mapAsset(p + e.yxy, spin) - mapAsset(p - e.yxy, spin), mapAsset(p + e.yyx, spin) - mapAsset(p - e.yyx, spin) )); } // Stage-2 refined procedural UV texture vec3 stage2Texture(vec3 objP, float detail) { float bands = 0.5 + 0.5 * sin(objP.y * 16.0 + sin(objP.x * 9.0) * 1.4); float plume = 0.5 + 0.5 * cos(atan(objP.z, objP.x) * 8.0 + objP.y * 10.0); vec3 cobalt = vec3(0.14, 0.36, 0.82); vec3 coral = vec3(0.95, 0.42, 0.26); vec3 gold = vec3(0.98, 0.80, 0.28); vec3 col = mix(cobalt, coral, smoothstep(-0.35, 0.45, objP.y)); col = mix(col, gold, smoothstep(0.55, 0.92, bands * plume) * detail); return col; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float splatR = clamp(P_SPLAT_SIZE, 0.05, 0.28); float detail = clamp(P_REFINE, 0.05, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.08, 2.35); vec3 rd = normalize(vec3(uv, -1.55)); vec3 bg = mix(vec3(0.025, 0.032, 0.054), vec3(0.068, 0.085, 0.132), smoothstep(-0.55, 0.55, uv.y)); vec3 col = bg; if (screenX < split) { // Left: Stage-1 generative 3D Gaussian Splats (28 anisotropic 3D Gaussians alpha-blended front-to-back) vec3 accum = vec3(0.0); float T = 1.0; for (int i = 0; i < 32; i++) { float fi = float(i); vec3 h = hash31(fi * 7.13 + 1.9); float theta = h.x * 6.2831853; float y = (h.y - 0.48) * 1.15; float rad = (y > 0.26) ? 0.22 : (0.42 + 0.22 * step(0.68, h.z)); vec3 cObj = vec3(cos(theta) * rad, y, sin(theta) * rad * (h.z > 0.68 ? 0.45 : 0.9)); vec3 cWorld = cObj; cWorld.xz = rot2(-spin * 0.52) * cWorld.xz; // Project 3D Gaussian center onto ray vec3 oc = cWorld - ro; float tProj = dot(oc, rd); if (tProj > 0.2) { vec3 dPerp = oc - rd * tProj; // Anisotropic stretch along tangent direction float aniso = 0.65 + 0.85 * h.z; float dist2 = dot(dPerp, dPerp) / max(splatR * splatR * aniso, 1e-5); float g = exp(-dist2 * 2.2); if (g > 0.015) { float alpha = clamp(g * 0.72, 0.0, 0.92); vec3 gCol = stage2Texture(cObj, 0.85) * (0.65 + 0.55 * clamp(cWorld.z + 0.6, 0.0, 1.0)); // Slight Gaussian ellipsoid rim float core = smoothstep(0.65, 0.95, g); accum += T * alpha * (gCol + vec3(0.18, 0.22, 0.28) * core); T *= (1.0 - alpha); if (T < 0.02) break; } } } col = accum + T * bg; } else { // Right: Stage-2 extracted UV mesh with refined PBR shading float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapAsset(ro + rd * t, spin); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.52) * objP.xz; vec3 l1 = normalize(vec3(0.55, 0.82, 0.52)); vec3 l2 = normalize(vec3(-0.68, -0.20, 0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 42.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = stage2Texture(objP, detail); col = alb * (0.28 + 0.85 * diff1 + 0.26 * diff2) + vec3(1.0, 0.96, 0.90) * spec * 0.45 + vec3(0.32, 0.75, 1.0) * fres * 0.38; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Score Distillation Sampling (DreamFusion)](https://texelatlas.vercel.app/t/score-distillation-sampling.md) - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): A density grid sampled from the splats is meshed by marching cubes to get the exportable surface. ## Sources 1. [primary] Jiaxiang Tang, Jiawei Ren, Hang Zhou, Ziwei Liu, Gang Zeng (2023) DreamGaussian: Generative Gaussian Splatting for Efficient 3D Content Creation. arXiv preprint (cs.CV). https://arxiv.org/abs/2309.16653 (verified via arxiv on 2026-11-29) 2. [implementation] dreamgaussian (2023) dreamgaussian/dreamgaussian. https://github.com/dreamgaussian/dreamgaussian License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "DreamGaussian." https://texelatlas.vercel.app/t/dreamgaussian/ (accessed 2026-12-01). --- id: "dual-contouring" title: "Dual Contouring" aliases: [DC] domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, cuda, desktop-gpu, unity, webgl2] year_introduced: 2002 inputs: [voxels, sdf] outputs: [mesh, normals] style: "both" dynamic: "both" cost: "medium" authority: "Ju et al., 2002" url: "https://texelatlas.vercel.app/t/dual-contouring/" sources_verified_at: "2026-11-29" --- # Dual Contouring (Ju et al., 2002) > Places one vertex per cell by minimising a quadratic error built from Hermite data (edge crossings plus surface normals), then connects vertices of cells sharing a sign-changing edge. Preserves sharp corners that marching cubes bevels. ## Reach for it when - marching cubes rounds off sharp corners and edges - voxel terrain needs crisp cliffs and building edges - extract mesh from sdf keeping sharp features - adaptive isosurface mesh with fewer triangles ## How it works Along each grid edge with a sign change, store the crossing point and the surface normal there (Hermite data). For every cell that contains the surface, collect those plane constraints and solve a small least-squares problem (QEF) for the point that best fits all planes; the solution lands on a corner when three or more different planes meet, on an edge for two. Faces are then generated in the dual sense: for each sign-changing edge, emit a quad joining the four cells around it. Octree versions collapse cells bottom-up when the combined QEF error stays under a tolerance, which makes adaptive meshes. QEF solving needs SVD or QR with truncation, plus clamping vertices to the cell so they cannot fly away on near-parallel planes. ## When to use it Choose it for voxel or SDF editing tools, CSG results and CAD-like shapes where hard edges must stay crisp. Prefer [Manifold Dual Contouring](https://texelatlas.vercel.app/t/manifold-dual-contouring.md) when the output must be a valid 2-manifold, [Surface Nets](https://texelatlas.vercel.app/t/surface-nets.md) when you want the same dual topology without needing normals, and [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) when you only have a binary or noisy field with no reliable gradient. ## Cost medium — Linear in surface cells; the per-cell QEF solve makes it a few times slower than marching cubes. Measured GPU Weight: 47.08× baseline (heavy) — 1.4782 ms median / 1.5332 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 39.63× baseline (heavy) — 0.6261 ms median (2.36× faster on L4). Ampere A100 scaling: 28.01× baseline (heavy) — 0.8067 ms median (1.83× faster on A100). ## Failure modes - Non-manifold edges and self-intersecting quads where several surface sheets pass through one cell - Vertices shoot out of the cell on near-degenerate QEFs unless clamped or biased towards the mass point - Needs good normals: noisy gradients create spikes - Flat-shaded look and zig-zag normals on thin features at coarse resolution - T-junction cracks between octree levels ## Engine support - blender: builtin — `Modifiers > Generate > Remesh (Blocks / Smooth / Sharp octree modes call dualcon dual-contouring library)` (evidence: https://github.com/blender/blender/blob/main/source/blender/modifiers/intern/MOD_remesh.cc, checked 2026-12-01) ## Dataflow - Inputs: voxels, sdf - Outputs: mesh, normals - Platforms: cpu, cuda, desktop-gpu, unity, webgl2 ## Presets ### Dual Contouring — Marching Cubes corner blunting (left) vs QEF sharp-feature preservation (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VOXEL_RES": 7, "P_DUAL_GRID": 0.85, "P_SPLIT": 0.46, "P_ROT_SPEED": 1 } ``` ```glsl const float P_VOXEL_RES = 7.0; // P Voxel Grid Res [4.0, 14.0, 1.0] const float P_DUAL_GRID = 0.85; // P Dual Quad Wire [0.0, 1.5, 0.05] const float P_SPLIT = 0.46; // P MC / DC Split [0.0, 1.0, 0.02] const float P_ROT_SPEED = 1.0; // P Spin Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } // Sharp-featured CAD mechanical block: 90-degree cube minus cylindrical bore minus corner step float exactCAD(vec3 q) { float dCube = sdBox(q, vec3(0.62)); float dBore = length(q.xy) - 0.30; float dCut = sdBox(q - vec3(0.42, 0.42, 0.0), vec3(0.32, 0.32, 0.85)); return max(max(dCube, -dBore), -dCut); } // Marching Cubes approximation: lacks Hermite normals so grid quantization bevels/blunts sharp 90-deg edges! float mapMarchingCubes(vec3 p, float res, float spin) { vec3 q = p; q.xz = rot2(spin * 0.38) * q.xz; q.yz = rot2(0.42) * q.yz; float h = 0.42 / max(res, 2.0); // 8-corner trilinear box blur of the SDF mimics Marching Cubes edge-crossing bevel loss float d = exactCAD(q); float dBlur = ( exactCAD(q + vec3(h, h, h)) + exactCAD(q + vec3(-h, h, h)) + exactCAD(q + vec3(h, -h, h)) + exactCAD(q + vec3(-h, -h, h)) + exactCAD(q + vec3(h, h, -h)) + exactCAD(q + vec3(-h, h, -h)) + exactCAD(q + vec3(h, -h, -h)) + exactCAD(q + vec3(-h, -h, -h)) ) * 0.125; // Subtle voxel-cell stair-stepping modulation vec3 cellWobble = sin(q * res * 6.2831853) * (0.045 / res); return mix(d, dBlur, 0.88) + (cellWobble.x + cellWobble.y + cellWobble.z) * 0.18; } // Dual Contouring (QEF solver): places dual vertices right onto sharp planes & creases using Hermite normals! float mapDualContour(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.38) * q.xz; q.yz = rot2(0.42) * q.yz; return exactCAD(q); } vec3 calcNormalMC(vec3 p, float res, float spin) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapMarchingCubes(p + e.xyy, res, spin) - mapMarchingCubes(p - e.xyy, res, spin), mapMarchingCubes(p + e.yxy, res, spin) - mapMarchingCubes(p - e.yxy, res, spin), mapMarchingCubes(p + e.yyx, res, spin) - mapMarchingCubes(p - e.yyx, res, spin) )); } vec3 calcNormalDC(vec3 p, float spin) { vec2 e = vec2(0.0018, 0.0); return normalize(vec3( mapDualContour(p + e.xyy, spin) - mapDualContour(p - e.xyy, spin), mapDualContour(p + e.yxy, spin) - mapDualContour(p - e.yxy, spin), mapDualContour(p + e.yyx, spin) - mapDualContour(p - e.yyx, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float res = clamp(floor(P_VOXEL_RES + 0.5), 3.0, 16.0); float wireVis = clamp(P_DUAL_GRID, 0.0, 1.6); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.08, 2.50); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.032, 0.044, 0.070), vec3(0.09, 0.115, 0.165), smoothstep(-0.55, 0.55, uv.y)); bool isDC = screenX >= split; float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; float d = isDC ? mapDualContour(p, spin) : mapMarchingCubes(p, res, spin); if (d < 0.002) { hit = true; break; } t += d * 0.85; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = isDC ? calcNormalDC(p, spin) : calcNormalMC(p, res, spin); // Object space for voxel / dual quad wireframe overlay vec3 objP = p; objP.xz = rot2(spin * 0.38) * objP.xz; objP.yz = rot2(0.42) * objP.yz; vec3 qf = abs(fract(objP * res - 0.5) - 0.5); vec3 an = abs(n); float dQuad = (an.x > an.y && an.x > an.z) ? min(qf.y, qf.z) : ((an.y > an.z) ? min(qf.x, qf.z) : min(qf.x, qf.y)); // Marching Cubes outputs irregular triangles (diagonal cuts across voxel faces); Dual Contouring outputs clean dual quads! float dTriDiag = abs((fract(objP.x * res) - fract(objP.y * res))); float wireMC = smoothstep(0.065, 0.015, min(dQuad, dTriDiag * 0.7)); float wireDC = smoothstep(0.055, 0.012, dQuad); // Highlight sharp QEF crease edges where two CAD faces intersect at 90 degrees float sharpCrease = 0.0; if (isDC) { vec3 nA = calcNormalDC(p + vec3(0.012, 0.0, 0.0), spin); vec3 nB = calcNormalDC(p + vec3(0.0, 0.012, 0.0), spin); vec3 nC = calcNormalDC(p + vec3(0.0, 0.0, 0.012), spin); sharpCrease = smoothstep(0.18, 0.55, (1.0 - dot(n, nA)) + (1.0 - dot(n, nB)) + (1.0 - dot(n, nC))); } vec3 l1 = normalize(vec3(0.62, 0.85, 0.55)); vec3 l2 = normalize(vec3(-0.72, -0.22, 0.52)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 42.0) * 0.48; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.28; vec3 alb = isDC ? vec3(0.20, 0.72, 0.68) : vec3(0.76, 0.44, 0.34); col = alb * (0.26 + 0.84 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.72, 1.0) * rim; if (isDC) { col = mix(col, vec3(0.05, 0.14, 0.18), wireDC * 0.52 * min(wireVis, 1.2)); col = mix(col, vec3(1.0, 0.92, 0.42), sharpCrease * 0.85); } else { col = mix(col, vec3(0.18, 0.08, 0.06), wireMC * 0.52 * min(wireVis, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [Manifold Dual Contouring](https://texelatlas.vercel.app/t/manifold-dual-contouring.md) ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): The SDF gives both edge crossings and analytic normals for the Hermite samples. ## Sources 1. [primary] Tao Ju, Frank Losasso, Scott Schaefer, Joe Warren (2002) Dual contouring of hermite data. Proceedings of the 29th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/566570.566586 (verified via crossref on 2026-11-29) 2. [tutorial] Boris the Brave Dual Contouring Tutorial. boristhebrave.com. https://www.boristhebrave.com/2018/04/15/dual-contouring-tutorial (verified via http on 2026-11-29) ## Cite this entry Texel. "Dual Contouring." https://texelatlas.vercel.app/t/dual-contouring/ (accessed 2026-12-01). --- id: "dual-filter-bloom" title: "Dual-filter and progressive-downsample bloom" aliases: [Call of Duty bloom, progressive downsample bloom] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2014 inputs: [hdr-image] outputs: [hdr-image] style: "both" dynamic: "both" cost: "cheap" authority: "Jimenez" url: "https://texelatlas.vercel.app/t/dual-filter-bloom/" sources_verified_at: "2026-11-29" --- # Dual-filter and progressive-downsample bloom (Jimenez) > Bloom built by downsampling the HDR image through a chain of mips with a wide-footprint filter, then upsampling and adding the levels back; the cost stays small even for very large glow radii. ## Reach for it when - glow around bright lights is too expensive on mobile - wide gaussian blur kills my frame rate - need big soft glow radius at low cost in webgl - emissive surfaces should bleed light into surroundings ## How it works Rather than one huge blur, the image is repeatedly halved. Each downsample uses a 13-tap tent-like pattern arranged to avoid fireflies and aliasing: weighted overlapping 4-tap groups around the pixel, with a Karis average on the first level so a single hot pixel cannot dominate. The result at the lowest mip has an effective radius of many pixels at tiny cost. The chain is then walked back up: each level is upsampled with a 3x3 tent filter, optionally multiplied by a per-level weight and added to the next-larger mip. The final blend adds the combined glow, scaled by an intensity, to the HDR scene before tonemapping. Thresholding is optional and often omitted for a physically motivated, energy-conserving look. ## When to use it Choose it for HDR glow around emissives and specular highlights, particularly on mobile and WebGL where wide Gaussians are too slow. Prefer a thresholded Gaussian when you need a tight, art-directed halo. Prefer [Pseudo lens flare](https://texelatlas.vercel.app/t/lens-flare.md) for streaks and ghosts rather than isotropic glow; the two share the downsampled mip chain. ## Cost cheap — About 2 x log2(height) small passes with shrinking cost; qualitative. Measured GPU Weight: 108.49× baseline (extreme) — 3.5692 ms median / 3.6353 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 52.39× baseline (heavy) — 0.833 ms median (4.28× faster on L4). Ampere A100 scaling: 56.1× baseline (heavy) — 1.6156 ms median (2.21× faster on A100). ## Failure modes - Without the Karis average a single bright pixel produces flickering blobs - Blocky or shimmering glow if the filter is replaced by plain bilinear downsample - Bloom in LDR after tonemapping looks washed out - Fixed mip radii give resolution-dependent glow size ## Engine support - babylonjs: builtin — `DefaultRenderingPipeline.bloomEnabled (BloomEffect)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/bloomEffect.ts, checked 2026-12-01) - blender: builtin — `Compositor > Glare node (Bloom / Fog Glow mode)` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/filter/glare.html, checked 2026-12-01) - godot: builtin — `WorldEnvironment > Environment.glow_enabled (multi-level mip pyramid bloom)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - threejs: official — `import { bloom } from 'three/addons/tsl/display/BloomNode.js' (WebGL: UnrealBloomPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/BloomNode.js, checked 2026-12-01) — Mip-chain blur bloom (BloomNode/UnrealBloomPass). - unity: builtin — `Volume > Add Override > Post-processing > Bloom > Filter = Dual (or Gaussian/Kawase)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/Bloom.cs, checked 2026-12-01) — URP Bloom has Gaussian, Dual and Kawase filter modes. - unreal: builtin — `Post Process Volume > Lens > Bloom > Method = Standard (multi-pass Gaussian mip pyramid) or Convolution` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/bloom-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: HDR frame tonemapped. Right: bloom from a 3-level dual-filter pyramid (5-tap down-sample chain, bright-pass first) (glsl-fragment; rendered 2026-11-29) ```json { "HPX": 3, "BI": 1.2 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float HPX=3.0; // P const float BI=1.2; // P vec3 src(vec2 p){ vec3 c=vec3(.02,.025,.04)+vec3(.08,.05,.1)*(p.y+.5); c=mix(c,vec3(.15,.12,.1),smoothstep(.002,-.002,abs(length(p-vec2(0.,-.2))-.11)-.02)); c+=vec3(1.,.8,.5)*30.*smoothstep(.002,-.002,length(p-vec2(-.1,.2))-.025); c+=vec3(.4,.7,1.)*30.*smoothstep(.002,-.002,length(p-vec2(.12,.0))-.02); c+=vec3(1.,.4,.4)*30.*smoothstep(.002,-.002,max(abs(p.x+.02),abs(p.y+.3)*.1-.0)-.008)*step(abs(p.y+.3),.1); return c;} vec3 D0(vec2 p){return max(src(p)-1.,vec3(0.));} vec3 D1(vec2 p,float h){return(4.*D0(p)+D0(p+h*vec2(1.,1.))+D0(p+h*vec2(-1.,1.))+D0(p+h*vec2(1.,-1.))+D0(p-h*vec2(1.,1.)))/8.;} vec3 D2(vec2 p,float h){float g=2.*h;return(4.*D1(p,h)+D1(p+g*vec2(1.,1.),h)+D1(p+g*vec2(-1.,1.),h)+D1(p+g*vec2(1.,-1.),h)+D1(p-g*vec2(1.,1.),h))/8.;} vec3 D3(vec2 p,float h){float g=4.*h;return(4.*D2(p,h)+D2(p+g*vec2(1.,1.),h)+D2(p+g*vec2(-1.,1.),h)+D2(p+g*vec2(1.,-1.),h)+D2(p-g*vec2(1.,1.),h))/8.;} vec3 D4(vec2 p,float h){float g=8.*h;return(4.*D3(p,h)+D3(p+g*vec2(1.,1.),h)+D3(p+g*vec2(-1.,1.),h)+D3(p+g*vec2(1.,-1.),h)+D3(p-g*vec2(1.,1.),h))/8.;} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 c=src(q); if(R){float h=HPX/512.;c+=BI*(D2(q,h)+D3(q,h));} vec3 col=gam(c/(1.+c*.5)); if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Combines with - [Pseudo lens flare](https://texelatlas.vercel.app/t/lens-flare.md): The bloom mip chain doubles as the source texture for ghosts and halos. - [Scatter-as-gather bokeh depth of field](https://texelatlas.vercel.app/t/depth-of-field-scatter-as-gather.md): Both rely on an HDR buffer and the same downsample infrastructure. ## Sources 1. [primary] Jorge Jimenez Next Generation Post Processing in Call of Duty: Advanced Warfare. SIGGRAPH 2014 Advances in Real-Time Rendering. https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare (verified via http on 2026-11-29) 2. [tutorial] Joey de Vries Bloom. learnopengl.com. https://learnopengl.com/Advanced-Lighting/Bloom (verified via http on 2026-11-29) 3. [implementation] pmndrs (2015) pmndrs/postprocessing. https://github.com/pmndrs/postprocessing License: Zlib. (verified via github on 2026-11-29) ## Cite this entry Texel. "Dual-filter and progressive-downsample bloom." https://texelatlas.vercel.app/t/dual-filter-bloom/ (accessed 2026-12-01). --- id: "dual-quaternion-skinning" title: "Dual quaternion skinning" aliases: [DQS] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity, unreal, blender] year_introduced: 2007 inputs: [mesh, skeleton] outputs: [mesh, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Kavan et al., 2007" url: "https://texelatlas.vercel.app/t/dual-quaternion-skinning/" sources_verified_at: "2026-11-29" --- # Dual quaternion skinning (Kavan et al., 2007) > Skinning that blends bone rigid transforms as dual quaternions instead of matrices, preserving volume at twisting joints at nearly linear-blend cost. ## Reach for it when - forearm twist collapses into a candy wrapper - joints lose volume when twisting - neck or tail pinches when rotated - skinned limbs look pinched at bends and twists - want volume-preserving skinning at similar cost ## How it works Each bone's rigid transform is a unit dual quaternion (rotation plus translation encoded together). Per vertex, the weighted sum of its bone dual quaternions is computed, with sign flips so all lie in the same hemisphere as the first, then the sum is normalised. The result is a rigid transform applied to position and normal. Because blending happens in a space that represents rotations on a curve rather than by averaging matrices, a twisting limb rotates rather than shrinking in the middle. Scale is not representable, so non-rigid bone scaling must be handled separately, and blending between very different rotations can create a slight bulge. ## When to use it Choose it for twisting limbs, forearms, necks and tails where candy-wrapper artefacts show. Prefer [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md) when the extra shader work and the 'joint bulge' side effect aren't worth it, or when bone scale is used, and pose-space deformers when artistic control of corrective shapes is the goal. ## Cost cheap — Slightly more than LBS: dual quaternion normalisation per vertex. Measured GPU Weight: 1.36× baseline (feather) — 0.0448 ms median / 0.0459 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.19× baseline (feather) — 0.019 ms median (2.36× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.56× faster on A100). ## Failure modes - Joint bulging when blending large relative rotations - No non-uniform scale in bone transforms - Hard to combine with existing LBS-based corrective/blend-shape pipelines - Needs sign-consistency step or flips occur ## Engine support - blender: builtin — `Armature modifier > Preserve Volume` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/deform/armature.html, checked 2026-12-01) — Preserve Volume uses quaternion blending. - unreal: builtin — `Skeletal Mesh skinning pipeline (Dual Quaternion skinning support)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/skeletal-mesh-animation-system-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, skeleton - Outputs: mesh, animation - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity, unreal, blender ## Presets ### Toy side view: dual-quaternion twist keeps volume while linear blending pinches (glsl-fragment; rendered 2026-11-29) ```json { "TWIST": 3, "RADIUS": 0.11 } ``` ```glsl // Toy side view of a twisted tube: dual-quaternion blend (top) keeps its radius, linear matrix blend (bottom) pinches. const float TWIST = 3.0; const float RADIUS = 0.11; float lbsR(float w) { return RADIUS * sqrt((1.0 - w) * (1.0 - w) + w * w + 2.0 * w * (1.0 - w) * cos(TWIST)); } vec3 tube(vec2 p, float cy, float rad, vec3 base) { float y = (p.y - cy) / max(rad, 1e-4); vec3 c = vec3(0.0); if (abs(y) < 1.0) { float z = sqrt(1.0 - y * y); c = base * (0.25 + 0.8 * z * z) + 0.25 * pow(z, 8.0); } return c; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 p = fragCoord / iResolution.xy; float w = clamp((p.x - 0.1) / 0.8, 0.0, 1.0); vec3 col = vec3(0.07, 0.08, 0.1); if (p.x > 0.1 && p.x < 0.9) { // dual quaternion: nlerp of the two rotation quaternions about the axis gives rotation w*TWIST, radius constant col = tube(p, 0.7, RADIUS, vec3(0.4, 0.8, 0.55)); col += tube(p, 0.3, lbsR(w), vec3(0.95, 0.45, 0.3)); float g = abs(abs(p.y - 0.3) - RADIUS); col = mix(col, vec3(0.9), smoothstep(0.004, 0.0, g) * 0.3 * step(0.0, sin(p.x * 120.0))); } float joint = min(abs(p.x - 0.1), abs(p.x - 0.9)); col = mix(col, vec3(1.0, 0.9, 0.3), smoothstep(0.004, 0.0, joint) * 0.8); fragColor = vec4(pow(col, vec3(0.6)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Ladislav Kavan, Steven Collins, Jiří Žára, Carol O'Sullivan (2007) Skinning with dual quaternions. Proceedings of the 2007 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1230100.1230107 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Dual quaternion skinning." https://texelatlas.vercel.app/t/dual-quaternion-skinning/ (accessed 2026-12-01). --- id: "dust3r" title: "DUSt3R" aliases: [Dense Unconstrained Stereo 3D Reconstruction] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [photos] outputs: [point-cloud, depth, camera-poses] style: "photoreal" dynamic: "static" cost: "medium" authority: "Wang et al., 2023" url: "https://texelatlas.vercel.app/t/dust3r/" sources_verified_at: "2026-11-29" --- # DUSt3R (Wang et al., 2023) > A transformer that takes two uncalibrated images and directly regresses dense pointmaps in a shared frame, from which depth, intrinsics, matches and relative pose follow without SfM. ## Reach for it when - reconstruct 3d from photos without camera poses - structure from motion fails with few images - get dense 3d points from just two images - no calibration known but want geometry from pictures ## How it works A ViT encoder processes each image and a decoder with cross-attention between the two streams outputs a pointmap per image: for every pixel, a 3D point expressed in the first image's coordinate frame, plus a confidence. Camera intrinsics, relative pose and depth are then derived from these pointmaps by simple geometric fitting, e.g. focal length by Weiszfeld-style optimisation and pose by Procrustes or PnP. For more than two views, pairwise predictions are combined by a global alignment optimisation over a graph of pairs, which recovers per-image scale and pose. Training uses large datasets with ground-truth depth and pose and a scale-normalised regression loss. No calibration or known poses are needed. ## When to use it Choose it for quick geometry and poses from a handful of casual images where [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md) fails from low overlap or texture. Prefer [MASt3R](https://texelatlas.vercel.app/t/mast3r.md) when you need accurate dense matching, [VGGT (Visual Geometry Grounded Transformer)](https://texelatlas.vercel.app/t/vggt.md) for many views in one pass, and COLMAP when you have dense, well-textured image sets and need maximum metric accuracy. ## Cost medium — Pairwise inference is fast on GPU, but global alignment over many images costs seconds to minutes. Measured GPU Weight: 20.29× baseline (heavy) — 0.6675 ms median / 0.7352 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.06× baseline (heavy) — 0.3348 ms median (1.99× faster on L4). Ampere A100 scaling: 13.69× baseline (moderate) — 0.3943 ms median (1.69× faster on A100). ## Failure modes - Quadratic pair count and slow global alignment on large image sets - Pointmaps drift on long trajectories since predictions are not bundle adjusted - Dynamic objects and reflective surfaces yield inconsistent pointmaps - Pretrained weights carry a non-commercial licence ## Dataflow - Inputs: photos - Outputs: point-cloud, depth, camera-poses - Platforms: cuda, python ## Presets ### DUSt3R — unposed stereo confidence & pointmap XYZ (left) vs fused 3D point cloud (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CONF_CUT": 0.45, "P_POINT_RES": 18, "P_ROT_SPEED": 0.58, "P_SPLIT": 0.48 } ``` ```glsl const float P_CONF_CUT = 0.45; // P Confidence Gain [0.1, 1.0, 0.02] const float P_POINT_RES = 18.0; // P Pointmap Density [8.0, 32.0, 1.0] const float P_ROT_SPEED = 0.58; // P 3D Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Pointmap / Fused 3D [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } // 3D landmark scene reconstructed directly into shared camera-1 coordinate frame by DUSt3R vec2 mapLandmark(vec3 p) { vec2 res = vec2(p.y + 0.65, 1.0); // courtyard floor float plinth = sdBox(p - vec3(0.0, -0.35, 0.0), vec3(0.55, 0.30, 0.55)) - 0.02; if (plinth < res.x) res = vec2(plinth, 2.0); float archL = sdBox(p - vec3(-0.34, 0.22, 0.0), vec3(0.12, 0.36, 0.16)) - 0.02; float archR = sdBox(p - vec3(0.34, 0.22, 0.0), vec3(0.12, 0.36, 0.16)) - 0.02; float topB = sdBox(p - vec3(0.0, 0.56, 0.0), vec3(0.52, 0.10, 0.18)) - 0.02; float dArch = min(min(archL, archR), topB); if (dArch < res.x) res = vec2(dArch, 3.0); float statue = length(p - vec3(0.0, 0.16, 0.0)) - 0.22; if (statue < res.x) res = vec2(statue, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapLandmark(p + e.xyy).x - mapLandmark(p - e.xyy).x, mapLandmark(p + e.yxy).x - mapLandmark(p - e.yxy).x, mapLandmark(p + e.yyx).x - mapLandmark(p - e.yyx).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isPointmap = screenX < split; float confGain = clamp(P_CONF_CUT, 0.1, 1.0); float ptRes = clamp(P_POINT_RES, 8.0, 36.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.34, 2.35); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.06), -1.48)); ro.xz = rot2(spin * 0.50) * ro.xz; rd.xz = rot2(spin * 0.50) * rd.xz; vec3 col = mix(vec3(0.022, 0.028, 0.048), vec3(0.058, 0.075, 0.125), smoothstep(-0.55, 0.55, uv.y)); float t = 0.05; vec2 hit = vec2(1e5, 0.0); for (int i = 0; i < 56; i++) { vec2 h = mapLandmark(ro + rd * t); if (h.x < 0.003) { hit = vec2(t, h.y); break; } t += h.x; if (t > 8.0) break; } if (hit.x < 1e4) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); // Pointmap XYZ normalized into [0,1] RGB vec3 xyzCol = clamp(p * 0.55 + 0.5, 0.0, 1.0); // Per-pixel regression confidence (highest on well-observed textured foreground geometry) float conf = clamp(exp(-hit.x * 0.28) * (0.4 + 0.6 * max(dot(n, -rd), 0.0)) + 0.25 * confGain, 0.0, 1.0); if (isPointmap) { // Left: Raw regressed dense 3D Pointmap X(u,v) colored by world XYZ + confidence iso-lines float iso = 0.82 + 0.18 * cos(length(p) * 28.0); col = xyzCol * iso * (0.35 + 0.75 * conf); // Show stereo camera baseline frustum hint in corner vec2 g = abs(fract(p.xz * 4.0) - 0.5); col += vec3(0.18, 0.92, 0.96) * smoothstep(0.05, 0.01, min(g.x, g.y)) * 0.22; } else { // Right: Fused dense 3D point cloud splats aligned from View-1 (cyan) & View-2 (warm lit RGB) vec3 q = p * ptRes; vec3 cell = floor(q) + 0.5; float dSplat = length(q - cell); float splatMask = smoothstep(0.56, 0.22, dSplat); vec3 lDir = normalize(vec3(0.58, 0.80, 0.45)); float diff = max(dot(n, lDir), 0.0); vec3 alb = vec3(0.58, 0.62, 0.68); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.78, 0.72, 0.62); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.86, 0.56, 0.34); else if (hit.y > 3.5) alb = vec3(0.24, 0.82, 0.94); vec3 lit = alb * (0.32 + 0.82 * diff); col = mix(col * 0.65, lit, splatMask * clamp(conf * 1.15, 0.3, 1.0)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [MASt3R](https://texelatlas.vercel.app/t/mast3r.md) ## Combines with - [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md): DUSt3R poses and points can replace COLMAP to initialise Gaussians from few images. ## Sources 1. [primary] Shuzhe Wang, Vincent Leroy, Yohann Cabon, Boris Chidlovskii, Jerome Revaud (2023) DUSt3R: Geometric 3D Vision Made Easy. arXiv preprint (cs.CV). https://arxiv.org/abs/2312.14132 (verified via arxiv on 2026-11-29) 2. [implementation] naver (2024) naver/dust3r. https://github.com/naver/dust3r License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "DUSt3R." https://texelatlas.vercel.app/t/dust3r/ (accessed 2026-12-01). --- id: "dynamic-swept-volume-slab-cutting" title: "Kinematic Swept-Volume Boolean Carving via 2D Slab Distance Fields" aliases: [swept-volume slab carving, kinematic aperture cutting, 2D swept profile SDF] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, houdini, blender] year_introduced: 2003 inputs: [mesh, sdf, animation] outputs: [mesh, sdf] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Sellán et al., 2021" url: "https://texelatlas.vercel.app/t/dynamic-swept-volume-slab-cutting/" sources_verified_at: "2026-11-30" --- # Kinematic Swept-Volume Boolean Carving via 2D Slab Distance Fields (Sellán et al., 2021) > Carves exact clearance slots through thin moving gates or walls by evaluating the kinematic swept volume of a passing body as a 2D minimum-envelope signed distance field on each slab plane. ## Reach for it when - carve real-time slices and grooves out of a 3d solid with a moving blade - boolean mesh subtraction is too slow for continuous lathe or milling cuts - simulate wood carving foam cutting or sculpting with a swept tool path - update cut geometry cleanly without leaving non-manifold mesh artifacts - visualize exact material removed by a moving planar or slab cutter ## How it works Computing the full 3D **swept volume** of a rigid body moving along a trajectory `M(t)`—whether by spacetime numerical continuation (Sellán et al.) or polyhedral envelope approximation (Kim et al.)—captures every point occupied by the body over time. When a moving object such as a pendulum bob or cutter passes through a thin barrier or rotating gate slab, the 3D boolean subtraction simplifies dramatically. Instead of meshing a full 4D spacetime isosurface, the solver transforms the moving body's analytic or sampled SDF `f_body(p)` into the **local 2D slab frame** `(u, v, w)` at discrete contact times `t_k` while the body intersects the slab thickness `|w| <= h/2`. Taking the temporal minimum envelope `d_sweep(u, v) = min_k f_body(M_slab(t_k)^-1 * p(u, v, w))` across the passage window yields a **2D signed distance field** of the exact silhouette carved through the slab, optionally expanded by a uniform clearance offset `-epsilon`. Extracting the zero-contour (via marching squares or contour tracing) produces clean 2D boolean hole loops that are triangulated with ear-clipping and extruded across the slab thickness `h`, guaranteeing collision-free passage even when both the cutter and the gate rotate synchronously. ## When to use it Choose it when carving tight-tolerance kinematic slots, keyholes, or synchronized mechanical gates through thin discs, plates, or stacked slices along known trajectories. Prefer [mesh-boolean-manifold](mesh-boolean-manifold) when thick, arbitrary 3D solids require exact volumetric CSG subtraction rather than planar slab extrusion. Prefer [sdf-csg-smooth-min](sdf-csg-smooth-min) when rendering implicit ray-marched scenes where the swept boolean can be evaluated analytically without extracting a triangle mesh. ## Cost cheap — Evaluating the 2D temporal minimum SDF on a coarse-to-fine slab grid and extruding the contour runs in a few milliseconds at generation time, with standard static mesh rendering cost at runtime. ## Failure modes - Temporal undersampling of fast rotations or narrow blades causes scalloped aperture walls or missed collisions between sample instants - Thin-slab 2D projection over-carves or misrepresents beveled entry walls when the obstacle thickness is large relative to the trajectory curvature - Tiny remaining islands or razor-thin bridges near the slab rim can create degenerate triangles during 2D contour extrusion - Non-rigid or unpredictable user-driven trajectories require re-carving the slab field whenever motion parameters change ## Dataflow - Inputs: mesh, sdf, animation - Outputs: mesh, sdf - Platforms: webgl2, webgpu, desktop-gpu, cpu, houdini, blender ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): Fillets sharp aperture corners and adds uniform clearance margins directly inside the 2D slab distance field before contour extraction. - [Manifold Mesh Booleans](https://texelatlas.vercel.app/t/mesh-boolean-manifold.md): Handles thick non-planar housings where 2D slab extrusion cannot represent slanted exit walls. ## Sources 1. [primary] Silvia Sellán, Noam Aigerman, Alec Jacobson (2021) Swept volumes via spacetime numerical continuation. ACM Transactions on Graphics. https://doi.org/10.1145/3450626.3459780 (verified via crossref on 2026-11-30) 2. [primary] Young J. Kim, Gokul Varadhan, Ming C. Lin, Dinesh Manocha (2004) Fast swept volume approximation of complex polyhedral models. Computer-Aided Design. https://doi.org/10.1016/j.cad.2004.01.004 (verified via doi.org on 2026-11-30) 3. [implementation] spite (2026) spite/codevember-2026. https://github.com/spite/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Kinematic Swept-Volume Boolean Carving via 2D Slab Distance Fields." https://texelatlas.vercel.app/t/dynamic-swept-volume-slab-cutting/ (accessed 2026-12-01). --- id: "ecosystem-plant-distribution" title: "Plant Ecosystem Distribution Simulation" aliases: [ecosystem simulation for vegetation, competition-based plant placement] domain: "procgen" stage: "procedural" realtime: "offline" platforms: [cpu, python, houdini] year_introduced: 1998 inputs: [heightfield, texture] outputs: [point-cloud, layout] style: "photoreal" dynamic: "static" cost: "offline" authority: "Deussen et al., 1998" url: "https://texelatlas.vercel.app/t/ecosystem-plant-distribution/" sources_verified_at: "2026-11-29" --- # Plant Ecosystem Distribution Simulation (Deussen et al., 1998) > Places thousands of plants on terrain by simulating seeding, competition for light and space, and survival across plant generations, so species cluster in ecologically plausible patterns. ## Reach for it when - scattered trees look random and unnatural - forest needs species mix, clearings and age variety - plants should compete for light and space realistically - placing thousands of plants by hand is impractical ## How it works Deussen et al. couple a procedural plant model with a population simulation. Starting from an initial set of plants, the simulation iterates over years: plants seed new individuals nearby with dispersion depending on species, each plant's growth and survival depend on its neighbours' shading and root competition and on terrain conditions such as height and moisture, and weaker plants die. Efficiency comes from sorting plants and using only the dominant competitor near each plant. The output is a distribution of species, ages and sizes, which is then rendered with LOD, billboard clouds or geometry instancing. Variants replace the individual-based loop with density maps and procedural rules for speed. ## When to use it Choose it for natural-looking vegetation layouts where species mix, age distribution and clearings matter (forests, meadows). Prefer [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md) for fast, uniform blue-noise placement when ecology doesn't matter, and [MAP-Elites (Quality-Diversity Search)](https://texelatlas.vercel.app/t/map-elites.md) or [Infinigen (Procedural Photorealistic Worlds)](https://texelatlas.vercel.app/t/infinigen.md) pipelines if the placement is part of a larger scene-generation system. ## Cost offline — Simulation over many plants and years; practical for 100k+ plants in the original work but scales superlinearly with density. Measured GPU Weight: 18.56× baseline (moderate) — 0.6106 ms median / 0.6488 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.92× baseline (moderate) — 0.2691 ms median (2.27× faster on L4). Ampere A100 scaling: 13.38× baseline (moderate) — 0.3853 ms median (1.58× faster on A100). ## Failure modes - Parameters (competition radii, seeding distance) need ecological calibration or the simulation yields monocultures - Terrain suitability maps (moisture, sunlight) need to be provided or the species distribution is flat - Simulated output is a static snapshot: no seasonal change or disturbance unless modelled - Renderer must handle massive instance counts; the plant distribution is only half of the problem ## Dataflow - Inputs: heightfield, texture - Outputs: point-cloud, layout - Platforms: cpu, python, houdini ## Presets ### Plant Ecosystem Distribution — Poisson competition radii & biomes (left) vs self-thinned forest canopy (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MOISTURE": 0.72, "P_COMPETE_R": 0.85, "P_TREE_SCALE": 8.5, "P_SPLIT": 0.46 } ``` ```glsl const float P_MOISTURE = 0.72; // P Valley Moisture [0.15, 1.2, 0.04] const float P_COMPETE_R = 0.85; // P Canopy Competition [0.3, 1.3, 0.04] const float P_TREE_SCALE = 8.5; // P Stand Density [5.0, 14.0, 0.5] const float P_SPLIT = 0.46; // P Radii / Forest Split [0.0, 1.0, 0.02] vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // Terrain elevation & river moisture field across the valley map vec2 evalSite(vec2 uv, float moistGain) { float river = abs(uv.x - 0.14 * sin(uv.y * 5.2 + 0.4)); float elev = clamp(0.12 + river * 1.15 + 0.18 * sin(uv.x * 4.2) * cos(uv.y * 3.8), 0.0, 1.0); float moist = clamp(exp(-river * 4.5) * moistGain + 0.15 * (1.0 - elev), 0.0, 1.0); return vec2(elev, moist); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isDiagram = screenX < split; float moistG = clamp(P_MOISTURE, 0.1, 1.4); float compR = clamp(P_COMPETE_R, 0.25, 1.4); float dens = clamp(P_TREE_SCALE, 4.5, 16.0); // Subtle slow drift over the watershed ecosystem vec2 worldUV = uv + vec2(0.0, iTime * 0.035); vec2 site = evalSite(worldUV, moistG); float elev = site.x; float moist = site.y; // Base terrain soil & alpine contour backdrop vec3 soil = mix(vec3(0.24, 0.30, 0.16), vec3(0.46, 0.42, 0.36), smoothstep(0.42, 0.85, elev)); // Valley river strip float inRiver = smoothstep(0.068, 0.038, abs(worldUV.x - 0.14 * sin(worldUV.y * 5.2 + 0.4))); vec3 riverCol = vec3(0.10, 0.46, 0.68); vec3 col = mix(soil, riverCol, inRiver); // Subtle elevation contour lines float contour = smoothstep(0.05, 0.012, abs(fract(elev * 9.0) - 0.5)); col = mix(col, vec3(0.12, 0.16, 0.20), contour * (isDiagram ? 0.45 : 0.14)); // Self-thinning Poisson-disk multi-species stand evaluation over 3x3 cell neighborhood vec2 g = worldUV * dens; vec2 cell = floor(g); vec2 sunDir = normalize(vec2(0.65, 0.76)); for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec2 nc = cell + vec2(float(dx), float(dy)); vec2 rnd = hash22(nc); vec2 treePos = (nc + 0.18 + 0.64 * rnd) / dens; vec2 tSite = evalSite(treePos, moistG); float tElev = tSite.x; float tMoist = tSite.y; // Skip plants falling directly into river channel or barren rocky peaks float dRiv = abs(treePos.x - 0.14 * sin(treePos.y * 5.2 + 0.4)); if (dRiv < 0.055 || tElev > 0.88) continue; // Species selection by niche suitability (elev, moisture) + self-thinning dominance radius! // 0 = riparian willow/alder (wet lowland), 1 = broadleaf oak (mid valley), 2 = alpine conifer (high dry ridge) float species = (tMoist > 0.46) ? 0.0 : ((tElev < 0.52) ? 1.0 : 2.0); float age = 0.45 + 0.55 * hash22(nc + 19.3).x; float canopyR = (species < 0.5 ? 0.42 : (species < 1.5 ? 0.50 : 0.34)) * age * compR / dens; vec2 diffP = worldUV - treePos; float d = length(diffP); if (isDiagram) { // Left: Ecological competition circles, trunk dots & species-coded dominance rings vec3 spCol = (species < 0.5) ? vec3(0.20, 0.92, 0.84) : (species < 1.5 ? vec3(0.96, 0.74, 0.22) : vec3(0.46, 0.88, 0.32)); float ring = exp(-abs(d - canopyR) * 180.0); float fill = smoothstep(canopyR, canopyR * 0.85, d) * 0.22; float dotC = smoothstep(0.010, 0.004, d); col = mix(col, spCol, fill); col += spCol * ring * 0.92; col = mix(col, vec3(0.98, 0.99, 1.0), dotC); } else { // Right: Rendered sunlit multi-species forest crowns with soft drop shadows! float dShad = length(diffP + sunDir * canopyR * 0.55); col *= mix(1.0, 0.62, smoothstep(canopyR * 1.05, canopyR * 0.6, dShad)); // Scalloped organic crown silhouette float ang = atan(diffP.y, diffP.x); float scallop = 1.0 + 0.12 * sin(ang * (species > 1.5 ? 9.0 : 5.0) + rnd.x * 6.28); float rEff = canopyR * scallop; if (d < rEff) { float hCrown = sqrt(max(1.0 - (d / max(rEff, 1e-4)) * (d / max(rEff, 1e-4)), 0.0)); vec3 nCrown = normalize(vec3(diffP / max(rEff, 1e-4), hCrown)); float lit = max(dot(nCrown, normalize(vec3(sunDir, 0.85))), 0.0); vec3 spCol = (species < 0.5) ? vec3(0.24, 0.66, 0.34) : (species < 1.5 ? mix(vec3(0.32, 0.56, 0.16), vec3(0.76, 0.54, 0.16), rnd.y) : vec3(0.08, 0.32, 0.22)); col = spCol * (0.28 + 0.90 * lit); } } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Space Colonization Tree Modeling](https://texelatlas.vercel.app/t/space-colonization-trees.md): The ecosystem simulation chooses which species goes where; tree generators supply the geometry. ## Combination ideas - [Regrow a photographed site](https://texelatlas.vercel.app/ideas/captured-site-revegetation/) - [Forests that grow into the gaps](https://texelatlas.vercel.app/ideas/eroded-biome-forests/) - [Tiger-bush drylands](https://texelatlas.vercel.app/ideas/patterned-dryland-vegetation/) ## Sources 1. [primary] Oliver Deussen, Pat Hanrahan, Bernd Lintermann, Radomír Měch, Matt Pharr, Przemyslaw Prusinkiewicz (1998) Realistic modeling and rendering of plant ecosystems. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280898 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Plant Ecosystem Distribution Simulation." https://texelatlas.vercel.app/t/ecosystem-plant-distribution/ (accessed 2026-12-01). --- id: "eikonal-coastal-wave-refraction-shoaling" title: "Fast-Sweeping Eikonal Coastal Wave Refraction & Ray-Tube Shoaling" aliases: [eikonal wave refraction, fast-sweeping shore breakers, bathymetry wave shoaling] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2002 inputs: [heightfield, texture] outputs: [heightfield, normals, mesh] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Zhao, 2004" url: "https://texelatlas.vercel.app/t/eikonal-coastal-wave-refraction-shoaling/" sources_verified_at: "2026-11-30" --- # Fast-Sweeping Eikonal Coastal Wave Refraction & Ray-Tube Shoaling (Zhao, 2004) > Solves the 2D Eikonal equation over seabed bathymetry via fast sweeping to obtain wave travel times, propagation directions, and ray-tube shoaling amplitudes so ocean swells bend realistically around islands and break onto shores. ## Reach for it when - ocean waves fail to bend parallel to curving beaches and headlands - fft ocean looks identical in deep water and shallow shorelines - need waves to slow down shorten and steepen as seabed depth drops - compute realistic coastal wave phase and direction from a bathymetry map - drive shoreline breaking swells and surf zones from terrain height ## How it works In shallow water, surface wave phase speed drops with seabed depth `h` according to linear shallow-water dispersion (`c ≈ sqrt(g * h)` in the shallow limit). By geometric optics, wave crests bend toward shallower contours and satisfy the **Eikonal equation** `|grad(tau)| = 1 / c(x, z)`, where `tau(x, z)` is the wave arrival travel time. Given a bathymetry heightfield, **Zhao's fast sweeping method** initializes `tau` along the shoreline or offshore boundary and performs alternating Gauss-Seidel grid sweeps across the four diagonal directions, solving a local quadratic upwind update at each cell until convergence in `O(N)` work. From the resulting travel-time texture `tau`, finite differences yield the local wave propagation direction `k_hat = grad(tau) / |grad(tau)|`, wavefront curvature (divergence of `k_hat`), and a **ray-tube shoaling factor** combining Green's law (`h^(-1/4)`) with energy focusing on headlands and defocusing in bays. At runtime, the vertex and fragment shaders evaluate wave phase `omega * (tau + t)` directly from the precomputed map, steepening crests into plunging asymmetric breakers up to the depth-limited breaking threshold (`~0.42–0.78 * h`), while damping regions where colliding wavefronts form shocks. ## When to use it Choose it when rendering large coastlines, islands, and reefs where offshore swells must smoothly refract parallel to beaches, wrap around sea stacks, and shoal into breaking surf at minimal runtime cost. Prefer [fft-ocean](fft-ocean) for open deep-water wind seas where bathymetry is uniform and periodic spectral synthesis excels. Prefer [shallow-water-equations](shallow-water-equations) when you need two-way dynamic fluid interactions, wakes, or rapidly changing water levels rather than steady-state swell refraction. Prefer [gerstner-waves](gerstner-waves) when a handful of unrefracted analytic wave trains suffice. ## Cost cheap — Fast-sweeping Eikonal baking runs once per bathymetry change in milliseconds on CPU or GPU; runtime evaluation needs only texture lookups per vertex/pixel (Ultra-Water reports ~1.9–3.0 ms total for its full water pass at 1440p on an RTX 3060). Measured GPU Weight: 5.29× baseline (light) — 0.1741 ms median / 0.1809 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.12× baseline (light) — 0.0814 ms median (2.14× faster on L4). Ampere A100 scaling: 3.69× baseline (light) — 0.1063 ms median (1.64× faster on A100). ## Failure modes - Eikonal shocks where wavefronts wrap around opposite sides of an island or rock and collide produce discontinuous gradients that cause folded mesh sheets unless damped - Pure geometric optics ignores wave diffraction behind sharp breakwaters and narrow harbor mouths, leaving overly stark shadow zones - Static baked travel-time fields must be re-swept if seabed bathymetry or large submerged obstacles move dynamically - Unfiltered steep coastal displacement on a sliding camera-centered mesh causes waterline swimming unless wave amplitudes are band-limited to local vertex spacing ## Dataflow - Inputs: heightfield, texture - Outputs: heightfield, normals, mesh - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Eikonal Coastal Wave Refraction & Shoaling — travel-time fronts & bathymetry (left) vs refracted breaking surf (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_WAVE_PERIOD": 18, "P_SHOAL_GAIN": 1.15, "P_SWELL_DIR": 0.28, "P_SPLIT": 0.48 } ``` ```glsl const float P_WAVE_PERIOD = 18.0; // P Swell Frequency [8.0, 32.0, 1.0] const float P_SHOAL_GAIN = 1.15; // P Shoaling Amp [0.3, 2.0, 0.05] const float P_SWELL_DIR = 0.28; // P Swell Angle [-0.8, 0.8, 0.04] const float P_SPLIT = 0.48; // P Eikonal / Ocean Split [0.0, 1.0, 0.02] // Coastal bathymetry depth h(p) > 0 in water, <= 0 on volcanic island & curved headland float evalBathymetry(vec2 p) { // Sloping mainland beach along top edge (y > 0.38) float beach = 0.42 - p.y + 0.09 * sin(p.x * 3.2) + 0.04 * cos(p.x * 7.5); // Offshore volcanic island with submerged shallow shoal apron float dIsl = length((p - vec2(-0.18, -0.08)) * vec2(0.95, 1.18)) - 0.19; // Secondary submerged reef shoal on right float dReef = length((p - vec2(0.36, 0.02)) * vec2(1.1, 0.85)) - 0.14; float h = min(beach, dIsl); h = min(h, dReef + 0.06); // reef stays slightly submerged so waves bend & amplify over it! return h; } // Fast-sweeping Eikonal travel-time solution T(p) where |grad T| = 1 / c(h), c(h) = sqrt(g * h) // Waves slow down in shallow water -> wavefronts bend/wrap concentrically around island & shoreline! float evalEikonalTime(vec2 p, float dirAng) { vec2 kDir = vec2(sin(dirAng), cos(dirAng)); float baseT = dot(p, kDir); // Local refraction delay accumulated around shallow bathymetry features float dIsl = length((p - vec2(-0.18, -0.08)) * vec2(0.95, 1.18)); float dReef = length((p - vec2(0.36, 0.02)) * vec2(1.1, 0.85)); float beachDist = max(0.42 - p.y + 0.09 * sin(p.x * 3.2), 0.005); // Shallow-water phase speed slowdown bends iso-T fronts parallel to depth contours! float slowIsl = 0.26 * exp(-max(dIsl - 0.16, 0.0) * 4.2); float slowReef = 0.16 * exp(-max(dReef - 0.10, 0.0) * 4.8); float slowBeach = 0.24 * exp(-beachDist * 5.2); return baseT + slowIsl + slowReef + slowBeach; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showOcean = sx >= split; float freq = clamp(P_WAVE_PERIOD, 6.0, 36.0); float shoalGain = clamp(P_SHOAL_GAIN, 0.2, 2.4); float dirAng = clamp(P_SWELL_DIR, -1.0, 1.0); vec2 p = uv * 1.15; float h = evalBathymetry(p); // Compute Eikonal travel time T and its gradient (wave propagation vector & local wave speed c = 1/|grad T|) float e = 0.004; float T = evalEikonalTime(p, dirAng); float Tx = (evalEikonalTime(p + vec2(e, 0.0), dirAng) - evalEikonalTime(p - vec2(e, 0.0), dirAng)) / (2.0 * e); float Ty = (evalEikonalTime(p + vec2(0.0, e), dirAng) - evalEikonalTime(p - vec2(0.0, e), dirAng)) / (2.0 * e); vec2 gradT = vec2(Tx, Ty); float slowness = length(gradT); // Ray-tube shoaling amplitude (Green's law ~ h^(-1/4) modulated by ray convergence) float hClamped = max(h, 0.015); float shoalAmp = clamp(pow(0.28 / hClamped, 0.34) * (0.65 + 0.45 * slowness) * shoalGain, 0.35, 2.2); // Refracted trochoidal swell wave height & normal float phase = T * freq - iTime * 2.6; float steep = clamp(shoalAmp * 0.42, 0.1, 0.85); float wave = sin(phase + steep * sin(phase)); float dWave = cos(phase + steep * sin(phase)) * (1.0 + steep * cos(phase)); vec3 col; if (h <= 0.0) { // Volcanic island & sandy coastal shore float elev = -h; vec3 sand = vec3(0.76, 0.68, 0.50); vec3 rock = vec3(0.26, 0.28, 0.24); vec3 veg = vec3(0.18, 0.36, 0.18); float hx = evalBathymetry(p + vec2(e, 0.0)) - evalBathymetry(p - vec2(e, 0.0)); float hy = evalBathymetry(p + vec2(0.0, e)) - evalBathymetry(p - vec2(0.0, e)); vec3 ln = normalize(vec3(hx * 22.0, hy * 22.0, 1.0)); float nl = max(dot(ln, normalize(vec3(0.55, -0.45, 0.7))), 0.15); vec3 land = mix(sand, mix(veg, rock, smoothstep(0.06, 0.16, elev)), smoothstep(0.015, 0.055, elev)); col = land * nl * 1.25; if (!showOcean) { // Elevation contour rings on land in Eikonal diagnostic view float cLine = smoothstep(0.08, 0.02, abs(fract(elev * 22.0) - 0.5)); col = mix(col * 0.72, vec3(0.95, 0.82, 0.52), cLine * 0.45); } } else if (!showOcean) { // Left: Bathymetry depth field + Eikonal iso-travel-time wavefronts + shoaling amplification heatmap vec3 deepC = vec3(0.04, 0.10, 0.24); vec3 midC = vec3(0.08, 0.44, 0.62); vec3 shoalC = vec3(0.98, 0.58, 0.14); float shNorm = clamp((shoalAmp - 0.5) / 1.4, 0.0, 1.0); col = mix(mix(deepC, midC, smoothstep(0.55, 0.05, h)), shoalC, shNorm * 0.72); // Crisp moving iso-travel-time Eikonal wavefront contours float front = smoothstep(0.12, 0.02, abs(fract(phase / 6.2831853) - 0.5)); col = mix(col, vec3(0.98, 0.99, 1.0), front * 0.85); // Subtle bathymetry iso-depth contour lines float bCont = smoothstep(0.06, 0.015, abs(fract(h * 12.0) - 0.5)); col = mix(col, vec3(0.28, 0.92, 0.82), bCont * 0.28); } else { // Right: Physically shaded coastal ocean with refracted swells, shallow turquoise absorption, and breaking surf foam! vec3 wN = normalize(vec3(-gradT.x * dWave * 0.24 * shoalAmp, -gradT.y * dWave * 0.24 * shoalAmp, 1.0)); vec3 sunDir = normalize(vec3(0.58, -0.52, 0.62)); vec3 V = vec3(0.0, 0.0, 1.0); vec3 H = normalize(sunDir + V); vec3 deepWater = vec3(0.02, 0.12, 0.24); vec3 shallowTurq = vec3(0.08, 0.56, 0.58); vec3 waterCol = mix(shallowTurq, deepWater, smoothstep(0.02, 0.48, h)); // Subsurface turquoise crest translucency + crisp solar glint float glint = pow(max(dot(wN, H), 0.0), 86.0) * 2.2; float sss = smoothstep(0.15, 0.95, wave) * smoothstep(0.45, 0.04, h) * 0.35; float fres = 0.06 + 0.45 * pow(1.0 - max(wN.z, 0.0), 3.0); vec3 skyRefl = vec3(0.42, 0.64, 0.88); col = mix(waterCol + vec3(0.12, 0.68, 0.64) * sss, skyRefl, fres) + vec3(1.0, 0.92, 0.78) * glint; // Breaking whitewater foam on steep shoaling wave crests & shoreline swash float crestFoam = smoothstep(0.68, 0.94, wave * clamp(shoalAmp * 0.68, 0.4, 1.25)) * smoothstep(0.28, 0.02, h); float shoreFoam = smoothstep(0.042, 0.004, h) * (0.65 + 0.35 * sin(phase)); float foam = clamp(crestFoam + shoreFoam, 0.0, 1.0); col = mix(col, vec3(0.95, 0.97, 0.99), foam); } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md): Provides multi-cascade deep-water wind waves that blend seamlessly into Eikonal refracted breakers as seabed depth shoals. - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Uses the refracted surface slopes and shallow bathymetry map to project depth-accurate animated caustics onto the seabed. ## Combination ideas - [Bathymetry-refracted coastal ocean with shore caustics](https://texelatlas.vercel.app/ideas/eikonal-refracted-fft-shore-caustics/) ## Sources 1. [primary] Hongkai Zhao (2004) A fast sweeping method for Eikonal equations. Mathematics of Computation. https://doi.org/10.1090/s0025-5718-04-01678-3 (verified via crossref on 2026-11-30) 2. [primary] Manuel N. Gamito, F.Kenton Musgrave (2002) An accurate model of wave refraction over shallow water. Computers & Graphics. https://doi.org/10.1016/s0097-8493(01)00181-9 (verified via crossref on 2026-11-30) 3. [secondary] Stefan Jeschke, Chris Wojtan (2017) Water wave packets. ACM Transactions on Graphics. https://doi.org/10.1145/3072959.3073678 (verified via crossref on 2026-11-30) 4. [implementation] Humpalumps (2026) Humpalumps/Ultra-Water. https://github.com/Humpalumps/Ultra-Water License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Fast-Sweeping Eikonal Coastal Wave Refraction & Ray-Tube Shoaling." https://texelatlas.vercel.app/t/eikonal-coastal-wave-refraction-shoaling/ (accessed 2026-12-01). --- id: "enhanced-sphere-tracing" title: "Enhanced Sphere Tracing" domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda] year_introduced: 2014 inputs: [sdf] outputs: [depth, normals] style: "both" dynamic: "dynamic" cost: "medium" authority: "Keinert et al., 2014" url: "https://texelatlas.vercel.app/t/enhanced-sphere-tracing/" sources_verified_at: "2026-11-29" --- # Enhanced Sphere Tracing (Keinert et al., 2014) > Sphere tracing with over-relaxation: step slightly beyond the safe distance and fall back only when consecutive spheres fail to overlap. Cuts iteration counts, especially for near-grazing rays, with a pixel-exact result. ## Reach for it when - ray marching is slow at grazing angles - too many iterations per pixel on distance fields - want faster raymarcher without changing the result - shader steps crawl along surfaces seen at a slant - reduce march step count in an sdf scene ## How it works Standard sphere tracing steps exactly by the distance d. Enhanced sphere tracing multiplies the step by a relaxation factor omega (around 1.2 to 1.6). After the step, it checks whether the new sphere still overlaps the previous one: the sum of the two radii must be at least the step length. If the check fails, it undoes the relaxation for that step and falls back to the safe step. It also uses the unrelaxed ray parameter with the smallest error to pick the best hit estimate. Automatic variants adapt omega per ray using the local curvature estimate. Some versions add a final refinement from the last spheres so grazing hits are resolved more precisely. ## When to use it Choose it as a drop-in speed-up for any sphere-traced scene where fields are exact or conservative and you see slow grazing pixels. Prefer plain [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md) when your field is far from 1-Lipschitz and fall-backs would be constant, and [Segment Tracing](https://texelatlas.vercel.app/t/segment-tracing.md) when you can supply local Lipschitz constants for warped or animated fields. ## Cost medium — Typically fewer iterations than basic sphere tracing at the cost of a few extra operations per step; gains depend on scene geometry. Measured GPU Weight: 11.65× baseline (moderate) — 0.3832 ms median / 0.3897 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.11× baseline (moderate) — 0.1608 ms median (2.38× faster on L4). Ampere A100 scaling: 7.12× baseline (moderate) — 0.2052 ms median (1.87× faster on A100). ## Failure modes - Overstep followed by backtrack wastes work on cluttered scenes - Poorly chosen omega leads to rejected relaxations on every step and no gain - Still assumes a Lipschitz-1 field; warps break the overlap test's guarantees - Divergent step counts across a warp reduce GPU efficiency ## Dataflow - Inputs: sdf - Outputs: depth, normals - Platforms: webgl2, webgpu, desktop-gpu, cuda ## Presets ### Over-relaxed sphere tracing step counts vs plain sphere tracing (glsl-fragment; rendered 2026-11-29) ```json { "MAX_STEPS": 48, "OMEGA": 1.6, "EPS": 0.001 } ``` ```glsl // Over-relaxed sphere tracing (omega 1.6 with fallback): left = plain tracing steps, right = relaxed steps, same heat scale. const int MAX_STEPS = 48; const float OMEGA = 1.6; const float EPS = 0.001; float map(vec3 p) { float s = length(p - vec3(-0.9, 0.0, 0.0)) - 0.8; vec2 q = vec2(length(p.xz - vec2(1.0, 0.2)) - 0.8, p.y); float t = length(q) - 0.25; float b = p.y + 0.9; return min(min(s, t), b); } vec3 heat(float x) { return clamp(vec3(1.5 * x, 1.5 - abs(3.0 * x - 1.5), 1.5 - 1.5 * x), 0.0, 1.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 1.0, -4.0), rd = normalize(vec3(uv.x, uv.y - 0.12, 1.4)); float om = uv.x > 0.0 ? OMEGA : 1.0; float t = 0.0, prevR = 0.0, stepLen = 0.0; int n = 0; bool hit = false; for (int i = 0; i < MAX_STEPS; i++) { n = i; float r = map(ro + rd * t); if (om > 1.0 && stepLen > prevR + r) { // overshoot: back up to the last safe step t += prevR - stepLen; stepLen = 0.0; prevR = 0.0; continue; } if (r < EPS * t + 0.0005) { hit = true; break; } stepLen = om * r; prevR = r; t += stepLen; if (t > 20.0) break; } vec3 col = heat(float(n) / float(MAX_STEPS)); if (!hit && t > 20.0) col *= 0.35; col = mix(col, vec3(1.0), smoothstep(0.003, 0.0, abs(uv.x))); fragColor = vec4(pow(col, vec3(0.6)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md) ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): Step bounds rely on the SDF being close to exact. ## Sources 1. [primary] Benjamin Keinert, Henry Schäfer, Johann Korndörfer, Urs Ganse, Marc Stamminger (2014) Enhanced Sphere Tracing. Smart Tools and Apps for Graphics - Eurographics Italian Chapter Conference. https://doi.org/10.2312/stag.20141233 (verified via doi.org on 2026-11-29) 2. [tutorial] Inigo Quilez Distance functions. iquilezles.org. https://iquilezles.org/articles/distfunctions (verified via http on 2026-11-29) ## Cite this entry Texel. "Enhanced Sphere Tracing." https://texelatlas.vercel.app/t/enhanced-sphere-tracing/ (accessed 2026-12-01). --- id: "environment-mapping-cubemaps" title: "Environment mapping, cubemaps and skyboxes" aliases: [cube mapping, skybox, reflection mapping, HDRI backdrop, environment map] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 1986 inputs: [hdr-image] outputs: [radiance] style: "both" dynamic: "both" cost: "cheap" authority: "Greene, 1986" url: "https://texelatlas.vercel.app/t/environment-mapping-cubemaps/" sources_verified_at: "2026-11-29" --- # Environment mapping, cubemaps and skyboxes (Greene, 1986) > Store the light arriving from the distant surroundings in a six-face cubemap or equirectangular image, then look it up by direction for backgrounds, mirror reflections and, once prefiltered, diffuse and glossy lighting. ## Reach for it when - need a skybox or hdri background behind the scene - want cheap fake reflections of the surroundings on shiny objects - metal looks dull without anything to reflect - how to store light from all directions in a texture ## How it works An environment map records incoming radiance as a function of direction only, which is exact when the light is far away compared with the object. The map is stored as six cube faces or a latitude-longitude image; a cubemap fetch converts a 3D direction into a face and texel, so there is no pole distortion and hardware filtering works across seams on modern GPUs. Uses build on one lookup. The background is a draw at the far plane that samples the map with the view ray. A mirror reflection samples with `reflect(view, normal)`. Rough and diffuse lighting need the map convolved against a lobe, which is why engines prefilter it into mips ([split-sum-ibl](split-sum-ibl)) or project it into [spherical-harmonics-lighting](spherical-harmonics-lighting). Captured HDR data must stay in linear floating point; an LDR map clips the sun and makes every reflection look weak. The map can be a photographed HDRI, a rendered sky ([hosek-wilkie-sky](hosek-wilkie-sky), [hillaire-sky-atmosphere](hillaire-sky-atmosphere)), or a capture from the scene itself. ## When to use it Choose it for the backdrop, for sky and studio lighting, and for reflections of things that are effectively at infinity. Prefer [reflection-probes-parallax-corrected-cubemaps](reflection-probes-parallax-corrected-cubemaps) for interiors, where finite room size makes plain lookups look pasted on. Prefer [screen-space-reflections](screen-space-reflections) or [path-tracing](path-tracing) when nearby dynamic objects must appear in reflections. Prefer [split-sum-ibl](split-sum-ibl) for glossy PBR lighting from the same map rather than raw reflect lookups. ## Cost cheap — One texture fetch per pixel for lookup; memory is six faces per probe, and prefiltering is a one-time cost. Measured GPU Weight: 4.91× baseline (light) — 0.1615 ms median / 0.1712 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 4.26× baseline (light) — 0.0678 ms median (2.38× faster on L4). Ampere A100 scaling: 3.49× baseline (light) — 0.1004 ms median (1.61× faster on A100). ## Failure modes - Reflections have no parallax, so an object near a floor or wall looks as if its reflection were infinitely far away - Seams along cube edges if filtering across faces is not enabled or if prefilter does not wrap - Clipped suns and lights when the map is stored in 8 bits, making metals dull - Equirectangular maps stretch and alias near the poles - Reflected content cannot contain the object itself or any local dynamic light - Mismatched handedness or axis convention flips the map horizontally or vertically between tools ## Engine support - babylonjs: builtin — `new BABYLON.CubeTexture(url, scene); scene.environmentTexture` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Textures/cubeTexture.pure.ts, checked 2026-12-01) - blender: builtin — `World > Surface > Environment Texture node` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/environment.html, checked 2026-12-01) — Equirectangular and mirror-ball projections; no native cubemap type. - godot: builtin — `WorldEnvironment > Environment.background_mode = BG_SKY with a Sky (PanoramaSkyMaterial for HDRI)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - metal: builtin — `MTLTextureType.typeCube; MSL texturecube` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtltexturetype.json, checked 2026-12-01) — Cube textures and sampling are primitives; skybox pass is yours. - threejs: builtin — `scene.background = scene.environment = cubeTexture (CubeTextureLoader)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/loaders/CubeTextureLoader.js, checked 2026-12-01) - unity: builtin — `Lighting > Environment > Skybox Material (cubemap/panoramic); HDRP Volume > Visual Environment = HDRI Sky` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RenderSettings-skybox.html, checked 2026-12-01) - unreal: builtin — `Sky Light with a manually specified cubemap` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sky-lights-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `createTexture(6 layers) + createView({dimension:'cube'}); WGSL texture_cube` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Cube view and sampling are primitives; skybox pass is yours. ## Dataflow - Inputs: hdr-image - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Environment Mapping & Cubemaps — unfolded 6-face cubemap cross & mip blur (left) vs seamless 3D skybox & glossy IBL spheres (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.18, "P_SUN_ELEV": 0.36, "P_CAM_ORBIT": 0.35, "P_SPLIT": 0.46 } ``` ```glsl const float P_ROUGHNESS = 0.18; // P IBL Roughness [0.0, 0.9, 0.03] const float P_SUN_ELEV = 0.36; // P Sun Elevation [0.08, 0.85, 0.03] const float P_CAM_ORBIT = 0.35; // P Orbit Speed [0.0, 1.5, 0.05] const float P_SPLIT = 0.46; // P Cross / 3D Split [0.0, 1.0, 0.02] // Analytic procedural HDR cubemap sampled by unit direction d and prefilter roughness r vec3 evalCubemap(vec3 d, float rough, float sunElev) { d = normalize(d); vec3 sunDir = normalize(vec3(0.72, sunElev, -0.58)); float blur = clamp(rough, 0.0, 1.0); // Sky zenith-to-horizon gradient with warm sunset scattering vec3 zenith = vec3(0.10, 0.24, 0.58); vec3 horizon = mix(vec3(0.95, 0.56, 0.30), vec3(0.65, 0.78, 0.94), smoothstep(0.15, 0.70, sunElev)); vec3 ground = vec3(0.12, 0.11, 0.13); float upT = smoothstep(-0.04 - blur * 0.35, 0.55 + blur * 0.25, d.y); vec3 sky = mix(horizon, zenith, upT); float gndT = smoothstep(0.02 + blur * 0.25, -0.18 - blur * 0.35, d.y); vec3 col = mix(sky, ground, gndT); // Distant mountain silhouette band around the horizon float az = atan(d.z, d.x); float mtnH = 0.055 + 0.045 * sin(az * 3.0 + 0.5) + 0.028 * cos(az * 7.0 - 1.1) + 0.015 * sin(az * 13.0); float mtnMask = smoothstep(mtnH + 0.012 + blur * 0.14, mtnH - 0.012 - blur * 0.10, d.y) * smoothstep(-0.08, 0.01, d.y); col = mix(col, vec3(0.14, 0.16, 0.24) + vec3(0.22, 0.14, 0.10) * max(dot(d, sunDir), 0.0), mtnMask * (1.0 - blur * 0.65)); // Soft volumetric cloud deck float cl = sin(az * 4.0 + d.y * 9.0) * cos(az * 6.0 - d.y * 5.0); float clBand = smoothstep(0.15, 0.45, d.y) * smoothstep(0.75, 0.35, d.y) * smoothstep(0.15, 0.72, cl); col = mix(col, mix(vec3(0.96, 0.86, 0.78), vec3(0.72, 0.78, 0.88), blur), clBand * 0.42 * (1.0 - blur * 0.5)); // Pre-filtered solar disc + Mie aureole float sunCos = max(dot(d, sunDir), 0.0); float sunExp = mix(220.0, 6.0, blur * blur); float sunGain = mix(6.5, 0.95, blur); col += vec3(1.0, 0.86, 0.62) * (pow(sunCos, sunExp) * sunGain + pow(sunCos, 8.0) * 0.42); return col; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool show3D = sx >= split; float rough = clamp(P_ROUGHNESS, 0.0, 0.95); float sunElev = clamp(P_SUN_ELEV, 0.06, 0.88); float orb = iTime * max(P_CAM_ORBIT, 0.0); vec3 col = vec3(0.05, 0.06, 0.09); if (!show3D) { // Left: Horizontal 4x3 cubemap cross layout (-X, +Z, +X, -Z across middle; +Y top; -Y bottom) vec2 p = vec2(sx / max(split, 0.05), fragCoord.y / max(iResolution.y, 1.0)); vec2 g = (p - vec2(0.06, 0.14)) / vec2(0.88, 0.72); vec2 cell = floor(g * vec2(4.0, 3.0)); vec2 f = fract(g * vec2(4.0, 3.0)) * 2.0 - 1.0; bool valid = false; vec3 dir = vec3(0.0, 0.0, 1.0); vec3 faceTint = vec3(1.0); if (cell.y == 1.0 && cell.x >= 0.0 && cell.x < 4.0) { valid = true; if (cell.x == 0.0) { dir = vec3(-1.0, f.y, f.x); faceTint = vec3(1.0, 0.45, 0.45); } else if (cell.x == 1.0) { dir = vec3(f.x, f.y, 1.0); faceTint = vec3(0.45, 0.85, 1.0); } else if (cell.x == 2.0) { dir = vec3(1.0, f.y, -f.x); faceTint = vec3(0.95, 0.72, 0.35); } else { dir = vec3(-f.x, f.y, -1.0); faceTint = vec3(0.65, 0.55, 1.0); } } else if (cell.x == 1.0 && cell.y == 2.0) { valid = true; dir = vec3(f.x, 1.0, -f.y); faceTint = vec3(0.45, 1.0, 0.65); } else if (cell.x == 1.0 && cell.y == 0.0) { valid = true; dir = vec3(f.x, -1.0, f.y); faceTint = vec3(0.85, 0.65, 0.45); } if (valid) { col = evalCubemap(dir, rough, sunElev); // Clean cubemap face border float edge = smoothstep(0.93, 0.985, max(abs(f.x), abs(f.y))); col = mix(col, faceTint * 1.15, edge); } else { vec2 bgG = abs(fract(p * 18.0) - 0.5); col = vec3(0.05, 0.06, 0.09) + vec3(0.025, 0.035, 0.05) * smoothstep(0.06, 0.01, min(0.5 - bgG.x, 0.5 - bgG.y)); } } else { // Right: Seamless 3D skybox + chrome mirror ball (center) + prefiltered glossy/diffuse companion spheres vec3 ro = vec3(2.35 * sin(orb), 0.16, 2.35 * cos(orb)); vec3 fw = normalize(-ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.38 + ri * (uv.x - 0.18) + up * uv.y); col = evalCubemap(rd, 0.0, sunElev); // Intersect 3 IBL chrome/glossy/matte spheres vec3 centers[3]; float radii[3]; float rVals[3]; centers[0] = vec3(0.0, 0.02, 0.0); radii[0] = 0.52; rVals[0] = rough; centers[1] = vec3(-0.74, -0.22, 0.25); radii[1] = 0.24; rVals[1] = 0.03; centers[2] = vec3(0.74, -0.22, -0.18); radii[2] = 0.24; rVals[2] = 0.82; float bestT = 1e5; int bestI = -1; for (int i = 0; i < 3; i++) { vec3 oc = ro - centers[i]; float b = dot(oc, rd); float c = dot(oc, oc) - radii[i] * radii[i]; float disc = b * b - c; if (disc > 0.0) { float t = -b - sqrt(disc); if (t > 0.05 && t < bestT) { bestT = t; bestI = i; } } } if (bestI >= 0) { vec3 p = ro + rd * bestT; vec3 n = normalize(p - centers[bestI]); vec3 v = -rd; vec3 rDir = reflect(-v, n); float r = rVals[bestI]; vec3 f0 = (bestI == 0) ? vec3(0.95, 0.78, 0.45) : ((bestI == 1) ? vec3(0.94) : vec3(0.32, 0.48, 0.62)); float ndv = max(dot(n, v), 0.0); vec3 F = f0 + (1.0 - f0) * pow(1.0 - ndv, 5.0); vec3 specIBL = evalCubemap(rDir, r, sunElev); vec3 diffIBL = evalCubemap(n, 0.92, sunElev) * 0.55; col = mix(specIBL * F, diffIBL * f0 + specIBL * F * 0.35, r * 0.75); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Reflection probes with parallax-corrected cubemaps](https://texelatlas.vercel.app/t/reflection-probes-parallax-corrected-cubemaps.md) ## Combines with - [Split-Sum Image-Based Lighting](https://texelatlas.vercel.app/t/split-sum-ibl.md): The raw environment map is the input that gets convolved per roughness into the prefiltered mip chain. - [Spherical-Harmonic Lighting (Irradiance Environment Maps)](https://texelatlas.vercel.app/t/spherical-harmonics-lighting.md): The same map projects to nine SH coefficients for cheap diffuse lighting. - [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md): A rendered sky can be captured into a cubemap each time the sun moves, giving a dynamic environment. ## Sources 1. [primary] Ned Greene (1986) Environment Mapping and Other Applications of World Projections. IEEE Computer Graphics and Applications. https://doi.org/10.1109/mcg.1986.276658 (verified via crossref on 2026-11-29) 2. [tutorial] Romain Guy, Mathias Agopian Filament: Physically based rendering (image based lights section). google.github.io. https://google.github.io/filament/Filament.html (verified via http on 2026-11-29) 3. [implementation] google (2018) google/filament. https://github.com/google/filament License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Environment mapping, cubemaps and skyboxes." https://texelatlas.vercel.app/t/environment-mapping-cubemaps/ (accessed 2026-12-01). --- id: "error-diffusion-dithering" title: "Error-diffusion dithering (Floyd-Steinberg)" domain: "npr" stage: "post" realtime: "offline" platforms: [cpu, python, cuda] year_introduced: 1976 inputs: [ldr-image, hdr-image] outputs: [ldr-image] style: "stylized" dynamic: "static" cost: "offline" authority: "Wikipedia" url: "https://texelatlas.vercel.app/t/error-diffusion-dithering/" sources_verified_at: "2026-11-29" --- # Error-diffusion dithering (Floyd-Steinberg) (Wikipedia) > Quantizes pixels one at a time and spreads each pixel's rounding error to unvisited neighbours, giving the best tonal accuracy among simple dithers. ## Reach for it when - banding when reducing colors to a small palette - retro limited palette image looks posterized - convert to 1-bit image that keeps tones - smooth gradients on low bit depth displays ## How it works Pixels are scanned in raster order. For each pixel, the colour plus accumulated error is rounded to the nearest palette entry, and the difference between wanted and output is distributed to neighbours not yet visited: for Floyd-Steinberg, 7/16 to the right, 3/16 below-left, 5/16 below and 1/16 below-right. Serpentine scanning reverses direction every row to reduce directional artefacts. Alternative kernels (Jarvis-Judice-Ninke, Stucki, Atkinson) trade smoothness against sharpness. The sequential dependence makes it hard to parallelise, so on GPUs it needs wavefront or tile tricks, and the pattern changes across the whole image whenever a single pixel changes. ## When to use it Choose it for offline conversion, texture baking, and stills where detail fidelity matters. Prefer [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md) or [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) for real-time 3D, because error diffusion crawls and shimmers with any change in the image. ## Cost offline — Sequential per-pixel work; trivially fast on CPU for stills but poor fit to massively parallel shaders. Measured GPU Weight: 123.21× baseline (extreme) — 4.0537 ms median / 4.2581 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 108.15× baseline (extreme) — 1.7196 ms median (2.36× faster on L4). Ampere A100 scaling: 73.1× baseline (extreme) — 2.1053 ms median (1.93× faster on A100). ## Failure modes - Pattern changes everywhere when the source changes, so animated output flickers badly - Worm-like directional artefacts in near-flat regions - Raster-order dependence blocks straightforward GPU parallelism - Edge bleed of error across hard boundaries ## Dataflow - Inputs: ldr-image, hdr-image - Outputs: ldr-image - Platforms: cpu, python, cuda ## Presets ### Error-diffusion dithering — split continuous tone vs Floyd-Steinberg residual stipple (glsl-fragment; rendered 2026-11-30) ```json { "P_LEVELS": 2, "P_DIFFUSION": 1, "P_PIXEL_SIZE": 2.5, "P_SPLIT": 0.36 } ``` ```glsl const float P_LEVELS = 2.0; // P Quant Levels [2.0, 6.0, 1.0] const float P_DIFFUSION = 1.0; // P Error Diffusion [0.0, 1.4, 0.05] const float P_PIXEL_SIZE = 2.5; // P Pixel Size [1.0, 6.0, 0.25] const float P_SPLIT = 0.36; // P Split Position [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } float mapObj(vec3 p) { vec3 q = p; q.xz = rot2(iTime * 0.42) * q.xz; q.xy = rot2(0.45 + 0.15 * sin(iTime * 0.6)) * q.xy; float d1 = sdTorus(q, vec2(0.62, 0.22)); float d2 = length(p - vec3(0.0, 0.0, 0.0)) - 0.34; float dFloor = p.y + 0.88; return min(min(d1, d2), dFloor); } vec3 calcN(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapObj(p + e.xyy) - mapObj(p - e.xyy), mapObj(p + e.yxy) - mapObj(p - e.yxy), mapObj(p + e.yyx) - mapObj(p - e.yyx) )); } // Continuous luminance of a 3D classical still-life scene at normalized cell coord float sampleTone(vec2 uv) { vec3 ro = vec3(0.0, 0.35, 2.55); vec3 rd = normalize(vec3(uv, -1.55)); float t = 0.0; bool hit = false; for (int i = 0; i < 42; i++) { float d = mapObj(ro + rd * t); if (d < 0.0025) { hit = true; break; } t += d; if (t > 8.0) break; } if (!hit) { // Smooth studio gradient backdrop to showcase gradient dithering quality return clamp(0.14 + 0.56 * smoothstep(-0.55, 0.55, uv.y) + 0.16 * exp(-length(uv - vec2(0.28, 0.26)) * 2.2), 0.0, 1.0); } vec3 p = ro + rd * t; vec3 n = calcN(p); vec3 l = normalize(vec3(0.65, 0.78, 0.55)); vec3 l2 = normalize(vec3(-0.7, 0.25, -0.4)); float diff = max(dot(n, l), 0.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.45; vec3 h = normalize(l - rd); float spec = pow(max(dot(n, h), 0.0), 32.0) * 0.55; float back = max(dot(n, l2), 0.0) * 0.22; float ao = clamp(0.55 + 0.45 * smoothstep(-0.88, -0.3, p.y), 0.0, 1.0); return clamp((0.08 + 0.72 * diff + back + rim + spec) * ao, 0.0, 1.0); } // Local finite-horizon Floyd-Steinberg (7/16, 3/16, 5/16, 1/16) error-diffusion solver // Runs a 5-column x 3-row causal error carry window ending at cell c float floydSteinbergLocal(vec2 c, float pxScale, float levels, float diffWeight) { float errRow[5]; for (int k = 0; k < 5; k++) errRow[k] = 0.0; float stepVal = 1.0 / max(levels - 1.0, 1.0); float outQ = 0.0; for (int ry = -2; ry <= 0; ry++) { float nextRow[5]; for (int k = 0; k < 5; k++) nextRow[k] = 0.0; float carryRight = 0.0; // Slight blue-like phase seed on top boundary to break periodic lock for (int rx = 0; rx < 5; rx++) { vec2 sc = c + vec2(float(rx - 4), float(ry)); vec2 suv = (sc * pxScale - 0.5 * iResolution.xy) / iResolution.y; float val = sampleTone(suv); // Add causal errors diffused from left (7/16) and previous row (3/16, 5/16, 1/16) float accum = val + diffWeight * (carryRight + errRow[rx]); float q = floor(accum / stepVal + 0.5) * stepVal; q = clamp(q, 0.0, 1.0); float err = accum - q; carryRight = err * (7.0 / 16.0); if (rx > 0) nextRow[rx - 1] += err * (3.0 / 16.0); nextRow[rx] += err * (5.0 / 16.0); if (rx < 4) nextRow[rx + 1] += err * (1.0 / 16.0); if (ry == 0 && rx == 4) outQ = q; } for (int k = 0; k < 5; k++) errRow[k] = nextRow[k]; } return outQ; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 screenUV = fragCoord / iResolution.xy; vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float pxSize = clamp(P_PIXEL_SIZE, 1.0, 8.0); float levels = floor(clamp(P_LEVELS, 2.0, 8.0) + 0.5); float diffW = clamp(P_DIFFUSION, 0.0, 1.5); float splitX = clamp(P_SPLIT, 0.0, 1.0); vec3 inkDark = vec3(0.055, 0.06, 0.085); vec3 paperLight = vec3(0.95, 0.93, 0.87); vec3 col; if (screenUV.x < splitX) { float tone = sampleTone(uv); col = mix(inkDark, paperLight, tone); } else { vec2 cell = floor(fragCoord / pxSize) + 0.5; float q = floydSteinbergLocal(cell, pxSize, levels, diffW); col = mix(inkDark, paperLight, q); } if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(0.92, 0.36, 0.22); } fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Sources 1. [primary] Wikipedia Floyd-Steinberg dithering. en.wikipedia.org. https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering (verified via http on 2026-11-29) ## Cite this entry Texel. "Error-diffusion dithering (Floyd-Steinberg)." https://texelatlas.vercel.app/t/error-diffusion-dithering/ (accessed 2026-12-01). --- id: "exact-euclidean-distance-transform" title: "Exact Euclidean Distance Transform" aliases: [EDT, Felzenszwalb distance transform] domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, cuda, webgpu, python] year_introduced: 2012 inputs: [voxels, texture] outputs: [sdf, texture] style: "both" dynamic: "static" cost: "cheap" authority: "Felzenszwalb & Huttenlocher, 2012" url: "https://texelatlas.vercel.app/t/exact-euclidean-distance-transform/" sources_verified_at: "2026-11-29" --- # Exact Euclidean Distance Transform (Felzenszwalb & Huttenlocher, 2012) > Computes the exact squared Euclidean distance from every grid cell to the nearest feature in linear time by running a one-dimensional lower-envelope-of-parabolas pass along each axis. ## Reach for it when - need accurate distance field from a binary image - baking font or shape sdfs gives lumpy errors - approximate distance fields are not precise enough - generate a clean distance volume from voxels ## How it works The squared distance to a set of seeds is the minimum over seeds of a parabola per cell: f(q) = min_p ((q-p)^2 + g(p)). In one dimension, that minimum is the lower envelope of parabolas centred at each sample, which can be built in a single left-to-right sweep that keeps a stack of parabola indices and the boundaries where one overtakes the next. Evaluating the envelope at each grid position is a second sweep. Because squared Euclidean distance is separable, doing the 1D transform along rows, then columns (then depth for 3D) yields the exact result in O(n) total. The signed version runs it on both the shape and its complement and subtracts the square roots. ## When to use it Choose it when you need exact SDFs from binary images or voxel volumes for baking font SDFs, collision fields, [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) input or ambient occlusion, and when CPU or compute-shader time is acceptable. Prefer [Jump Flooding Algorithm](https://texelatlas.vercel.app/t/jump-flooding-algorithm.md) for per-frame, GPU-render-pass use where small errors are acceptable. ## Cost cheap — Linear in grid cells; separable, so each row or column is an independent parallel task. Measured GPU Weight: 2.74× baseline (light) — 0.0901 ms median / 0.0924 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.92× baseline (feather) — 0.0306 ms median (2.94× faster on L4). Ampere A100 scaling: 1.74× baseline (feather) — 0.0501 ms median (1.8× faster on A100). ## Failure modes - Distances are to cell centres, not to the sub-cell boundary, so binary inputs yield staircase fields unless anti-aliased input is used - Values near thin features differ by up to half a cell from the true surface distance - Memory-bound for large 3D volumes - Squared values overflow low-precision storage unless scaled ## Dataflow - Inputs: voxels, texture - Outputs: sdf, texture - Platforms: cpu, cuda, webgpu, python ## Presets ### Toy: the distance field this transform outputs (computed by brute force, not the linear-time algorithm) (glsl-fragment; rendered 2026-11-29) ```json { "N": 14, "BAND": 0.06 } ``` ```glsl // Exact Euclidean distance to the nearest feature (brute-force reference of what the linear-time EDT outputs), shown as banded field. const int N = 14; const float BAND = 0.06; vec2 site(int i) { float f = float(i); return vec2(fract(sin(f * 12.9898) * 43758.5), fract(sin(f * 78.233 + 1.0) * 24634.6)) * 0.84 + 0.08; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float d2 = 1e9; int id = 0; for (int i = 0; i < N; i++) { vec2 q = uv - site(i); float d = dot(q, q); if (d < d2) { d2 = d; id = i; } } float d = sqrt(d2); vec3 col = 0.5 + 0.5 * cos(6.2831 * (d * 2.2) + vec3(0.0, 0.8, 1.6)); col *= 0.35 + 0.65 * smoothstep(0.0, 0.5, abs(fract(d / BAND) - 0.5) + 0.3); col = mix(col, vec3(0.0), smoothstep(0.004, 0.0, abs(fract(d / BAND + 0.5) - 0.5) * BAND - 0.001) * 0.6); col = mix(col, vec3(1.0), smoothstep(0.012, 0.008, d)); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): Exact SDF from a binary volume gives a smoother input for contouring. ## Sources 1. [primary] Pedro F. Felzenszwalb, Daniel P. Huttenlocher (2012) Distance Transforms of Sampled Functions. Theory of Computing 8(19), 2012. https://theoryofcomputing.org/articles/v008a019 (verified via http on 2026-11-29) ## Cite this entry Texel. "Exact Euclidean Distance Transform." https://texelatlas.vercel.app/t/exact-euclidean-distance-transform/ (accessed 2026-12-01). --- id: "exponential-height-fog" title: "Exponential Height Fog" aliases: [analytic height fog, altitude fog] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unreal, unity, godot] year_introduced: 2002 inputs: [depth, material-params] outputs: [radiance, ldr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Quilez" url: "https://texelatlas.vercel.app/t/exponential-height-fog/" sources_verified_at: "2026-11-29" --- # Exponential Height Fog (Quilez) > Fog whose density falls off exponentially with altitude, integrated in closed form along the view ray so a fragment shader gets exact extinction and in-scatter with no ray marching. ## Reach for it when - need cheap ground fog that thickens near the floor - valley haze that fades with altitude - depth cueing for mobile or web with minimal cost - fog without raymarching in a fragment shader - mist that pools low in a stylised game ## How it works Density is a function rho(y) = a * exp(-b * y). For a straight segment from the camera to a surface point, the optical depth is the integral of rho along the segment. With exponential density along y this has a closed form: the integral becomes a * (exp(-b y0) - exp(-b y1)) / (b * dir.y) scaled by distance, with a limiting case when the ray is horizontal that must be handled to avoid dividing by zero. Transmittance is exp of minus optical depth; the fog colour, optionally tinted toward the sun with a directional lobe, is blended in by one minus transmittance. This is a single per-pixel expression that depends on camera height, fragment depth and view direction, and is applied in a post pass or in each material. ## When to use it Choose it for ground fog, valley haze and general depth cueing in mobile, web and stylised games where cost must be negligible and there is no per-light interaction. Prefer [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md) when fog must be lit and shadowed by dynamic lights, and prefer [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) for physically based aerial perspective. Use [Screen-space Volumetric Light Scattering (God Rays)](https://texelatlas.vercel.app/t/volumetric-light-scattering-god-rays.md) for sun shafts on top of an analytic fog. ## Cost cheap — A handful of ALU operations and one exponential per pixel. Measured GPU Weight: 2.36× baseline (light) — 0.0776 ms median / 0.0803 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.16× baseline (light) — 0.0344 ms median (2.26× faster on L4). Ampere A100 scaling: 1.51× baseline (feather) — 0.0436 ms median (1.78× faster on A100). ## Failure modes - Division by zero or NaN for rays near horizontal if the limit case is not handled - Fog does not interact with light sources or shadows, so there are no light shafts - Sky is shaded by the same fog and looks flat unless the fog is faded out with view angle - Sudden colour jump at transparent surfaces when fog is applied in a post pass after they were drawn - Fog colour banding in 8-bit targets at low density ## Engine support - godot: builtin — `Environment.fog_enabled = true; Environment.fog_height / fog_height_density` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - threejs: builtin — `import { exponentialHeightFogFactor } from 'three/tsl'; scene.fogNode = ...` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/fog/Fog.js, checked 2026-12-01) — TSL / WebGPURenderer node. - unity: builtin — `Volume > Add Override > Fog > Enable; Fog Attenuation Distance / Base Height / Maximum Height` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/fog-volume-override-reference.md, checked 2026-12-01) — HDRP only; height-based exponential fog. - unreal: builtin — `Place Actors > Visual Effects > Exponential Height Fog` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/exponential-height-fog-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, material-params - Outputs: radiance, ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unreal, unity, godot ## Presets ### Analytic exponential height fog: no fog (left) vs fog (right) (glsl-fragment; rendered 2026-11-29) ```json { "FOG_DENSITY": 0.06, "FOG_FALLOFF": 0.35 } ``` ```glsl // Exponential height fog: density(y) = D0 * exp(-FALLOFF * y), integrated analytically along each ray. // Left half: no fog. Right half: fog. const float FOG_DENSITY = 0.06; const float FOG_FALLOFF = 0.35; vec3 sky(vec3 rd, vec3 sd) { vec3 c = mix(vec3(0.75, 0.82, 0.9), vec3(0.2, 0.4, 0.8), pow(clamp(rd.y, 0.0, 1.0), 0.5)); return c + vec3(1.0, 0.8, 0.5) * pow(max(dot(rd, sd), 0.0), 64.0) * 2.0; } bool sph(vec3 ro, vec3 rd, vec3 c, float r, out float t) { vec3 oc = ro - c; float b = dot(oc, rd); float h = b * b - dot(oc, oc) + r * r; if (h < 0.0) return false; t = -b - sqrt(h); return t > 0.0; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 sd = normalize(vec3(-0.5, 0.12, -0.8)); vec3 ro = vec3(0.0, 1.3, 2.0); vec3 rd = normalize(vec3(uv.x, uv.y - 0.08, -1.1)); float t = 1e4; vec3 col = sky(rd, sd); if (rd.y < -1e-3) { t = -ro.y / rd.y; vec3 p = ro + rd * t; float chk = mod(floor(p.x * 0.5) + floor(p.z * 0.5), 2.0); col = mix(vec3(0.22, 0.3, 0.18), vec3(0.5, 0.55, 0.4), chk); } for (int i = 0; i < 5; i++) { float k = float(i); vec3 c = vec3(sin(k * 2.3) * 3.5, 1.0, -6.0 - k * 7.0); float ts; if (sph(ro, rd, c, 1.0, ts) && ts < t) { t = ts; vec3 n = normalize(ro + rd * ts - c); col = vec3(0.8, 0.35, 0.25) * (0.25 + 0.8 * max(dot(n, sd + vec3(0.0, 0.5, 0.0)), 0.0)); } } if (fragCoord.x > 0.5 * iResolution.x) { float tf = min(t, 300.0); float k = FOG_FALLOFF * rd.y; float integ = abs(k) < 1e-4 ? tf : (1.0 - exp(-k * tf)) / k; float tau = FOG_DENSITY * exp(-FOG_FALLOFF * ro.y) * integ; vec3 fc = mix(vec3(0.6, 0.7, 0.8), vec3(1.0, 0.8, 0.55), pow(max(dot(rd, sd), 0.0), 6.0)); col = mix(fc, col, exp(-tau)); } if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Hosek-Wilkie Sky Model](https://texelatlas.vercel.app/t/hosek-wilkie-sky.md): Horizon sky colour is sampled as the fog colour to hide the far plane. ## Sources 1. [primary] Inigo Quilez Better fog. iquilezles.org. https://iquilezles.org/articles/fog (verified via http on 2026-11-29) 2. [tutorial] Epic Games Exponential Height Fog in Unreal Engine. dev.epicgames.com. https://dev.epicgames.com/documentation/en-us/unreal-engine/exponential-height-fog-in-unreal-engine (verified via http on 2026-11-29) ## Cite this entry Texel. "Exponential Height Fog." https://texelatlas.vercel.app/t/exponential-height-fog/ (accessed 2026-12-01). --- id: "exponential-variance-shadow-maps" title: "Exponential Variance Shadow Maps" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2008 inputs: [depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "2016" url: "https://texelatlas.vercel.app/t/exponential-variance-shadow-maps/" sources_verified_at: "2026-11-29" --- # Exponential Variance Shadow Maps (2016) > Warps depth through exponentials before storing moments, which drastically reduces the light bleeding of plain variance shadow maps while keeping the map filterable. ## Reach for it when - variance shadow maps show light bleeding - need prefilterable soft shadows with fewer artifacts - blurred shadow maps leak light behind overlapping occluders - want shadows that can be mipmapped and blurred on gpu ## How it works EVSM applies the monotonic warps exp(c*z) and -exp(-c*z) to depth, then stores the first two moments of each warped value (four channels). Filtering happens in warped space, and at shade time Chebyshev's bound is evaluated on both the positive and negative warp, taking the minimum. The exponential stretches small depth differences so that occluders only slightly in front of a receiver are separated cleanly, which is what plain VSM cannot do. The constant c trades bleeding against precision: large values need 32-bit float storage to avoid overflow and quantisation, and a pure exponential variant (ESM) drops the variance and keeps one channel. ## When to use it Choose it when you want blurrable soft shadows and plain VSM leaks too much, and your target supports float32 render targets. Prefer [Moment Shadow Maps](https://texelatlas.vercel.app/t/moment-shadow-maps.md) when you want a more principled bound with a cleaner artifact profile, [Variance Shadow Maps](https://texelatlas.vercel.app/t/variance-shadow-maps.md) when memory is tight, and [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) when robustness beats softness. ## Cost cheap — Four 32-bit channels per texel; roughly 4x the bandwidth of a depth map before filtering. Measured GPU Weight: 9.8× baseline (moderate) — 0.3225 ms median / 0.3328 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.13× baseline (moderate) — 0.1611 ms median (2× faster on L4). Ampere A100 scaling: 6.5× baseline (moderate) — 0.1873 ms median (1.72× faster on A100). ## Failure modes - Float precision or overflow at large exponent constants - Residual bleeding with complex overlapping occluders - Memory-heavy for many cascades or lights - Banding or darkening if the exponent is tuned too aggressively ## Engine support - unity: builtin — `HDRP Asset > Lighting > Shadows > Area Shadow Filtering Quality = Medium (EVSM)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md, checked 2026-12-01) — HDRP only, used for area light shadows. ## Dataflow - Inputs: depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Visibility behind two overlapping occluders (depth profile on top). White exact, orange VSM (light bleeds in the middle), cyan EVSM (glsl-fragment; rendered 2026-11-29) ```json { "W": 0.09, "EC": 20, "TR": 1 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float W=0.09; // P const float EC=20.0; // P const float TR=1.0; // P float mapD(float x){float d=1.;if(x>.12&&x<.45)d=min(d,.08);if(x>.4&&x<.78)d=min(d,.6);return d;} float cheb(float mu,float m2,float t,float mv){float v=max(m2-mu*mu,mv);return t<=mu?1.:v/(v+(t-mu)*(t-mu));} float exact(float x){return mapD(x).55){float d=mapD(x),yy=(u.y-.55)/.45; if(yy>1.-d*1.0+0.0&&d<.99)col=vec3(.25,.3,.4); if(d>.99&&yy>.97)col=vec3(.2,.2,.25);} float ph=.07+.36*(u.y)/.55*0.; float yb=u.y/.5; if(u.y<.5){ float lo=.06,sc=.38; float y0=lo+sc*exact(x),y1=lo+sc*vsm(x),y2=lo+sc*evsm(x); float yy=u.y; col=mix(col,vec3(.9,.9,.9),smoothstep(.006,.002,abs(yy-y0))); col=mix(col,vec3(1.,.55,.2),smoothstep(.007,.003,abs(yy-y1))); col=mix(col,vec3(.3,.85,1.),smoothstep(.007,.003,abs(yy-y2))); if(abs(yy-lo)<.001||abs(yy-lo-sc)<.001)col=mix(col,vec3(.35),.6); } fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Lineage - extends [Variance Shadow Maps](https://texelatlas.vercel.app/t/variance-shadow-maps.md) ## Sources 1. [primary] (2016) Variance Shadow Maps Light-Bleeding Reduction Tricks. GPU Pro 2. https://doi.org/10.1201/b11325-21 (verified via crossref on 2026-11-29) 2. [tutorial] Andrew Lauritzen Summed-Area Variance Shadow Maps. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-8-summed-area-variance-shadow-maps (verified via http on 2026-11-29) ## Cite this entry Texel. "Exponential Variance Shadow Maps." https://texelatlas.vercel.app/t/exponential-variance-shadow-maps/ (accessed 2026-12-01). --- id: "fabrik-ik" title: "FABRIK inverse kinematics" aliases: [Forward And Backward Reaching Inverse Kinematics] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, webgl2, webgpu, unity, unreal, godot] year_introduced: 2011 inputs: [skeleton] outputs: [skeleton, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Aristidou & Lasenby, 2011" url: "https://texelatlas.vercel.app/t/fabrik-ik/" sources_verified_at: "2026-11-29" --- # FABRIK inverse kinematics (Aristidou & Lasenby, 2011) > Heuristic IK solver that moves joints along lines (backward from the target, forward from the root) instead of rotating angles, converging fast with natural motion. ## Reach for it when - feet or hands need to reach a target naturally - tentacles and tails should follow a moving point - jacobian ik is unstable or too complex to implement - procedural spider legs must plant on terrain ## How it works Treat the chain as points. The backward pass places the end effector on the target and, moving toward the root, positions each joint on the line from the next joint at its original bone-length distance. The forward pass then fixes the root back at its base and repeats outward. Iterating the two passes converges in a few iterations. If the target is unreachable the chain simply stretches in a line towards it. Joint limits are applied by clamping or re-projecting directions after each placement. Branched chains (fingers, spines with arms) are handled by solving sub-chains and averaging at the junction. ## When to use it Choose it for foot placement, hands reaching, tentacles, tails and procedural spiders where robustness and simplicity beat exact joint control. Prefer analytic two-bone IK for arms and legs when you need exact elbow/knee control, Jacobian-based IK for tight constraints, and [Motion matching](https://texelatlas.vercel.app/t/motion-matching.md) or authored animation when the pose quality matters more than reaching accuracy. ## Cost cheap — Cheap: a few passes over a handful of joints. Measured GPU Weight: 11.02× baseline (moderate) — 0.3625 ms median / 0.3691 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.73× baseline (moderate) — 0.1388 ms median (2.61× faster on L4). Ampere A100 scaling: 7.58× baseline (moderate) — 0.2183 ms median (1.66× faster on A100). ## Failure modes - Joint-limit handling is approximate and can oscillate - No natural twist control: needs a pole/up vector added separately - Ambiguous solutions flip between frames without a bias towards the previous pose - Multi-chain solutions with end effectors in conflict converge unpredictably ## Engine support - godot: builtin — `Add FABRIK3D (IKModifier3D) under a Skeleton3D` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/FABRIK3D.xml, checked 2026-12-01) — Legacy SkeletonIK3D also solves with FABRIK. - unity: official — `Package Manager > Animation Rigging > Chain IK Constraint` (evidence: https://docs.unity3d.com/Packages/com.unity.animation.rigging@1.3/manual/constraints/ChainIKConstraint.html, checked 2026-12-01) — Official Animation Rigging package. - unreal: builtin — `Animation Blueprint > FABRIK node or Control Rig > Multi FABRIK (RigUnit_MultiFABRIK)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/RigUnit_MultiFABRIK, checked 2026-12-01) ## Dataflow - Inputs: skeleton - Outputs: skeleton, animation - Platforms: cpu, webgl2, webgpu, unity, unreal, godot ## Presets ### FABRIK on a 5-joint chain: pose after 1 vs 6 backward/forward sweeps (glsl-fragment; rendered 2026-11-29) ```json { "J": 5, "ITER": 6, "SEG": 0.2 } ``` ```glsl // FABRIK on a 5-joint chain: orange = pose after 1 iteration, white = after 6; target moves with time. const int J = 5; const int ITER = 6; const float SEG = 0.2; float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); } void solve(inout vec2 p[J], vec2 base, vec2 tgt, int iters) { for (int it = 0; it < ITER; it++) { if (it >= iters) break; p[J - 1] = tgt; for (int i = J - 2; i >= 0; i--) p[i] = p[i + 1] + normalize(p[i] - p[i + 1]) * SEG; p[0] = base; for (int i = 1; i < J; i++) p[i] = p[i - 1] + normalize(p[i] - p[i - 1]) * SEG; } } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 base = vec2(0.5, 0.12); vec2 tgt = vec2(0.5 + 0.34 * cos(iTime * 1.3), 0.45 + 0.25 * sin(iTime * 1.3 + 0.5)); vec2 a[J], b[J]; for (int i = 0; i < J; i++) { a[i] = base + vec2(0.04 * float(i), SEG * float(i)); b[i] = a[i]; } solve(a, base, tgt, 1); solve(b, base, tgt, ITER); vec3 col = mix(vec3(0.05, 0.06, 0.09), vec3(0.1, 0.12, 0.17), uv.y); float reach = SEG * float(J - 1); col = mix(col, vec3(0.2, 0.25, 0.35), smoothstep(0.004, 0.0, abs(length(uv - base) - reach)) * 0.6); float da = 1e9, db = 1e9, jd = 1e9; for (int i = 0; i < J - 1; i++) { da = min(da, segd(uv, a[i], a[i + 1])); db = min(db, segd(uv, b[i], b[i + 1])); } for (int i = 0; i < J; i++) jd = min(jd, length(uv - b[i])); col = mix(col, vec3(1.0, 0.55, 0.2), smoothstep(0.008, 0.005, da) * 0.8); col = mix(col, vec3(0.95), smoothstep(0.012, 0.009, db)); col = mix(col, vec3(0.2, 0.5, 1.0), smoothstep(0.02, 0.016, jd)); float tg = length(uv - tgt); col = mix(col, vec3(0.3, 1.0, 0.4), smoothstep(0.004, 0.0, abs(tg - 0.025)) + smoothstep(0.01, 0.007, tg)); col = mix(col, vec3(1.0, 0.9, 0.3), smoothstep(0.022, 0.018, length(uv - base))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Andreas Aristidou, Joan Lasenby (2011) FABRIK: A fast, iterative solver for the Inverse Kinematics problem. Graphical Models. https://doi.org/10.1016/j.gmod.2011.05.003 (verified via crossref on 2026-11-29) 2. [tutorial] Andreas Aristidou FABRIK - Forward And Backward Reaching Inverse Kinematics. andreasaristidou.com. https://www.andreasaristidou.com/FABRIK.html (verified via http on 2026-11-29) ## Cite this entry Texel. "FABRIK inverse kinematics." https://texelatlas.vercel.app/t/fabrik-ik/ (accessed 2026-12-01). --- id: "fft-ocean" title: "FFT Ocean (Tessendorf)" aliases: [Tessendorf ocean, statistical ocean waves, inverse FFT ocean] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, unity, unreal, houdini, blender] year_introduced: 2001 inputs: [material-params] outputs: [heightfield, normals, texture] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Tessendorf" url: "https://texelatlas.vercel.app/t/fft-ocean/" sources_verified_at: "2026-11-29" --- # FFT Ocean (Tessendorf) (Tessendorf) > Synthesise a tileable, animated ocean surface by evolving a random wave spectrum in the frequency domain and taking an inverse FFT each frame for height, choppy displacement and slopes. ## Reach for it when - ocean should look like real wind-driven waves - need tileable animated sea surface for open water - waves need choppy crests and realistic spectrum - water repeats too obviously with a few sine waves - control wave look by wind speed and direction ## How it works Draw a random complex amplitude for every wave vector k on an N by N grid, scaled by the square root of a directional wave spectrum (Phillips, or JONSWAP with a spreading function). Each frame, advance the phase of each amplitude by the deep-water dispersion relation, omega = sqrt(g |k|), keeping the conjugate-symmetric partner so the result is real. Inverse FFTs then produce the height field, the horizontal displacement (multiplying by i k / |k| for choppiness), and the x and z slopes (multiplying by i k). The displaced grid is rendered as a heightfield mesh or vertex-texture-fetch plane, with the slopes giving normals, and a Jacobian of the displacement indicating where waves fold and foam appears. Multiple cascades with different tile sizes are blended to avoid visible tiling at near and far distances. ## When to use it Choose it for open-sea scenes with realistic wind-driven wave statistics, where the surface must tile, animate indefinitely and respond to wind speed and direction in real time. Prefer [Gerstner (Trochoidal) Waves](https://texelatlas.vercel.app/t/gerstner-waves.md) when you need a few controllable, analytic waves for stylised water or cheap mobile hardware, and when gameplay needs the exact surface height in a gameplay script. Prefer [Shallow Water Equations (Height-field Water)](https://texelatlas.vercel.app/t/shallow-water-equations.md) for interactive ripples and wakes near shores. Use [JONSWAP Wave Spectrum](https://texelatlas.vercel.app/t/jonswap-spectrum.md) as the input spectrum for fully developed seas. ## Cost medium — Several N by N inverse FFTs per frame per cascade (N = 256 to 512 is common); cost is dominated by FFT compute passes. Measured GPU Weight: 35.28× baseline (heavy) — 1.1608 ms median / 1.215 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.32× baseline (heavy) — 0.4344 ms median (2.67× faster on L4). Ampere A100 scaling: 21.51× baseline (heavy) — 0.6194 ms median (1.87× faster on A100). ## Failure modes - Visible repetition of the tile at distance when only one cascade is used - Aliasing or shimmering of high-frequency normals at distance without normal mip filtering or roughness adjustment - Choppy displacement self-intersections (loops) if the choppiness scale is too large - Waves cannot interact with boats, shores or obstacles because the model is purely statistical - Aliasing in the spectrum when the grid size and tile length make high k exceed Nyquist for the chosen wavelengths ## Engine support - blender: builtin — `Add Modifier > Physics > Ocean` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/physics/ocean.html, checked 2026-12-01) — Port of the Houdini Ocean Toolkit (spectral FFT ocean). - unity: builtin — `GameObject > Water > Ocean, Sea or Lake (HDRP Water System)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/FourierTransform.compute, checked 2026-12-01) — HDRP only; FFT-based spectrum simulation (Phillips). - unreal: official — `Water plugin (WaterBodyOcean wave spectrum & Gerstner/FFT ocean system)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/water-system-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params - Outputs: heightfield, normals, texture - Platforms: webgl2, webgpu, desktop-gpu, cuda, unity, unreal, houdini, blender ## Presets ### Tessendorf spectral ocean — Phillips dispersion wave sum with choppy crests and foam (glsl-fragment; rendered 2026-11-30) ```json { "WIND_SPEED": 1.35, "CHOPPINESS": 1.15, "FOAM_BIAS": 0.58, "WATER_CLARITY": 0.65 } ``` ```glsl const float WIND_SPEED = 1.35; // P const float CHOPPINESS = 1.15; // P const float FOAM_BIAS = 0.58; // P const float WATER_CLARITY = 0.65; // P // Multi-band Phillips-spectrum directional wave synthesis with deep-water dispersion vec3 evalWave(vec2 p, float t, float wind, float chop, out float jacobian) { vec2 windDir = normalize(vec2(0.82, 0.57)); float L = max(wind * wind * 0.45, 0.08); float h = 0.0; vec2 slope = vec2(0.0); float fold = 0.0; float freq = 0.42; for (int i = 0; i < 14; i++) { float fi = float(i); float ang = fi * 2.39996 + 0.35 * sin(fi * 1.7); vec2 kDir = vec2(cos(ang), sin(ang)); float align = abs(dot(kDir, windDir)); float k = freq; float kL = max(k * L, 0.25); float phillips = exp(-1.0 / (kL * kL)) / (k * k * k) * (0.28 + 0.72 * align * align); float amp = sqrt(phillips) * 0.14 * max(wind, 0.2); float omega = sqrt(9.81 * k); float ph = dot(kDir * k, p) - omega * t + fi * 1.91; float s = sin(ph), c = cos(ph); h += amp * s; slope += kDir * (amp * k * c); fold += chop * amp * k * s; freq *= 1.24; } jacobian = 1.0 - fold; return vec3(slope.x, h, slope.y); } vec3 skyColor(vec3 d, vec3 sunDir) { float y = max(d.y, 0.0); vec3 zenith = vec3(0.11, 0.26, 0.52); vec3 horiz = vec3(0.82, 0.64, 0.48); vec3 col = mix(horiz, zenith, pow(y, 0.52)); float sun = max(dot(d, sunDir), 0.0); col += vec3(1.0, 0.72, 0.42) * pow(sun, 12.0) * 0.65; col += vec3(1.0, 0.92, 0.78) * pow(sun, 220.0) * 4.5; return col; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float yaw = 0.0; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) yaw = (iMouse.x / iResolution.x - 0.5) * 1.4; vec3 ro = vec3(0.0, 2.35, 0.0); vec3 rd = normalize(vec3(uv.x, uv.y - 0.16, -1.25)); float cy = cos(yaw), sy = sin(yaw); rd.xz = mat2(cy, -sy, sy, cy) * rd.xz; vec3 sunDir = normalize(vec3(0.38, 0.24, -0.89)); float wind = max(WIND_SPEED, 0.15); float chop = max(CHOPPINESS, 0.0); if (rd.y > 0.02) { vec3 col = skyColor(rd, sunDir); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); return; } float t = 0.6, tMax = 65.0; float prevD = 1.0, prevT = t; bool hit = false; float jac = 1.0; vec3 wv = vec3(0.0); for (int i = 0; i < 48; i++) { vec3 p = ro + rd * t; wv = evalWave(p.xz, iTime, wind, chop, jac); float d = p.y - wv.y; if (d < 0.0) { float a = prevT, b = t; for (int k = 0; k < 4; k++) { float m = 0.5 * (a + b); vec3 pm = ro + rd * m; wv = evalWave(pm.xz, iTime, wind, chop, jac); if (pm.y - wv.y < 0.0) b = m; else a = m; } t = 0.5 * (a + b); hit = true; break; } prevD = d; prevT = t; t += max(0.18, d * 0.55 + t * 0.045); if (t > tMax) break; } vec3 col = skyColor(rd, sunDir); if (hit) { vec3 p = ro + rd * t; wv = evalWave(p.xz, iTime, wind, chop, jac); vec3 n = normalize(vec3(-wv.x, 1.0, -wv.z)); float ndv = max(dot(n, -rd), 0.001); float fres = 0.02 + 0.98 * pow(1.0 - ndv, 5.0); vec3 refl = reflect(rd, n); refl.y = max(refl.y, 0.01); vec3 env = skyColor(normalize(refl), sunDir); // Subsurface scatter through sunlit wave crests float sss = pow(max(dot(rd, sunDir), 0.0), 3.0) * smoothstep(-0.2, 0.65, wv.y) * max(WATER_CLARITY, 0.0); vec3 deepCol = vec3(0.012, 0.065, 0.11); vec3 scatterCol = vec3(0.04, 0.38, 0.36) * (0.28 + 1.35 * sss); vec3 water = mix(deepCol + scatterCol, env, fres); // Crisp sun specular sparkle vec3 h = normalize(sunDir - rd); float spec = pow(max(dot(n, h), 0.0), 180.0) * 3.8; water += vec3(1.0, 0.88, 0.68) * spec; // Jacobian crest folding -> whitecap foam float foamMask = smoothstep(FOAM_BIAS, FOAM_BIAS - 0.38, jac) * smoothstep(-0.05, 0.38, wv.y); float fTex = 0.5 + 0.5 * sin(p.x * 9.0 + sin(p.z * 7.0)) * cos(p.z * 8.0 - p.x * 5.0); float foam = clamp(foamMask * (0.55 + 0.65 * fTex), 0.0, 1.0); water = mix(water, vec3(0.88, 0.92, 0.95) * (0.55 + 0.45 * max(dot(n, sunDir), 0.0)), foam * 0.88); float fog = 1.0 - exp(-0.018 * t); col = mix(water, skyColor(normalize(vec3(rd.x, 0.015, rd.z)), sunDir), fog); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [JONSWAP Wave Spectrum](https://texelatlas.vercel.app/t/jonswap-spectrum.md) ## Combines with - [JONSWAP Wave Spectrum](https://texelatlas.vercel.app/t/jonswap-spectrum.md): Provides the directional amplitude spectrum that scales the random amplitudes before the FFT. - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Slope and height maps from the FFT drive the refraction that creates caustic patterns on the seabed. ## Combination ideas - [Bathymetry-refracted coastal ocean with shore caustics](https://texelatlas.vercel.app/ideas/eikonal-refracted-fft-shore-caustics/) - [Sun glitter from horizon to bow](https://texelatlas.vercel.app/ideas/sun-glitter-ocean/) ## Sources 1. [primary] Jerry Tessendorf Simulating Ocean Water. SIGGRAPH Course Notes 2001/2004. https://jtessen.people.clemson.edu/reports/papers_files/coursenotes2004.pdf (verified via http on 2026-11-29) 2. [primary] Christopher J. Horvath (2015) Empirical directional wave spectra for computer graphics. Proceedings of the 2015 Symposium on Digital Production. https://doi.org/10.1145/2791261.2791267 (verified via crossref on 2026-11-29) 3. [implementation] gasgiant (2020) gasgiant/FFT-Ocean. https://github.com/gasgiant/FFT-Ocean License: MIT. (verified via github on 2026-11-29) 4. [implementation] jbouny (2013) jbouny/ocean. https://github.com/jbouny/ocean License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "FFT Ocean (Tessendorf)." https://texelatlas.vercel.app/t/fft-ocean/ (accessed 2026-12-01). --- id: "fidelityfx-super-resolution" title: "AMD FidelityFX Super Resolution" aliases: [FSR] domain: "post" stage: "post" realtime: "realtime" platforms: [desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2021 inputs: [ldr-image, depth, gbuffer] outputs: [ldr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "GPUOpen-Effects, 2021" url: "https://texelatlas.vercel.app/t/fidelityfx-super-resolution/" sources_verified_at: "2026-11-29" --- # AMD FidelityFX Super Resolution (GPUOpen-Effects, 2021) > AMD's open upscaler family. FSR 1 is a spatial edge-adaptive upscale plus sharpen; FSR 2 and later reconstruct from jittered, motion-vector-reprojected frames like TAA and run on any GPU. ## Reach for it when - need to upscale on any gpu vendor - raise frame rate by rendering at lower resolution - upscaler that works without motion vectors or ai hardware - game too slow on integrated or older graphics cards ## How it works FSR 1 (EASU then RCAS) is purely spatial: EASU looks at a 12-tap neighbourhood, estimates edge direction and length from gradient analysis, and applies a direction-stretched Lanczos-like kernel; RCAS then sharpens with a contrast-adaptive filter. It operates on tonemapped LDR input. FSR 2 and 3 are temporal. The renderer supplies low-resolution colour, depth, motion vectors, exposure and jitter offsets. The pass reprojects accumulated high-resolution history, validates it against depth and luminance, reconstructs thin features, locks sub-pixel detail and writes an output at display resolution. Later versions add frame generation. All variants are shaders with no vendor-specific hardware requirement. ## When to use it Choose it when you need a vendor-neutral upscaler that runs on consoles, integrated GPUs and mobile, or when you cannot ship an ML runtime. Prefer [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) on RTX hardware when you can accept the proprietary SDK for higher reconstruction quality. Prefer [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) at native resolution when no upscaling is needed. ## Cost cheap — FSR 1 is a pair of cheap passes; the temporal versions cost more but are designed to be a net saving versus native rendering. Qualitative. Measured GPU Weight: 146.9× baseline (extreme) — 4.8329 ms median / 4.8863 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 294.22× baseline (extreme) — 4.6781 ms median (1.03× faster on L4). Ampere A100 scaling: 120.46× baseline (extreme) — 3.4693 ms median (1.39× faster on A100). ## Failure modes - FSR 1 cannot recover detail absent in the input and amplifies aliasing present in it - Temporal versions ghost on objects lacking motion vectors - Thin wires and particles shimmer or disappear at low scale factors - Wrong jitter, mip bias or exposure inputs cause visible shimmer or brightness pumping ## Engine support - babylonjs: builtin — `new BABYLON.FSR1RenderingPipeline('fsr', scene, camera)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/fsr1RenderingPipeline.ts, checked 2026-12-01) — FSR 1 spatial upscaler only. - godot: builtin — `Viewport.scaling_3d_mode = Viewport.SCALING_3D_MODE_FSR2 (or SCALING_3D_MODE_FSR for FSR 1)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Viewport.xml, checked 2026-12-01) — FSR 1 in 4.0, FSR 2.2 in 4.2; Forward+ and Mobile. - threejs: official — `import { fsr1 } from 'three/addons/tsl/display/FSR1Node.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/FSR1Node.js, checked 2026-12-01) — FSR 1 spatial upscaler. - unity: builtin — `URP Asset > Quality > Upscaling Filter = FidelityFX Super Resolution 1.0; HDRP: Dynamic Resolution > Upscale Filter` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs, checked 2026-12-01) — FSR 1.0 in URP and HDRP; HDRP also exposes FSR2 options through its upscaler API. - unreal: plugin — `AMD FSR plugin (third-party); plugs into the temporal upscaler interface` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/temporal-upscalers-in-unreal-engine, checked 2026-12-01) — Docs list FSR 2.0+ as a third-party distributed plugin. ## Dataflow - Inputs: ldr-image, depth, gbuffer - Outputs: ldr-image - Platforms: desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### AMD FidelityFX Super Resolution (FSR) — blurry bilinear upscale (left) vs EASU directional Lanczos + RCAS sharpening (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_UPSCALE": 2.6, "P_RCAS": 0.8, "P_EDGE_ANISO": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_UPSCALE = 2.60; // P Upscale Factor [1.4, 4.5, 0.1] const float P_RCAS = 0.80; // P RCAS Sharpen [0.0, 1.5, 0.05] const float P_EDGE_ANISO = 0.85; // P EASU Anisotropy [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P Bilinear / FSR [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // High-contrast crisp synthetic render target (diagonal fins, glossy badge, radial spokes) vec3 renderSource(vec2 uv, float t) { vec2 p = rot2(uv, 0.14 * sin(t * 0.55)); vec3 bg = mix(vec3(0.07, 0.09, 0.14), vec3(0.16, 0.22, 0.32), smoothstep(-0.5, 0.5, uv.y)); // Sharp diagonal geometric chevrons & architectural bands float diag = sin((p.x * 18.0 + p.y * 12.0) + 0.4 * sin(t * 0.7)); float chevron = smoothstep(-0.08, 0.08, diag); vec3 col = mix(bg, vec3(0.18, 0.34, 0.46), chevron * 0.55); // Perspective high-contrast floor tiles if (uv.y < -0.14) { float z = 0.35 / max(-uv.y - 0.10, 0.02); float x = uv.x * z; float chk = mod(floor(x * 2.2) + floor(z * 2.2 - t * 0.8), 2.0); vec3 tile = mix(vec3(0.10, 0.11, 0.14), vec3(0.82, 0.84, 0.88), chk); float rim = step(0.88, fract(x * 2.2)) + step(0.88, fract(z * 2.2 - t * 0.8)); tile = mix(tile, vec3(0.95, 0.36, 0.18), clamp(rim, 0.0, 1.0) * 0.55); col = mix(bg, tile, exp(-z * 0.14)); } // Crisp central emblem sphere with high-contrast radial ring & diagonal blade vec2 sp = uv - vec2(0.0, 0.06); float r = length(sp); if (r < 0.34) { float nz = sqrt(max(0.34 * 0.34 - r * r, 0.0)); vec3 n = normalize(vec3(sp, nz)); vec3 l = normalize(vec3(0.6 * cos(t * 0.4), 0.7, 0.65)); float ang = atan(sp.y, sp.x) + t * 0.35; float spoke = smoothstep(0.02, 0.12, cos(ang * 8.0)); float ring = smoothstep(0.015, 0.0, abs(r - 0.24) - 0.012); vec3 alb = mix(vec3(0.88, 0.22, 0.14), vec3(0.96, 0.82, 0.34), spoke); alb = mix(alb, vec3(0.98, 0.98, 1.0), ring); float ndl = max(dot(n, l), 0.0); float spec = pow(max(dot(reflect(-l, n), vec3(0.0, 0.0, 1.0)), 0.0), 36.0); col = alb * (0.20 + 0.92 * ndl) + vec3(1.1) * spec; } // Crisp diagonal frame bars on upper corners float bar1 = smoothstep(0.008, 0.001, abs(abs(uv.x) - 0.56 + uv.y * 0.38) - 0.016); col = mix(col, vec3(0.96, 0.97, 1.0), bar1 * 0.9); return col; } // Low-resolution quantized texel fetch (simulating low-res input texture to FSR) vec3 fetchLow(vec2 lowTexel, float cell, float t) { vec2 fc = (lowTexel + 0.5) * cell; vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; return renderSource(uv, t); } float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } // FSR-style Lanczos-2 polynomial approximation weight float lanczos2(float d2, float lobe) { float x = clamp(d2, 0.0, 4.0); float w1 = (0.4 * x - 1.0); float w2 = (0.25 * x - 1.0); return (w1 * w1 - 0.16) * (w2 * w2) * mix(1.0, 1.15, lobe); } vec3 evalEASU(vec2 fragCoord, float cell, float aniso, float t) { vec2 pos = fragCoord / cell - 0.5; vec2 base = floor(pos); vec2 f = pos - base; // Fetch 4 central + cross neighbors for gradient direction & edge length estimation vec3 c00 = fetchLow(base + vec2(0.0, 0.0), cell, t); vec3 c10 = fetchLow(base + vec2(1.0, 0.0), cell, t); vec3 c01 = fetchLow(base + vec2(0.0, 1.0), cell, t); vec3 c11 = fetchLow(base + vec2(1.0, 1.0), cell, t); vec3 cm0 = fetchLow(base + vec2(-1.0, 0.0), cell, t); vec3 c20 = fetchLow(base + vec2(2.0, 0.0), cell, t); vec3 c0m = fetchLow(base + vec2(0.0, -1.0), cell, t); vec3 c02 = fetchLow(base + vec2(0.0, 2.0), cell, t); vec3 c1m = fetchLow(base + vec2(1.0, -1.0), cell, t); vec3 c12 = fetchLow(base + vec2(1.0, 2.0), cell, t); vec3 cm1 = fetchLow(base + vec2(-1.0, 1.0), cell, t); vec3 c21 = fetchLow(base + vec2(2.0, 1.0), cell, t); // Estimate dominant local edge direction from luminance gradients float l00 = luma(c00), l10 = luma(c10), l01 = luma(c01), l11 = luma(c11); vec2 grad = vec2((l10 - l00) + (l11 - l01), (l01 - l00) + (l11 - l10)); float gLen = length(grad); vec2 dir = (gLen > 1e-4) ? (grad / gLen) : vec2(1.0, 0.0); vec2 tangent = vec2(-dir.y, dir.x); float stretch = 1.0 + aniso * smoothstep(0.04, 0.35, gLen) * 1.35; // 12-tap EASU elliptical Lanczos accumulation vec3 acc = vec3(0.0); float wSum = 0.0; vec2 offs[12]; vec3 cols[12]; offs[0] = vec2(0.0, 0.0); cols[0] = c00; offs[1] = vec2(1.0, 0.0); cols[1] = c10; offs[2] = vec2(0.0, 1.0); cols[2] = c01; offs[3] = vec2(1.0, 1.0); cols[3] = c11; offs[4] = vec2(-1.0, 0.0); cols[4] = cm0; offs[5] = vec2(2.0, 0.0); cols[5] = c20; offs[6] = vec2(0.0, -1.0); cols[6] = c0m; offs[7] = vec2(0.0, 2.0); cols[7] = c02; offs[8] = vec2(1.0, -1.0); cols[8] = c1m; offs[9] = vec2(1.0, 2.0); cols[9] = c12; offs[10] = vec2(-1.0, 1.0); cols[10] = cm1; offs[11] = vec2(2.0, 1.0); cols[11] = c21; for (int i = 0; i < 12; i++) { vec2 d = offs[i] - f; float along = dot(d, tangent) / stretch; float across = dot(d, dir) * mix(1.0, 1.35, aniso * smoothstep(0.04, 0.35, gLen)); float d2 = along * along + across * across; float w = lanczos2(d2, aniso); acc += cols[i] * w; wSum += w; } vec3 res = acc / max(wSum, 1e-4); // Anti-ringing clamp to inner 2x2 neighborhood min/max vec3 lo = min(min(c00, c10), min(c01, c11)); vec3 hi = max(max(c00, c10), max(c01, c11)); return clamp(res, lo, hi); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float cell = clamp(P_UPSCALE, 1.2, 5.0) * max(iResolution.y / 360.0, 1.0); float aniso = clamp(P_EDGE_ANISO, 0.0, 1.0); float rcas = clamp(P_RCAS, 0.0, 1.6); vec3 col = vec3(0.0); if (screenX < split) { // Left: Standard bilinear upscale from low-res buffer (soft edges, blurred diagonals) vec2 pos = fragCoord / cell - 0.5; vec2 base = floor(pos); vec2 f = pos - base; vec3 c00 = fetchLow(base + vec2(0.0, 0.0), cell, iTime); vec3 c10 = fetchLow(base + vec2(1.0, 0.0), cell, iTime); vec3 c01 = fetchLow(base + vec2(0.0, 1.0), cell, iTime); vec3 c11 = fetchLow(base + vec2(1.0, 1.0), cell, iTime); col = mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y); } else { // Right: EASU edge-adaptive directional upscale + RCAS contrast-adaptive sharpening vec3 eC = evalEASU(fragCoord, cell, aniso, iTime); vec3 eL = evalEASU(fragCoord + vec2(-1.0, 0.0), cell, aniso, iTime); vec3 eR = evalEASU(fragCoord + vec2(1.0, 0.0), cell, aniso, iTime); vec3 eD = evalEASU(fragCoord + vec2(0.0, -1.0), cell, aniso, iTime); vec3 eU = evalEASU(fragCoord + vec2(0.0, 1.0), cell, aniso, iTime); vec3 mn = min(eC, min(min(eL, eR), min(eD, eU))); vec3 mx = max(eC, max(max(eL, eR), max(eD, eU))); // RCAS robust adaptive negative lobe weight capped to prevent clipping halos vec3 hitMin = min(mn, 1.0 - mx); float amp = clamp(min(hitMin.r, min(hitMin.g, hitMin.b)) / max(max(mx.r, max(mx.g, mx.b)), 0.08), 0.0, 1.0); float w = -0.18 * rcas * sqrt(amp + 0.15); col = (eC + w * (eL + eR + eD + eU)) / max(1.0 + 4.0 * w, 0.25); col = clamp(col, mn * 0.94, mx * 1.06); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) ## Combines with - [Contrast Adaptive Sharpening](https://texelatlas.vercel.app/t/contrast-adaptive-sharpening.md): RCAS in FSR 1 is a derivative of CAS, applied after upscaling. ## Combination ideas - [Dithered impostor forests, temporally rebuilt](https://texelatlas.vercel.app/ideas/impostor-forest-temporal-upscale/) ## Sources 1. [primary] GPUOpen-Effects (2021) GPUOpen-Effects/FidelityFX-FSR. https://github.com/GPUOpen-Effects/FidelityFX-FSR License: MIT. (verified via github on 2026-11-29) 2. [implementation] GPUOpen-LibrariesAndSDKs (2023) GPUOpen-LibrariesAndSDKs/FidelityFX-SDK. https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK (verified via github on 2026-11-29) 3. [tutorial] AMD GPUOpen GPUOpen learning resources. gpuopen.com. https://gpuopen.com/learn (verified via http on 2026-11-29) ## Cite this entry Texel. "AMD FidelityFX Super Resolution." https://texelatlas.vercel.app/t/fidelityfx-super-resolution/ (accessed 2026-12-01). --- id: "film-emulation" title: "Film emulation (spectral stock simulation)" domain: "post" stage: "post" realtime: "offline" platforms: [python, cpu] year_introduced: 2025 inputs: [hdr-image, ldr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "offline" authority: "andreavolpato, 2025" url: "https://texelatlas.vercel.app/t/film-emulation/" sources_verified_at: "2026-11-29" --- # Film emulation (spectral stock simulation) (andreavolpato, 2025) > Simulates analog colour film end to end: exposure of a spectral stock model, dye density, optional enlarger and print stage, producing the cross-channel colour behaviour of a real emulsion rather than a LUT. ## Reach for it when - lut grading doesn't capture real film colour behaviour - want the look of a specific analog stock - highlights should respond like real emulsion dyes - digital render looks too clinical compared to film ## How it works Instead of a colour matrix, film emulation models the physical chain. Scene RGB is expanded to a spectrum, which exposes three light-sensitive layers with their own spectral sensitivities. Each layer's exposure goes through a characteristic density curve, and the resulting dye densities modulate transmitted light with spectral absorption overlap between dyes, which is what gives film its characteristic colour crosstalk. A print or scan stage then converts densities to display colour. Grain, halation and other effects can be layered on. spektrafilm implements this in Python from manufacturer spectral datasheet data; full-resolution export is slow, so treat it as an offline stills tool. ## When to use it Choose it when you want the colour behaviour and highlights of a specific stock, beyond what a 3D LUT captures, for stills or pre-rendered frames. Prefer [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md) for real-time. Add [Film grain synthesis](https://texelatlas.vercel.app/t/film-grain-synthesis.md) for texture. ## Cost offline — Python per-image processing; not a real-time pipeline. Measured GPU Weight: 34.4× baseline (heavy) — 1.1316 ms median / 1.8699 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 31.85× baseline (heavy) — 0.5064 ms median (2.23× faster on L4). Ampere A100 scaling: 24.32× baseline (heavy) — 0.7003 ms median (1.62× faster on A100). ## Failure modes - Depends on the quality of the measured stock data - Needs scene-referred linear input; display-referred sources give odd results - Slow for video - Results vary between releases of the tool while it is young ## Dataflow - Inputs: hdr-image, ldr-image - Outputs: ldr-image - Platforms: python, cpu ## Presets ### Left: raw digital sRGB clip. Right: spectral film emulsion with H&D curve, red halation and grain (glsl-fragment; rendered 2026-11-30) ```json { "EXPOSURE": 1.15, "HALATION": 0.68, "GRAIN": 0.32, "CONTRAST": 1.25 } ``` ```glsl const float EXPOSURE = 1.15; // P const float HALATION = 0.68; // P const float GRAIN = 0.32; // P const float CONTRAST = 1.25; // P float hash(vec2 p) { vec3 q = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); } // Scene-referred HDR dusk streetscape (bright tungsten lamps, cyan neon, wet street reflection) vec3 hdrScene(vec2 uv) { float pulse = 0.88 + 0.12 * sin(iTime * 1.4); // Twilight gradient sky vec3 col = mix(vec3(0.28, 0.14, 0.24), vec3(0.03, 0.07, 0.22), clamp((uv.y + 0.12) * 1.6, 0.0, 1.0)); // Architectural skyline silhouettes float bld1 = step(abs(uv.x + 0.34), 0.15) * step(uv.y, 0.26) * step(-0.12, uv.y); float bld2 = step(abs(uv.x - 0.30), 0.18) * step(uv.y, 0.34) * step(-0.12, uv.y); col = mix(col, vec3(0.025, 0.03, 0.05), max(bld1, bld2)); // Glowing HDR cyan neon bar on right building vec2 nBar = abs(uv - vec2(0.24, 0.16)) - vec2(0.095, 0.014); float dNeon = length(max(nBar, 0.0)); col += vec3(0.18, 2.2, 3.6) * exp(-dNeon * 38.0) * pulse; col += vec3(0.55, 4.5, 6.2) * smoothstep(0.012, 0.002, dNeon); // Overexposed tungsten streetlamps (prime halation triggers) vec2 l1 = vec2(-0.18, 0.18 + 0.02 * sin(iTime * 0.7)); vec2 l2 = vec2( 0.08, 0.05); vec2 l3 = vec2(-0.36, 0.08); float d1 = length(uv - l1), d2 = length(uv - l2), d3 = length(uv - l3); col += vec3(7.5, 4.8, 2.1) * smoothstep(0.042, 0.016, d1) + vec3(2.8, 1.5, 0.55) * exp(-d1 * 18.0); col += vec3(6.8, 4.2, 1.9) * smoothstep(0.028, 0.010, d2) + vec3(2.2, 1.1, 0.42) * exp(-d2 * 24.0); col += vec3(5.2, 3.1, 1.4) * smoothstep(0.022, 0.008, d3) + vec3(1.6, 0.85, 0.32) * exp(-d3 * 28.0); // Wet asphalt road below y = -0.12 with stretched vertical specular streaks if (uv.y < -0.12) { float dist = -0.12 - uv.y; vec2 rUv = vec2(uv.x + 0.006 * sin(uv.y * 95.0 + iTime * 2.0), -0.12 + dist * 0.92); float streak1 = exp(-abs(rUv.x - l1.x) * 14.0) * exp(-dist * 2.2); float streak2 = exp(-abs(rUv.x - l2.x) * 18.0) * exp(-dist * 2.8); float streakN = exp(-abs(rUv.x - 0.24) * 9.5) * exp(-dist * 2.4); col = vec3(0.018, 0.022, 0.032); col += vec3(3.2, 1.85, 0.75) * streak1 * 0.85; col += vec3(2.6, 1.45, 0.60) * streak2 * 0.72; col += vec3(0.22, 1.85, 2.95) * streakN * 0.65 * pulse; } return col * max(EXPOSURE, 0.05); } // Emulsion Hurter-Driffield S-curve + cross-channel dye-coupler print stage vec3 filmEmulsion(vec3 lin, vec2 uv, vec2 fragCoord) { // 1. Red-orange anti-halation backing scatter from nearby overexposed HDR highlights vec3 hal = vec3(0.0); float halStr = max(HALATION, 0.0); for (int i = 0; i < 12; i++) { float a = float(i) * 0.523599; vec2 dir = vec2(cos(a), sin(a)); vec3 s1 = hdrScene(uv + dir * 0.024); vec3 s2 = hdrScene(uv + dir * 0.052); hal += max(s1 - 1.15, 0.0) * 0.65 + max(s2 - 1.35, 0.0) * 0.35; } hal /= 12.0; lin += vec3(hal.r * 0.82 + hal.g * 0.28, hal.r * 0.18 + hal.g * 0.08, hal.b * 0.02) * halStr; // 2. Spectral-inspired cross-channel sensitivity matrix (warm tungsten skin/gold, cyan shadow tint) mat3 sens = mat3( 0.92, 0.09, 0.02, 0.04, 0.90, 0.06, 0.01, 0.08, 0.88 ); vec3 expRGB = max(sens * lin, vec3(1e-5)); // 3. Per-layer H&D density curve (toe + gamma + shoulder rolloff) vec3 logE = log2(expRGB) * max(CONTRAST, 0.25); vec3 density = 1.0 / (1.0 + exp(-(logE + vec3(0.42, 0.35, 0.22)))); // 4. Print-stock dye crosstalk (subtle cool-teal shadows, creamy warm highlights) vec3 printCol = vec3( pow(density.r, 0.94) * 1.04, pow(density.g, 1.00) * 1.00, pow(density.b, 1.06) * 0.96 ); printCol += vec3(0.012, 0.024, 0.032) * (1.0 - printCol); // 5. Luminance-dependent silver-halide grain float g = (hash(floor(fragCoord * 0.85) + floor(iTime * 24.0) * 17.3) - 0.5) * 2.0; float lum = dot(printCol, vec3(0.2126, 0.7152, 0.0722)); float grainEnv = smoothstep(0.0, 0.35, lum) * smoothstep(1.0, 0.45, lum); printCol += g * max(GRAIN, 0.0) * 0.14 * (0.35 + 0.65 * grainEnv); return clamp(printCol, 0.0, 1.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float splitX = 0.0; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { splitX = (iMouse.x - 0.5 * iResolution.xy.x) / iResolution.y; } vec3 hdr = hdrScene(uv); vec3 col; if (uv.x < splitX) { // Left: raw digital hard-clipped sRGB col = pow(clamp(hdr, 0.0, 1.0), vec3(1.0 / 2.2)); } else { // Right: spectral photochemical film stock emulation col = filmEmulsion(hdr, uv, fragCoord); } if (abs(uv.x - splitX) < 0.0025) col = vec3(1.0, 0.88, 0.62); fragColor = vec4(col, 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md) - extends [Spectral upsampling with sigmoid polynomials](https://texelatlas.vercel.app/t/spectral-upsampling-sigmoid.md) ## Combines with - [Film grain synthesis](https://texelatlas.vercel.app/t/film-grain-synthesis.md): Grain layers on top of the emulated density image. - [Spectral upsampling with sigmoid polynomials](https://texelatlas.vercel.app/t/spectral-upsampling-sigmoid.md): Provides spectra from RGB input. ## Combination ideas - [Film stocks exposed by spectra](https://texelatlas.vercel.app/ideas/spectral-film-for-renders/) ## Sources 1. [primary] andreavolpato (2025) andreavolpato/spektrafilm. https://github.com/andreavolpato/spektrafilm License: GPL-3.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Film emulation (spectral stock simulation)." https://texelatlas.vercel.app/t/film-emulation/ (accessed 2026-12-01). --- id: "film-grain-synthesis" title: "Film grain synthesis" domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, python] year_introduced: 2017 inputs: [ldr-image, hdr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "medium" authority: "Newson et al., 2017" url: "https://texelatlas.vercel.app/t/film-grain-synthesis/" sources_verified_at: "2026-11-29" --- # Film grain synthesis (Newson et al., 2017) > Adds grain from a stochastic model of film grains rather than uniform noise, giving intensity-dependent, resolution-independent texture; real-time shaders approximate it with filtered noise. ## Reach for it when - digital image looks too clean and sterile - want grain that resembles a real film stock - uniform noise looks fake and resolution dependent - grain should be stronger in midtones than highlights - match cinematic texture across different output sizes ## How it works Newson et al. model film as a Boolean process: grains are discs of random radius scattered over the image as a Poisson point process. A pixel's output value is the probability that it is covered by some grain, which is a function of the input intensity. Rendering simulates by Monte Carlo: for each output pixel, a few random points are drawn over a window, grains are placed around the nearest Poisson grid cells, and the covered fraction is counted. Rendering at any resolution is possible because the model is defined in continuous space. Mid-tones get the strongest grain, while shadows and highlights show less, matching real film. Real-time engines substitute luminance-weighted blue-ish noise with a grain size parameter. ## When to use it Choose it when you want grain whose size and distribution match a real film stock and survive resolution changes. Prefer cheap hash noise scaled by luminance for games, and apply it after [Chromatic aberration and vignette](https://texelatlas.vercel.app/t/chromatic-aberration.md). Prefer a full [Film emulation (spectral stock simulation)](https://texelatlas.vercel.app/t/film-emulation.md) pipeline if colour behaviour matters, not only texture. ## Cost medium — The exact Monte Carlo model is heavy; shader approximations are cheap. GPU code exists for the full model. Measured GPU Weight: 2.93× baseline (light) — 0.0965 ms median / 0.1 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.58× baseline (light) — 0.041 ms median (2.35× faster on L4). Ampere A100 scaling: 1.72× baseline (feather) — 0.0494 ms median (1.95× faster on A100). ## Failure modes - Animated grain crawls and shimmers if the seed is not changed per frame at film rate - Grain applied before AA or upscaling is smeared or reinforced by the filter - Plain Gaussian noise looks digital and shows in sky gradients as banding structure - Video compression erases fine grain at low bitrates ## Engine support - babylonjs: builtin — `pipeline.grainEnabled = true (GrainPostProcess)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.pure.ts, checked 2026-12-01) — Simple noise grain, not spectral synthesis. - blender: builtin — `Compositor > Add > Camera Lens Effects > Film Grain` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/camera_lens_effects/film_grain.html, checked 2026-12-01) - threejs: official — `import { film } from 'three/addons/tsl/display/FilmNode.js' (WebGL: FilmPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/FilmNode.js, checked 2026-12-01) — Simple noise grain, not physically based synthesis. - unity: builtin — `Volume > Add Override > Post-processing > Film Grain` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Post-Processing-Film-Grain.md, checked 2026-12-01) — Texture-based grain presets or a custom texture, not spectral grain synthesis. - unreal: builtin — `Post Process Volume > Film Grain` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, cpu, python ## Presets ### A smooth grey ramp. Left: uniform additive noise. Right: correlated grain scaled by an intensity function (glsl-fragment; rendered 2026-11-29) ```json { "GRAINSZ": 1.6, "AMT": 0.55 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float GRAINSZ=1.6; // P const float AMT=0.55; // P float vn(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f); return mix(mix(hash(i),hash(i+vec2(1.,0.)),f.x),mix(hash(i+vec2(0.,1.)),hash(i+vec2(1.,1.)),f.x),f.y);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); float L=clamp((q.x+.25)/.5,0.,1.);if(uv.y<0.)L=.5; float g=(vn(fragCoord/GRAINSZ+3.)+.5*vn(fragCoord/(GRAINSZ*.5)+9.)-.75)*1.6; float n=hash(fragCoord)-.5; float v=R?L+g*AMT*sqrt(max(L*(1.-L),0.))*.5:L+n*.18; vec3 col=vec3(clamp(v,0.,1.)); if(abs(uv.x)<.0015)col=vec3(1.); fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Combines with - [Film emulation (spectral stock simulation)](https://texelatlas.vercel.app/t/film-emulation.md): Grain is the last stage of a film-stock simulation. ## Sources 1. [primary] Alasdair Newson, Noura Faraj, Bruno Galerne, Julie Delon (2017) Realistic Film Grain Rendering. Image Processing On Line. https://doi.org/10.5201/ipol.2017.192 (verified via doi.org on 2026-11-29) 2. [primary] A. Newson, J. Delon, B. Galerne (2017) A Stochastic Film Grain Model for Resolution‐Independent Rendering. Computer Graphics Forum. https://doi.org/10.1111/cgf.13159 (verified via crossref on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Film grain synthesis." https://texelatlas.vercel.app/t/film-grain-synthesis/ (accessed 2026-12-01). --- id: "fixed-timestep-integration" title: "Fixed timestep game loop and integration" aliases: [fix your timestep, semi-fixed timestep, accumulator loop] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, unity, unreal, godot, python] year_introduced: 2004 inputs: [particles] outputs: [particles, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Fiedler" url: "https://texelatlas.vercel.app/t/fixed-timestep-integration/" sources_verified_at: "2026-11-29" --- # Fixed timestep game loop and integration (Fiedler) > Advance physics in constant-size steps from a time accumulator, then interpolate rendered state between the last two steps so simulation stays deterministic while display frame rate varies. ## Reach for it when - physics behaves differently at different frame rates - simulation explodes when a frame takes too long - motion judders even though physics runs at fixed rate - need deterministic stepping so replays match exactly ## How it works The loop measures wall-clock time per rendered frame, clamps it to a maximum (to avoid the spiral of death where slow frames demand more steps that make the next frame slower), and adds it to an accumulator. While the accumulator holds at least one step dt, the simulation advances by exactly dt and dt is subtracted. Because every step has identical length, results do not depend on frame rate, integrators such as semi-implicit Euler, Verlet or RK4 keep their stability limits, and recorded inputs replay identically. After stepping, the leftover fraction alpha = accumulator / dt describes how far the display time is between the previous and current states. The renderer blends those two stored states with alpha, which removes the temporal stutter that a fixed step otherwise causes when it does not divide the display rate. Variants run several substeps inside each step, or drive the simulation from the audio or network clock. ## When to use it Choose it for any physics, particle or gameplay simulation where stability, determinism or networking replay matter. Prefer plain variable-dt stepping only for purely visual effects that tolerate drift, such as small [Particle systems](https://texelatlas.vercel.app/t/particle-systems.md) updates. It underpins [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md), [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md), [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) and [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md), whose stiffness and iteration counts are tuned for a fixed dt. Use substepping (as in [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) small-step solvers) instead of a smaller global step when only the solver needs more resolution. ## Cost cheap — Overhead is negligible; total cost is steps per frame times the cost of one simulation step. ## Failure modes - Spiral of death when a step costs more than dt of real time, unless frame time is clamped - Temporal aliasing and judder if the render state is not interpolated and dt does not divide the display period - Interpolating between states lags rendering by up to one step, which matters for input latency in competitive games - Interpolation of rotations or wrapped values needs slerp or angle handling, not component-wise lerp - Floating-point accumulation in the accumulator drifts if stored as float seconds over long sessions ## Engine support - babylonjs: builtin — `physicsEngine.setTimeStep(1 / 60) and physicsEngine.setSubTimeStep(ms) in Physics v2` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Physics/v2/physicsEngine.ts, checked 2026-12-01) - godot: builtin — `Node._physics_process(delta); Project Settings > Physics > Common > Physics Ticks Per Second` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ProjectSettings.xml, checked 2026-12-01) — Fixed-rate physics tick; physics_jitter_fix controls frame-time smoothing. - unity: builtin — `Project Settings > Time > Fixed Timestep; MonoBehaviour.FixedUpdate` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Time-fixedDeltaTime.html, checked 2026-12-01) - unreal: builtin — `Project Settings > Physics > Substepping` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/physics-sub-stepping-in-unreal-engine, checked 2026-12-01) — Physics sub-stepping into fixed steps; the frame loop itself is variable-rate. ## Dataflow - Inputs: particles - Outputs: particles, animation - Platforms: cpu, webgl2, webgpu, desktop-gpu, unity, unreal, godot, python ## Presets ### 60 Hz physics step with frame clamp (json-params; parameter preset) ```json { "dt": 0.016667, "max_frame_time": 0.25, "max_steps_per_frame": 5, "interpolate_render_state": true } ``` Attribution: written for this index ## Combines with - [Quaternion slerp rotation interpolation](https://texelatlas.vercel.app/t/quaternion-slerp-interpolation.md): Render-state interpolation between the last two fixed steps blends orientations with slerp rather than component-wise lerp. - [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md): A fixed dt makes constraint compliance and iteration counts mean the same thing every frame. ## Sources 1. [primary] Glenn Fiedler Fix Your Timestep!. gafferongames.com. https://gafferongames.com/post/fix_your_timestep (verified via http on 2026-11-29) 2. [tutorial] Glenn Fiedler Integration Basics. gafferongames.com. https://gafferongames.com/post/integration_basics (verified via http on 2026-11-29) ## Cite this entry Texel. "Fixed timestep game loop and integration." https://texelatlas.vercel.app/t/fixed-timestep-integration/ (accessed 2026-12-01). --- id: "flip-pic-fluids" title: "FLIP/PIC fluids" aliases: [FLIP, PIC, PIC/FLIP] domain: "simulation" stage: "simulation" realtime: "interactive" platforms: [cpu, cuda, houdini, blender, desktop-gpu] year_introduced: 2005 inputs: [particles, voxels] outputs: [particles, volume-density] style: "photoreal" dynamic: "dynamic" cost: "offline" authority: "Zhu & Bridson, 2005" url: "https://texelatlas.vercel.app/t/flip-pic-fluids/" sources_verified_at: "2026-11-29" --- # FLIP/PIC fluids (Zhu & Bridson, 2005) > Hybrid fluid method: particles carry mass and velocity, a grid solves pressure, and FLIP-style delta transfer gives splashy, low-dissipation liquid motion. ## Reach for it when - water simulation looks too damped and viscous - splashy liquid with lots of detail and particles - pure grid fluid loses small scale motion - simulate liquid pouring and splashing for vfx ## How it works Each step: transfer particle velocities to a staggered MAC grid, add gravity, enforce boundary conditions, project the velocity field to be divergence-free with a pressure solve (PCG or multigrid), then transfer back. PIC copies the new grid velocity to particles, which is stable but very viscous. FLIP transfers only the change in grid velocity, preserving detail but noisy. Production solvers blend them (for example 95-99% FLIP). Particles are advected with the grid velocity, and re-seeded to keep about 8 per fluid cell. Sand and granular media can be modelled by adding a friction-based yield model on top. The surface is extracted from particles via a level-set or anisotropic kernel. ## When to use it Choose it when you want film-quality liquids with energetic splashes and little numerical dissipation. Prefer [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) or [Position Based Fluids](https://texelatlas.vercel.app/t/position-based-fluids.md) for realtime GPU liquids, [Material Point Method (snow)](https://texelatlas.vercel.app/t/mpm-snow.md) when you also need elastoplastic solids (snow, sand, mud) in the same solver, and [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md) for smoke on a pure grid. ## Cost offline — Pressure solve on the grid dominates; production solvers are offline or interactive at modest resolution. Measured GPU Weight: 44.69× baseline (heavy) — 1.3855 ms median / 1.4413 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 43.97× baseline (heavy) — 0.6991 ms median (1.98× faster on L4). Ampere A100 scaling: 31× baseline (heavy) — 0.8929 ms median (1.55× faster on A100). ## Failure modes - FLIP noise: high-frequency velocity jitter and splash 'fizz' when blend ratio is too high - Volume drift or loss without particle-count-per-cell maintenance and volume correction - Thin features below the grid resolution are lost or turn into clumps - Pressure solve with free-surface and solid boundaries is sensitive to bad Neumann/Dirichlet setups ## Engine support - blender: builtin — `Physics Properties > Fluid > Type = Domain, Domain Type = Liquid > Liquid > Simulation Method = FLIP or APIC` (evidence: https://docs.blender.org/manual/en/5.2/physics/fluid/type/domain/settings.html, checked 2026-12-01) — FLIP and APIC; the solver is Mantaflow. - unreal: official — `Enable Niagara Fluids plugin > Grid 3D FLIP Liquid emitter templates` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/niagara-fluids-reference-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: particles, voxels - Outputs: particles, volume-density - Platforms: cpu, cuda, houdini, blender, desktop-gpu ## Presets ### FLIP/PIC Fluids — damped PIC grid transfer (left) vs energetic FLIP velocity-delta blend (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FLIP_RATIO": 0.95, "P_GRID_RES": 10, "P_WAVE_AMP": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_FLIP_RATIO = 0.95; // P FLIP Blend Beta [0.0, 1.0, 0.02] const float P_GRID_RES = 10.0; // P MAC Grid Cells [6.0, 18.0, 1.0] const float P_WAVE_AMP = 1.0; // P Splash Energy [0.3, 1.8, 0.05] const float P_SPLIT = 0.48; // P PIC / FLIP Split [0.0, 1.0, 0.02] vec2 hash21(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // Divergence-free MAC grid velocity field u(x,y) = curl(psi) vec2 macVelocity(vec2 p, float t, float flipBeta) { float k = 4.2; float vx = cos(p.y * k + t * 1.4) * sin(p.x * 3.1 - t * 0.9); float vy = -sin(p.y * k + t * 1.4) * cos(p.x * 3.1 - t * 0.9) * 0.72; // FLIP preserves fine high-frequency sub-grid vorticity that PIC diffuses away float sub = flipBeta * 0.55; vx += sub * sin(p.y * 11.5 - t * 2.8) * cos(p.x * 9.2 + t * 1.9); vy += sub * cos(p.y * 11.5 - t * 2.8) * sin(p.x * 9.2 + t * 1.9); return vec2(vx, vy); } float sdArrow(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a; vec2 ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isFlip = screenX >= split; float beta = isFlip ? clamp(P_FLIP_RATIO, 0.0, 1.0) : 0.04; float res = clamp(floor(P_GRID_RES + 0.5), 6.0, 18.0); float amp = clamp(P_WAVE_AMP, 0.2, 2.0); float t = iTime; vec3 col = mix(vec3(0.022, 0.032, 0.052), vec3(0.052, 0.072, 0.112), smoothstep(-0.5, 0.5, uv.y)); // Tank domain vec2 tankBox = abs(uv) - vec2(0.68, 0.39); float dTank = length(max(tankBox, 0.0)) + min(max(tankBox.x, tankBox.y), 0.0); float inTank = step(dTank, 0.0); // Background staggered MAC pressure/velocity grid vec2 cellUV = uv * res; vec2 cellId = floor(cellUV); vec2 cellF = fract(cellUV) - 0.5; vec2 cellCenter = (cellId + 0.5) / res; float gridLine = smoothstep(0.045, 0.01, min(abs(cellF.x - 0.5), abs(cellF.y - 0.5))); gridLine = max(gridLine, smoothstep(0.045, 0.01, min(abs(cellF.x + 0.5), abs(cellF.y + 0.5)))); col += vec3(0.045, 0.075, 0.125) * gridLine * inTank; // Draw MAC velocity vectors inside each grid cell vec2 vCell = macVelocity(cellCenter, t, beta); float vMag = length(vCell); vec2 arrowEnd = (vCell / max(vMag, 1e-4)) * min(vMag * 0.24, 0.38); float dArr = sdArrow(cellF, -arrowEnd * 0.35, arrowEnd); col += mix(vec3(0.14, 0.38, 0.62), vec3(0.28, 0.85, 0.92), clamp(vMag * 0.7, 0.0, 1.0)) * smoothstep(0.055, 0.015, dArr) * 0.42 * inTank; // Evaluate 36 Lagrangian fluid particles transferring velocity with MAC grid float fluidField = 0.0; float speedSum = 0.0; float minP = 1e5; float splashMask = 0.0; for (int i = 0; i < 36; i++) { float fi = float(i); vec2 h = hash21(fi * 13.7 + 1.9); float colI = mod(fi, 9.0); float rowI = floor(fi / 9.0); // Base wave + PIC viscous damping vs FLIP ballistic cresting float bx = (colI - 4.0) * 0.142 + 0.05 * sin(t * 1.4 + rowI * 0.8); float crest = sin(bx * 4.2 - t * 2.1) * 0.095 * amp * (0.35 + 0.65 * beta); float by = -0.27 + rowI * 0.102 + crest; // FLIP retains sharp sub-grid spray arcs above the wave crest vec2 vLocal = macVelocity(vec2(bx, by), t, beta); float lift = (rowI > 2.5) ? (beta * 0.115 * amp * pow(max(0.5 + 0.5 * sin(t * 2.4 + fi * 1.3), 0.0), 2.0)) : 0.0; vec2 pPos = vec2(bx, by + lift) + vLocal * (0.022 + 0.055 * beta) * amp; pPos.x = clamp(pPos.x, -0.63, 0.63); pPos.y = clamp(pPos.y, -0.35, 0.34); float d = length(uv - pPos); minP = min(minP, d); float rK = 0.135; if (d < rK) { float q = 1.0 - d / rK; float w = q * q * q; fluidField += w; speedSum += w * (length(vLocal) + lift * 6.0); } if (rowI > 2.5 && beta > 0.3) { splashMask = max(splashMask, smoothstep(0.024, 0.008, d) * beta); } } float mask = smoothstep(0.42, 0.58, fluidField) * inTank; if (mask > 0.005) { float avgSpd = speedSum / max(fluidField, 1e-4); vec3 picCol = mix(vec3(0.08, 0.28, 0.56), vec3(0.22, 0.52, 0.74), clamp(avgSpd * 0.5, 0.0, 1.0)); vec3 flipCol = mix(vec3(0.05, 0.42, 0.78), vec3(0.18, 0.92, 0.88), clamp(avgSpd * 0.65, 0.0, 1.0)); flipCol = mix(flipCol, vec3(0.95, 0.98, 1.0), smoothstep(1.1, 2.0, avgSpd) * 0.65); vec3 water = mix(picCol, flipCol, beta); float edgeFoam = smoothstep(0.75, 0.44, fluidField); water += vec3(0.85, 0.96, 1.0) * edgeFoam * (0.18 + 0.38 * beta); col = mix(col, water, mask * 0.88); } // Particle dots + ballistic FLIP spray droplets col = mix(col, vec3(0.88, 0.96, 1.0), smoothstep(0.015, 0.006, minP) * 0.72 * inTank); col += vec3(0.82, 0.97, 1.0) * splashMask * 0.75 * inTank; // Border and split bar col = mix(col, vec3(0.68, 0.84, 0.98), smoothstep(0.009, 0.002, abs(dTank)) * 0.85); col = mix(col, vec3(0.95, 0.97, 1.0), smoothstep(0.0035, 0.0008, abs(screenX - split))); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Oblique-clipped planar reflections on sloshing FLIP fluid pools](https://texelatlas.vercel.app/ideas/flip-fluid-oblique-planar-reflections/) ## Sources 1. [primary] Yongning Zhu, Robert Bridson (2005) Animating sand as a fluid. ACM Transactions on Graphics. https://doi.org/10.1145/1073204.1073298 (verified via crossref on 2026-11-29) 2. [tutorial] Matthias Müller Ten Minute Physics. matthias-research.github.io. https://matthias-research.github.io/pages/tenMinutePhysics (verified via http on 2026-11-29) ## Cite this entry Texel. "FLIP/PIC fluids." https://texelatlas.vercel.app/t/flip-pic-fluids/ (accessed 2026-12-01). --- id: "flow-map-water" title: "Flow-map water animation" aliases: [flowmap, flow mapping, river flow shader, two-phase flow blend] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2010 inputs: [texture] outputs: [normals, texture] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Vlachos" url: "https://texelatlas.vercel.app/t/flow-map-water/" sources_verified_at: "2026-11-29" --- # Flow-map water animation (Vlachos) > Animate water along authored directions by scrolling a normal map through a flow texture, using two time-shifted layers cross-faded so the reset of the distortion is hidden. Gives rivers, whirlpools and fountains cheaply. ## Reach for it when - river water should flow along a bend - water texture stretches and smears when scrolled - want cheap flowing water without a simulation - pulsing visible when looping flowing normal maps ## How it works A flow map is a texture whose red and green channels hold a 2D flow vector per texel, painted or simulated for a river bend, eddy or waterfall. Distorting a normal map by a flow vector that grows over time stretches the pattern without bound, so the technique resets the distortion periodically. The lookup works with two phases. Compute `phase0 = fract(t / T)` and `phase1 = fract(t / T + 0.5)`. For each phase, sample the water normals at `uv - flow * phase * strength`. Blend the two samples with weight `abs(1 - 2 * phase0)`, so each layer is fully visible at the middle of its cycle and invisible at its reset, where distortion is largest and the jump happens. Adding a per-pixel noise offset to each phase breaks the visible pulsing; a small per-layer UV offset avoids repeating bands. Flow speed can also modulate normal-map scale and foam. Results feed refraction, reflection and specular shading of the water surface. ## When to use it Choose it for rivers, streams, pools with currents, spillways and any surface where the flow direction is authored and cheap animation matters. Prefer [gerstner-waves](gerstner-waves) or [fft-ocean](fft-ocean) for open water where waves propagate and displace geometry. Prefer [shallow-water-equations](shallow-water-equations) or [stable-fluids](stable-fluids) when the flow must react to obstacles and player interaction, and render the simulated velocity through the same two-phase blend. Use [water-caustics-realtime](water-caustics-realtime) and [planar-reflections-oblique-clipping](planar-reflections-oblique-clipping) for the surrounding water look. ## Cost cheap — Two normal-map fetches and one flow-map fetch per pixel; no simulation. Measured GPU Weight: 8.5× baseline (moderate) — 0.2795 ms median / 0.4756 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.83× baseline (moderate) — 0.1245 ms median (2.24× faster on L4). Ampere A100 scaling: 6.17× baseline (moderate) — 0.1778 ms median (1.57× faster on A100). ## Failure modes - Visible pulsing at the cycle period if the two phases are not offset or noise-jittered - Smearing and stretching of the pattern in regions where the flow is strong relative to the cycle length - Discontinuities when the flow map has seams or its resolution is too low, since bilinear filtering of vectors cancels opposing flows - Flow does not interact with objects dynamically unless the map is updated at runtime - Normal-map detail that is anisotropic looks wrong when rotated by a changing flow direction - Foam and shoreline masks need separate authoring, or they remain static while the water moves ## Engine support - threejs: official — `import { Water } from 'three/addons/objects/Water2.js' (flowMap option)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/objects/Water2.js, checked 2026-12-01) - unity: builtin — `HDRP Water System > Current Map / water decals` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/water-create-a-current-in-the-water-system.md, checked 2026-12-01) — HDRP water currents. - unreal: builtin — `Material Functions > Misc > FlowMap material functions for animated UV water flow` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/misc-material-functions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: texture - Outputs: normals, texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Two-phase flow-map water with an eddy (glsl-fragment; rendered 2026-11-29) ```json { "cycle_seconds": 2, "strength": 0.35 } ``` ```glsl // Flow-map water: a flow field advects a pattern; two phase-offset layers are cross-faded to hide the reset. const float CYCLE = 2.0; // seconds per advection cycle const float STRENGTH = 0.35; // how far the pattern travels per cycle float hash(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix(mix(hash(i), hash(i + vec2(1, 0)), f.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), f.x), f.y); } float ripples(vec2 p) { return 0.6 * vnoise(p * 6.0) + 0.3 * vnoise(p * 13.0 + 7.0) + 0.1 * vnoise(p * 29.0); } vec2 flowField(vec2 p) { // a river bend plus an eddy vec2 c = p - vec2(0.62, 0.45); vec2 swirl = vec2(-c.y, c.x) / (dot(c, c) * 40.0 + 0.5); return normalize(vec2(1.0, 0.4 * sin(p.x * 5.0)) + swirl * 2.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 f = flowField(uv); float t = iTime / CYCLE; float p0 = fract(t), p1 = fract(t + 0.5); float w = abs(1.0 - 2.0 * p0); // weight of layer 0 (layer 1 gets 1 - w) float a = ripples(uv - f * p0 * STRENGTH + 0.0); float b = ripples(uv - f * p1 * STRENGTH + 0.37); float v = mix(b, a, w); vec3 deep = vec3(0.02, 0.18, 0.28), shallow = vec3(0.25, 0.6, 0.62); vec3 col = mix(deep, shallow, smoothstep(0.2, 0.9, v)); col += pow(smoothstep(0.6, 0.85, v), 3.0) * vec3(0.8, 0.9, 0.95); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index; algorithm from the cited Valve talk; basis: 0 ## Combines with - [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md): A simulated velocity field can be baked or streamed as the flow map so water reacts to obstacles. - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Normals from the blended layers drive the caustic pattern on the river bed. - [Planar reflections with oblique near-plane clipping](https://texelatlas.vercel.app/t/planar-reflections-oblique-clipping.md): The perturbed normals offset the reflection texture lookup on the water plane. ## Sources 1. [primary] Alex Vlachos Water Flow in Portal 2. SIGGRAPH 2010. https://steamcdn-a.akamaihd.net/apps/valve/2010/siggraph2010_vlachos_waterflow.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Flow-map water animation." https://texelatlas.vercel.app/t/flow-map-water/ (accessed 2026-12-01). --- id: "foliage-wind-animation" title: "Procedural foliage wind animation" aliases: [vertex wind, tree sway, grass sway, vegetation wind] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2007 inputs: [mesh, texture] outputs: [mesh, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Zadeh" url: "https://texelatlas.vercel.app/t/foliage-wind-animation/" sources_verified_at: "2026-11-29" --- # Procedural foliage wind animation (Zadeh) > Move vegetation in the vertex shader with layered trunk bend, branch sway and leaf flutter, steered by a global wind direction and masked by painted vertex data. ## Reach for it when - grass and trees need to sway convincingly in the wind - wind animation shadows detach from moving leaves - all plants pulse in sync like a wave machine - want cheap ambient vegetation motion in the vertex shader ## How it works Wind is treated as a scalar or vector field in world space, scrolled over time: a sum of low-frequency sines or a tiling noise texture gives gusts that travel across the scene. Each vertex reads that field at its world position and applies several displacement bands. A main bend moves the whole plant with a weight that rises with height, usually squared so the base stays rooted. A branch band offsets groups of vertices with a phase stored per branch so limbs do not move in lockstep. A detail band shakes leaves with high-frequency noise along the normal and edge, keyed to a per-vertex phase. The masks live in vertex colours or UVs: height weight, branch phase, leaf flutter amount. Displacements are applied as rotations or length-preserving offsets, not raw translations, to avoid stretching. Shadow and depth passes must run the same function so shadows follow the sway. ## When to use it Choose it for grass, trees, bushes and flags in open scenes, where cost per vertex must stay tiny and the animation is ambient. Prefer [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md) or [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) when branches must react to colliders or the player, and [Vertex animation textures (VAT) and GPU crowds](https://texelatlas.vercel.app/t/vertex-animation-textures.md) when you need a baked, unique motion on a few hero assets. Prefer [Curl noise for procedural fluid motion](https://texelatlas.vercel.app/t/curl-noise-flow.md) as the wind source when you want swirling, non-directional gusts. Pair with [Octahedral impostors](https://texelatlas.vercel.app/t/octahedral-impostors.md) for distant trees so the sway fades out with distance. ## Cost cheap — A few sine or texture lookups per vertex; no extra passes beyond matching the shadow pass. Measured GPU Weight: 13.32× baseline (moderate) — 0.4382 ms median / 0.4564 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 12.99× baseline (moderate) — 0.2065 ms median (2.12× faster on L4). Ampere A100 scaling: 9.51× baseline (moderate) — 0.2738 ms median (1.6× faster on A100). ## Failure modes - Shadow-map and depth prepass geometry not animated identically, so shadows and outlines detach from the foliage - Raw translation stretches leaves and trunks; bending should preserve length - Synchronised phase makes the whole field pulse like a wave machine; per-instance and per-branch phase offsets are required - Normals not rotated with the bend cause lighting to flicker on sway - Wind field not distance-faded to LOD or impostors leaves popping when switching representation ## Engine support - unity: builtin — `GameObject > 3D Object > Wind Zone (bends Terrain trees and SpeedTree)` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/class-WindZone.html, checked 2026-12-01) — Tree wind only; grass and custom meshes need shaders. - unreal: builtin — `Material graph: SimpleGrassWind material function into World Position Offset` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/world-position-offset-material-functions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, texture - Outputs: mesh, animation - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### 2D grass-blade sway with travelling gusts (glsl-fragment; rendered 2026-11-29) ```json { "spacing": 0.045, "blade_height": 0.35, "wind": 0.12, "wave_freq": 6, "wave_speed": 2, "flutter": 0.012 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. 2D grass-blade sway: bend grows with height squared, a travelling gust plus fast flutter. const float SPACING = 0.045; // blade pitch const float BLADE_H = 0.35; // blade height const float WIND = 0.12; // peak tip displacement of the main bend const float WAVE_FREQ = 6.0; // gust wave number along x const float WAVE_SPD = 2.0; // gust travel speed const float FLUTTER = 0.012; // small high-frequency tip shake const float GROUND = -0.3; float hash11(float n) { return fract(sin(n * 127.1) * 43758.5453); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 col = mix(vec3(0.80, 0.90, 0.98), vec3(0.30, 0.55, 0.90), uv.y + 0.5); for (int layer = 0; layer < 3; layer++) { float fl = float(layer); float shade = 0.45 + 0.28 * fl; float cell = floor(uv.x / SPACING + fl * 0.37); for (int k = -3; k <= 3; k++) { float id = cell + float(k) + fl * 91.0; float cx = (id + 0.5 + (hash11(id) - 0.5) * 0.6 - fl * 0.37) * SPACING; float height = BLADE_H * (0.6 + 0.6 * hash11(id + 17.0)); float h = (uv.y - GROUND) / height; if (h < 0.0 || h > 1.0) continue; float gust = 0.5 + 0.5 * sin(WAVE_FREQ * cx - WAVE_SPD * iTime); float bend = WIND * h * h * (0.25 + 0.75 * gust); bend += FLUTTER * h * h * sin(11.0 * iTime + hash11(id + 3.0) * 6.28); float halfW = 0.011 * (1.0 - 0.85 * h); if (abs(uv.x - (cx + bend)) < halfW) col = vec3(0.10, 0.45, 0.12) * shade + vec3(0.25, 0.35, 0.05) * h * shade; } } if (uv.y < GROUND) col = vec3(0.16, 0.11, 0.07) * (1.0 + 0.5 * (uv.y - GROUND)); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Combines with - [Curl noise for procedural fluid motion](https://texelatlas.vercel.app/t/curl-noise-flow.md): A scrolling curl-noise field supplies the wind vector each vertex samples, producing swirling gusts that stay incompressible. - [Octahedral impostors](https://texelatlas.vercel.app/t/octahedral-impostors.md): Distant trees swap to impostors, so the wind amplitude is faded toward zero before the swap to hide the transition. ## Sources 1. [primary] Zadeh GPU Gems 3, Chapter 6: GPU-Generated Procedural Wind Animations for Trees. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-6-gpu-generated-procedural-wind-animations-trees (verified via http on 2026-11-29) 2. [tutorial] Sousa GPU Gems 3, Chapter 16: Vegetation Procedural Animation and Shading in Crysis. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-16-vegetation-procedural-animation-and-shading-crysis (verified via http on 2026-11-29) ## Cite this entry Texel. "Procedural foliage wind animation." https://texelatlas.vercel.app/t/foliage-wind-animation/ (accessed 2026-12-01). --- id: "fp16-stochastic-rounding-reaction-field" title: "Coupled Ground Reaction-Front Field with FP16 Stochastic Rounding" aliases: [FP16 stochastic rounding decay, coupled elemental ground field, stochastically rounded half-float surface PDE] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cuda] year_introduced: 2021 inputs: [texture, particles] outputs: [texture, material-params] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Connolly et al., 2021" url: "https://texelatlas.vercel.app/t/fp16-stochastic-rounding-reaction-field/" sources_verified_at: "2026-11-30" --- # Coupled Ground Reaction-Front Field with FP16 Stochastic Rounding (Connolly et al., 2021) > Evolve multi-channel persistent surface reaction fronts (heat, char, wetness, frost, cracks) in bandwidth-efficient RGBA16F ping-pong targets, using per-texel stochastic rounding so slow high-frame-rate exponential decays never stall on 10-bit mantissa quantization. ## Reach for it when - reaction-diffusion or wetness pde freezes solid when stored in fp16 textures - small per-frame simulation increments underflow to zero in half float buffers - cut fluid or chemical field memory bandwidth in half without stalling evolution - eliminate visible quantization banding in slow-evolving fp16 gpu simulations - preserve long-term diffusion conservation using randomized rounding on half floats ## How it works Real-time arenas often track coupled persistent ground effects—heat melting frost into wetness, wetness quenching fire, frost creeping along crystalline veins, or cracks radiating outward—in world-aligned ping-pong MRT textures. Storing eight channels in `RGBA16F` halves memory bandwidth relative to `RGBA32F`, but IEEE half-precision floats have only 10 mantissa bits (a minimum relative step of $\approx 2^{-10} \approx 0.1\%$). At 120–144 Hz, a slow decay with time constant $\tau = 25\,\text{s}$ changes a texel by roughly $0.03\%$ per frame, which round-to-nearest hardware silently snaps back to the old value—causing permanent stagnation. **Stochastic rounding** (Connolly, Higham & Mary 2021) eliminates this stagnation in expectation without switching to FP32. When writing a decayed value $x$ between adjacent FP16 representable levels $x_-$ and $x_+$, the shader adds a uniform hash-based dither offset proportional to the local FP16 ULP before quantizing, rounding up with probability $(x - x_-)/(x_+ - x_-)$ and down otherwise. Averaged over frames and neighboring texels, the decay remains unbiased and smooth across any refresh rate. To stay within tight frame budgets at high resolutions, active impact regions are clustered into a few bounding boxes stepped every frame while inactive areas update via rotating row bands using accumulated `dt`, with directional masks gating propagating fronts. ## When to use it Choose it when maintaining large, multi-channel interactive ground or surface state textures (scorch, snow, frost, wetness, corrosion) in FP16 on bandwidth-bound desktop or mobile GPUs at high refresh rates. Prefer [deferred-and-projected-decals](deferred-and-projected-decals) when effects are isolated stamps that do not chemically react, diffuse, or propagate into neighboring texels. Prefer [gray-scott-reaction-diffusion](gray-scott-reaction-diffusion) when simulating organic Turing pattern synthesis rather than gameplay-coupled state channels. Prefer FP32 storage when exact deterministic per-texel precision is required and bandwidth headroom allows. ## Cost cheap — Halves render-target memory and bandwidth versus FP32; combining active bounding-box updates with rotating background row bands keeps a 1024×1024 dual-MRT field well under a fraction of a millisecond on desktop GPUs. ## Failure modes - High-frequency spatial hash noise from stochastic rounding can become faintly visible if the field is rendered directly without material filtering or mask modulation - Rotating-band partial updates cause non-active areas to decay in subtle staggered sweeps if band count is too high or accumulated dt is large - Fixed world-aligned textures waste resolution on distant terrain unless clipped to a bounded arena or scrolled as a toroidal clipmap - Over-tight baked mask thresholds can trap propagating frost or crack fronts in fragmented isolated islands ## Dataflow - Inputs: texture, particles - Outputs: texture, material-params - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cuda ## Presets ### Dual-MRT FP16 reaction-field partial-update defaults (json-params; parameter preset) ```json { "texture_format": "RGBA16F", "mrt_targets": 2, "max_active_boxes": 4, "rotating_background_bands": 32, "slow_decay_tau_seconds": 25 } ``` Attribution: written for this index ## Combines with - [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md): Floor-contacting particles render additively into a cleared paint target that injects heat, wetness, frost, or acid straight into the reaction field. - [Deferred and projected decals](https://texelatlas.vercel.app/t/deferred-and-projected-decals.md): Floor materials sample the persistent multi-channel reaction texture alongside static decals to blend roughness, emissive glow, and fracture reliefs. ## Combination ideas - [Narrow-range SSF liquid with whitewater and wet-ground reaction field](https://texelatlas.vercel.app/ideas/narrow-range-ssf-whitewater-ground-field/) ## Sources 1. [primary] Michael P. Connolly, Nicholas J. Higham, Theo Mary (2021) Stochastic Rounding and Its Probabilistic Backward Error Analysis. SIAM Journal on Scientific Computing. https://doi.org/10.1137/20m1334796 (verified via crossref on 2026-11-30) 2. [implementation] Humpalumps (2026) Humpalumps/ultra-elements. https://github.com/Humpalumps/ultra-elements License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Coupled Ground Reaction-Front Field with FP16 Stochastic Rounding." https://texelatlas.vercel.app/t/fp16-stochastic-rounding-reaction-field/ (accessed 2026-12-01). --- id: "fractal-brownian-motion" title: "Fractal Brownian Motion and Multifractals" aliases: [fBm, ridged multifractal, hybrid multifractal, spectral synthesis] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, houdini, unity, unreal, godot, python] year_introduced: 1989 outputs: [heightfield, texture, volume-density] style: "both" dynamic: "both" cost: "cheap" authority: "Musgrave et al., 1989" url: "https://texelatlas.vercel.app/t/fractal-brownian-motion/" sources_verified_at: "2026-11-29" --- # Fractal Brownian Motion and Multifractals (Musgrave et al., 1989) > Sum several octaves of a band-limited noise with increasing frequency and decreasing amplitude to get a self-similar field. Multifractal variants modulate each octave by the previous so rough peaks and smooth valleys emerge. ## Reach for it when - need a natural-looking base heightfield - single noise layer looks smooth and boring - clouds or marble need detail at many scales - want rough mountains with smoother valleys ## How it works fBm evaluates noise at p, then repeatedly multiplies frequency by a lacunarity (usually about 2) and amplitude by a gain (about 0.5, i.e. Hurst exponent H with gain = 2^-H), accumulating the sum. The gain controls the spectral slope and hence perceived roughness; lacunarity should be a bit off 2 or the octaves are rotated and offset to hide lattice alignment. Musgrave's multifractals break the statistical uniformity: in a multifractal each octave is scaled by the running value, so high areas receive more small-scale detail than low ones, mimicking eroded mountains over smooth basins. Ridged multifractal takes 1-|n| to create sharp crests, and hybrid versions mix additive and multiplicative behaviour. The octave count caps detail and cost; bandlimiting octaves above the Nyquist for the pixel footprint avoids shimmering. ## When to use it Choose it as the base heightfield generator and for clouds, marble or any natural-looking detail. Prefer [Domain Warping](https://texelatlas.vercel.app/t/domain-warping.md) on top when you want swirled, flow-like structure, [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) or [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) when plain fBm terrain looks unconvincing because it lacks drainage networks, and [Thermal (Talus) Erosion](https://texelatlas.vercel.app/t/thermal-erosion.md) for cheap slope relaxation. ## Cost cheap — Linear in octave count; 4 to 8 octaves is typical for terrain. Measured GPU Weight: 52.91× baseline (heavy) — 1.7407 ms median / 1.7977 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 45.06× baseline (heavy) — 0.7165 ms median (2.43× faster on L4). Ampere A100 scaling: 36.43× baseline (heavy) — 1.0491 ms median (1.66× faster on A100). ## Failure modes - Statistically stationary: peaks and valleys look equally rough, the telltale 'blobby' fBm terrain without drainage networks - Lattice alignment accumulates across octaves when frequency is exactly 2 with no rotation or offset - Too many octaves alias at distance and shimmer unless fade-by-pixel-footprint is applied - Domain-wide gain tuned for one height range breaks when the field is later remapped or clamped ## Engine support - babylonjs: builtin — `NoiseProceduralTexture (octaves, persistence in noise.fragment.fx) and Node Material CloudBlock (octaves)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Shaders/noise.fragment.fx, checked 2026-12-01) - blender: builtin — `Noise Texture > Type = fBM, Multifractal, Hybrid Multifractal, Ridged Multifractal or Hetero Terrain` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/noise.html, checked 2026-12-01) - godot: builtin — `FastNoiseLite > fractal_type = FastNoiseLite.FRACTAL_FBM with configurable fractal_octaves` (evidence: https://github.com/godotengine/godot/blob/4.4-stable/modules/noise/fastnoise_lite.cpp, checked 2026-12-01) - threejs: builtin — `import { mx_fractal_noise_float } from 'three/tsl'` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/materialx/MaterialXNodes.js, checked 2026-12-01) — TSL node. - unity: official — `Visual Effect Graph > Operator > Perlin Noise or Cellular Noise with Octaves > 1` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.visualeffectgraph/Documentation~/Operator-PerlinNoise.md, checked 2026-12-01) — Requires the Visual Effect Graph package. - unreal: builtin — `Material Noise expression > Levels (octaves) with optional Turbulence` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/utility-material-expressions-in-unreal-engine, checked 2026-12-01) — Octave summation via Levels, Output Min/Max and Level Scale. ## Dataflow - Inputs: — - Outputs: heightfield, texture, volume-density - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, houdini, unity, unreal, godot, python ## Presets ### fBm heightfield with hypsometric colouring and hillshade (glsl-fragment; rendered 2026-11-29) ```json { "octaves": 7, "lacunarity": 2, "gain": 0.5, "sea_level": 0.45 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. fBm terrain: sea, beach, grass, rock, snow + hillshade. const int OCTAVES = 7; const float LACUNARITY = 2.0; const float GAIN = 0.5; const float SEA = 0.45; float hash21(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } float vnoise(vec2 p){ vec2 i = floor(p), f = fract(p); vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0); float a = hash21(i), b = hash21(i + vec2(1.0, 0.0)); float c = hash21(i + vec2(0.0, 1.0)), d = hash21(i + vec2(1.0, 1.0)); return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); } float fbm(vec2 p){ float s = 0.0, a = 0.5, norm = 0.0; mat2 rot = mat2(0.8, 0.6, -0.6, 0.8); for (int i = 0; i < OCTAVES; i++) { s += a * vnoise(p); norm += a; p = rot * p * LACUNARITY + vec2(17.1, 9.2); a *= GAIN; } return s / norm; } float height(vec2 p){ return fbm(p); } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = fragCoord / iResolution.y; vec2 p = uv * 3.0 + vec2(iTime * 0.02, 0.0); float h = height(p); float e = 0.004; vec3 n = normalize(vec3(height(p - vec2(e, 0.0)) - height(p + vec2(e, 0.0)), height(p - vec2(0.0, e)) - height(p + vec2(0.0, e)), 2.0 * e * 4.0)); float light = clamp(dot(n, normalize(vec3(-0.6, 0.5, 0.65))), 0.0, 1.0); vec3 deep = vec3(0.02, 0.10, 0.25), shallow = vec3(0.10, 0.35, 0.50); vec3 sand = vec3(0.76, 0.70, 0.50), grass = vec3(0.20, 0.42, 0.15); vec3 rock = vec3(0.42, 0.38, 0.34), snow = vec3(0.95, 0.96, 0.98); vec3 col; if (h < SEA) { col = mix(deep, shallow, smoothstep(SEA - 0.2, SEA, h)); } else { col = mix(sand, grass, smoothstep(SEA, SEA + 0.04, h)); col = mix(col, rock, smoothstep(SEA + 0.12, SEA + 0.22, h)); col = mix(col, snow, smoothstep(SEA + 0.28, SEA + 0.34, h)); col *= 0.45 + 0.9 * light; } fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Lineage - extends [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) - extended by [Domain Warping](https://texelatlas.vercel.app/t/domain-warping.md) ## Combines with - [Domain Warping](https://texelatlas.vercel.app/t/domain-warping.md): fBm provides both the base field and the warp vectors. - [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md): fBm heightfield is the typical starting terrain that erosion then carves. ## Sources 1. [primary] F. K. Musgrave, C. E. Kolb, R. S. Mace (1989) The synthesis and rendering of eroded fractal terrains. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/74334.74337 (verified via crossref on 2026-11-29) 2. [primary] F. Kenton Musgrave (2003) Procedural fractal terrains. Texturing and Modeling. https://doi.org/10.1016/b978-155860848-1/50045-0 (verified via crossref on 2026-11-29) 3. [tutorial] Inigo Quilez fBM. iquilezles.org. https://iquilezles.org/articles/fbm (verified via http on 2026-11-29) 4. [tutorial] Patricio Gonzalez Vivo The Book of Shaders: Fractal Brownian Motion. thebookofshaders.com. https://thebookofshaders.com/13 (verified via http on 2026-11-29) ## Cite this entry Texel. "Fractal Brownian Motion and Multifractals." https://texelatlas.vercel.app/t/fractal-brownian-motion/ (accessed 2026-12-01). --- id: "fresnel-schlick-approximation" title: "Schlick Fresnel approximation" aliases: [Schlick's approximation, F_Schlick] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender] year_introduced: 1994 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Schlick, 1994" url: "https://texelatlas.vercel.app/t/fresnel-schlick-approximation/" sources_verified_at: "2026-11-29" --- # Schlick Fresnel approximation (Schlick, 1994) > A cheap polynomial stand-in for the Fresnel equations: reflectance climbs from a base value F0 at normal incidence to 1 at grazing angles via (1 - cos)^5. It is the F term in practically every real-time PBR shader. ## Reach for it when - surface should reflect more at grazing angles - edges of glossy objects look too flat - need cheap fresnel for water or glass rim - metal and plastic share the same reflectivity - rim highlight is too bright on rough materials ## How it works Real Fresnel reflectance depends on polarisation and complex refractive index. Schlick observed that the curve is well matched by F(theta) = F0 + (1 - F0) * (1 - cos theta)^5, where F0 is the reflectance when looking straight at the surface. For dielectrics F0 follows from the index of refraction as ((n-1)/(n+1))^2, which gives about 0.04 for common plastics and glass; for metals F0 is a coloured vec3 taken from measured data or a base-colour texture. Which cosine you use matters: in a microfacet BRDF it is dot(V, H), the angle to the half vector, not dot(V, N). For ambient and image-based lighting the roughness-aware variant clamps the grazing value to max(1 - roughness, F0), because rough surfaces do not reach full mirror reflectance. Metal workflows also let artists set a per-material F90 so the rim colour can be tuned. ## When to use it Use it as the default Fresnel in any microfacet pipeline ([Cook-Torrance microfacet BRDF](https://texelatlas.vercel.app/t/cook-torrance-brdf.md), [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md), [Frostbite physically based rendering](https://texelatlas.vercel.app/t/frostbite-pbr.md)) and in cheap rim-light or water-edge effects. Prefer the exact Fresnel equations for offline spectral rendering or conductors with strongly coloured grazing behaviour. Prefer [Thin-film iridescence](https://texelatlas.vercel.app/t/thin-film-iridescence.md) when a view-dependent hue shift is needed, and [Clearcoat layer](https://texelatlas.vercel.app/t/clearcoat-layer.md) when a second dielectric interface sits on top. ## Cost cheap — A few multiplies; the fifth power is two squarings and a multiply. Measured GPU Weight: 1.56× baseline (feather) — 0.0514 ms median / 0.0528 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.26× baseline (feather) — 0.02 ms median (2.57× faster on L4). Ampere A100 scaling: 1.01× baseline (feather) — 0.029 ms median (1.77× faster on A100). ## Failure modes - Using dot(N,V) instead of dot(V,H) in the specular BRDF gives the wrong rim brightness - Unclamped grazing reflectance on rough surfaces makes IBL edges glow unrealistically - Fixed F0=0.04 applied to metals removes their colour - Inaccurate for metals and absorbing media near the pseudo-Brewster angle where true reflectance dips - Negative cosine from interpolated normals produces NaNs unless the base is clamped ## Engine support - babylonjs: builtin — `Used internally by PBRMaterial (fresnelSchlickGGX)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Shaders/ShadersInclude/pbrBRDFFunctions.fx, checked 2026-12-01) - blender: builtin — `Shader node: Fresnel / Layer Weight, plus Principled BSDF dielectric/metallic Fresnel` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/input/fresnel.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.specular_mode = SPECULAR_SCHLICK_GGX (default)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) — Used inside the default PBR specular model. - threejs: builtin — `Used internally by MeshStandardMaterial/MeshPhysicalMaterial (F_Schlick)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/renderers/shaders/ShaderChunk/bsdfs.glsl.js, checked 2026-12-01) - unity: builtin — `Used by HDRP/URP Lit shading; Shader Graph Fresnel Effect node for authored use` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl, checked 2026-12-01) — ShaderLibrary function F_Schlick. - unreal: builtin — `Material graph: Fresnel expression (ExponentIn, BaseReflectFractionIn) plus PBR grazing Fresnel` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/using-fresnel-in-your-unreal-engine-materials, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender ## Presets ### Schlick Fresnel sphere, F0 = 0.04 (glsl-fragment; rendered 2026-11-29) ```json { "F0": 0.04 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Schlick Fresnel blending sky reflection and diffuse. const float F0 = 0.04; const vec3 ALBEDO = vec3(0.1, 0.35, 0.6); vec3 sky(vec3 d) { float t = clamp(d.y * 0.5 + 0.5, 0.0, 1.0); vec3 c = mix(vec3(0.9, 0.8, 0.7), vec3(0.25, 0.45, 0.85), t); return c * (0.6 + 0.4 * smoothstep(0.6, 1.0, t) + 0.5 * pow(max(d.x, 0.0), 8.0)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 3.0); vec3 rd = normalize(vec3(uv, -1.5)); vec3 col = sky(rd) * 0.5; float b = dot(ro, rd); float h = b * b - (dot(ro, ro) - 1.0); if (h > 0.0) { vec3 p = ro + rd * (-b - sqrt(h)); vec3 n = normalize(p); float c = clamp(dot(n, -rd), 0.0, 1.0); float f = F0 + (1.0 - F0) * pow(1.0 - c, 5.0); vec3 refl = sky(reflect(rd, n)); vec3 diff = ALBEDO * (0.2 + 0.8 * max(dot(n, normalize(vec3(0.5, 0.7, 0.6))), 0.0)); col = mix(diff, refl, f); } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) ## Combines with - [Split-Sum Image-Based Lighting](https://texelatlas.vercel.app/t/split-sum-ibl.md): The roughness-aware Schlick term feeds the pre-integrated environment BRDF so ambient reflections get a correct rim. ## Sources 1. [primary] Christophe Schlick (1994) An Inexpensive BRDF Model for Physically‐based Rendering. Computer Graphics Forum. https://doi.org/10.1111/1467-8659.1330233 (verified via crossref on 2026-11-29) 2. [tutorial] Brian Karis Real Shading in Unreal Engine 4 (course notes). blog.selfshadow.com. https://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Schlick Fresnel approximation." https://texelatlas.vercel.app/t/fresnel-schlick-approximation/ (accessed 2026-12-01). --- id: "frostbite-pbr" title: "Frostbite physically based rendering" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2014 inputs: [material-params, normals, irradiance-probes] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Lagarde & Rousiers" url: "https://texelatlas.vercel.app/t/frostbite-pbr/" sources_verified_at: "2026-11-29" --- # Frostbite physically based rendering (Lagarde & Rousiers) > The Frostbite engine's PBR recipe: GGX specular with height-correlated Smith, Disney-style diffuse, photometric light units, and a consistent IBL and area-light pipeline. Its course notes are the reference for shipping PBR in a game engine. ## Reach for it when - need a checklist for shipping pbr in a game engine - lighting units and roughness remapping are inconsistent - specular occlusion and ibl prefiltering questions - auditing my game's physically based pipeline - area lights and ibl don't match in brightness ## How it works The notes document a full engine-level pipeline rather than a single BRDF. Materials use a base colour/metalness/reflectance/smoothness parameterisation with a remap from artist roughness to GGX alpha. Direct lighting evaluates GGX with the height-correlated Smith visibility term and a Frostbite-tuned diffuse (a Disney variant with energy normalisation). Lights are specified in physical photometric units (lumens, lux, nits) with exposure applied afterwards, and area lights use representative-point or LTC-style approximations. IBL uses pre-filtered specular cubemaps and a split-sum BRDF LUT with a dominant-direction correction for rough reflections, and diffuse from pre-integrated irradiance. The text also covers unit conversion, occlusion handling and specular occlusion. ## When to use it Choose it as a checklist when building or auditing a game PBR pipeline: units, roughness remapping, specular occlusion, IBL pre-filtering. Prefer [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) when you want the artist parameter philosophy instead of an engine recipe, and [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) for offline interchange. ## Cost cheap — Designed for console budgets: one GGX lobe per light plus pre-filtered IBL lookups. Measured GPU Weight: 3.63× baseline (light) — 0.1195 ms median / 0.126 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.82× baseline (light) — 0.0448 ms median (2.67× faster on L4). Ampere A100 scaling: 2.22× baseline (light) — 0.0638 ms median (1.87× faster on A100). ## Failure modes - Split-sum IBL assumes view = normal, so stretched reflections at grazing angles and on rough surfaces are too short - Pre-filtered cubemaps are box-parallax-free; interiors need local probes or reflections look detached - Photometric exposure workflows break when artists or tonemappers assume sRGB-ranged lights - Single-scatter specular loses energy at high roughness; add kulla-conty-multiscatter ## Engine support - babylonjs: builtin — `PBRMaterial combines Burley diffuse, GGX NDF, height-correlated Smith visibility (smithVisibility_GGXCorrelated), and photometric light units` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Shaders/ShadersInclude/pbrDirectLightingFunctions.fx, checked 2026-12-01) - unity: builtin — `HDRP Lit and Lighting pipeline (follows Moving Frostbite to PBR: physical light units, renormalized DisneyDiffuse, height-correlated Smith GGX)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl, checked 2026-12-01) — HDRP lighting and BSDF follow Lagarde and de Rousiers' Frostbite PBR model. ## Dataflow - Inputs: material-params, normals, irradiance-probes - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Frostbite PBR spheres: dielectric and gold, roughness sweep (glsl-fragment; rendered 2026-11-29) ```json { "ROUGH_MIN": 0.08 } ``` ```glsl // Frostbite-style PBR: GGX + height-correlated Smith visibility + Burley diffuse with the energy-conserving // bias/factor. Top row dielectric, bottom row gold metal, roughness 0.08 -> 1.0 left to right. const float ROUGH_MIN = 0.08; const vec3 ALBEDO = vec3(0.75, 0.12, 0.1); const vec3 METAL_F0 = vec3(1.0, 0.77, 0.34); const vec3 L_DIR = vec3(0.5, 0.7, 0.6); vec3 env(vec3 d) { vec3 c = mix(vec3(0.12, 0.1, 0.1), vec3(0.4, 0.55, 0.85), smoothstep(-0.3, 0.8, d.y)); return c + vec3(3.0) * pow(max(dot(d, normalize(L_DIR)), 0.0), 50.0); } float visSmith(float nl, float nv, float a) { float a2 = a * a; float gv = nl * sqrt((-nv * a2 + nv) * nv + a2); float gl = nv * sqrt((-nl * a2 + nl) * nl + a2); return 0.5 / max(gv + gl, 1e-4); } vec3 shade(vec3 n, vec3 v, float rough, float metal) { vec3 l = normalize(L_DIR); vec3 h = normalize(v + l); float nl = clamp(dot(n, l), 1e-3, 1.0), nv = max(dot(n, v), 1e-3); float nh = clamp(dot(n, h), 0.0, 1.0), lh = clamp(dot(l, h), 0.0, 1.0); float a = rough * rough; float d = nh * nh * (a * a - 1.0) + 1.0; float D = a * a / (3.14159 * d * d); vec3 f0 = mix(vec3(0.04), METAL_F0, metal); vec3 F = f0 + (1.0 - f0) * pow(1.0 - lh, 5.0); vec3 spec = D * visSmith(nl, nv, a) * F; float eb = mix(0.0, 0.5, rough), ef = mix(1.0, 1.0 / 1.51, rough); float fd90 = eb + 2.0 * lh * lh * rough; float fd = (1.0 + (fd90 - 1.0) * pow(1.0 - nl, 5.0)) * (1.0 + (fd90 - 1.0) * pow(1.0 - nv, 5.0)) * ef; vec3 diff = (1.0 - metal) * ALBEDO * fd / 3.14159; vec3 amb = env(n) * ALBEDO * (1.0 - metal) * 0.5; vec3 fr = f0 + (max(vec3(1.0 - rough), f0) - f0) * pow(1.0 - nv, 5.0); amb += env(reflect(-v, n)) * fr * (1.0 - 0.5 * rough); return (diff + spec) * nl * 3.14159 * 1.4 + amb; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -1.6)); vec3 col = env(rd) * 0.35; float best = 1e9; for (int j = 0; j < 2; j++) for (int i = 0; i < 5; i++) { vec3 c = vec3((float(i) - 2.0) * 0.5, j == 0 ? 0.28 : -0.28, 0.0); vec3 oc = ro - c; float b = dot(oc, rd); float hh = b * b - dot(oc, oc) + 0.23 * 0.23; if (hh < 0.0) continue; float t = -b - sqrt(hh); if (t > 0.0 && t < best) { best = t; vec3 n = normalize(ro + rd * t - c); col = shade(n, -rd, mix(ROUGH_MIN, 1.0, float(i) / 4.0), j == 0 ? 0.0 : 1.0); } } col = col / (1.0 + col); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) ## Sources 1. [primary] Sébastien Lagarde, Charles de Rousiers Moving Frostbite to Physically Based Rendering. SIGGRAPH 2014 course. https://seblagarde.wordpress.com/wp-content/uploads/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Frostbite physically based rendering." https://texelatlas.vercel.app/t/frostbite-pbr/ (accessed 2026-12-01). --- id: "froxel-volumetric-fog" title: "Froxel Volumetric Fog" aliases: [frustum-aligned voxel fog, volumetric fog] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [desktop-gpu, webgpu, unreal, unity] year_introduced: 2014 inputs: [depth, volume-density, visibility-mask] outputs: [radiance, volume-density] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Wronski" url: "https://texelatlas.vercel.app/t/froxel-volumetric-fog/" sources_verified_at: "2026-11-29" --- # Froxel Volumetric Fog (Wronski) > Scatter light into a low-resolution 3D grid that follows the camera frustum, then integrate front to back to get in-scattering and transmittance for each pixel from a single texture fetch. ## Reach for it when - need light shafts and fog that react to lights - real-time volumetric fog in a game - fog should be lit by many lights and shadowed - cheap participating media with temporal accumulation ## How it works The view frustum is cut into a 3D texture (typically 160x90x64 or similar) with exponentially spaced depth slices, so each cell is a froxel. A compute pass writes extinction and albedo per froxel from fog volumes, height falloff and particle density. A second pass loops over lights, evaluating each light's contribution at the froxel centre with its shadow map or cascades and a phase function, and temporally jitters the sample position and blends with the previous frame to hide the low resolution. A final pass integrates along depth, storing accumulated scattered light and transmittance per slice. Opaque and transparent surfaces then fetch the volume at their view depth and apply scattered plus transmittance times surface colour. Because lighting is separated from integration, many lights and shadows are cheap. ## When to use it Choose it for dense, local, light-reactive fog and god-ray effects in a deferred or forward+ engine where you need shadowed light shafts from many lights, particles contributing density, and consistent fog on transparents. Prefer [Exponential Height Fog](https://texelatlas.vercel.app/t/exponential-height-fog.md) when only an analytic haze is needed. Prefer [Screen-space Volumetric Light Scattering (God Rays)](https://texelatlas.vercel.app/t/volumetric-light-scattering-god-rays.md) for a single sun with a screen-space trick. Prefer [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) per pixel for a few hero volumes where froxel resolution is insufficient. ## Cost medium — Cost scales with grid size and number of shadowed lights; the paper's grid is small and tuned for console budgets. Measured GPU Weight: 335.86× baseline (extreme) — 11.0497 ms median / 11.169 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 349.35× baseline (extreme) — 5.5547 ms median (1.99× faster on L4). Ampere A100 scaling: 201× baseline (extreme) — 5.7887 ms median (1.91× faster on A100). ## Failure modes - Temporal ghosting trailing behind moving lights and density - Blocky or flickering light shafts when the froxel resolution is too low for thin shadow casters - Depth-slice banding near the camera with linear slices, or loss of detail far away with exponential slices - Fog leaks across thin geometry because the froxel integrates across the full cell - Edge halos on foreground objects when applied at low resolution without depth-aware upsampling ## Engine support - blender: builtin — `EEVEE Volumetrics evaluates participating media on a frustum-aligned 3D froxel grid in eevee_volume.cc` (evidence: https://github.com/blender/blender/blob/main/source/blender/draw/engines/eevee/eevee_volume.cc, checked 2026-12-01) - godot: builtin — `Environment.volumetric_fog_enabled = true (plus FogVolume nodes)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) — Forward+ only. - unity: builtin — `Volume > Add Override > Fog > Enable Volumetric Fog; Local Volumetric Fog` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Volumetric-Lighting.md, checked 2026-12-01) — HDRP only (froxel-based). URP volumetric fog is not in Unity 6.3. - unreal: builtin — `Exponential Height Fog actor > Volumetric Fog checkbox` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/volumetric-fog-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, volume-density, visibility-mask - Outputs: radiance, volume-density - Platforms: desktop-gpu, webgpu, unreal, unity ## Presets ### Froxel volumetric fog — exponential depth-slice in-scattering with Henyey-Greenstein shafts (glsl-fragment; rendered 2026-11-30) ```json { "DENSITY": 0.18, "ANISOTROPY": 0.72, "FROXEL_SLICES": 36, "SCATTER_GAIN": 3.2 } ``` ```glsl const float DENSITY = 0.18; // P const float ANISOTROPY = 0.72; // P const int FROXEL_SLICES = 36; // P const float SCATTER_GAIN = 3.2; // P 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); } // Dark vaulted hall with tall right-side colonnade windows letting diagonal sunbeams enter float mapScene(vec3 p) { float floorD = p.y + 1.3; float leftWall = p.x + 2.4; float backWall = p.z + 11.5; vec3 q = p; q.z = mod(q.z + 1.5, 3.0) - 1.5; // Right colonnade wall with tall vertical window slits float colWall = sdBox(vec3(p.x - 1.55, p.y - 0.35, q.z), vec3(0.28, 2.0, 0.58)); float lintel = sdBox(vec3(p.x - 1.55, p.y - 2.15, p.z + 5.0), vec3(0.32, 0.45, 9.0)); float roof = sdBox(vec3(p.x + 0.5, p.y - 2.35, p.z + 5.0), vec3(2.2, 0.25, 9.0)); float plinth = sdBox(p - vec3(-0.35, -0.82, -3.8), vec3(0.45, 0.48, 0.45)); float d = min(floorD, min(leftWall, backWall)); d = min(d, min(colWall, min(lintel, min(roof, plinth)))); return d; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.004, 0.0); return normalize(vec3( mapScene(p + e.xyy) - mapScene(p - e.xyy), mapScene(p + e.yxy) - mapScene(p - e.yxy), mapScene(p + e.yyx) - mapScene(p - e.yyx) )); } float shadowVisibility(vec3 ro, vec3 rd) { float t = 0.06; for (int i = 0; i < 22; i++) { vec3 pos = ro + rd * t; if (pos.x > 2.05) return 1.0; float d = mapScene(pos); if (d < 0.012) return 0.0; t += max(d, 0.07); if (t > 6.5) break; } return 1.0; } float hgPhase(float cosT, float g) { float g2 = g * g; return (1.0 - g2) / (12.56637 * pow(max(1.0 + g2 - 2.0 * g * cosT, 0.001), 1.5)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(-0.65, -0.1, 1.5); vec3 rd = normalize(vec3(uv.x + 0.16, uv.y + 0.04, -1.18)); float sunSweep = 0.25 * sin(iTime * 0.45); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { vec2 m = iMouse.xy / iResolution.xy * 2.0 - 1.0; sunSweep = m.x * 0.85; } vec3 sunDir = normalize(vec3(0.84, 0.46, -0.45 + sunSweep)); vec3 sunCol = vec3(1.0, 0.78, 0.42); float tHit = 0.1; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapScene(ro + rd * tHit); if (d < 0.004) { hit = true; break; } tHit += d; if (tHit > 15.0) break; } vec3 surf = vec3(1.8, 1.45, 0.95) * (0.4 + 0.8 * pow(max(dot(rd, sunDir), 0.0), 3.0)); if (hit) { vec3 p = ro + rd * tHit; vec3 n = calcNormal(p); float vis = shadowVisibility(p + n * 0.03, sunDir); float nl = max(dot(n, sunDir), 0.0); vec2 tile = floor(p.xz * 1.3); float chk = mod(tile.x + tile.y, 2.0); vec3 albedo = mix(vec3(0.11, 0.13, 0.17), vec3(0.24, 0.23, 0.22), 0.5 + 0.5 * chk); surf = albedo * (vec3(0.03, 0.05, 0.09) + sunCol * nl * vis * 5.5); } // Frustum-aligned exponential depth-slice froxel integration int slices = clamp(FROXEL_SLICES, 8, 64); float zNear = 0.35, zFar = min(tHit, 13.5); float ratio = max(zFar / zNear, 1.01); float jitter = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453); float cosT = dot(rd, sunDir); float phase = hgPhase(cosT, clamp(ANISOTROPY, -0.85, 0.90)); float densBase = max(DENSITY, 0.0); float gain = max(SCATTER_GAIN, 0.0); vec3 inScatter = vec3(0.0); float transmittance = 1.0; float prevZ = zNear; for (int i = 0; i < 64; i++) { if (i >= slices) break; float f = (float(i) + 1.0) / float(slices); float currZ = zNear * pow(ratio, f); float dt = currZ - prevZ; float zMid = mix(prevZ, currZ, jitter); vec3 wp = ro + rd * zMid; float hFog = exp(-max(wp.y + 1.2, 0.0) * 0.32); float sigma = densBase * (0.35 + 0.9 * hFog); float lit = shadowVisibility(wp, sunDir); vec3 scatter = (sunCol * lit * (0.35 + phase * 18.0) + vec3(0.008, 0.016, 0.035)) * gain * sigma; float stepTrans = exp(-sigma * dt * 0.45); inScatter += transmittance * scatter * (1.0 - stepTrans) / max(sigma, 1e-4); transmittance *= stepTrans; prevZ = currZ; if (transmittance < 0.02) break; } vec3 col = surf * transmittance + inScatter; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) ## Combines with - [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md): Aerial perspective volume and fog froxels can share one front-to-back integration. - [Henyey-Greenstein Phase Function](https://texelatlas.vercel.app/t/henyey-greenstein-phase-function.md): Phase function applied when each light is scattered into a froxel. ## Combination ideas - [Fog that flows through generated caves](https://texelatlas.vercel.app/ideas/drafts-through-generated-dungeons/) - [Scale-consistent volumetric fog shafts through Mip-Splatting scenes](https://texelatlas.vercel.app/ideas/mip-splat-froxel-fog-occlusion/) - [Fog shafts that do not flicker](https://texelatlas.vercel.app/ideas/prefiltered-shadows-in-fog/) ## Sources 1. [primary] Bartlomiej Wronski Volumetric Fog: Unified compute shader based solution to atmospheric scattering. SIGGRAPH 2014. https://advances.realtimerendering.com/s2014/wronski/bwronski_volumetric_fog_siggraph2014.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Froxel Volumetric Fog." https://texelatlas.vercel.app/t/froxel-volumetric-fog/ (accessed 2026-12-01). --- id: "fxaa" title: "FXAA" aliases: [Fast Approximate Anti-Aliasing] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2009 inputs: [ldr-image] outputs: [ldr-image] style: "both" dynamic: "both" cost: "cheap" authority: "Lottes" url: "https://texelatlas.vercel.app/t/fxaa/" sources_verified_at: "2026-11-29" --- # FXAA (Lottes) > A single-pass post filter that finds edges from luma contrast, estimates their orientation and blends pixels along the edge normal; cheap and shader-only, but it also softens interior texture detail. ## Reach for it when - jagged edges but no budget for heavy antialiasing - mobile or webgl needs the cheapest edge smoothing - msaa isn't available in my deferred pipeline - need quick post-process edge softening ## How it works FXAA runs on the final LDR image with no depth or geometry. It computes luma for a pixel and its four neighbours, skips the pixel if local contrast is below a threshold, then classifies the edge as horizontal or vertical from second-derivative-like sums over the 3x3 neighbourhood. It moves half a pixel toward the stronger gradient side, searches along the edge in both directions until the luma profile departs from the edge average, and uses the endpoints to compute a subpixel offset. The final sample is a bilinear fetch shifted perpendicular to the edge, which blends the edge with the other side. A separate subpixel-aliasing term lowpasses isolated bright pixels. Quality presets differ in the length of the edge search. ## When to use it Choose it when you need the cheapest possible AA on mobile or WebGL, or as a fallback for forward-rendered scenes without motion vectors. Prefer [SMAA](https://texelatlas.vercel.app/t/smaa.md) when you can afford three passes and want sharper results with proper corner handling. Prefer [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) when shading aliasing and subpixel detail dominate and motion vectors exist. ## Cost cheap — Single full-screen pass with a handful of texture fetches; the cheapest AA in this index (qualitative). Measured GPU Weight: 11.42× baseline (moderate) — 0.3758 ms median / 0.3902 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.51× baseline (moderate) — 0.1353 ms median (2.78× faster on L4). Ampere A100 scaling: 7.82× baseline (moderate) — 0.2253 ms median (1.67× faster on A100). ## Failure modes - Global softening of text and fine textures because it cannot distinguish edges from detail - Rounded corners and wobbly near-horizontal lines from the heuristic edge search - No help with subpixel geometry or temporal shimmer - Must run after tonemapping, otherwise HDR highlights alias unfiltered ## Engine support - babylonjs: builtin — `pipeline.fxaaEnabled = true (DefaultRenderingPipeline) or new BABYLON.FxaaPostProcess` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.pure.ts, checked 2026-12-01) - godot: builtin — `Viewport.screen_space_aa = Viewport.SCREEN_SPACE_AA_FXAA` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Viewport.xml, checked 2026-12-01) - threejs: official — `import { fxaa } from 'three/addons/tsl/display/FXAANode.js' (WebGL: FXAAPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/FXAANode.js, checked 2026-12-01) - unity: builtin — `URP: Camera > Rendering > Anti-aliasing = Fast Approximate Anti-aliasing (FXAA)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/FXAA3_11.hlsl, checked 2026-12-01) — URP and HDRP. - unreal: builtin — `Project Settings > Rendering > Default Settings > Anti-Aliasing Method = FXAA` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/anti-aliasing-and-upscaling-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Left: aliased frame. Right: FXAA, luma-gradient direction and two blurred taps along the edge (glsl-fragment; rendered 2026-11-29) ```json { "DREDMUL": 0.125, "DREDMIN": 0.0078 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 scnA(vec2 px){vec2 p=(px-256.)/512.; vec3 c=vec3(.93,.92,.88); float s=fract((p.x*.866+p.y*.5)*11.);c=mix(c,vec3(.1,.12,.2),step(s,.18)*step(abs(p.y+p.x*.3),.38)); float d=length(p-vec2(.0,.0));c=mix(c,vec3(.85,.25,.2),step(abs(d-.2),.02)); c=mix(c,vec3(.1,.5,.4),step(length(p-vec2(-.25,.28)),.1)); c=mix(c,vec3(.1),step(abs(p.x-.2),.004)*step(abs(p.y-.1),.3)); return c;} const float DREDMUL=0.125; // P const float DREDMIN=0.0078; // P vec3 T(vec2 f){return scnA(floor(f)+.5);} vec3 Tb(vec2 f){vec2 g=f-.5,i=floor(g),w=g-i; return mix(mix(T(i+.5),T(i+vec2(1.5,.5)),w.x),mix(T(i+vec2(.5,1.5)),T(i+1.5),w.x),w.y);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=T(fragCoord); if(R){ vec2 f=floor(fragCoord)+.5; vec3 nw=T(f+vec2(-1.,-1.)),ne=T(f+vec2(1.,-1.)),sw=T(f+vec2(-1.,1.)),se=T(f+vec2(1.,1.)),m=T(f); float a=lum(nw),b=lum(ne),c=lum(sw),d=lum(se),e=lum(m); float lo=min(e,min(min(a,b),min(c,d))),hi=max(e,max(max(a,b),max(c,d))); vec2 dir=vec2(-((a+b)-(c+d)),(a+c)-(b+d)); float red=max((a+b+c+d)*.25*DREDMUL,DREDMIN); dir=clamp(dir/(min(abs(dir.x),abs(dir.y))+red),-8.,8.); vec3 r1=.5*(Tb(f+dir*(1./3.-.5))+Tb(f+dir*(2./3.-.5))); vec3 r2=r1*.5+.25*(Tb(f-dir*.5)+Tb(f+dir*.5)); float lb=lum(r2);col=(lbhi)?r1:r2; } if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Lineage - extended by [SMAA](https://texelatlas.vercel.app/t/smaa.md) ## Combines with - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): FXAA can clean up the output of a TAA resolve on frames where history was rejected. ## Sources 1. [primary] Timothy Lottes FXAA. NVIDIA white paper. https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "FXAA." https://texelatlas.vercel.app/t/fxaa/ (accessed 2026-12-01). --- id: "gamengen" title: "GameNGen diffusion game engine" aliases: [GameNGen, Diffusion Models Are Real-Time Game Engines] domain: "genai" stage: "generation" realtime: "realtime" platforms: [python, cuda] year_introduced: 2024 inputs: [ldr-image, animation] outputs: [ldr-image] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Valevski et al., 2024" url: "https://texelatlas.vercel.app/t/gamengen/" sources_verified_at: "2026-11-29" --- # GameNGen diffusion game engine (Valevski et al., 2024) > A diffusion model that acts as a game engine: it predicts the next frame from past frames and player actions, running interactively on one accelerator without explicit geometry, physics or game logic. ## Reach for it when - can a neural network replace the game engine rendering loop - want a playable neural simulation from recorded gameplay - predict next frame from player actions with diffusion - need real time interactive video generation - generated game world forgets what was behind me ## How it works Training happens in two phases. First, an RL agent plays the target game (Doom in the paper) while frames, actions and the game state are recorded as a large dataset. Second, a pretrained text-to-image latent diffusion model is fine-tuned to generate the next frame conditioned on a window of previous frames and actions; action tokens replace the text conditioning, and previous frames enter as latent channels concatenated to the noisy latent. To stop autoregressive drift over long play, the training adds noise augmentation to the context frames with the noise level provided to the model, so it learns to correct accumulated errors. At inference only a few denoising steps are used, and the decoder is fine-tuned to improve small details such as the heads-up display. The result plays like the original at interactive rates but has no persistent world state beyond its context window. ## When to use it Study it when exploring neural simulators and world models as an alternative to a hand-built renderer, for games that already have lots of recorded play. Prefer [Genie 2 and Genie 3 (interactive world models)](https://texelatlas.vercel.app/t/genie-world-models.md) for learned, action-controllable environments from unlabelled video, [Marble (World Labs multimodal world model)](https://texelatlas.vercel.app/t/marble-world-model.md) for persistent 3D generation, and a conventional engine plus [Neural Radiance Caching](https://texelatlas.vercel.app/t/neural-radiance-caching.md)-style learned shading when determinism and editing matter. ## Cost heavy — The paper reports about 20 frames per second on a single TPU (an accelerator, not a consumer GPU); model size and denoising steps set the budget. Measured GPU Weight: 13.08× baseline (moderate) — 0.4303 ms median / 0.4472 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 11.77× baseline (moderate) — 0.1871 ms median (2.3× faster on L4). Ampere A100 scaling: 8.3× baseline (moderate) — 0.2391 ms median (1.8× faster on A100). ## Failure modes - Loss of long-term consistency: items, enemy positions and map layout drift beyond the context window - Accumulating autoregressive error causes colour drift, blur or hallucination over long sessions - No exact game rules: health, ammo and physics are approximated visually - Training needs a large, action-labelled gameplay dataset per game - Latency and hardware requirements far above the original engine ## Dataflow - Inputs: ldr-image, animation - Outputs: ldr-image - Platforms: python, cuda ## Presets ### GameNGen — DDIM denoising latent frame (left) vs synthesized playable corridor engine (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_NOISE_LVL": 0.45, "P_WALK_SPEED": 1, "P_NEON_GAIN": 1.15, "P_SPLIT": 0.46 } ``` ```glsl const float P_NOISE_LVL = 0.45; // P Diffusion Noise [0.05, 0.95, 0.02] const float P_WALK_SPEED = 1.0; // P Corridor Speed [0.0, 2.5, 0.05] const float P_NEON_GAIN = 1.15; // P Corridor Glow [0.3, 2.0, 0.05] const float P_SPLIT = 0.46; // P Latent / Frame Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // First-person sci-fi/retro FPS corridor SDF for neural game engine synthesis vec2 mapCorridor(vec3 p) { float floorD = p.y + 0.88; float ceilD = 0.92 - p.y; float wallD = 1.22 - abs(p.x); // Repeating structural ribs along Z float rz = mod(p.z + 1.0, 2.0) - 1.0; float ribX = 1.02 - abs(p.x); float ribZ = abs(rz) - 0.14; float rib = max(ribX, ribZ); float d = min(min(floorD, ceilD), min(wallD, rib)); float mat = 1.0; if (abs(d - floorD) < 0.002) mat = 2.0; else if (abs(d - rib) < 0.002) mat = 3.0; else if (abs(d - ceilD) < 0.002) mat = 4.0; return vec2(d, mat); } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapCorridor(p + e.xyy).x - mapCorridor(p - e.xyy).x, mapCorridor(p + e.yxy).x - mapCorridor(p - e.yxy).x, mapCorridor(p + e.yyx).x - mapCorridor(p - e.yyx).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float screenY = fragCoord.y / max(iResolution.y, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float noiseLvl = clamp(P_NOISE_LVL, 0.05, 0.95); float speed = max(P_WALK_SPEED, 0.0); float neon = clamp(P_NEON_GAIN, 0.2, 2.2); // Subtle head-bob walking motion float bob = sin(iTime * 5.2 * speed) * 0.03; vec3 ro = vec3(sin(iTime * 0.65 * speed) * 0.18, bob, -iTime * 2.1 * speed); vec3 rd = normalize(vec3(uv.x, uv.y, -1.25)); vec3 col = vec3(0.04, 0.03, 0.05); float t = 0.05; vec2 hit = vec2(1e5, 0.0); for (int i = 0; i < 52; i++) { vec2 h = mapCorridor(ro + rd * t); if (h.x < 0.004) { hit = vec2(t, h.y); break; } t += h.x; if (t > 14.0) break; } if (hit.x < 1e4) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); // Periodic ceiling/wall corridor lights float lz = floor((p.z + 1.0) / 2.0) * 2.0; vec3 lPos = vec3(0.0, 0.72, lz); vec3 toL = lPos - p; float dL = length(toL); vec3 lDir = toL / max(dL, 1e-4); float atten = 1.0 / (1.0 + 0.38 * dL * dL); float diff = max(dot(n, lDir), 0.0); vec3 alb = vec3(0.32, 0.30, 0.28); if (hit.y > 1.5 && hit.y < 2.5) { // Industrial tiled metal floor vec2 tile = step(0.06, fract(p.xz * 1.5)); alb = mix(vec3(0.16, 0.18, 0.22), vec3(0.34, 0.36, 0.40), tile.x * tile.y); } else if (hit.y > 2.5 && hit.y < 3.5) { alb = vec3(0.46, 0.24, 0.18); } else if (hit.y > 3.5) { alb = vec3(0.22, 0.24, 0.28); } vec3 lightCol = mix(vec3(1.0, 0.62, 0.26), vec3(0.24, 0.88, 1.0), 0.5 + 0.5 * sin(lz * 0.7)); col = alb * (0.14 + 1.25 * diff * atten * lightCol); // Emissive wall strip + ceiling strip float strip = exp(-abs(p.y + 0.10) * 24.0) * step(0.85, abs(n.x)); float ceilGlow = exp(-abs(p.x) * 6.0) * step(0.85, -n.y) * smoothstep(0.35, 0.10, abs(mod(p.z + 1.0, 2.0) - 1.0)); col += lightCol * (strip * 0.85 + ceilGlow * 1.45) * neon; // Distance atmospheric haze float fog = 1.0 - exp(-hit.x * 0.16); col = mix(col, vec3(0.08, 0.05, 0.09), fog); } // Retro FPS HUD bar along bottom + center crosshair if (screenY < 0.14) { float bar = smoothstep(0.14, 0.132, screenY); vec3 hud = vec3(0.12, 0.13, 0.16); float hp = step(abs(screenX - 0.25), 0.10) * step(abs(screenY - 0.07), 0.025); float ammo = step(abs(screenX - 0.75), 0.10) * step(abs(screenY - 0.07), 0.025); hud = mix(hud, vec3(0.95, 0.24, 0.18), hp); hud = mix(hud, vec3(0.96, 0.78, 0.22), ammo); col = mix(col, hud, bar * 0.92); } float crossH = smoothstep(0.005, 0.001, abs(uv.y)) * smoothstep(0.032, 0.024, abs(uv.x)); float crossV = smoothstep(0.005, 0.001, abs(uv.x)) * smoothstep(0.032, 0.024, abs(uv.y)); col = mix(col, vec3(0.95, 0.98, 0.85), max(crossH, crossV) * 0.75); // Left side: Intermediate DDIM diffusion denoising step (noisy latent patches + denoising scan) if (screenX < split) { vec2 patchCell = floor(fragCoord / 6.0); float n1 = hash21(patchCell + floor(iTime * 12.0) * 0.31); float n2 = hash21(patchCell * 1.37 + floor(iTime * 12.0) * 0.19); float n3 = hash21(patchCell * 1.91 + floor(iTime * 12.0) * 0.43); vec3 epsNoise = vec3(n1, n2, n3) - 0.5; float alphaBar = 1.0 - noiseLvl * 0.72; col = sqrt(alphaBar) * col + sqrt(1.0 - alphaBar) * (0.45 + epsNoise * 0.95); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Genie 2 and Genie 3 (interactive world models)](https://texelatlas.vercel.app/t/genie-world-models.md): Latent-action models can supply control labels that a GameNGen-style next-frame diffusion model would otherwise need from game logs. ## Sources 1. [primary] Dani Valevski, Yaniv Leviathan, Moab Arar, Shlomi Fruchter (2024) Diffusion Models Are Real-Time Game Engines. arXiv preprint (cs.LG). https://arxiv.org/abs/2408.14837 (verified via arxiv on 2026-11-29) 2. [tutorial] Valevski, Leviathan, Arar, Fruchter Diffusion Models Are Real-Time Game Engines (project page). gamengen.github.io. https://gamengen.github.io/ (verified via http on 2026-11-29) ## Cite this entry Texel. "GameNGen diffusion game engine." https://texelatlas.vercel.app/t/gamengen/ (accessed 2026-12-01). --- id: "gaussian-splatting-3dgs" title: "3D Gaussian Splatting" aliases: [3DGS, Gaussian splatting] domain: "capture" stage: "capture" realtime: "realtime" platforms: [cuda, webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2023 inputs: [photos, camera-poses, point-cloud] outputs: [gaussians] style: "photoreal" dynamic: "static" cost: "medium" authority: "Kerbl et al., 2023" url: "https://texelatlas.vercel.app/t/gaussian-splatting-3dgs/" sources_verified_at: "2026-11-29" --- # 3D Gaussian Splatting (Kerbl et al., 2023) > Models a scene as millions of anisotropic 3D Gaussians with opacity and spherical-harmonic colour, optimised from photos and rendered by fast depth-sorted tile rasterisation. ## Reach for it when - view captured scene in real time from new angles - nerf renders too slowly for interactive viewing - turn photos into a fast photoreal viewable scene - need novel view synthesis at high frame rates - photoreal capture playable on a gpu ## How it works Initialise one Gaussian per sparse SfM point. Each carries a position, a covariance stored as scale and rotation, an opacity and spherical-harmonic coefficients for view-dependent colour. To render, each Gaussian is projected to a 2D ellipse using the local affine approximation of the perspective transform, binned into 16x16 screen tiles, sorted by depth per tile, and alpha-composited front to back. The whole pipeline is differentiable, so photometric L1 plus D-SSIM loss trains all parameters with Adam. During optimisation an adaptive density control step clones Gaussians in under-reconstructed regions, splits large ones, prunes near-transparent ones, and periodically resets opacity to shed floaters. The result renders at real-time rates at 1080p on a desktop GPU. ## When to use it Choose it for real-time novel-view viewing of captured scenes. Prefer [Mip-Splatting](https://texelatlas.vercel.app/t/mip-splatting.md) when you need zoom-stable rendering without aliasing, [2D Gaussian Splatting](https://texelatlas.vercel.app/t/2d-gaussian-splatting.md) when you need accurate surfaces, [StopThePop (Sorted Gaussian Splatting)](https://texelatlas.vercel.app/t/stopthepop.md) for popping-free sorting, and [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) or [NeuS](https://texelatlas.vercel.app/t/neus.md) if the deliverable is a mesh. Prefer [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md) when a CUDA-only, volumetric field is acceptable. ## Cost medium — Training takes tens of minutes on one desktop GPU for typical scenes; rendering is real time but memory scales with Gaussian count (millions per scene). Measured GPU Weight: 214.53× baseline (extreme) — 6.6504 ms median / 6.7367 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 197.4× baseline (extreme) — 3.1386 ms median (2.12× faster on L4). Ampere A100 scaling: 151.47× baseline (extreme) — 4.3622 ms median (1.52× faster on A100). ## Failure modes - Popping and view-inconsistency from per-tile depth sorting of overlapping Gaussians - Aliasing and dilation when zooming out or changing resolution relative to training - Floaters and needle-like Gaussians in poorly observed regions - Geometry is not a clean surface, so meshing and relighting are unreliable - Large VRAM and file sizes, often hundreds of MB per scene ## Engine support - babylonjs: builtin — `BABYLON.GaussianSplattingMesh (loads .splat/.ply/.spz via SceneLoader)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/GaussianSplatting/gaussianSplattingMesh.pure.ts, checked 2026-12-01) - blender: plugin — `Blender add-on: 3DGS Render by KIRI Engine` (evidence: https://github.com/Kiri-Innovation/3dgs-render-blender-addon, checked 2026-12-01) — Imports and renders trained splats; training is external. - godot: plugin — `Install the gdgs addon (ReconWorldLab/godot-gaussian-splatting)` (evidence: https://github.com/ReconWorldLab/godot-gaussian-splatting, checked 2026-12-01) — Third-party compute-based 3DGS renderer. - threejs: official — `import { GaussianSplat } from 'three/addons/objects/GaussianSplat.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/objects/GaussianSplat.js, checked 2026-12-01) — WebGPURenderer. - unity: plugin — `git url: https://github.com/aras-p/UnityGaussianSplatting.git?path=/package` (evidence: https://github.com/aras-p/UnityGaussianSplatting, checked 2026-12-01) — Third-party renderer (aras-p), URP, HDRP and built-in. - unreal: plugin — `Gaussian Splatting for Unreal Engine plugin (third-party)` (evidence: https://github.com/Italink/GaussianSplattingForUnrealEngine, checked 2026-12-01) ## Dataflow - Inputs: photos, camera-poses, point-cloud - Outputs: gaussians - Platforms: cuda, webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Official 3DGS training hyper-parameters (json-params; parameter preset) ```json { "iterations": 30000, "sh_degree": 3, "position_lr_init": 0.00016, "position_lr_final": 0.0000016, "feature_lr": 0.0025, "opacity_lr": 0.025, "scaling_lr": 0.005, "rotation_lr": 0.001, "percent_dense": 0.01, "lambda_dssim": 0.2, "densification_interval": 100, "opacity_reset_interval": 3000, "densify_from_iter": 500, "densify_until_iter": 15000, "densify_grad_threshold": 0.0002 } ``` Attribution: Defaults from graphdeco-inria/gaussian-splatting (Inria/MPI Gaussian-Splatting licence, non-commercial research use; see repo LICENSE.md).; basis: 2 ### 3D Gaussian Splatting — 2-sigma EWA covariance ellipses (left) vs sorted SH alpha-blended splats (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SPLAT_SCALE": 1, "P_SH_GAIN": 1, "P_ROT_SPEED": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_SPLAT_SCALE = 1.0; // P Gaussian Scale [0.45, 1.8, 0.05] const float P_SH_GAIN = 1.0; // P View-Dep SH [0.0, 2.0, 0.05] const float P_ROT_SPEED = 0.75; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Ellipses / 3DGS Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // 3D anisotropic Gaussian primitive i arranged on a sculpted twisted torus-knot + luminous core void getGaussian(int idx, float spin, float scaleG, out vec3 posView, out vec3 axisU, out vec3 axisV, out vec3 shBase, out vec3 shDir, out float opac) { float fi = float(idx); float N = 32.0; float u = fi / N * 6.2831853; // 24 anisotropic elongated Gaussians tracing a 3D trefoil ribbon + 8 inner core splats vec3 pObj, tDir, nDir; vec2 radii; if (idx < 24) { float a = fi / 24.0 * 6.2831853; float rMaj = 0.56 + 0.14 * cos(a * 3.0); pObj = vec3(cos(a) * rMaj, 0.24 * sin(a * 3.0), sin(a) * rMaj); tDir = normalize(vec3(-sin(a) * rMaj, 0.72 * cos(a * 3.0), cos(a) * rMaj)); nDir = normalize(cross(tDir, vec3(0.0, 1.0, 0.15))); radii = vec2(0.18, 0.068) * scaleG; shBase = 0.52 + 0.45 * cos(a + vec3(0.0, 2.094, 4.188)); shDir = vec3(0.35, 0.18, -0.28); opac = 0.76; } else { float b = float(idx - 24) / 8.0 * 6.2831853; pObj = vec3(cos(b) * 0.20, sin(b * 2.0) * 0.16, sin(b) * 0.20); tDir = normalize(vec3(-sin(b), cos(b), cos(b))); nDir = normalize(cross(tDir, vec3(0.1, 0.9, 0.2))); radii = vec2(0.14, 0.10) * scaleG; shBase = vec3(0.95, 0.78, 0.34); shDir = vec3(-0.22, 0.32, 0.25); opac = 0.84; } // Camera view transform W (orbit around object) pObj.xz = rot2(spin * 0.65) * pObj.xz; pObj.yz = rot2(0.45) * pObj.yz; tDir.xz = rot2(spin * 0.65) * tDir.xz; tDir.yz = rot2(0.45) * tDir.yz; nDir.xz = rot2(spin * 0.65) * nDir.xz; nDir.yz = rot2(0.45) * nDir.yz; posView = pObj + vec3(0.0, 0.0, -2.35); axisU = tDir * radii.x; axisV = nDir * radii.y; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isBlended = screenX >= split; float scaleG = clamp(P_SPLAT_SCALE, 0.35, 2.0); float shGain = clamp(P_SH_GAIN, 0.0, 2.2); float spin = iTime * max(P_ROT_SPEED, 0.0); float focal = 1.55; vec3 bg = mix(vec3(0.022, 0.030, 0.052), vec3(0.062, 0.082, 0.132), smoothstep(-0.55, 0.55, uv.y)); // Subtle perspective reference grid vec3 rd = normalize(vec3(uv, -focal)); if (rd.y < -0.02) { float tf = (-0.65) / rd.y; if (tf > 0.0 && tf < 14.0) { vec3 pf = vec3(0.0, 0.0, 0.0) + rd * tf; vec2 gf = abs(fract(pf.xz * 2.0 - 0.5) - 0.5); float gl = smoothstep(0.04, 0.008, min(gf.x, gf.y)) * exp(-tf * 0.28); bg += vec3(0.08, 0.14, 0.24) * gl; } } // Approximate depth-ordered front-to-back compositing using 4 depth buckets (exact 3DGS front-to-back T_i update) vec3 accumCol = vec3(0.0); float trans = 1.0; float ellipseRing = 0.0; float centerDot = 0.0; for (int pass = 0; pass < 4; pass++) { float zLo = -1.45 - float(pass) * 0.45; float zHi = zLo - 0.45; for (int i = 0; i < 32; i++) { vec3 pV, aU, aV, sh0, sh1; float opac; getGaussian(i, spin, scaleG, pV, aU, aV, sh0, sh1, opac); if (pass == 0 && pV.z <= zHi) continue; if (pass == 1 && (pV.z > zLo || pV.z <= zHi)) continue; if (pass == 2 && (pV.z > zLo || pV.z <= zHi)) continue; if (pass == 3 && pV.z > zLo) continue; float invZ = 1.0 / max(-pV.z, 0.25); vec2 mean2D = pV.xy * (focal * invZ); // EWA perspective Jacobian J = focal/z * [1, 0, -x/z; 0, 1, -y/z] projecting 3D covariance axes -> 2D! vec2 jU = (aU.xy - pV.xy * (aU.z * invZ)) * (focal * invZ); vec2 jV = (aV.xy - pV.xy * (aV.z * invZ)) * (focal * invZ); // 2x2 projected covariance Sigma_2D = jU*jU^T + jV*jV^T + low-pass eps*I float eps = 0.00018; float s00 = jU.x * jU.x + jV.x * jV.x + eps; float s01 = jU.x * jU.y + jV.x * jV.y; float s11 = jU.y * jU.y + jV.y * jV.y + eps; float det = max(s00 * s11 - s01 * s01, 1e-8); float invDet = 1.0 / det; // Mahalanobis squared distance d^T Sigma_2D^-1 d vec2 d = uv - mean2D; float m2 = (s11 * d.x * d.x - 2.0 * s01 * d.x * d.y + s00 * d.y * d.y) * invDet; if (m2 > 9.5) continue; // Evaluate spherical-harmonic view-dependent color c(d) = SH0 + SH1 * dot(viewDir, axis) vec3 viewDir = normalize(pV); vec3 splatCol = clamp(sh0 + sh1 * dot(viewDir, normalize(aU)) * shGain + 0.16 * shGain * viewDir.y, 0.04, 1.8); float g = exp(-0.5 * m2); float alpha = clamp(opac * g, 0.0, 0.98); if (!isBlended) { // Left: visualize 1.8-sigma EWA projected covariance ellipses & Gaussian means float ring = smoothstep(0.28, 0.06, abs(sqrt(max(m2, 0.0)) - 1.65)); ellipseRing = max(ellipseRing, ring * trans); centerDot = max(centerDot, smoothstep(0.014, 0.005, length(d))); accumCol += trans * (alpha * 0.42) * splatCol; trans *= (1.0 - alpha * 0.42); } else { // Right: full 3DGS front-to-back alpha compositing C += T * alpha * c; T *= (1 - alpha) accumCol += trans * alpha * splatCol; trans *= (1.0 - alpha); } if (trans < 0.01) break; } } vec3 col = accumCol + trans * bg; if (!isBlended) { col += vec3(0.32, 0.92, 1.0) * ellipseRing * 0.72; col = mix(col, vec3(1.0, 0.92, 0.44), centerDot * 0.88); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [2D Gaussian Splatting](https://texelatlas.vercel.app/t/2d-gaussian-splatting.md) - extended by [3D Gaussian Ray Tracing (3DGRT)](https://texelatlas.vercel.app/t/3d-gaussian-ray-tracing.md) - extended by [3DGUT (Unscented Transform Gaussian Splatting)](https://texelatlas.vercel.app/t/3dgut.md) - extended by [4D Gaussian Splatting](https://texelatlas.vercel.app/t/4d-gaussian-splatting.md) - extended by [DreamGaussian](https://texelatlas.vercel.app/t/dreamgaussian.md) - extended by [Hierarchical Binary-Tree 3DGS LOD & Paged Streaming](https://texelatlas.vercel.app/t/hierarchical-binary-tree-3dgs-lod.md) - extended by [Mip-Splatting](https://texelatlas.vercel.app/t/mip-splatting.md) - extended by [Self-Organizing Gaussians (SOG) 2D Codebook Image Compression](https://texelatlas.vercel.app/t/self-organizing-gaussians-compression.md) - extended by [4× MSAA Sort-Free Stochastic Gaussian Splatting](https://texelatlas.vercel.app/t/sort-free-stochastic-splatting-msaa.md) - extended by [StopThePop (Sorted Gaussian Splatting)](https://texelatlas.vercel.app/t/stopthepop.md) ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): COLMAP supplies the posed cameras and sparse points that seed the Gaussians. - [Segment Anything (SAM)](https://texelatlas.vercel.app/t/segment-anything.md): SAM masks can be lifted to label or isolate Gaussians for editing. ## Combination ideas - [Far LOD for captured splat objects](https://texelatlas.vercel.app/ideas/splat-captures-impostor-lod/) - [Splats as world-anchored brush strokes](https://texelatlas.vercel.app/ideas/splats-as-brush-strokes/) - [Sort-free neural-denoised LOD Gaussian splats](https://texelatlas.vercel.app/ideas/stochastic-lod-neural-splats/) - [Freeze a generated world into splats](https://texelatlas.vercel.app/ideas/world-model-walkthrough-to-splats/) ## Sources 1. [primary] Bernhard Kerbl, Georgios Kopanas, Thomas Leimkuehler, George Drettakis (2023) 3D Gaussian Splatting for Real-Time Radiance Field Rendering. ACM Transactions on Graphics. https://doi.org/10.1145/3592433 (verified via crossref on 2026-11-29) 2. [primary] Bernhard Kerbl, Georgios Kopanas, Thomas Leimkühler, George Drettakis (2023) 3D Gaussian Splatting for Real-Time Radiance Field Rendering. ACM Transactions on Graphics, volume 42(4), July 2023. https://arxiv.org/abs/2308.04079 (verified via arxiv on 2026-11-29) 3. [implementation] graphdeco-inria (2023) graphdeco-inria/gaussian-splatting. https://github.com/graphdeco-inria/gaussian-splatting License: NOASSERTION. (verified via github on 2026-11-29) 4. [tutorial] Kerbl, Kopanas, Leimkuehler, Drettakis 3D Gaussian Splatting for Real-Time Radiance Field Rendering (project page). repo-sam.inria.fr. https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting (verified via http on 2026-11-29) ## Cite this entry Texel. "3D Gaussian Splatting." https://texelatlas.vercel.app/t/gaussian-splatting-3dgs/ (accessed 2026-12-01). --- id: "genie-world-models" title: "Genie 2 and Genie 3 (interactive world models)" aliases: [Genie 3] domain: "genai" stage: "generation" realtime: "realtime" platforms: [cuda] year_introduced: 2024 inputs: [text-prompt, ldr-image] outputs: [ldr-image] style: "both" dynamic: "dynamic" cost: "heavy" authority: "DeepMind" url: "https://texelatlas.vercel.app/t/genie-world-models/" sources_verified_at: "2026-11-29" --- # Genie 2 and Genie 3 (interactive world models) (DeepMind) > Google DeepMind's foundation world models that generate an interactive, navigable environment frame by frame from a prompt, conditioned on the user's actions rather than producing a 3D asset. ## Reach for it when - generate playable interactive worlds from a prompt - want a game environment that responds to keyboard input - create interactive scenes from an image without an engine - learned simulator that predicts next frame from actions ## How it works The model is an autoregressive video generator conditioned on actions (keyboard or mouse). Each new frame is produced from previous frames and the latest action, so the "world" exists only as the model's memory of recent frames, not as an explicit mesh or splat set. DeepMind's official posts describe Genie 2 as producing action-controllable 3D-like worlds for agents, and Genie 3 as raising resolution and real-time interactivity with some consistency over minutes. There is no exportable geometry and no public weights or paper as of the sources cited here; both are described only on DeepMind's blog. ## When to use it Choose it as a reference when you care about interactive world simulation for agents or play, not renderer-compatible assets. Prefer [Marble (World Labs multimodal world model)](https://texelatlas.vercel.app/t/marble-world-model.md) or [WorldGen (text/image to 3D scene)](https://texelatlas.vercel.app/t/worldgen.md) when you need exportable 3D scene data, and [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) or [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) for single assets. ## Cost heavy — Server-side generation on accelerators; no public performance data beyond the official posts. Measured GPU Weight: 70.65× baseline (extreme) — 2.3243 ms median / 2.4424 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 63.28× baseline (extreme) — 1.0061 ms median (2.31× faster on L4). Ampere A100 scaling: 52.77× baseline (heavy) — 1.5199 ms median (1.53× faster on A100). ## Failure modes - No explicit 3D state, so layout can drift or contradict itself after returning to a place - Limited interaction horizon and physics fidelity - Not available as an open model or exportable asset - Text rendering and fine detail are unreliable ## Dataflow - Inputs: text-prompt, ldr-image - Outputs: ldr-image - Platforms: cuda ## Presets ### Genie World Models — latent action-token state grid (left) vs playable 3D world rollout (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_STEER": 0.45, "P_WALK_SPEED": 1, "P_TOKEN_VIS": 0.85, "P_SPLIT": 0.44 } ``` ```glsl const float P_STEER = 0.45; // P Latent Action Steer [-1.0, 1.0, 0.05] const float P_WALK_SPEED = 1.0; // P Rollout Speed [0.0, 2.5, 0.05] const float P_TOKEN_VIS = 0.85; // P Token Grid Vis [0.0, 1.5, 0.05] const float P_SPLIT = 0.44; // P Latent / World Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y ); } // Stylised walkable 3D plateau/valley generated autoregressively along camera rollout float terrainH(vec2 xz) { float valley = smoothstep(0.5, 3.2, abs(xz.x - sin(xz.y * 0.25) * 1.4)); float hills = vnoise(xz * 0.45) * 1.4 + vnoise(xz * 1.15) * 0.42; float terraces = floor(hills * 3.5) / 3.5 * 0.35 + hills * 0.65; return terraces * valley - 0.55; } vec3 terrainN(vec2 xz) { float e = 0.06; return normalize(vec3( terrainH(xz - vec2(e, 0.0)) - terrainH(xz + vec2(e, 0.0)), 2.0 * e, terrainH(xz - vec2(0.0, e)) - terrainH(xz + vec2(0.0, e)) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float steer = clamp(P_STEER, -1.0, 1.0); float speed = max(P_WALK_SPEED, 0.0); float tokVis = clamp(P_TOKEN_VIS, 0.0, 1.5); float zPos = -iTime * 1.45 * speed; float xPos = sin(zPos * 0.25) * 1.2 + steer * 0.55; vec3 ro = vec3(xPos, 0.52, zPos); vec3 rd = normalize(vec3(uv.x + steer * 0.18, uv.y - 0.12, -1.32)); // Golden-hour navigable world sky vec3 sunDir = normalize(vec3(0.45, 0.38, -0.80)); vec3 sky = mix(vec3(0.95, 0.66, 0.42), vec3(0.18, 0.42, 0.78), smoothstep(-0.08, 0.48, rd.y)); sky += vec3(1.0, 0.88, 0.62) * pow(max(dot(rd, sunDir), 0.0), 18.0) * 0.85; vec3 col = sky; // March terrain heightfield float t = 0.2; bool hit = false; for (int i = 0; i < 52; i++) { vec3 p = ro + rd * t; float h = terrainH(p.xz); float d = p.y - h; if (d < 0.015) { hit = true; break; } t += max(d * 0.55, 0.05); if (t > 16.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = terrainN(p.xz); float diff = max(dot(n, sunDir), 0.0); float grass = smoothstep(0.65, 0.90, n.y); vec3 rockCol = vec3(0.42, 0.34, 0.32); vec3 meadow = mix(vec3(0.18, 0.56, 0.30), vec3(0.46, 0.68, 0.26), vnoise(p.xz * 1.4)); vec3 pathMask = vec3(smoothstep(0.75, 0.35, abs(p.x - sin(p.z * 0.25) * 1.4))); vec3 alb = mix(rockCol, meadow, grass); alb = mix(alb, vec3(0.78, 0.68, 0.52), pathMask.x * 0.75); vec3 lit = alb * (0.28 + 0.88 * diff) + vec3(0.22, 0.38, 0.62) * 0.22 * (0.5 + 0.5 * n.y); // Atmospheric distance fog float fog = 1.0 - exp(-t * 0.095); col = mix(lit, sky, fog); } // Left side: Discrete spacetime latent token grid & action-conditioned flow pulse if (screenX < split) { vec2 cell = floor(fragCoord / 16.0); vec2 cf = fract(fragCoord / 16.0); float grid = smoothstep(0.10, 0.02, min(cf.x, cf.y)); float tokHash = hash21(cell + floor(iTime * 3.0) * 0.13); // Quantize color into latent token patch aesthetic vec3 qCol = floor(col * 5.0 + 0.5) / 5.0; vec3 tokTint = mix(vec3(0.14, 0.82, 0.94), vec3(0.98, 0.58, 0.18), tokHash); col = mix(col, mix(qCol, tokTint, 0.24), 0.78); col += tokTint * grid * 0.35 * tokVis; // Latent action impulse chevron in lower-left vec2 aUV = uv - vec2(-0.34, -0.34); float ring = exp(-abs(length(aUV) - 0.085) * 48.0); float arrow = smoothstep(0.035, 0.01, length(aUV - vec2(steer * 0.045, 0.025))); col += vec3(0.24, 0.96, 0.88) * (ring + arrow * 1.2) * tokVis; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Freeze a generated world into splats](https://texelatlas.vercel.app/ideas/world-model-walkthrough-to-splats/) ## Sources 1. [primary] Google DeepMind Genie 3: A new frontier for world models. deepmind.google. https://deepmind.google/blog/genie-3-a-new-frontier-for-world-models (verified via http on 2026-11-29) 2. [primary] Google DeepMind Genie 2: A large-scale foundation world model. deepmind.google. https://deepmind.google/blog/genie-2-a-large-scale-foundation-world-model (verified via http on 2026-11-29) ## Cite this entry Texel. "Genie 2 and Genie 3 (interactive world models)." https://texelatlas.vercel.app/t/genie-world-models/ (accessed 2026-12-01). --- id: "geometry-clipmaps-terrain" title: "Geometry clipmaps" aliases: [clipmap terrain, geometry clipmap] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal] year_introduced: 2004 inputs: [heightfield] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "Losasso & Hoppe, 2004" url: "https://texelatlas.vercel.app/t/geometry-clipmaps-terrain/" sources_verified_at: "2026-11-29" --- # Geometry clipmaps (Losasso & Hoppe, 2004) > Cache terrain heights as a stack of nested, camera-centered regular grids of equal size but doubling spacing, updated incrementally as the viewer moves. ## Reach for it when - terrain mesh needs lod around the camera - huge heightmap rendering with constant triangle count - terrain vertices pop when lod changes - open world ground detail near viewer only - avoid cpu quadtree traversal for terrain ## How it works Each LOD level is a square window of the heightmap of fixed vertex count; level k covers twice the world extent of level k-1 at half the sampling density. All levels are centered on the viewer, so detail falls off roughly with distance and the triangle count is nearly constant. As the camera moves, each level shifts in toroidal fashion: only the strip of new rows and columns entering the window is uploaded or generated, the rest is reused. Because the grids are regular, they are drawn as instanced ring meshes with heights fetched in the vertex shader. Seams between levels are hidden by blending heights over a transition band at each ring's outer edge (geomorphing) and by stitching or skirt triangles; the original also compresses the height data and synthesizes extra detail at the finest levels. ## When to use it Choose it for very large heightfield terrain viewed from near the ground, when you want constant triangle budget and no CPU quadtree traversal. Prefer [CDLOD terrain](https://texelatlas.vercel.app/t/cdlod-terrain.md) when you want adaptive detail per quadtree node (flat areas cost less) and smoother per-node morphing. Prefer [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) when terrain is arbitrary mesh rather than a heightfield, and use [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) style data as the height source. ## Cost cheap — Fixed vertex budget per frame, mostly vertex-texture fetch cost; update cost is proportional to camera movement. Measured GPU Weight: 181.9× baseline (extreme) — 5.6388 ms median / 5.739 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 163.19× baseline (extreme) — 2.5948 ms median (2.17× faster on L4). Ampere A100 scaling: 132.66× baseline (extreme) — 3.8205 ms median (1.48× faster on A100). ## Failure modes - Cannot represent overhangs, caves or cliffs, since terrain is a single-valued height function - Vertices swim or visibly pop when the clip window snaps and morphing is too short - Cracks between rings if stitching and morph ranges disagree - Uniform detail in flat regions wastes triangles compared with adaptive schemes - Normals computed from coarse levels look faceted unless a separate normal map is used ## Engine support - godot: plugin — `Install Terrain3D (GDExtension)` (evidence: https://github.com/TokisanGames/Terrain3D/blob/main/doc/docs/introduction.md, checked 2026-12-01) — Third-party Terrain3D uses a geometry clipmap mesh. ## Dataflow - Inputs: heightfield - Outputs: mesh - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal ## Presets ### Geometry Clipmaps — nested doubling LOD rings & morph bands (left) vs blended alpine terrain (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RING_SCALE": 1, "P_WIRE_GAIN": 0.9, "P_CAM_SPEED": 0.7, "P_SPLIT": 0.5 } ``` ```glsl const float P_RING_SCALE = 1.0; // P Clipmap Scale [0.5, 2.0, 0.05] const float P_WIRE_GAIN = 0.90; // P Grid Wireframe [0.0, 1.5, 0.05] const float P_CAM_SPEED = 0.70; // P Flyover Speed [0.0, 2.0, 0.05] const float P_SPLIT = 0.50; // P LOD Rings / Lit Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float noise2(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } // Multi-octave ridged alpine terrain heightfield float terrainH(vec2 p) { float h = 0.0; float amp = 0.55; float freq = 0.45; for (int i = 0; i < 5; i++) { float n = 1.0 - abs(noise2(p * freq) * 2.0 - 1.0); h += n * n * amp; p = mat2(0.8, 0.6, -0.6, 0.8) * p; freq *= 2.05; amp *= 0.48; } return h - 0.58; } vec3 terrainNormal(vec2 p) { float e = 0.025; float hx = terrainH(p + vec2(e, 0.0)) - terrainH(p - vec2(e, 0.0)); float hz = terrainH(p + vec2(0.0, e)) - terrainH(p - vec2(0.0, e)); return normalize(vec3(-hx, 2.0 * e, -hz)); } vec3 lodPalette(float lvl) { if (lvl < 0.5) return vec3(0.18, 0.90, 0.82); // L0 finest if (lvl < 1.5) return vec3(0.28, 0.72, 0.98); // L1 2x if (lvl < 2.5) return vec3(0.96, 0.78, 0.22); // L2 4x if (lvl < 3.5) return vec3(0.96, 0.44, 0.20); // L3 8x return vec3(0.76, 0.30, 0.88); // L4 16x } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isLit = screenX >= split; float ringScale = clamp(P_RING_SCALE, 0.45, 2.2); float wireGain = clamp(P_WIRE_GAIN, 0.0, 1.5); float flyZ = -iTime * max(P_CAM_SPEED, 0.0) * 1.1; vec3 ro = vec3(0.0, 1.85, 2.2 + flyZ); vec3 ta = vec3(0.0, 0.15, -3.2 + flyZ); vec3 fwd = normalize(ta - ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.45 + right * uv.x + up * uv.y); // Horizon sky vec3 skyCol = mix(vec3(0.46, 0.62, 0.82), vec3(0.10, 0.20, 0.42), smoothstep(-0.08, 0.55, rd.y)); vec3 col = skyCol; // Raymarch heightfield terrain float t = 0.2; bool hit = false; for (int i = 0; i < 80; i++) { vec3 p = ro + rd * t; float h = terrainH(p.xz); float d = p.y - h; if (d < 0.008 * t) { hit = true; break; } t += max(d * 0.55, 0.035); if (t > 26.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = terrainNormal(p.xz); vec3 lDir = normalize(vec3(0.62, 0.68, 0.40)); float diff = max(dot(n, lDir), 0.0); // Clipmap center anchored on camera XZ footprint: Chebyshev L-infinity square rings! vec2 rel = abs(p.xz - ro.xz) / ringScale; float cheb = max(rel.x, rel.y); float contLvl = max(log2(max(cheb * 0.48, 0.5)), 0.0); float lvl = floor(contLvl); float ringFrac = fract(contLvl); // Doubling grid cell spacing per clipmap level: 2^lvl * baseSpacing float spacing = 0.18 * pow(2.0, min(lvl, 5.0)) * ringScale; vec2 gUV = p.xz / spacing; vec2 gf = abs(fract(gUV - 0.5) - 0.5); float wire = smoothstep(0.075, 0.015, min(gf.x, gf.y)); // Diagonal triangle split edge inside each clipmap quad float diag = smoothstep(0.06, 0.012, abs(fract(gUV.x + gUV.y) - 0.5)); wire = max(wire, diag * 0.45); // Highlight concentric square ring transition morph band (outer 15% of each ring) float morphBand = smoothstep(0.82, 0.96, ringFrac); float ringSeam = smoothstep(0.04, 0.008, abs(ringFrac - 0.98)); // Natural alpine coloring (valley forest -> rock -> snow peaks) float snow = smoothstep(0.08, 0.36, p.y) * smoothstep(0.45, 0.78, n.y); vec3 ground = mix(vec3(0.16, 0.28, 0.18), vec3(0.38, 0.35, 0.32), smoothstep(-0.22, 0.16, p.y)); ground = mix(ground, vec3(0.92, 0.95, 0.98), snow); vec3 litTerrain = ground * (0.24 + 0.92 * diff) + vec3(0.12, 0.20, 0.34) * (0.5 + 0.5 * n.y) * 0.28; if (!isLit) { // Left: nested clipmap LOD rings color-coded with doubling grid resolution & morph bands vec3 ringCol = lodPalette(lvl); vec3 nextCol = lodPalette(lvl + 1.0); vec3 lodMix = mix(ringCol, nextCol, morphBand * 0.65); col = mix(litTerrain * 0.42, lodMix * (0.35 + 0.75 * diff), 0.74); col = mix(col, vec3(0.03, 0.05, 0.09), wire * 0.68 * min(wireGain, 1.2)); col = mix(col, vec3(1.0, 0.98, 0.85), ringSeam * 0.85); } else { // Right: seamless shaded terrain with subtle morph-band wireframe hint col = litTerrain; col = mix(col, vec3(0.10, 0.16, 0.24), wire * 0.12 * min(wireGain, 1.0)); } float fog = 1.0 - exp(-t * t * 0.0045); col = mix(col, skyCol, clamp(fog, 0.0, 0.88)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [CDLOD terrain](https://texelatlas.vercel.app/t/cdlod-terrain.md) ## Combines with - [Sparse virtual texturing](https://texelatlas.vercel.app/t/virtual-texturing.md): Clipmap rings give a camera-centered mesh whose color and normals come from a streamed virtual texture. ## Combination ideas - [Mesh-shader amplified geometry clipmaps with zero CPU draw calls](https://texelatlas.vercel.app/ideas/clipmap-terrain-mesh-shaders/) ## Sources 1. [primary] Frank Losasso, Hugues Hoppe (2004) Geometry clipmaps. ACM Transactions on Graphics. https://doi.org/10.1145/1015706.1015799 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Geometry clipmaps." https://texelatlas.vercel.app/t/geometry-clipmaps-terrain/ (accessed 2026-12-01). --- id: "geometry-images" title: "Geometry Images" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, desktop-gpu] year_introduced: 2002 inputs: [mesh] outputs: [texture, uv-atlas] style: "both" dynamic: "static" cost: "interactive" authority: "Gu et al., 2002" url: "https://texelatlas.vercel.app/t/geometry-images/" sources_verified_at: "2026-11-29" --- # Geometry Images (Gu et al., 2002) > Cuts a mesh into a single disc, parametrizes it onto a square, and stores x, y, z as three colour channels of an ordinary image. The geometry becomes a texture that GPUs filter, compress and tessellate naturally. ## Reach for it when - want mesh geometry stored as a regular texture - need lod through mipmaps on geometry - neural surface needs a regular grid representation - stream and compress meshes like ordinary images ## How it works Choose a cut graph that turns the surface into a topological disc, e.g. by shortest paths between handles after removing triangles until only a tree remains. Parametrize the disc onto a square so that the boundary maps to the border with matching sample points on the two sides of every seam. Then resample the surface on a regular grid in parameter space and store positions in a floating-point image, along with normals in a second one. The grid structure gives a mesh implicitly (connect neighbours), with no index buffer. Because the seams are consistent, 'zippering' the border samples makes the surface watertight. Standard image tools apply: mipmaps give levels of detail, compression gives mesh compression, and displacement-map-like editing works on the geometry directly. ## When to use it Choose it for regular, GPU-friendly meshes: LOD via mipmaps, streaming, compression research and neural surface representations that need a regular grid. Prefer [xatlas](https://texelatlas.vercel.app/t/xatlas.md) or [Least Squares Conformal Maps](https://texelatlas.vercel.app/t/lscm-uv-unwrapping.md) when you want a conventional UV atlas for texturing a retained mesh, and [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md) for LODs of an irregular mesh. ## Cost interactive — Parametrization and resampling are offline; rendering is a regular grid draw call. Measured GPU Weight: 13.87× baseline (moderate) — 0.43 ms median / 0.4543 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.1× baseline (moderate) — 0.1606 ms median (2.68× faster on L4). Ampere A100 scaling: 8.1× baseline (moderate) — 0.2333 ms median (1.84× faster on A100). ## Failure modes - Seam artifacts and cracks where mip levels or filtering break the boundary correspondence - Stretching in the parameter domain undersamples regions of high detail - Single-chart parametrization of high-genus shapes is hard and distorts heavily - Bilinear filtering of positions mixes across seams unless borders are handled ## Dataflow - Inputs: mesh - Outputs: texture, uv-atlas - Platforms: cpu, webgl2, webgpu, desktop-gpu ## Presets ### Geometry Images — 2D square RGB=[X,Y,Z] atlas (left) vs reconstructed 3D surface & cut seam (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GRID_RES": 12, "P_SEAM_VIS": 1, "P_ROT_SPEED": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_GRID_RES = 12.0; // P Regular Grid N [6.0, 24.0, 2.0] const float P_SEAM_VIS = 1.0; // P Cut Seam Highlight [0.0, 1.5, 0.05] const float P_ROT_SPEED = 0.75; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P 2D Atlas / 3D Mesh [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Octahedral geometry-image bijection: 2D square [0,1]^2 <-> 3D unit sphere S^2 (Gu-Gortler-Hoppe!) vec3 octDecode(vec2 uv01) { vec2 f = uv01 * 2.0 - 1.0; vec3 n = vec3(f.x, f.y, 1.0 - abs(f.x) - abs(f.y)); float t = max(-n.z, 0.0); n.x += (n.x >= 0.0) ? -t : t; n.y += (n.y >= 0.0) ? -t : t; return normalize(n); } vec2 octEncode(vec3 n) { n /= max(abs(n.x) + abs(n.y) + abs(n.z), 1e-5); if (n.z < 0.0) { vec2 sgn = vec2((n.x >= 0.0) ? 1.0 : -1.0, (n.y >= 0.0) ? 1.0 : -1.0); n.xy = (1.0 - abs(n.yx)) * sgn; } return n.xy * 0.5 + 0.5; } // Sculpted genus-0 organic displacement encoded into the Geometry Image RGB = (x, y, z) vec3 evalSurfacePoint(vec3 dir) { float disp = 0.68 + 0.14 * sin(dir.x * 4.2) * cos(dir.y * 4.2) + 0.09 * sin(dir.z * 5.5); return dir * disp; } float mapShape(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.65) * q.xz; q.yz = rot2(0.35) * q.yz; float r = length(q); vec3 d = q / max(r, 1e-5); float targetR = length(evalSurfacePoint(d)); return (r - targetR) * 0.72; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapShape(p + e.xyy, spin) - mapShape(p - e.xyy, spin), mapShape(p + e.yxy, spin) - mapShape(p - e.yxy, spin), mapShape(p + e.yyx, spin) - mapShape(p - e.yyx, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 uv01 = fragCoord / max(iResolution.xy, vec2(1.0)); float split = clamp(P_SPLIT, 0.0, 1.0); bool is3D = uv01.x >= split; float gridN = clamp(floor(P_GRID_RES + 0.5), 6.0, 26.0); float seamVis = clamp(P_SEAM_VIS, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 col = mix(vec3(0.026, 0.036, 0.058), vec3(0.068, 0.088, 0.138), smoothstep(-0.55, 0.55, uv.y)); if (!is3D) { // Left: 2D square Geometry Image texture where RGB encodes 3D vertex positions (x, y, z) float panelCX = split * 0.5 * (iResolution.x / max(iResolution.y, 1.0)); vec2 rel = vec2((uv01.x - split * 0.5) * (iResolution.x / max(iResolution.y, 1.0)), uv.y); vec2 gUV = rel / 0.72 + 0.5; if (gUV.x >= 0.0 && gUV.x <= 1.0 && gUV.y >= 0.0 && gUV.y <= 1.0) { vec3 dir = octDecode(gUV); vec3 pos3D = evalSurfacePoint(dir); // Map XYZ coordinates [-0.9, 0.9] -> [0, 1] RGB channels (exact Geometry Image encoding) vec3 rgbPos = clamp(pos3D * 0.55 + 0.5, 0.0, 1.0); // Regular 2D square sampling lattice (completely regular topology!) vec2 gf = abs(fract(gUV * gridN - 0.5) - 0.5); float gWire = smoothstep(0.055, 0.012, min(gf.x, gf.y)); col = mix(rgbPos, vec3(0.04, 0.06, 0.10), gWire * 0.52); // Outer cut-seam boundary (the 4 edges of the square glue symmetrically onto the 3D cut tree!) float bdr = min(min(gUV.x, 1.0 - gUV.x), min(gUV.y, 1.0 - gUV.y)); col = mix(col, vec3(1.0, 0.88, 0.28), smoothstep(0.024, 0.005, bdr) * min(seamVis, 1.0)); } } else { // Right: Reconstructed 3D surface sampled from the regular 2D Geometry Image grid vec2 rightUV = vec2((uv01.x - (split + 1.0) * 0.5) * (iResolution.x / max(iResolution.y, 1.0)), uv.y); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(rightUV, -1.52)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapShape(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 7.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.65) * objP.xz; objP.yz = rot2(0.35) * objP.yz; vec2 gUV = octEncode(normalize(objP)); // Regular quad mesh reconstructed directly from the 2D Geometry Image pixels vec2 gf = abs(fract(gUV * gridN - 0.5) - 0.5); float gWire = smoothstep(0.060, 0.014, min(gf.x, gf.y)); // Highlight the 3D cut seam (where gUV hits 0 or 1 boundary of the square) float bdr = min(min(gUV.x, 1.0 - gUV.x), min(gUV.y, 1.0 - gUV.y)); float seamLine = smoothstep(0.025, 0.005, bdr); vec3 l1 = normalize(vec3(0.58, 0.82, 0.55)); float diff = max(dot(n, l1), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 42.0); vec3 rgbPos = clamp(objP * 0.55 + 0.5, 0.0, 1.0); vec3 alb = mix(vec3(0.76, 0.80, 0.86), rgbPos, 0.62); col = alb * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.45; col = mix(col, vec3(0.04, 0.07, 0.12), gWire * 0.55); col = mix(col, vec3(1.0, 0.88, 0.28), seamLine * 0.92 * min(seamVis, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(uv01.x - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Least Squares Conformal Maps](https://texelatlas.vercel.app/t/lscm-uv-unwrapping.md): A conformal or stretch-minimising parametrization places the chart on the square. ## Sources 1. [primary] Xianfeng Gu, Steven J. Gortler, Hugues Hoppe (2002) Geometry images. Proceedings of the 29th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/566570.566589 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Geometry Images." https://texelatlas.vercel.app/t/geometry-images/ (accessed 2026-12-01). --- id: "gerstner-waves" title: "Gerstner (Trochoidal) Waves" aliases: [trochoidal waves, sum of Gerstner waves] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2004 inputs: [material-params] outputs: [heightfield, normals, mesh] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Finch & Worlds" url: "https://texelatlas.vercel.app/t/gerstner-waves/" sources_verified_at: "2026-11-29" --- # Gerstner (Trochoidal) Waves (Finch & Worlds) > An analytic water surface made of a few sine-like waves in which each point also moves in a circle, yielding sharp crests and flat troughs with a closed-form displacement and normal. ## Reach for it when - need cheap stylised water with sharp crests - boats need a height query on the cpu for buoyancy - mobile water that still looks like moving waves - sine waves look too round and smooth - a few controllable swell directions on a lake ## How it works Each wave i has a direction D, wavenumber k, amplitude A and a speed from the deep-water dispersion relation, omega = sqrt(g k). For a point at rest position x0 and time t, the phase is theta = k D.x0 - omega t. The surface point is x0 minus D times Q A cos(theta) horizontally and A sin(theta) vertically, where Q is a steepness factor; the sum over waves gives the final surface. The horizontal term pulls vertices toward the crests, and keeping the sum of Q k A below one prevents loops. Normals come analytically from the partial derivatives, so shading needs no finite differences. The displacement is applied in a vertex shader on a dense grid, or the field can be ray-marched in a fragment shader by inverting the horizontal term with a few fixed-point iterations. ## When to use it Choose it for stylised or mobile water, for a handful of directional swells on a lake or harbour, and wherever the height at a point must be cheaply and exactly queryable on the CPU for buoyancy. Prefer [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md) when you need a realistic spectrum with hundreds of waves and tiling statistics. Prefer [Shallow Water Equations (Height-field Water)](https://texelatlas.vercel.app/t/shallow-water-equations.md) for ripples and wakes that react to objects. Use [JONSWAP Wave Spectrum](https://texelatlas.vercel.app/t/jonswap-spectrum.md) to choose wave amplitudes and wavelengths statistically. ## Cost cheap — A few sine and cosine evaluations per wave per vertex or pixel. Measured GPU Weight: 98.07× baseline (extreme) — 3.2266 ms median / 3.289 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 77.86× baseline (extreme) — 1.238 ms median (2.61× faster on L4). Ampere A100 scaling: 65.59× baseline (extreme) — 1.889 ms median (1.71× faster on A100). ## Failure modes - Self-intersecting loops at crests when the steepness sum exceeds one - Visible regular repetition: with few waves the pattern looks periodic and synthetic - Height at a world position requires inverting the horizontal displacement, otherwise buoyancy queries drift - No foam, breaking or shoreline interaction on its own - Aliasing and shimmering for short wavelengths when mesh density is low - Mesh vertex density must be high or the displaced geometry shows faceting at the crests ## Engine support - unity: official — `Package Manager > Shader Graph > Samples > Production Ready Shaders > Water (Gerstner)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Production-Ready-Water.md, checked 2026-12-01) — Shader Graph sample content (Gerstner subgraphs); not the HDRP Water System. - unreal: official — `Enable the Water plugin; Water Body Ocean/Lake/River with a Water Waves asset (default uses Gerstner waves)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/simulating-waves-using-the-water-waves-asset-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params - Outputs: heightfield, normals, mesh - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Four Gerstner waves, ray-marched ocean (glsl-fragment; rendered 2026-11-29) ```json { "waves": 4, "steepness": 0.7, "gravity": 9.81 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Sum of four Gerstner waves, heightfield ray-march, Fresnel sky reflection. const float GRAV = 9.81; const float STEEP = 0.7; const vec3 SUN_DIR = vec3(-0.45, 0.28, -0.85); // each wave: direction.xy, amplitude, wavelength const vec4 WAVES[4] = vec4[4]( vec4(0.96, 0.28, 0.55, 16.0), vec4(0.60, -0.80, 0.30, 9.0), vec4(-0.30, 0.95, 0.16, 5.0), vec4(0.85, 0.52, 0.07, 2.6)); vec3 sky(vec3 rd) { float t = clamp(rd.y, 0.0, 1.0); vec3 c = mix(vec3(0.75, 0.82, 0.90), vec3(0.18, 0.37, 0.70), pow(t, 0.5)); float s = max(dot(rd, normalize(SUN_DIR)), 0.0); return c + vec3(1.0, 0.8, 0.5) * (pow(s, 600.0) * 6.0 + pow(s, 8.0) * 0.25); } // Gerstner displacement at rest position q. xy = horizontal offset, z = height. vec3 gerstner(vec2 q) { vec3 r = vec3(0.0); for (int i = 0; i < 4; i++) { vec2 d = normalize(WAVES[i].xy); float A = WAVES[i].z; float k = 6.2831853 / WAVES[i].w; float th = k * dot(d, q) - sqrt(GRAV * k) * iTime; float Q = STEEP / (k * A * 4.0); r.xy += d * (Q * A * cos(th)); r.z += A * sin(th); } return r; } // Height at world xz: undo the horizontal displacement with fixed-point iteration. float height(vec2 xz) { vec2 q = xz; for (int i = 0; i < 3; i++) q = xz - gerstner(q).xy; return gerstner(q).z; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 3.2, 0.0); vec3 rd = normalize(vec3(uv.x, uv.y - 0.22, -1.0)); vec3 col; float t = 0.0; bool hit = false; for (int i = 0; i < 90; i++) { vec3 p = ro + rd * t; float d = p.y - height(p.xz); if (d < 0.02 * (1.0 + t * 0.02)) { hit = true; break; } t += max(d * 0.6, 0.02); if (t > 250.0) break; } if (hit) { vec3 p = ro + rd * t; float e = 0.05 + t * 0.002; float h0 = height(p.xz); vec3 n = normalize(vec3(h0 - height(p.xz + vec2(e, 0.0)), e, h0 - height(p.xz + vec2(0.0, e)))); float cosT = clamp(dot(n, -rd), 0.0, 1.0); float F = 0.02 + 0.98 * pow(1.0 - cosT, 5.0); vec3 refl = sky(reflect(rd, n)); vec3 deep = vec3(0.01, 0.12, 0.17); vec3 shallow = vec3(0.06, 0.35, 0.38); vec3 body = mix(deep, shallow, clamp(0.5 + p.y * 0.8, 0.0, 1.0)); col = mix(body, refl, F); col = mix(col, sky(vec3(rd.x, 0.02, rd.z)), 1.0 - exp(-t * 0.006)); } else { col = sky(rd); } col = col / (1.0 + col); col = pow(col, vec3(1.0 / 2.2)); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; wave parameters are original sensible defaults ## Combines with - [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md): Gerstner swells provide large-scale controllable motion while the FFT adds fine, statistically correct detail. - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Surface normals from the analytic derivative drive the refracted light that makes caustics. ## Sources 1. [primary] Mark Finch, Cyan Worlds Effective Water Simulation from Physical Models. GPU Gems, 2004. https://developer.nvidia.com/gpugems/gpugems/part-i-natural-effects/chapter-1-effective-water-simulation-physical-models (verified via http on 2026-11-29) ## Cite this entry Texel. "Gerstner (Trochoidal) Waves." https://texelatlas.vercel.app/t/gerstner-waves/ (accessed 2026-12-01). --- id: "ggx-trowbridge-reitz" title: "GGX / Trowbridge-Reitz normal distribution" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2007 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Walter et al., 2007" url: "https://texelatlas.vercel.app/t/ggx-trowbridge-reitz/" sources_verified_at: "2026-11-29" --- # GGX / Trowbridge-Reitz normal distribution (Walter et al., 2007) > The microfacet normal distribution with a long, heavy tail, popularised for graphics by Walter et al. Its soft halo around the highlight matches measured materials well and it has closed-form visible-normal sampling, so it is the default D term in PBR. ## Reach for it when - highlights look plasticky with no long tail - need a physically based specular lobe for metals - specular falloff too sharp compared to real materials - match reflections of rough surfaces seen in photographs ## How it works GGX describes the density of microfacet normals with an ellipsoid-derived function: D(h) = a^2 / (pi * ((n.h)^2 (a^2 - 1) + 1)^2), where a = roughness^2 in the common remapping. Compared with Beckmann it falls off polynomially rather than exponentially, giving the characteristic bright core with a faint wide glow. Walter et al. introduced it to graphics (it is the Trowbridge-Reitz distribution from 1975 optics) in the context of rough refraction, and showed how to importance-sample it. In a renderer it appears as the D factor of a Cook-Torrance BRDF; pair it with the height-correlated Smith G for consistency. The anisotropic form replaces a with two axis-aligned roughnesses ax, ay. ## When to use it Choose it as the D term of any real-time or offline microfacet specular lobe; it is the de facto standard in glTF, Unreal, Filament and OpenPBR. Prefer plain Beckmann only to match legacy assets. For fabric or velvet, where highlights brighten at grazing angles, prefer [Charlie sheen (Estevez-Kulla)](https://texelatlas.vercel.app/t/charlie-sheen.md). For stretched highlights use [Anisotropic GGX](https://texelatlas.vercel.app/t/anisotropic-ggx.md). ## Cost cheap — One division and a few multiplies per light; the cost is dominated by the surrounding lighting, not D. Measured GPU Weight: 1.91× baseline (feather) — 0.0627 ms median / 0.0654 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.77× baseline (feather) — 0.0282 ms median (2.22× faster on L4). Ampere A100 scaling: 1.25× baseline (feather) — 0.0361 ms median (1.74× faster on A100). ## Failure modes - Very low roughness makes D numerically explode near the peak, so clamp roughness (about 0.03-0.045) or you get fireflies and aliased pinpoint highlights - Long tail can overpower thin dielectric looks, creating a milky halo on glossy plastics - Without specular antialiasing (toksvig-mipmapping, normal-distribution-filtering) normal-mapped surfaces shimmer - Single-scattering GGX darkens rough metals; compensate with kulla-conty-multiscatter ## Engine support - babylonjs: builtin — `BABYLON.PBRMaterial (GGX NDF is the default microfacet distribution)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Shaders/ShadersInclude/pbrBRDFFunctions.fx, checked 2026-12-01) - blender: builtin — `Principled BSDF > Distribution = GGX or Multiscatter GGX` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) - godot: builtin — `StandardMaterial3D default specular mode SPECULAR_SCHLICK_GGX` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: builtin — `MeshStandardMaterial / MeshPhysicalMaterial` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/functions/BSDF/D_GGX.js, checked 2026-12-01) - unity: builtin — `Lit shaders in URP and HDRP` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl, checked 2026-12-01) — URP and HDRP. - unreal: builtin — `Material > Shading Model = Default Lit / Substrate (GGX normal distribution driven by Roughness)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Aluminium, roughness 0.35 (three-material; rendered 2026-11-29) ```json { "color": "#f5f6f6", "roughness": 0.35, "metalness": 1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 2 ### Polished gold (three-material; rendered 2026-11-29) ```json { "color": "#ffe496", "roughness": 0.12, "metalness": 1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 2 ### GGX / Trowbridge-Reitz microfacet BRDF (WGSL) (webgpu-wgsl; WebGPU WGSL runtime) ```json { "ROUGHNESS": 0.28, "METALNESS": 0.85, "IOR": 1.5 } ``` ```wgsl // WebGPU WGSL fragment specimen: GGX NDF + Smith G2 + Schlick Fresnel const ROUGHNESS: f32 = 0.2800; // P const METALNESS: f32 = 0.8500; // P const IOR: f32 = 1.5000; // P fn d_ggx(nh: f32, a: f32) -> f32 { let a2 = a * a; let d = nh * nh * (a2 - 1.0) + 1.0; return a2 / (3.1415926 * d * d + 1e-5); } fn f_schlick(uVal: f32, f0: vec3f) -> vec3f { return f0 + (vec3f(1.0) - f0) * pow(clamp(1.0 - uVal, 0.0, 1.0), 5.0); } fn studio_env(d: vec3f) -> vec3f { let y = clamp(d.y * 0.5 + 0.5, 0.0, 1.0); let key = smoothstep(0.82, 0.96, dot(d, normalize(vec3f(0.55, 0.72, 0.42)))) * 2.6; let rim = smoothstep(0.80, 0.95, dot(d, normalize(vec3f(-0.72, 0.40, 0.56)))) * 1.4; return mix(vec3f(0.18, 0.19, 0.21), vec3f(0.82, 0.84, 0.86), pow(y, 1.2)) + vec3f(key + rim * 0.85); } @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f { let uv = (pos.xy - 0.5 * u.resolution) / u.resolution.y; let ro = vec3f(0.0, 0.12, 2.6); let rd = normalize(vec3f(uv.x, -uv.y, -1.45)); let b = dot(ro, rd); let c = dot(ro, ro) - 0.62; let h = b * b - c; if (h < 0.0) { let bg = mix(vec3f(0.86, 0.87, 0.85), vec3f(0.75, 0.76, 0.78), clamp(-uv.y + 0.5, 0.0, 1.0)); return vec4f(pow(bg, vec3f(1.0 / 2.2)), 1.0); } let p = ro + rd * (-b - sqrt(h)); let n = normalize(p); let v = -rd; let l = normalize(vec3f(cos(u.time * 0.4) * 0.75, 0.72, 0.62)); let hv = normalize(l + v); let nl = max(dot(n, l), 0.0); let nv = max(dot(n, v), 0.001); let nh = max(dot(n, hv), 0.0); let vh = max(dot(v, hv), 0.0); let base = vec3f(0.88, 0.71, 0.46); let f0s = pow((IOR - 1.0) / (IOR + 1.0), 2.0); let f0 = mix(vec3f(f0s), base, METALNESS); let a = max(0.04, ROUGHNESS * ROUGHNESS); let F = f_schlick(vh, f0); let D = d_ggx(nh, a); let G = 1.0 / (4.0 * max(nl * nv, 0.05)); let spec = D * F * G * nl * 2.5; let diff = (vec3f(1.0) - F) * (1.0 - METALNESS) * base / 3.1415926 * nl * 2.2; let ibl = studio_env(reflect(-v, n)) * f_schlick(nv, f0) * mix(1.0, 0.25, ROUGHNESS) + studio_env(n) * (1.0 - METALNESS) * base * 0.35; let col = diff + spec + ibl; let mapped = (col * (2.51 * col + 0.03)) / (col * (2.43 * col + 0.59) + 0.14); return vec4f(pow(clamp(mapped, vec3f(0.0), vec3f(1.0)), vec3f(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Cook-Torrance microfacet BRDF](https://texelatlas.vercel.app/t/cook-torrance-brdf.md) - extended by [Anisotropic GGX](https://texelatlas.vercel.app/t/anisotropic-ggx.md) - extended by [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) - extended by [Kulla-Conty multiple-scattering compensation](https://texelatlas.vercel.app/t/kulla-conty-multiscatter.md) - extended by [Smith masking-shadowing function](https://texelatlas.vercel.app/t/smith-masking-shadowing.md) ## Sources 1. [primary] Bruce Walter, Stephen R. Marschner, Hongsong Li, Kenneth E. Torrance (2007) Microfacet Models for Refraction through Rough Surfaces. Rendering Techniques. https://doi.org/10.2312/egwr/egsr07/195-206 (verified via doi.org on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) 3. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "GGX / Trowbridge-Reitz normal distribution." https://texelatlas.vercel.app/t/ggx-trowbridge-reitz/ (accessed 2026-12-01). --- id: "gjk-epa-collision-detection" title: "GJK and EPA convex collision detection" aliases: [GJK, Gilbert-Johnson-Keerthi, EPA, expanding polytope algorithm] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, cuda, unity, unreal, godot, webgl2, webgpu, desktop-gpu] year_introduced: 1988 inputs: [mesh] outputs: [point-cloud] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Gilbert et al., 1988" url: "https://texelatlas.vercel.app/t/gjk-epa-collision-detection/" sources_verified_at: "2026-11-29" --- # GJK and EPA convex collision detection (Gilbert et al., 1988) > Narrow-phase test for convex shapes: GJK finds whether two shapes overlap or their closest points through support mappings, and EPA recovers penetration depth and normal when they do. ## Reach for it when - need overlap test between arbitrary convex colliders - want penetration depth and normal for two hulls - closest distance between two convex shapes for physics - need a generic narrow phase using only support functions ## How it works Both algorithms work on the Minkowski difference of two convex shapes, which is never built explicitly. All they need is a support function: for a direction, return the farthest point of each shape, and subtract. GJK keeps a small simplex (point, segment, triangle, tetrahedron) inside that difference. Each iteration asks for the support point toward the origin, adds it, and reduces the simplex to the feature closest to the origin. If the simplex encloses the origin the shapes overlap; if the support point cannot pass the origin, they are separate and the last closest feature gives distance and witness points. When overlap is found, EPA starts from the final simplex, inflates it into a polytope, and repeatedly expands the face closest to the origin by a new support point until the face stops moving; that face's normal and distance are the minimum translation vector, and barycentric weights give contact points. Spheres, capsules, boxes and hulls plug in with only a support function. ## When to use it Choose it as the generic narrow phase for arbitrary convex colliders (hulls, capsules, cones, rounded boxes) and for continuous or distance queries. Prefer a dedicated analytic test for sphere-sphere or box-box pairs, which are faster and more robust. Prefer [CoACD Approximate Convex Decomposition](https://texelatlas.vercel.app/t/coacd-convex-decomposition.md) to turn concave meshes into convex pieces GJK can consume, [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md) for triangle-mesh queries, and [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) or [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) to resolve the contacts GJK and EPA produce. ## Cost cheap — A handful of support evaluations per pair, usually under about ten iterations when warm-started from the previous frame's simplex. Measured GPU Weight: 52.47× baseline (heavy) — 1.6477 ms median / 1.8002 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 55.7× baseline (heavy) — 0.8801 ms median (1.87× faster on L4). Ampere A100 scaling: 37.36× baseline (heavy) — 1.076 ms median (1.53× faster on A100). ## Failure modes - Degenerate simplices (coplanar or collinear points) cause infinite loops or NaNs unless guarded with tolerances - EPA returns wrong or unstable normals for shallowly penetrating or very large or thin shapes - Tolerance mismatch between GJK and EPA leaves shapes reported as touching with no usable normal - Contact manifold from one EPA point jitters; stacking needs a manifold generator or persistent contacts - Only convex shapes: concave meshes silently give the hull's contacts ## Engine support - godot: builtin — `Physics: default GodotPhysics3D (GJK/EPA); Jolt Physics is also bundled` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/godot_physics_3d/gjk_epa.cpp, checked 2026-12-01) — Internal to the physics engines; not a user-facing setting. - unity: builtin — `Built-in 3D Physics (NVIDIA PhysX narrow-phase convex collision via MeshCollider.convex / primitive colliders)` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/PhysicsOverview.html, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: point-cloud - Platforms: cpu, cuda, unity, unreal, godot, webgl2, webgpu, desktop-gpu ## Presets ### GJK & EPA convex collision — live Minkowski difference A−B, enclosing simplex & EPA penetration vector (glsl-fragment; rendered 2026-11-30) ```json { "P_ORBIT_SEP": 0.22, "P_ROT_SPEED": 1, "P_MINKOWSKI_VIS": 1, "P_SHAPE_ROUND": 0.03 } ``` ```glsl const float P_ORBIT_SEP = 0.22; // P Orbit Distance [0.08, 0.42, 0.01] const float P_ROT_SPEED = 1.0; // P Motion Speed [0.0, 2.5, 0.05] const float P_MINKOWSKI_VIS = 1.0; // P Minkowski Glow [0.2, 1.8, 0.05] const float P_SHAPE_ROUND = 0.03; // P Margin Radius [0.005, 0.07, 0.005] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } // Support function for a regular N-gon centered at c, rotated by ang, radius r, margin m vec2 supportPoly(vec2 dir, vec2 c, float r, float ang, int nSides, float margin) { vec2 ld = rot2(-ang) * dir; float bestDot = -1e9; vec2 bestV = vec2(0.0); for (int i = 0; i < 6; i++) { if (i >= nSides) break; float a = float(i) * (6.2831853 / float(nSides)); vec2 v = vec2(cos(a), sin(a)) * r; float d = dot(v, ld); if (d > bestDot) { bestDot = d; bestV = v; } } vec2 nd = dir / max(length(dir), 1e-5); return c + rot2(ang) * bestV + nd * margin; } // Signed distance to a regular N-gon via exact half-space intersection float sdPoly(vec2 p, vec2 c, float r, float ang, int nSides, float margin) { vec2 q = rot2(-ang) * (p - c); float dMax = -1e9; float apothem = r * cos(3.14159265 / float(nSides)); for (int i = 0; i < 6; i++) { if (i >= nSides) break; float a = (float(i) + 0.5) * (6.2831853 / float(nSides)); vec2 n = vec2(cos(a), sin(a)); dMax = max(dMax, dot(q, n) - apothem); } return dMax - margin; } // Signed distance to exact convex Minkowski difference M = A - B via support planes! // Also outputs EPA closest boundary point to the origin (minimum translation vector) float sdMinkowski(vec2 p, vec2 cA, float rA, float aA, vec2 cB, float rB, float aB, float m, out vec2 epaVec, out float epaDepth) { float dMax = -1e9; epaDepth = 1e9; epaVec = vec2(1.0, 0.0); for (int i = 0; i < 24; i++) { float ang = float(i) * (6.2831853 / 24.0); vec2 dir = vec2(cos(ang), sin(ang)); vec2 sup = supportPoly(dir, cA, rA, aA, 5, m) - supportPoly(-dir, cB, rB, aB, 3, m); float planeDist = dot(sup, dir); // Half-space signed distance at query point p dMax = max(dMax, dot(p, dir) - planeDist); // EPA: minimum distance from origin (0,0) to supporting hyperplane if (planeDist < epaDepth) { epaDepth = planeDist; epaVec = dir * planeDist; } } return dMax; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tAnim = iTime * max(P_ROT_SPEED, 0.0); float sep = clamp(P_ORBIT_SEP, 0.05, 0.48); float mGlow = clamp(P_MINKOWSKI_VIS, 0.1, 2.0); float margin = clamp(P_SHAPE_ROUND, 0.004, 0.08); // Split viewport: Left = World Space (Shapes A & B), Right = Configuration Space (Minkowski Diff A - B) bool rightPane = uv.x > 0.0; vec2 lp = uv - vec2(rightPane ? 0.42 : -0.42, 0.0); // Two convex shapes oscillating cleanly between separated and penetrating states float osc = sep * (0.65 + 0.55 * sin(tAnim * 0.85)); vec2 cA = vec2(-osc * 0.55, 0.06 * cos(tAnim * 0.6)); vec2 cB = vec2(osc * 0.55, -0.06 * cos(tAnim * 0.6)); float rA = 0.145; float rB = 0.135; float aA = tAnim * 0.45; float aB = -tAnim * 0.62 + 0.5; vec2 epaVec; float epaDepth; float dMinkOrigin = sdMinkowski(vec2(0.0), cA, rA, aA, cB, rB, aB, margin, epaVec, epaDepth); bool colliding = dMinkOrigin < 0.0; // Blueprint grid background vec3 col = vec3(0.028, 0.038, 0.062); vec2 g = abs(fract(lp * 10.0 - 0.5) - 0.5); col += vec3(0.02, 0.032, 0.048) * smoothstep(0.035, 0.005, min(g.x, g.y)); // Subtle coordinate axes in each pane float axes = min(abs(lp.x), abs(lp.y)); col += vec3(0.08, 0.12, 0.18) * smoothstep(px * 2.2, px * 0.4, axes); if (!rightPane) { // Left Pane: World Space convex shapes A (pentagon) and B (triangle) float dA = sdPoly(lp, cA, rA, aA, 5, margin); float dB = sdPoly(lp, cB, rB, aB, 3, margin); vec3 colA = vec3(0.18, 0.72, 0.96); vec3 colB = vec3(0.96, 0.58, 0.18); if (dA < 0.0) col = mix(col, colA, 0.48); if (dB < 0.0) col = mix(col, colB, 0.48); if (dA < 0.0 && dB < 0.0) { // Overlap intersection zone glowing hot crimson col = mix(col, vec3(1.0, 0.22, 0.36), 0.75); } col = mix(col, colA * 1.25, smoothstep(px * 3.2, px * 0.6, abs(dA))); col = mix(col, colB * 1.25, smoothstep(px * 3.2, px * 0.6, abs(dB))); // Draw EPA Minimum Translation Vector (MTV) separating B from A when colliding if (colliding) { vec2 mtvStart = 0.5 * (cA + cB); vec2 mtvEnd = mtvStart + epaVec; float dMtv = sdSegment(lp, mtvStart, mtvEnd); col = mix(col, vec3(1.0, 0.96, 0.42), smoothstep(px * 4.0, px * 0.8, dMtv)); col = mix(col, vec3(1.0, 0.98, 0.65), smoothstep(0.016, 0.005, length(lp - mtvEnd))); } } else { // Right Pane: Minkowski Difference M = A - B centered on Origin (0,0) vec2 dummyVec; float dummyD; float dM = sdMinkowski(lp, cA, rA, aA, cB, rB, aB, margin, dummyVec, dummyD); // Distance field contour rings outside Minkowski sum float iso = smoothstep(0.07, 0.01, abs(fract(max(dM, 0.0) * 14.0) - 0.5)); col += vec3(0.07, 0.14, 0.22) * iso * step(0.0, dM) * 0.6; // Fill Minkowski Difference polygon (emerald when separated, crimson when Origin is inside!) vec3 minkCol = colliding ? vec3(0.95, 0.24, 0.36) : vec3(0.16, 0.86, 0.58); if (dM < 0.0) { col = mix(col, minkCol * 0.55, 0.58 * min(mGlow, 1.4)); } col = mix(col, minkCol * 1.35, smoothstep(px * 3.5, px * 0.7, abs(dM))); // Construct a 3-vertex GJK Simplex inside M around the origin vec2 s0 = supportPoly(vec2(1.0, 0.15), cA, rA, aA, 5, margin) - supportPoly(vec2(-1.0, -0.15), cB, rB, aB, 3, margin); vec2 s1 = supportPoly(vec2(-0.55, 0.84), cA, rA, aA, 5, margin) - supportPoly(vec2(0.55, -0.84), cB, rB, aB, 3, margin); vec2 s2 = supportPoly(vec2(-0.45, -0.89), cA, rA, aA, 5, margin) - supportPoly(vec2(0.45, 0.89), cB, rB, aB, 3, margin); float dSimplex = min(sdSegment(lp, s0, s1), min(sdSegment(lp, s1, s2), sdSegment(lp, s2, s0))); col = mix(col, vec3(0.86, 0.94, 1.0), smoothstep(px * 2.8, px * 0.6, dSimplex) * 0.85); // Highlight EPA penetration vector from Origin (0,0) to closest edge of M if (colliding) { float dEpa = sdSegment(lp, vec2(0.0), epaVec); col += vec3(1.0, 0.92, 0.32) * exp(-dEpa * 85.0) * 0.85; col = mix(col, vec3(1.0, 0.96, 0.45), smoothstep(px * 3.8, px * 0.8, dEpa)); col = mix(col, vec3(1.0, 0.98, 0.72), smoothstep(0.017, 0.005, length(lp - epaVec))); } // Origin (0,0) target crosshair float dOrig = length(lp); col = mix(col, vec3(1.0), smoothstep(0.022, 0.008, dOrig)); col = mix(col, colliding ? vec3(1.0, 0.25, 0.35) : vec3(0.2, 0.95, 0.65), smoothstep(0.012, 0.004, dOrig)); } // Center pane divider col = mix(col, vec3(0.75, 0.84, 0.96), smoothstep(px * 2.5, px * 0.5, abs(uv.x))); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md): GJK/EPA output (normal, depth, witness points) becomes the contact constraints the impulse solver iterates over. - [CoACD Approximate Convex Decomposition](https://texelatlas.vercel.app/t/coacd-convex-decomposition.md): Decomposition supplies the convex parts whose support functions GJK queries for concave objects. ## Sources 1. [primary] E.G. Gilbert, D.W. Johnson, S.S. Keerthi (1988) A fast procedure for computing the distance between complex objects in three-dimensional space. IEEE Journal on Robotics and Automation. https://doi.org/10.1109/56.2083 (verified via crossref on 2026-11-29) 2. [primary] Gino Van den Bergen (1999) A Fast and Robust GJK Implementation for Collision Detection of Convex Objects. Journal of Graphics Tools. https://doi.org/10.1080/10867651.1999.10487502 (verified via crossref on 2026-11-29) 3. [tutorial] Casey Muratori Implementing GJK (Molly Rocket). caseymuratori.com. https://caseymuratori.com/blog_0003 (verified via http on 2026-11-29) 4. [implementation] jrouwe (2021) jrouwe/JoltPhysics. https://github.com/jrouwe/JoltPhysics License: MIT. (verified via github on 2026-11-29) 5. [implementation] bulletphysics (2011) bulletphysics/bullet3. https://github.com/bulletphysics/bullet3 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "GJK and EPA convex collision detection." https://texelatlas.vercel.app/t/gjk-epa-collision-detection/ (accessed 2026-12-01). --- id: "gltf-2-0" title: "glTF 2.0 asset format" aliases: [glTF, GLB, gltf2] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender, python] year_introduced: 2017 inputs: [mesh, texture, material-params, skeleton, animation] outputs: [mesh, texture, material-params, animation] style: "both" dynamic: "both" cost: "cheap" authority: "Group" url: "https://texelatlas.vercel.app/t/gltf-2-0/" sources_verified_at: "2026-11-29" --- # glTF 2.0 asset format (Group) > A JSON-plus-binary scene format with a metallic-roughness PBR material model and extensions, designed to be uploaded to the GPU with minimal processing. ## Reach for it when - need one format to move 3d assets to the web - exported model looks different in each viewer - reduce download size of a 3d model - pbr material interchange between blender and three.js - load animated skinned characters in a browser ## How it works A glTF asset is a JSON description of a scene graph (nodes, meshes, skins, cameras, animations) that points at binary buffers and image files. Buffers are organized as bufferViews and typed accessors that match GPU vertex attribute layouts, so data can often be copied to vertex buffers as is. The GLB container packs JSON and buffers into one file. Materials use a metallic-roughness model (base color, metallic, roughness, normal, occlusion, emissive), so a viewer needs only one shader family. Everything beyond that core is optional, named extensions: KHR_materials_* for clearcoat, transmission, sheen, anisotropy and others, KHR_draco_mesh_compression and EXT_meshopt_compression for geometry, KHR_texture_basisu for KTX2 textures. Animation is stored as keyframe samplers targeting node transforms or morph weights; skinning uses joints and weights per vertex. ## When to use it Choose it as the runtime and web interchange format between DCC tools, three.js, Babylon, engines and viewers. Prefer USD or FBX for authoring pipelines needing layering, variants or complex rigs, and [MaterialX](https://texelatlas.vercel.app/t/materialx.md) or [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) where full authoring-time material graphs are needed. Add [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md) or [Draco mesh compression](https://texelatlas.vercel.app/t/draco-mesh-compression.md) and [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md) to shrink delivery size. ## Cost cheap — Load cost is mostly decoding compressed buffers and textures; the format itself adds little overhead. Measured GPU Weight: 4.23× baseline (light) — 0.1393 ms median / 0.1433 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.26× baseline (light) — 0.0519 ms median (2.68× faster on L4). Ampere A100 scaling: 3× baseline (light) — 0.0863 ms median (1.61× faster on A100). ## Failure modes - Core material model cannot express layered or measured BRDFs, so extensions are required and viewer support varies - Different exporters disagree on units, axis conventions and sRGB vs linear texture tagging, causing mis-scaled or washed-out assets - Compressed-geometry or Basis extensions fail silently in viewers that lack decoders - Vertex colors, KHR_materials_emissive_strength or unlit materials are interpreted differently across renderers - Large scenes in a single JSON file load slowly; there is no built-in streaming or LOD ## Engine support - babylonjs: official — `import "@babylonjs/loaders/glTF"` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/loaders/src/glTF/2.0/glTFLoader.pure.ts, checked 2026-12-01) - blender: official — `File > Import/Export > glTF 2.0 (.glb/.gltf)` (evidence: https://docs.blender.org/manual/en/5.2/addons/scene_gltf2.html, checked 2026-12-01) — Official Blender-maintained add-on. - godot: builtin — `Import .gltf/.glb as a scene; GLTFDocument for runtime load and export` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/gltf/doc_classes/GLTFDocument.xml, checked 2026-12-01) - threejs: official — `import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/loaders/GLTFLoader.js, checked 2026-12-01) - unity: official — `Package Manager > Unity Registry > glTFast (com.unity.cloud.gltfast)` (evidence: https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@6.0/manual/index.html, checked 2026-12-01) — Unity-published package; import and runtime load. - unreal: official — `Import .gltf/.glb through Interchange (Import Into Level or Content Browser import)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/interchange-import-reference-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, texture, material-params, skeleton, animation - Outputs: mesh, texture, material-params, animation - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender, python ## Presets ### glTF 2.0 PBR Asset Format — raw metallic-roughness + tangent normal channels (left) vs full Khronos PBR + KHR_materials_clearcoat render (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_METALLIC": 0.78, "P_ROUGHNESS": 0.28, "P_CLEARCOAT": 0.65, "P_SPLIT": 0.45 } ``` ```glsl const float P_METALLIC = 0.78; // P Metallic Factor [0.0, 1.0, 0.02] const float P_ROUGHNESS = 0.28; // P Roughness Factor [0.08, 0.90, 0.02] const float P_CLEARCOAT = 0.65; // P KHR Clearcoat [0.0, 1.0, 0.05] const float P_SPLIT = 0.45; // P PBR Channels / Final [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } float D_GGX(float ndh, float a) { float a2 = a * a; float d = ndh * ndh * (a2 - 1.0) + 1.0; return a2 / max(3.1415926 * d * d, 1e-5); } float G_Smith(float ndv, float ndl, float a) { float k = (a + 1.0) * (a + 1.0) * 0.125; float gv = ndv / max(ndv * (1.0 - k) + k, 1e-4); float gl = ndl / max(ndl * (1.0 - k) + k, 1e-4); return gv * gl; } vec3 F_Schlick(float cosT, vec3 f0) { return f0 + (1.0 - f0) * pow(clamp(1.0 - cosT, 0.0, 1.0), 5.0); } vec3 evalStudioIBL(vec3 r, float rough) { vec3 sky = mix(vec3(0.08, 0.10, 0.15), vec3(0.45, 0.56, 0.72), smoothstep(-0.25, 0.7, r.y)); float panel1 = smoothstep(0.65 - rough * 0.25, 0.92, dot(r, normalize(vec3(0.6, 0.65, 0.45)))); float panel2 = smoothstep(0.60 - rough * 0.25, 0.90, dot(r, normalize(vec3(-0.75, 0.35, 0.55)))); float horizon = exp(-abs(r.y) * mix(16.0, 3.0, rough)) * 0.45; return sky + vec3(2.2, 1.95, 1.65) * panel1 + vec3(0.55, 0.85, 1.25) * panel2 + vec3(0.75, 0.82, 0.92) * horizon; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float metFactor = clamp(P_METALLIC, 0.0, 1.0); float rghFactor = clamp(P_ROUGHNESS, 0.06, 0.95); float coatFactor = clamp(P_CLEARCOAT, 0.0, 1.0); vec3 ro = vec3(0.0, 0.25, 2.35); vec3 rd = normalize(vec3(uv.x, uv.y - 0.06, -1.52)); vec3 col = evalStudioIBL(rd, 0.55) * 0.35; // Classic glTF 2.0 Khronos DamagedHelmet-inspired center hero sphere + flanking dielectric/metal reference spheres vec3 pos[3]; float rad[3]; pos[0] = vec3(0.0, 0.04, 0.05); rad[0] = 0.44; pos[1] = vec3(-0.68, -0.14, -0.12); rad[1] = 0.24; pos[2] = vec3(0.68, -0.14, -0.12); rad[2] = 0.24; float tMin = 1e5; int hitId = -1; vec3 hp = vec3(0.0); vec3 hn = vec3(0.0, 1.0, 0.0); if (rd.y < -0.005) { float tf = (-0.42 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { tMin = tf; hitId = 10; hp = ro + rd * tf; hn = vec3(0.0, 1.0, 0.0); } } for (int i = 0; i < 3; i++) { vec3 oc = ro - pos[i]; float b = dot(oc, rd); float d = b * b - (dot(oc, oc) - rad[i] * rad[i]); if (d > 0.0) { float ts = -b - sqrt(d); if (ts > 0.05 && ts < tMin) { tMin = ts; hitId = i; hp = ro + rd * ts; hn = normalize(hp - pos[i]); } } } if (hitId >= 0) { vec3 v = -rd; vec3 n = hn; vec3 baseColor = vec3(0.75); float metallic = metFactor; float roughness = rghFactor; vec3 emissive = vec3(0.0); if (hitId == 10) { vec2 g = hp.xz * 2.4; float chk = mod(floor(g.x) + floor(g.y), 2.0); baseColor = mix(vec3(0.16, 0.18, 0.22), vec3(0.32, 0.35, 0.40), chk); metallic = 0.10; roughness = 0.42; } else if (hitId == 0) { vec3 lp = hn; lp.xz = rot2(lp.xz, iTime * 0.45); // Procedural panel seams & emissive visor band (classic glTF 2.0 packed textures) float panel = smoothstep(0.03, 0.09, abs(sin(lp.x * 12.0)) * abs(sin(lp.y * 10.0))); float visor = smoothstep(0.18, 0.06, abs(lp.y - 0.08)) * smoothstep(-0.1, 0.35, lp.z); baseColor = mix(vec3(0.14, 0.16, 0.20), vec3(0.88, 0.66, 0.30), panel); baseColor = mix(baseColor, vec3(0.06, 0.09, 0.14), visor); metallic = mix(0.25, metFactor, panel); roughness = mix(0.55, rghFactor, panel); // Micro normal perturbation along panel seams n = normalize(hn + vec3(cos(lp.x * 12.0), cos(lp.y * 10.0), 0.0) * 0.09 * (1.0 - panel)); emissive = vec3(0.18, 0.92, 1.0) * smoothstep(0.05, 0.015, abs(lp.y - 0.08)) * smoothstep(0.0, 0.35, lp.z) * 1.4; } else if (hitId == 1) { baseColor = vec3(0.88, 0.24, 0.20); metallic = 0.04; roughness = 0.22; } else { baseColor = vec3(0.92, 0.78, 0.48); metallic = 0.96; roughness = 0.18; } if (screenX < split) { // Left: glTF 2.0 packed buffer attribute breakdown (top half = normal map, bottom half = R:AO G:Roughness B:Metallic!) if (uv.y > 0.02) { col = n * 0.5 + 0.5; } else { float ao = (hitId == 10) ? smoothstep(0.18, 0.65, length(hp.xz)) : (0.5 + 0.5 * n.y); col = vec3(ao, roughness, metallic); } } else { // Right: Spec-compliant glTF 2.0 metallic-roughness BRDF + KHR_materials_clearcoat + emissive vec3 l = normalize(vec3(0.62 * cos(iTime * 0.35), 0.75, 0.55)); vec3 h = normalize(l + v); float ndl = max(dot(n, l), 0.0); float ndv = max(dot(n, v), 0.001); float ndh = max(dot(n, h), 0.0); float vdh = max(dot(v, h), 0.0); vec3 f0 = mix(vec3(0.04), baseColor, metallic); float a = roughness * roughness; vec3 F = F_Schlick(vdh, f0); float D = D_GGX(ndh, a); float G = G_Smith(ndv, ndl, roughness); vec3 specDir = (D * G * F) / max(4.0 * ndv * ndl, 0.001); vec3 kD = (1.0 - F) * (1.0 - metallic); vec3 direct = (kD * baseColor / 3.1415926 + specDir) * vec3(2.4, 2.25, 2.0) * ndl; vec3 r = reflect(-v, n); vec3 envSpec = evalStudioIBL(r, roughness) * F_Schlick(ndv, f0); vec3 envDiff = evalStudioIBL(n, 0.9) * baseColor * (1.0 - metallic) * 0.35; // KHR_materials_clearcoat secondary specular lobe (IOR 1.5 -> F0 = 0.04, low roughness) float coatA = 0.06 * 0.06; float coatD = D_GGX(ndh, coatA); float coatF = 0.04 + 0.96 * pow(1.0 - ndv, 5.0); vec3 coatSpec = (vec3(coatD * 0.25 * ndl) + evalStudioIBL(r, 0.06) * coatF) * coatFactor * (hitId == 10 ? 0.1 : 0.85); col = direct + envDiff + envSpec + coatSpec + emissive; if (hitId == 10) col = mix(evalStudioIBL(rd, 0.55) * 0.35, col, exp(-tMin * 0.14)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md): glTF's EXT_meshopt_compression stores buffers in meshoptimizer's encoded form for smaller downloads. - [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md): KHR_texture_basisu lets glTF reference KTX2 textures that transcode to the GPU's native block format. ## Sources 1. [primary] The Khronos® 3D Formats Working Group glTF 2.0 Specification. registry.khronos.org. https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html (verified via http on 2026-11-29) 2. [implementation] KhronosGroup (2017) KhronosGroup/glTF-Sample-Viewer. https://github.com/KhronosGroup/glTF-Sample-Viewer License: Apache-2.0. (verified via github on 2026-11-29) 3. [implementation] donmccurdy (2018) donmccurdy/glTF-Transform. https://github.com/donmccurdy/glTF-Transform License: MIT. (verified via github on 2026-11-29) 4. [secondary] KhronosGroup (2013) KhronosGroup/glTF. https://github.com/KhronosGroup/glTF License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "glTF 2.0 asset format." https://texelatlas.vercel.app/t/gltf-2-0/ (accessed 2026-12-01). --- id: "gooch-shading" title: "Gooch tone shading" domain: "npr" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1998 inputs: [normals, material-params] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Gooch et al., 1998" url: "https://texelatlas.vercel.app/t/gooch-shading/" sources_verified_at: "2026-11-29" --- # Gooch tone shading (Gooch et al., 1998) > A lighting model that replaces light-to-dark with a warm-to-cool colour ramp, so shape stays readable without relying on black shadows, with outlines added separately. ## Reach for it when - black shadows hide detail in a technical viewer - need readable shape without dark shading - cad or anatomy diagrams look muddy with realistic lighting - want warm to cool colour shading with outlines ## How it works Instead of modulating brightness with N·L, the model interpolates between a cool colour and a warm colour. Each is built by mixing a fixed hue (blue for cool, yellow for warm) with the object's own diffuse colour using two scalar weights, so material identity survives. The interpolation parameter is (1 + N·L)/2, which means surfaces facing away from the light shift toward blue instead of black, while lit ones shift toward yellow. Highlights are added on top as white, and silhouettes and creases are drawn as black lines, which stay visible because no shaded region is dark. The effect mimics hand technical illustration where hue shift, not value, carries depth. ## When to use it Choose it for CAD viewers, anatomy and technical diagrams, where black shadows would hide detail and you need outlines to read. Prefer [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md) when you want a flat stylized character look with discrete bands. Prefer physically based shading when the viewer is supposed to judge real material. ## Cost cheap — A handful of ALU ops per pixel and no extra textures; effectively free. Measured GPU Weight: 2.03× baseline (light) — 0.0669 ms median / 0.0705 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.6× baseline (feather) — 0.0254 ms median (2.63× faster on L4). Ampere A100 scaling: 1.29× baseline (feather) — 0.0372 ms median (1.8× faster on A100). ## Failure modes - Warm/cool hue shift interacts badly with already coloured materials and may be read as a real colour change - No cast shadows by default, so depth ordering between separate objects relies on outlines alone - Colour-blind viewers may lose the blue/yellow cue; parameters need tuning per palette ## Dataflow - Inputs: normals, material-params - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: Lambert shading. Right: Gooch warm-to-cool ramp with specular and silhouette lines (glsl-fragment; rendered 2026-11-29) ```json { "COOLB": 0.4, "WARMY": 0.4, "ALPHA": 0.2, "BETA": 0.6, "EDGE": 0.28 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float COOLB=0.4; // P const float WARMY=0.4; // P const float ALPHA=0.2; // P const float BETA=0.6; // P const float EDGE=0.28; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t,a=alb(P);float ndl=dot(n,LD); if(!R) col=a*(.12+.95*max(ndl,0.)); else{ float k=.5+.5*ndl; vec3 cool=vec3(0.,0.,COOLB)+ALPHA*a,warm=vec3(WARMY,WARMY,0.)+BETA*a; col=mix(cool,warm,k); col=mix(col,vec3(1.),pow(max(dot(reflect(-LD,n),-rd),0.),40.)*.8); if(dot(n,-rd)-.69)col=vec3(0.); } col=mix(col,sky(rd),smoothstep(6.,25.,t)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Combines with - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Outline pass restores the contour lines the Gooch tone ramp deliberately omits. ## Sources 1. [primary] Amy Gooch, Bruce Gooch, Peter Shirley, Elaine Cohen (1998) A non-photorealistic lighting model for automatic technical illustration. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280950 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Gooch tone shading." https://texelatlas.vercel.app/t/gooch-shading/ (accessed 2026-12-01). --- id: "gpu-driven-rendering" title: "GPU-driven rendering" aliases: [GPU-driven pipeline, indirect rendering] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgpu, desktop-gpu, unity, unreal] year_introduced: 2015 inputs: [mesh] outputs: [gbuffer, depth] style: "both" dynamic: "both" cost: "cheap" authority: "Haar & Aaltonen" url: "https://texelatlas.vercel.app/t/gpu-driven-rendering/" sources_verified_at: "2026-11-29" --- # GPU-driven rendering (Haar & Aaltonen) > Move scene culling, LOD choice and draw-call generation onto the GPU so one indirect call renders a whole scene's visible clusters without CPU per-object work. ## Reach for it when - cpu is bottlenecked submitting thousands of draw calls - scene with tens of thousands of objects runs slowly - want culling and lod decided on the gpu - reduce per-object cpu work in big scenes - render a whole scene with one indirect call ## How it works Geometry is kept in a few big vertex and index buffers, and per-instance data lives in a scene buffer. A compute pass tests each instance or cluster against the frustum and a depth pyramid, writes compacted draw arguments, and an indirect multi-draw consumes them. The usual refinement is two-pass culling: draw what was visible last frame, rebuild the depth pyramid from that, then test and draw the remainder. Bindless or array-indexed materials keep state changes out of the loop, and a visibility buffer can defer material evaluation. ## When to use it Choose it for scenes with tens of thousands of objects where CPU draw submission is the limit. Prefer `gpu-instancing` style batching when many copies of few meshes suffice, which is simpler. Prefer plain engine culling for small scenes. Pair with [Mesh shaders](https://texelatlas.vercel.app/t/mesh-shaders.md) where hardware supports them. ## Cost cheap — Culling is a cheap compute pass; the savings are mostly CPU time. Measured GPU Weight: 3.74× baseline (light) — 0.1231 ms median / 0.1262 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.06× baseline (light) — 0.0486 ms median (2.53× faster on L4). Ampere A100 scaling: 2.74× baseline (light) — 0.0788 ms median (1.56× faster on A100). ## Failure modes - Stale depth pyramid causes flicker or popping of moving objects in one-pass schemes - Needs bindless or large texture arrays, limiting platforms - Indirect draws are harder to debug and profile - Transparent objects need ordering the compute pass does not give ## Engine support - metal: builtin — `MTLIndirectCommandBuffer (GPU-encoded draws/dispatches)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlindirectcommandbuffer.json, checked 2026-12-01) - unity: builtin — `URP/HDRP Asset > Rendering > GPU Resident Drawer = Instanced Drawing` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/gpu-resident-drawer.md, checked 2026-12-01) — Unity 6 GPU Resident Drawer with GPU occlusion culling. - unreal: builtin — `Nanite GPU-driven cluster culling, LOD selection, and indirect rendering pipeline` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/nanite-virtualized-geometry-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `renderPass.drawIndexedIndirect(buffer, offset); computePass.dispatchWorkgroupsIndirect(buffer, offset)` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Indirect draw/dispatch and render bundles; no multi-draw-indirect or ICB. ## Dataflow - Inputs: mesh - Outputs: gbuffer, depth - Platforms: webgpu, desktop-gpu, unity, unreal ## Presets ### GPU-Driven Rendering — unfiltered CPU draw flood (left) vs compute frustum + Hi-Z occlusion culling & LOD clusters (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FOV_WIDTH": 0.55, "P_OCCLUDER_H": 0.75, "P_SCAN_SPEED": 0.55, "P_SPLIT": 0.46 } ``` ```glsl const float P_FOV_WIDTH = 0.55; // P Frustum Half-FOV [0.25, 0.95, 0.05] const float P_OCCLUDER_H = 0.75; // P Hi-Z Occluder Wall [0.0, 1.0, 0.05] const float P_SCAN_SPEED = 0.55; // P Camera Sweep [0.0, 1.6, 0.05] const float P_SPLIT = 0.46; // P CPU Flood / GPU Cull [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float fov = clamp(P_FOV_WIDTH, 0.20, 1.05); float occStr = clamp(P_OCCLUDER_H, 0.0, 1.0); float t = iTime * max(P_SCAN_SPEED, 0.0); // Angled isometric tactical map of 14x10 GPU-instanced scene clusters vec2 world = uv * 2.35; vec3 col = vec3(0.04, 0.06, 0.10); // Subtle spatial hash grid floor vec2 gLine = abs(fract(world * 3.0) - 0.5); float grid = smoothstep(0.05, 0.012, min(gLine.x, gLine.y)); col += vec3(0.06, 0.10, 0.16) * grid; // Virtual camera orbiting at bottom-left sweeping across the instanced city vec2 camPos = vec2(-0.78, -0.78); float camAng = 0.78 + 0.42 * sin(t * 0.65); vec2 camDir = vec2(cos(camAng), sin(camAng)); vec2 camRight = vec2(-camDir.y, camDir.x); // Large Hi-Z depth occluder barrier in middle of frustum vec2 occCenter = camPos + camDir * 0.88 + camRight * 0.08; vec2 toOcc = world - occCenter; float occAlong = dot(toOcc, camDir); float occAcross = dot(toOcc, camRight); float occHalfW = 0.28 * occStr; // Test instanced clusters on a regular grid vec2 cellScale = vec2(3.6); vec2 cid = floor(world * cellScale); vec2 cf = fract(world * cellScale) - 0.5; vec2 cPos = (cid + 0.5) / cellScale; // Cluster geometry & instance bounding box float rnd = hash21(cid + vec2(17.3, 41.1)); float boxR = 0.22 + 0.16 * rnd; vec2 dBox = abs(cf) - vec2(boxR); float inCluster = smoothstep(0.03, -0.02, max(dBox.x, dBox.y)); float boxBorder = smoothstep(0.055, 0.015, abs(max(dBox.x, dBox.y))); // Evaluate frustum & Hi-Z occlusion for cluster center cPos vec2 rel = cPos - camPos; float depth = dot(rel, camDir); float lat = dot(rel, camRight); float halfSpan = max(depth * tan(fov * 0.72), 0.05); bool inFrustum = (depth > 0.12 && depth < 2.25 && abs(lat) < halfSpan); // Hi-Z shadow behind occluder wall float occDepth = 0.88; float projLat = (depth > 0.01) ? (lat * (occDepth / max(depth, 0.01))) : 9.0; bool hizOccluded = (occStr > 0.05) && (depth > occDepth + 0.08) && (abs(projLat - 0.08) < occHalfW); if (inCluster > 0.01 && length(cPos - camPos) > 0.22) { if (screenX < split) { // Left: CPU submits ALL instances blindly (uniform red-orange draw-call flood) vec3 cpuCol = mix(vec3(0.62, 0.22, 0.18), vec3(0.95, 0.42, 0.24), rnd); col = mix(col, cpuCol * (0.65 + 0.35 * boxBorder), inCluster); } else { // Right: GPU compute culling + indirect draw compaction + distance LOD selection! vec3 instCol; if (!inFrustum) { // Frustum-culled (skipped completely, zero indirect draw command!) instCol = vec3(0.09, 0.12, 0.18); } else if (hizOccluded) { // Hi-Z depth-pyramid occluded (culled in compute pass!) instCol = vec3(0.28, 0.10, 0.18); } else { // Visible -> select LOD tier by screen-space distance (LOD0 emerald, LOD1 cyan, LOD2 amber) if (depth < 0.95) instCol = vec3(0.16, 0.94, 0.56); else if (depth < 1.55) instCol = vec3(0.18, 0.76, 1.0); else instCol = vec3(0.98, 0.74, 0.22); } col = mix(col, instCol * (0.72 + 0.40 * boxBorder), inCluster); } } // Draw the glowing frustum cone rays and Hi-Z occluder barrier vec2 relP = world - camPos; float dp = dot(relP, camDir); float lp = dot(relP, camRight); float coneSpan = dp * tan(fov * 0.72); float edgeFrust = smoothstep(0.024, 0.005, abs(abs(lp) - coneSpan)) * step(0.0, dp) * step(dp, 2.25); float farArc = smoothstep(0.024, 0.005, abs(dp - 2.25)) * step(abs(lp), coneSpan); col = mix(col, vec3(0.25, 0.95, 1.0), clamp(edgeFrust + farArc, 0.0, 1.0) * 0.85); // Hi-Z occluder wall slab if (occStr > 0.05) { float wall = smoothstep(0.02, -0.01, max(abs(occAlong) - 0.045, abs(occAcross) - occHalfW)); col = mix(col, vec3(0.98, 0.34, 0.42), wall); } // Camera icon at apex float camDot = smoothstep(0.07, 0.04, length(world - camPos)); col = mix(col, vec3(1.0, 0.96, 0.82), camDot); float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md) - extended by [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): The depth pyramid built from last frame's depth is what the culling compute shader samples. ## Combination ideas - [Meshlet foliage with compute-rasterized atomic spores](https://texelatlas.vercel.app/ideas/meshlet-foliage-atomic-spore-raster/) - [Meshlet kelp forests through underwater PSF scattering](https://texelatlas.vercel.app/ideas/meshlet-kelp-small-angle-underwater-psf/) ## Sources 1. [primary] Ulrich Haar, Sebastian Aaltonen GPU-Driven Rendering Pipelines. SIGGRAPH 2015 Advances in Real-Time Rendering. https://advances.realtimerendering.com/s2015/index.html (verified via http on 2026-11-29) 2. [implementation] zeux (2018) zeux/niagara. https://github.com/zeux/niagara License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "GPU-driven rendering." https://texelatlas.vercel.app/t/gpu-driven-rendering/ (accessed 2026-12-01). --- id: "gpu-particle-systems" title: "GPU particle systems" aliases: [compute particles, GPU-resident particles] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal, godot] year_introduced: 2004 inputs: [particles, depth] outputs: [particles] style: "both" dynamic: "dynamic" cost: "medium" authority: "Kipfer et al., 2004" url: "https://texelatlas.vercel.app/t/gpu-particle-systems/" sources_verified_at: "2026-11-29" --- # GPU particle systems (Kipfer et al., 2004) > Keep particle state in GPU buffers or textures and run spawn, update, collision and sort on the GPU so millions of particles cost no CPU time or bus traffic. ## Reach for it when - cpu particle update is too slow past a few thousand sprites - want a million particles that bounce off scene depth - particle buffers stall pipeline from cpu to gpu uploads - need compute shader spawning and recycling of effect particles ## How it works State such as position, velocity, age and seed lives in float textures (ping-pong render targets in WebGL2) or storage buffers (compute shaders in WebGPU and desktop APIs). Each frame an update pass reads the previous state and writes the next: apply forces, integrate, kill expired particles. Dead slots are tracked in a free list; on compute hardware an atomic counter and an append/consume buffer let emitters claim slots without CPU readback, and an indirect draw call consumes the live count. Collision with the scene is done against the depth buffer or a signed distance field by reflecting velocity at the first penetration. Rendering instances a quad per particle with positions fetched in the vertex stage. Sorting for alpha blending uses a GPU radix or bitonic sort on view depth, and is skipped for additive effects. ## When to use it Choose it when particle counts reach tens of thousands and above, or when particles must react to scene depth or a field the GPU already owns. Prefer [Particle systems](https://texelatlas.vercel.app/t/particle-systems.md) for the plain model and for small counts where CPU authoring and callbacks are easier. Prefer [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) or [Unified particle physics](https://texelatlas.vercel.app/t/unified-particle-physics.md) when particles need neighbour interaction, which needs a spatial grid pass on top of this. Combine with [Curl noise for procedural fluid motion](https://texelatlas.vercel.app/t/curl-noise-flow.md) for cheap turbulence and [Soft particles (depth-fade billboards)](https://texelatlas.vercel.app/t/soft-particles.md) for depth-faded sprites. ## Cost medium — Update is cheap; sort and overdraw dominate. Cost scales with particle count and sprite coverage. ## Failure modes - Unbounded slot allocation when the free list runs dry makes new emitters silently drop particles - Depth-buffer collision only sees visible surfaces, so particles leak behind occluders and through thin walls - Texture-based state in WebGL2 loses precision with half floats, causing visible drift or snapping - Readback of the live count stalls the pipeline; it must stay on the GPU via indirect draw - Per-frame sort cost can exceed the simulation cost for translucent effects ## Engine support - babylonjs: builtin — `new BABYLON.GPUParticleSystem(name, { capacity }, scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Particles/gpuParticleSystem.pure.ts, checked 2026-12-01) - godot: builtin — `Add a GPUParticles3D node with a ParticleProcessMaterial` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/GPUParticles3D.xml, checked 2026-12-01) - unity: official — `Visual Effect Graph asset on a Visual Effect component (compute-driven particles)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.visualeffectgraph/Documentation~/System-Requirements.md, checked 2026-12-01) — Requires the Visual Effect Graph package. - unreal: builtin — `Niagara Emitter > Sim Target = GPUCompute Sim` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-niagara-effects-for-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: particles, depth - Outputs: particles - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal, godot ## Lineage - extends [Particle systems](https://texelatlas.vercel.app/t/particle-systems.md) ## Combines with - [Curl noise for procedural fluid motion](https://texelatlas.vercel.app/t/curl-noise-flow.md): The update shader samples a curl field per particle to get turbulence with no neighbour search. - [Soft particles (depth-fade billboards)](https://texelatlas.vercel.app/t/soft-particles.md): Instanced particle quads fade against the depth buffer in the fragment shader. ## Sources 1. [primary] Peter Kipfer, Mark Segal, Rüdiger Westermann (2004) UberFlow. Proceedings of the ACM SIGGRAPH/EUROGRAPHICS conference on Graphics hardware. https://doi.org/10.1145/1058129.1058146 (verified via crossref on 2026-11-29) 2. [tutorial] Cantlay GPU Gems 3, Chapter 23: High-Speed, Off-Screen Particles. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-iv-image-effects/chapter-23-high-speed-screen-particles (verified via http on 2026-11-29) 3. [implementation] three.js contributors three.js GPGPU examples (webgl_gpgpu_birds and particles). github.com. https://github.com/mrdoob/three.js/blob/dev/examples/webgl_gpgpu_birds.html (verified via http on 2026-11-29) 4. [implementation] Unity-Technologies (2020) Unity-Technologies/Graphics. https://github.com/Unity-Technologies/Graphics License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "GPU particle systems." https://texelatlas.vercel.app/t/gpu-particle-systems/ (accessed 2026-12-01). --- id: "gpu-pipe-model-erosion" title: "GPU Pipe-Model Hydraulic Erosion" aliases: [virtual pipes erosion, Mei et al. erosion] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [webgl2, webgpu, desktop-gpu, cuda, unity, unreal, godot] year_introduced: 2007 inputs: [heightfield] outputs: [heightfield, normals] style: "photoreal" dynamic: "static" cost: "medium" authority: "Mei et al., 2007" url: "https://texelatlas.vercel.app/t/gpu-pipe-model-erosion/" sources_verified_at: "2026-11-29" --- # GPU Pipe-Model Hydraulic Erosion (Mei et al., 2007) > A fully GPU-resident erosion solver using virtual pipes between grid cells to move water, with sediment transport and thermal slumping implemented as fragment or compute passes. ## Reach for it when - procedural terrain looks too smooth and fake - real-time erosion of heightmaps on gpu - carve river valleys and ridges into noise terrain - interactive terrain sculpting with water flow ## How it works Each cell stores terrain height, water height, suspended sediment and outflow flux to four neighbours, treating adjacent cells as connected by virtual pipes. Per step: add rainfall, compute outflow flux from hydrostatic height difference with a scaling that prevents negative water, update water height and velocity from net flux, then erode or deposit based on a capacity that depends on speed and local tilt. Sediment is advected semi-Lagrangian along the velocity, evaporation removes water, and a thermal pass limits slopes. Everything is a per-cell stencil, so each step is a handful of texture passes or compute dispatches and runs at interactive rates even for large grids. ## When to use it Choose it for in-engine or in-browser erosion where the heightfield already lives on the GPU and you want visual feedback while sculpting. Prefer [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) when you need layered strata and artist control over rock hardness, and [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) when you need large-scale, resolution-independent drainage rather than local gullies. ## Cost medium — Several full-grid passes per step; interactive iterations per second at 1k to 4k grids on a desktop GPU, but meaningful erosion needs hundreds to thousands of steps. Measured GPU Weight: 108.59× baseline (extreme) — 3.5727 ms median / 3.813 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 98.31× baseline (extreme) — 1.5631 ms median (2.29× faster on L4). Ampere A100 scaling: 80.27× baseline (extreme) — 2.3117 ms median (1.55× faster on A100). ## Failure modes - Flux clamping artifacts: too large a timestep makes water oscillate and checkerboard - Semi-Lagrangian sediment advection diffuses sediment, smearing deposits - Pooling water in basins creates flat lake plateaus that never drain - Grid-axis bias from four-neighbour pipes: gullies run along rows and columns - Needs float render targets with linear filtering, which mobile WebGL2 may lack ## Engine support - unity: official — `Package Manager > Terrain Tools > Paint Terrain > Erosion > Hydraulic (GPU hydraulic and thermal erosion brush)` (evidence: https://docs.unity3d.com/Packages/com.unity.terrain-tools@5.1/manual/erosion-hydraulic.html, checked 2026-12-01) — Official Terrain Tools package. ## Dataflow - Inputs: heightfield - Outputs: heightfield, normals - Platforms: webgl2, webgpu, desktop-gpu, cuda, unity, unreal, godot ## Presets ### GPU Pipe-Model Erosion — virtual-pipe flux & water depth map (left) vs active flowing shallow-water channels (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RAINFALL": 0.78, "P_FLOW_SPEED": 1, "P_CARVE_DEPTH": 0.85, "P_SPLIT": 0.46 } ``` ```glsl const float P_RAINFALL = 0.78; // P Water Flux [0.1, 1.4, 0.04] const float P_FLOW_SPEED = 1.0; // P Flow Velocity [0.0, 2.5, 0.05] const float P_CARVE_DEPTH = 0.85; // P Channel Carve [0.1, 1.4, 0.04] const float P_SPLIT = 0.46; // P Flux Map / Water 3D [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y ); } // Compute terrain height + shallow-water pipe channel mask + downstream flow coordinate vec3 evalPipeBasin(vec2 xz, float carve, float rain) { // Sloping alpine watershed draining from -z toward +z float baseSlope = -xz.y * 0.24 + 0.12 * abs(xz.x); // Two braided meandering river channels converging into a main trunk float mainRiver = abs(xz.x - 0.34 * sin(xz.y * 1.45 + 0.4)); float tribRiver = abs((xz.x - 0.58) + (xz.y + 0.4) * 0.42 - 0.14 * sin(xz.y * 2.8)); float dChan = min(mainRiver, tribRiver * 1.15); float hills = vnoise(xz * 1.2) * 0.48 + vnoise(xz * 2.7) * 0.18 + vnoise(xz * 5.8) * 0.06; float channelCut = exp(-dChan * dChan * 18.0) * 0.34 * carve; float terrainH = baseSlope + hills - channelCut - 0.38; // Shallow-water column height d(x,z) concentrated in pipe channels + sheet-flow tributaries float waterD = exp(-dChan * dChan * 22.0) * 0.16 * rain; float rills = smoothstep(0.62, 0.88, sin(xz.x * 10.0 + hills * 8.0) * 0.5 + 0.5) * 0.03 * rain; waterD += rills * smoothstep(0.08, 0.35, dChan); return vec3(terrainH, waterD, dChan); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isFluxVis = screenX < split; float rain = clamp(P_RAINFALL, 0.08, 1.6); float flowT = iTime * max(P_FLOW_SPEED, 0.0); float carve = clamp(P_CARVE_DEPTH, 0.1, 1.5); vec3 ro = vec3(0.0, 1.28, 2.30); vec3 rd = normalize(vec3(uv.x, uv.y - 0.38, -1.32)); vec3 sky = mix(vec3(0.66, 0.78, 0.90), vec3(0.14, 0.32, 0.62), smoothstep(-0.08, 0.52, rd.y)); vec3 col = sky; float t = 0.2; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; vec3 b = evalPipeBasin(p.xz, carve, rain); float d = p.y - (b.x + b.y * 0.55); if (d < 0.008) { hit = true; break; } t += max(d * 0.45, 0.025); if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; float e = 0.018; vec3 bC = evalPipeBasin(p.xz, carve, rain); float hX = evalPipeBasin(p.xz + vec2(e, 0.0), carve, rain).x; float hZ = evalPipeBasin(p.xz + vec2(0.0, e), carve, rain).x; vec3 n = normalize(vec3((bC.x - hX) / e, 1.0, (bC.x - hZ) / e)); vec3 sunDir = normalize(vec3(0.60, 0.72, 0.42)); float diff = max(dot(n, sunDir), 0.0); float wet = smoothstep(0.018, 0.095, bC.y); float flowRipple = 0.5 + 0.5 * sin(p.z * 26.0 - flowT * 5.2 + sin(p.x * 12.0)); if (isFluxVis) { // Left: Virtual-pipe grid cells & shallow-water velocity flux heatmap vec2 grid = abs(fract(p.xz * 6.0) - 0.5); float cellLine = smoothstep(0.055, 0.015, min(grid.x, grid.y)); float flux = clamp(bC.y * 8.5, 0.0, 1.0); vec3 heat = mix(vec3(0.07, 0.11, 0.18), vec3(0.08, 0.76, 0.94), smoothstep(0.0, 0.55, flux)); heat = mix(heat, vec3(0.98, 0.86, 0.24), smoothstep(0.50, 0.95, flux)); heat *= (0.48 + 0.65 * diff); // Animated downstream pipe-flux dashes float pulse = smoothstep(0.55, 0.92, flowRipple) * flux; col = heat + vec3(0.95, 0.98, 1.0) * pulse * 0.48 + vec3(0.18, 0.34, 0.50) * cellLine * 0.35; } else { // Right: Shaded carved basin with glistening shallow-water river & suspended sediment foam vec3 rock = mix(vec3(0.32, 0.28, 0.24), vec3(0.56, 0.46, 0.36), smoothstep(0.18, 0.52, 1.0 - n.y)); vec3 bank = vec3(0.24, 0.42, 0.22); vec3 ground = mix(bank, rock, smoothstep(0.10, 0.35, 1.0 - n.y)); vec3 waterCol = mix(vec3(0.06, 0.36, 0.48), vec3(0.18, 0.76, 0.86), flowRipple * 0.45 + 0.35); vec3 alb = mix(ground, waterCol, wet); vec3 nW = normalize(mix(n, normalize(vec3(sin(p.z * 24.0 - flowT * 5.0) * 0.08, 1.0, cos(p.x * 20.0) * 0.08)), wet)); float spec = pow(max(dot(nW, normalize(sunDir - rd)), 0.0), 48.0) * wet; col = alb * (0.26 + 0.86 * diff) + vec3(0.95, 0.98, 1.0) * spec * 0.95; col += vec3(0.88, 0.94, 0.98) * smoothstep(0.75, 0.98, flowRipple) * wet * 0.22; } col = mix(col, sky, 1.0 - exp(-t * 0.075)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Thermal (Talus) Erosion](https://texelatlas.vercel.app/t/thermal-erosion.md) - extended by [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) ## Combination ideas - [Overhang-capable voxel erosion with pipe-model water](https://texelatlas.vercel.app/ideas/margolus-voxel-erosion-pipe-water/) ## Sources 1. [primary] Xing Mei, Philippe Decaudin, Bao-Gang Hu (2007) Fast Hydraulic Erosion Simulation and Visualization on GPU. 15th Pacific Conference on Computer Graphics and Applications (PG'07). https://doi.org/10.1109/pg.2007.15 (verified via crossref on 2026-11-29) 2. [implementation] dandrino (2018) dandrino/terrain-erosion-3-ways. https://github.com/dandrino/terrain-erosion-3-ways License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "GPU Pipe-Model Hydraulic Erosion." https://texelatlas.vercel.app/t/gpu-pipe-model-erosion/ (accessed 2026-12-01). --- id: "grass-blade-rendering" title: "GPU grass blade rendering" aliases: [GPU grass, instanced grass blades, grass geometry shader] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2004 inputs: [heightfield, texture] outputs: [mesh, gbuffer] style: "both" dynamic: "dynamic" cost: "medium" authority: "Pelzer" url: "https://texelatlas.vercel.app/t/grass-blade-rendering/" sources_verified_at: "2026-11-29" --- # GPU grass blade rendering (Pelzer) > Draws millions of grass blades by instancing a tiny blade mesh, generating position, height, bend and colour per instance in the vertex shader from hashes and a wind field. ## Reach for it when - need a field of grass that sways in wind - too many grass blades kill performance - grass blades look flat from the side - cheap vegetation for open world terrain ## How it works Represent one blade as a few quads or a strip of segments with a tapered width. Instance it across the terrain: per-instance data comes from a jittered grid or a compute-shader scatter, so the position is a hash of the cell, snapped to the heightfield. In the vertex shader, derive height, facing direction, lean and colour tint from hashes, then bend the upper vertices with a curve (quadratic Bézier) and add wind as a scrolling noise offset weighted by the vertex height along the blade. Fade out by distance with level-of-detail ring buffers that drop segments, thin out the density and finally swap to a flat ground texture. Lighting uses the terrain normal blended with the blade normal, plus fake translucency and ambient occlusion from height along the blade. Cull instances in a compute pass for large fields. ## When to use it Choose it for open-world meadows and stylised fields where the camera sees individual blades at close range. Prefer alpha-tested textured cards when grass is distant or low budget, [Octahedral impostors](https://texelatlas.vercel.app/t/octahedral-impostors.md) for trees and larger vegetation, [Plant Ecosystem Distribution Simulation](https://texelatlas.vercel.app/t/ecosystem-plant-distribution.md) for deciding where grass grows, and [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) once you need indirect draws and GPU culling at scale. ## Cost medium — Dominated by vertex throughput and overdraw from thin alpha-blended or MSAA-edged blades; density and LOD set the budget. Measured GPU Weight: 52.21× baseline (heavy) — 1.7176 ms median / 1.8398 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 46.97× baseline (heavy) — 0.7468 ms median (2.3× faster on L4). Ampere A100 scaling: 35.32× baseline (heavy) — 1.0173 ms median (1.69× faster on A100). ## Failure modes - Aliasing and shimmer on thin distant blades without MSAA or temporal filtering - Hard LOD rings pop when density or segment count changes with distance - Overdraw and over-bright specular if blade normals are not blended with terrain normals - Wind looks like a sliding pattern when the noise scale does not match blade size and it moves uniformly ## Engine support - unity: builtin — `Terrain > Paint Details > DetailPrototype with useInstancing = true (GPU-instanced grass and foliage meshes)` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/DetailPrototype-useInstancing.html, checked 2026-12-01) - unreal: builtin — `Landscape material Grass Output node + Landscape Grass Type asset` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/landscape-materials-in-unreal-engine, checked 2026-12-01) — Procedural grass instances spawned from landscape layers. ## Dataflow - Inputs: heightfield, texture - Outputs: mesh, gbuffer - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### GPU grass blades — Bezier curved swaying meadow with wind waves & translucency (glsl-fragment; rendered 2026-11-30) ```json { "P_WIND_SPEED": 1.2, "P_BLADE_DENSITY": 1, "P_BEND_STRENGTH": 0.78, "P_TRANSLUCENCY": 0.85 } ``` ```glsl const float P_WIND_SPEED = 1.2; // P Wind Speed [0.0, 3.0, 0.05] const float P_BLADE_DENSITY = 1.0; // P Density [0.4, 2.0, 0.05] const float P_BEND_STRENGTH = 0.78; // P Wind Bend [0.0, 1.6, 0.04] const float P_TRANSLUCENCY = 0.85; // P Translucency [0.0, 1.8, 0.05] float hash21(vec2 p) { p = fract(p * vec2(234.34, 435.345)); p += dot(p, p + 34.23); return fract(p.x * p.y); } float noise2(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / iResolution.y; // Golden-hour sunlit sky with warm horizon haze vec2 sunPos = vec2(0.32, 0.24); vec3 skyTop = vec3(0.14, 0.34, 0.66); vec3 skyHor = vec3(0.95, 0.72, 0.44); vec3 col = mix(skyHor, skyTop, pow(clamp((uv.y + 0.12) * 1.5, 0.0, 1.0), 0.65)); float sunD = length(uv - sunPos); col += vec3(1.0, 0.85, 0.52) * exp(-sunD * 4.5) * 0.85; col += vec3(1.0, 0.96, 0.86) * smoothstep(0.065, 0.025, sunD) * 2.2; float windT = iTime * max(P_WIND_SPEED, 0.0); float bendStr = max(P_BEND_STRENGTH, 0.0); float dens = clamp(P_BLADE_DENSITY, 0.35, 2.2); float transGain = max(P_TRANSLUCENCY, 0.0); // Rolling distant meadow hill silhouette float hill = -0.04 + 0.055 * sin(uv.x * 2.4 + 0.5) + 0.025 * cos(uv.x * 5.2); if (uv.y < hill) { float dHill = clamp((hill - uv.y) * 4.0, 0.0, 1.0); col = mix(vec3(0.24, 0.38, 0.14), vec3(0.07, 0.14, 0.05), dHill); } // Render 16 depth-sorted parallax grass strata from far horizon to near foreground for (int layer = 0; layer < 16; layer++) { float fl = float(layer) / 15.0; // 0 = far, 1 = near float depth = mix(0.22, 1.0, fl * fl); float baseY = mix(hill - 0.01, -0.56, pow(fl, 1.12)) + 0.025 * sin(uv.x * (2.6 + fl * 1.5) + fl * 4.0); float bladeH = mix(0.09, 0.44, fl * fl); // Quick vertical culling for layer if (uv.y > baseY + bladeH * 1.15) continue; float freq = mix(42.0, 11.0, fl) * dens; float xCoord = (uv.x + 0.35 * fl) * freq; float baseCell = floor(xCoord); // Check current and +/- 1 neighbor blade cells so strongly bent blades never clip for (int nb = -1; nb <= 1; nb++) { float cid = baseCell + float(nb); float r1 = hash21(vec2(cid, float(layer) * 19.1)); float r2 = hash21(vec2(cid * 1.7 + 3.1, float(layer) * 7.3)); float r3 = hash21(vec2(cid * 2.3 - 1.9, float(layer) * 11.7)); float hMul = 0.62 + 0.65 * r1; float H = bladeH * hMul; float yLocal = (uv.y - baseY) / H; if (yLocal < -0.05 || yLocal > 1.02) continue; float t = clamp(yLocal, 0.0, 1.0); float worldX = (cid + 0.15 + 0.7 * r2) / freq - 0.35 * fl; // Coherent wind gust wave sweeping across the field float gust = noise2(vec2(worldX * 2.2 - windT * 0.85, fl * 2.5 - windT * 0.25)); float lean = (r3 - 0.42) * 0.12 + (gust - 0.28) * 0.28 * bendStr; lean += 0.05 * bendStr * sin(windT * 2.6 + worldX * 7.5 + r2 * 6.28); // Quadratic Bezier spine displacement: B(t) = t^2 * lean * H float spineX = worldX + lean * H * (t * t + 0.25 * t); float dx = uv.x - spineX; // Tapered blade width from sturdy stem to sharp tip float halfW = (0.011 + 0.013 * fl) * (1.0 - pow(t, 1.35)) / sqrt(max(dens, 0.4)); float edgeAA = max(px * 1.25, 0.0012); float mask = smoothstep(halfW + edgeAA, halfW - edgeAA, abs(dx)); if (mask > 0.001) { // Curved cross-section blade normal + central spine crease float across = clamp(dx / (halfW + 1e-4), -1.0, 1.0); vec3 nBlade = normalize(vec3(across * 0.65, 0.25 + 0.35 * t, 0.72)); vec3 lDir = normalize(vec3(sunPos.x - uv.x, sunPos.y - uv.y + 0.35, 0.55)); float ndl = max(dot(nBlade, lDir), 0.0); // Rich chlorophyll palette: deep shaded roots -> sunlit chartreuse tips vec3 rootCol = vec3(0.03, 0.11, 0.025); vec3 midCol = mix(vec3(0.11, 0.34, 0.05), vec3(0.24, 0.46, 0.08), r2); vec3 tipCol = mix(vec3(0.42, 0.62, 0.12), vec3(0.68, 0.72, 0.18), r1); vec3 albedo = mix(rootCol, mix(midCol, tipCol, t), smoothstep(0.0, 0.85, t)); // Root AO + wind wave specular sheen + backlit subsurface translucency float ao = mix(0.22, 1.0, pow(t, 0.65)); float sss = pow(clamp(t, 0.0, 1.0), 1.5) * exp(-length(uv - sunPos) * 1.9) * transGain; float spec = pow(max(dot(nBlade, normalize(lDir + vec3(0.0, 0.0, 1.0))), 0.0), 18.0) * 0.38 * (0.4 + 0.6 * gust); vec3 bladeCol = albedo * (0.28 + 1.15 * ndl) * ao; bladeCol += vec3(0.65, 0.82, 0.14) * sss * 0.95; bladeCol += vec3(0.95, 0.92, 0.68) * spec * t; // Atmospheric horizon mist on distant layers float fog = (1.0 - depth) * 0.55; bladeCol = mix(bladeCol, vec3(0.74, 0.66, 0.50), fog); col = mix(col, bladeCol, mask); } } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Plant Ecosystem Distribution Simulation](https://texelatlas.vercel.app/t/ecosystem-plant-distribution.md): Distribution density maps decide where and how thick grass blades spawn before the instancer reads them. - [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md): Compute culling and indirect draw let huge grass fields render without CPU per-chunk work. ## Sources 1. [primary] Kurt Pelzer GPU Gems ch.7 Rendering Countless Blades of Waving Grass. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems/part-i-natural-effects/chapter-7-rendering-countless-blades-waving-grass (verified via http on 2026-11-29) ## Cite this entry Texel. "GPU grass blade rendering." https://texelatlas.vercel.app/t/grass-blade-rendering/ (accessed 2026-12-01). --- id: "gray-scott-reaction-diffusion" title: "Gray-Scott reaction-diffusion" aliases: [Turing patterns, Gray-Scott] domain: "simulation" stage: "simulation" realtime: "interactive" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 1993 inputs: [texture] outputs: [texture, heightfield] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Pearson, 1993" url: "https://texelatlas.vercel.app/t/gray-scott-reaction-diffusion/" sources_verified_at: "2026-11-29" --- # Gray-Scott reaction-diffusion (Pearson, 1993) > Two chemicals diffusing and reacting on a grid or surface produce spots, stripes, mazes and coral-like patterns that can drive textures, displacement or growth. ## Reach for it when - want spots, stripes or maze patterns that grow - need animal-coat or coral textures that evolve - static noise textures look too artificial - generate organic self-organising patterns on a grid ## How it works Two concentration fields A and B update by `A' = A + (Da*lap(A) - A*B*B + f*(1-A))*dt` and `B' = B + (Db*lap(B) + A*B*B - (k+f)*B)*dt`. The feed rate `f` and kill rate `k` pick the regime: spots, worms, mazes, solitons. The Laplacian is a 3x3 stencil on a texture; on GPUs the update is a ping-pong fragment pass or compute pass, run many substeps per frame because the system evolves slowly. On meshes the Laplacian is a cotangent or graph Laplacian, or the pattern is simulated in a UV atlas (Turk, Witkin and Kass). The resulting B field is mapped to colour, bump, or used as a mask for growth and material. ## When to use it Choose it when you want organic, self-organising patterns (animal coats, coral, cracks of paint, worm textures) that animate or evolve. Prefer [Physarum agent transport networks](https://texelatlas.vercel.app/t/physarum-transport-networks.md) when you want branching network paths, noise-based procedural textures when you need direct per-pixel evaluation without a simulation state, and [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md) when the pattern should advect with flow. ## Cost cheap — Cheap on a 512^2 grid but needs several substeps per frame. Measured GPU Weight: 3.11× baseline (light) — 0.1022 ms median / 0.1056 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.73× baseline (light) — 0.0434 ms median (2.35× faster on L4). Ampere A100 scaling: 1.98× baseline (feather) — 0.0569 ms median (1.8× faster on A100). ## Failure modes - Parameter space is narrow; most (f,k) values give a flat or dead field - Pattern is resolution dependent: features scale with the grid and Da/Db - Explicit stencil requires small dt to stay stable - On meshes with uneven triangles, patterns stretch and have visible seams in UV space ## Dataflow - Inputs: texture - Outputs: texture, heightfield - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Analytic reaction-diffusion look (no simulation) (glsl-fragment; rendered 2026-11-29) ```json { "SCALE": 9, "WARP": 0.55, "EDGE": 0.18 } ``` ```glsl // GLSL ES 3.0 - analytic Turing-pattern look (no buffers); written for this index const float SCALE = 9.0; // pattern frequency const float WARP = 0.55; // domain-warp strength const float EDGE = 0.18; // softness of the spot/stripe edge const vec3 COL_A = vec3(0.04, 0.07, 0.16); const vec3 COL_B = vec3(0.95, 0.80, 0.45); float waves(vec2 p, float t) { float s = 0.0; for (int i = 0; i < 6; i++) { float a = 6.2831853 * float(i) / 6.0 + 0.3 * sin(t * 0.2 + float(i)); s += cos(dot(p, vec2(cos(a), sin(a))) + 1.7 * float(i)); } return s / 3.0; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 p = uv * SCALE; float t = iTime; p += WARP * vec2(sin(p.y * 0.7 + t * 0.3), cos(p.x * 0.7 - t * 0.25)); float v = waves(p, t); v += 0.35 * waves(p * 2.1 + 3.0, t); float m = smoothstep(-EDGE, EDGE, v); float rim = exp(-pow(v / 0.35, 2.0)); vec3 col = mix(COL_A, COL_B, m); col += 0.25 * rim * vec3(0.3, 0.5, 0.7); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; an analytic approximation of the look, not a simulation ## Combination ideas - [Tiger-bush drylands](https://texelatlas.vercel.app/ideas/patterned-dryland-vegetation/) ## Sources 1. [primary] John E. Pearson (1993) Complex Patterns in a Simple System. Science. https://doi.org/10.1126/science.261.5118.189 (verified via crossref on 2026-11-29) 2. [primary] Greg Turk (1991) Generating textures on arbitrary surfaces using reaction-diffusion. Proceedings of the 18th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/122718.122749 (verified via crossref on 2026-11-29) 3. [primary] Andrew Witkin, Michael Kass (1991) Reaction-diffusion textures. Proceedings of the 18th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/122718.122750 (verified via crossref on 2026-11-29) 4. [tutorial] Karl Sims Reaction-Diffusion Tutorial. karlsims.com. https://www.karlsims.com/rd.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Gray-Scott reaction-diffusion." https://texelatlas.vercel.app/t/gray-scott-reaction-diffusion/ (accessed 2026-12-01). --- id: "greebling" title: "Greebling" aliases: [greebles, kitbashing detail, surface detail scattering] domain: "procgen" stage: "procedural" realtime: "offline" platforms: [blender, houdini, cpu, python] year_introduced: 1977 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "offline" authority: "Wikipedia" url: "https://texelatlas.vercel.app/t/greebling/" sources_verified_at: "2026-11-29" --- # Greebling (Wikipedia) > Adds small, plausible-looking mechanical detail (boxes, pipes, panels, vents) over large hard-surface forms so a flat hull or wall reads as complex, engineered scale. ## Reach for it when - flat spaceship hull looks empty and scale-less - sci-fi wall needs fine mechanical detail fast - large surfaces read as toy-like without small details - automatically scatter pipes, panels and vents - make machinery look engineered and huge ## How it works The base mesh is analysed for face regions: large planar quads are split into panels by recursive subdivision (often along their longer axis), and each resulting panel is displaced by a small random depth or extruded into a block, with sizes sampled from a distribution that mimics real manufacturing detail. Greeble kits are libraries of small modules (vents, hatches, pipes) scattered onto panels with instancing, with size and density tied to distance from edges or to a mask. Rules can enforce orientation, spacing (blue noise) and no-intersection tests. The effect is mostly additive geometry or normal-map detail, giving high visual complexity at low authoring cost. ## When to use it Choose it for spaceships, sci-fi walls and machinery, where the silhouette and secondary detail sell scale. Prefer [CGA Shape Grammar (Procedural Buildings)](https://texelatlas.vercel.app/t/cga-shape-grammar.md) for architectural facades with consistent structure, [Procedural Kit Modeling with Verification (procgen-kit)](https://texelatlas.vercel.app/t/procedural-kit-modeling.md) when parts must be parametric, watertight and collision-verified, and [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md) for the placement of modules. ## Cost offline — Mesh generation with many instances; real-time use relies on instancing, normal maps or baked detail. Measured GPU Weight: 155.45× baseline (extreme) — 5.1144 ms median / 5.175 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 129.42× baseline (extreme) — 2.0577 ms median (2.49× faster on L4). Ampere A100 scaling: 102.19× baseline (extreme) — 2.943 ms median (1.74× faster on A100). ## Failure modes - Random uniform detail looks noisy without hierarchy: real structures have large, medium and small elements - Overlapping or floating modules because placement ignores neighbour geometry - Scale confusion: wrong module size relative to implied human scale breaks the sense of size - Triangle counts balloon quickly if the splits are not limited ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: blender, houdini, cpu, python ## Presets ### Hierarchical sci-fi hull greebling — recursive panel subdivision, extruded blocks, vents and lights (glsl-fragment; rendered 2026-11-30) ```json { "SCALE": 3.2, "DEPTH": 0.16, "PANEL_DETAIL": 4, "LIGHT_DENSITY": 0.28 } ``` ```glsl const float SCALE = 3.2; // P const float DEPTH = 0.16; // P const int PANEL_DETAIL = 4; // P const float LIGHT_DENSITY = 0.28; // P float hash21(vec2 p) { vec3 q = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); } // Multi-level recursive quad-panel greeble heightfield (large hull plates -> modules -> vents/pipes) vec3 evalGreeble(vec2 p, out float lightMask, out float seamMask) { int levels = clamp(PANEL_DETAIL, 1, 5); float h = 0.0; float matTone = 0.5; lightMask = 0.0; seamMask = 0.0; vec2 q = p * max(SCALE, 0.5); float amp = 1.0; for (int lv = 0; lv < 5; lv++) { if (lv >= levels) break; vec2 id = floor(q); vec2 f = fract(q); float r1 = hash21(id + float(lv) * 19.7); float r2 = hash21(id + float(lv) * 43.3 + 7.1); // Split panel along alternating aspect ratios for authentic engineered hierarchy vec2 edge = min(f, 1.0 - f); float border = min(edge.x, edge.y); float bevel = smoothstep(0.025, 0.075, border); seamMask = max(seamMask, smoothstep(0.06, 0.015, border) * amp); float blockH = (0.25 + 0.75 * r1) * bevel; // Louver cooling vents on ~22% of mid-level panels if (lv >= 1 && r2 > 0.76) { float louver = 0.5 + 0.5 * sin(f.y * 37.7); blockH *= 0.65 + 0.35 * step(0.45, louver); } // Recessed cylindrical conduit pipes on ~18% of panels if (lv == 1 && r2 < 0.20) { float pipe = smoothstep(0.16, 0.04, abs(f.x - 0.5)); blockH = mix(blockH * 0.4, 0.95, pipe); } h += blockH * amp; matTone = mix(matTone, 0.28 + 0.52 * r2, amp * 0.45); // Tiny glowing viewport slits on fine panels if (lv >= 2 && r1 < clamp(LIGHT_DENSITY, 0.0, 1.0)) { float win = smoothstep(0.18, 0.10, abs(f.y - 0.5)) * smoothstep(0.36, 0.28, abs(f.x - 0.5)); lightMask = max(lightMask, win * (r2 > 0.5 ? 1.0 : 2.0)); } // Subdivide selectively based on cell hash so large plates coexist with dense clusters float sub = (r1 > 0.35) ? 2.0 : 1.0; q = fract(q) * sub + floor(q) * 2.0 + vec2(r2 * 1.3, r1 * 2.1); amp *= 0.52; } return vec3(h * max(DEPTH, 0.01), matTone, 0.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float camTilt = 0.28; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { camTilt = clamp((iMouse.y / iResolution.y) * 0.65 + 0.05, 0.05, 0.72); } vec3 ro = vec3(0.0, 1.35, -iTime * 0.35); vec3 rd = normalize(vec3(uv.x, uv.y - camTilt - 0.32, -1.25)); // Raymarch perspective hull heightfield y = greeble(xz) float t = 0.4, maxT = 16.0; bool hit = false; float lm = 0.0, sm = 0.0; vec3 gVal = vec3(0.0); for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; gVal = evalGreeble(p.xz, lm, sm); float d = p.y - gVal.x; if (d < 0.004) { hit = true; break; } t += max(d * 0.55, 0.025 + t * 0.012); if (t > maxT) break; } vec3 sky = mix(vec3(0.02, 0.04, 0.08), vec3(0.10, 0.16, 0.28), clamp(uv.y + 0.5, 0.0, 1.0)); vec3 col = sky; if (hit) { vec3 p = ro + rd * t; float e = 0.008 + 0.003 * t; float l0, s0; float hx = evalGreeble(p.xz + vec2(e, 0.0), l0, s0).x - gVal.x; float hz = evalGreeble(p.xz + vec2(0.0, e), l0, s0).x - gVal.x; vec3 n = normalize(vec3(-hx, e, -hz)); vec3 keyDir = normalize(vec3(0.72, 0.58, 0.38)); vec3 rimDir = normalize(vec3(-0.75, 0.35, -0.55)); float nl = max(dot(n, keyDir), 0.0); float rim = max(dot(n, rimDir), 0.0); vec3 H = normalize(keyDir - rd); float spec = pow(max(dot(n, H), 0.0), 36.0); float ao = clamp(0.32 + 0.68 * (gVal.x / max(DEPTH * 1.4, 0.01)), 0.22, 1.0) * (1.0 - sm * 0.48); vec3 hullAlb = mix(vec3(0.16, 0.19, 0.24), vec3(0.46, 0.50, 0.55), gVal.y); col = hullAlb * ao * (vec3(0.08, 0.13, 0.22) + vec3(1.65, 1.48, 1.25) * nl + vec3(0.28, 0.52, 0.85) * rim * 0.65); col += vec3(0.95, 0.90, 0.82) * spec * ao * 0.55; // Emissive hull viewport lights (amber & cyan) if (lm > 0.05) { vec3 eCol = (lm > 1.5) ? vec3(0.35, 1.65, 2.4) : vec3(2.4, 1.35, 0.35); col += eCol * smoothstep(0.05, 0.9, fract(lm + 0.999)); } col = mix(col, sky, 1.0 - exp(-0.085 * t)); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Sources 1. [primary] Wikipedia Greeble. en.wikipedia.org. https://en.wikipedia.org/wiki/Greeble (verified via http on 2026-11-29) ## Cite this entry Texel. "Greebling." https://texelatlas.vercel.app/t/greebling/ (accessed 2026-12-01). --- id: "greedy-voxel-meshing" title: "Greedy meshing for voxel worlds" aliases: [greedy mesher, binary greedy meshing] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, unity, unreal, godot] year_introduced: 2012 inputs: [voxels] outputs: [mesh] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Lysenko" url: "https://texelatlas.vercel.app/t/greedy-voxel-meshing/" sources_verified_at: "2026-11-29" --- # Greedy meshing for voxel worlds (Lysenko) > Turns a chunk of blocky voxels into far fewer quads by hiding interior faces and merging coplanar neighbouring faces of the same type into larger rectangles. ## Reach for it when - voxel chunk has far too many triangles - minecraft style terrain mesh optimisation - merge adjacent block faces into bigger quads - chunk remeshing takes too long after edits ## How it works First cull faces between two solid voxels, leaving only the visible boundary. Then, for each of the six face directions and each slice perpendicular to it, build a 2D mask of visible faces tagged with their block type, light and any other attribute that must match. Sweep the mask: at the first unvisited cell, grow the rectangle along one axis while neighbours have the same tag, then grow along the other axis while the entire row matches, emit one quad, and clear those mask cells. The result is not minimal but close, and linear in chunk volume. Ambient occlusion baked per vertex or per face blocks merging unless it matches, so merge keys must include it. Bitwise variants process whole columns of 64 voxels with bit tricks for much faster meshing. ## When to use it Choose it for Minecraft-style worlds where chunk meshes are rebuilt on edits and vertex count or draw bandwidth matters. Prefer [Surface Nets](https://texelatlas.vercel.app/t/surface-nets.md), [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) or [Dual Contouring](https://texelatlas.vercel.app/t/dual-contouring.md) when the voxel data is a smooth scalar field rather than blocks, [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md) to post-process any mesh, and ray marching over the grid with [Voxel grid DDA ray traversal (Amanatides–Woo)](https://texelatlas.vercel.app/t/voxel-grid-dda-traversal.md) when you would rather not build a mesh at all. ## Cost cheap — Meshing is per chunk on the CPU or a compute shader and amortised across frames; runtime cost is the reduced triangle count. Measured GPU Weight: 14.2× baseline (moderate) — 0.446 ms median / 0.462 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.94× baseline (moderate) — 0.2202 ms median (2.03× faster on L4). Ampere A100 scaling: 9.76× baseline (moderate) — 0.2811 ms median (1.59× faster on A100). ## Failure modes - T-junction cracks and sparkling pixels where large merged quads meet smaller ones, especially with texture atlases - Texture atlas bleeding or stretched UVs because merged quads need tiling rather than a single tile - Per-vertex AO or lighting gradients look wrong on merged quads, so merge keys must include them or lighting must be moved to the shader - Chunk borders need neighbour data, or you get seams and hidden-face mistakes at edges ## Dataflow - Inputs: voxels - Outputs: mesh - Platforms: cpu, webgl2, webgpu, desktop-gpu, unity, unreal, godot ## Presets ### Greedy voxel meshing — per-voxel 1×1 quad faces (left) vs merged maximal rectangular greedy quads (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VOXEL_GRID": 1, "P_MERGE_COLORS": 0.78, "P_SPLIT": 0.45, "P_ROT_SPEED": 1 } ``` ```glsl const float P_VOXEL_GRID = 1.0; // P Wire Contrast [0.2, 1.6, 0.05] const float P_MERGE_COLORS = 0.78; // P Merged Quad Tint [0.0, 1.0, 0.02] const float P_SPLIT = 0.45; // P Naive / Greedy Split [0.0, 1.0, 0.02] const float P_ROT_SPEED = 1.0; // P Orbit Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } // Terraced voxel chunk height (integer voxel layers inside [-6, 6]^2 -> ideal for greedy rectangular merging!) float voxelChunkHeight(vec2 cell) { vec2 a = abs(cell); if (a.x > 5.5 || a.y > 5.5) return -10.0; // Crisp stepped architectural plateaus (flat runs merge cleanly into single large greedy quads!) float h = 1.0; if (a.x <= 3.5 && a.y <= 3.5) h = 3.0; if (cell.x >= -2.5 && cell.x <= 1.5 && cell.y >= -1.5 && cell.y <= 2.5) h = 5.0; if (cell.x >= 2.5 && cell.y <= -1.5) h = 4.0; if (cell.x <= -3.5 && cell.y >= 1.5) h = 2.0; return h; } // Evaluate solid occupancy of integer voxel coordinate v bool isVoxelSolid(vec3 v) { if (v.y < 0.0 || v.y > 6.0) return false; float h = voxelChunkHeight(v.xz); return v.y < h; } // Exact Amanatides-Woo 3D DDA voxel traversal returning hit position, voxel coord, and face normal bool traceVoxels(vec3 ro, vec3 rd, out float tHit, out vec3 hitPos, out vec3 voxCoord, out vec3 hitNorm) { // Intersect chunk bounding box [-6, 0, -6] to [6, 6, 6] vec3 bMin = vec3(-6.0, 0.0, -6.0); vec3 bMax = vec3(6.0, 6.0, 6.0); vec3 invD = 1.0 / (rd + sign(rd + 1e-6) * 1e-5); vec3 t0 = (bMin - ro) * invD; vec3 t1 = (bMax - ro) * invD; float tNear = max(max(min(t0.x, t1.x), min(t0.y, t1.y)), min(t0.z, t1.z)); float tFar = min(min(max(t0.x, t1.x), max(t0.y, t1.y)), max(t0.z, t1.z)); if (tFar < max(tNear, 0.0)) return false; float tStart = max(tNear, 0.0) + 0.001; vec3 p = ro + rd * tStart; vec3 mapP = floor(p); vec3 deltaDist = abs(invD); vec3 stepDir = sign(rd); vec3 sideDist = (stepDir * (mapP - p) + (stepDir * 0.5) + 0.5) * deltaDist; vec3 mask = vec3(0.0); for (int i = 0; i < 42; i++) { if (isVoxelSolid(mapP)) { tHit = tStart + dot(mask, sideDist - deltaDist); hitPos = ro + rd * tHit; voxCoord = mapP; // Handle immediate entry hit on outer bounding box face if (dot(mask, mask) < 0.5) { vec3 rel = abs(hitPos - vec3(0.0, 3.0, 0.0)) / vec3(6.0, 3.0, 6.0); if (rel.x > rel.y && rel.x > rel.z) hitNorm = vec3(sign(hitPos.x), 0.0, 0.0); else if (rel.y > rel.z) hitNorm = vec3(0.0, sign(hitPos.y - 3.0), 0.0); else hitNorm = vec3(0.0, 0.0, sign(hitPos.z)); } else { hitNorm = -mask * stepDir; } return true; } mask = step(sideDist.xyz, sideDist.yzx) * step(sideDist.xyz, sideDist.zxy); sideDist += mask * deltaDist; mapP += mask * stepDir; if (any(lessThan(mapP, bMin - vec3(1.0))) || any(greaterThan(mapP, bMax + vec3(1.0)))) break; } return false; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float wireGain = clamp(P_VOXEL_GRID, 0.1, 1.8); float mergeTint = clamp(P_MERGE_COLORS, 0.0, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0); // Orbiting isometric-style 3/4 camera around the voxel island float camAng = 0.65 + spin * 0.25; vec3 ro = vec3(cos(camAng) * 14.5, 10.5, sin(camAng) * 14.5); vec3 ta = vec3(0.0, 2.0, 0.0); vec3 fw = normalize(ta - ro); vec3 rt = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(rt, fw); vec3 rd = normalize(fw * 1.65 + rt * uv.x + up * uv.y); vec3 col = mix(vec3(0.035, 0.048, 0.075), vec3(0.10, 0.14, 0.21), smoothstep(-0.5, 0.6, uv.y)); float tHit; vec3 hp, vc, n; if (traceVoxels(ro, rd, tHit, hp, vc, n)) { // Tangent axes (uAxis, vAxis) on the hit voxel face vec3 uAxis = (abs(n.y) > 0.5) ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0); vec3 vAxis = normalize(cross(n, uAxis)); vec2 fLocal = vec2(fract(dot(hp, uAxis)), fract(dot(hp, vAxis))); // Naive 1x1 voxel face wireframe (draws border around EVERY single voxel unit!) float dNaive = min(min(fLocal.x, 1.0 - fLocal.x), min(fLocal.y, 1.0 - fLocal.y)); float naiveWire = smoothstep(0.085, 0.02, dNaive); // Greedy Voxel Meshing: check whether adjacent coplanar neighbors share the EXACT same exposed face! // If neighbor is solid AND its outward neighbor (along +n) is empty, the face edge is MERGED away! bool mergeU0 = isVoxelSolid(vc - uAxis) && !isVoxelSolid(vc - uAxis + n); bool mergeU1 = isVoxelSolid(vc + uAxis) && !isVoxelSolid(vc + uAxis + n); bool mergeV0 = isVoxelSolid(vc - vAxis) && !isVoxelSolid(vc - vAxis + n); bool mergeV1 = isVoxelSolid(vc + vAxis) && !isVoxelSolid(vc + vAxis + n); float dGreedy = 1.0; if (!mergeU0) dGreedy = min(dGreedy, fLocal.x); if (!mergeU1) dGreedy = min(dGreedy, 1.0 - fLocal.x); if (!mergeV0) dGreedy = min(dGreedy, fLocal.y); if (!mergeV1) dGreedy = min(dGreedy, 1.0 - fLocal.y); float greedyWire = smoothstep(0.10, 0.022, dGreedy); // Deterministic greedy patch ID color by walking toward (-u, -v) corner of the coplanar run vec3 patchAnchor = vc; for (int s = 0; s < 5; s++) { if (isVoxelSolid(patchAnchor - uAxis) && !isVoxelSolid(patchAnchor - uAxis + n)) patchAnchor -= uAxis; } for (int s = 0; s < 5; s++) { if (isVoxelSolid(patchAnchor - vAxis) && !isVoxelSolid(patchAnchor - vAxis + n)) patchAnchor -= vAxis; } vec3 patchCol = 0.30 + 0.65 * hash33(patchAnchor * 1.7 + n * 5.3 + 9.1); // Base biome voxel albedo (grass top, sandstone mid, basalt base) vec3 biomeAlb = (n.y > 0.5) ? vec3(0.32, 0.72, 0.36) : ((vc.y >= 3.0) ? vec3(0.78, 0.64, 0.44) : vec3(0.42, 0.48, 0.56)); bool isGreedy = screenX >= split; vec3 alb = isGreedy ? mix(biomeAlb, patchCol, mergeTint * 0.72) : biomeAlb; vec3 l1 = normalize(vec3(0.55, 0.88, 0.45)); float diff = max(dot(n, l1), 0.0); float hemi = 0.32 + 0.16 * n.y; col = alb * (hemi + 0.85 * diff); if (isGreedy) { // Crisp bright border ONLY around merged maximal greedy quads! col = mix(col, vec3(0.98, 0.96, 0.72), greedyWire * 0.85 * min(wireGain, 1.2)); // Very faint hint of eliminated internal voxel grid lines col = mix(col, col * 0.88, naiveWire * 0.25); } else { // Heavy dark grid on every unmerged 1x1 voxel face + diagonal split (2 tris per face!) float diag = smoothstep(0.055, 0.012, abs(fLocal.x - fLocal.y)); col = mix(col, vec3(0.04, 0.06, 0.09), max(naiveWire * 0.85, diag * 0.38) * min(wireGain, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Voxel grid DDA ray traversal (Amanatides–Woo)](https://texelatlas.vercel.app/t/voxel-grid-dda-traversal.md): The same voxel grid can be edited and picked with DDA rays while the greedy mesher produces the chunk geometry for rendering. ## Sources 1. [primary] Mikola Lysenko Meshing in a Minecraft Game. 0fps.net. https://0fps.net/2012/06/30/meshing-in-a-minecraft-game (verified via http on 2026-11-29) 2. [implementation] mikolalysenko (2013) mikolalysenko/greedy-mesher. https://github.com/mikolalysenko/greedy-mesher License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Greedy meshing for voxel worlds." https://texelatlas.vercel.app/t/greedy-voxel-meshing/ (accessed 2026-12-01). --- id: "ground-truth-ambient-occlusion" title: "Ground-Truth Ambient Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2016 inputs: [depth, normals] outputs: [visibility-mask, normals] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Jimenez et al." url: "https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion/" sources_verified_at: "2026-11-29" --- # Ground-Truth Ambient Occlusion (Jimenez et al.) > A horizon-based AO that integrates the cosine-weighted visibility in closed form, matching a path-traced ground truth for the depth-buffer model and cheap enough for games. ## Reach for it when - cheap ao on mobile or console budgets - ssao looks noisy or too dark and grayish - contact shadows in crevices missing in screen space - ambient occlusion that matches ray traced reference ## How it works GTAO slices the hemisphere with a few screen-space planes. For each slice it finds the two horizon angles (left and right) by marching the depth buffer and integrates the cosine-weighted visible arc analytically, projecting the surface normal into the slice. The per-slice results are averaged across rotated slices per pixel and across frames. Because it uses the exact cosine kernel it avoids the bias of earlier approximations, and the same horizons give a bent normal and an AO value that feeds a multi-bounce correction. The paper pairs it with a temporal and spatial denoiser at a low sample count. ## When to use it Choose it as the default quality AO for deferred or forward+ renderers with depth and normals. Prefer [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) for older codebases and [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) if you have almost no GPU budget; prefer [Visibility Bitmask Ambient Occlusion](https://texelatlas.vercel.app/t/visibility-bitmask-ssao.md) when thin geometry matters, and [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) for off-screen accuracy. ## Cost cheap — About one to two ms at 1080p on desktop for a 2 to 4 slice setup including denoise, depending on resolution and implementation. Measured GPU Weight: 35.42× baseline (heavy) — 1.1653 ms median / 1.189 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 28.33× baseline (heavy) — 0.4505 ms median (2.59× faster on L4). Ampere A100 scaling: 21.19× baseline (heavy) — 0.6102 ms median (1.91× faster on A100). ## Failure modes - Assumes infinite thickness behind the depth buffer, so thin objects cast overly large occlusion - Temporal denoiser ghosting on fast motion - Radius-dependent artifacts at screen edges where horizons are unknown - Self-occlusion on tessellated normals ## Engine support - blender: builtin — `EEVEE Raytracing / Fast GI Approximation & Ambient Occlusion node` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/input/ao.html, checked 2026-12-01) - threejs: official — `import { ao } from 'three/addons/tsl/display/GTAONode.js' (WebGL: GTAOPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/GTAONode.js, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Lighting > Ambient Occlusion` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/HDRenderPipeline.AmbientOcclusion.cs, checked 2026-12-01) — HDRP only; the AO override is GTAO. - unreal: builtin — `Post Process Volume > Ambient Occlusion (Screen Space Ambient Occlusion / GTAO via r.AmbientOcclusion.Method)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask, normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: flat ambient. Right: GTAO, closed-form cosine-weighted visibility between two horizons per slice (glsl-fragment; rendered 2026-11-29) ```json { "INT": 1.6, "NS": 4, "NSTEP": 8, "RADS": 0.7 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const float INT=1.6; // P const int NS=4; // P const int NSTEP=8; // P const float RADS=0.7; // P float gtao(vec3 P,vec3 N,vec2 uv){ vec3 V=normalize(RO-P);float zp=P.z-RO.z,vis=0.; for(int d=0;d1e8)continue; vec3 D=unproj(u2,zs)-P;float l=length(D); float c=mix(-1.,dot(D/l,V),max(1.-l*l/(RADS*RADS),0.)); if(k==0)c1=max(c1,c);else c2=max(c2,c);}} float h1=n+max(-acos(c2)-n,-1.5707963),h2=n+min(acos(c1)-n,1.5707963); vis+=pl*.25*(-cos(2.*h1-n)+cos(n)+2.*h1*sin(n)-cos(2.*h2-n)+cos(n)+2.*h2*sin(n));} return clamp(vis/float(NS),0.,1.);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao=R?clamp(1.-INT*(1.-gtao(P,n,uv)),0.,1.):1.;col=mix(ambShade(P,n,vec3(ao)),sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extends [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) ## Combines with - [Multi-Bounce Ambient Occlusion Approximation](https://texelatlas.vercel.app/t/multi-bounce-ambient-occlusion.md): GTAO produces single-bounce visibility that the multi-bounce fit brightens using surface albedo. - [Bent Normals](https://texelatlas.vercel.app/t/bent-normals.md): The same horizon pass can output the average unoccluded direction used to look up diffuse and specular lighting. ## Combination ideas - [Hatching that deepens in the creases](https://texelatlas.vercel.app/ideas/occlusion-driven-hatching/) ## Sources 1. [primary] Jorge Jimenez, Xian-Chun Wu, Angelo Pesce, Adrian Jarabo Practical Real-Time Strategies for Accurate Indirect Occlusion. SIGGRAPH 2016 Course: Physically Based Shading in Theory and Practice. https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf (verified via http on 2026-11-29) 2. [implementation] GameTechDev (2021) GameTechDev/XeGTAO. https://github.com/GameTechDev/XeGTAO License: MIT. (verified via github on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Ground-Truth Ambient Occlusion." https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion/ (accessed 2026-12-01). --- id: "ground-truth-specular-occlusion" title: "Ground-Truth Specular Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2016 inputs: [normals, depth] outputs: [visibility-mask] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Jimenez et al." url: "https://texelatlas.vercel.app/t/ground-truth-specular-occlusion/" sources_verified_at: "2026-11-29" --- # Ground-Truth Specular Occlusion (Jimenez et al.) > Converts the AO visibility cone and the specular lobe into an intersection so reflections are darkened only where the lobe actually faces occluders. ## Reach for it when - reflections glow inside crevices where they should be dark - specular light leaks through occluded areas - screen-space occlusion darkens spec wrongly or not at all - need cheap reflection occlusion for probe lighting ## How it works Specular lighting from probes or environment maps ignores local geometry, so reflections leak into crevices. The method models the unoccluded region as a cone around the bent normal with aperture from the AO value, and the specular lobe as a cone around the reflection vector with width from roughness. It then evaluates the solid-angle overlap of the two cones analytically, and fits the result with a compact function of AO, roughness and the angle between the cones. Multiply the result into specular ambient lighting. It needs the bent normal and AO from the same pass and a few ALU instructions. ## When to use it Choose it for image-based specular lighting with screen-space AO when reflections leak into occluded areas. Prefer a real traced term ([Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) or reflection tracing) when accuracy matters more than cost, and plain horizon occlusion ([Bent Normals](https://texelatlas.vercel.app/t/bent-normals.md)) for a cruder fix. ## Cost cheap — A few ALU instructions per pixel plus bent normals from the AO pass. Measured GPU Weight: 31.25× baseline (heavy) — 1.028 ms median / 1.088 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 26.88× baseline (heavy) — 0.4274 ms median (2.41× faster on L4). Ampere A100 scaling: 19.71× baseline (moderate) — 0.5676 ms median (1.81× faster on A100). ## Failure modes - Depends on a correct bent normal and AO input - Approximate for rough lobes where the cone model is poor - Cannot darken reflections of off-screen blockers - May dim reflections excessively in narrow concavities ## Engine support - babylonjs: builtin — `PBRBaseMaterial bent-normal Spherical Gaussian specular occlusion (environmentBentNormalOcclusion / bentNormalSGOcclusion) and useRadianceOcclusion` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Shaders/ShadersInclude/pbrIBLFunctions.fx, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.bent_normal_enabled = true (applies Jimenez et al. SIGGRAPH 2016 specular cone-cone intersection in scene_forward_clustered.glsl)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl, checked 2026-12-01) ## Dataflow - Inputs: normals, depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Ground-truth specular occlusion — cone-cone visibility vs naive scalar AO split (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.24, "P_AO_STRENGTH": 1, "P_METALLIC": 0.85, "P_SPLIT": 0.45 } ``` ```glsl const float P_ROUGHNESS = 0.24; // P Roughness [0.06, 0.75, 0.02] const float P_AO_STRENGTH = 1.0; // P AO Strength [0.0, 1.5, 0.05] const float P_METALLIC = 0.85; // P Metallic [0.0, 1.0, 0.02] const float P_SPLIT = 0.45; // P Naive/GTSO Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } // Glossy nested metallic rings & recessed sphere over a reflective tiled floor (crevice torture test) vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.78, 1.0); vec3 q = p - vec3(0.0, -0.04, 0.0); q.xz = rot2(iTime * 0.28) * q.xz; float dCore = length(q) - 0.56; // Deep equatorial crevices & interlocking rings that create strong directional visibility cones float dR1 = sdTorus(q, vec2(0.68, 0.16)); vec3 q2 = q; q2.xy = rot2(1.05) * q2.xy; float dR2 = sdTorus(q2, vec2(0.68, 0.15)); float dSculpt = min(dCore, min(dR1, dR2)); if (dSculpt < res.x) res = vec2(dSculpt, 2.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // High-contrast studio HDR environment with overhead softbox strips & horizon band vec3 sampleEnv(vec3 d, float rough) { float y = d.y; vec3 sky = mix(vec3(0.10, 0.12, 0.17), vec3(0.36, 0.46, 0.62), smoothstep(-0.1, 0.75, y)); // Crisp softbox light strips that visibly reflect across glossy curves float strip1 = smoothstep(0.62 - rough * 0.25, 0.92, dot(d, normalize(vec3(0.55, 0.78, 0.35)))); float strip2 = smoothstep(0.68 - rough * 0.25, 0.95, dot(d, normalize(vec3(-0.72, 0.52, 0.42)))); float horiz = exp(-abs(y - 0.04) * mix(16.0, 3.0, rough)); sky += vec3(3.2, 2.8, 2.3) * strip1; sky += vec3(1.4, 2.1, 3.0) * strip2; sky += vec3(0.85, 0.72, 0.58) * horiz * 0.65; return sky; } // Analytic spherical cap intersection of bent-normal visibility cone & specular reflection lobe (GTSO) float sphericalCapIntersection(float f0, float f1, float d) { float r0 = max(f0, 1e-4); float r1 = max(f1, 1e-4); if (d >= r0 + r1) return 0.0; if (d <= abs(r0 - r1)) return 6.2831853 * (1.0 - cos(min(r0, r1))); float c0 = cos(r0), s0 = sin(r0); float c1 = cos(r1), s1 = sin(r1); float cd = cos(d), sd = sin(d); float a0 = acos(clamp((c1 - c0 * cd) / (s0 * sd + 1e-5), -1.0, 1.0)); float a1 = acos(clamp((c0 - c1 * cd) / (s1 * sd + 1e-5), -1.0, 1.0)); float a2 = acos(clamp((cd - c0 * c1) / (s0 * s1 + 1e-5), -1.0, 1.0)); return max(0.0, 2.0 * (3.14159265 - a2 - a0 * c0 - a1 * c1)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; vec3 ro = vec3(0.0, 0.45, 2.65); vec3 ta = vec3(0.0, -0.14, 0.0); vec3 ww = normalize(ta - ro); vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.55 * ww); float rough = clamp(P_ROUGHNESS, 0.05, 0.85); float aoStr = clamp(P_AO_STRENGTH, 0.0, 1.6); float metal = clamp(P_METALLIC, 0.0, 1.0); float splitX = clamp(P_SPLIT, 0.0, 1.0); vec3 col = sampleEnv(rd, 0.45) * 0.25; float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 v = -rd; vec3 rDir = reflect(rd, n); // Estimate diffuse visibility AO & bent normal over 6 hemispherical directions vec3 tV = normalize(abs(n.y) < 0.9 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0))); vec3 bV = cross(n, tV); float visSum = 0.0; vec3 bentAccum = vec3(0.0); for (int k = 0; k < 6; k++) { float phi = float(k) * 1.0472 + 0.35; vec3 d = normalize(n * 0.58 + (cos(phi) * tV + sin(phi) * bV) * 0.815); float s1 = mapScene(p + d * 0.14).x / 0.14; float s2 = mapScene(p + d * 0.34).x / 0.34; float vis = clamp(min(s1, s2), 0.0, 1.0); visSum += vis; bentAccum += d * (vis + 0.03); } float diffAO = clamp(1.0 - (1.0 - visSum / 6.0) * aoStr, 0.02, 1.0); vec3 bentN = normalize(bentAccum + n * 0.05); // Also evaluate direct cone visibility along reflection vector for ground-truth specular occlusion float reflTrace = clamp(min(mapScene(p + rDir * 0.18).x / 0.18, mapScene(p + rDir * 0.45).x / 0.45), 0.0, 1.0); // Cone-cone intersection GTSO (Jimenez / Oat & Sander): // Visibility cone half-angle from diffuse AO; specular cone half-angle from roughness float visAngle = acos(clamp(1.0 - diffAO, -1.0, 1.0)); float specAngle = clamp(rough * 1.15 + 0.08, 0.08, 1.25); float coneSep = acos(clamp(dot(bentN, rDir), -1.0, 1.0)); float specCap = 6.2831853 * (1.0 - cos(specAngle)); float coneOverlap = sphericalCapIntersection(visAngle, specAngle, coneSep) / max(specCap, 1e-4); float gtso = clamp(mix(coneOverlap, coneOverlap * reflTrace, 0.55), 0.0, 1.0); gtso = mix(1.0, gtso, clamp(aoStr, 0.0, 1.0)); // Left: naive scalar AO * specular; Right: Ground-Truth Specular Occlusion float specOcc = (screenUV.x < splitX) ? diffAO : gtso; vec3 baseCol = (matId < 1.5) ? vec3(0.42, 0.45, 0.50) : vec3(0.92, 0.74, 0.46); float ndv = max(dot(n, v), 0.001); vec3 f0 = mix(vec3(0.04), baseCol, metal); vec3 fres = f0 + (1.0 - f0) * pow(1.0 - ndv, 5.0); vec3 envDiff = sampleEnv(bentN, 0.95) * (1.0 - metal) * baseCol * diffAO * 0.55; vec3 envSpec = sampleEnv(rDir, rough) * fres * specOcc * 1.15; // Subtle key light highlight vec3 lDir = normalize(vec3(0.55, 0.82, 0.45)); vec3 hVec = normalize(lDir + v); float specL = pow(max(dot(n, hVec), 0.0), mix(96.0, 10.0, rough)) * specOcc; col = envDiff + envSpec + fres * vec3(1.8, 1.65, 1.45) * specL * 0.5; } if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(1.0, 0.82, 0.35); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Bent Normals](https://texelatlas.vercel.app/t/bent-normals.md): Bent normal supplies the cone axis that the specular lobe is intersected against. ## Sources 1. [primary] Jorge Jimenez, Xian-Chun Wu, Angelo Pesce, Adrian Jarabo Practical Real-Time Strategies for Accurate Indirect Occlusion. SIGGRAPH 2016 Course: Physically Based Shading in Theory and Practice. https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Ground-Truth Specular Occlusion." https://texelatlas.vercel.app/t/ground-truth-specular-occlusion/ (accessed 2026-12-01). --- id: "gsplat" title: "gsplat" domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [photos, camera-poses, point-cloud] outputs: [gaussians] style: "photoreal" dynamic: "static" cost: "medium" authority: "Ye et al., 2024" url: "https://texelatlas.vercel.app/t/gsplat/" sources_verified_at: "2026-11-29" --- # gsplat (Ye et al., 2024) > An open-source CUDA library and PyTorch API for differentiable Gaussian rasterisation, with training strategies, compression and several camera models, used inside Nerfstudio. ## Reach for it when - need a maintained library to train gaussian scenes in python - want permissive licence for splat training code - extend differentiable gaussian rasterisation in pytorch - compress or tweak splat training strategies - use splats inside nerfstudio ## How it works gsplat packages the forward and backward passes of Gaussian rasterisation as PyTorch-callable CUDA ops: projection to screen space, tile intersection and sorting, and alpha compositing, each with analytic gradients. On top it provides reusable training strategies (default densification, absolute-gradient densification, MCMC-based relocation), anti-aliased rasterisation, support for pinhole, fisheye and orthographic cameras, depth outputs and batched or multi-GPU training. Memory-efficiency optimisations reduce peak VRAM and training time compared with the original reference code. Developers use it to build new splat research, or via the Nerfstudio splatfacto method for end-to-end training. ## When to use it Choose it when you want a maintained, permissively licensed (Apache-2.0) library for training or extending Gaussian splatting inside Python. Prefer the original [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) repo to reproduce the paper's exact numbers, and [3DGUT (Unscented Transform Gaussian Splatting)](https://texelatlas.vercel.app/t/3dgut.md) when you need unscented projection of distorted cameras. ## Cost medium — Training time is similar to or better than the reference 3DGS code in the library's own comparisons; check the paper for hardware. ## Failure modes - CUDA toolchain and PyTorch version mismatches complicate installation - Defaults differ from the reference 3DGS, so metrics may not match published numbers - Inherits splatting artefacts such as floaters and non-surface geometry - API evolves quickly, so old training scripts can break ## Dataflow - Inputs: photos, camera-poses, point-cloud - Outputs: gaussians - Platforms: cuda, python ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): COLMAP poses and points are the standard dataset input for gsplat training. ## Sources 1. [primary] Vickie Ye, Ruilong Li, Justin Kerr, Matias Turkulainen, Brent Yi, Zhuoyang Pan, Otto Seiskari, Jianbo Ye, Jeffrey Hu, Matthew Tancik, Angjoo Kanazawa (2024) gsplat: An Open-Source Library for Gaussian Splatting. arXiv preprint (cs.CV). https://arxiv.org/abs/2409.06765 (verified via arxiv on 2026-11-29) 2. [implementation] nerfstudio-project (2023) nerfstudio-project/gsplat. https://github.com/nerfstudio-project/gsplat License: Apache-2.0. (verified via github on 2026-11-29) 3. [tutorial] Nerfstudio project gsplat documentation. docs.gsplat.studio. https://docs.gsplat.studio/ (verified via http on 2026-11-29) ## Cite this entry Texel. "gsplat." https://texelatlas.vercel.app/t/gsplat/ (accessed 2026-12-01). --- id: "guilty-gear-xrd-shading" title: "Guilty Gear Xrd anime-style 3D shading" domain: "npr" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, unreal] year_introduced: 2014 inputs: [mesh, normals, texture] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Motomura" url: "https://texelatlas.vercel.app/t/guilty-gear-xrd-shading/" sources_verified_at: "2026-11-29" --- # Guilty Gear Xrd anime-style 3D shading (Motomura) > A production recipe that makes 3D characters look hand-drawn through artist-edited normals and vertex data, a threshold texture on shading, and custom outlines, animated at a lowered frame rate. ## Reach for it when - anime characters look flat in 3d toon shading - shadow edges on toon faces look ugly and noisy - make 3d model look like hand drawn 2d animation - artist control over shadow shapes on cel shaded characters ## How it works Characters are rendered with a simple toon shader whose light term is thresholded, but the key is how it is controlled: artists edit vertex normals so shadow terminators fall in drawn-looking shapes; a vertex-colour channel biases the threshold per area, and a texture channel adds ink-style lines inside the surface. Outlines combine inverted-hull shells with vertex-colour-driven thickness, plus separate strokes for interior lines. The characters are animated on limited key poses and with hand-adjusted camera angles to mimic 2D animation. The talk lays out these choices and the workflow around them. ## When to use it Choose it when you want hand-controllable, anime-grade stills and animation from 3D, and can afford artist time. Prefer [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md) with a standard ramp for generic stylization, and [Ligne-claire / Moebius-style shading](https://texelatlas.vercel.app/t/ligne-claire-moebius-shading.md) when you want a sparse, European comics look. ## Cost cheap — Cheap shading, plus a hull outline pass; the real cost is authoring. Measured GPU Weight: 35.41× baseline (heavy) — 1.1651 ms median / 1.2162 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 31.63× baseline (heavy) — 0.5029 ms median (2.32× faster on L4). Ampere A100 scaling: 21.81× baseline (heavy) — 0.6281 ms median (1.85× faster on A100). ## Failure modes - Depends on heavy manual normal and vertex-data authoring per character - Looks break when lighting changes or the model is re-posed beyond tuned ranges - Edited normals conflict with standard skinning or LOD pipelines - Low-framerate animation can read as stutter in a smooth game engine ## Dataflow - Inputs: mesh, normals, texture - Outputs: ldr-image - Platforms: desktop-gpu, unreal ## Presets ### Guilty Gear Xrd anime 3D shading — stepped cel threshold, ink contour outlines and stylized rim (glsl-fragment; rendered 2026-11-30) ```json { "SHADOW_THRESH": 0.18, "OUTLINE_WIDTH": 0.032, "RIM_STRENGTH": 0.9, "SPEC_CUTOFF": 0.72 } ``` ```glsl const float SHADOW_THRESH = 0.18; // P const float OUTLINE_WIDTH = 0.032; // P const float RIM_STRENGTH = 0.9; // P const float SPEC_CUTOFF = 0.72; // P 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); } 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; } // Stylized anime mecha-knight bust with angular armor plates, visor and crest vec2 mapHero(vec3 p) { // Stepped 12 fps key-pose turntable (classic Xrd limited-framerate feel) float tStep = floor(iTime * 12.0) / 12.0; float yaw = 0.42 * sin(tStep * 0.9); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { yaw = (iMouse.x / iResolution.x - 0.5) * 2.6; } float cy = cos(yaw), sy = sin(yaw); p.xz = mat2(cy, -sy, sy, cy) * p.xz; // 1: crimson armor crown, 2: ivory faceplate, 3: glowing cyan visor, 4: gold V-fin crest vec3 q = p - vec3(0.0, 0.14, 0.0); float helm = length(q * vec3(1.05, 0.95, 0.98)) - 0.48; float cheek = sdBox(vec3(abs(q.x) - 0.28, q.y + 0.14, q.z - 0.06), vec3(0.14, 0.24, 0.26)) - 0.04; float pauldron = sdBox(vec3(abs(p.x) - 0.56, p.y + 0.48, p.z), vec3(0.28, 0.20, 0.28)) - 0.05; float chest = sdBox(p - vec3(0.0, -0.56, -0.02), vec3(0.36, 0.26, 0.24)) - 0.04; float dRed = min(min(helm, cheek), min(pauldron, chest)); float face = sdBox(q - vec3(0.0, -0.14, 0.28), vec3(0.20, 0.22, 0.18)) - 0.05; float visor = sdBox(q - vec3(0.0, 0.02, 0.37), vec3(0.26, 0.075, 0.10)) - 0.015; vec3 vp = vec3(abs(q.x), q.y - 0.24, q.z - 0.34); float fin = sdCapsule(vp, vec3(0.0, -0.05, 0.05), vec3(0.46, 0.34, -0.06), 0.042); float gem = sdBox(q - vec3(0.0, 0.22, 0.42), vec3(0.055, 0.075, 0.05)) - 0.01; float dGold = min(fin, gem); vec2 res = vec2(dRed, 1.0); if (face < res.x) res = vec2(face, 2.0); if (visor < res.x) res = vec2(visor, 3.0); if (dGold < res.x) res = vec2(dGold, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapHero(p + e.xyy).x - mapHero(p - e.xyy).x, mapHero(p + e.yxy).x - mapHero(p - e.yxy).x, mapHero(p + e.yyx).x - mapHero(p - e.yyx).x )); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, -0.02, 2.55); vec3 rd = normalize(vec3(uv, -1.65)); // Speedline anime backdrop float ang = atan(uv.y, uv.x); float rays = smoothstep(0.65, 0.95, sin(ang * 24.0 + iTime * 0.4) * 0.5 + 0.5); vec3 bg = mix(vec3(0.11, 0.13, 0.22), vec3(0.22, 0.28, 0.46), clamp(uv.y + 0.55, 0.0, 1.0)); bg += vec3(0.07, 0.09, 0.16) * rays * smoothstep(0.15, 0.65, length(uv)); float t = 0.2, minD = 1e5; vec2 hit = vec2(-1.0); for (int i = 0; i < 72; i++) { vec2 res = mapHero(ro + rd * t); minD = min(minD, res.x); if (res.x < 0.002) { hit = vec2(t, res.y); break; } t += res.x * 0.85; if (t > 6.5) break; } float outW = max(OUTLINE_WIDTH, 0.001); vec3 inkCol = vec3(0.05, 0.04, 0.09); vec3 col = bg; if (hit.x > 0.0) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 v = -rd; vec3 L = normalize(vec3(0.68, 0.62, 0.55)); // Stylized edited-normal bias on the faceplate for clean 2D shadow shapes vec3 nShade = (hit.y > 1.5 && hit.y < 2.5) ? normalize(mix(n, normalize(vec3(p.x, 0.15, 0.85)), 0.55)) : n; float nl = dot(nShade, L); float thresh = clamp(SHADOW_THRESH, -0.6, 0.85); float litMask = smoothstep(thresh - 0.025, thresh + 0.025, nl); // Saturated anime base & cool-shifted shadow palettes (never desaturated grey) vec3 baseC, shadC; if (hit.y < 1.5) { baseC = vec3(0.92, 0.20, 0.24); shadC = vec3(0.36, 0.08, 0.24); } else if (hit.y < 2.5) { baseC = vec3(0.97, 0.94, 0.88); shadC = vec3(0.56, 0.58, 0.76); } else if (hit.y < 3.5) { baseC = vec3(0.20, 0.96, 1.00); shadC = vec3(0.06, 0.45, 0.72); } else { baseC = vec3(1.00, 0.80, 0.20); shadC = vec3(0.62, 0.32, 0.12); } col = mix(shadC, baseC, litMask); // Crisp stepped specular band vec3 H = normalize(L + v); float spec = smoothstep(SPEC_CUTOFF - 0.02, SPEC_CUTOFF + 0.02, dot(n, H)) * litMask; col = mix(col, vec3(1.0, 0.98, 0.92), spec * 0.82); // Lit-side stylized Fresnel rim highlight float ndv = max(dot(n, v), 0.0); float rim = smoothstep(0.56, 0.62, 1.0 - ndv) * smoothstep(-0.15, 0.15, nl); col += vec3(0.95, 0.92, 1.0) * rim * clamp(RIM_STRENGTH, 0.0, 1.5) * 0.55; // Subtle manga shadow hatch lines in deep shadow float hatch = smoothstep(0.65, 0.85, sin((fragCoord.x + fragCoord.y) * 0.55)); col *= 1.0 - (1.0 - litMask) * smoothstep(thresh - 0.22, thresh - 0.35, nl) * hatch * 0.28; // Interior crease & silhouette ink lines via normal derivative float edgeN = length(fwidth(n)) * 1.45; float sil = smoothstep(0.28, 0.14, ndv) * step(0.005, outW); float innerInk = smoothstep(0.42, 0.65, edgeN); col = mix(col, inkCol, clamp(max(sil, innerInk), 0.0, 1.0)); } else if (minD < outW) { // Crisp inverted-hull-style exterior ink outline float outMask = smoothstep(outW, outW * 0.65, minD); col = mix(bg, inkCol, outMask); } fragColor = vec4(clamp(col, 0.0, 1.0), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md) ## Combines with - [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md): Vertex-colour-controlled hull gives the varying line weight of the hand-drawn look. ## Sources 1. [primary] Junya Motomura Guilty Gear Xrd's Art Style: The X Factor Between 2D and 3D. GDC 2015. https://www.gdcvault.com/play/1022031/GuiltyGearXrd-s-Art-Style-The (verified via http on 2026-11-29) ## Cite this entry Texel. "Guilty Gear Xrd anime-style 3D shading." https://texelatlas.vercel.app/t/guilty-gear-xrd-shading/ (accessed 2026-12-01). --- id: "hable-filmic-tonemapping" title: "Hable filmic (Uncharted 2) tonemapping" aliases: [Uncharted 2 tonemapper, filmic curve] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2010 inputs: [hdr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Hable" url: "https://texelatlas.vercel.app/t/hable-filmic-tonemapping/" sources_verified_at: "2026-11-29" --- # Hable filmic (Uncharted 2) tonemapping (Hable) > A parametric filmic curve from Uncharted 2 with separate toe, linear and shoulder terms. It gives contrasty blacks and a soft highlight roll-off, and is easy to tune by hand. ## Reach for it when - hdr image looks washed out with flat blacks - want contrasty filmic look i can tune by hand - highlights clip harshly to white - need a simple tweakable shoulder and toe curve ## How it works The curve is a rational function ((x(Ax+CB)+DE)/(x(Ax+B)+DF)) - E/F with six constants controlling shoulder strength, linear strength, linear angle, toe strength, toe numerator and toe denominator. The input is scaled by an exposure bias, passed through the function, and divided by the same function evaluated at a linear white point so that white maps to 1. It is applied per channel in the shader, then gamma encoded. The toe crushes dark values for a film-like black, the linear section keeps mid-tones close to proportional, and the shoulder compresses highlights gradually. Because the constants are explicit, artists can re-fit the curve to a target look. ## When to use it Choose it when you want a simple filmic curve you can tune by hand with no matrices or LUTs. Prefer [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) for an industry-standard look, [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md) for hue stability, and [Reinhard photographic tone reproduction](https://texelatlas.vercel.app/t/reinhard-tonemapping.md) for the least contrast. Hable's curve skews hue like ACES because it runs per channel. ## Cost cheap — One rational function per channel. Measured GPU Weight: 1.28× baseline (feather) — 0.042 ms median / 0.0445 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.03× baseline (feather) — 0.0163 ms median (2.58× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.46× faster on A100). ## Failure modes - Per-channel hue skew and desaturation of saturated highlights - Constants are scene-dependent: the white point and exposure bias need re-tuning - Crushed blacks when exposure is low - Colours differ from authored albedo, unlike a neutral mapper ## Engine support - babylonjs: builtin — `new BABYLON.TonemapPostProcess('t', BABYLON.TonemappingOperator.Hable, exposure, camera)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/thinTonemapPostProcess.ts, checked 2026-12-01) - godot: builtin — `Environment.tonemap_mode = Environment.TONE_MAPPER_FILMIC (Hable Uncharted 2 filmic curve in tonemap.glsl)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Post-processing > Tonemapping > Mode = Neutral` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl, checked 2026-12-01) — Neutral mode is built on a Hable/Hejl/Frostbite curve, not the exact Uncharted 2 operator. ## Dataflow - Inputs: hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Filmic curve visualised against Reinhard and clamp (glsl-fragment; rendered 2026-11-29) ```json { "A": 0.15, "B": 0.5, "C": 0.1, "D": 0.2, "E": 0.02, "F": 0.3, "W": 11.2, "EXPOSURE_BIAS": 2 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style // Plots Hable filmic, Reinhard and linear clamp for scene values 0..8. const float A = 0.15, B = 0.50, C = 0.10, D = 0.20, E = 0.02, F = 0.30; const float W = 11.2; const float EXPOSURE_BIAS = 2.0; const float X_MAX = 8.0; float hable(float x) { return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F; } float filmic(float x) { return hable(EXPOSURE_BIAS * x) / hable(W); } float reinhard(float x) { return x / (1.0 + x); } float line(float y, float f, float w) { return smoothstep(w, w * 0.4, abs(y - f)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float x = uv.x * X_MAX; vec3 col = vec3(0.07, 0.08, 0.10); // grid float gx = abs(fract(uv.x * X_MAX) - 0.5); float gy = abs(fract(uv.y * 5.0) - 0.5); col += 0.05 * smoothstep(0.47, 0.5, max(gx, gy)); // curves in the upper part, gradient strip below float cy = (uv.y - 0.18) / 0.82; if (uv.y > 0.18) { col = mix(col, vec3(0.9), line(cy, min(x, 1.0), 0.008)); col = mix(col, vec3(0.2, 0.7, 1.0), line(cy, reinhard(x), 0.008)); col = mix(col, vec3(1.0, 0.55, 0.15), line(cy, filmic(x), 0.010)); } else if (uv.y > 0.09) { float v = filmic(x); col = vec3(pow(clamp(v, 0.0, 1.0), 1.0 / 2.2)); } else { col = vec3(pow(clamp(x, 0.0, 1.0), 1.0 / 2.2)); } fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; constants are the published ones from the primary source (0) ## Lineage - extends [Reinhard photographic tone reproduction](https://texelatlas.vercel.app/t/reinhard-tonemapping.md) - extended by [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) ## Combines with - [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md): Tonemap first, then grade the LDR result with a LUT. ## Sources 1. [primary] John Hable Filmic Tonemapping Operators. filmicworlds.com. https://filmicworlds.com/blog/filmic-tonemapping-operators (verified via http on 2026-11-29) 2. [implementation] dmnsgn (2019) dmnsgn/shaders-tone-map. https://github.com/dmnsgn/shaders-tone-map License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hable filmic (Uncharted 2) tonemapping." https://texelatlas.vercel.app/t/hable-filmic-tonemapping/ (accessed 2026-12-01). --- id: "halftone-screen" title: "Halftone screens" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1880 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Wikipedia" url: "https://texelatlas.vercel.app/t/halftone-screen/" sources_verified_at: "2026-11-29" --- # Halftone screens (Wikipedia) > Replaces continuous tone with a regular grid of dots whose size encodes brightness, imitating newspaper, comic and screen-print reproduction. ## Reach for it when - want a newspaper or comic dot print look - render should look screen-printed - pop-art effect with dots sized by brightness - convert smooth shading into printed dots ## How it works The image is sampled on a rotated grid: each cell's centre samples the source brightness, and the fragment is filled if its distance to the cell centre is below a radius derived from that brightness. Using `sqrt(1 - tone)` for the radius keeps covered area roughly proportional to darkness. For colour, separate channels (CMYK or RGB) are screened at different angles, typically 15°, 75°, 0° and 45°, so the dot rosettes interlock instead of producing strong moire. The edge of the dot is smoothed with `fwidth`. Sampling the tone at cell centres rather than per pixel avoids dot shapes dissolving into noise. ## When to use it Choose it for a comic, pop-art or print look from a rendered frame. Prefer [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) or [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md) when you need a pixel-level pattern for 1-bit output, and [Procedural cross-hatching shader](https://texelatlas.vercel.app/t/procedural-cross-hatching.md) for line-based shading. ## Cost cheap — One post pass with a few samples; cheap. Measured GPU Weight: 2.67× baseline (light) — 0.088 ms median / 0.089 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.87× baseline (feather) — 0.0298 ms median (2.95× faster on L4). Ampere A100 scaling: 1.72× baseline (feather) — 0.0494 ms median (1.78× faster on A100). ## Failure modes - Dot grid moires with the screen pixel grid or with texture detail at certain scales - Dot grid is fixed in screen space and slides over moving objects - Small dots in dark regions alias without derivative-based smoothing - Colour screens with wrong angles produce distracting rosette or moire patterns ## Engine support - threejs: official — `import { HalftonePass } from 'three/addons/postprocessing/HalftonePass.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/postprocessing/HalftonePass.js, checked 2026-12-01) ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: greyscale. Right: 45-degree dot screen, dot radius set by cell brightness (glsl-fragment; rendered 2026-11-29) ```json { "CELLP": 9 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } const float CELLP=9.0; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=vec3(lum(img(q))); if(R){ float c=.70710678;mat2 M=mat2(c,-c,c,c); // rotate 45 deg vec2 gp=M*fragCoord/CELLP,id=floor(gp)+.5; vec2 cs=transpose(M)*(id*CELLP),cu=(cs-.5*iResolution.xy)/iResolution.y; float L=lum(img(vec2(cu.x-.25,cu.y))); float rad=sqrt(clamp(1.-L,0.,1.))*.72,d=length(fract(gp)-.5); col=mix(vec3(.96,.94,.88),vec3(.08,.1,.2),smoothstep(rad+.04,rad-.04,d)); } if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Sources 1. [primary] Wikipedia Halftone. en.wikipedia.org. https://en.wikipedia.org/wiki/Halftone (verified via http on 2026-11-29) 2. [implementation] daniel-ilett (2022) daniel-ilett/shaders-halftone. https://github.com/daniel-ilett/shaders-halftone License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Halftone screens." https://texelatlas.vercel.app/t/halftone-screen/ (accessed 2026-12-01). --- id: "hardware-hatching-tone-control" title: "Fine tone control in hardware hatching" domain: "npr" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2002 inputs: [mesh, uv-atlas, normals, texture] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Webb et al., 2002" url: "https://texelatlas.vercel.app/t/hardware-hatching-tone-control/" sources_verified_at: "2026-11-29" --- # Fine tone control in hardware hatching (Webb et al., 2002) > Extends tonal art map hatching by packing several tone levels into multitexture channels and combining them per fragment so tone can be reproduced in many more steps than the number of textures. ## Reach for it when - real-time pen and ink hatching look - hatching strokes pop or swim when the camera moves - smooth tone gradients in sketch style rendering - non-photorealistic engraving style on the gpu ## How it works Classic tonal art maps blend only two textures at a time, which limits tonal precision and needs many levels for smooth gradients. The multitexture approach stores several hatch levels in the channels of a few textures and computes per-fragment blend weights that sum to the target tone. The shader chooses weights so that the integrated darkness of the combined strokes matches the desired lighting value, with sharper transitions between layers than a plain cross-fade. This yields finer tone control and reduced blurring of strokes between neighbouring tone levels while still using standard texturing hardware. ## When to use it Choose it when plain [Real-time hatching with tonal art maps](https://texelatlas.vercel.app/t/tonal-art-maps.md) shows visible tone steps or greyish blending and you want more controlled hatching on the GPU. Prefer [Procedural cross-hatching shader](https://texelatlas.vercel.app/t/procedural-cross-hatching.md) for screen-space shader hatching without precomputed textures. ## Cost cheap — Cheap: a few texture fetches and a per-fragment weight computation. Measured GPU Weight: 42.88× baseline (heavy) — 1.4107 ms median / 1.4563 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 39.51× baseline (heavy) — 0.6282 ms median (2.25× faster on L4). Ampere A100 scaling: 26.63× baseline (heavy) — 0.767 ms median (1.84× faster on A100). ## Failure modes - Needs the same careful UV and direction parameterisation as tonal art maps - Channel packing limits you to a fixed number of stroke layers - Weights tuned for one texture set do not transfer to another without recalibration - Mip transitions still change stroke thickness at distance ## Dataflow - Inputs: mesh, uv-atlas, normals, texture - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Hardware hatching tone control — continuous multi-stroke copperplate TAM engraving (glsl-fragment; rendered 2026-11-30) ```json { "P_HATCH_DENSITY": 26, "P_STROKE_CONTRAST": 3.4, "P_LIGHT_ANGLE": 0.85, "P_CROSS_WEIGHT": 0.9 } ``` ```glsl const float P_HATCH_DENSITY = 26.0; // P Hatch Density [10.0, 52.0, 1.0] const float P_STROKE_CONTRAST = 3.4; // P Stroke Crispness [1.0, 6.0, 0.1] const float P_LIGHT_ANGLE = 0.85; // P Light Azimuth [0.0, 6.28, 0.05] const float P_CROSS_WEIGHT = 0.9; // P Cross-Hatch [0.0, 1.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } float sdCylinder(vec3 p, float r, float h) { vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h); return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)); } // Sculpted classical geometry: fluted pedestal, tilted torus, sphere vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.95, 1.0); // Central classical sphere float dS = length(p - vec3(-0.32, -0.22, 0.15)) - 0.56; if (dS < res.x) res = vec2(dS, 2.0); // Tilted sculptural ring vec3 q = p - vec3(0.42, 0.08, -0.15); q.xy = rot2(0.65 + 0.25 * sin(iTime * 0.45)) * q.xy; q.xz = rot2(iTime * 0.35) * q.xz; float dT = sdTorus(q, vec2(0.52, 0.17)); if (dT < res.x) res = vec2(dT, 3.0); // Background fluted column vec3 cp = p - vec3(-0.95, 0.1, -1.1); float fluting = 0.025 * cos(atan(cp.z, cp.x) * 14.0); float dC = sdCylinder(cp, 0.38 + fluting, 1.35); if (dC < res.x) res = vec2(dC, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Continuous hardware hatching stroke signal with fine tone-controlled thresholding float hatchWave(vec2 uv, float ang, float freq, float wobble) { vec2 r = rot2(ang) * uv; float w = sin(r.x * freq + sin(r.y * freq * 0.18) * wobble); return 0.5 + 0.5 * w; } // Evaluate 5 nested tonal art map (TAM) engraving bands with fine tone control float evalHatchTone(vec2 uv, float tone, float freq, float contrast, float crossW) { // Paper grain subtly modulates threshold so transitions feel hand-engraved float grain = 0.04 * sin(uv.x * 110.0) * cos(uv.y * 97.0); float t = clamp(tone + grain, 0.0, 1.0); // Band 1: primary parallel diagonal strokes (light midtones) float s1 = hatchWave(uv, 0.68, freq, 0.45); float ink1 = smoothstep(0.0, 1.0, (0.82 - t) * contrast - s1 * 0.95 + 0.48); // Band 2: tighter interstitial parallel strokes (midtones) float s2 = hatchWave(uv + vec2(0.017, -0.011), 0.68, freq * 1.45, 0.35); float ink2 = smoothstep(0.0, 1.0, (0.62 - t) * contrast - s2 * 0.95 + 0.44); // Band 3: opposing cross-hatch strokes (core shadow) float s3 = hatchWave(uv, -0.62, freq * 1.05, 0.42); float ink3 = smoothstep(0.0, 1.0, (0.46 - t) * contrast - s3 * 0.95 + 0.42) * clamp(crossW, 0.0, 1.5); // Band 4: near-horizontal engraving lines (deep shadow) float s4 = hatchWave(uv, 0.08, freq * 1.25, 0.3); float ink4 = smoothstep(0.0, 1.0, (0.28 - t) * contrast - s4 * 0.92 + 0.38) * clamp(crossW, 0.0, 1.5); // Band 5: solid ink velvet shadow float ink5 = smoothstep(0.14, 0.03, t); return clamp(max(max(ink1, ink2), max(max(ink3, ink4), ink5)), 0.0, 1.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.32, 2.85); vec3 rd = normalize(vec3(uv, -1.6)); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 12.0) break; } float freq = clamp(P_HATCH_DENSITY, 8.0, 64.0) * 6.28318 * 0.5; float contrast = clamp(P_STROKE_CONTRAST, 0.8, 7.0); float crossW = clamp(P_CROSS_WEIGHT, 0.0, 1.6); // Warm archival cotton rag paper base float paperTex = 0.97 + 0.03 * sin(uv.x * 190.0 + sin(uv.y * 130.0)) * cos(uv.y * 165.0); vec3 paper = vec3(0.95, 0.91, 0.83) * paperTex; vec3 ink = vec3(0.09, 0.08, 0.11); float tone = clamp(0.62 + 0.34 * uv.y - 0.12 * abs(uv.x), 0.18, 0.98); vec2 hatchUV = uv; float silhouette = 0.0; if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); float lAng = P_LIGHT_ANGLE + 0.35 * sin(iTime * 0.5); vec3 lDir = normalize(vec3(cos(lAng) * 0.9, 0.78, sin(lAng) * 0.7 + 0.45)); // Soft cast shadow check float sh = 1.0; float ts = 0.03; for (int s = 0; s < 18; s++) { float ds = mapScene(p + n * 0.015 + lDir * ts).x; sh = min(sh, clamp(6.0 * ds / ts, 0.0, 1.0)); ts += max(ds, 0.04); if (ts > 3.0) break; } float diff = max(dot(n, lDir), 0.0) * (0.35 + 0.65 * sh); float hemi = 0.5 + 0.5 * n.y; vec3 hVec = normalize(lDir - rd); float spec = pow(max(dot(n, hVec), 0.0), 28.0) * 0.42 * sh; float baseAl = (matId < 1.5) ? 0.84 : (matId < 2.5 ? 0.94 : 0.88); tone = clamp((0.12 * hemi + 0.82 * diff + spec) * baseAl, 0.0, 1.0); // Object-space curved UV projection so strokes wrap gracefully over 3D curvature if (matId < 1.5) { hatchUV = p.xz * 0.48; } else { hatchUV = vec2(atan(n.x, n.z) * 0.28 + p.x * 0.18, p.y * 0.72 + n.y * 0.15); } // Crisp grazing-angle contour ink line float ndv = max(dot(n, -rd), 0.0); silhouette = smoothstep(0.26, 0.08, ndv) * step(1.5, matId); } float inkMask = evalHatchTone(hatchUV, tone, freq, contrast, crossW); inkMask = max(inkMask, silhouette * 0.92); // Subtle architectural copperplate border frame vec2 b = abs(fragCoord / iResolution.xy - 0.5); float border = smoothstep(0.468, 0.472, max(b.x, b.y)) * (1.0 - smoothstep(0.478, 0.482, max(b.x, b.y))); vec3 col = mix(paper, ink, clamp(inkMask + border * 0.6, 0.0, 1.0)); fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Real-time hatching with tonal art maps](https://texelatlas.vercel.app/t/tonal-art-maps.md) ## Sources 1. [primary] Matthew Webb, Emil Praun, Adam Finkelstein, Hugues Hoppe (2002) Fine tone control in hardware hatching. Proceedings of the 2nd international symposium on Non-photorealistic animation and rendering. https://doi.org/10.1145/508530.508540 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Fine tone control in hardware hatching." https://texelatlas.vercel.app/t/hardware-hatching-tone-control/ (accessed 2026-12-01). --- id: "hardware-occlusion-queries" title: "GPU hardware occlusion queries" aliases: [occlusion queries, conditional rendering, CHC++] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, desktop-gpu, unity, unreal] year_introduced: 2004 inputs: [mesh, depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Bittner et al., 2004" url: "https://texelatlas.vercel.app/t/hardware-occlusion-queries/" sources_verified_at: "2026-11-29" --- # GPU hardware occlusion queries (Bittner et al., 2004) > Ask the GPU how many samples a bounding proxy would pass the depth test, then use that answer, with temporal coherence to hide latency, to skip drawing hidden objects. ## Reach for it when - draw calls wasted on objects hidden behind walls - gpu should tell me whether an object is visible - occlusion culling that uses real depth buffer - popping when culling uses last frame's visibility - skip drawing hidden meshes without authored occluders ## How it works Render the bounding box of an object with color and depth writes disabled inside a query. The GPU reports whether any sample passed the depth test against the already-drawn occluders; if none did, the real object is hidden and need not be drawn. The catch is latency: the result arrives a frame or more later, and stalling for it wastes the CPU/GPU overlap. Coherent hierarchical culling avoids stalls by exploiting that visibility rarely changes between frames. Nodes of a scene hierarchy visible last frame are drawn immediately and re-queried in parallel, while nodes that were hidden are queried and only drawn if the query returns visible later. Queries are issued for tree nodes front to back so a hidden interior node prunes its whole subtree. A conditional-rendering mode lets the GPU itself skip the draw using the query result with no CPU readback. ## When to use it Choose it when you need exact occlusion against real rendered depth with no authored occluders, in a classic CPU-driven pipeline with a spatial hierarchy. Prefer [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md) for GPU-driven pipelines (no query latency, culls thousands of instances in one dispatch) and [Masked software occlusion culling](https://texelatlas.vercel.app/t/masked-software-occlusion-culling.md) when you need a result before submission without GPU roundtrip. Prefer [Portal and PVS visibility culling](https://texelatlas.vercel.app/t/portal-pvs-culling.md) for static interiors. ## Cost medium — Query overhead per proxy draw plus pipeline bubbles if results are polled too early; WebGL2 exposes only boolean results. Measured GPU Weight: 3.98× baseline (light) — 0.1309 ms median / 0.1354 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.67× baseline (light) — 0.0584 ms median (2.24× faster on L4). Ampere A100 scaling: 2.61× baseline (light) — 0.0752 ms median (1.74× faster on A100). ## Failure modes - Reading results early stalls the pipeline and can cost more than the culled draws - One-frame-old results make objects pop in when the camera rotates quickly - Many tiny queries add driver overhead that exceeds the saved draw cost - Bounding boxes over-estimate silhouettes, so partially hidden objects count as visible - Not available on all mobile drivers, and WebGL2 only returns any-samples-passed ## Engine support - babylonjs: builtin — `mesh.occlusionType = AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC; mesh.occlusionQueryAlgorithmType` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/abstractMesh.pure.ts, checked 2026-12-01) - metal: builtin — `MTLRenderPassDescriptor.visibilityResultBuffer + setVisibilityResultMode(.boolean/.counting, offset:)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlrenderpassdescriptor.json, checked 2026-12-01) - threejs: builtin — `Set object.occlusionTest = true, then renderer.isOccluded( object ) (WebGPURenderer)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/renderers/common/Renderer.js, checked 2026-12-01) — WebGPURenderer only. - unreal: builtin — `Project Settings > Rendering > Culling > Occlusion Culling (GPU Hardware Occlusion Queries and HZB)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/visibility-and-occlusion-culling-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `device.createQuerySet({type:'occlusion',count}); pass.beginOcclusionQuery(i)` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Returns samples-passed count; resolve via resolveQuerySet. ## Dataflow - Inputs: mesh, depth - Outputs: visibility-mask - Platforms: webgl2, desktop-gpu, unity, unreal ## Presets ### Hardware Occlusion Queries — bounding-box query proxies & pass/fail depth test (left) vs occluded-skip shaded render (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_WALL_WIDTH": 0.65, "P_ORBIT": 0.55, "P_PROXY_VIS": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_WALL_WIDTH = 0.65; // P Occluder Pillar [0.25, 1.1, 0.05] const float P_ORBIT = 0.55; // P Camera Orbit [0.0, 1.5, 0.05] const float P_PROXY_VIS = 0.75; // P Query Proxy Vis [0.2, 1.0, 0.05] const float P_SPLIT = 0.48; // P Query AABBs / Render [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } vec2 boxHit(vec3 ro, vec3 rd, vec3 bc, vec3 br, out vec3 nOut) { vec3 invR = 1.0 / (rd + vec3(1e-6)); vec3 t0 = (bc - br - ro) * invR; vec3 t1 = (bc + br - ro) * invR; vec3 tn = min(t0, t1); vec3 tf = max(t0, t1); float tNear = max(max(tn.x, tn.y), tn.z); float tFar = min(min(tf.x, tf.y), tf.z); vec3 lp = (ro + rd * tNear - bc) / max(br, vec3(1e-4)); vec3 ap = abs(lp); nOut = (ap.x > ap.y && ap.x > ap.z) ? vec3(sign(lp.x), 0.0, 0.0) : (ap.y > ap.z ? vec3(0.0, sign(lp.y), 0.0) : vec3(0.0, 0.0, sign(lp.z))); return vec2(tNear, tFar); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float wallW = clamp(P_WALL_WIDTH, 0.20, 1.2) * 0.42; float t = iTime * max(P_ORBIT, 0.0); float proxyVis = clamp(P_PROXY_VIS, 0.1, 1.0); // Camera glides laterally so hero spheres pass behind and emerge from behind the foreground occluder wall float camX = 0.85 * sin(t * 0.65); vec3 ro = vec3(camX, 0.28, 2.35); vec3 lookTarget = vec3(0.0, -0.05, -0.2); vec3 fwd = normalize(lookTarget - ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.48 + right * uv.x + up * uv.y); vec3 lDir = normalize(vec3(0.52, 0.78, 0.58)); vec3 col = mix(vec3(0.05, 0.07, 0.11), vec3(0.14, 0.20, 0.30), smoothstep(-0.4, 0.5, uv.y)); // Foreground solid occluder monolith wall at z = 0.55 vec3 wallC = vec3(0.0, -0.05, 0.55); vec3 wallR = vec3(wallW, 0.44, 0.12); // 4 background hero objects positioned behind the occluder wall vec3 objC[4]; objC[0] = vec3(-0.78, -0.14, -0.55); objC[1] = vec3(-0.24, -0.14, -0.62); objC[2] = vec3(0.28, -0.14, -0.62); objC[3] = vec3(0.78, -0.14, -0.55); float tMin = 1e5; int hitId = -1; vec3 hn = vec3(0.0, 1.0, 0.0); vec3 hp = vec3(0.0); // Floor if (rd.y < -0.005) { float tf = (-0.48 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { tMin = tf; hitId = 10; hp = ro + rd * tf; hn = vec3(0.0, 1.0, 0.0); } } // Test occluder wall vec3 wn; vec2 wh = boxHit(ro, rd, wallC, wallR, wn); float tWall = (wh.y > max(wh.x, 0.05)) ? wh.x : 1e5; if (tWall < tMin) { tMin = tWall; hitId = 20; hp = ro + rd * tWall; hn = wn; } // Test 4 hero spheres for (int i = 0; i < 4; i++) { vec3 oc = ro - objC[i]; float b = dot(oc, rd); float d = b * b - (dot(oc, oc) - 0.22 * 0.22); if (d > 0.0) { float ts = -b - sqrt(d); if (ts > 0.05 && ts < tMin) { tMin = ts; hitId = i; hp = ro + rd * ts; hn = normalize(hp - objC[i]); } } } if (hitId == 10) { vec2 g = hp.xz * 2.5; float chk = mod(floor(g.x) + floor(g.y), 2.0); col = mix(vec3(0.11, 0.13, 0.18), vec3(0.22, 0.25, 0.32), chk); col = mix(vec3(0.05, 0.07, 0.11), col, exp(-tMin * 0.14)); } else if (hitId == 20) { float ndl = max(dot(hn, lDir), 0.0); float groove = step(0.85, fract(hp.y * 8.0)); vec3 wAlb = mix(vec3(0.26, 0.30, 0.38), vec3(0.14, 0.18, 0.24), groove); col = wAlb * (0.30 + 0.85 * ndl); } else if (hitId >= 0 && hitId < 4) { float fi = float(hitId); vec3 alb = 0.55 + 0.42 * cos(vec3(0.0, 2.0, 4.0) + fi * 1.35); float ndl = max(dot(hn, lDir), 0.0); float spec = pow(max(dot(reflect(-lDir, hn), -rd), 0.0), 32.0); col = alb * (0.24 + 0.90 * ndl) + vec3(0.95) * spec * 0.65; } // Left: Overlay hardware occlusion query bounding-box proxies (X-ray through occluder!) // Green/Cyan AABB = samples PASSED depth test; Crimson dashed AABB = 0 samples passed (CULLED!) if (screenX < split) { for (int i = 0; i < 4; i++) { vec3 bn; vec2 bh = boxHit(ro, rd, objC[i], vec3(0.24), bn); if (bh.y > max(bh.x, 0.05)) { // Determine analytically if ANY corner of this proxy is unoccluded by the wall from ro bool anyVisible = false; for (int s = -1; s <= 1; s += 2) { vec3 testPt = objC[i] + vec3(float(s) * 0.22, 0.0, 0.0); vec3 toT = normalize(testPt - ro); float distT = length(testPt - ro); vec3 dummyN; vec2 wh2 = boxHit(ro, toT, wallC, wallR, dummyN); if (!(wh2.y > max(wh2.x, 0.05) && wh2.x < distT)) { anyVisible = true; } } vec3 bp = ro + rd * bh.x; vec3 lp = abs((bp - objC[i]) / 0.24); float edge = max(min(lp.x, lp.y), max(min(lp.y, lp.z), min(lp.z, lp.x))); float wire = smoothstep(0.84, 0.96, edge); vec3 qCol = anyVisible ? vec3(0.16, 0.96, 0.72) : vec3(1.0, 0.24, 0.34); // Tint proxy box wireframe (visible even behind wall to illustrate the GPU query!) float alpha = wire * proxyVis * (bh.x < tWall ? 0.95 : 0.65) + 0.14 * proxyVis; col = mix(col, qCol, clamp(alpha, 0.0, 0.92)); } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): Use queries for what the depth pyramid misses, such as results against the current frame's depth. ## Sources 1. [primary] Jiří Bittner, Michael Wimmer, Harald Piringer, Werner Purgathofer (2004) Coherent Hierarchical Culling: Hardware Occlusion Queries Made Useful. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2004.00793.x (verified via crossref on 2026-11-29) 2. [tutorial] Michael Wimmer, Jiri Bittner Hardware Occlusion Queries Made Useful. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems2/part-i-geometric-complexity/chapter-6-hardware-occlusion-queries-made-useful (verified via http on 2026-11-29) ## Cite this entry Texel. "GPU hardware occlusion queries." https://texelatlas.vercel.app/t/hardware-occlusion-queries/ (accessed 2026-12-01). --- id: "hardware-tessellation-pn-triangles" title: "Hardware tessellation: PN triangles and displacement" aliases: [PN triangles, curved PN triangles, hull/domain shader tessellation, phong tessellation] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [desktop-gpu, unity, unreal] year_introduced: 2001 inputs: [mesh, texture] outputs: [mesh] style: "both" dynamic: "dynamic" cost: "medium" authority: "Vlachos et al., 2001" url: "https://texelatlas.vercel.app/t/hardware-tessellation-pn-triangles/" sources_verified_at: "2026-11-29" --- # Hardware tessellation: PN triangles and displacement (Vlachos et al., 2001) > Uses the GPU's fixed-function tessellator to subdivide coarse triangles on the fly, bending them with a curved patch such as PN triangles and optionally displacing the new vertices from a height map. ## Reach for it when - low poly silhouettes look faceted and need rounding - real displacement mapping with correct silhouettes - add geometry detail on the gpu without more vertices - need adaptive subdivision based on distance to camera ## How it works A hull (tessellation control) stage receives each coarse triangle, computes per-edge and inner tessellation factors, and passes control data along. The fixed-function tessellator emits a barycentric lattice at those factors. A domain (evaluation) shader then places each new vertex. With PN triangles, the hull stage builds a cubic Bézier patch from the three positions and normals (ten control points, plus a quadratic normal patch), and the domain shader evaluates it so silhouettes become round without extra authored geometry. For displacement, it samples a height texture at the interpolated UV and moves the point along the normal. Tessellation factors are adaptive: from edge screen length or distance, and matched on shared edges so no cracks appear. Catmull-Clark feature-adaptive schemes follow the same stage layout with limit-surface patches. ## When to use it Choose it to smooth low-poly silhouettes cheaply or to add real displacement with correct silhouettes and shadows on hardware that has tessellation stages. Prefer [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) when you cannot change silhouettes and want a cheaper fake, [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md) for authored subdivision-surface models, and [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) / [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) for modern pipelines where mesh shaders and clustered geometry replace tessellation. WebGL2 and WebGPU expose no tessellation stages. ## Cost medium — Cost scales with the output triangle count; small triangles waste rasteriser quads, so factors must be capped. Qualitative. Measured GPU Weight: 20.95× baseline (heavy) — 0.6579 ms median / 0.6847 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.63× baseline (moderate) — 0.2628 ms median (2.5× faster on L4). Ampere A100 scaling: 12.49× baseline (moderate) — 0.3597 ms median (1.83× faster on A100). ## Failure modes - Cracks along shared edges when neighbouring patches compute different tessellation factors - PN triangles bulge or flatten near hard edges because vertex normals are averaged; separate normals or crease handling are required - Shimmering and swimming vertices as adaptive factors change between frames without hysteresis - Micro-triangles from over-tessellation tank rasteriser efficiency; and the stage is absent or slow on mobile and web APIs ## Engine support - metal: builtin — `MTLRenderPipelineDescriptor.tessellationPartitionMode + compute-written tessellation factors` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlrenderpipelinedescriptor.json, checked 2026-12-01) — Fixed-function tessellator; PN-triangle / displacement shader is yours. - unity: builtin — `HDRP Lit Tessellation material; Displacement Mode = Tessellation` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/lit-tessellation-material.md, checked 2026-12-01) — HDRP only; Phong tessellation with displacement. ## Dataflow - Inputs: mesh, texture - Outputs: mesh - Platforms: desktop-gpu, unity, unreal ## Presets ### Hardware tessellation (PN triangles) — coarse flat polyhedron (left) vs curved cubic Bézier PN silhouette & displacement (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TESS_FACTOR": 5, "P_DISPLACE": 0.55, "P_SPLIT": 0.45, "P_ROT_SPEED": 1 } ``` ```glsl const float P_TESS_FACTOR = 5.0; // P Tessellation Level [1.0, 9.0, 1.0] const float P_DISPLACE = 0.55; // P Displacement Amp [0.0, 1.4, 0.04] const float P_SPLIT = 0.45; // P Flat / PN Split [0.0, 1.0, 0.02] const float P_ROT_SPEED = 1.0; // P Spin Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Coarse low-poly icosahedron / octahedron-dodecahedron hull (sharp flat triangular facets!) float sdCoarseOctaIco(vec3 q) { vec3 a = abs(q); // Intersection of 8 octahedral planes & 6 axial planes -> crisp faceted 14-face low-poly control mesh float dOct = (a.x + a.y + a.z - 1.18) * 0.57735027; float dCube = max(a.x, max(a.y, a.z)) - 0.72; float dEdge = (max(a.x + a.y, max(a.y + a.z, a.z + a.x)) - 1.06) * 0.70710678; return max(max(dOct, dCube), dEdge); } // Curved PN-Triangle Bezier surface: replaces each flat triangle with a curved cubic patch + height displacement float mapPN(vec3 p, float dispAmp, float spin) { vec3 q = p; q.xz = rot2(spin * 0.36) * q.xz; q.yz = rot2(0.32) * q.yz; float r = length(q); vec3 d = q / max(r, 1e-4); // Smooth cubic Bezier PN-patch silhouette inflation (smoothly rounds flat hull to curved sphere-like patch) float baseR = 0.78; // High-frequency carved stone / scale displacement unlocked ONLY by hardware tessellation! float disp = (0.042 * sin(d.x * 14.0) * cos(d.y * 14.0) * sin(d.z * 14.0) + 0.024 * cos(atan(d.z, d.x) * 12.0 + d.y * 9.0)) * dispAmp; return (r - (baseR + disp)) * 0.80; } float mapFlat(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.36) * q.xz; q.yz = rot2(0.32) * q.yz; return sdCoarseOctaIco(q); } vec3 calcNormalFlat(vec3 p, float spin) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapFlat(p + e.xyy, spin) - mapFlat(p - e.xyy, spin), mapFlat(p + e.yxy, spin) - mapFlat(p - e.yxy, spin), mapFlat(p + e.yyx, spin) - mapFlat(p - e.yyx, spin) )); } vec3 calcNormalPN(vec3 p, float dispAmp, float spin) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapPN(p + e.xyy, dispAmp, spin) - mapPN(p - e.xyy, dispAmp, spin), mapPN(p + e.yxy, dispAmp, spin) - mapPN(p - e.yxy, dispAmp, spin), mapPN(p + e.yyx, dispAmp, spin) - mapPN(p - e.yyx, dispAmp, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float tessF = clamp(floor(P_TESS_FACTOR + 0.5), 1.0, 10.0); float dispAmp = clamp(P_DISPLACE, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.08, 2.48); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.03, 0.04, 0.068), vec3(0.09, 0.115, 0.168), smoothstep(-0.55, 0.55, uv.y)); bool isPN = screenX >= split; float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; float d = isPN ? mapPN(p, dispAmp, spin) : mapFlat(p, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = isPN ? calcNormalPN(p, dispAmp, spin) : calcNormalFlat(p, spin); // Object-space barycentric octahedral projection for coarse hull edges & tessellated sub-triangles! vec3 objP = p; objP.xz = rot2(spin * 0.36) * objP.xz; objP.yz = rot2(0.32) * objP.yz; vec3 a = abs(objP) / max(abs(objP.x) + abs(objP.y) + abs(objP.z), 1e-4); // Coarse patch triangle boundaries (octant edges) float coarseEdge = smoothstep(0.025, 0.004, min(a.x, min(a.y, a.z))); // Subdivided hardware tessellation barycentric lattice (scales with P_TESS_FACTOR!) vec3 tf = abs(fract(a * tessF) - 0.5); float subWire = smoothstep(0.45, 0.495, max(tf.x, max(tf.y, tf.z))); vec3 l1 = normalize(vec3(0.62, 0.85, 0.55)); vec3 l2 = normalize(vec3(-0.72, -0.22, 0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 42.0) * 0.52; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.32; vec3 alb = isPN ? vec3(0.24, 0.68, 0.92) : vec3(0.72, 0.52, 0.34); col = alb * (0.24 + 0.86 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.78, 1.0) * rim; if (isPN) { col = mix(col, vec3(0.14, 0.96, 0.78), subWire * 0.42); col = mix(col, vec3(1.0, 0.86, 0.36), coarseEdge * 0.78); } else { col = mix(col, vec3(1.0, 0.86, 0.36), coarseEdge * 0.88); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md): Tessellated, displaced surfaces need consistent tangent frames so detail normal maps still shade correctly. ## Sources 1. [primary] Alex Vlachos, Jörg Peters, Chas Boyd, Jason L. Mitchell (2001) Curved PN triangles. Proceedings of the 2001 symposium on Interactive 3D graphics. https://doi.org/10.1145/364338.364387 (verified via crossref on 2026-11-29) 2. [secondary] Matthias Nießner, Charles Loop, Mark Meyer, Tony Derose (2012) Feature-adaptive GPU rendering of Catmull-Clark subdivision surfaces. ACM Transactions on Graphics. https://doi.org/10.1145/2077341.2077347 (verified via crossref on 2026-11-29) 3. [implementation] PixarAnimationStudios (2012) PixarAnimationStudios/OpenSubdiv. https://github.com/PixarAnimationStudios/OpenSubdiv License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hardware tessellation: PN triangles and displacement." https://texelatlas.vercel.app/t/hardware-tessellation-pn-triangles/ (accessed 2026-12-01). --- id: "hashed-alpha-testing" title: "Hashed alpha testing / alpha-to-coverage for foliage" aliases: [hashed alpha, stochastic alpha testing, alpha to coverage, A2C] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2017 inputs: [texture, mesh] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Wyman & McGuire, 2017" url: "https://texelatlas.vercel.app/t/hashed-alpha-testing/" sources_verified_at: "2026-11-29" --- # Hashed alpha testing / alpha-to-coverage for foliage (Wyman & McGuire, 2017) > Replaces the fixed alpha-test threshold with a per-pixel hashed random one, so cutout edges in foliage and fences keep expected coverage as they shrink in the distance. ## Reach for it when - tree leaves thin out and vanish as they get farther away - alpha tested fences shimmer or alias at distance - foliage cutouts look crunchy and swim when moving - need cutout transparency that still writes depth for shadows - alpha to coverage still shows banding on grass cards ## How it works A fixed threshold discards pixels whose alpha is below, say, 0.5. As mipmapping averages alpha and leaves shrink on screen, the surviving area drifts, so distant foliage thins out, and the hard step produces aliasing. Hashed alpha testing compares alpha against a pseudo-random threshold in (0,1] derived from a hash of the object-space position (rather than screen position) so the pattern sticks to the surface and does not swim when the object moves. To keep the density of the noise constant on screen, the hash input is quantised at a scale taken from the screen-space derivative of the position, with the threshold interpolated between two adjacent scales. The expected coverage then equals alpha, giving a stochastic approximation of true blending that needs no sorting. Alpha-to-coverage achieves similar results with MSAA by mapping alpha to a coverage mask, optionally with dithering; [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) averages the stochastic noise over frames. ## When to use it Choose it for leaves, hair cards, grass, chain-link fences and anywhere alpha-tested cutouts must stay stable across mip levels and still write depth, so shadow maps and deferred buffers work. Prefer [Weighted blended order-independent transparency](https://texelatlas.vercel.app/t/weighted-blended-oit.md) or sorted blending for truly translucent surfaces such as glass or smoke, plain A2C when hardware MSAA is already on, and [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md) thresholds if you want a smoother noise distribution and have a TAA resolve. ## Cost cheap — A small hash and a compare in the pixel shader, plus the depth-write benefits of discarding; the main cost is the noise which needs a resolve. Measured GPU Weight: 2.26× baseline (light) — 0.0744 ms median / 0.0759 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.82× baseline (feather) — 0.0289 ms median (2.57× faster on L4). Ampere A100 scaling: 1.5× baseline (feather) — 0.0432 ms median (1.72× faster on A100). ## Failure modes - Visible static noise on foliage when there is no TAA or MSAA to average it, especially in shadows - Temporal shimmer when the hash input or scale changes with camera distance, if not quantised - Shadow maps filled with noisy cutouts need extra filtering to avoid speckled shadows - Thin geometry at distance can break up into isolated pixels instead of a coherent silhouette - Per-pixel hash behaves poorly with skinned or UV-animated materials unless a stable key is chosen ## Engine support - blender: builtin — `EEVEE Material > Surface > Render Method = Dithered (stochastic alpha)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/material_settings.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.transparency = TRANSPARENCY_ALPHA_HASH; alpha_antialiasing_mode = ALPHA_ANTIALIASING_ALPHA_TO_COVERAGE` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: builtin — `material.alphaHash = true; material.alphaToCoverage = true` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/Material.js, checked 2026-12-01) - unreal: builtin — `Material > Blend Mode = Masked with Dither Opacity Mask (dither_opacity_mask) or Alpha to Coverage (alpha_to_coverage)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/Material, checked 2026-12-01) ## Dataflow - Inputs: texture, mesh - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Hard cutoff (left) vs hashed alpha (right) leaf field (glsl-fragment; rendered 2026-11-29) ```json { "cutoff": 0.5, "leaf_scale": 6 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Left: hard alpha test at 0.5. Right: hashed alpha test (stochastic threshold per pixel). // The soft leafy alpha field is shown as black foliage over sky, so the hashed side has dithered soft edges. const float CUTOFF = 0.5; const float LEAF_SCALE = 6.0; float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); } float alphaField(vec2 uv) { vec2 g = uv * LEAF_SCALE; vec2 id = floor(g); vec2 f = fract(g) - 0.5; float r = hash12(id); vec2 off = (vec2(hash12(id + 7.1), hash12(id + 3.7)) - 0.5) * 0.4; float ang = r * 6.2831 + iTime * 0.1; mat2 R = mat2(cos(ang), -sin(ang), sin(ang), cos(ang)); vec2 q = R * (f - off) * vec2(1.0, 2.2); float leaf = 1.0 - smoothstep(0.0, 0.45, length(q)); // soft alpha ramp 0..1 inside each leaf return leaf; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float a = alphaField(uv); vec3 sky = mix(vec3(0.75, 0.88, 1.0), vec3(0.30, 0.55, 0.90), uv.y); vec3 leafCol = mix(vec3(0.10, 0.35, 0.08), vec3(0.35, 0.60, 0.12), uv.y); float threshold = (uv.x < 0.5) ? CUTOFF : hash12(floor(fragCoord)); float visible = step(threshold, a - 1e-4); vec3 col = mix(sky, leafCol, visible); if (abs(uv.x - 0.5) < 0.003) col = vec3(1.0); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; uses the Dave Hoskins-style hash without sine ## Combines with - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): TAA integrates the per-pixel stochastic coverage over frames, turning noise into smooth soft edges. ## Sources 1. [primary] Chris Wyman, Morgan McGuire (2017) Hashed alpha testing. Proceedings of the 21st ACM SIGGRAPH Symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/3023368.3023370 (verified via crossref on 2026-11-29) 2. [primary] Chris Wyman, Morgan McGuire (2019) Improved Alpha Testing Using Hashed Sampling. IEEE Transactions on Visualization and Computer Graphics. https://doi.org/10.1109/tvcg.2017.2739149 (verified via crossref on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hashed alpha testing / alpha-to-coverage for foliage." https://texelatlas.vercel.app/t/hashed-alpha-testing/ (accessed 2026-12-01). --- id: "hbao" title: "Horizon-Based Ambient Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2008 inputs: [depth, normals] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Bavoil et al., 2008" url: "https://texelatlas.vercel.app/t/hbao/" sources_verified_at: "2026-11-29" --- # Horizon-Based Ambient Occlusion (Bavoil et al., 2008) > Treats the depth buffer as a heightfield and, along several screen-space directions, finds the highest horizon angle to integrate how much of the hemisphere is blocked. ## Reach for it when - screen-space occlusion looks noisy or flat - contact shadows in creases need to be more accurate - only depth and normals available but want better darkening - cheap occlusion shows banding and haloing ## How it works HBAO marches a few steps along each of several directions around the pixel in screen space, tracking the maximum elevation angle of the sampled depth above the tangent plane of the surface. The occlusion contribution of each direction is the integral of a cosine-weighted visibility between the tangent angle and that horizon angle, evaluated analytically, with a distance falloff. Averaging across directions (jittered per pixel) gives the AO term. Because it integrates analytically over the arc rather than counting random points, it is smoother and more orientation-correct than point-sampled SSAO at similar cost, though still limited to the depth-buffer heightfield assumption. ## When to use it Choose it when SSAO looks too noisy or flat and you still only have a depth and normal buffer. Prefer [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) when you want the cosine-correct formulation with multi-bounce and bent normals, [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) for the simplest budget option, and [Visibility Bitmask Ambient Occlusion](https://texelatlas.vercel.app/t/visibility-bitmask-ssao.md) for thin-occluder handling. ## Cost cheap — Directions times steps per pixel (e.g. 4x6) plus blur; comparable to or slightly above SSAO. Measured GPU Weight: 20.48× baseline (heavy) — 0.6738 ms median / 0.699 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.16× baseline (moderate) — 0.257 ms median (2.62× faster on L4). Ampere A100 scaling: 11.69× baseline (moderate) — 0.3366 ms median (2× faster on A100). ## Failure modes - Treats everything in the depth buffer as infinitely thick, over-darkening thin objects - Banding on large radius if step count is low - Noise requires a depth-aware blur which can leak across edges - Bias from tangent-plane angle on low-poly normals ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: flat ambient. Right: HBAO, 6 screen directions x 6 steps, highest horizon above the tangent plane (glsl-fragment; rendered 2026-11-29) ```json { "INT": 1.6, "ND": 6, "NSTEP": 6, "RADS": 0.7 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const float INT=1.6; // P const int ND=6; // P const int NSTEP=6; // P const float RADS=0.7; // P float hbao(vec3 P,vec3 N,vec2 uv){ float zp=P.z-RO.z,sum=0.; for(int d=0;d1e8)continue; vec3 D=unproj(u2,zs)-P;float l=length(D); best=max(best,dot(N,D)/l*max(1.-l*l/(RADS*RADS),0.));} sum+=best;} return 1.-sum/float(ND);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao=R?clamp(1.-INT*(1.-hbao(P,n,uv)),0.,1.):1.;col=mix(ambShade(P,n,vec3(ao)),sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extends [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) - extended by [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) - extended by [Visibility Bitmask Ambient Occlusion](https://texelatlas.vercel.app/t/visibility-bitmask-ssao.md) ## Sources 1. [primary] Louis Bavoil, Miguel Sainz, Rouslan Dimitrov (2008) Image-space horizon-based ambient occlusion. ACM SIGGRAPH 2008 talks. https://doi.org/10.1145/1401032.1401061 (verified via crossref on 2026-11-29) 2. [implementation] GameTechDev (2021) GameTechDev/XeGTAO. https://github.com/GameTechDev/XeGTAO License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Horizon-Based Ambient Occlusion." https://texelatlas.vercel.app/t/hbao/ (accessed 2026-12-01). --- id: "hdr-display-output-pq" title: "HDR display output (PQ / BT.2100)" aliases: [HDR10 output, PQ encoding, ST 2084, Rec.2100 PQ, scRGB output] domain: "post" stage: "post" realtime: "realtime" platforms: [desktop-gpu, webgpu, unity, unreal, godot] year_introduced: 2014 inputs: [hdr-image] outputs: [hdr-image] style: "both" dynamic: "both" cost: "cheap" authority: "" url: "https://texelatlas.vercel.app/t/hdr-display-output-pq/" sources_verified_at: "2026-11-29" --- # HDR display output (PQ / BT.2100) > Convert scene-linear HDR rendering to an absolute-luminance signal for HDR TVs and monitors: Rec.2020 primaries plus the PQ curve, with paper white, peak and UI levels managed deliberately. ## Reach for it when - image looks washed out on an hdr monitor - need to output hdr10 from my renderer - highlights clip on hdr television despite high peak brightness - ui is far too bright when hdr is enabled - how to encode scene light values into nits for display ## How it works HDR10 and Dolby Vision-class output encode luminance in absolute nits with the perceptual quantizer (PQ, SMPTE ST 2084): linear luminance divided by 10 000 nits goes through a fixed rational power function so that 10-bit code values are spaced to match the eye's contrast sensitivity from near black to 10 000 nits. A game or viewer first renders in scene-linear colour, tone maps to a target peak (the display's reported or user-calibrated maximum) while keeping mid-grey and diffuse white mapped to a chosen reference white level (commonly around 200 nits, ITU-R BT.2408), converts from the working gamut (Rec.709/P3) to Rec.2020 with a matrix, multiplies by the reference-white scale to get nits, applies the PQ inverse EOTF, and writes to a 10-bit or float swap chain flagged as HDR10 (ST 2084 + BT.2020) or as linear scRGB. Interface elements are composited at a separately tuned brightness. Metadata like MaxCLL may be passed along. SDR fallbacks reuse the same tonemapper with a lower peak. ## When to use it Use it when shipping to HDR10 displays, consoles or OS compositors with HDR enabled; choose it for the encoding stage after tone mapping, not instead of it. Use [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md), [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md) or [Khronos PBR Neutral tone mapper](https://texelatlas.vercel.app/t/khronos-pbr-neutral.md) to compress the scene to the display's peak, [Linear-space rendering and gamma correction](https://texelatlas.vercel.app/t/linear-color-workflow.md) for the upstream linear pipeline, and [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md) for the creative look. Prefer plain sRGB output with [Reinhard photographic tone reproduction](https://texelatlas.vercel.app/t/reinhard-tonemapping.md) or [Hable filmic (Uncharted 2) tonemapping](https://texelatlas.vercel.app/t/hable-filmic-tonemapping.md) when the target is SDR, or scRGB float on Windows when the compositor handles encoding. ## Cost cheap — A per-pixel colour matrix and PQ curve in the final pass; the real work is calibration and tone mapping design. Measured GPU Weight: 1.83× baseline (feather) — 0.0602 ms median / 0.0619 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.43× baseline (feather) — 0.0227 ms median (2.65× faster on L4). Ampere A100 scaling: 1.17× baseline (feather) — 0.0336 ms median (1.79× faster on A100). ## Failure modes - Washed-out or too-dark image when PQ is written to an SDR swap chain, or an sRGB image is sent flagged as HDR - Banding in dark gradients when the framebuffer is 8-bit instead of 10-bit or float - Eye-searing UI and bloom because paper-white scaling was not applied to overlays - Highlight clipping or wrong tone when the tonemapper's peak does not match the display's reported peak - Out-of-gamut colours turning negative after Rec.709 to Rec.2020 conversion and not clamped ## Engine support - babylonjs: builtin — `WebGPU canvas configuration exposes CanvasToneMappingMode.Extended for HDR display output` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Engines/WebGPU/webgpuConstants.ts, checked 2026-12-01) — Requires a browser and display supporting WebGPU extended-range canvas presentation. - blender: builtin — `Render Properties > Color Management (wide-gamut / HDR display output transforms)` (evidence: https://docs.blender.org/manual/en/5.2/render/color_management.html, checked 2026-12-01) - godot: builtin — `Project Settings > Display > Window > HDR > Request HDR Output; Window.hdr_output_requested` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ProjectSettings.xml, checked 2026-12-01) — Platform support dependent. - metal: builtin — `CAMetalLayer.wantsExtendedDynamicRangeContent = true + MTLPixelFormat.rgba16Float / CGColorSpace.itur_2100_PQ` (evidence: https://developer.apple.com/tutorials/data/documentation/quartzcore/cametallayer/wantsextendeddynamicrangecontent.json, checked 2026-12-01) - unity: builtin — `HDRP Asset / Graphics Settings HDR Output; Volume > Tonemapping` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDR-Output.md, checked 2026-12-01) - unreal: builtin — `Enable HDR output with r.HDR.EnableHDROutput or GameUserSettings; ST-2084 (PQ) output device` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/high-dynamic-range-display-output-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `context.configure({ format: "rgba16float", toneMapping: { mode: "extended" } })` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Extended dynamic range canvas presentation in supported browsers/displays. ## Dataflow - Inputs: hdr-image - Outputs: hdr-image - Platforms: desktop-gpu, webgpu, unity, unreal, godot ## Presets ### PQ inverse EOTF vs SDR gamma, log-nits plot (glsl-fragment; rendered 2026-11-29) ```json { "m1": 0.1593017578125, "m2": 78.84375, "c1": 0.8359375, "c2": 18.8515625, "c3": 18.6875, "reference_white_nits": 203 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Plots signal value vs luminance (log axis, 0.01 .. 10000 nits): // cyan = PQ (SMPTE ST 2084) inverse EOTF, orange = SDR gamma 2.4 referenced to 100 nits (clips above 100). const float M1 = 0.1593017578125; const float M2 = 78.84375; const float C1 = 0.8359375; const float C2 = 18.8515625; const float C3 = 18.6875; const float REF_WHITE = 203.0; // BT.2408 HDR reference white in nits float pqEncode(float nits) { float y = clamp(nits / 10000.0, 0.0, 1.0); float ym = pow(y, M1); return pow((C1 + C2 * ym) / (1.0 + C3 * ym), M2); } float line(float d, float w) { return 1.0 - smoothstep(w, w * 1.8, d); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float lg = mix(-2.0, 4.0, uv.x); // log10(nits) float nits = pow(10.0, lg); vec3 col = vec3(0.07, 0.08, 0.10); // decade grid float gx = abs(fract(lg + 0.5) - 0.5) / 6.0; col += vec3(0.10) * line(gx, 0.0015); float gy = abs(fract(uv.y * 10.0 + 0.5) - 0.5) / 10.0; col += vec3(0.06) * line(gy, 0.0015); // reference-white marker float markerDist = abs(uv.x - (log(REF_WHITE) / log(10.0) + 2.0) / 6.0); col += vec3(0.5, 0.5, 0.2) * line(markerDist, 0.002); // curves: pixel distance in y to each curve float pq = pqEncode(nits); float sdr = pow(clamp(nits / 100.0, 0.0, 1.0), 1.0 / 2.4); float pxy = 1.0 / iResolution.y; col = mix(col, vec3(0.25, 0.85, 1.0), line(abs(uv.y - pq), 2.0 * pxy)); col = mix(col, vec3(1.0, 0.6, 0.2), line(abs(uv.y - sdr), 2.0 * pxy)); // filled gradient bar along the bottom showing PQ code value as grey if (uv.y < 0.04) col = vec3(pq); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; constants are those published in SMPTE ST 2084; basis: 0 ## Lineage - extends [Linear-space rendering and gamma correction](https://texelatlas.vercel.app/t/linear-color-workflow.md) ## Combines with - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): The tonemapper compresses scene light to the display's peak before PQ encodes absolute luminance. - [Auto exposure from luminance histogram](https://texelatlas.vercel.app/t/auto-exposure-histogram.md): Exposure decides where scene mid-grey lands relative to the reference-white nit level before encoding. ## Sources 1. [primary] High Dynamic Range Electro-Optical Transfer Function of Mastering Reference Displays. IEEE. https://doi.org/10.5594/smpte.st2084.2014 (verified via crossref on 2026-11-29) 2. [primary] ITU-R ITU-R BT.2100. itu.int. https://www.itu.int/rec/R-REC-BT.2100 (verified via http on 2026-11-29) 3. [tutorial] Microsoft Using DirectX with High Dynamic Range displays and Advanced Color. learn.microsoft.com. https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range (verified via http on 2026-11-29) 4. [implementation] microsoft (2015) microsoft/DirectX-Graphics-Samples. https://github.com/microsoft/DirectX-Graphics-Samples License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "HDR display output (PQ / BT.2100)." https://texelatlas.vercel.app/t/hdr-display-output-pq/ (accessed 2026-12-01). --- id: "heat-method-geodesics" title: "Heat Method for Geodesic Distance" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, python, blender] year_introduced: 2013 inputs: [mesh, point-cloud] outputs: [texture] style: "both" dynamic: "static" cost: "interactive" authority: "Crane et al., 2017" url: "https://texelatlas.vercel.app/t/heat-method-geodesics/" sources_verified_at: "2026-11-29" --- # Heat Method for Geodesic Distance (Crane et al., 2017) > Computes geodesic distance on meshes by letting heat diffuse briefly from the source, normalising its gradient, then solving a Poisson equation for the distance function. Two sparse solves, prefactorable, with no wavefront tracking. ## Reach for it when - need distance along a mesh surface, not straight line - many geodesic queries on the same mesh - draw paths or fields across a model surface - wavefront propagation for distance is too heavy - compute skinning weights from surface distance ## How it works Step one: solve one backward-Euler step of heat flow from the source, producing a smooth heat distribution u. Step two: take the gradient of u at each face and normalise it, giving a unit vector field that points away from the source. The direction is accurate even for a short time; the magnitudes are not. Step three: find the scalar function whose gradient best matches that field, by solving a Poisson equation (the Laplacian equals the divergence). Subtract the minimum so the source has zero. All three steps use the same cotan Laplacian matrix, so you factor it once and re-solve for different sources in milliseconds. The method extends to point clouds and other discretizations. ## When to use it Choose it for repeated geodesic queries on a fixed mesh: texture mapping, remeshing guides, skinning weights, vector-field design, drawing paths. Prefer exact window propagation (e.g. MMP) when you need exactness, and [Intrinsic Delaunay Triangulation](https://texelatlas.vercel.app/t/intrinsic-delaunay-triangulation.md) plus this method when mesh quality is poor and robustness matters. ## Cost interactive — Prefactor the Laplacian once; each source costs a backsolve. Scales to millions of faces with sparse Cholesky. Measured GPU Weight: 35.32× baseline (heavy) — 1.1619 ms median / 1.2168 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 30.5× baseline (heavy) — 0.4849 ms median (2.4× faster on L4). Ampere A100 scaling: 20.52× baseline (heavy) — 0.5909 ms median (1.97× faster on A100). ## Failure modes - Smoothing time step too large rounds off distance contours near sharp or thin features - Poor triangle quality (needle triangles) degrades the cotan Laplacian and the result - Not exact; errors are a few percent on regular meshes - Non-manifold or disconnected meshes need regularisation ## Dataflow - Inputs: mesh, point-cloud - Outputs: texture - Platforms: cpu, python, blender ## Presets ### Heat method geodesics — intrinsic distance isolines & normalized heat gradient on 3D manifold (glsl-fragment; rendered 2026-11-30) ```json { "P_CONTOUR_FREQ": 14, "P_DIFFUSION_TIME": 0.65, "P_HEAT_GLOW": 1, "P_GRADIENT_FIELD": 0.72 } ``` ```glsl const float P_CONTOUR_FREQ = 14.0; // P Isoline Freq [4.0, 28.0, 0.5] const float P_DIFFUSION_TIME = 0.65; // P Heat Time t [0.15, 2.0, 0.05] const float P_HEAT_GLOW = 1.0; // P Source Heat [0.0, 2.0, 0.05] const float P_GRADIENT_FIELD = 0.72; // P Gradient Lines [0.0, 1.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Sculpted genus-1 undulating manifold (fluted torus) float mapManifold(vec3 p) { vec3 q = p; q.xz = rot2(iTime * 0.28) * q.xz; q.xy = rot2(0.42) * q.xy; float ang = atan(q.z, q.x); float rMajor = 0.76 + 0.07 * sin(ang * 3.0); vec2 tq = vec2(length(q.xz) - rMajor, q.y); float phi = atan(tq.y, tq.x); float rMinor = 0.30 + 0.035 * cos(phi * 4.0 + ang * 2.0); return (length(tq) - rMinor) * 0.8; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapManifold(p + e.xyy) - mapManifold(p - e.xyy), mapManifold(p + e.yxy) - mapManifold(p - e.yxy), mapManifold(p + e.yyx) - mapManifold(p - e.yyx) )); } // Compute intrinsic toroidal-manifold geodesic distance from heat source (theta0, phi0) // Incorporates surface metric distortion from radial/minor ripples so isolines bend over curvature vec2 torusCoords(vec3 p) { vec3 q = p; q.xz = rot2(iTime * 0.28) * q.xz; q.xy = rot2(0.42) * q.xy; float theta = atan(q.z, q.x); float rMajor = 0.76 + 0.07 * sin(theta * 3.0); vec2 tq = vec2(length(q.xz) - rMajor, q.y); float phi = atan(tq.y, tq.x); return vec2(theta, phi); } float wrapPi(float a) { return mod(a + 3.14159265, 6.2831853) - 3.14159265; } // Shortest intrinsic geodesic arc length on the sculpted torus with metric curvature warp float geodesicDist(vec2 tp, vec2 src) { float dTheta = wrapPi(tp.x - src.x); float dPhi = wrapPi(tp.y - src.y); float rEff = 0.76 + 0.30 * cos(0.5 * (tp.y + src.y)); float metricBump = 1.0 + 0.08 * sin(tp.x * 3.0) + 0.06 * cos(tp.y * 4.0 + tp.x * 2.0); float ds1 = rEff * dTheta * metricBump; float ds2 = 0.31 * dPhi * (1.0 + 0.07 * sin(tp.y * 4.0)); return sqrt(ds1 * ds1 + ds2 * ds2 + 1e-6); } // Scientific perceptually-uniform inferno/plasma palette for heat -> geodesic field vec3 heatPalette(float x) { x = clamp(x, 0.0, 1.0); vec3 c0 = vec3(0.06, 0.09, 0.26); vec3 c1 = vec3(0.18, 0.44, 0.68); vec3 c2 = vec3(0.86, 0.34, 0.24); vec3 c3 = vec3(1.00, 0.88, 0.42); if (x < 0.35) return mix(c0, c1, x / 0.35); if (x < 0.72) return mix(c1, c2, (x - 0.35) / 0.37); return mix(c2, c3, (x - 0.72) / 0.28); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.15, 2.75); vec3 rd = normalize(vec3(uv, -1.5)); // Clean technical studio slate backdrop vec3 col = mix(vec3(0.04, 0.055, 0.08), vec3(0.11, 0.135, 0.18), smoothstep(-0.6, 0.6, uv.y)); vec2 g = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.03, 0.04, 0.06) * smoothstep(0.025, 0.0, min(g.x, g.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapManifold(ro + rd * t); if (d < 0.002) { hit = true; break; } t += d; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec2 tp = torusCoords(p); // Moving heat impulse source on manifold vec2 src = vec2(sin(iTime * 0.45) * 1.1, cos(iTime * 0.35) * 0.8); float dist = geodesicDist(tp, src); // Step 1 of Heat Method: heat kernel u(x,t) = exp(-d^2 / (4t)) float diffT = max(P_DIFFUSION_TIME, 0.12); float uHeat = exp(-dist * dist / (2.4 * diffT)); // Step 2: normalized negative gradient X = -grad(u)/|grad(u)| = grad(d) vec2 eps = vec2(0.015, 0.0); float dTx = geodesicDist(tp + eps.xy, src) - geodesicDist(tp - eps.xy, src); float dTy = geodesicDist(tp + eps.yx, src) - geodesicDist(tp - eps.yx, src); vec2 gradDir = normalize(vec2(dTx, dTy) + 1e-5); float flowAngle = atan(gradDir.y, gradDir.x); // Geodesic distance isolines (solution to Poisson equation div(X) = laplacian(phi)) float freq = clamp(P_CONTOUR_FREQ, 3.0, 32.0); float isoWave = abs(fract(dist * freq * 0.38 - iTime * 0.25) - 0.5); float isoLine = smoothstep(0.065, 0.015, isoWave); float majorLine = smoothstep(0.045, 0.01, abs(fract(dist * freq * 0.095 - iTime * 0.0625) - 0.5)); // Subtle orthogonal gradient flow streaks (-grad u / |grad u|) float flowStripe = smoothstep(0.86, 0.98, 0.5 + 0.5 * cos(flowAngle * 14.0)); float gradVis = flowStripe * smoothstep(0.08, 0.45, dist) * clamp(P_GRADIENT_FIELD, 0.0, 1.5) * 0.24; // Color map combining geodesic distance ramp + diffused heat core vec3 baseCol = heatPalette(1.0 - clamp(dist * 0.38, 0.0, 1.0)); baseCol = mix(baseCol, vec3(1.0, 0.96, 0.84), pow(uHeat, 2.2) * 0.55 * clamp(P_HEAT_GLOW, 0.0, 2.0)); // Subtle studio lighting over the manifold vec3 l1 = normalize(vec3(0.65, 0.82, 0.55)); vec3 l2 = normalize(vec3(-0.7, -0.2, 0.6)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 36.0) * 0.45; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.28; col = baseCol * (0.28 + 0.82 * diff1 + 0.25 * diff2) + vec3(spec) + vec3(0.45, 0.68, 1.0) * rim; col = mix(col, vec3(0.05, 0.07, 0.11), isoLine * 0.52); col = mix(col, vec3(1.0, 0.98, 0.90), majorLine * 0.72); col += vec3(0.85, 0.92, 1.0) * gradVis; // Bright heat source emitter beacon float srcSpot = smoothstep(0.11, 0.025, dist); col += vec3(1.8, 1.15, 0.45) * srcSpot * max(P_HEAT_GLOW, 0.0); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Intrinsic Delaunay Triangulation](https://texelatlas.vercel.app/t/intrinsic-delaunay-triangulation.md): Run on the intrinsic Delaunay triangulation for robustness on bad meshes. - [Tufted Cover Laplacian](https://texelatlas.vercel.app/t/tufted-laplacian.md): The tufted Laplacian lets the method run on non-manifold or messy meshes. ## Combination ideas - [Weathering that creeps along the surface](https://texelatlas.vercel.app/ideas/geodesic-weathering-sources/) ## Sources 1. [primary] Keenan Crane, Clarisse Weischedel, Max Wardetzky (2017) The heat method for distance computation. Communications of the ACM. https://doi.org/10.1145/3131280 (verified via crossref on 2026-11-29) 2. [implementation] nmwsharp (2017) nmwsharp/geometry-central. https://github.com/nmwsharp/geometry-central License: MIT. (verified via github on 2026-11-29) 3. [tutorial] Keenan Crane The Heat Method for Distance Computation. cs.cmu.edu. https://www.cs.cmu.edu/~kmcrane/Projects/HeatMethod (verified via http on 2026-11-29) ## Cite this entry Texel. "Heat Method for Geodesic Distance." https://texelatlas.vercel.app/t/heat-method-geodesics/ (accessed 2026-12-01). --- id: "henyey-greenstein-phase-function" title: "Henyey-Greenstein Phase Function" aliases: [HG phase, Cornette-Shanks (variant)] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu] year_introduced: 1941 inputs: [volume-density] outputs: [radiance] style: "both" dynamic: "both" cost: "cheap" authority: "Henyey & Greenstein, 1941" url: "https://texelatlas.vercel.app/t/henyey-greenstein-phase-function/" sources_verified_at: "2026-11-29" --- # Henyey-Greenstein Phase Function (Henyey & Greenstein, 1941) > A one-parameter model of the angular distribution of scattered light in a medium; the asymmetry g runs from strongly backward (negative) to strongly forward (positive) scattering. ## Reach for it when - fog and clouds need forward scattering glow - volume scattering direction needs one tunable parameter - light halo around sun seen through haze - cheap anisotropic scattering for participating media ## How it works A phase function gives the probability density of light scattering from one direction into another, and depends only on the cosine of the angle between them. The HG form is (1 - g^2) divided by 4 pi times (1 + g^2 - 2 g cos theta) to the power 1.5. With g = 0 it is isotropic; g near 0.7 to 0.9 gives the strong forward lobe seen on clouds and aerosol haze near the sun; negative g gives backscatter. It integrates to one over the sphere and has an exact importance-sampling inverse, so it is cheap in both ray marchers and path tracers. Real media often need two lobes: a forward and a backward HG lobe blended, which also approximates the silver lining and dark core of clouds. Rayleigh scattering uses its own dipole phase and should not be replaced by HG. ## When to use it Choose it whenever you need anisotropic scattering for fog, clouds, atmospheric Mie scattering or skin-like media at the cost of one pow per evaluation. Prefer the Rayleigh phase inside [Ray-marched Rayleigh/Mie Single Scattering](https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering.md) for molecular scattering, and use a two-lobe HG mix in [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md) or [Multiple-Scattering Approximation by Octaves](https://texelatlas.vercel.app/t/multiple-scattering-octaves.md) when a single lobe cannot capture both the sun glare and the backscattered brightness. For exact droplet behaviour use tabulated Mie phase functions offline. ## Cost cheap — A few multiplies and one pow per sample. Measured GPU Weight: 3.19× baseline (light) — 0.1049 ms median / 0.1073 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.08× baseline (light) — 0.0489 ms median (2.15× faster on L4). Ampere A100 scaling: 2.26× baseline (light) — 0.0652 ms median (1.61× faster on A100). ## Failure modes - Single lobe cannot reproduce the real Mie peak: glory and fogbow are missing - Using g close to 1 gives a very narrow lobe that aliases in ray marching with few samples - Forgetting the 4 pi normalization makes fog energy scale wrongly with g - Applying HG to Rayleigh scattering gives wrong sky polarisation-free brightness and color - Mismatch of sign convention for the angle (view vs light direction) flips forward and backward scattering ## Engine support - babylonjs: official — `@babylonjs/addons atmosphereFunctions.fx miePhase (Henyey-Greenstein Mie scattering phase)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/addons/src/atmosphere/Shaders/ShadersInclude/atmosphereFunctions.fx, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Shader > Volume Scatter > Phase = Henyey-Greenstein` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/volume_scatter.html, checked 2026-12-01) - godot: builtin — `Environment.volumetric_fog_anisotropy drives henyey_greenstein(cos_theta, g) in volumetric_fog_process.glsl` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/servers/rendering/renderer_rd/shaders/environment/volumetric_fog_process.glsl, checked 2026-12-01) - unity: builtin — `HDRP Fog > Anisotropy; Local Volumetric Fog > Anisotropy` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/VolumeRendering.hlsl, checked 2026-12-01) — HDRP volumetric fog and clouds use the HG phase function. - unreal: builtin — `SkyAtmosphereComponent Mie Anisotropy and VolumetricCloud MaterialExpressionVolumetricAdvancedMaterialOutput dual-lobe Phase controls` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/SkyAtmosphereComponent, checked 2026-12-01) ## Dataflow - Inputs: volume-density - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu ## Presets ### Henyey-Greenstein anisotropy g = -0.6, 0, 0.8 on a backlit medium (glsl-fragment; rendered 2026-11-29) ```json { "SIGMA": 3.5, "RAD": 0.72, "LIGHT": 14 } ``` ```glsl // A uniform-density sphere of scattering medium, lit from behind, single scattering only. // Three panels differ ONLY in the Henyey-Greenstein anisotropy g: -0.6 (back), 0 (isotropic), +0.8 (forward). const float SIGMA = 3.5; const float RAD = 0.72; const float LIGHT = 14.0; float hg(float c, float g) { float g2 = g * g; return (1.0 - g2) / (12.566371 * pow(1.0 + g2 - 2.0 * g * c, 1.5)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float pw = iResolution.x / 3.0; int panel = int(floor(fragCoord.x / pw)); float g = panel == 0 ? -0.6 : (panel == 1 ? 0.0 : 0.8); vec2 uv = (fragCoord - vec2((float(panel) + 0.5) * pw, 0.5 * iResolution.y)) / (0.5 * pw); vec3 col = vec3(0.015, 0.02, 0.03) + 0.02 * (uv.y * 0.5 + 0.5); vec3 ro = vec3(uv, 3.0), rd = vec3(0.0, 0.0, -1.0); vec3 L = normalize(vec3(0.25, 0.15, -1.0)); float b = dot(ro, rd); float h = b * b - dot(ro, ro) + RAD * RAD; if (h > 0.0) { float t0 = -b - sqrt(h), t1 = -b + sqrt(h); float ds = (t1 - t0) / 24.0; vec3 acc = vec3(0.0); for (int i = 0; i < 24; i++) { float s = (float(i) + 0.5) * ds; vec3 p = ro + rd * (t0 + s); float bl = dot(p, L); float tl = -bl + sqrt(max(bl * bl - dot(p, p) + RAD * RAD, 0.0)); acc += vec3(1.0, 0.95, 0.85) * SIGMA * ds * exp(-SIGMA * s) * exp(-SIGMA * tl) * hg(dot(L, rd), g) * LIGHT; } col += acc; } float edge = fract(fragCoord.x / pw); if (edge < 0.004 || edge > 0.996) col = vec3(0.3); col = 1.0 - exp(-col * 1.5); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Ray-marched Rayleigh/Mie Single Scattering](https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering.md) ## Combines with - [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md): Gives the per-sample phase weight applied to in-scattered light. - [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md): Used when injecting light into each froxel to produce a forward-scattering halo around lights. ## Sources 1. [primary] L. C. Henyey, J. L. Greenstein (1941) Diffuse radiation in the Galaxy. The Astrophysical Journal. https://doi.org/10.1086/144246 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Phase Functions (Physically Based Rendering, 4th ed.). pbr-book.org. https://www.pbr-book.org/4ed/Volume_Scattering/Phase_Functions (verified via http on 2026-11-29) ## Cite this entry Texel. "Henyey-Greenstein Phase Function." https://texelatlas.vercel.app/t/henyey-greenstein-phase-function/ (accessed 2026-12-01). --- id: "hex-tiling" title: "Hex-tiling" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2022 inputs: [texture] outputs: [texture] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Mikkelsen" url: "https://texelatlas.vercel.app/t/hex-tiling/" sources_verified_at: "2026-11-29" --- # Hex-tiling (Mikkelsen) > Mikkelsen's practical hexagonal tiling: break texture repetition by randomly rotating, offsetting and blending three overlapping hex cells per pixel. Simple, cheap and fits into existing shaders. ## Reach for it when - repeating texture pattern is obvious across terrain - tiling visible on large floors and walls - need a cheap drop-in way to hide repetition - textures look copy-pasted over big surfaces ## How it works A hexagonal grid is overlaid on UV space. For each pixel the three nearest hex centres are found and each gets a pseudo-random offset (and optionally rotation or mirroring) hashed from its cell id. The texture is sampled once per cell and the three results are blended with weights that fall from 1 at the cell centre to 0 at the edge. To avoid contrast loss in the blend, the weights are sharpened with a power function and, for detail textures, the variance can be rescaled in a histogram-preserving way (as in Heitz-Neyret). For normal maps the three fetched normals should be combined carefully (for example as surface gradients) so lighting stays consistent. Mip level selection uses analytic gradients per cell to avoid seams. ## When to use it Choose it when you want a drop-in anti-tiling operator for terrain, floors and walls with stochastic textures. Prefer [Histogram-preserving blending (stochastic texturing)](https://texelatlas.vercel.app/t/histogram-preserving-blending.md) when contrast must be exactly preserved. Prefer [Image quilting](https://texelatlas.vercel.app/t/image-quilting.md) or authored variation for structured patterns where blending would ghost. Use with [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md) for rocks. ## Cost cheap — Three fetches per texture plus a hash and weight computation. Measured GPU Weight: 3.88× baseline (light) — 0.1276 ms median / 0.1349 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.28× baseline (light) — 0.0522 ms median (2.44× faster on L4). Ampere A100 scaling: 2.4× baseline (light) — 0.0692 ms median (1.84× faster on A100). ## Failure modes - Ghosting and loss of contrast in the blend regions, especially on high-frequency textures - Visible hex structure if offsets are too small or the texture has strong directional features - Mip seams if derivatives from the transformed coordinates are not used - Rotation of an anisotropic or directional texture causes lighting direction mismatches on normal maps ## Engine support - babylonjs: builtin — `pbrMaterial.textureRepetitionMode (hex tiling mode) + textureRepetitionHexTilingParams` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBaseMaterial.pure.ts, checked 2026-12-01) — WebGL2/WebGPU only. - threejs: official — `MaterialXLoader hextile node (examples/jsm/loaders/materialx/MaterialXHextile.js)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/loaders/materialx/MaterialXHextile.js, checked 2026-12-01) — Via MaterialX hextile; not a general material option. - unity: official — `Shader Graph samples > Terrain Sample > Hex layer nodes (LayerHex)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Terrain-Shaders.md, checked 2026-12-01) — Shipped as a Shader Graph sample (Terrain Sample), not a core node. ## Dataflow - Inputs: texture - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Repeating tiles (left) vs stochastic hex-grid tiling (right) (glsl-fragment; rendered 2026-11-29) ```json { "TILES": 6, "BLEND_POW": 7 } ``` ```glsl // Stochastic hex-grid tiling: a triangle grid picks 3 random offsets per fragment and blends them // with contrast-sharpened barycentric weights. Left: ordinary repeating tiles. Right: hex tiling. const float TILES = 6.0; const float BLEND_POW = 7.0; vec3 tex(vec2 uv) { vec2 f = fract(uv); vec3 c = vec3(0.5 + 0.18 * sin(6.2832 * f.x + 1.0) * sin(12.566 * f.y)); c *= vec3(0.9, 0.8, 0.65); c = mix(c, vec3(0.08, 0.06, 0.05), smoothstep(0.17, 0.1, length(f - vec2(0.3, 0.65)))); c = mix(c, vec3(0.9, 0.85, 0.7), smoothstep(0.02, 0.0, abs(length(f - vec2(0.72, 0.3)) - 0.12))); c = mix(c, vec3(0.7, 0.2, 0.15), smoothstep(0.025, 0.0, abs(f.x - f.y * 0.5 - 0.4))); return c; } vec2 h2(vec2 p) { return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); } vec3 hexTex(vec2 uv) { vec2 sk = mat2(1.0, -0.57735027, 0.0, 1.15470054) * (uv * 3.4641016); vec2 base = floor(sk); vec2 tt = fract(sk); vec3 bary = vec3(tt, 1.0 - tt.x - tt.y); vec2 v1, v2, v3; vec3 w; if (bary.z > 0.0) { v1 = base; v2 = base + vec2(0.0, 1.0); v3 = base + vec2(1.0, 0.0); w = vec3(bary.z, bary.y, bary.x); } else { v1 = base + vec2(1.0, 1.0); v2 = base + vec2(1.0, 0.0); v3 = base + vec2(0.0, 1.0); w = vec3(-bary.z, 1.0 - bary.y, 1.0 - bary.x); } w = pow(w, vec3(BLEND_POW)); w /= (w.x + w.y + w.z); return tex(uv + h2(v1)) * w.x + tex(uv + h2(v2)) * w.y + tex(uv + h2(v3)) * w.z; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy * TILES; vec3 col = fragCoord.x < 0.5 * iResolution.x ? tex(uv) : hexTex(uv); if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Histogram-preserving blending (stochastic texturing)](https://texelatlas.vercel.app/t/histogram-preserving-blending.md) ## Combines with - [Surface gradient based bump mapping framework](https://texelatlas.vercel.app/t/surface-gradient-bump-mapping.md): Blends the three hex-cell normals as surface gradients so shading stays consistent. ## Combination ideas - [One phone photo, a whole floor](https://texelatlas.vercel.app/ideas/one-photo-endless-material/) ## Sources 1. [primary] Morten S. Mikkelsen Practical Real-Time Hex-Tiling. JCGT 2022. https://jcgt.org/published/0011/03/05 (verified via http on 2026-11-29) 2. [implementation] mmikk (2022) mmikk/hextile-demo. https://github.com/mmikk/hextile-demo License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hex-tiling." https://texelatlas.vercel.app/t/hex-tiling/ (accessed 2026-12-01). --- id: "hierarchical-binary-tree-3dgs-lod" title: "Hierarchical Binary-Tree 3DGS LOD & Paged Streaming" aliases: [Hierarchical 3D Gaussians, 3DGS LOD hierarchy, paged Gaussian splat streaming] domain: "capture" stage: "capture" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, cuda] year_introduced: 2024 inputs: [gaussians, camera-poses] outputs: [gaussians, hdr-image] style: "photoreal" dynamic: "static" cost: "medium" authority: "Kerbl et al., 2024" url: "https://texelatlas.vercel.app/t/hierarchical-binary-tree-3dgs-lod/" sources_verified_at: "2026-11-30" --- # Hierarchical Binary-Tree 3DGS LOD & Paged Streaming (Kerbl et al., 2024) > Organizes tens of millions of 3D Gaussians into a spatial binary tree whose internal nodes store merged parent splats, enabling view-dependent cut selection, smooth LOD blending, and out-of-core paged streaming. ## Reach for it when - million-splat 3dgs scenes drop frames when viewed from a distance - need automatic level of detail for huge city-scale gaussian splat captures - bound per-frame active splat count via view-dependent screen-space error - merge distant gaussians cleanly without darkening or holes in the silhouette - stream and traverse large 3dgs hierarchies dynamically in a compute shader ## How it works Flat 3D Gaussian Splatting breaks down on city-scale or multi-room captures because every splat must reside in VRAM and be projected every frame regardless of screen size. Hierarchical 3DGS partitions a massive capture into spatial chunks and builds a **binary LOD tree** over the Gaussians: leaves hold the finest captured primitives, while each internal node merges a cluster of child Gaussians into a coarser proxy Gaussian whose covariance, opacity, and spherical-harmonic appearance are re-optimized against the training views. At runtime, a view-dependent traversal walks the tree against a projected **screen-space error threshold** (in pixels), selecting an active **cut** where every rendered splat covers roughly a target pixel budget. Nodes whose children project too small collapse to their parent; as the camera approaches, parents smoothly cross-fade into their children to suppress LOD popping. For web and memory-constrained viewers, subtrees are serialized into fixed-size **paged chunks** fetched asynchronously on demand. An LRU residency cache maps active pages into a bounded GPU storage pool, letting browsers stream multi-gigabyte splat worlds within a fixed memory and draw budget. ## When to use it Choose it when rendering large outdoor environments, architectural walkthroughs, or multi-million-splat captures that exceed GPU memory or browser download budgets. Prefer [gaussian-splatting-3dgs](gaussian-splatting-3dgs) when the scene has under a few million splats and fits comfortably in VRAM without preprocessing. Prefer [mip-splatting](mip-splatting) when you only need alias-free minification of a single-resolution cloud without out-of-core streaming. Prefer [nanite-virtualized-geometry](nanite-virtualized-geometry) when your asset is authored as high-density triangle meshes rather than radiance-field splats. ## Cost medium — Keeps active splat count bounded to a steady screen-space budget regardless of total world size; offline tree construction and chunk optimization are heavy. ## Failure modes - Visible density shifts or color shimmer during parent-to-child transitions if coarse proxies were not jointly re-optimized - Asynchronous network or disk paging delays leave coarse stand-ins visible during rapid camera teleports - Tree traversal and page residency bookkeeping add per-frame CPU or compute-shader scheduling overhead - Hierarchy structure assumes static scene geometry and cannot easily accommodate deforming splats ## Dataflow - Inputs: gaussians, camera-poses - Outputs: gaussians, hdr-image - Platforms: webgpu, webgl2, desktop-gpu, cuda ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combines with - [Self-Organizing Gaussians (SOG) 2D Codebook Image Compression](https://texelatlas.vercel.app/t/self-organizing-gaussians-compression.md): Encodes each streamed LOD page as compact 2D codebook textures to slash network transfer and VRAM residency. - [4× MSAA Sort-Free Stochastic Gaussian Splatting](https://texelatlas.vercel.app/t/sort-free-stochastic-splatting-msaa.md): Avoids expensive global re-sorts whenever streamed LOD pages enter or leave the active GPU pool. ## Combination ideas - [Sort-free neural-denoised LOD Gaussian splats](https://texelatlas.vercel.app/ideas/stochastic-lod-neural-splats/) ## Sources 1. [primary] Bernhard Kerbl, Andreas Meuleman, Georgios Kopanas, Michael Wimmer, Alexandre Lanvin, George Drettakis (2024) A Hierarchical 3D Gaussian Representation for Real-Time Rendering of Very Large Datasets. ACM Transactions on Graphics. https://doi.org/10.1145/3658160 (verified via crossref on 2026-11-30) 2. [implementation] graphdeco-inria (2024) graphdeco-inria/hierarchical-3d-gaussians. https://github.com/graphdeco-inria/hierarchical-3d-gaussians License: NOASSERTION. (verified via github on 2026-11-30) 3. [implementation] WilliamLiu-1997 (2026) WilliamLiu-1997/Gaussian-Splat-Lite. https://github.com/WilliamLiu-1997/Gaussian-Splat-Lite License: Apache-2.0. (verified via github on 2026-11-30) ## Cite this entry Texel. "Hierarchical Binary-Tree 3DGS LOD & Paged Streaming." https://texelatlas.vercel.app/t/hierarchical-binary-tree-3dgs-lod/ (accessed 2026-12-01). --- id: "hierarchical-z-occlusion-culling" title: "Hierarchical-Z occlusion culling" aliases: [Hi-Z culling, HZB culling] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal] year_introduced: 1993 inputs: [depth, mesh] outputs: [visibility-mask] style: "both" dynamic: "both" cost: "cheap" authority: "Greene et al., 1993" url: "https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling/" sources_verified_at: "2026-11-29" --- # Hierarchical-Z occlusion culling (Greene et al., 1993) > Build a mip chain of the depth buffer keeping the farthest depth per texel, then reject any object whose bounds lie entirely behind that conservative depth. ## Reach for it when - objects hidden behind walls still get drawn - dense city or indoor scene overdraws badly - need to skip hidden geometry using the depth buffer - too many draws for things you can't see - gpu culling against last frame's depth ## How it works After rendering occluders, downsample the depth buffer into a pyramid where each texel stores the maximum (farthest) depth of the texels beneath it. To test an object, project its bounding box to screen, pick the mip level at which the box covers about one texel or a few, sample depth there, and compare the box's nearest depth against it. If the nearest point is behind everything, the object is hidden. GPU-driven engines typically reuse the previous frame's depth, reprojected, then test and draw in a second pass to fix false rejections. ## When to use it Choose it for dense indoor or urban scenes where large occluders hide most geometry. Prefer software occlusion rasterization on CPU for non-GPU-driven pipelines, or portal and PVS systems for static levels. Prefer plain frustum culling in open, flat scenes where occlusion rarely helps. ## Cost cheap — Pyramid build is a few small passes; tests are a handful of texture fetches per object. Measured GPU Weight: 345.82× baseline (extreme) — 10.8589 ms median / 10.9263 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 379.3× baseline (extreme) — 5.993 ms median (1.81× faster on L4). Ampere A100 scaling: 231.36× baseline (extreme) — 6.6632 ms median (1.63× faster on A100). ## Failure modes - Using last frame's depth causes objects to be culled wrongly after fast camera or object motion - Conservative tests miss thin occluders, leaving culling inefficient - Mip selection errors give over-culling and visible holes - Needs depth readable as a texture, which complicates MSAA ## Engine support - blender: builtin — `EEVEE maintains a mipmapped HiZBuffer pyramid for screen-space raytracing and visibility culling` (evidence: https://github.com/blender/blender/blob/main/source/blender/draw/engines/eevee/eevee_hizbuffer.cc, checked 2026-12-01) - unity: builtin — `URP/HDRP Asset > GPU Resident Drawer enabled > GPU Occlusion Culling` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/gpu-culling.md, checked 2026-12-01) — GPU occlusion culling needs GPU Resident Drawer. - unreal: builtin — `Console variable r.HZBOcclusion=1` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/visibility-and-occlusion-culling-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, mesh - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal ## Presets ### Hierarchical-Z occlusion culling — Hi-Z max-depth mip pyramid vs conservative box culling (glsl-fragment; rendered 2026-11-30) ```json { "P_MIP_LEVEL": 3, "P_OCCLUDER_H": 0.72, "P_SPLIT": 0.44, "P_SWEEP_SPEED": 1 } ``` ```glsl const float P_MIP_LEVEL = 3.0; // P Hi-Z Mip Level [1.0, 5.0, 1.0] const float P_OCCLUDER_H = 0.72; // P Occluder Height [0.25, 1.2, 0.03] const float P_SPLIT = 0.44; // P Hi-Z / Cull Split [0.0, 1.0, 0.02] const float P_SWEEP_SPEED = 1.0; // P Camera Sway [0.0, 2.5, 0.05] 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); } // Primary foreground occluder walls & piers float mapOccluders(vec3 p, float occH) { float d = p.y + 0.85; float w1 = sdBox(p - vec3(-0.72, -0.85 + occH, -0.8), vec3(0.58, occH, 0.14)); float w2 = sdBox(p - vec3(0.68, -0.85 + occH * 0.88, -1.15), vec3(0.52, occH * 0.88, 0.14)); float w3 = sdBox(p - vec3(0.02, -0.85 + occH * 0.62, -2.05), vec3(0.46, occH * 0.62, 0.14)); return min(d, min(w1, min(w2, w3))); } // Evaluate depth of foreground occluders along a view ray float traceOccluderDepth(vec3 ro, vec3 rd, float occH) { float t = 0.05; for (int i = 0; i < 40; i++) { float d = mapOccluders(ro + rd * t, occH); if (d < 0.003) return t; t += d; if (t > 12.0) break; } return 12.0; } vec3 calcOccNormal(vec3 p, float occH) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapOccluders(p + e.xyy, occH) - mapOccluders(p - e.xyy, occH), mapOccluders(p + e.yxy, occH) - mapOccluders(p - e.yxy, occH), mapOccluders(p + e.yyx, occH) - mapOccluders(p - e.yyx, occH) )); } // Project a 3D world point into camera screen space (uv, depth) vec3 projectPt(vec3 p, vec3 ro, vec3 fw, vec3 rt, vec3 up) { vec3 v = p - ro; float z = dot(v, fw); float x = dot(v, rt) / max(z, 0.05) * 1.45; float y = dot(v, up) / max(z, 0.05) * 1.45; return vec3(x, y, z); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float tAnim = iTime * max(P_SWEEP_SPEED, 0.0); float occH = clamp(P_OCCLUDER_H, 0.2, 1.3); float mipLvl = floor(clamp(P_MIP_LEVEL, 1.0, 5.0)); float split = clamp(P_SPLIT, 0.0, 1.0); vec3 ro = vec3(0.65 * sin(tAnim * 0.55), 0.35 + 0.12 * cos(tAnim * 0.4), 2.35); vec3 ta = vec3(0.0, -0.15, -1.4); vec3 fw = normalize(ta - ro); vec3 rt = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(rt, fw); vec3 rd = normalize(fw * 1.45 + rt * uv.x + up * uv.y); // Trace foreground occluders float tOcc = traceOccluderDepth(ro, rd, occH); // Conservative Hi-Z max-depth mip cell for current pixel float cellRes = pow(2.0, 6.0 - mipLvl); vec2 cellSize = vec2(1.0 / cellRes); vec2 cellCenter = (floor(uv * cellRes) + 0.5) * cellSize; float hiZMax = 0.0; for (int j = 0; j < 2; j++) { for (int i = 0; i < 2; i++) { vec2 off = (vec2(float(i), float(j)) - 0.5) * cellSize * 0.72; vec2 suv = cellCenter + off; vec3 srd = normalize(fw * 1.45 + rt * suv.x + up * suv.y); hiZMax = max(hiZMax, traceOccluderDepth(ro, srd, occH)); } } // Base shaded scene (sky + occluder walls) vec3 sky = mix(vec3(0.05, 0.07, 0.11), vec3(0.12, 0.18, 0.28), clamp(uv.y + 0.5, 0.0, 1.0)); vec3 sceneCol = sky; if (tOcc < 11.5) { vec3 p = ro + rd * tOcc; vec3 n = calcOccNormal(p, occH); vec3 lDir = normalize(vec3(0.55, 0.85, 0.45)); float diff = max(dot(n, lDir), 0.0); float isFloor = step(0.85, n.y); vec2 grid = abs(fract(p.xz * 1.5 - 0.5) - 0.5); float gLine = smoothstep(0.035, 0.008, min(grid.x, grid.y)); vec3 alb = mix(vec3(0.18, 0.22, 0.29), vec3(0.12, 0.14, 0.18) + gLine * vec3(0.07, 0.11, 0.16), isFloor); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); sceneCol = alb * (0.28 + 0.85 * diff) + vec3(0.18, 0.34, 0.52) * rim * (1.0 - isFloor) * 0.45; } // Evaluate 9 candidate bounding boxes behind the occluders against the Hi-Z pyramid vec3 boxOverlay = vec3(0.0); float boxAlpha = 0.0; for (int k = 0; k < 9; k++) { float fk = float(k); float row = floor(fk / 3.0); float colIdx = mod(fk, 3.0) - 1.0; vec3 bPos = vec3( colIdx * 0.92 + 0.25 * sin(tAnim * 0.7 + fk * 1.4), -0.42 + 0.32 * sin(tAnim * 0.9 + fk * 2.1) + row * 0.18, -1.55 - row * 0.95 ); vec3 bHalf = vec3(0.20, 0.24, 0.20); // Project candidate box center & evaluate conservative Hi-Z occlusion test vec3 proj = projectPt(bPos, ro, fw, rt, up); float boxMinZ = proj.z - 0.24; vec2 bCell = (floor(proj.xy * cellRes) + 0.5) * cellSize; float localHiZ = 0.0; for (int sy = 0; sy < 2; sy++) { for (int sx = 0; sx < 2; sx++) { vec2 suv = bCell + (vec2(float(sx), float(sy)) - 0.5) * cellSize * 0.65; vec3 srd = normalize(fw * 1.45 + rt * suv.x + up * suv.y); localHiZ = max(localHiZ, traceOccluderDepth(ro, srd, occH)); } } bool isCulled = boxMinZ > localHiZ; // Ray-box analytic intersection for rendering the candidate box vec3 invRd = 1.0 / (rd + sign(rd + 1e-6) * 1e-5); vec3 t0 = (bPos - bHalf - ro) * invRd; vec3 t1 = (bPos + bHalf - ro) * invRd; vec3 tMinV = min(t0, t1); vec3 tMaxV = max(t0, t1); float tNear = max(max(tMinV.x, tMinV.y), tMinV.z); float tFar = min(min(tMaxV.x, tMaxV.y), tMaxV.z); if (tFar > max(tNear, 0.05)) { vec3 hitP = ro + rd * tNear; vec3 lp = abs((hitP - bPos) / bHalf); float edge = smoothstep(0.84, 0.96, max(max(min(lp.x, lp.y), min(lp.y, lp.z)), min(lp.x, lp.z))); if (!isCulled && tNear < tOcc) { vec3 bn = normalize(sign(hitP - bPos) * step(vec3(0.98), lp)); float bDiff = 0.35 + 0.75 * max(dot(bn, normalize(vec3(0.5, 0.9, 0.4))), 0.0); vec3 visCol = mix(vec3(0.14, 0.84, 0.58), vec3(0.96, 0.98, 0.85), edge); sceneCol = visCol * bDiff; tOcc = tNear; } else if (isCulled) { // X-ray magenta wireframe showing Hi-Z culled geometry saved from rasterization vec3 cullCol = vec3(1.0, 0.22, 0.55) * (0.28 + 1.35 * edge); boxOverlay = max(boxOverlay, cullCol); boxAlpha = max(boxAlpha, 0.24 + 0.58 * edge); } } // Screen-space projected AABB indicator on Hi-Z side float halfW = 0.24 / max(proj.z, 0.3) * 1.45; vec2 boxD = abs(uv - proj.xy) - vec2(halfW); float rectEdge = smoothstep(0.012, 0.002, abs(max(boxD.x, boxD.y))); if (screenX < split) { vec3 tagCol = isCulled ? vec3(1.0, 0.24, 0.52) : vec3(0.18, 0.96, 0.62); boxOverlay = max(boxOverlay, tagCol * rectEdge * 1.4); boxAlpha = max(boxAlpha, rectEdge * 0.85); } } // Left view: Hi-Z Depth Mip Pyramid visualization vec3 hiZCol; float zNorm = clamp(1.0 - (hiZMax - 1.2) / 5.5, 0.0, 1.0); hiZCol = mix(vec3(0.04, 0.08, 0.22), vec3(0.18, 0.68, 0.94), smoothstep(0.0, 0.65, zNorm)); hiZCol = mix(hiZCol, vec3(0.96, 0.92, 0.52), smoothstep(0.65, 1.0, zNorm)); vec2 cellF = abs(fract(uv * cellRes) - 0.5); float cellGrid = smoothstep(0.46, 0.50, max(cellF.x, cellF.y)); hiZCol = mix(hiZCol, vec3(0.05, 0.09, 0.14), cellGrid * 0.55); vec3 col = (screenX < split) ? mix(hiZCol, boxOverlay, boxAlpha) : mix(sceneCol, boxOverlay, boxAlpha * 0.68); float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) - extended by [Masked software occlusion culling](https://texelatlas.vercel.app/t/masked-software-occlusion-culling.md) ## Combines with - [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md): Meshlet bounding spheres project to small boxes that the pyramid can reject cheaply. ## Sources 1. [primary] Ned Greene, Michael Kass, Gavin Miller (1993) Hierarchical Z-buffer visibility. Proceedings of the 20th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/166117.166147 (verified via crossref on 2026-11-29) 2. [implementation] zeux (2018) zeux/niagara. https://github.com/zeux/niagara License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hierarchical-Z occlusion culling." https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling/ (accessed 2026-12-01). --- id: "hillaire-sky-atmosphere" title: "Scalable Production Sky and Atmosphere (Hillaire)" aliases: [UE Sky Atmosphere, multi-scattering LUT] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unreal] year_introduced: 2020 inputs: [material-params, depth] outputs: [radiance, hdr-image] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Hillaire, 2020" url: "https://texelatlas.vercel.app/t/hillaire-sky-atmosphere/" sources_verified_at: "2026-11-29" --- # Scalable Production Sky and Atmosphere (Hillaire) (Hillaire, 2020) > Real-time planetary atmosphere built from small per-frame lookup tables: transmittance, a multiple-scattering table and a sky-view table, plus a camera froxel volume for aerial perspective. ## Reach for it when - real-time sky with time of day changes - view from ground to space atmosphere in a game - aerial perspective haze over distant terrain - sky colour must update without long precompute ## How it works Every frame a few tiny LUTs are rebuilt, so all atmosphere parameters can be animated. A transmittance LUT stores optical depth to the top of atmosphere indexed by height and sun angle. A multi-scattering LUT replaces higher-order scattering with an isotropic-source approximation: it evaluates a geometric series of the second-order bounce, indexed by height and sun angle, which is cheap and close to brute-force results. A sky-view LUT then ray-marches single scattering once per direction (parametrized to concentrate texels at the horizon) and adds the multi-scattering term. For geometry, a low-resolution camera-aligned volume of scattering and transmittance gives aerial perspective on opaque and transparent objects by one fetch. Sun and moon discs, ground bounce and planet shadow fall out of the same tables. ## When to use it Choose it when the atmosphere must be fully dynamic (time of day, weather-driven density, alien planets), run on a console or mobile-class budget, and be applied to opaque objects, particles and clouds consistently. Prefer [Precomputed Atmospheric Scattering](https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering.md) when parameters are fixed and you want the more exact multi-order reference with irradiance tables. Prefer [Preetham Analytic Daylight Model](https://texelatlas.vercel.app/t/preetham-sky.md) or [Hosek-Wilkie Sky Model](https://texelatlas.vercel.app/t/hosek-wilkie-sky.md) when you only need a ground-level sky dome with no aerial perspective. Pair with [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md) for the cloud layer. ## Cost cheap — The paper reports it runs within a small frame budget on consoles and mobile hardware; the LUT updates are low resolution so cost scales mainly with the sky-view and froxel passes. Measured GPU Weight: 103.13× baseline (extreme) — 3.393 ms median / 3.5244 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 90.42× baseline (extreme) — 1.4377 ms median (2.36× faster on L4). Ampere A100 scaling: 70.36× baseline (extreme) — 2.0265 ms median (1.67× faster on A100). ## Failure modes - Multi-scattering approximation drifts from ground truth for very thick atmospheres or high-albedo ground - Low-res aerial perspective volume shows banding or leaks near depth discontinuities - Sky-view LUT interpolation can blur the sun's near-horizon glow and produce a faint ring around the sun disc - Camera inside a cloud or fog layer needs separate handling; the model assumes space-like atmosphere layers - No shadowing of atmosphere by terrain unless extra shadow-volume sampling is added ## Engine support - babylonjs: official — `import { Atmosphere } from '@babylonjs/addons/atmosphere'` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/addons/src/atmosphere/atmosphere.ts, checked 2026-12-01) — Sky-view LUT, aerial perspective, multiple scattering. - blender: builtin — `World Shader > Sky Texture node (Nishita physical multi-scattering sky)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/sky.html, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Sky > Visual Environment > Sky Type = Physically Based Sky` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/physically-based-sky-volume-override-reference.md, checked 2026-12-01) — HDRP only; Physically Based Sky cites Hillaire 2020 and Bruneton 2008. - unreal: builtin — `Place Actors > Visual Effects > Sky Atmosphere (Sky Atmosphere component)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sky-atmosphere-component-in-unreal-engine, checked 2026-12-01) — Physically based multiple-scattering sky/aerial perspective; docs do not name the paper. ## Dataflow - Inputs: material-params, depth - Outputs: radiance, hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unreal ## Presets ### Toy ray-marched single-scattering atmosphere with Hillaire coefficients at sunset (glsl-fragment; rendered 2026-11-29) ```json { "R_PLANET": 6360, "R_ATMOS": 6460, "SUN_I": 22 } ``` ```glsl // Toy single-scattering atmosphere ray-march using the Hillaire (2020) coefficient set: // Rayleigh + Mie + ozone absorption, planet shadow, ground bounce. Real-time version bakes this into LUTs. const float R_PLANET = 6360.0; const float R_ATMOS = 6460.0; const vec3 BETA_R = vec3(5.802, 13.558, 33.1) * 1e-3; const float BETA_M_S = 3.996e-3; const float BETA_M_E = 4.44e-3; const vec3 BETA_O = vec3(0.65, 1.881, 0.085) * 1e-3; const float SUN_I = 22.0; vec2 raySph(vec3 ro, vec3 rd, float r) { float b = dot(ro, rd), c = dot(ro, ro) - r * r, h = b * b - c; if (h < 0.0) return vec2(-1.0); h = sqrt(h); return vec2(-b - h, -b + h); } vec3 densities(vec3 p) { float h = length(p) - R_PLANET; return vec3(exp(-h / 8.0), exp(-h / 1.2), max(0.0, 1.0 - abs(h - 25.0) / 15.0)); } vec3 ext(vec3 d) { return BETA_R * d.x + BETA_M_E * d.y + BETA_O * d.z; } vec3 sunTrans(vec3 p, vec3 sd) { if (raySph(p, sd, R_PLANET).x > 0.0) return vec3(0.0); float len = raySph(p, sd, R_ATMOS).y; float ds = len / 6.0; vec3 od = vec3(0.0); for (int i = 0; i < 6; i++) od += ext(densities(p + sd * (float(i) + 0.5) * ds)) * ds; return exp(-od); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, R_PLANET + 0.3, 0.0); vec3 rd = normalize(vec3(uv.x * 1.3, uv.y * 1.3 + 0.14, -1.0)); vec3 sd = normalize(vec3(0.25, 0.07, -1.0)); vec2 pg = raySph(ro, rd, R_PLANET); float tmax = pg.x > 0.0 ? pg.x : raySph(ro, rd, R_ATMOS).y; float cs = dot(rd, sd); float phR = 3.0 / (16.0 * 3.14159) * (1.0 + cs * cs); float g = 0.8; float phM = (1.0 - g * g) / (12.566 * pow(1.0 + g * g - 2.0 * g * cs, 1.5)); vec3 od = vec3(0.0), L = vec3(0.0); for (int i = 0; i < 24; i++) { float t0 = tmax * pow(float(i) / 24.0, 2.0), t1 = tmax * pow(float(i + 1) / 24.0, 2.0); float ds = t1 - t0; vec3 p = ro + rd * (0.5 * (t0 + t1)); vec3 d = densities(p); od += ext(d) * ds; L += exp(-od) * sunTrans(p, sd) * (BETA_R * d.x * phR + BETA_M_S * d.y * phM) * ds * SUN_I; } if (pg.x > 0.0) { vec3 hp = ro + rd * pg.x; vec3 n = normalize(hp); L += exp(-od) * vec3(0.12, 0.1, 0.08) * sunTrans(hp, sd) * max(dot(n, sd), 0.0) * SUN_I; } else if (cs > 0.99995) L += exp(-od) * SUN_I * 8.0; L = 1.0 - exp(-L * 0.9); fragColor = vec4(pow(L, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Precomputed Atmospheric Scattering](https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering.md) ## Combines with - [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md): Sky-view and transmittance LUTs light the cloud layer; clouds are composited before the aerial-perspective volume is applied. - [Exponential Height Fog](https://texelatlas.vercel.app/t/exponential-height-fog.md): Aerial perspective handles distant haze while height fog covers the low, dense layer near ground. ## Sources 1. [primary] Sébastien Hillaire (2020) A Scalable and Production Ready Sky and Atmosphere Rendering Technique. Computer Graphics Forum. https://doi.org/10.1111/cgf.14050 (verified via crossref on 2026-11-29) 2. [implementation] sebh (2020) sebh/UnrealEngineSkyAtmosphere. https://github.com/sebh/UnrealEngineSkyAtmosphere License: MIT. (verified via github on 2026-11-29) 3. [implementation] takram-design-engineering (2024) takram-design-engineering/three-geospatial. https://github.com/takram-design-engineering/three-geospatial License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Scalable Production Sky and Atmosphere (Hillaire)." https://texelatlas.vercel.app/t/hillaire-sky-atmosphere/ (accessed 2026-12-01). --- id: "histogram-preserving-blending" title: "Histogram-preserving blending (stochastic texturing)" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2018 inputs: [texture] outputs: [texture] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Heitz & Neyret, 2018" url: "https://texelatlas.vercel.app/t/histogram-preserving-blending/" sources_verified_at: "2026-11-29" --- # Histogram-preserving blending (stochastic texturing) (Heitz & Neyret, 2018) > Heitz and Neyret's by-example noise: tile a texture stochastically on a triangular grid and blend overlapping tiles in a Gaussianised colour space so the blended result keeps the exemplar's histogram, instead of washing out to grey. ## Reach for it when - blending tiles washes the texture out to grey - tiling hidden but contrast and detail get lost - need seamless non-repeating terrain texture - stochastic tiling must keep the original colour distribution ## How it works Naive random blending of texture tiles averages colours, which narrows the histogram and loses contrast. The method first transforms the exemplar to a Gaussian colour space by histogram transfer and stores an inverse lookup table. A triangle grid selects three random tile offsets per pixel; the three Gaussianised samples are blended linearly with barycentric weights, which keeps Gaussian statistics, then variance is renormalised by the weights' length, and the table is inverted to return to colour space. Result: non-repeating texture with the same colour distribution as the input, evaluated with three fetches and no precomputed large texture. Works best on stochastic (non-structured) exemplars like rock, grass or dirt, and requires texture compression of the Gaussianised data to avoid quantisation. ## When to use it Choose it to remove tiling on stochastic textures such as terrain and large floors. Prefer [Hex-tiling](https://texelatlas.vercel.app/t/hex-tiling.md) when you want a cheaper, simpler hexagonal variant that works with arbitrary textures (it has weaker statistics preservation). Prefer [Image quilting](https://texelatlas.vercel.app/t/image-quilting.md) when the texture has structure that must be preserved. Combine with [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md) on cliffs. ## Cost cheap — Three texture fetches plus a LUT inversion per map; modest overhead over plain tiling. Measured GPU Weight: 18.52× baseline (moderate) — 0.6093 ms median / 0.6211 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 15.46× baseline (moderate) — 0.2458 ms median (2.48× faster on L4). Ampere A100 scaling: 12.03× baseline (moderate) — 0.3466 ms median (1.76× faster on A100). ## Failure modes - Fails on structured textures (bricks, tiles): blending destroys edges and creates ghosting - Gaussian transform needs precomputation and extra LUT storage per texture - Compressed textures can band after the inverse LUT - Blending normals or roughness maps needs separate care, since they are not colour-histogram data ## Dataflow - Inputs: texture - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Histogram-Preserving Blending — linear hex-tile washout (left) vs variance-preserving stochastic blend (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TILE_SCALE": 5.5, "P_BLEND_SOFT": 0.75, "P_CAM_DRIFT": 0.6, "P_SPLIT": 0.48 } ``` ```glsl const float P_TILE_SCALE = 5.5; // P Hex Grid Scale [2.5, 10.0, 0.25] const float P_BLEND_SOFT = 0.75; // P Overlap Width [0.2, 1.0, 0.02] const float P_CAM_DRIFT = 0.60; // P Glide Speed [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Linear / Histogram [0.0, 1.0, 0.02] vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // High-contrast exemplar stone-pebble & lichen texture (Gaussian-like zero-mean scalar + rich palette) // Returns vec4(rgb, gaussianVal) where gaussianVal has mean 0 and unit variance for exact HPB math vec4 sampleExemplar(vec2 uv) { vec2 g = uv * 4.5; vec2 i = floor(g); vec2 f = fract(g); float d1 = 8.0; float d2 = 8.0; vec2 id = vec2(0.0); for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { vec2 n = vec2(float(x), float(y)); vec2 o = hash22(i + n); vec2 r = n + 0.18 + 0.64 * o - f; float d = dot(r, r); if (d < d1) { d2 = d1; d1 = d; id = i + n; } else if (d < d2) { d2 = d; } } } float edge = sqrt(d2) - sqrt(d1); float pebble = smoothstep(0.04, 0.18, edge); float grain = sin(uv.x * 48.0 + sin(uv.y * 36.0)) * 0.12; float h = clamp(pebble * (0.68 + 0.32 * hash22(id).x) + grain, 0.0, 1.0); // Zero-mean centered Gaussian proxy for variance-preserving blend float gVal = (h - 0.52) * 2.2; vec3 rock = mix(vec3(0.10, 0.12, 0.15), vec3(0.76, 0.68, 0.56), h); rock = mix(rock, vec3(0.26, 0.44, 0.24), smoothstep(0.08, 0.02, edge) * 0.72); return vec4(rock, gVal); } // Map centered Gaussianized value back through non-linear exemplar CDF -> razor-sharp contrast! vec3 invCDFColor(float gVal, vec3 avgTint) { // Smooth S-curve matching the bimodal pebble/mortar histogram float h = clamp(0.52 + 0.46 * tanh(gVal * 1.15), 0.0, 1.0); vec3 c = mix(vec3(0.07, 0.09, 0.12), vec3(0.82, 0.72, 0.58), smoothstep(0.18, 0.82, h)); c = mix(c, vec3(0.22, 0.46, 0.22), smoothstep(0.32, 0.12, h) * 0.65); return mix(c, avgTint * 1.15, 0.28); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isHPB = screenX >= split; float scale = clamp(P_TILE_SCALE, 2.0, 12.0); float soft = clamp(P_BLEND_SOFT, 0.15, 1.0); float drift = iTime * max(P_CAM_DRIFT, 0.0) * 0.35; // Oblique ground plane to showcase large-scale non-repeating stochastic tiling vec3 ro = vec3(0.0, 1.15, 2.0 - drift); vec3 rd = normalize(vec3(uv.x, uv.y - 0.36, -1.25)); vec3 sky = mix(vec3(0.035, 0.048, 0.082), vec3(0.12, 0.18, 0.28), smoothstep(-0.15, 0.5, uv.y)); vec3 col = sky; if (rd.y < -0.01) { float t = -ro.y / rd.y; if (t > 0.1 && t < 24.0) { vec3 p = ro + rd * t; vec2 st = p.xz * scale * 0.38; // Triangular simplex lattice for 3-tap stochastic hex-tile blending (Heitz & Neyret 2018) const mat2 skew = mat2(1.0, 0.0, -0.57735027, 1.15470054); vec2 sUV = skew * st; vec2 base = floor(sUV); vec2 f = fract(sUV); vec2 v1 = base; vec2 v2 = base + ((f.x > f.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)); vec2 v3 = base + vec2(1.0, 1.0); // Barycentric weights of the 3 stochastic tiles float w1 = (f.x > f.y) ? (1.0 - f.x) : (1.0 - f.y); float w2 = abs(f.x - f.y); float w3 = min(f.x, f.y); // Sharpen or widen overlap region with P_BLEND_SOFT float pw = mix(4.5, 1.15, soft); w1 = pow(max(w1, 1e-4), pw); w2 = pow(max(w2, 1e-4), pw); w3 = pow(max(w3, 1e-4), pw); float wSum = w1 + w2 + w3; w1 /= wSum; w2 /= wSum; w3 /= wSum; // 3 randomized tile offsets vec4 t1 = sampleExemplar(st + hash22(v1) * 7.3); vec4 t2 = sampleExemplar(st + hash22(v2) * 7.3); vec4 t3 = sampleExemplar(st + hash22(v3) * 7.3); vec3 linRGB = w1 * t1.rgb + w2 * t2.rgb + w3 * t3.rgb; if (!isHPB) { // Left: Standard linear blending (notice muddy contrast loss inside overlap zones!) col = linRGB; } else { // Right: Histogram-Preserving Blending normalizes by L2 norm sqrt(w1^2 + w2^2 + w3^2)! float invL2 = 1.0 / sqrt(max(w1 * w1 + w2 * w2 + w3 * w3, 1e-4)); float gBlend = (w1 * t1.w + w2 * t2.w + w3 * t3.w) * invL2; col = invCDFColor(gBlend, linRGB); } // Subtle hex-blend overlap indicator contour float overlap = 1.0 - max(w1, max(w2, w3)); col += (isHPB ? vec3(0.04, 0.14, 0.16) : vec3(0.16, 0.05, 0.08)) * smoothstep(0.35, 0.65, overlap) * 0.35; col = mix(col, sky, 1.0 - exp(-t * 0.075)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Hex-tiling](https://texelatlas.vercel.app/t/hex-tiling.md) ## Combines with - [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md): Removes visible repetition from each of the three projected fetches. ## Sources 1. [primary] Eric Heitz, Fabrice Neyret (2018) High-Performance By-Example Noise using a Histogram-Preserving Blending Operator. Proceedings of the ACM on Computer Graphics and Interactive Techniques. https://doi.org/10.1145/3233304 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Histogram-preserving blending (stochastic texturing)." https://texelatlas.vercel.app/t/histogram-preserving-blending/ (accessed 2026-12-01). --- id: "hosek-wilkie-sky" title: "Hosek-Wilkie Sky Model" aliases: [Hosek sky, analytic full-spectral sky-dome radiance] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 2012 inputs: [material-params] outputs: [radiance, hdr-image] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Hosek & Wilkie, 2012" url: "https://texelatlas.vercel.app/t/hosek-wilkie-sky/" sources_verified_at: "2026-11-29" --- # Hosek-Wilkie Sky Model (Hosek & Wilkie, 2012) > Analytic sky-dome radiance fitted to brute-force atmospheric simulations, with turbidity, ground albedo and solar elevation controls and a correct sun-disc and horizon behaviour. ## Reach for it when - need accurate daytime sky colour from dawn to dusk - sun halo and horizon look wrong in my analytic sky - sky dome with turbidity and ground albedo controls - want a visible solar aureole cheaply - realistic sky without a full atmosphere simulation ## How it works Like the Perez-style approach, the sky radiance is a closed-form expression in the view direction and sun angle, but the fit is far more accurate. A nine-parameter formula adds terms for the circumsolar brightening (a Mie-like lobe), for horizon darkening, and for multiple scattering, with a ground-albedo dependence. The nine coefficients and a zenith radiance are not computed analytically: they are interpolated from tables obtained by fitting simulation data over turbidity, albedo, solar elevation and wavelength. The RGB variant uses tables for three wavelength bands, and a spectral version covers many bands. At run time you fetch the coefficients once per frame on the CPU (sun elevation and turbidity change slowly) and evaluate one formula per pixel on the GPU. ## When to use it Choose it for ground-based skies when you want accurate color from dawn to dusk, including a visible solar aureole, and when the table-lookup coefficients can be baked into uniforms. Prefer [Preetham Analytic Daylight Model](https://texelatlas.vercel.app/t/preetham-sky.md) when a smaller code footprint is more important than accuracy. Prefer [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) when you need aerial perspective, camera altitude changes or a sun below the horizon. Prefer [Precomputed Atmospheric Scattering](https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering.md) for planet-scale views. ## Cost cheap — One formula evaluation per pixel; coefficient interpolation is done on the CPU once per frame. Measured GPU Weight: 4.79× baseline (light) — 0.1577 ms median / 0.1591 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 4.2× baseline (light) — 0.0668 ms median (2.36× faster on L4). Ampere A100 scaling: 2.89× baseline (light) — 0.0833 ms median (1.89× faster on A100). ## Failure modes - Coefficient tables are large and embedded as data, which makes porting error-prone - Valid only for sun above or near the horizon; twilight needs another model - No aerial perspective: distant objects are not tinted - Ground albedo only changes the sky radiance, not the ground itself - RGB fit can show a slight hue shift versus the spectral version ## Engine support - blender: builtin — `Sky Texture node > Sky Type = Hosek/Wilkie` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/sky.html, checked 2026-12-01) — Marked legacy and slated for removal. ## Dataflow - Inputs: material-params - Outputs: radiance, hdr-image - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Hosek-Wilkie analytic sky dome with circumsolar aureole, turbidity and ocean reflection (glsl-fragment; rendered 2026-11-30) ```json { "TURBIDITY": 3, "SUN_ELEV": 0.24, "ALBEDO": 0.35, "EXPOSURE": 1.1 } ``` ```glsl const float TURBIDITY = 3.0; // P const float SUN_ELEV = 0.24; // P const float ALBEDO = 0.35; // P const float EXPOSURE = 1.1; // P float chi(float g, float cosG) { float d = max(1.0 + g * g - 2.0 * g * cosG, 1e-4); return (1.0 + cosG * cosG) / pow(d, 1.5); } vec3 hosekSky(vec3 dir, vec3 sunDir, float turb, float elev, float alb) { float cosT = max(dir.y, 0.002); float cosG = clamp(dot(dir, sunDir), -1.0, 1.0); float gamma = acos(cosG); float t = clamp((turb - 1.0) / 9.0, 0.0, 1.0); float s = clamp(elev / 1.4, 0.0, 1.0); // Hosek-Wilkie 9-parameter structure fitted across turbidity, elevation & ground albedo vec3 A = mix(vec3(-1.12, -1.08, -0.98), vec3(-0.78, -0.82, -0.88), t); vec3 B = mix(vec3(-0.34, -0.38, -0.44), vec3(-0.18, -0.22, -0.26), t); vec3 C = mix(vec3(0.28, 0.42, 0.68), vec3(0.82, 0.72, 0.60), t) * (1.0 + 0.35 * alb); vec3 D = mix(vec3(3.8, 2.4, 1.2), vec3(1.5, 1.25, 0.95), s) * mix(1.0, 1.5, t); vec3 E = vec3(-2.6, -2.85, -3.2); vec3 F = mix(vec3(0.24, 0.30, 0.42), vec3(0.18, 0.20, 0.22), t); vec3 G = mix(vec3(0.05, 0.065, 0.08), vec3(0.14, 0.13, 0.11), t); vec3 H = mix(vec3(0.22, 0.48, 1.05), vec3(0.65, 0.62, 0.58), t) * (0.65 + 0.5 * alb); float gMie = mix(0.74, 0.88, t); vec3 expM = exp(E * gamma); vec3 rayM = vec3(cosG * cosG); vec3 mieM = vec3(chi(gMie, cosG)); vec3 zenith = mix(vec3(0.26, 0.20, 0.34), vec3(0.12, 0.38, 0.95), pow(s, 0.55)); zenith = mix(zenith, vec3(0.45, 0.44, 0.46), t * 0.45) * (0.45 + 0.85 * s); vec3 Fval = (1.0 + A * exp(B / (cosT + 0.01))) * (C + D * expM + F * rayM + G * mieM + H * sqrt(cosT)); vec3 sky = max(Fval * zenith, 0.0); // Limb-darkened solar disk + aureole float sunRad = 0.028; float ang = gamma; float disk = smoothstep(sunRad, sunRad * 0.55, ang); float limb = sqrt(max(1.0 - (ang / sunRad) * (ang / sunRad), 0.0)); vec3 sunCol = mix(vec3(1.0, 0.36, 0.10), vec3(1.0, 0.94, 0.84), pow(s, 0.45)) * mix(1.0, 0.72, t); sky += sunCol * (disk * (14.0 + 22.0 * limb) + 0.38 * exp(-ang * 7.0) * (1.0 + t)); return sky; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float elev = clamp(SUN_ELEV + 0.06 * sin(iTime * 0.35), 0.03, 1.35); float azim = 0.25 * sin(iTime * 0.22); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { vec2 m = iMouse.xy / iResolution.xy; elev = clamp(m.y * 1.15 + 0.03, 0.03, 1.35); azim = (m.x - 0.5) * 1.8; } vec3 sunDir = normalize(vec3(sin(azim) * cos(elev), sin(elev), -cos(azim) * cos(elev))); vec3 rd = normalize(vec3(uv.x, uv.y + 0.14, -1.05)); float turb = max(TURBIDITY, 1.0); float alb = clamp(ALBEDO, 0.0, 1.0); vec3 col; if (rd.y >= 0.0) { col = hosekSky(rd, sunDir, turb, elev, alb); } else { float t = -1.2 / min(rd.y, -0.002); vec2 p = rd.xz * t; float w1 = sin(p.x * 1.4 + iTime * 1.6 + sin(p.y * 0.8)) * 0.015; float w2 = cos(p.y * 2.1 - iTime * 1.2 + p.x * 0.7) * 0.012; vec3 n = normalize(vec3(w1, 1.0, w2)); vec3 refl = reflect(rd, n); refl.y = max(refl.y, 0.004); float fres = 0.04 + 0.96 * pow(1.0 - max(dot(-rd, n), 0.0), 5.0); vec3 skyR = hosekSky(normalize(refl), sunDir, turb, elev, alb); vec3 sea = vec3(0.012, 0.032, 0.065) * (0.25 + 0.65 * sin(elev)); col = mix(sea, skyR, fres * 0.85); vec3 horiz = hosekSky(normalize(vec3(rd.x, 0.005, rd.z)), sunDir, turb, elev, alb); col = mix(horiz, col, exp(-0.018 * t)); } col *= max(EXPOSURE, 0.1); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extends [Preetham Analytic Daylight Model](https://texelatlas.vercel.app/t/preetham-sky.md) ## Combines with - [Exponential Height Fog](https://texelatlas.vercel.app/t/exponential-height-fog.md): Sky horizon radiance gives a matching fog color. ## Combination ideas - [Day-cycle relighting for a dot product](https://texelatlas.vercel.app/ideas/time-of-day-prt/) ## Sources 1. [primary] Lukas Hosek, Alexander Wilkie (2012) An analytic model for full spectral sky-dome radiance. ACM Transactions on Graphics. https://doi.org/10.1145/2185520.2185591 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Hosek-Wilkie Sky Model." https://texelatlas.vercel.app/t/hosek-wilkie-sky/ (accessed 2026-12-01). --- id: "hunyuan3d-2-1" title: "Hunyuan3D 2.1" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [ldr-image] outputs: [mesh, material-params, texture] style: "both" dynamic: "static" cost: "heavy" authority: "Hunyuan3D et al., 2025" url: "https://texelatlas.vercel.app/t/hunyuan3d-2-1/" sources_verified_at: "2026-11-29" --- # Hunyuan3D 2.1 (Hunyuan3D et al., 2025) > An update of Hunyuan3D 2.0 that replaces plain colour texturing with physically based material generation, released with its training code. ## Reach for it when - generated 3d models have blurry or inconsistent textures - need pbr textured meshes from a single image - want open source image to 3d with materials - ai asset generation with relightable materials ## How it works The shape stage remains an image-conditioned diffusion transformer over a mesh latent. The change is in texturing: the paint model generates multi-view images for several material channels (albedo plus metallic and roughness) so that the assembled UV maps can be relit in a standard PBR renderer instead of having shading baked in. The authors also open the training pipeline for both stages, which makes fine-tuning on private assets possible. Everything else, including bare-mesh extraction and UV baking, follows the 2.0 design. ## When to use it Choose it when generated assets will be relit in an engine and need metallic and roughness maps. Prefer [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) when you only need albedo and want the lighter pipeline, [TRELLIS.2 (O-Voxel structured latents)](https://texelatlas.vercel.app/t/trellis-2.md) when open surfaces and native PBR voxels matter, and [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) for quick Gaussian previews. ## Cost heavy — Larger memory footprint than 2.0 because of the additional material views; see the repo for requirements. ## Failure modes - Generated metallic and roughness are plausible guesses, not measurements, and can disagree with the albedo - Residual baked highlights in albedo from reference photo - Seams where multi-view material images overlap - Custom licence terms on weights (SPDX NOASSERTION) ## Dataflow - Inputs: ldr-image - Outputs: mesh, material-params, texture - Platforms: cuda, python ## Lineage - extends [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) ## Sources 1. [primary] Team Hunyuan3D, Shuhui Yang, Mingxin Yang, Yifei Feng, Xin Huang, Sheng Zhang, Zebin He, Di Luo, Haolin Liu, Yunfei Zhao, Qingxiang Lin, Zeqiang Lai, Xianghui Yang, Huiwen Shi, Zibo Zhao, Bowen Zhang, Hongyu Yan, Lifu Wang, Sicong Liu, Jihong Zhang, Meng Chen, Liang Dong, Yiwen Jia, Yulin Cai, Jiaao Yu, Yixuan Tang, Dongyuan Guo, Junlin Yu, Hao Zhang, Zheng Ye, Peng He, Runzhou Wu, Shida Wei, Chao Zhang, Yonghao Tan, Yifu Sun, Lin Niu, Shirui Huang, Bojian Zheng, Shu Liu, Shilin Chen, Xiang Yuan, Xiaofeng Yang, Kai Liu, Jianchen Zhu, Peng Chen, Tian Liu, Di Wang, Yuhong Liu, Linus, Jie Jiang, Jingwei Huang, Chunchao Guo (2025) Hunyuan3D 2.1: From Images to High-Fidelity 3D Assets with Production-Ready PBR Material. arXiv preprint (cs.CV). https://arxiv.org/abs/2506.15442 (verified via arxiv on 2026-11-29) 2. [implementation] Tencent-Hunyuan (2025) Tencent-Hunyuan/Hunyuan3D-2.1. https://github.com/Tencent-Hunyuan/Hunyuan3D-2.1 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hunyuan3D 2.1." https://texelatlas.vercel.app/t/hunyuan3d-2-1/ (accessed 2026-12-01). --- id: "hunyuan3d-2" title: "Hunyuan3D 2.0" aliases: [Hunyuan3D-DiT] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [ldr-image] outputs: [mesh, texture, uv-atlas] style: "both" dynamic: "static" cost: "heavy" authority: "Zhao et al., 2025" url: "https://texelatlas.vercel.app/t/hunyuan3d-2/" sources_verified_at: "2026-11-29" --- # Hunyuan3D 2.0 (Zhao et al., 2025) > A two-stage open system: a flow-based diffusion transformer generates a bare mesh from an image, then a separate multi-view diffusion model paints a texture onto it. ## Reach for it when - want a textured game-ready mesh from one image - need to re-texture generated geometry separately - generated 3d meshes should be open weights - image-to-3d where i can swap the paint stage ## How it works Stage one, Hunyuan3D-DiT, encodes meshes into a latent with a shape VAE and trains a flow-matching diffusion transformer on that latent, conditioned on an image; the decoded signed distance field becomes a bare mesh. Stage two, Hunyuan3D-Paint, takes the bare mesh and the input image, renders geometry-aware conditions such as normal and position maps from several viewpoints, generates consistent multi-view colour images and back-projects them into a UV texture. Because the stages are decoupled, either can be used alone: you can texture any mesh, not just generated ones. ## When to use it Choose it when you want a textured game-ready mesh from an image and the freedom to swap or re-run the texture stage on your own geometry. Prefer [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) when you need PBR material maps, [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) for Gaussian output and a more permissive licence, and [MeshAnything](https://texelatlas.vercel.app/t/meshanything.md) or [MeshFlow](https://texelatlas.vercel.app/t/meshflow.md) afterwards when you need artist-style low-poly topology. ## Cost heavy — Seconds to minutes per asset depending on resolution and GPU; see the repo. ## Failure modes - Texture seams and lighting baked into albedo from the input photo - Back-projection leaves low-resolution or smeared patches in occluded regions - Meshes are dense, irregular triangulations, not artist topology - Licence for weights is a custom community licence (SPDX NOASSERTION), restricting use in some regions ## Dataflow - Inputs: ldr-image - Outputs: mesh, texture, uv-atlas - Platforms: cuda, python ## Lineage - extended by [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) ## Combines with - [MeshAnything](https://texelatlas.vercel.app/t/meshanything.md): The dense generated mesh can be retopologised into an artist-like low-poly mesh by an autoregressive mesh model. ## Sources 1. [primary] Zibo Zhao, Zeqiang Lai, Qingxiang Lin, Yunfei Zhao, Haolin Liu, Shuhui Yang, Yifei Feng, Mingxin Yang, Sheng Zhang, Xianghui Yang, Huiwen Shi, Sicong Liu, Junta Wu, Yihang Lian, Fan Yang, Ruining Tang, Zebin He, Xinzhou Wang, Jian Liu, Xuhui Zuo, Zhuo Chen, Biwen Lei, Haohan Weng, Jing Xu, Yiling Zhu, Xinhai Liu, Lixin Xu, Changrong Hu, Shaoxiong Yang, Song Zhang, Yang Liu, Tianyu Huang, Lifu Wang, Jihong Zhang, Meng Chen, Liang Dong, Yiwen Jia, Yulin Cai, Jiaao Yu, Yixuan Tang, Hao Zhang, Zheng Ye, Peng He, Runzhou Wu, Chao Zhang, Yonghao Tan, Jie Xiao, Yangyu Tao, Jianchen Zhu, Jinbao Xue, Kai Liu, Chongqing Zhao, Xinming Wu, Zhichao Hu, Lei Qin, Jianbing Peng, Zhan Li, Minghui Chen, Xipeng Zhang, Lin Niu, Paige Wang, Yingkai Wang, Haozhao Kuang, Zhongyi Fan, Xu Zheng, Weihao Zhuang, YingPing He, Tian Liu, Yong Yang, Di Wang, Yuhong Liu, Jie Jiang, Jingwei Huang, Chunchao Guo (2025) Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation. arXiv preprint (cs.CV). https://arxiv.org/abs/2501.12202 (verified via arxiv on 2026-11-29) 2. [implementation] Tencent-Hunyuan (2025) Tencent-Hunyuan/Hunyuan3D-2. https://github.com/Tencent-Hunyuan/Hunyuan3D-2 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hunyuan3D 2.0." https://texelatlas.vercel.app/t/hunyuan3d-2/ (accessed 2026-12-01). --- id: "hunyuan3d-paint" title: "Hunyuan3D-Paint" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [mesh, ldr-image] outputs: [texture, uv-atlas] style: "both" dynamic: "static" cost: "heavy" authority: "Zhao et al., 2025" url: "https://texelatlas.vercel.app/t/hunyuan3d-paint/" sources_verified_at: "2026-11-29" --- # Hunyuan3D-Paint (Zhao et al., 2025) > The texturing half of Hunyuan3D 2.0: it generates consistent multi-view colour renderings of a given mesh from an image and bakes them into a UV texture. ## Reach for it when - have a mesh and need a texture matching a concept image - texturing a scanned or generated mesh from one picture - generated textures differ between viewing angles - bake consistent multi-view colour into a uv map - paint an existing model from a reference image ## How it works Given a mesh and a reference image, the model renders geometry conditions (normal and position maps) for a set of camera views and runs a multi-view diffusion model that outputs colour images for all views at once, with attention shared across views to keep them consistent. The images are projected onto the mesh, blended in UV space, and inpainted where views did not reach. Since it only needs a mesh and an image, it is usable as a stand-alone texturing tool on hand-modelled or scanned geometry. ## When to use it Choose it when you have a fixed mesh (scanned, sculpted or generated by another model) and a single concept image to match. Prefer [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md) or [Text2Tex](https://texelatlas.vercel.app/t/text2tex.md) when only a text prompt is available, [Paint3D](https://texelatlas.vercel.app/t/paint3d.md) when you need lighting-less albedo from a prompt, and [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) for PBR channels. ## Cost heavy — Seconds to minutes per mesh on a single GPU. ## Failure modes - Seams and ghosting in UV where view blending disagrees - Texture detail limited by the number and resolution of generated views - Concave regions and under-surfaces get blurry inpainting - Input mesh without clean UVs forces automatic unwrapping that wastes texel density ## Dataflow - Inputs: mesh, ldr-image - Outputs: texture, uv-atlas - Platforms: cuda, python ## Sources 1. [primary] Zibo Zhao, Zeqiang Lai, Qingxiang Lin, Yunfei Zhao, Haolin Liu, Shuhui Yang, Yifei Feng, Mingxin Yang, Sheng Zhang, Xianghui Yang, Huiwen Shi, Sicong Liu, Junta Wu, Yihang Lian, Fan Yang, Ruining Tang, Zebin He, Xinzhou Wang, Jian Liu, Xuhui Zuo, Zhuo Chen, Biwen Lei, Haohan Weng, Jing Xu, Yiling Zhu, Xinhai Liu, Lixin Xu, Changrong Hu, Shaoxiong Yang, Song Zhang, Yang Liu, Tianyu Huang, Lifu Wang, Jihong Zhang, Meng Chen, Liang Dong, Yiwen Jia, Yulin Cai, Jiaao Yu, Yixuan Tang, Hao Zhang, Zheng Ye, Peng He, Runzhou Wu, Chao Zhang, Yonghao Tan, Jie Xiao, Yangyu Tao, Jianchen Zhu, Jinbao Xue, Kai Liu, Chongqing Zhao, Xinming Wu, Zhichao Hu, Lei Qin, Jianbing Peng, Zhan Li, Minghui Chen, Xipeng Zhang, Lin Niu, Paige Wang, Yingkai Wang, Haozhao Kuang, Zhongyi Fan, Xu Zheng, Weihao Zhuang, YingPing He, Tian Liu, Yong Yang, Di Wang, Yuhong Liu, Jie Jiang, Jingwei Huang, Chunchao Guo (2025) Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation. arXiv preprint (cs.CV). https://arxiv.org/abs/2501.12202 (verified via arxiv on 2026-11-29) 2. [implementation] Tencent-Hunyuan (2025) Tencent-Hunyuan/Hunyuan3D-2. https://github.com/Tencent-Hunyuan/Hunyuan3D-2 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hunyuan3D-Paint." https://texelatlas.vercel.app/t/hunyuan3d-paint/ (accessed 2026-12-01). --- id: "hybrid-ray-traced-reflections" title: "Hybrid ray-traced reflections" aliases: [RT reflections with SSR fallback, hybrid reflections, ray-traced reflections denoised] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, unreal, unity] year_introduced: 2018 inputs: [gbuffer, depth, normals, irradiance-probes] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Barré-Brisebois et al., 2019" url: "https://texelatlas.vercel.app/t/hybrid-ray-traced-reflections/" sources_verified_at: "2026-11-29" --- # Hybrid ray-traced reflections (Barré-Brisebois et al., 2019) > Reflections are traced against the scene only where screen-space reflections or probes would fail, with ray counts adapted to roughness and a denoiser to clean the result. It trades some tracing cost for high-quality, off-screen reflections. ## Reach for it when - screen space reflections are missing off screen content - want high quality glossy reflections on rtx hardware - reflections need to fall back gracefully when rays miss - probes reflections are too coarse for mirror like floors ## How it works A hybrid pipeline mixes sources for the reflected radiance. The cheapest is screen-space marching ([screen-space-reflections](screen-space-reflections)); when the march leaves the screen or reaches hidden surfaces the pipeline falls back to hardware ray tracing against the BVH, and misses beyond that read a reflection probe ([reflection-probes-parallax-corrected-cubemaps](reflection-probes-parallax-corrected-cubemaps)) or sky. Rays are generated per pixel from importance-sampled GGX normals ([vndf-sampling](vndf-sampling)), with count and tracing budget scaled by roughness. Very rough surfaces skip tracing entirely and use probes. At hit points the renderer evaluates a simplified material with probe or cached lighting rather than recursive shading, to bound cost. The traced result is noisy, so a spatial filter guided by roughness and a temporal accumulation stage reconstruct it. Shadow rays at the hit and a reflection-to-reflection depth of one keep it within a frame budget on current GPUs. ## When to use it Choose it for mirror-like and glossy reflections of dynamic content on ray-tracing-capable hardware, where SSR leaves holes at screen edges and probes are too coarse. Prefer [screen-space-reflections](screen-space-reflections) alone on mid-range hardware or when off-screen reflections are unimportant. Prefer [planar-reflections-oblique-clipping](planar-reflections-oblique-clipping) for a single flat mirror where re-rendering is cheaper and exact. Prefer [path-tracing](path-tracing) or [restir-gi](restir-gi) when reflections must include multiple glossy bounces and full global illumination, and [reflection-probes-parallax-corrected-cubemaps](reflection-probes-parallax-corrected-cubemaps) when rays are unavailable. ## Cost heavy — Tracing plus denoising typically takes several milliseconds at 1080p on ray-tracing GPUs; cost scales with ray count and hit-shader complexity. Measured GPU Weight: 42.15× baseline (heavy) — 1.3866 ms median / 1.4713 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 46.43× baseline (heavy) — 0.7383 ms median (1.88× faster on L4). Ampere A100 scaling: 27.49× baseline (heavy) — 0.7918 ms median (1.75× faster on A100). ## Failure modes - Visible seam where the pipeline switches between SSR, traced and probe sources, especially in mirrored moving content - Noisy or smeared rough reflections when the denoiser's history is rejected on moving objects - Ghosting of dynamic objects because temporal accumulation keeps reflections from previous frames - Reflections of simplified hit shading look flatter than the directly shaded scene - Ray budget runs out on very glossy large surfaces such as wet floors, producing tracing bubbles - Fine detail such as thin grates or foliage gives incoherent rays and slow traversal ## Engine support - metal: builtin — `MTLAccelerationStructure + intersector<> in MSL` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlaccelerationstructure.json, checked 2026-12-01) — API primitive for ray/scene intersection; reflection shader and denoise are yours. - unity: builtin — `HDRP Volume > Ray-Traced Reflections (layers over Screen Space Reflection)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Reflections.md, checked 2026-12-01) — HDRP with DXR hardware only. - unreal: builtin — `Project Settings > Engine > Rendering: Support Hardware Ray Tracing + Use Hardware Ray Tracing when available; Ray Lighting Mode = Hit Lighting for Reflections` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/lumen-technical-details-in-unreal-engine, checked 2026-12-01) — Lumen screen traces/surface cache with hardware RT hit lighting. ## Dataflow - Inputs: gbuffer, depth, normals, irradiance-probes - Outputs: radiance - Platforms: desktop-gpu, unreal, unity ## Presets ### Hybrid Ray-Traced Reflections — screen-space reflection holes & missing off-screen emitters (left) vs world-space RT fallback (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FLOOR_ROUGH": 0.1, "P_PANEL_GLOW": 1.4, "P_CAM_SWAY": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_FLOOR_ROUGH = 0.10; // P Floor Roughness [0.02, 0.35, 0.02] const float P_PANEL_GLOW = 1.40; // P Neon Intensity [0.4, 2.4, 0.1] const float P_CAM_SWAY = 0.45; // P Camera Sway [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P SSR / Hybrid RT Split [0.0, 1.0, 0.02] 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); } // Gallery hall with glossy floor, pillars, a central sculpture, AND off-screen overhead neon light strips! vec2 mapGallery(vec3 p) { float dFloor = p.y + 0.65; vec2 res = vec2(dFloor, 1.0); // Back wall float dBack = p.z + 2.45; if (dBack < res.x) res = vec2(dBack, 2.0); // Two dark slate pillars (visible on-screen) float dP1 = sdBox(p - vec3(-0.92, 0.25, -0.75), vec3(0.22, 0.92, 0.22)); if (dP1 < res.x) res = vec2(dP1, 3.0); float dP2 = sdBox(p - vec3(0.92, 0.25, -0.95), vec3(0.22, 0.92, 0.22)); if (dP2 < res.x) res = vec2(dP2, 3.0); // Central floating warm amber neon ring/monolith (partially on screen) float dCol = length(p - vec3(0.0, -0.05, -0.55)) - 0.34; if (dCol < res.x) res = vec2(dCol, 4.0); // OFF-SCREEN overhead magenta-gold ceiling light panel (above camera frustum y = 1.45!) float dCeilPanel = sdBox(p - vec3(0.0, 1.48, -0.65), vec3(1.15, 0.06, 0.55)); if (dCeilPanel < res.x) res = vec2(dCeilPanel, 5.0); // OFF-SCREEN behind-pillar cyan vertical beacon strip (occluded from primary camera!) float dHiddenStrip = sdBox(p - vec3(-0.92, 0.15, -1.28), vec3(0.16, 0.72, 0.06)); if (dHiddenStrip < res.x) res = vec2(dHiddenStrip, 6.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapGallery(p + e.xyy).x - mapGallery(p - e.xyy).x, mapGallery(p + e.yxy).x - mapGallery(p - e.yxy).x, mapGallery(p + e.yyx).x - mapGallery(p - e.yyx).x )); } vec3 shadeHit(vec3 p, vec3 n, float id, float glow) { vec3 lDir = normalize(vec3(0.45, 0.85, 0.35)); float ndl = max(dot(n, lDir), 0.0); if (id < 1.5) return vec3(0.06, 0.07, 0.09) * (0.4 + 0.6 * ndl); if (id < 2.5) { float stripe = smoothstep(0.06, 0.01, abs(fract(p.x * 1.4) - 0.5)); return mix(vec3(0.14, 0.16, 0.21), vec3(0.28, 0.32, 0.40), stripe) * (0.35 + 0.65 * ndl); } if (id < 3.5) { // Pillar with thin emissive trim float trim = smoothstep(0.06, 0.015, abs(p.y + 0.12)); return vec3(0.18, 0.21, 0.28) * (0.3 + 0.7 * ndl) + vec3(0.18, 0.88, 1.0) * trim * glow * 1.4; } if (id < 4.5) return vec3(0.95, 0.66, 0.28) * (0.28 + 0.72 * ndl); if (id < 5.5) { // Overhead off-screen neon art panel (warm coral + magenta bars) float bars = 0.5 + 0.5 * sin(p.x * 7.5 + iTime * 1.4); return mix(vec3(2.4, 0.32, 0.58), vec3(2.8, 1.45, 0.25), bars) * glow; } return vec3(0.16, 1.95, 2.35) * glow; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useHybridRT = sx >= split; float rough = clamp(P_FLOOR_ROUGH, 0.01, 0.45); float glow = clamp(P_PANEL_GLOW, 0.3, 2.8); float sway = sin(iTime * max(P_CAM_SWAY, 0.0) * 0.8) * 0.28; vec3 ro = vec3(sway, 0.16, 2.15); vec3 ta = vec3(0.0, -0.22, -0.65); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); float fl = 1.48; vec3 rd = normalize(fw * fl + ri * uv.x + up * uv.y); vec3 envAmb = mix(vec3(0.04, 0.05, 0.08), vec3(0.11, 0.14, 0.22), smoothstep(-0.3, 0.5, rd.y)); vec3 col = envAmb; float t = 0.05; float hitId = 0.0; for (int i = 0; i < 64; i++) { vec2 h = mapGallery(ro + rd * t); if (h.x < 0.002) { hitId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hitId > 0.5) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); col = shadeHit(p, n, hitId, glow); // Glossy reflection pass on marble floor (id == 1) and chrome sphere (id == 4) if (hitId < 1.5 || (hitId > 3.5 && hitId < 4.5)) { vec3 reflN = n; if (hitId < 1.5) { // Subtle marble tile normal ripple for floor roughness vec2 tile = floor(p.xz * 2.0); float w = sin(p.x * 16.0 + tile.y) * cos(p.z * 16.0 + tile.x) * rough * 0.08; reflN = normalize(n + vec3(w, 0.0, -w)); } vec3 rDir = reflect(rd, reflN); vec3 rOrig = p + n * 0.015; // Trace world-space reflection ray float rt = 0.04; float rId = 0.0; for (int j = 0; j < 52; j++) { vec2 rh = mapGallery(rOrig + rDir * rt); if (rh.x < 0.003) { rId = rh.y; break; } rt += rh.x; if (rt > 8.0) break; } vec3 reflCol = envAmb; if (rId > 0.5) { vec3 rp = rOrig + rDir * rt; vec3 rn = calcNormal(rp); vec3 trueRefl = shadeHit(rp, rn, rId, glow); // Project reflection hit point rp back into primary camera screen space to test SSR visibility! vec3 camToHit = rp - ro; float cz = dot(camToHit, fw); vec2 projUv = vec2(dot(camToHit, ri), dot(camToHit, up)) * (fl / max(cz, 0.05)); float aspect = iResolution.x / max(iResolution.y, 1.0); bool onScreen = (cz > 0.1) && (abs(projUv.x) < 0.48 * aspect) && (abs(projUv.y) < 0.46); // Also test if rp is occluded from the primary camera (e.g., back of pillar or hidden beacon) bool unoccluded = onScreen; if (onScreen) { vec3 camDir = normalize(camToHit); float camDist = length(camToHit); float ocT = 0.08; for (int k = 0; k < 24; k++) { float od = mapGallery(ro + camDir * ocT).x; if (od < 0.008 && ocT < camDist - 0.08) { unoccluded = false; break; } ocT += max(od, 0.06); if (ocT >= camDist - 0.08) break; } } if (useHybridRT) { // Hybrid RT: seamlessly uses world-space ray hit everywhere, even off-screen or occluded! reflCol = trueRefl; } else { // SSR-only: succeeds for visible on-screen objects, but drops out to dull probe fallback off-screen/occluded! float edgeFade = smoothstep(0.49 * aspect, 0.36 * aspect, abs(projUv.x)) * smoothstep(0.47, 0.34, abs(projUv.y)); float ssrConf = (unoccluded ? 1.0 : 0.0) * edgeFade; reflCol = mix(envAmb * 0.8, trueRefl, ssrConf); } } float ndv = max(dot(reflN, -rd), 0.0); float F = (hitId < 1.5) ? (0.18 + 0.78 * pow(1.0 - ndv, 4.0)) : (0.55 + 0.45 * pow(1.0 - ndv, 4.0)); col = mix(col, reflCol, clamp(F * (1.0 - rough * 0.6), 0.0, 0.94)); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Screen-space reflections](https://texelatlas.vercel.app/t/screen-space-reflections.md) ## Combines with - [Visible normal distribution sampling (GGX VNDF)](https://texelatlas.vercel.app/t/vndf-sampling.md): Visible-normal sampling picks the microfacet normal for each reflection ray so rough lobes are sampled efficiently. - [Blue-noise error distribution sampler](https://texelatlas.vercel.app/t/blue-noise-screen-space-sampler.md): Per-pixel ray directions use the sampler so the noise the denoiser sees is high-frequency. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Reprojection and history rejection logic is shared between the reflection denoiser and TAA. ## Sources 1. [primary] Colin Barré-Brisebois, Henrik Halén, Graham Wihlidal, Andrew Lauritzen, Jasper Bekkers, Tomasz Stachowiak, Johan Andersson (2019) Hybrid Rendering for Real-Time Ray Tracing. Ray Tracing Gems. https://doi.org/10.1007/978-1-4842-4427-2_25 (verified via crossref on 2026-11-29) 2. [implementation] NVIDIAGameWorks (2017) NVIDIAGameWorks/Falcor. https://github.com/NVIDIAGameWorks/Falcor License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Hybrid ray-traced reflections." https://texelatlas.vercel.app/t/hybrid-ray-traced-reflections/ (accessed 2026-12-01). --- id: "hydraulic-erosion-stava" title: "Interactive Hydraulic Erosion on Heightfields" aliases: [particle hydraulic erosion, layered hydraulic erosion] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, desktop-gpu, cuda, houdini, unity, unreal, godot, python] year_introduced: 2008 inputs: [heightfield] outputs: [heightfield] style: "photoreal" dynamic: "static" cost: "offline" authority: "Stava et al., 2008" url: "https://texelatlas.vercel.app/t/hydraulic-erosion-stava/" sources_verified_at: "2026-11-29" --- # Interactive Hydraulic Erosion on Heightfields (Stava et al., 2008) > Simulates rainfall, runoff, sediment pickup and deposition on a terrain, with an interactive layered heightfield and a procedural base, to produce branching river valleys and alluvial fans that noise alone cannot. ## Reach for it when - terrain from noise lacks realistic river channels - need physically plausible water erosion on heightfield - erosion that creates deposits and sharp gullies - interactive erosion editing for landscape artists ## How it works Stava and colleagues build on a grid shallow-water model: water height, flux and velocity are stored per cell, rain adds water, and flux moves it downhill. Flow velocity sets a sediment carrying capacity; when carrying less than capacity the water dissolves terrain, when carrying more it deposits. Thermal and talus-like slumping stabilise banks. The paper runs this on a layered representation (bedrock, sediment) so authors can paint rain and source water and see valleys form, then continues the simulation interactively. A widely used simpler cousin is the droplet (particle) method: spawn many water droplets, move each along the gradient with inertia, erode while fast and deposit while slow. Both families need many iterations before channels become visible. ## When to use it Choose it for authoring plausible mountain valleys and deltas where you can afford seconds-to-minutes of simulation and want local control. Prefer [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md) for a fully GPU-resident implementation, [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) when you need continent-scale drainage that is stable and fast, and [Terrain from Hydrology (River-First Terrain Synthesis)](https://texelatlas.vercel.app/t/hydrology-terrain-synthesis.md) when rivers must be designed first and terrain derived from them. ## Cost offline — Many iterations over the entire grid; interactive for moderate resolutions on GPU, minutes to hours for large high-resolution terrains. Measured GPU Weight: 251.29× baseline (extreme) — 8.2673 ms median / 8.3171 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 224.28× baseline (extreme) — 3.5661 ms median (2.32× faster on L4). Ampere A100 scaling: 184.71× baseline (extreme) — 5.3197 ms median (1.55× faster on A100). ## Failure modes - Pits and flat basins accumulate water and create blocky lakes unless filled or drained explicitly - Parameter coupling (capacity, dissolve rate, evaporation) makes results vary wildly; too much dissolve gives canyons with no tributaries - Resolution dependence: channel width tracks cell size, so erosion tuned at 512 cells looks different at 2048 - Grid-aligned gullies and streak artifacts when flow follows axis directions only - Mass leakage at tile borders when erosion is run per-tile without halo exchange ## Dataflow - Inputs: heightfield - Outputs: heightfield - Platforms: cpu, desktop-gpu, cuda, houdini, unity, unreal, godot, python ## Presets ### Hydraulic Erosion — raw fBm heightfield (left) vs carved dendritic gullies & alluvial sediment (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_EROSION": 0.85, "P_SEDIMENT": 0.72, "P_CAM_ORBIT": 0.4, "P_SPLIT": 0.48 } ``` ```glsl const float P_EROSION = 0.85; // P Gully Erosion [0.05, 1.3, 0.04] const float P_SEDIMENT = 0.72; // P Sediment Fan [0.0, 1.2, 0.04] const float P_CAM_ORBIT = 0.40; // P Orbit Speed [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Raw fBm / Eroded [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Value noise returning (value, d/dx, d/dz) analytical gradient for gradient-advected hydraulic erosion vec3 noiseD(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); vec2 du = 6.0 * f * (1.0 - f); float a = hash21(i); float b = hash21(i + vec2(1.0, 0.0)); float c = hash21(i + vec2(0.0, 1.0)); float d = hash21(i + vec2(1.0, 1.0)); float v = a + (b - a) * u.x + (c - a) * u.y + (a - b - c + d) * u.x * u.y; vec2 g = du * vec2((b - a) + (a - b - c + d) * u.y, (c - a) + (a - b - c + d) * u.x); return vec3(v, g); } // Raw un-eroded mountain fBm float rawTerrain(vec2 p) { float h = 0.0, amp = 0.55; vec2 q = p * 0.78; for (int i = 0; i < 4; i++) { h += amp * noiseD(q).x; q = rot2(0.55) * q * 2.02 + vec2(3.7, 1.9); amp *= 0.48; } float peak = exp(-dot(p, p) * 0.42) * 0.85; return h * 0.65 + peak - 0.52; } // Hydraulically eroded heightfield using analytical slope-driven ridge & dendritic gully carving (returns height, sediment) vec2 erodedTerrain(vec2 p, float eroStr, float sedStr) { float h = 0.0, amp = 0.55; vec2 gradAcc = vec2(0.0); float gullyAcc = 0.0; vec2 q = p * 0.78; mat2 m = rot2(0.55); for (int i = 0; i < 5; i++) { vec3 nd = noiseD(q); gradAcc += nd.yz * amp; float slope = length(gradAcc); // Steep slopes erode sharp concave dendritic gullies; flat basins accumulate smooth sediment float ridge = 1.0 - abs(nd.x * 2.0 - 1.0); float carve = (ridge * ridge) / (1.0 + slope * 3.8 * eroStr); h += amp * mix(nd.x, carve, clamp(eroStr * 0.85, 0.0, 1.0)); gullyAcc += amp * (nd.x - carve) * eroStr; q = m * q * 2.04 + vec2(3.7, 1.9) + gradAcc * 0.14 * eroStr; amp *= 0.48; } float r2 = dot(p, p); float peak = exp(-r2 * 0.42) * 0.85; // Alluvial sediment deposition apron around base foothills float sedMask = clamp(smoothstep(0.45, 1.35, r2) * smoothstep(0.65, 0.12, length(gradAcc)) * sedStr + max(gullyAcc * 0.5, 0.0), 0.0, 1.0); float height = h * 0.65 + peak - 0.52 + sedMask * 0.06; return vec2(height, sedMask); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isEroded = screenX >= split; float ero = clamp(P_EROSION, 0.05, 1.4); float sed = clamp(P_SEDIMENT, 0.0, 1.4); float spin = iTime * max(P_CAM_ORBIT, 0.0) * 0.35; vec3 ro = vec3(0.0, 1.25, 2.55); vec3 rd = normalize(vec3(uv.x, uv.y - 0.34, -1.35)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 sky = mix(vec3(0.86, 0.72, 0.58), vec3(0.18, 0.38, 0.68), smoothstep(-0.08, 0.52, rd.y)); vec3 col = sky; float t = 0.2; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; float h = isEroded ? erodedTerrain(p.xz, ero, sed).x : rawTerrain(p.xz); float d = p.y - h; if (d < 0.008) { hit = true; break; } t += max(d * 0.45, 0.025); if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; float e = 0.015; vec2 cVal = isEroded ? erodedTerrain(p.xz, ero, sed) : vec2(rawTerrain(p.xz), 0.0); float hx = isEroded ? erodedTerrain(p.xz + vec2(e, 0.0), ero, sed).x : rawTerrain(p.xz + vec2(e, 0.0)); float hz = isEroded ? erodedTerrain(p.xz + vec2(0.0, e), ero, sed).x : rawTerrain(p.xz + vec2(0.0, e)); vec3 n = normalize(vec3((cVal.x - hx) / e, 1.0, (cVal.x - hz) / e)); vec3 sunDir = normalize(vec3(0.68, 0.56, 0.46)); float diff = max(dot(n, sunDir), 0.0); float slope = 1.0 - n.y; // Geologic strata: dark granite rock on steep eroded cliffs, ochre alluvial sediment in gullies/fans, snow peaks vec3 rock = mix(vec3(0.28, 0.26, 0.25), vec3(0.48, 0.44, 0.40), smoothstep(0.15, 0.55, slope)); vec3 grass = vec3(0.22, 0.40, 0.20); vec3 sedimentCol = vec3(0.76, 0.56, 0.34); vec3 snow = vec3(0.92, 0.94, 0.98); vec3 alb = mix(grass, rock, smoothstep(0.14, 0.38, slope)); if (isEroded) { alb = mix(alb, sedimentCol, clamp(cVal.y * 0.85, 0.0, 0.85)); } alb = mix(alb, snow, smoothstep(0.44, 0.66, cVal.x) * smoothstep(0.45, 0.16, slope)); vec3 lit = alb * (0.24 + 0.92 * diff) + vec3(0.20, 0.34, 0.56) * 0.20 * (0.5 + 0.5 * n.y); col = mix(lit, sky, 1.0 - exp(-t * 0.075)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md) ## Combines with - [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md): The noise heightfield is the initial terrain that erosion refines. ## Combination ideas - [Forests that grow into the gaps](https://texelatlas.vercel.app/ideas/eroded-biome-forests/) ## Sources 1. [primary] Ondrej Stava, Bedrich Benes, Matthew Brisbin, Jaroslav Krivanek (2008) Interactive Terrain Modeling Using Hydraulic Erosion. Eurographics/SIGGRAPH Symposium on Computer Animation. https://doi.org/10.2312/sca/sca08/201-210 (verified via doi.org on 2026-11-29) 2. [implementation] SebLague (2019) SebLague/Hydraulic-Erosion. https://github.com/SebLague/Hydraulic-Erosion License: MIT. (verified via github on 2026-11-29) 3. [implementation] dandrino (2018) dandrino/terrain-erosion-3-ways. https://github.com/dandrino/terrain-erosion-3-ways License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Interactive Hydraulic Erosion on Heightfields." https://texelatlas.vercel.app/t/hydraulic-erosion-stava/ (accessed 2026-12-01). --- id: "hydrology-terrain-synthesis" title: "Terrain from Hydrology (River-First Terrain Synthesis)" aliases: [procedural terrain from river networks] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, desktop-gpu, python, houdini] year_introduced: 2013 inputs: [graph] outputs: [heightfield] style: "photoreal" dynamic: "static" cost: "medium" authority: "Génevaux et al., 2013" url: "https://texelatlas.vercel.app/t/hydrology-terrain-synthesis/" sources_verified_at: "2026-11-29" --- # Terrain from Hydrology (River-First Terrain Synthesis) (Génevaux et al., 2013) > Build a river network first as a tree with drainage-area-based constraints, then synthesise a heightfield that is consistent with it by interpolating around the rivers and adding noise detail. ## Reach for it when - need to place rivers exactly where i want them - terrain should be consistent with a designed watershed - erosion simulation takes too long for map design - game map needs believable drainage and valleys ## How it works The user (or a generator) provides a coarse drainage structure: river segments, branching topology and a few elevation constraints. The algorithm expands this into a full tree where each segment's flow grows downstream, and elevations are assigned so rivers always flow downhill. Terrain between rivers is built by interpolating from the river elevations upward with a profile that depends on distance to the nearest channel and on drainage area, then adding procedural noise as detail. Since rivers are an input rather than an outcome of simulation, results are controllable and fast to compute, and the river layout is guaranteed to be hydrologically plausible. Landscape features like valley width and ridgelines follow from the tree. ## When to use it Choose it when you need to control where rivers and watersheds go (game maps, scenic composition) and want terrain consistent with them without running a long erosion simulation. Prefer [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) when you want the river network to emerge from uplift rather than be drawn, and [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) for fine erosion detail on top. ## Cost medium — Graph construction plus an interpolation pass over the grid; far cheaper than iterating full erosion. Measured GPU Weight: 40.86× baseline (heavy) — 1.3444 ms median / 1.4474 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 34.88× baseline (heavy) — 0.5546 ms median (2.42× faster on L4). Ampere A100 scaling: 27.2× baseline (heavy) — 0.7834 ms median (1.72× faster on A100). ## Failure modes - Terrain between rivers is generic noise-modulated interpolation, lacking tributary gullies unless a post-erosion pass is added - Constraints that force uphill flow need explicit repair or the tree rejects them - Large drainage-area contrast gives unrealistically wide valleys for small rivers - River sketches without enough branching produce flat, featureless basins ## Dataflow - Inputs: graph - Outputs: heightfield - Platforms: cpu, desktop-gpu, python, houdini ## Presets ### Hydrology Terrain Synthesis — Strahler river-tree & watershed map (left) vs uplifted alpine valleys (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_UPLIFT": 0.92, "P_RIVER_WIDTH": 0.85, "P_CAM_SWAY": 0.42, "P_SPLIT": 0.46 } ``` ```glsl const float P_UPLIFT = 0.92; // P Ridge Uplift [0.3, 1.5, 0.04] const float P_RIVER_WIDTH = 0.85; // P River Network [0.3, 1.5, 0.04] const float P_CAM_SWAY = 0.42; // P Camera Sway [0.0, 2.0, 0.05] const float P_SPLIT = 0.46; // P River Tree / 3D [0.0, 1.0, 0.02] float sdSeg(vec2 p, vec2 a, vec2 b, out float h) { vec2 pa = p - a, ba = b - a; h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } // River-first hierarchical dendritic drainage tree (Genevaux et al. 2013): // Returns vec3(distToNearestRiver, riverElevation, strahlerOrder) vec3 evalRiverTree(vec2 p) { // Subtle natural meander warp vec2 q = p + vec2(0.12 * sin(p.y * 2.2), 0.08 * cos(p.x * 2.4)); float h0, h1, h2, h3, h4; // Order-3 main trunk river flowing from (0, -1.6) to (0, 1.8) float dMain = sdSeg(q, vec2(0.0, -1.6), vec2(0.0, 1.8), h0); float zMain = mix(0.22, -0.30, h0); // Order-2 primary tributaries branching left and right float dT1 = sdSeg(q, vec2(-1.45, -1.15), vec2(0.0, -0.25), h1); float zT1 = mix(0.46, -0.02, h1); float dT2 = sdSeg(q, vec2(1.45, -0.85), vec2(0.0, 0.15), h2); float zT2 = mix(0.44, -0.08, h2); // Order-1 headwater streams feeding tributaries float dH1 = sdSeg(q, vec2(-1.35, 0.35), vec2(-0.62, -0.62), h3); float zH1 = mix(0.56, 0.20, h3); float dH2 = sdSeg(q, vec2(1.25, 0.72), vec2(0.68, -0.32), h4); float zH2 = mix(0.54, 0.16, h4); // Pick closest drainage segment & its Strahler order float d = dMain; float zR = zMain; float ord = 3.0; if (dT1 < d) { d = dT1; zR = zT1; ord = 2.0; } if (dT2 < d) { d = dT2; zR = zT2; ord = 2.0; } if (dH1 < d) { d = dH1; zR = zH1; ord = 1.0; } if (dH2 < d) { d = dH2; zR = zH2; ord = 1.0; } return vec3(d, zR, ord); } // Uplift watershed ridges proportionally to distance from the river network! float evalHydroTerrain(vec2 xz, float uplift) { vec3 rt = evalRiverTree(xz); // Concave valley cross-section rising to sharp alpine watershed divides between rivers float ridge = pow(clamp(rt.x * 0.95, 0.0, 1.4), 1.15) * 0.68 * uplift; float detail = 0.08 * sin(xz.x * 5.2 + cos(xz.y * 4.7)) + 0.035 * cos(xz.x * 11.0 - xz.y * 9.5); return rt.y + ridge + detail * smoothstep(0.05, 0.35, rt.x); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isMap = screenX < split; float uplift = clamp(P_UPLIFT, 0.25, 1.6); float rw = clamp(P_RIVER_WIDTH, 0.25, 1.6); float sway = sin(iTime * 0.45 * max(P_CAM_SWAY, 0.0)) * 0.35; vec3 ro = vec3(sway, 1.45, 2.55); vec3 rd = normalize(vec3(uv.x - sway * 0.12, uv.y - 0.42, -1.32)); vec3 sky = mix(vec3(0.84, 0.88, 0.94), vec3(0.18, 0.42, 0.76), smoothstep(-0.08, 0.52, rd.y)); vec3 col = sky; float t = 0.2; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; float h = evalHydroTerrain(p.xz, uplift); float d = p.y - h; if (d < 0.008) { hit = true; break; } t += max(d * 0.45, 0.025); if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; float e = 0.016; float hC = evalHydroTerrain(p.xz, uplift); float hX = evalHydroTerrain(p.xz + vec2(e, 0.0), uplift); float hZ = evalHydroTerrain(p.xz + vec2(0.0, e), uplift); vec3 n = normalize(vec3((hC - hX) / e, 1.0, (hC - hZ) / e)); vec3 rt = evalRiverTree(p.xz); float riverW = (0.028 + 0.024 * rt.z) * rw; float inRiver = smoothstep(riverW * 1.4, riverW * 0.5, rt.x); vec3 sunDir = normalize(vec3(0.62, 0.68, 0.45)); float diff = max(dot(n, sunDir), 0.0); if (isMap) { // Left: Topographic watershed map showing Strahler river tree orders & elevation iso-contours! float contour = smoothstep(0.06, 0.012, abs(fract(hC * 8.0) - 0.5)); vec3 topo = mix(vec3(0.07, 0.14, 0.22), vec3(0.28, 0.52, 0.36), smoothstep(-0.25, 0.35, hC)); topo = mix(topo, vec3(0.86, 0.72, 0.42), smoothstep(0.35, 0.85, hC)); topo = mix(topo, vec3(0.95, 0.96, 1.0), contour * 0.38); // Color river branches by Strahler order (1 = mint, 2 = cyan, 3 = bright sky-blue trunk) vec3 ordCol = (rt.z > 2.5) ? vec3(0.16, 0.88, 1.0) : (rt.z > 1.5 ? vec3(0.20, 0.96, 0.72) : vec3(0.98, 0.84, 0.26)); col = mix(topo * (0.45 + 0.65 * diff), ordCol * 1.35, inRiver); } else { // Right: Full 3D alpine valley landscape synthesized from the hydrology tree float slope = 1.0 - n.y; vec3 forest = vec3(0.14, 0.36, 0.18); vec3 rock = vec3(0.42, 0.40, 0.38); vec3 snow = vec3(0.92, 0.95, 0.98); vec3 alb = mix(forest, rock, smoothstep(0.16, 0.42, slope)); alb = mix(alb, snow, smoothstep(0.38, 0.68, hC) * smoothstep(0.48, 0.18, slope)); vec3 riverCol = vec3(0.08, 0.52, 0.72); alb = mix(alb, riverCol, inRiver); float spec = pow(max(dot(n, normalize(sunDir - rd)), 0.0), 40.0) * inRiver; col = alb * (0.24 + 0.88 * diff) + vec3(0.95, 0.98, 1.0) * spec * 0.85; } col = mix(col, sky, 1.0 - exp(-t * 0.07)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) ## Combines with - [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md): The river-consistent heightfield gets small-scale gullies and deposits from a short erosion pass. ## Sources 1. [primary] Jean-David Génevaux, Éric Galin, Eric Guérin, Adrien Peytavie, Bedrich Benes (2013) Terrain generation using procedural models based on hydrology. ACM Transactions on Graphics. https://doi.org/10.1145/2461912.2461996 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Terrain from Hydrology (River-First Terrain Synthesis)." https://texelatlas.vercel.app/t/hydrology-terrain-synthesis/ (accessed 2026-12-01). --- id: "icp-registration" title: "Iterative Closest Point (ICP) registration" aliases: [ICP, iterative closest point] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cpu, cuda, python] year_introduced: 1992 inputs: [point-cloud] outputs: [camera-poses, point-cloud] style: "photoreal" dynamic: "static" cost: "offline" authority: "Besl & McKay, 1992" url: "https://texelatlas.vercel.app/t/icp-registration/" sources_verified_at: "2026-11-29" --- # Iterative Closest Point (ICP) registration (Besl & McKay, 1992) > Aligns two overlapping 3D scans by alternating nearest-neighbour matching and a closed-form rigid transform fit until the residual stops improving. ## Reach for it when - two scans do not line up in one coordinate frame - align a depth scan to a reference model - need to stitch overlapping lidar or scanner captures - refine camera pose against a point cloud ## How it works Start with an initial guess of the rigid transform between a source and a target cloud. Each iteration: transform the source, find for every point its closest point on the target, optionally reject bad pairs by distance, normal angle or rank, then solve the best rotation and translation that minimises the squared distance between pairs, using an SVD of the cross-covariance or a quaternion eigenproblem. Apply it and repeat until the update is below a tolerance. The point-to-plane variant minimises distance along target normals and converges much faster on smooth surfaces. Generalised ICP weighs by local covariances, and colour or feature terms can be added. Nearest-neighbour queries run on a k-d tree or a voxel hash, which is the real cost. It converges only to a local minimum, so a coarse global alignment is needed first. ## When to use it Choose it to refine the alignment of range scans, depth frames or point clouds that already roughly overlap, and in SLAM or scan-stitching pipelines. Prefer [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md) when you only have photos and need poses, [DUSt3R](https://texelatlas.vercel.app/t/dust3r.md) for learned feature-free pose and geometry from image pairs, and global registration (feature matching with RANSAC) to initialise ICP when the starting pose is far off. ## Cost offline — Each iteration is dominated by nearest-neighbour search; real-time is feasible with GPU or small clouds, typically dozens of iterations. Measured GPU Weight: 45.34× baseline (heavy) — 1.4917 ms median / 1.5431 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 43.01× baseline (heavy) — 0.6839 ms median (2.18× faster on L4). Ampere A100 scaling: 32.43× baseline (heavy) — 0.9339 ms median (1.6× faster on A100). ## Failure modes - Converges to a wrong local minimum if the initial pose is far off - Flat or symmetric geometry such as corridors and planes leaves sliding degrees of freedom unconstrained - Outliers and non-overlapping regions bias the fit unless pairs are rejected or the overlap is trimmed - Different sampling density or noise between scans causes systematic bias in point-to-point matching ## Dataflow - Inputs: point-cloud - Outputs: camera-poses, point-cloud - Platforms: cpu, cuda, python ## Presets ### ICP Registration — misaligned scans & correspondences (left) vs converged rigid SVD alignment (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ITER_PROG": 0.88, "P_INIT_ERR": 0.75, "P_CORR_VIS": 0.95, "P_SPLIT": 0.48 } ``` ```glsl const float P_ITER_PROG = 0.88; // P ICP Convergence [0.0, 1.0, 0.02] const float P_INIT_ERR = 0.75; // P Initial Pose Err [0.1, 1.2, 0.04] const float P_CORR_VIS = 0.95; // P Match Lines [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Unaligned / Aligned [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdSeg(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } // Target 2D/3D-projected curved LiDAR scan profile (24 scanned surface points) vec2 targetPt(int idx) { float u = (float(idx) / 23.0) * 2.0 - 1.0; float ang = u * 2.25; float r = 0.27 + 0.075 * sin(ang * 3.0) + 0.045 * cos(ang * 5.0); return vec2(cos(ang) * r, sin(ang) * r); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isRight = screenX >= split; float prog = clamp(P_ITER_PROG, 0.0, 1.0); float initErr = clamp(P_INIT_ERR, 0.05, 1.4); float corrVis = clamp(P_CORR_VIS, 0.0, 1.5); // Engineering coordinate backdrop vec3 col = mix(vec3(0.022, 0.030, 0.050), vec3(0.052, 0.068, 0.108), smoothstep(-0.55, 0.55, uv.y)); vec2 g = abs(fract(uv * 8.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.044) * smoothstep(0.035, 0.008, min(g.x, g.y)); // Periodic ICP iteration sweep on right side; initial unaligned pose on left side float iterCycle = 0.5 + 0.5 * sin(iTime * 0.9 - 1.2); float conv = isRight ? clamp(prog * (0.45 + 0.55 * iterCycle), 0.0, 1.0) : 0.08; float remErr = (1.0 - conv) * initErr; float rotErr = 0.58 * remErr; vec2 transErr = vec2(0.16, -0.11) * remErr; vec2 center = isRight ? vec2(0.32, 0.0) : vec2(-0.32, 0.0); vec2 p = uv - center; // Draw 24 target points (cyan), source points (amber), and closest-point correspondence vectors for (int i = 0; i < 24; i++) { vec2 qt = targetPt(i); // Rigidly misaligned source scan + slight sensor noise vec2 qs = rot2(rotErr) * qt + transErr + vec2(0.006 * sin(float(i) * 4.3), 0.006 * cos(float(i) * 3.1)); // Closest-point correspondence line from source point to target point float dLine = sdSeg(p, qs, qt); float lineMask = smoothstep(0.0045, 0.0012, dLine); float errLen = clamp(length(qs - qt) * 3.5, 0.0, 1.0); vec3 lineCol = mix(vec3(0.24, 0.95, 0.58), vec3(0.98, 0.34, 0.28), errLen); col += lineCol * lineMask * 0.65 * corrVis; // Target scan point (cyan) float dT = length(p - qt); col = mix(col, vec3(0.14, 0.84, 0.98), smoothstep(0.014, 0.006, dT)); col += vec3(0.14, 0.84, 0.98) * exp(-dT * 42.0) * 0.25; // Source scan point (warm amber) float dS = length(p - qs); col = mix(col, vec3(0.98, 0.58, 0.16), smoothstep(0.013, 0.005, dS)); col += vec3(0.98, 0.58, 0.16) * exp(-dS * 42.0) * 0.25; } // Residual RMSE convergence ring around centroid float rmseR = 0.04 + 0.18 * remErr; float ring = exp(-abs(length(p) - rmseR) * 48.0); col += mix(vec3(0.22, 0.96, 0.58), vec3(0.98, 0.36, 0.24), remErr) * ring * 0.55; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/poisson-surface-reconstruction.md): After ICP aligns scans into one cloud with normals, Poisson reconstruction fuses it into a watertight mesh. - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): SfM gives a global, feature-based pose that ICP then refines against depth or lidar scans. ## Sources 1. [primary] P.J. Besl, Neil D. McKay (1992) A method for registration of 3-D shapes. IEEE Transactions on Pattern Analysis and Machine Intelligence. https://doi.org/10.1109/34.121791 (verified via crossref on 2026-11-29) 2. [secondary] Yang Chen, Gérard Medioni (1992) Object modelling by registration of multiple range images. Image and Vision Computing. https://doi.org/10.1016/0262-8856(92)90066-c (verified via crossref on 2026-11-29) 3. [secondary] S. Rusinkiewicz, M. Levoy Efficient variants of the ICP algorithm. Proceedings Third International Conference on 3-D Digital Imaging and Modeling. https://doi.org/10.1109/im.2001.924423 (verified via crossref on 2026-11-29) 4. [implementation] isl-org (2016) isl-org/Open3D. https://github.com/isl-org/Open3D License: NOASSERTION. (verified via github on 2026-11-29) 5. [implementation] PointCloudLibrary (2013) PointCloudLibrary/pcl. https://github.com/PointCloudLibrary/pcl License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Iterative Closest Point (ICP) registration." https://texelatlas.vercel.app/t/icp-registration/ (accessed 2026-12-01). --- id: "ihmsen-unified-whitewater" title: "Ihmsen Unified Spray, Foam, and Bubble Whitewater Simulation" aliases: [unified whitewater, diffuse fluid particles, secondary spray foam bubble simulation] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu, houdini, blender] year_introduced: 2012 inputs: [particles, voxels] outputs: [particles] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Ihmsen et al., 2012" url: "https://texelatlas.vercel.app/t/ihmsen-unified-whitewater/" sources_verified_at: "2026-11-30" --- # Ihmsen Unified Spray, Foam, and Bubble Whitewater Simulation (Ihmsen et al., 2012) > Generate and advect secondary spray, surface foam, and submerged air-bubble particles from a single one-way-coupled particle pool driven by primary fluid turbulence, wave crests, and local fluid density. ## Reach for it when - particle fluid simulation lacks convincing spray foam and underwater bubbles - need physically driven whitewater emission from breaking waves and splashes - spawn secondary foam particles automatically where fluid air gets trapped - transition whitewater smoothly between ballistic spray surface foam and bubbles - make real-time sph or pbf water splashes look turbulent and aerated ## How it works Primary liquid solvers such as [sph-fluids](sph-fluids) and [flip-pic-fluids](flip-pic-fluids) resolve bulk water motion but lack the resolution to directly capture fine droplets, bubbly wakes, and lingering frothy sheets. Ihmsen's unified model runs a lightweight secondary particle pool coupled one-way to the liquid. Each step, emission potential is evaluated at primary fluid particles (or sampled fluid cells) by combining three physical cues: **trapped air** from velocity differences with nearby fluid (or FLIP/PIC disagreement and impact impulses), **wave crests** where surface curvature and outward motion peak, and **kinetic energy** so calm water emits nothing. High-potential regions spawn diffuse particles into free pool slots. All diffuse particles share one state representation and are dynamically classified every step solely by the surrounding primary fluid density (or neighbor count): particles in low-density air act as **spray** flying ballistically under gravity and drag; particles at the free surface act as **foam** advected passively by the underlying fluid velocity while gradually decaying; and particles surrounded by dense liquid act as **air bubbles** experiencing upward buoyancy plus drag toward the local water velocity. Because classification is continuous and stateless, plunging spray seamlessly turns into submerged bubbles that rise back into surface foam. ## When to use it Choose it whenever particle-based waterfalls, splashes, ocean breakers, or water spells need believable aerated detail without shrinking the primary fluid particle spacing. Prefer [flow-map-water](flow-map-water) or [fft-ocean](fft-ocean) with Jacobian foam masks when rendering large open water surfaces that do not use 3D fluid particles. Prefer [soft-particles](soft-particles) for hand-placed mist or waterfall billboard sheets when no physical fluid solver is present. ## Cost medium — One-way coupling avoids expensive inter-particle pressure solves; cost scales linearly with secondary particle count and grid/neighbor density lookups, fitting easily into GPU compute or fragment passes. ## Failure modes - One-way coupling means dense foam mats cannot dampen surface waves or exert buoyancy back onto the liquid - Poorly tuned trapped-air or kinetic-energy thresholds either flood calm pools with snow-like foam or starve energetic splashes - Coarse primary fluid grids cause foam particles to float slightly above or sink below the reconstructed liquid surface - Dense overlapping whitewater sprites cause heavy overdraw and sorting pops unless rendered with order-independent blending ## Dataflow - Inputs: particles, voxels - Outputs: particles - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu, houdini, blender ## Lineage - extends [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) ## Combines with - [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md): Primary FLIP particle velocity, trapped-air aeration, and grid density fields seed, classify, and advect the secondary whitewater pool. - [Screen-space fluid rendering (curvature flow)](https://texelatlas.vercel.app/t/screen-space-fluid-rendering.md): Spray, foam, and bubbles layer over the smoothed liquid depth surface to add turbulent visual breakup and splash detail. - [Weighted blended order-independent transparency](https://texelatlas.vercel.app/t/weighted-blended-oit.md): Order-independent compositing renders tens of thousands of translucent foam and spray sprites without per-frame depth sorting. ## Combination ideas - [Narrow-range SSF liquid with whitewater and wet-ground reaction field](https://texelatlas.vercel.app/ideas/narrow-range-ssf-whitewater-ground-field/) ## Sources 1. [primary] Markus Ihmsen, Nadir Akinci, Gizem Akinci, Matthias Teschner (2012) Unified spray, foam and air bubbles for particle-based fluids. The Visual Computer. https://doi.org/10.1007/s00371-012-0697-9 (verified via crossref on 2026-11-30) 2. [implementation] Humpalumps (2026) Humpalumps/ultra-elements. https://github.com/Humpalumps/ultra-elements License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Ihmsen Unified Spray, Foam, and Bubble Whitewater Simulation." https://texelatlas.vercel.app/t/ihmsen-unified-whitewater/ (accessed 2026-12-01). --- id: "image-quilting" title: "Image quilting" domain: "materials" stage: "material" realtime: "offline" platforms: [cpu, python] year_introduced: 2001 inputs: [texture] outputs: [texture] style: "both" dynamic: "static" cost: "offline" authority: "Efros & Freeman, 2001" url: "https://texelatlas.vercel.app/t/image-quilting/" sources_verified_at: "2026-11-29" --- # Image quilting (Efros & Freeman, 2001) > Synthesises a larger texture from a small exemplar by stitching overlapping patches along minimum-error seams. Preserves structure such as bricks and strokes that pixel-based synthesis blurs. ## Reach for it when - need a large texture from a tiny sample - tiled textures show obvious repetition - brick or stone patterns blur when synthesised pixel by pixel - stitch patches into seamless structured texture - transfer texture style onto another image ## How it works Efros and Freeman tile the output in raster order with square blocks taken from the exemplar. For each new block, candidates are scored by how well their overlap region matches the already-placed neighbours (sum of squared differences), and one is picked at random from those within a tolerance of the best, which adds variety. The overlap is not blended; instead a minimum-cost path through the overlap error surface, found by dynamic programming, chooses the cut that hides the seam along pixels already similar. A variant adds a correspondence map for texture transfer: blocks must also match a target image's luminance, so a photograph is re-rendered in the texture's style. Block size controls the scale of structure that survives; larger blocks reduce visible repetition less. ## When to use it Choose it for offline generation of large, structured, seamless textures (brick, stone walls, foliage) from a single scan, or for texture transfer stylisation. Prefer [Histogram-preserving blending (stochastic texturing)](https://texelatlas.vercel.app/t/histogram-preserving-blending.md) or [Hex-tiling](https://texelatlas.vercel.app/t/hex-tiling.md) for real-time, runtime anti-tiling of stochastic textures. Prefer procedural noise ([Procedural noise for texturing](https://texelatlas.vercel.app/t/procedural-noise-texturing.md)) when no exemplar exists. ## Cost offline — Seconds to minutes per output image on a CPU; not intended for per-frame use. Measured GPU Weight: 104.55× baseline (extreme) — 3.4397 ms median / 3.5559 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 90.99× baseline (extreme) — 1.4467 ms median (2.38× faster on L4). Ampere A100 scaling: 62.03× baseline (extreme) — 1.7864 ms median (1.93× faster on A100). ## Failure modes - Verbatim copying of recognisable chunks reveals the exemplar as visible repetition - Fails on globally structured or semantic textures (faces, text, long straight lines crossing blocks) - Block size trade-off: too small loses structure, too large repeats - Seam cuts can leave staircase artefacts on smooth gradients ## Dataflow - Inputs: texture - Outputs: texture - Platforms: cpu, python ## Presets ### Image quilting — straight patch seams vs minimum-error boundary-cut synthesis (glsl-fragment; rendered 2026-11-30) ```json { "P_PATCH_SCALE": 3.6, "P_CUT_WIGGLE": 1, "P_SEAM_VIS": 0.65, "P_SPLIT": 0.38 } ``` ```glsl const float P_PATCH_SCALE = 3.6; // P Patch Grid [2.0, 7.0, 0.2] const float P_CUT_WIGGLE = 1.0; // P Min-Error Cut [0.0, 1.8, 0.05] const float P_SEAM_VIS = 0.65; // P Seam Highlight [0.0, 1.5, 0.05] const float P_SPLIT = 0.38; // P Naive/Quilt Split [0.0, 1.0, 0.02] vec2 hash22(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); } // Rich procedural cobblestone & terracotta mosaic exemplar texture (returns vec4(color, mortarMask)) vec4 sampleExemplar(vec2 p) { vec2 n = floor(p); vec2 f = fract(p); float d1 = 8.0, d2 = 8.0; vec2 bestId = vec2(0.0); vec2 bestR = vec2(0.0); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 g = vec2(float(i), float(j)); vec2 o = 0.16 + 0.68 * hash22(n + g); vec2 r = g + o - f; float d = dot(r, r); if (d < d1) { d2 = d1; d1 = d; bestId = n + g; bestR = r; } else if (d < d2) { d2 = d; } } } float edge = sqrt(d2) - sqrt(d1); vec2 h = hash22(bestId * 1.7 + 3.1); // Warm Mediterranean limestone, slate & terracotta stone palette vec3 stoneA = vec3(0.68, 0.56, 0.44); vec3 stoneB = vec3(0.46, 0.49, 0.54); vec3 stoneC = vec3(0.76, 0.41, 0.28); vec3 baseCol = mix(stoneA, stoneB, h.x); baseCol = mix(baseCol, stoneC, smoothstep(0.68, 0.92, h.y)); // Stone micro-grain + directional bevel lighting float grain = 0.88 + 0.24 * sin(p.x * 19.0 + h.x * 6.0) * cos(p.y * 17.0 - h.y * 6.0); float bevel = smoothstep(0.04, 0.22, edge); float tilt = clamp(0.65 + 0.55 * dot(normalize(bestR + 1e-4), normalize(vec2(-0.6, 0.8))), 0.25, 1.35); vec3 stoneCol = baseCol * grain * tilt * (0.62 + 0.42 * bevel); // Dark sandy mortar groove float mortar = smoothstep(0.11, 0.045, edge); vec3 mortarCol = vec3(0.14, 0.13, 0.12) * (0.85 + 0.3 * sin(p.x * 45.0) * cos(p.y * 45.0)); vec3 col = mix(stoneCol, mortarCol, mortar); return vec4(col, mortar); } // Compute minimum-error cut energy between two overlapping patches A and B float overlapError(vec2 uvA, vec2 uvB) { vec4 a = sampleExemplar(uvA); vec4 b = sampleExemplar(uvB); vec3 d = a.rgb - b.rgb; // Strongly prefer cuts passing through low-contrast mortar valleys float valleyBonus = 1.0 - 0.55 * max(a.a, b.a); return (dot(d, d) + 0.04) * valleyBonus; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; float patchScale = clamp(P_PATCH_SCALE, 1.8, 8.0); float cutWig = clamp(P_CUT_WIGGLE, 0.0, 2.0); float seamVis = clamp(P_SEAM_VIS, 0.0, 1.8); float splitX = clamp(P_SPLIT, 0.0, 1.0); vec2 pan = vec2(iTime * 0.16, iTime * 0.09); vec2 gp = uv * patchScale + pan; vec2 cell = floor(gp); vec2 f = fract(gp); float texFreq = 3.2; // Each synthesized patch selects a random exemplar offset vec2 offC = hash22(cell) * 14.0; vec2 offR = hash22(cell + vec2(1.0, 0.0)) * 14.0; vec2 offU = hash22(cell + vec2(0.0, 1.0)) * 14.0; vec2 offUR = hash22(cell + vec2(1.0, 1.0)) * 14.0; vec2 pC = gp * texFreq + offC; vec2 pR = gp * texFreq + offR; vec2 pU = gp * texFreq + offU; vec2 pUR = gp * texFreq + offUR; vec3 col; float seamGlow = 0.0; if (screenUV.x < splitX) { // Left side: naive unquilted square patch tiling with abrupt visible seams col = sampleExemplar(pC).rgb; float edge = min(min(f.x, 1.0 - f.x), min(f.y, 1.0 - f.y)); seamGlow = smoothstep(0.032, 0.005, edge) * seamVis; col = mix(col, vec3(1.0, 0.32, 0.22), seamGlow * 0.78); } else { // Right side: Efros-Freeman minimum-error boundary cut across 28% overlap strips // Sample error energy across horizontal & vertical overlap bands to find lowest-error cut position float bestX = 0.84; float minEX = 1e6; float bestY = 0.84; float minEY = 1e6; for (int k = 0; k < 5; k++) { float s = 0.72 + float(k) * 0.065; // Add subtle smooth path continuity along perpendicular axis vec2 probeX = vec2(cell.x + s, gp.y) * texFreq; float ex = overlapError(probeX + offC, probeX + offR); if (ex < minEX) { minEX = ex; bestX = s; } vec2 probeY = vec2(gp.x, cell.y + s) * texFreq; float ey = overlapError(probeY + offC, probeY + offU); if (ey < minEY) { minEY = ey; bestY = s; } } // Smooth organic boundary curve modulated by P_CUT_WIGGLE float cutX = mix(0.85, bestX + 0.045 * sin(gp.y * 9.0 + cell.x * 2.3), clamp(cutWig, 0.0, 1.5)); float cutY = mix(0.85, bestY + 0.045 * cos(gp.x * 9.0 + cell.y * 2.7), clamp(cutWig, 0.0, 1.5)); float wx = smoothstep(cutX - 0.025, cutX + 0.025, f.x); float wy = smoothstep(cutY - 0.025, cutY + 0.025, f.y); vec3 c00 = sampleExemplar(pC).rgb; vec3 c10 = sampleExemplar(pR).rgb; vec3 c01 = sampleExemplar(pU).rgb; vec3 c11 = sampleExemplar(pUR).rgb; col = mix(mix(c00, c10, wx), mix(c01, c11, wx), wy); // Highlight the jagged minimum-error cut path in glowing turquoise-gold float dCutX = abs(f.x - cutX); float dCutY = abs(f.y - cutY); seamGlow = max(smoothstep(0.028, 0.004, dCutX), smoothstep(0.028, 0.004, dCutY)) * seamVis; col = mix(col, vec3(0.28, 0.96, 0.88), seamGlow * 0.72); } if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(1.0, 0.86, 0.42); } fragColor = vec4(pow(clamp(aces(col * 1.15), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combination ideas - [One phone photo, a whole floor](https://texelatlas.vercel.app/ideas/one-photo-endless-material/) ## Sources 1. [primary] Alexei A. Efros, William T. Freeman (2001) Image quilting for texture synthesis and transfer. Proceedings of the 28th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/383259.383296 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Image quilting." https://texelatlas.vercel.app/t/image-quilting/ (accessed 2026-12-01). --- id: "implicit-cloth-integration" title: "Implicit cloth integration (Baraff-Witkin)" aliases: [Large steps in cloth simulation] domain: "simulation" stage: "simulation" realtime: "interactive" platforms: [cpu, cuda, desktop-gpu] year_introduced: 1998 inputs: [mesh] outputs: [mesh] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Baraff & Witkin, 1998" url: "https://texelatlas.vercel.app/t/implicit-cloth-integration/" sources_verified_at: "2026-11-29" --- # Implicit cloth integration (Baraff-Witkin) (Baraff & Witkin, 1998) > Cloth simulation with implicit Euler on a triangle mesh with stretch/shear/bend energies, solved by modified conjugate gradient so large time steps stay stable. ## Reach for it when - cloth simulation explodes with large time steps - stiff fabric needs stable integration - garment simulation jitters or blows up at low frame rates - want realistic cloth that stretches and bends properly ## How it works Cloth is a triangle mesh whose internal forces come from condition functions (stretch and shear in the UV plane, bend across edges). Rather than integrate explicitly, the method uses implicit Euler and linearises forces, so each step solves a sparse system `(M - dt df/dv - dt^2 df/dx) dv = dt (f0 + dt df/dx v0)`. The authors solve it with a conjugate gradient variant that enforces per-vertex constraints (pins, contact planes) through a filtering step. Damping forces are included in the Jacobian. Collision is handled with penalty or constraint-filtered response. The result: stable, relatively stiff cloth at time steps of the order of a frame. ## When to use it Choose it when you want physically grounded stiff cloth on CPU with large steps, e.g. offline garments. Prefer [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) / [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) for game-style cloth, [Vertex Block Descent](https://texelatlas.vercel.app/t/vertex-block-descent.md) for fast stiff cloth on GPUs, and [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md) for flags and capes where accuracy does not matter. ## Cost heavy — A sparse linear solve per step; cost grows with mesh size and stiffness. Not frame-budget friendly at film resolution. Measured GPU Weight: 26.31× baseline (heavy) — 0.826 ms median / 0.8981 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 24.37× baseline (heavy) — 0.385 ms median (2.15× faster on L4). Ampere A100 scaling: 17.11× baseline (moderate) — 0.4927 ms median (1.68× faster on A100). ## Failure modes - Implicit Euler adds numerical damping: cloth looks heavy and loses wrinkles - CG solves with few iterations give rubbery or uneven stretch - Collision handling is the weak part: cloth interpenetrates or locks - Tuning stretch vs bend stiffness ratios is unintuitive ## Engine support - blender: builtin — `Physics Properties > Cloth uses an implicit mass-spring Baraff-Witkin integrator in source/blender/blenkernel/intern/cloth.cc` (evidence: https://github.com/blender/blender/blob/main/source/blender/blenkernel/intern/cloth.cc, checked 2026-12-01) - unreal: builtin — `Chaos Cloth Simulation provides interactive implicit/XPBD garment solvers on Skeletal Meshes` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/cloth-simulation-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, cuda, desktop-gpu ## Presets ### Implicit cloth integration (Baraff-Witkin) — 3D billowing woven drape over collider & stretch/shear stress map (glsl-fragment; rendered 2026-11-30) ```json { "P_WIND_FORCE": 1, "P_BEND_STIFF": 0.65, "P_STRESS_SPLIT": 0.38, "P_DRAPE_SPEED": 1 } ``` ```glsl const float P_WIND_FORCE = 1.0; // P Wind Force [0.1, 2.2, 0.05] const float P_BEND_STIFF = 0.65; // P Bend Stiffness [0.15, 1.4, 0.04] const float P_STRESS_SPLIT = 0.38; // P Stress Map Split [0.0, 1.0, 0.02] const float P_DRAPE_SPEED = 1.0; // P Motion Speed [0.0, 2.5, 0.05] // Evaluate hanging cloth z-displacement (pinned at top corners y = +0.72, draped over sphere at origin) float clothSurfaceZ(vec2 xy, float t, float wind, float stiff, out float strainOut) { // Pin factor: 0 at top corners (-0.65, 0.72) and (0.65, 0.72), 1 freely billowing below float dPinL = length(xy - vec2(-0.62, 0.68)); float dPinR = length(xy - vec2(0.62, 0.68)); float freeMask = smoothstep(0.04, 0.36, min(dPinL, dPinR)); // Stable Baraff-Witkin implicit-damped billowing harmonics (high stiffness dampens fine ripples) float damp = exp(-stiff * 0.65); float w1 = sin(xy.x * 3.4 - t * 2.1) * cos(xy.y * 2.5 - t * 1.45) * 0.14 * wind; float w2 = sin(xy.x * 6.8 + xy.y * 4.2 - t * 3.2) * 0.055 * wind * damp; float w3 = cos(xy.x * 11.2 - xy.y * 8.4 + t * 4.1) * 0.018 * wind * damp * damp; // Natural catenary drape sag between pins float catenary = -0.14 * (1.0 - (xy.x * xy.x) * 1.8) * smoothstep(-0.7, 0.7, xy.y); float z = (w1 + w2 + w3 + catenary) * freeMask; // Collision bulge over orbiting obsidian sphere behind cloth vec2 spXY = vec2(0.24 * sin(t * 0.65), -0.08 + 0.12 * cos(t * 0.85)); float rSp = length(xy - spXY); float bulge = 0.28 * exp(-rSp * rSp * 7.5); // Radial compression folds radiating around the collider bulge float radialFolds = 0.024 * cos(atan(xy.y - spXY.y, xy.x - spXY.x) * 7.0 + t * 0.8) * exp(-rSp * 3.2) * smoothstep(0.06, 0.24, rSp); z += bulge + radialFolds; // Approximate warp/weft tensile strain (highest near pin anchors and over collider dome) float pinTension = exp(-min(dPinL, dPinR) * 4.2); float domeTension = exp(-rSp * rSp * 6.5); strainOut = clamp(pinTension * 0.92 + domeTension * 0.78 + abs(w2) * 3.2, 0.0, 1.0); return z; } // Signed distance to finite cloth sheet with thickness float mapCloth(vec3 p, float t, float wind, float stiff) { float st; vec2 clampedXY = clamp(p.xy, vec2(-0.68, -0.68), vec2(0.68, 0.68)); float zSurf = clothSurfaceZ(clampedXY, t, wind, stiff, st); vec2 edgeD = abs(p.xy) - vec2(0.68, 0.68); float outXY = length(max(edgeD, 0.0)); float dz = abs(p.z - zSurf) - 0.014; return (outXY > 0.0) ? sqrt(outXY * outXY + max(dz, 0.0) * max(dz, 0.0)) : dz; } vec3 calcClothNormal(vec3 p, float t, float wind, float stiff) { float e = 0.008; float s0, sx, sy; float z0 = clothSurfaceZ(p.xy, t, wind, stiff, s0); float zx = clothSurfaceZ(p.xy + vec2(e, 0.0), t, wind, stiff, sx); float zy = clothSurfaceZ(p.xy + vec2(0.0, e), t, wind, stiff, sy); return normalize(vec3(-(zx - z0) / e, -(zy - z0) / e, 1.0)); } vec3 stressPalette(float s) { s = clamp(s, 0.0, 1.0); vec3 c0 = vec3(0.08, 0.24, 0.56); vec3 c1 = vec3(0.14, 0.84, 0.72); vec3 c2 = vec3(0.98, 0.74, 0.18); vec3 c3 = vec3(0.98, 0.22, 0.34); if (s < 0.35) return mix(c0, c1, s / 0.35); if (s < 0.70) return mix(c1, c2, (s - 0.35) / 0.35); return mix(c2, c3, (s - 0.70) / 0.30); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float tAnim = iTime * max(P_DRAPE_SPEED, 0.0); float wind = clamp(P_WIND_FORCE, 0.05, 2.4); float stiff = clamp(P_BEND_STIFF, 0.1, 1.6); float split = clamp(P_STRESS_SPLIT, 0.0, 1.0); vec3 ro = vec3(0.18 * sin(tAnim * 0.28), 0.04, 2.25); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.03, 0.04, 0.065), vec3(0.09, 0.115, 0.165), smoothstep(-0.55, 0.55, uv.y)); float t = 0.4; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapCloth(ro + rd * t, tAnim, wind, stiff); if (d < 0.0025) { hit = true; break; } t += d * 0.65; if (t > 6.5) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcClothNormal(p, tAnim, wind, stiff); if (dot(n, -rd) < 0.0) n = -n; float strain; clothSurfaceZ(p.xy, tAnim, wind, stiff, strain); // Fine procedural twill weave + structural warp/weft spring mesh lines vec2 wuv = p.xy * 26.0; float twill = 0.5 + 0.5 * sin(wuv.x * 3.14159 + sin(wuv.y * 3.14159)) * cos(wuv.y * 3.14159); vec2 springG = abs(fract(p.xy * 11.0 - 0.5) - 0.5); float springWire = smoothstep(0.055, 0.012, min(springG.x, springG.y)); vec3 l1 = normalize(vec3(0.62, 0.78, 0.68)); vec3 l2 = normalize(vec3(-0.72, -0.25, 0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); // Charlie / velvet sheen grazing highlight characteristic of woven cloth float sheen = pow(1.0 - max(dot(n, -rd), 0.0), 2.6) * 0.46; // Rich crimson-burgundy woven cloth (right) vs Baraff-Witkin warp/weft strain & spring grid (left) vec3 fabricAlb = mix(vec3(0.58, 0.14, 0.18), vec3(0.76, 0.24, 0.26), twill * 0.55); // Gold embroidered border hem float hem = smoothstep(0.61, 0.65, max(abs(p.x), abs(p.y))); fabricAlb = mix(fabricAlb, vec3(0.88, 0.70, 0.28), hem * 0.85); vec3 fabricCol = fabricAlb * (0.24 + 0.86 * diff1 + 0.24 * diff2) + vec3(0.95, 0.68, 0.62) * sheen; vec3 stressCol = stressPalette(strain) * (0.34 + 0.76 * diff1) + vec3(0.35, 0.55, 0.85) * sheen * 0.5; stressCol = mix(stressCol, vec3(0.95, 0.98, 1.0), springWire * 0.42); col = (screenX < split) ? stressCol : fabricCol; // Highlight pinned top corner anchor grommets float dPin = min(length(p.xy - vec2(-0.62, 0.68)), length(p.xy - vec2(0.62, 0.68))); col = mix(col, vec3(1.0, 0.88, 0.38), smoothstep(0.055, 0.03, dPin)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Sources 1. [primary] David Baraff, Andrew Witkin (1998) Large steps in cloth simulation. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280821 (verified via crossref on 2026-11-29) 2. [primary] Tiantian Liu, Adam W. Bargteil, James F. O'Brien, Ladislav Kavan (2013) Fast simulation of mass-spring systems. ACM Transactions on Graphics. https://doi.org/10.1145/2508363.2508406 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Implicit cloth integration (Baraff-Witkin)." https://texelatlas.vercel.app/t/implicit-cloth-integration/ (accessed 2026-12-01). --- id: "improved-perlin-noise" title: "Improved Perlin Noise" aliases: [Perlin 2002] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, unity, unreal, godot, python] year_introduced: 2002 outputs: [texture, heightfield, volume-density] style: "both" dynamic: "both" cost: "cheap" authority: "Perlin, 2002" url: "https://texelatlas.vercel.app/t/improved-perlin-noise/" sources_verified_at: "2026-11-29" --- # Improved Perlin Noise (Perlin, 2002) > Perlin's revision of gradient noise: a quintic fade curve with continuous second derivative and gradients drawn from the 12 cube-edge directions, removing the creases and directional bias of the 1985 version. ## Reach for it when - noise shows creases or axis-aligned artifacts - need smooth derivatives for lighting or bump - noise gradient has visible discontinuities - want analytic slope for erosion terrain ## How it works Structure is the same as classic gradient noise (hash lattice corners, dot offset with gradient, interpolate), with two changes. First, the interpolation weight becomes the quintic 6t^5-15t^4+10t^3, whose first and second derivatives vanish at cell boundaries, so the field is C2 continuous and its analytic derivatives have no seams. Second, instead of random unit vectors the gradient set is limited to the twelve vectors from the cube centre to edge midpoints, selected with a few bit operations from the hash. This avoids long axis-aligned gradients that caused visible streaks and makes the gradient dot product a sum of at most two terms. The reference Java code is a short permutation-table implementation that is trivially ported to shaders, usually replacing the table with an arithmetic hash. ## When to use it Choose it as the default gradient noise whenever you light, bump or differentiate the result, or when you need analytic derivatives for erosion-style terrain. Prefer [Simplex Noise](https://texelatlas.vercel.app/t/simplex-noise.md) when you need 4D or want cheaper high-dimensional evaluation, and [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) only when reproducing legacy 1985 output exactly. If you need cell structure rather than smooth blobs use [Worley (Cellular) Noise](https://texelatlas.vercel.app/t/worley-noise.md). ## Cost cheap — Slightly more arithmetic than the 1985 fade, same lookup count; negligible per-octave cost on GPU. Measured GPU Weight: 9.17× baseline (moderate) — 0.3016 ms median / 0.3188 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.98× baseline (moderate) — 0.1428 ms median (2.11× faster on L4). Ampere A100 scaling: 6.81× baseline (moderate) — 0.196 ms median (1.54× faster on A100). ## Failure modes - Still lattice-aligned at low frequency, producing faint grid-oriented banding that fBm with rotated octaves hides but does not remove - Integer-hash quality matters: weak hashes show repeating patterns or correlated rows far from the origin - Float precision loss at large coordinates makes the noise collapse into stripes or blocks - Not tileable without wrapping the lattice hash, a common surprise when baking seamless textures ## Engine support - babylonjs: official — `@babylonjs/procedural-textures PerlinNoiseProceduralTexture (and core NoiseProceduralTexture perlinNoise2D)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/proceduralTextures/src/perlinNoise/perlinNoiseProceduralTexture.ts, checked 2026-12-01) - blender: builtin — `Shader / Geometry node: Noise Texture (Perlin / Multifractal / fBM)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/noise.html, checked 2026-12-01) - godot: builtin — `FastNoiseLite.noise_type = FastNoiseLite.TYPE_PERLIN` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/noise/doc_classes/FastNoiseLite.xml, checked 2026-12-01) - threejs: official — `import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/math/ImprovedNoise.js, checked 2026-12-01) - unity: official — `Package Manager > Mathematics > noise.cnoise / noise.pnoise` (evidence: https://github.com/Unity-Technologies/Unity.Mathematics/blob/master/src/Unity.Mathematics/Noise/classicnoise3D.cs, checked 2026-12-01) — Unity.Mathematics classic Perlin noise (Gustavson). - unreal: builtin — `Material graph: Noise expression > Function = Gradient / Perlin (NoiseFunction)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/NoiseFunction, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: texture, heightfield, volume-density - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, unity, unreal, godot, python ## Presets ### Lit gradient noise: cubic fade creases (left) vs improved quintic fade (right) (glsl-fragment; rendered 2026-11-29) ```json { "SCALE": 7 } ``` ```glsl // Gradient noise lit as a height field: left uses Perlin's old cubic fade (grid creases visible), right the improved quintic fade. const float SCALE = 7.0; vec2 grad(vec2 i) { // 8 edge-ish directions chosen by a lattice hash float h = fract(sin(dot(i, vec2(127.1, 311.7))) * 43758.5453); float a = floor(h * 8.0) * 0.7853982; return vec2(cos(a), sin(a)); } float noise(vec2 p, bool quintic) { vec2 i = floor(p), f = fract(p); vec2 u = quintic ? f * f * f * (f * (f * 6.0 - 15.0) + 10.0) : f * f * (3.0 - 2.0 * f); float a = dot(grad(i), f); float b = dot(grad(i + vec2(1, 0)), f - vec2(1, 0)); float c = dot(grad(i + vec2(0, 1)), f - vec2(0, 1)); float d = dot(grad(i + vec2(1, 1)), f - vec2(1, 1)); return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; bool q = uv.x > 0.5; vec2 p = uv * SCALE + vec2(iTime * 0.0); float e = 0.01; float h = noise(p, q); float hx = noise(p + vec2(e, 0), q) - noise(p - vec2(e, 0), q); float hy = noise(p + vec2(0, e), q) - noise(p - vec2(0, e), q); vec3 n = normalize(vec3(-hx * 12.0, -hy * 12.0, 1.0)); float dif = max(dot(n, normalize(vec3(-0.5, 0.6, 0.7))), 0.0); float spec = pow(max(dot(reflect(-normalize(vec3(-0.5, 0.6, 0.7)), n), vec3(0, 0, 1)), 0.0), 24.0); vec3 col = mix(vec3(0.15, 0.2, 0.35), vec3(0.95, 0.8, 0.6), h * 1.2 + 0.5) * (0.25 + 0.8 * dif) + 0.3 * spec; col = mix(col, vec3(1.0), smoothstep(0.004, 0.0, abs(uv.x - 0.5))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - supersedes [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) ## Sources 1. [primary] Ken Perlin (2002) Improving noise. Proceedings of the 29th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/566570.566636 (verified via crossref on 2026-11-29) 2. [tutorial] Patricio Gonzalez Vivo The Book of Shaders: Noise. thebookofshaders.com. https://thebookofshaders.com/11 (verified via http on 2026-11-29) 3. [tutorial] Inigo Quilez Gradient Noise - Derivatives. iquilezles.org. https://iquilezles.org/articles/gradientnoise (verified via http on 2026-11-29) ## Cite this entry Texel. "Improved Perlin Noise." https://texelatlas.vercel.app/t/improved-perlin-noise/ (accessed 2026-12-01). --- id: "infinigen" title: "Infinigen (Procedural Photorealistic Worlds)" aliases: [Infinigen Nature] domain: "procgen" stage: "procedural" realtime: "offline" platforms: [blender, python, cpu, cuda] year_introduced: 2023 outputs: [mesh, material-params, texture, layout] style: "photoreal" dynamic: "static" cost: "offline" authority: "Raistrick et al., 2023" url: "https://texelatlas.vercel.app/t/infinigen/" sources_verified_at: "2026-11-29" --- # Infinigen (Procedural Photorealistic Worlds) (Raistrick et al., 2023) > A Blender-based procedural generator of natural scenes: terrain, plants, creatures and materials all come from random parametric programs, with ground-truth geometry labels for training vision models. ## Reach for it when - need endless varied natural scenes for training data - generate terrain, plants and creatures procedurally in blender - want reproducible photoreal worlds from a seed - synthetic dataset with ground-truth geometry labels - hand-modelling natural environments takes too long ## How it works Every asset is a program with parameters sampled from priors: terrain from SDF-based elements with erosion and tectonic features, trees and plants via grammar-based branching, creatures from skeleton-and-skin templates, materials as shader node graphs with noise-based textures. A scene composer places assets according to ecological and spatial constraints (terrain slope, water, density), then Blender renders with Cycles. Because the whole scene is generated from code, exact depth, normals, segmentation, flow and occlusion edges are produced without annotation. Level of detail is controlled by distance from camera so only visible detail is generated. The code is open source (BSD-3-Clause). ## When to use it Choose it for synthetic training data and for hero-quality natural scenes you can script and reproduce from a seed. Prefer [Plant Ecosystem Distribution Simulation](https://texelatlas.vercel.app/t/ecosystem-plant-distribution.md) and the individual terrain and plant techniques for engine-integrated runtime generation, and learned generators in the genai domain when you want text-conditioned results rather than rules. ## Cost offline — Cycles rendering and heavy asset generation: minutes to hours per scene depending on resolution and detail. Measured GPU Weight: 303.7× baseline (extreme) — 9.9916 ms median / 10.1357 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 295.96× baseline (extreme) — 4.7058 ms median (2.12× faster on L4). Ampere A100 scaling: 236.91× baseline (extreme) — 6.8229 ms median (1.46× faster on A100). ## Failure modes - Blender and Python dependency stack is heavy; builds break across versions or platforms - Asset diversity is limited to the shipped generators (natural scenes), so urban or interior content needs the Indoors extension - Scene composition is rule-based, so structural realism (e.g. consistent ecology) can fail in corner cases - Generation time is high; tuning a scene means re-running long jobs ## Engine support - blender: plugin — `Install from github.com/princeton-vl/infinigen (runs on bpy / Blender)` (evidence: https://github.com/princeton-vl/infinigen, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: mesh, material-params, texture, layout - Platforms: blender, python, cpu, cuda ## Presets ### Infinigen — ground-truth semantic & surface-normal labels (left) vs procedural photoreal alpine terrain (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TERRAIN_SEED": 1.4, "P_RIVER_CARVE": 0.75, "P_SUN_AZIMUTH": 0.52, "P_SPLIT": 0.48 } ``` ```glsl const float P_TERRAIN_SEED = 1.40; // P World Seed [0.0, 6.0, 0.2] const float P_RIVER_CARVE = 0.75; // P Valley Carve [0.2, 1.4, 0.05] const float P_SUN_AZIMUTH = 0.52; // P Sun Azimuth [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Labels / World Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } float fbm(vec2 p) { float s = 0.0, a = 0.5; mat2 m = mat2(0.80, -0.60, 0.60, 0.80); for (int i = 0; i < 5; i++) { s += a * vnoise(p); p = m * p * 2.04; a *= 0.5; } return s; } // Procedural alpine valley terrain heightfield with carved winding river & rocky ridges float evalTerrain(vec2 xz, float seed, float carve) { vec2 q = xz * 0.34 + vec2(seed * 1.7, seed * 0.9); float ridge = 1.0 - abs(fbm(q) * 2.0 - 1.0); float base = fbm(q * 1.45 + 3.1) * 1.15 + ridge * ridge * 1.25; // Meandering glacial river channel along z float riverX = 0.72 * sin(xz.y * 0.35 + seed) + 0.25 * cos(xz.y * 0.85); float dRiv = abs(xz.x - riverX); float valley = smoothstep(0.18, 2.25, dRiv); float h = base * mix(0.22, 1.48, pow(valley, 0.85)) - (1.0 - valley) * 0.45 * carve; // Subtle procedural pine-tree cluster bumps on mid-elevation forested slopes float forestBand = smoothstep(0.14, 0.32, h) * smoothstep(0.95, 0.58, h); float trees = smoothstep(0.45, 0.78, vnoise(xz * 5.8 + seed)) * 0.14 * forestBand; return h + trees; } vec3 calcTerrainNormal(vec2 xz, float seed, float carve) { float e = 0.035; float hL = evalTerrain(xz - vec2(e, 0.0), seed, carve); float hR = evalTerrain(xz + vec2(e, 0.0), seed, carve); float hD = evalTerrain(xz - vec2(0.0, e), seed, carve); float hU = evalTerrain(xz + vec2(0.0, e), seed, carve); return normalize(vec3(hL - hR, 2.0 * e, hD - hU)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showPhoto = sx >= split; float seed = clamp(P_TERRAIN_SEED, 0.0, 8.0); float carve = clamp(P_RIVER_CARVE, 0.1, 1.6); float sunAz = clamp(P_SUN_AZIMUTH, 0.0, 2.5) + iTime * 0.14; vec3 ro = vec3(0.45 * sin(iTime * 0.18), 1.45, 3.6 - iTime * 0.25); vec3 ta = ro + vec3(-0.25 * sin(iTime * 0.18), -0.45, -2.5); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.45 + ri * uv.x + up * uv.y); vec3 sunDir = normalize(vec3(cos(sunAz) * 0.78, 0.48, sin(sunAz) * 0.55 - 0.45)); vec3 sky = mix(vec3(0.76, 0.84, 0.94), vec3(0.16, 0.36, 0.72), smoothstep(-0.05, 0.55, rd.y)); sky += vec3(1.8, 1.4, 0.9) * pow(max(dot(rd, sunDir), 0.0), 42.0); vec3 col = showPhoto ? sky : vec3(0.14, 0.36, 0.78); // Sky semantic class ID on left float waterLevel = 0.08; float t = 0.12; bool hit = false; for (int i = 0; i < 72; i++) { vec3 p = ro + rd * t; float h = max(evalTerrain(p.xz, seed, carve), waterLevel); float d = p.y - h; if (d < 0.008 * t) { hit = true; break; } t += max(d * 0.55, 0.035); if (t > 24.0) break; } if (hit) { vec3 p = ro + rd * t; float th = evalTerrain(p.xz, seed, carve); bool isWater = th <= waterLevel + 0.01; vec3 n = isWater ? normalize(vec3(0.04 * sin(p.x * 12.0 + iTime * 2.0), 1.0, 0.04 * cos(p.z * 12.0 - iTime * 1.8))) : calcTerrainNormal(p.xz, seed, carve); // Procedural biome semantic classification: 0=Water, 1=Pine Forest, 2=Alpine Rock, 3=Snow Peak float slope = 1.0 - n.y; float snowMask = smoothstep(0.92, 1.18, p.y - slope * 0.45); float rockMask = smoothstep(0.24, 0.46, slope); float forestMask = smoothstep(0.14, 0.30, p.y) * smoothstep(0.95, 0.62, p.y) * (1.0 - rockMask); if (!showPhoto) { // Left: Infinigen ground-truth semantic segmentation + depth contours & crisp class boundaries vec3 semCol = vec3(0.10, 0.65, 0.88); // water class if (!isWater) { if (snowMask > 0.5) semCol = vec3(0.92, 0.94, 0.98); // snow class else if (rockMask > 0.45) semCol = vec3(0.68, 0.42, 0.24); // cliff rock class else if (forestMask > 0.35) semCol = vec3(0.18, 0.78, 0.32); // evergreen vegetation class else semCol = vec3(0.76, 0.72, 0.26); // meadow/shore class } // Overlay subtle ground-truth surface-normal tint & depth iso-lines float depthIso = smoothstep(0.08, 0.02, abs(fract(t * 0.65) - 0.5)); col = mix(semCol * (0.65 + 0.35 * (n.y * 0.5 + 0.5)), n * 0.5 + 0.5, 0.22); col = mix(col, vec3(0.04, 0.05, 0.08), depthIso * 0.35); } else { // Right: Full photorealistic procedural alpine world with crisp sun shadows & aerial perspective float sh = 1.0; float st = 0.08; for (int s = 0; s < 16; s++) { vec3 sp = p + sunDir * st; float shH = evalTerrain(sp.xz, seed, carve); if (sp.y < shH) { sh = 0.0; break; } st += max((sp.y - shH) * 0.65, 0.09); if (st > 6.0) break; } vec3 alb; if (isWater) { vec3 refl = reflect(rd, n); float fres = 0.08 + 0.85 * pow(1.0 - max(dot(n, -rd), 0.0), 4.0); vec3 waterBody = vec3(0.04, 0.20, 0.28); vec3 reflSky = mix(vec3(0.45, 0.62, 0.82), vec3(0.95, 0.86, 0.72), pow(max(dot(refl, sunDir), 0.0), 12.0)); col = mix(waterBody, reflSky, fres) + vec3(1.5, 1.3, 1.0) * pow(max(dot(refl, sunDir), 0.0), 96.0) * sh; } else { float strata = 0.82 + 0.18 * sin(p.y * 24.0 + fbm(p.xz * 3.0) * 4.0); vec3 meadow = vec3(0.24, 0.36, 0.16); vec3 pine = vec3(0.08, 0.22, 0.10); vec3 rock = vec3(0.36, 0.34, 0.32) * strata; vec3 snow = vec3(0.90, 0.93, 0.97); alb = mix(meadow, pine, forestMask); alb = mix(alb, rock, rockMask); alb = mix(alb, snow, snowMask); float ndl = max(dot(n, sunDir), 0.0); vec3 skyAmb = mix(vec3(0.14, 0.18, 0.24), vec3(0.34, 0.48, 0.72), 0.5 + 0.5 * n.y); col = alb * (vec3(1.55, 1.38, 1.12) * ndl * sh + skyAmb * 0.52); } // Exponential aerial perspective haze float fog = 1.0 - exp(-t * 0.068); col = mix(col, sky, clamp(fog, 0.0, 0.92)); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Alexander Raistrick, Lahav Lipson, Zeyu Ma, Lingjie Mei, Mingzhe Wang, Yiming Zuo, Karhan Kayan, Hongyu Wen, Beining Han, Yihan Wang, Alejandro Newell, Hei Law, Ankit Goyal, Kaiyu Yang, Jia Deng (2023) Infinite Photorealistic Worlds Using Procedural Generation. 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/cvpr52729.2023.01215 (verified via crossref on 2026-11-29) 2. [implementation] princeton-vl (2023) princeton-vl/infinigen. https://github.com/princeton-vl/infinigen License: BSD-3-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "Infinigen (Procedural Photorealistic Worlds)." https://texelatlas.vercel.app/t/infinigen/ (accessed 2026-12-01). --- id: "instant-meshes" title: "Instant Field-Aligned Meshes" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu] year_introduced: 2015 inputs: [mesh, point-cloud] outputs: [mesh] style: "both" dynamic: "static" cost: "offline" authority: "Jakob et al., 2015" url: "https://texelatlas.vercel.app/t/instant-meshes/" sources_verified_at: "2026-11-29" --- # Instant Field-Aligned Meshes (Jakob et al., 2015) > Computes a smooth orientation and position field over the surface and extracts a quad-dominant mesh whose edges follow the field, interactively and with user guidance by strokes. Good topology without manual retopology. ## Reach for it when - scanned mesh is a messy triangle soup - need clean quad dominant remesh for animation - retopologize a sculpt automatically - edge flow should follow surface curvature ## How it works A multiresolution hierarchy of the input point set is built. At each level, an orientation field (four-way rotational symmetry) and a position field (lattice offsets) are optimised by Gauss-Seidel smoothing, with results prolonged to finer levels. Fields align to principal curvature directions where features exist. The lattice defined by the fields is then extracted as a mesh: vertices on lattice points, edges between neighbours, and faces by tracing short cycles; remaining holes become triangles. Users can draw strokes to impose directions or singularities. Everything runs interactively on CPU using a fast parallel solver. ## When to use it Choose it for quick retopology of sculpts, scans or marching-cubes meshes into clean quad or triangle meshes you can subdivide or animate. Prefer [QuadriFlow](https://texelatlas.vercel.app/t/quadriflow.md) when you need a pure-quad mesh with guaranteed manifold output and fewer irregular vertices, [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md) when you want triangles and no field alignment, and [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md) for plain decimation. ## Cost offline — Seconds to a minute on CPU for typical sculpts; interactive on smaller meshes. The solver is multiresolution and threaded. ## Failure modes - Output can contain triangles, pentagons and non-manifold bits that need cleanup - Poor handling of very thin features and thin shells - Edge flow does not follow semantic loops (eyes, mouths) without strokes - Orientation singularities fall where the optimiser puts them, not where an artist would ## Dataflow - Inputs: mesh, point-cloud - Outputs: mesh - Platforms: cpu ## Combines with - [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md): The quad output serves as a Catmull-Clark control cage. ## Sources 1. [primary] Wenzel Jakob, Marco Tarini, Daniele Panozzo, Olga Sorkine-Hornung (2015) Instant field-aligned meshes. ACM Transactions on Graphics. https://doi.org/10.1145/2816795.2818078 (verified via crossref on 2026-11-29) 2. [implementation] wjakob (2015) wjakob/instant-meshes. https://github.com/wjakob/instant-meshes License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Instant Field-Aligned Meshes." https://texelatlas.vercel.app/t/instant-meshes/ (accessed 2026-12-01). --- id: "instant-ngp" title: "Instant NGP (Multiresolution Hash Encoding)" aliases: [Instant-NGP, hash grid encoding] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda] year_introduced: 2022 inputs: [photos, camera-poses] outputs: [radiance-field, sdf] style: "photoreal" dynamic: "static" cost: "offline" authority: "Müller et al., 2022" url: "https://texelatlas.vercel.app/t/instant-ngp/" sources_verified_at: "2026-11-29" --- # Instant NGP (Multiresolution Hash Encoding) (Müller et al., 2022) > Replaces large coordinate MLPs with a small network fed by a multiresolution hash table of trainable features, training NeRFs and SDFs in seconds to minutes on one GPU. ## Reach for it when - nerf training takes hours - want a neural radiance field in minutes on one gpu - large coordinate network trains too slowly - need interactive preview of a neural scene while training ## How it works The input position is looked up in several grids of increasing resolution. Each level hashes its integer corner coordinates into a fixed-size table of trainable feature vectors, interpolates trilinearly between corners, and the per-level features are concatenated. Hash collisions are tolerated: the small downstream MLP and gradient averaging resolve them in favour of the cells that matter. Because most of the capacity sits in the table, the MLP can be tiny and is fused into one CUDA kernel, so training is bandwidth-bound rather than FLOP-bound. An occupancy grid skips empty space during ray marching. The same encoding works for NeRF, signed distance functions, images and neural volumes. ## When to use it Choose it when you want a NeRF or neural SDF trained in minutes and previewed interactively on an NVIDIA GPU. Prefer [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for higher render speed and quality on large scenes, [Mip-NeRF 360](https://texelatlas.vercel.app/t/mip-nerf-360.md) when anti-aliasing and unbounded quality matter more than training time, and [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) for high-fidelity surfaces built on the same hash encoding. ## Cost offline — Paper-reported training in seconds to a few minutes on a single high-end NVIDIA GPU; requires CUDA/tiny-cuda-nn. Measured GPU Weight: 476.58× baseline (extreme) — 15.6795 ms median / 15.8455 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 422.87× baseline (extreme) — 6.7236 ms median (2.33× faster on L4). Ampere A100 scaling: 363.57× baseline (extreme) — 10.4709 ms median (1.5× faster on A100). ## Failure modes - Hash collisions add high-frequency noise and speckle when the table is too small for the scene - Floaters and background fog in sparsely observed regions, as in vanilla NeRF - Not anti-aliased across scales, so zoomed-out views alias - Tied to NVIDIA GPUs and a non-commercial research licence in the reference code ## Engine support - blender: plugin — `Blender add-on: BlenderNeRF (exports Instant NGP datasets)` (evidence: https://github.com/maximeraafat/BlenderNeRF, checked 2026-12-01) — Dataset export only; training is external. ## Dataflow - Inputs: photos, camera-poses - Outputs: radiance-field, sdf - Platforms: cuda ## Presets ### Hash encoding configuration used for NeRF (json-params; parameter preset) ```json { "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "mlp_hidden_layers": 1, "mlp_neurons": 64 } ``` Attribution: Values follow the configuration reported in the paper; the reference repo NVlabs/instant-ngp is under NVIDIA's non-commercial source code licence.; basis: 0 ### Instant NGP — multiresolution spatial hash-grid levels (left) vs decoded high-frequency NeRF (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_HASH_LEVELS": 5, "P_SIGMA_GAIN": 5.2, "P_ROT_SPEED": 0.58, "P_SPLIT": 0.48 } ``` ```glsl const float P_HASH_LEVELS = 5.0; // P Hash Levels L [1.0, 6.0, 1.0] const float P_SIGMA_GAIN = 5.2; // P Volume Sigma [1.5, 10.0, 0.25] const float P_ROT_SPEED = 0.58; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Hash Grid / NGP [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); } // Multiresolution hash-encoded neural feature sum across geometric cascade resolutions N_l = N_min * b^l float evalHashFeatures(vec3 p, float maxL) { float acc = 0.0; float res = 3.0; float amp = 0.5; for (int l = 0; l < 6; l++) { if (float(l) >= maxL) break; vec3 gp = p * res; vec3 cell = floor(gp); vec3 f = fract(gp); f = f * f * (3.0 - 2.0 * f); // Trilinearly interpolated hashed vertex features (mimicking T-entry spatial hash table) float v000 = hash31(cell); float v100 = hash31(cell + vec3(1.0, 0.0, 0.0)); float v010 = hash31(cell + vec3(0.0, 1.0, 0.0)); float v110 = hash31(cell + vec3(1.0, 1.0, 0.0)); float v001 = hash31(cell + vec3(0.0, 0.0, 1.0)); float v101 = hash31(cell + vec3(1.0, 0.0, 1.0)); float v011 = hash31(cell + vec3(0.0, 1.0, 1.0)); float v111 = hash31(cell + vec3(1.0, 1.0, 1.0)); float c00 = mix(v000, v100, f.x); float c10 = mix(v010, v110, f.x); float c01 = mix(v001, v101, f.x); float c11 = mix(v011, v111, f.x); float c0 = mix(c00, c10, f.y); float c1 = mix(c01, c11, f.y); acc += (mix(c0, c1, f.z) - 0.5) * amp; res *= 1.85; amp *= 0.54; } return acc; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isGrid = screenX < split; float maxL = clamp(floor(P_HASH_LEVELS + 0.5), 1.0, 6.0); float sigmaGain = clamp(P_SIGMA_GAIN, 1.0, 12.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.22, 2.28); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.03), -1.52)); ro.xz = rot2(spin * 0.52) * ro.xz; rd.xz = rot2(spin * 0.52) * rd.xz; vec3 bg = mix(vec3(0.018, 0.025, 0.044), vec3(0.052, 0.072, 0.120), smoothstep(-0.55, 0.55, uv.y)); vec3 col = bg; float b = dot(ro, rd); float c = dot(ro, ro) - 1.02 * 1.02; float disc = b * b - c; if (disc > 0.0) { float t0 = max(-b - sqrt(disc), 0.1); float t1 = -b + sqrt(disc); float dt = (t1 - t0) / 44.0; vec3 acc = vec3(0.0); float T = 1.0; vec3 lDir = normalize(vec3(0.58, 0.80, 0.45)); for (int i = 0; i < 44; i++) { float t = t0 + (float(i) + 0.5) * dt; vec3 p = ro + rd * t; // Sculpted bonsai-arch/crystal core modulated by multiresolution hash encoding float baseD = length(p) - 0.58; float ringD = length(vec2(length(p.xz) - 0.52, p.y)) - 0.16; float dShape = min(baseD, ringD); float hf = evalHashFeatures(p, maxL); float d = dShape + hf * 0.22; float sigma = exp(-max(d, 0.0) * 20.0) * smoothstep(0.14, -0.04, d) * sigmaGain; if (isGrid) { // Left: Visualize active occupancy grid + multiresolution hash-lattice wireframe vec3 gCoarse = abs(fract(p * 4.0) - 0.5); vec3 gFine = abs(fract(p * 10.0) - 0.5); float wC = smoothstep(0.04, 0.01, min(gCoarse.x, min(gCoarse.y, gCoarse.z))); float wF = smoothstep(0.05, 0.012, min(gFine.x, min(gFine.y, gFine.z))) * smoothstep(0.18, -0.05, dShape); vec3 hashCol = 0.5 + 0.5 * cos(vec3(0.0, 2.1, 4.2) + hf * 8.0 + p.y * 2.5); float sVis = sigma * 0.45 + wC * 0.35 + wF * 1.4; float a = 1.0 - exp(-sVis * dt); vec3 rad = mix(vec3(0.14, 0.78, 0.96) * wC + vec3(0.98, 0.62, 0.18) * wF, hashCol, clamp(sigma * 0.25, 0.0, 1.0)); acc += T * a * rad * 1.25; T *= (1.0 - a); } else { // Right: Tiny fused MLP radiance decode with sharp high-frequency surface detail float a = 1.0 - exp(-sigma * dt); if (a > 0.005) { vec3 n = normalize(p + vec3(hf * 0.8, hf * 0.6, -hf * 0.7) + vec3(1e-4)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 36.0); vec3 alb = mix(vec3(0.16, 0.66, 0.88), vec3(0.96, 0.52, 0.22), smoothstep(-0.35, 0.35, hf + p.y * 0.5)); vec3 rad = alb * (0.30 + 0.82 * diff) + vec3(1.0, 0.95, 0.88) * spec * 0.45; acc += T * a * rad; T *= (1.0 - a); } } if (T < 0.015) break; } col = acc + T * bg; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Neural Radiance Fields (NeRF)](https://texelatlas.vercel.app/t/nerf.md) ## Combines with - [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md): Neuralangelo uses the multiresolution hash grid as its SDF feature backbone. ## Sources 1. [primary] Thomas Müller, Alex Evans, Christoph Schied, Alexander Keller (2022) Instant neural graphics primitives with a multiresolution hash encoding. ACM Transactions on Graphics. https://doi.org/10.1145/3528223.3530127 (verified via crossref on 2026-11-29) 2. [primary] Thomas Müller, Alex Evans, Christoph Schied, Alexander Keller (2022) Instant Neural Graphics Primitives with a Multiresolution Hash Encoding. ACM Trans. Graph. 41, 4, Article 102 (July 2022), 15 pages. https://arxiv.org/abs/2201.05989 (verified via arxiv on 2026-11-29) 3. [implementation] NVlabs (2022) NVlabs/instant-ngp. https://github.com/NVlabs/instant-ngp License: NOASSERTION. (verified via github on 2026-11-29) 4. [tutorial] NVIDIA Research Instant Neural Graphics Primitives project page. nvlabs.github.io. https://nvlabs.github.io/instant-ngp (verified via http on 2026-11-29) ## Cite this entry Texel. "Instant NGP (Multiresolution Hash Encoding)." https://texelatlas.vercel.app/t/instant-ngp/ (accessed 2026-12-01). --- id: "instant-radiosity" title: "Instant Radiosity (Virtual Point Lights)" aliases: [VPL, many-lights GI] domain: "gi" stage: "lighting" realtime: "interactive" platforms: [desktop-gpu, cpu] year_introduced: 1997 inputs: [mesh, gbuffer] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Keller, 1997" url: "https://texelatlas.vercel.app/t/instant-radiosity/" sources_verified_at: "2026-11-29" --- # Instant Radiosity (Virtual Point Lights) (Keller, 1997) > Approximates indirect light by tracing random particles from the light and placing a virtual point light at each hit, then lighting the scene with all those point lights using standard shadow-mapped direct lighting. ## Reach for it when - want dynamic diffuse bounce light using ordinary shadow maps - prototype global illumination quickly - indirect lighting without precomputed bake - approximate light bounces with many small lights - colour bleeding in a real-time scene ## How it works Indirect illumination is just direct illumination from surfaces that were lit. Instant radiosity makes this literal. A quasi-random walk is traced from each light source. Each time the particle hits a diffuse surface, the renderer drops a **virtual point light** there with a flux scaled by surface reflectance and the walk's survival probability, and the walk continues by Russian roulette. The scene is then rendered as if lit by a few hundred to thousands of ordinary point lights, each with its own shadow map or ray cast. Because the VPLs form a Monte Carlo estimator of the path integral, the sum converges to indirect lighting. The same VPL set can be reused across frames (with changes only when lights move) and across the whole image, which is why this gave early interactive GI on GPUs. The big flaw is that a point light has an unbounded `1/r^2` near-field, so surfaces close to a VPL show bright splotches. Clamping the contribution or using bounded-kernel virtual sphere lights trades this singularity for bias. ## When to use it Choose it to prototype dynamic diffuse GI with ordinary shadow mapping, or as the conceptual basis for many-light rendering. Prefer [reflective-shadow-maps](reflective-shadow-maps) when only one-bounce indirect from a single light is needed and no shadow maps per VPL are affordable. Prefer [lightcuts](lightcuts) or [light-bvh-many-lights](light-bvh-many-lights) when thousands of VPLs must be gathered efficiently and cleanly. Prefer [path-tracing](path-tracing) for unbiased final images and [ddgi](ddgi) for today's real-time dynamic GI. ## Cost heavy — Shadow maps per VPL dominate; interactive on 1997-era hardware only for small VPL counts, and modern variants use imperfect shadow maps or ray tracing. Measured GPU Weight: 30.53× baseline (heavy) — 0.9587 ms median / 1.0267 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 30.37× baseline (heavy) — 0.4799 ms median (2× faster on L4). Ampere A100 scaling: 18.57× baseline (moderate) — 0.5348 ms median (1.79× faster on A100). ## Failure modes - Bright splotches and spikes near each VPL because of the singular 1/r^2 falloff - Banding or a visible grid of overlapping VPL shadows when the VPL count is low - Low-frequency-only: glossy transfer through VPLs is poor and very bright lamps cause noise - Cost grows linearly with the VPL count times pixels unless gathered hierarchically ## Dataflow - Inputs: mesh, gbuffer - Outputs: radiance - Platforms: desktop-gpu, cpu ## Presets ### Instant Radiosity (VPLs) — bounce-spawned Virtual Point Lights & singularity clamp control (glsl-fragment; rendered 2026-11-30) ```json { "P_VPL_GAIN": 1.3, "P_CLAMP_EPS": 0.28, "P_SHOW_VPLS": 1, "P_BEAM_SPEED": 1 } ``` ```glsl const float P_VPL_GAIN = 1.3; // P VPL Bounce Gain [0.0, 2.6, 0.05] const float P_CLAMP_EPS = 0.28; // P Clamp Radius [0.04, 0.75, 0.02] const float P_SHOW_VPLS = 1.0; // P Show VPL Nodes [0.0, 1.5, 0.05] const float P_BEAM_SPEED = 1.0; // P Light Orbit [0.0, 2.5, 0.05] 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); } vec2 mapRoom(vec3 p) { vec2 res = vec2(1.0 + p.y, 1.0); // floor float cD = 1.0 - p.y; if (cD < res.x) res = vec2(cD, 1.0); float bD = 1.45 + p.z; if (bD < res.x) res = vec2(bD, 1.0); float lD = 1.45 + p.x; if (lD < res.x) res = vec2(lD, 2.0); // ruby red wall float rD = 1.45 - p.x; if (rD < res.x) res = vec2(rD, 3.0); // emerald green wall float dB1 = sdBox(p - vec3(-0.48, -0.45, -0.45), vec3(0.28, 0.55, 0.28)) - 0.02; if (dB1 < res.x) res = vec2(dB1, 4.0); float dB2 = sdBox(p - vec3(0.55, -0.68, -0.15), vec3(0.30, 0.32, 0.30)) - 0.02; if (dB2 < res.x) res = vec2(dB2, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRoom(p + e.xyy).x - mapRoom(p - e.xyy).x, mapRoom(p + e.yxy).x - mapRoom(p - e.yxy).x, mapRoom(p + e.yyx).x - mapRoom(p - e.yyx).x )); } vec3 getAlbedo(float id) { if (id < 1.5) return vec3(0.75, 0.75, 0.74); if (id < 2.5) return vec3(0.90, 0.16, 0.14); if (id < 3.5) return vec3(0.14, 0.80, 0.42); return vec3(0.84, 0.84, 0.82); } // Compute 6 deterministic first-bounce Virtual Point Lights spawned from the primary light source void getVPL(int k, vec3 lPos, out vec3 vPos, out vec3 vNorm, out vec3 vFlux) { if (k == 0) { vPos = vec3(-1.44, -0.10, -0.25); vNorm = vec3(1.0, 0.0, 0.0); vFlux = vec3(1.0, 0.18, 0.15); } else if (k == 1) { vPos = vec3(-1.44, 0.35, -0.82); vNorm = vec3(1.0, 0.0, 0.0); vFlux = vec3(0.95, 0.16, 0.14); } else if (k == 2) { vPos = vec3(1.44, -0.15, -0.35); vNorm = vec3(-1.0, 0.0, 0.0); vFlux = vec3(0.16, 0.92, 0.48); } else if (k == 3) { vPos = vec3(1.44, 0.32, -0.92); vNorm = vec3(-1.0, 0.0, 0.0); vFlux = vec3(0.14, 0.86, 0.44); } else if (k == 4) { vPos = vec3(0.05, -0.99, -0.45); vNorm = vec3(0.0, 1.0, 0.0); vFlux = vec3(0.88, 0.85, 0.78); } else { vPos = vec3(0.0, -0.05, -1.44); vNorm = vec3(0.0, 0.0, 1.0); vFlux = vec3(0.86, 0.84, 0.80); } // Modulate each VPL flux by incident direct illumination from moving primary ceiling lamp vec3 toL = lPos - vPos; float d = length(toL); float inc = max(dot(vNorm, toL / max(d, 1e-4)), 0.0) / (0.45 + 0.35 * d * d); vFlux *= inc * 2.2; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float tAnim = iTime * max(P_BEAM_SPEED, 0.0); float vplGain = max(P_VPL_GAIN, 0.0); float clampEps = max(P_CLAMP_EPS, 0.03); float showVpls = clamp(P_SHOW_VPLS, 0.0, 1.6); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.48)); vec3 lightPos = vec3(0.68 * sin(tAnim * 0.65), 0.78, -0.35 + 0.45 * cos(tAnim * 0.52)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapRoom(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = getAlbedo(matId); // Direct primary light with shadow ray vec3 toL = lightPos - p; float dL = length(toL); vec3 lDir = toL / max(dL, 1e-4); float sh = 1.0; float ts = 0.03; for (int i = 0; i < 22; i++) { float dh = mapRoom(p + lDir * ts).x; if (dh < 0.004) { sh = 0.0; break; } ts += dh; if (ts > dL - 0.08) break; } vec3 direct = alb * vec3(1.9, 1.75, 1.45) * max(dot(n, lDir), 0.0) * sh / (0.5 + 0.45 * dL * dL); // Instant Radiosity VPL Gather with adjustable weak-singularity clamp (1 / max(r^2, eps^2)) vec3 vplBounce = vec3(0.0); vec3 vplMarker = vec3(0.0); for (int k = 0; k < 6; k++) { vec3 vp, vn, vf; getVPL(k, lightPos, vp, vn, vf); vec3 toV = vp - p; float r2 = dot(toV, toV); float r = sqrt(max(r2, 1e-5)); vec3 dv = toV / r; float cosP = max(dot(n, dv), 0.0); float cosV = max(dot(vn, -dv), 0.0); // Geometry factor clamped by P_CLAMP_EPS^2 to control bright VPL corner singularities! float gTerm = (cosP * cosV) / max(r2, clampEps * clampEps); vplBounce += vf * gTerm * 0.24; // Render glowing VPL emitter beacon at bounce site if (showVpls > 0.01) { float dMark = length(p - vp); vplMarker += (vf * 1.4 + vec3(0.35)) * smoothstep(0.095, 0.028, dMark) * showVpls; } } col = direct + alb * vplBounce * vplGain + vplMarker; } // Primary orbiting light bulb flare in space vec3 toBulb = lightPos - ro; float proj = dot(toBulb, rd); if (proj > 0.0 && proj < t) { float db = length(ro + rd * proj - lightPos); col += vec3(2.8, 2.4, 1.7) * exp(-db * 22.0); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Lightcuts](https://texelatlas.vercel.app/t/lightcuts.md): A light cut clusters the VPL set so each pixel evaluates only a small subset. ## Sources 1. [primary] Alexander Keller (1997) Instant radiosity. Proceedings of the 24th annual conference on Computer graphics and interactive techniques - SIGGRAPH '97. https://doi.org/10.1145/258734.258769 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Instant Radiosity (Virtual Point Lights)." https://texelatlas.vercel.app/t/instant-radiosity/ (accessed 2026-12-01). --- id: "instantmesh" title: "InstantMesh" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [ldr-image] outputs: [mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Xu et al., 2024" url: "https://texelatlas.vercel.app/t/instantmesh/" sources_verified_at: "2026-11-29" --- # InstantMesh (Xu et al., 2024) > Generates a fixed set of consistent views of the object with a multi-view diffusion model, then reconstructs a mesh from those views with a sparse-view LRM that extracts surfaces differentiably. ## Reach for it when - generate a 3d mesh from one photo quickly - turn a single image into textured model in seconds - image to 3d output looks inconsistent from other sides - need fast feed-forward single image reconstruction ## How it works Step one runs a multi-view diffusion model that, from one image, produces a six-view grid at known camera poses. Step two feeds those views into a sparse-view Large Reconstruction Model, which predicts a triplane that is decoded to a differentiable iso-surface (FlexiCubes) rather than a NeRF, so training can add geometry losses on depth and normals directly on the mesh. Having a mesh representation in the loop yields cleaner surfaces than density-field marching cubes. Total inference is the diffusion sampling plus one reconstruction pass. ## When to use it Choose it when you want a textured mesh from one picture in seconds and can accept an Apache-2.0 pipeline with a diffusion front end. Prefer [TripoSR](https://texelatlas.vercel.app/t/triposr.md) when speed and simplicity matter most, [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) or [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) when you need higher fidelity or PBR, and [Zero-1-to-3](https://texelatlas.vercel.app/t/zero-1-to-3.md) if you only need novel views. ## Cost heavy — Seconds on a single modern GPU as described by the authors; qualitative here. Measured GPU Weight: 13.85× baseline (moderate) — 0.4558 ms median / 0.4861 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 12.54× baseline (moderate) — 0.1994 ms median (2.29× faster on L4). Ampere A100 scaling: 9× baseline (moderate) — 0.2592 ms median (1.76× faster on A100). ## Failure modes - Multi-view generator hallucinations (wrong back, extra limbs) are baked into the reconstruction - Fixed six views limit coverage of concavities - Textures are vertex-coloured or baked from low-resolution views and blur on close inspection - Unusual aspect ratios or inputs with cast shadows break the consistency of the view grid ## Dataflow - Inputs: ldr-image - Outputs: mesh - Platforms: cuda, python ## Presets ### InstantMesh — orthogonal triplane feature grids (left) vs FlexiCubes decoded 3D mesh (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PLANE_GLOW": 0.9, "P_ISO_DETAIL": 0.75, "P_ROT_SPEED": 0.6, "P_SPLIT": 0.48 } ``` ```glsl const float P_PLANE_GLOW = 0.90; // P Triplane Glow [0.1, 1.6, 0.05] const float P_ISO_DETAIL = 0.75; // P Mesh Detail [0.1, 1.0, 0.02] const float P_ROT_SPEED = 0.60; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Triplane / Mesh [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // 3 orthogonal triplane feature decoders F_xy, F_xz, F_yz summed to predict FlexiCubes SDF float evalTriplaneSDF(vec3 q, float detail) { float fXY = length(q.xy) - 0.52 + 0.08 * sin(q.x * 7.0) * cos(q.y * 7.0) * detail; float fXZ = length(q.xz) - 0.52 + 0.08 * cos(q.x * 6.0 - q.z * 6.0) * detail; float fYZ = length(q.yz) - 0.52 + 0.08 * sin(q.y * 6.0 + q.z * 6.0) * detail; // Intersection of 3 orthogonal sculpted cylinders with rounded core -> mechanical artifact float d = max(fXY, max(fXZ, fYZ)); float core = length(q) - 0.58; return mix(d, core, 0.35) * 0.82; } vec3 calcNormal(vec3 p, float spin, float detail) { vec2 e = vec2(0.0025, 0.0); vec3 px = p + e.xyy; px.xz = rot2(spin) * px.xz; px.yz = rot2(0.32) * px.yz; vec3 mx = p - e.xyy; mx.xz = rot2(spin) * mx.xz; mx.yz = rot2(0.32) * mx.yz; vec3 py = p + e.yxy; py.xz = rot2(spin) * py.xz; py.yz = rot2(0.32) * py.yz; vec3 my = p - e.yxy; my.xz = rot2(spin) * my.xz; my.yz = rot2(0.32) * my.yz; vec3 pz = p + e.yyx; pz.xz = rot2(spin) * pz.xz; pz.yz = rot2(0.32) * pz.yz; vec3 mz = p - e.yyx; mz.xz = rot2(spin) * mz.xz; mz.yz = rot2(0.32) * mz.yz; return normalize(vec3( evalTriplaneSDF(px, detail) - evalTriplaneSDF(mx, detail), evalTriplaneSDF(py, detail) - evalTriplaneSDF(my, detail), evalTriplaneSDF(pz, detail) - evalTriplaneSDF(mz, detail) )); } // Visualize feature activation on one of the 3 orthogonal triplanes vec3 planeFeatureVis(vec2 u, vec3 tint) { float inside = step(max(abs(u.x), abs(u.y)), 0.78); vec2 g = abs(fract(u * 8.0) - 0.5); float grid = smoothstep(0.07, 0.015, min(g.x, g.y)); float feat = 0.5 + 0.5 * sin(u.x * 11.0) * cos(u.y * 11.0); float border = smoothstep(0.025, 0.005, abs(max(abs(u.x), abs(u.y)) - 0.78)); float silhouette = smoothstep(0.56, 0.44, length(u)); return inside * (tint * (0.18 + 0.45 * feat * silhouette) + tint * grid * 0.35 + vec3(1.0) * border * 0.85); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float glow = clamp(P_PLANE_GLOW, 0.05, 1.8); float detail = clamp(P_ISO_DETAIL, 0.05, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.55; vec3 ro = vec3(0.0, 0.18, 2.45); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.03), -1.55)); vec3 col = mix(vec3(0.020, 0.028, 0.048), vec3(0.056, 0.078, 0.128), smoothstep(-0.55, 0.55, uv.y)); // Transform ray into object space to intersect the 3 orthogonal triplanes (z=0, y=0, x=0) vec3 roO = ro; roO.xz = rot2(spin) * roO.xz; roO.yz = rot2(0.32) * roO.yz; vec3 rdO = rd; rdO.xz = rot2(spin) * rdO.xz; rdO.yz = rot2(0.32) * rdO.yz; // Raymarch decoded FlexiCubes iso-surface float tHit = 1e5; float t = 0.0; for (int i = 0; i < 56; i++) { vec3 p = roO + rdO * t; float d = evalTriplaneSDF(p, detail); if (d < 0.0025) { tHit = t; break; } t += d; if (t > 5.0) break; } vec3 meshCol = col; if (tHit < 1e4) { vec3 pW = ro + rd * tHit; vec3 pO = roO + rdO * tHit; vec3 n = calcNormal(pW, spin, detail); vec3 l1 = normalize(vec3(0.62, 0.78, 0.48)); float diff = max(dot(n, l1), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 44.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); // Subtle FlexiCubes dual-grid iso-lines vec3 vg = abs(fract(pO * 9.0) - 0.5); float flexWire = smoothstep(0.04, 0.01, min(vg.x, min(vg.y, vg.z))); vec3 alb = mix(vec3(0.18, 0.62, 0.88), vec3(0.95, 0.56, 0.24), smoothstep(-0.45, 0.45, pO.y)); meshCol = alb * (0.28 + 0.82 * diff) + vec3(0.98) * spec * 0.48 + vec3(0.26, 0.88, 0.96) * fres * 0.40; meshCol = mix(meshCol, vec3(0.92, 0.96, 1.0), flexWire * 0.22); } // Accumulate additive glow from the 3 orthogonal triplanes on the left side vec3 triVis = vec3(0.0); float tZ = -roO.z / (abs(rdO.z) < 1e-4 ? 1e-4 : rdO.z); if (tZ > 0.1 && (tZ < tHit || screenX < split)) { vec3 hp = roO + rdO * tZ; triVis += planeFeatureVis(hp.xy, vec3(0.18, 0.78, 1.0)); } float tY = -roO.y / (abs(rdO.y) < 1e-4 ? 1e-4 : rdO.y); if (tY > 0.1 && (tY < tHit || screenX < split)) { vec3 hp = roO + rdO * tY; triVis += planeFeatureVis(hp.xz, vec3(0.24, 0.96, 0.58)); } float tX = -roO.x / (abs(rdO.x) < 1e-4 ? 1e-4 : rdO.x); if (tX > 0.1 && (tX < tHit || screenX < split)) { vec3 hp = roO + rdO * tX; triVis += planeFeatureVis(hp.yz, vec3(0.98, 0.46, 0.22)); } if (screenX < split) { col = mix(col, meshCol * 0.55, tHit < 1e4 ? 0.65 : 0.0) + triVis * glow * 0.72; } else { col = meshCol + triVis * glow * 0.14; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Jiale Xu, Weihao Cheng, Yiming Gao, Xintao Wang, Shenghua Gao, Ying Shan (2024) InstantMesh: Efficient 3D Mesh Generation from a Single Image with Sparse-view Large Reconstruction Models. arXiv preprint (cs.CV). https://arxiv.org/abs/2404.07191 (verified via arxiv on 2026-11-29) 2. [implementation] TencentARC (2024) TencentARC/InstantMesh. https://github.com/TencentARC/InstantMesh License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "InstantMesh." https://texelatlas.vercel.app/t/instantmesh/ (accessed 2026-12-01). --- id: "intel-xess" title: "Intel XeSS" aliases: [XeSS, Xe Super Sampling] domain: "post" stage: "post" realtime: "realtime" platforms: [desktop-gpu, unreal, unity] year_introduced: 2022 inputs: [hdr-image, depth, gbuffer] outputs: [hdr-image] style: "both" dynamic: "dynamic" cost: "medium" authority: "intel, 2022" url: "https://texelatlas.vercel.app/t/intel-xess/" sources_verified_at: "2026-11-29" --- # Intel XeSS (intel, 2022) > A neural temporal upscaler: given a low-resolution jittered colour frame, depth and motion vectors, it reconstructs a higher-resolution image with an ML model that runs on Intel XMX units or generic GPUs via DP4a. ## Reach for it when - want to render at lower resolution and upscale with ml - need an upscaler that runs on non nvidia and non amd gpus - game runs below target framerate at native resolution - upscaled image ghosts on thin moving objects - add a third vendor upscaling option to my engine ## How it works Like other temporal super-resolution, the renderer draws at a lower internal resolution with a sub-pixel jitter each frame, and supplies colour, depth and motion vectors (plus an exposure value and a reset flag). XeSS reprojects previous high-resolution output with the motion vectors and feeds that history, together with the current jittered samples, to a convolutional network that decides per output pixel how much history to trust and how to combine it into a sharp, anti-aliased result. Quality presets (ultra quality to performance) set the internal-to-output scale. The same network ships in two forms: a full model on Intel Arc XMX matrix hardware and a lighter integer DP4a path for other vendors' GPUs. The SDK integrates through DX12, DX11 or Vulkan, and it exposes mip bias and jitter-sequence helpers for the host engine. ## When to use it Choose it when you want vendor-agnostic ML upscaling that works on Intel hardware best and on other GPUs reasonably, or to offer a third option beside [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) and [AMD FidelityFX Super Resolution](https://texelatlas.vercel.app/t/fidelityfx-super-resolution.md). Prefer [AMD FidelityFX Super Resolution](https://texelatlas.vercel.app/t/fidelityfx-super-resolution.md) for an open, non-ML spatial-temporal path with broad support, [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) on NVIDIA RTX for best quality and ray reconstruction, and plain [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) when you do not render below native resolution. ## Cost medium — Network inference at output resolution; the net frame time usually drops because internal rendering cost falls more than the upscale adds, but the gain depends on GPU and preset. Measured GPU Weight: 9.29× baseline (moderate) — 0.3056 ms median / 0.3129 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.48× baseline (moderate) — 0.1349 ms median (2.27× faster on L4). Ampere A100 scaling: 6.35× baseline (moderate) — 0.183 ms median (1.67× faster on A100). ## Failure modes - Ghosting and trails on thin moving objects, particles and transparent surfaces whose motion vectors are missing - Shimmering or flicker on fine repeating patterns and specular aliasing if jitter or mip bias is misconfigured - Disocclusion blur at the edges of moving objects, revealed regions have no history - DP4a path quality and speed lower than the XMX path, and is not identical across vendors - UI and post-effects applied before upscale (or noise added to colour) get smeared ## Engine support - unreal: plugin — `Install the Intel XeSS plugin and enable it` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/temporal-upscalers-in-unreal-engine, checked 2026-12-01) — Third-party plugin from Intel. ## Dataflow - Inputs: hdr-image, depth, gbuffer - Outputs: hdr-image - Platforms: desktop-gpu, unreal, unity ## Presets ### Intel XeSS — low-res jittered frame + motion vectors (left) vs temporal neural super-resolution with disocclusion clamping (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_JITTER_RES": 0.42, "P_TEMPORAL_W": 0.85, "P_FLOW_VIS": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_JITTER_RES = 0.42; // P Internal Scale [0.22, 0.75, 0.02] const float P_TEMPORAL_W = 0.85; // P History Weight [0.2, 0.95, 0.05] const float P_FLOW_VIS = 0.45; // P Motion Vector HUD [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P Input+MV / XeSS [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Rotating multi-spoke turbine + static grid backdrop (creates strong motion vectors & disocclusions) void evalTurbine(vec2 uv, float t, out vec3 col, out vec2 mv) { mv = vec2(0.0); // Crisp perspective blue-slate laboratory backdrop vec3 bg = mix(vec3(0.05, 0.08, 0.14), vec3(0.14, 0.24, 0.38), smoothstep(-0.5, 0.5, uv.y)); vec2 g = uv * 12.0; float grid = max(smoothstep(0.92, 0.98, fract(g.x)), smoothstep(0.92, 0.98, fract(g.y))); col = mix(bg, vec3(0.24, 0.56, 0.88), grid * 0.28); // Orbiting satellite sphere creating disocclusion trail over grid vec2 satPos = vec2(0.46 * cos(t * 0.95), 0.26 * sin(t * 1.25)); vec2 satVel = vec2(-0.46 * 0.95 * sin(t * 0.95), 0.26 * 1.25 * cos(t * 1.25)); vec2 sd = uv - satPos; float sr = length(sd); if (sr < 0.13) { float sz = sqrt(max(0.13 * 0.13 - sr * sr, 0.0)); vec3 sn = normalize(vec3(sd, sz)); vec3 sl = normalize(vec3(0.5, 0.7, 0.5)); float ndl = max(dot(sn, sl), 0.0); float spec = pow(max(dot(reflect(-sl, sn), vec3(0.0, 0.0, 1.0)), 0.0), 28.0); col = vec3(0.22, 0.78, 1.0) * (0.25 + 0.85 * ndl) + vec3(1.1) * spec; mv = satVel * 0.18; } // Central fast-spinning 12-blade metallic turbine rotor float r = length(uv); float omega = 1.35; if (r < 0.36) { vec2 rp = rot2(uv, -t * omega); float ang = atan(rp.y, rp.x); float blade = smoothstep(0.12, 0.26, cos(ang * 12.0 + r * 9.0)); float hub = smoothstep(0.11, 0.095, r); float rim = smoothstep(0.015, 0.0, abs(r - 0.335) - 0.012); float shade = 0.45 + 0.55 * cos(ang * 2.0 - 0.7); vec3 metal = mix(vec3(0.16, 0.22, 0.30), vec3(0.84, 0.90, 0.98), blade * shade); metal = mix(metal, vec3(0.12, 0.62, 1.0), rim * 0.85); metal = mix(metal, vec3(0.95, 0.55, 0.16), hub * (0.65 + 0.35 * sin(ang * 4.0))); float alpha = max(blade, max(hub, rim)); if (alpha > 0.08) { col = mix(col, metal, smoothstep(0.08, 0.35, alpha)); // Tangential velocity motion vector of spinning blade mv = vec2(-uv.y, uv.x) * omega * 0.45; } } } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float scale = clamp(P_JITTER_RES, 0.20, 0.80); float tempW = clamp(P_TEMPORAL_W, 0.1, 0.96); float flowVis = clamp(P_FLOW_VIS, 0.0, 1.0); vec3 col = vec3(0.0); if (screenX < split) { // Left: Low-resolution jittered input + subtle motion-vector direction arrows float cell = max(1.0 / scale, 1.6); float frameIdx = floor(iTime * 20.0); vec2 jit = vec2(fract(frameIdx * 0.6180339), fract(frameIdx * 0.3247179)) - 0.5; vec2 lowCoord = (floor(fragCoord / cell) + 0.5 + jit * 0.4) * cell; vec2 uvLow = (lowCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 mv; evalTurbine(uvLow, iTime, col, mv); // Visualize per-tile motion vectors as crisp directional ticks if (flowVis > 0.01) { vec2 tileSize = vec2(26.0); vec2 tileC = (floor(fragCoord / tileSize) + 0.5) * tileSize; vec2 uvTile = (tileC - 0.5 * iResolution.xy) / iResolution.y; vec3 dummy; vec2 mvTile; evalTurbine(uvTile, iTime, dummy, mvTile); float mvMag = length(mvTile); if (mvMag > 0.01) { vec2 local = (fragCoord - tileC) / 13.0; vec2 dir = mvTile / mvMag; float proj = clamp(dot(local, dir), 0.0, min(mvMag * 3.2, 0.85)); float distSeg = length(local - dir * proj); float arrow = smoothstep(0.11, 0.03, distSeg); vec3 mvCol = vec3(0.5 + 0.5 * dir.x, 0.5 + 0.5 * dir.y, 1.0); col = mix(col, mvCol * 1.4, arrow * flowVis * 0.85); } } } else { // Right: XeSS-style motion-reprojected jittered accumulation with neighborhood variance clamping vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 curCol; vec2 curMv; evalTurbine(uv, iTime, curCol, curMv); vec3 acc = vec3(0.0); float wTotal = 0.0; vec3 mn = curCol; vec3 mx = curCol; float dtStep = 0.016; for (int i = 0; i < 6; i++) { float fi = float(i); vec2 sub = vec2(fract(fi * 0.5 + 0.25), fract(fi * 0.3333 + 0.1667)) - 0.5; vec2 uvHist = (fragCoord + sub * 0.9 - 0.5 * iResolution.xy) / iResolution.y - curMv * (fi * dtStep * 0.12); vec3 hCol; vec2 hMv; evalTurbine(uvHist, iTime - fi * dtStep * 0.12, hCol, hMv); // Disocclusion rejection when motion vector diverges from current pixel float mvDiff = length(hMv - curMv); float w = pow(tempW, fi) * exp(-mvDiff * 14.0); acc += hCol * w; wTotal += w; mn = min(mn, hCol); mx = max(mx, hCol); } col = clamp(acc / max(wTotal, 1e-4), mn * 0.95, mx * 1.05); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) ## Combines with - [Contrast Adaptive Sharpening](https://texelatlas.vercel.app/t/contrast-adaptive-sharpening.md): A light sharpening pass after upscaling restores crispness that the reconstruction softens. ## Sources 1. [primary] intel (2022) intel/xess. https://github.com/intel/xess License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Intel XeSS." https://texelatlas.vercel.app/t/intel-xess/ (accessed 2026-12-01). --- id: "intrinsic-delaunay-triangulation" title: "Intrinsic Delaunay Triangulation" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, python] year_introduced: 2019 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "interactive" authority: "Sharp et al., 2019" url: "https://texelatlas.vercel.app/t/intrinsic-delaunay-triangulation/" sources_verified_at: "2026-11-29" --- # Intrinsic Delaunay Triangulation (Sharp et al., 2019) > Re-triangulates a mesh purely through its edge lengths, flipping edges until the Delaunay condition holds, without moving vertices. Gives a high-quality Laplacian and robust geometry processing on bad triangulations. ## Reach for it when - laplacian or heat solve is unstable on skinny triangles - scanned mesh has bad triangulation for geometry processing - need better weights without moving vertices - poor interpolation on marching-cubes output ## How it works An intrinsic triangulation is defined by edge lengths and combinatorics, not by embedded positions; every triangle is a flat triangle with those lengths, glued to its neighbours. An edge flip replaces the shared diagonal of two triangles with the other diagonal. The new length is computed from the unfolded quad in the plane, and the geometry of the surface is unchanged because the new edge is a geodesic across the old triangles. Flip edges that violate the Delaunay condition (opposite angle sum greater than pi) until none remain; the process terminates and the resulting cotan Laplacian has non-negative weights. A signpost or normal-coordinate data structure tracks how the new edges cross the original mesh, so functions can be mapped between the two triangulations. ## When to use it Choose it before solving a Laplace, Poisson or heat problem on a mesh with skinny triangles (scans, marching-cubes output, CAD tessellations) to get stable weights and better interpolation. Prefer [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md) when you also want a new embedded mesh, and [Tufted Cover Laplacian](https://texelatlas.vercel.app/t/tufted-laplacian.md) when the mesh is non-manifold or has holes and disconnected parts. ## Cost interactive — Linear-time flipping in practice; additional bookkeeping for the mapping to the original mesh. ## Failure modes - Does not change the embedded geometry, so rendering still sees bad triangles - Edge flips can create paths that wind through many original faces, which slows later queries - Requires manifold, oriented surfaces - Implementation needs careful treatment of numerical robustness in the unfolding ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, python ## Combines with - [Heat Method for Geodesic Distance](https://texelatlas.vercel.app/t/heat-method-geodesics.md): Better Laplacian yields more accurate heat-method distances. ## Sources 1. [primary] Nicholas Sharp, Yousuf Soliman, Keenan Crane (2019) Navigating intrinsic triangulations. ACM Transactions on Graphics. https://doi.org/10.1145/3306346.3322979 (verified via crossref on 2026-11-29) 2. [implementation] nmwsharp (2017) nmwsharp/geometry-central. https://github.com/nmwsharp/geometry-central License: MIT. (verified via github on 2026-11-29) 3. [implementation] MarkGillespie (2021) MarkGillespie/intrinsic-triangulations-demo. https://github.com/MarkGillespie/intrinsic-triangulations-demo License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Intrinsic Delaunay Triangulation." https://texelatlas.vercel.app/t/intrinsic-delaunay-triangulation/ (accessed 2026-12-01). --- id: "inverted-hull-outline" title: "Inverted-hull outlines" domain: "npr" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1999 inputs: [mesh, normals] outputs: [mesh, ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Raskar & Cohen, 1999" url: "https://texelatlas.vercel.app/t/inverted-hull-outline/" sources_verified_at: "2026-11-29" --- # Inverted-hull outlines (Raskar & Cohen, 1999) > Draws a second copy of the mesh pushed outward along its normals with front faces culled, so only a thin back-facing shell peeks out as a contour line. ## Reach for it when - need cartoon outlines around characters cheaply - want controllable line thickness per vertex - outline without a post-process pass - toon characters need a black contour - stylised game silhouette lines ## How it works The mesh is rendered twice. The second pass extrudes each vertex along its normal by a small width in the vertex shader, flips culling to discard front faces, and fills the result with a flat line colour. Because the shell is behind the original surface, depth testing leaves only a rim visible around the silhouette. Width can be scaled with distance to the camera or in clip space to keep a constant pixel thickness. Meshes with split normals at hard edges open gaps in the shell, so the extrusion direction is usually read from smoothed normals baked into a vertex colour or a second UV set. The idea builds on image-precision silhouette rendering, where back faces are drawn offset to expose contours. ## When to use it Choose it for characters and props in real-time games where you want controllable per-vertex line width and no post-process. Prefer [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md) for outlining interior creases and for scenes you cannot re-render, and [Jump-flood wide outlines](https://texelatlas.vercel.app/t/jump-flood-outline.md) when you need wide, uniform-width lines around arbitrary selection masks. Prefer [Suggestive contours](https://texelatlas.vercel.app/t/suggestive-contours.md) for view-dependent interior lines on smooth surfaces. ## Cost cheap — Costs a second geometry pass, roughly doubling vertex work for outlined meshes; fill cost is small. Measured GPU Weight: 2.29× baseline (light) — 0.0752 ms median / 0.0789 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.01× baseline (light) — 0.032 ms median (2.35× faster on L4). Ampere A100 scaling: 1.56× baseline (feather) — 0.0449 ms median (1.67× faster on A100). ## Failure modes - Hard-edged meshes (cubes) split into disconnected shells unless smoothed normals are baked - Thickness varies with scale and perspective unless corrected in clip space - Only silhouettes: interior creases and overlapping parts get no line - Thin geometry such as hair planes produces double lines or poke-through ## Engine support - babylonjs: builtin — `mesh.renderOutline = true; mesh.outlineWidth / outlineColor` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Rendering/outlineRenderer.ts, checked 2026-12-01) - blender: builtin — `Solidify modifier > Normals > Flip + Material Offset with Backface Culling` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/generate/solidify.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.grow = true on a next_pass material with cull_mode = CULL_FRONT` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: official — `import { OutlineEffect } from 'three/addons/effects/OutlineEffect.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/effects/OutlineEffect.js, checked 2026-12-01) - unity: official — `Unity Toon Shader > Outline > Outline Mode = Normal Direction` (evidence: https://github.com/Unity-Technologies/com.unity.toonshader, checked 2026-12-01) — Official Unity Toon Shader package. ## Dataflow - Inputs: mesh, normals - Outputs: mesh, ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: toon shading. Right: inverted-hull outline (shell pushed out along normals, only its back faces show) (glsl-fragment; rendered 2026-11-29) ```json { "W": 0.035 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float W=0.035; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t;vec3 q;float sh=isect(P+n*2e-3,LD,q)>1e8?1.:0.; float b=floor(clamp(dot(n,LD)*sh,0.,.999)*3.)/2.; col=mix(col,alb(P)*(.35+.65*b),1.);col=mix(col,sky(rd),smoothstep(6.,25.,t)); } if(R){ float th=1e9; for(int i=0;i<3;i++){vec3 oc=RO-SP[i].xyz;float bq=dot(oc,rd),r=SP[i].w+W,c=dot(oc,oc)-r*r,h=bq*bq-c; if(h>0.){float tf=-bq+sqrt(h);if(tf>0.)th=min(th,tf);}} if(th Computes expensive diffuse indirect irradiance only at sparse surface points and interpolates between them, placing samples more densely near geometry where lighting changes quickly. ## Reach for it when - path tracing diffuse bounce is slow and noisy - indirect lighting computed too often in smooth areas - speed up offline gi for diffuse interiors - reuse indirect light between nearby surface points ## How it works Diffuse indirect light varies slowly over open surfaces and quickly near corners and occluders. Irradiance caching exploits this by computing the hemispherical integral (with hundreds of rays) only at selected points and reusing it for neighbours. When a shading point `x` needs indirect light, the renderer searches an **octree** of earlier cache records. A record at `p` with normal `n_p` and **validity radius** `R_p` (tied to the harmonic mean distance to surfaces seen from `p`) contributes a weight `w = 1 / (|x - p| / R_p + sqrt(1 - n . n_p))`. If the summed weights exceed a threshold, the result is the weighted average of the contributing records. Otherwise a new record is computed and inserted. Because the validity radius is proportional to the distance of nearby geometry, cache records are dense in corners and sparse on flat walls. **Irradiance gradients** (translational and rotational) extrapolate each record's value linearly, which allows larger spacing and smoother results. ## When to use it Choose it for offline diffuse GI where final gathering at every pixel is too expensive, such as in a classic ray-tracing renderer or baker with photon maps. Prefer [path-tracing](path-tracing) when you want unbiased, simpler code and cost is acceptable. Prefer [lightmap-baking](lightmap-baking) when the output should live in texture space for real-time use. Prefer [surfel-gi](surfel-gi) when you want the same idea (sparse cached surface irradiance) at runtime and dynamically. ## Cost offline — Reduces indirect rays per pixel by one to two orders of magnitude on smooth scenes; cost depends on the error threshold. Measured GPU Weight: 89.1× baseline (extreme) — 2.7621 ms median / 2.8965 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 80.71× baseline (extreme) — 1.2833 ms median (2.15× faster on L4). Ampere A100 scaling: 61.3× baseline (extreme) — 1.7654 ms median (1.56× faster on A100). ## Failure modes - Splotchy low-frequency artifacts where record spacing is coarse and interpolation is visible - Light leaks at thin geometry because records near a wall can be applied to the other side - Not view-independent in practice: sampling order shows as temporal inconsistency in animation, so caches must be shared across frames - Diffuse only; poor for glossy indirect lighting ## Engine support - blender: builtin — `EEVEE Light Probe > Volume bakes and caches indirect diffuse irradiance in eevee_lightprobe_volume.cc` (evidence: https://github.com/blender/blender/blob/main/source/blender/draw/engines/eevee/eevee_lightprobe_volume.cc, checked 2026-12-01) - unreal: builtin — `World Settings > Lightmass > Volumetric Lightmaps cache precomputed indirect irradiance probes in a 3D brick hierarchy` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/volumetric-lightmaps-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params - Outputs: irradiance-probes - Platforms: cpu ## Presets ### Irradiance Caching — sparse Ward cache records & validity radii (left) vs smooth gradient GI (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ERROR_TOL": 0.55, "P_CACHE_VIS": 1, "P_GI_GAIN": 1.25, "P_SPLIT": 0.48 } ``` ```glsl const float P_ERROR_TOL = 0.55; // P Error Tolerance a [0.2, 1.2, 0.03] const float P_CACHE_VIS = 1.0; // P Cache Overlay [0.0, 1.5, 0.05] const float P_GI_GAIN = 1.25; // P Indirect Gain [0.3, 2.2, 0.05] const float P_SPLIT = 0.48; // P Records / Smooth Split [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); } vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } 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); } vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); float dC = 1.05 - p.y; if (dC < res.x) res = vec2(dC, 1.0); float dB = p.z + 1.38; if (dB < res.x) res = vec2(dB, 1.0); float dL = p.x + 1.28; if (dL < res.x) res = vec2(dL, 2.0); float dR = 1.28 - p.x; if (dR < res.x) res = vec2(dR, 3.0); float dArch = sdBox(p - vec3(-0.35, -0.35, -0.35), vec3(0.28, 0.50, 0.28)) - 0.02; if (dArch < res.x) res = vec2(dArch, 4.0); float dSph = length(p - vec3(0.42, -0.49, -0.10)) - 0.36; if (dSph < res.x) res = vec2(dSph, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Harmonic-mean distance R_i proxy: shrinks tightly in creases/corners, grows wide on open walls float harmonicRadius(vec3 p, vec3 n) { float h1 = max(mapScene(p + n * 0.16).x, 0.02); float h2 = max(mapScene(p + n * 0.42).x, 0.04); float crease = clamp((h1 / 0.16) * 0.55 + (h2 / 0.42) * 0.45, 0.18, 1.0); return 0.10 + 0.26 * crease; } vec3 evalIndirect(vec3 p, vec3 n) { float wL = clamp(1.0 - (p.x + 1.28) * 0.52, 0.0, 1.0); float wR = clamp(1.0 - (1.28 - p.x) * 0.52, 0.0, 1.0); vec3 warm = vec3(0.95, 0.36, 0.14) * wL * (0.45 + 0.55 * max(dot(n, vec3(1.0, 0.0, 0.0)), 0.0)); vec3 cool = vec3(0.16, 0.74, 0.88) * wR * (0.45 + 0.55 * max(dot(n, vec3(-1.0, 0.0, 0.0)), 0.0)); vec3 sky = vec3(0.32, 0.34, 0.38) * (0.45 + 0.55 * max(n.y, 0.0)); float ao = clamp(0.38 + 0.62 * mapScene(p + n * 0.25).x / 0.25, 0.18, 1.0); return (warm * 0.58 + cool * 0.58 + sky * 0.48) * ao; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSmooth = screenX >= split; float errTol = clamp(P_ERROR_TOL, 0.18, 1.25); float cacheVis = clamp(P_CACHE_VIS, 0.0, 1.5); float giGain = clamp(P_GI_GAIN, 0.2, 2.4); vec3 ro = vec3(0.0, 0.02, 2.34); vec3 rd = normalize(vec3(uv, -1.50)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = vec3(0.78, 0.78, 0.80); if (matId > 1.5 && matId < 2.5) alb = vec3(0.92, 0.34, 0.16); if (matId > 2.5 && matId < 3.5) alb = vec3(0.14, 0.72, 0.84); vec3 lPos = vec3(0.18 * sin(iTime * 0.65), 0.94, -0.25); vec3 lDir = normalize(lPos - p); float direct = max(dot(n, lDir), 0.0) * 0.58; vec3 smoothGI = evalIndirect(p, n) * giGain; // Adaptive spatial hash placing Ward irradiance cache samples denser near creases (small R_i) float rHarm = harmonicRadius(p, n) * (0.55 + 0.85 * errTol); float cellSz = max(rHarm * 0.92, 0.08); vec3 cid = floor(p / cellSz); float minDist = 1e5; float ringVis = 0.0; vec3 nearestIrr = smoothGI; float nearestRad = rHarm; // Search 3x3x3 neighborhood of 3D cache cells to find nearest surface records & Ward weights vec3 wIrr = vec3(0.0); float wSum = 0.0; for (int dz = -1; dz <= 1; dz++) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec3 nb = cid + vec3(float(dx), float(dy), float(dz)); vec3 rnd = hash33(nb); vec3 cPos = (nb + 0.15 + 0.70 * rnd) * cellSz; // Project record onto tangent plane of p so it sits on the surface vec3 cSurf = cPos - n * dot(cPos - p, n); float d = length(p - cSurf); float rValid = cellSz * 0.72; if (d < minDist) { minDist = d; nearestIrr = evalIndirect(cSurf, n) * giGain; nearestRad = rValid; } // Ward weighting function w_i(p) = 1 / (d / R_i + sqrt(1 - n.n_i)) - 1/a float w = max(1.0 / (d / max(rValid, 0.04) + 0.15) - 1.0 / (1.0 + errTol * 2.2), 0.0); wIrr += evalIndirect(cSurf, n) * giGain * w; wSum += w; ringVis = max(ringVis, smoothstep(0.012, 0.003, abs(d - rValid * 0.65))); } } } vec3 interpGI = (wSum > 1e-4) ? (wIrr / wSum) : smoothGI; vec3 finalGI = mix(nearestIrr, interpGI, isSmooth ? 0.92 : 0.35); col = alb * (direct + finalGI); if (!isSmooth) { // Left: visualize cache sample centers (bright gold dots) & validity circles (cyan) float dotMask = smoothstep(0.024, 0.011, minDist); col = mix(col, vec3(0.22, 0.92, 1.0), ringVis * 0.42 * min(cacheVis, 1.2)); col = mix(col, vec3(1.0, 0.88, 0.32), dotMask * 0.92 * min(cacheVis, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Photon Mapping](https://texelatlas.vercel.app/t/photon-mapping.md): Final gathering at cache points uses photon-map irradiance rather than tracing every ray. ## Combination ideas - [Owen-scrambled Sobol hemisphere sampling for blotch-free irradiance caches](https://texelatlas.vercel.app/ideas/sobol-stratified-irradiance-cache/) ## Sources 1. [primary] Gregory J. Ward, Francis M. Rubinstein, Robert D. Clear (1988) A ray tracing solution for diffuse interreflection. Proceedings of the 15th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/54852.378490 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Irradiance Caching." https://texelatlas.vercel.app/t/irradiance-caching/ (accessed 2026-12-01). --- id: "irradiance-volumes" title: "Irradiance Volumes and Light Probes" aliases: [light probes, ambient cubes, probe grids] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1998 inputs: [irradiance-probes, mesh] outputs: [irradiance-probes] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Greger et al., 1998" url: "https://texelatlas.vercel.app/t/irradiance-volumes/" sources_verified_at: "2026-11-29" --- # Irradiance Volumes and Light Probes (Greger et al., 1998) > Stores precomputed irradiance at points in space (often as low-order spherical harmonics) and interpolates between them to light moving objects with indirect light consistent with the baked environment. ## Reach for it when - dynamic characters look unlit in baked scenes - moving props don't pick up indirect light - need bounce light on objects without lightmaps - fog and particles need indirect lighting in baked levels ## How it works A light probe records how much light arrives at a point from each direction, compressed into a handful of coefficients, usually L1 or L2 [spherical-harmonics-lighting](spherical-harmonics-lighting) or a six-sided **ambient cube**. Probes are placed on a regular grid, on an adaptive tetrahedral mesh, or by hand near interesting lighting changes. Baking computes each probe's radiance from a skyline and scene capture (or an offline [path-tracing](path-tracing) of the neighbourhood) and projects it into the basis. At runtime an object finds the probes surrounding it, interpolates their coefficients (trilinearly in a grid, barycentrically in a tetrahedralization), and evaluates the irradiance for its normal in the shader. Because only a few numbers per probe are needed, thousands fit in a small buffer. Common refinements: visibility-aware interpolation to prevent probes on the wrong side of a wall from contributing, **adaptive probe volumes** that subdivide where lighting varies, and runtime-updated probes ([ddgi](ddgi)) for dynamic GI. ## When to use it Choose it for lighting dynamic characters and props in baked scenes, and for adding indirect light to volumes (fog, particles) where lightmaps cannot go. Prefer [lightmap-baking](lightmap-baking) for large static surfaces where per-texel detail is needed. Prefer [ddgi](ddgi) when the probes must update at runtime. Prefer [precomputed-radiance-transfer](precomputed-radiance-transfer) when objects need self-shadowing under changing low-frequency light. Prefer [spherical-harmonics-lighting](spherical-harmonics-lighting) alone when a single global environment is enough. ## Cost cheap — Per-pixel cost is interpolating a few coefficient sets; memory and bake time scale with probe count. Measured GPU Weight: 25.92× baseline (heavy) — 0.814 ms median / 0.8577 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 26.59× baseline (heavy) — 0.4201 ms median (1.94× faster on L4). Ampere A100 scaling: 17.17× baseline (moderate) — 0.4945 ms median (1.65× faster on A100). ## Failure modes - Light leaking when interpolation mixes probes separated by a wall - Low-order SH gives soft, low-contrast lighting that cannot represent sharp shadows or strong directional light, and can ring (negative lobes) - Pop or discontinuity when an object switches tetrahedron or crosses a probe-volume boundary - Probe placement inside geometry produces black or wrong probes unless invalid ones are detected and filled ## Engine support - blender: builtin — `Add > Light Probe > Volume, then Bake Light Caches (EEVEE)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_probes/volume.html, checked 2026-12-01) - godot: builtin — `Add LightmapProbe nodes under a baked LightmapGI for dynamic objects` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/LightmapProbe.xml, checked 2026-12-01) - threejs: official — `import { LightProbeGrid } from 'three/addons/lighting/LightProbeGrid.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/lighting/LightProbeGrid.js, checked 2026-12-01) - unity: builtin — `GameObject > Light > Adaptive Probe Volume (or Light Probe Group)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/probevolumes.md, checked 2026-12-01) — Adaptive Probe Volumes (baked) and Light Probe Groups, URP and HDRP. - unreal: builtin — `Volumetric Lightmaps built by Lightmass (World Settings > Lightmass > Volume Lighting Sample Placement Scale)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/volumetric-lightmaps-in-unreal-engine, checked 2026-12-01) — Precomputed SH volumetric lightmap. ## Dataflow - Inputs: irradiance-probes, mesh - Outputs: irradiance-probes - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Irradiance Volumes & Light Probes — 3D trilinear SH probe lattice & directional probe spheres (glsl-fragment; rendered 2026-11-30) ```json { "P_PROBE_SIZE": 0.11, "P_GI_STRENGTH": 1.25, "P_SUN_SWEEP": 1, "P_SH_CONTRAST": 1 } ``` ```glsl const float P_PROBE_SIZE = 0.11; // P Probe Sphere Size [0.0, 0.18, 0.005] const float P_GI_STRENGTH = 1.25; // P Volume GI Gain [0.2, 2.4, 0.05] const float P_SUN_SWEEP = 1.0; // P Sun Motion [0.0, 2.5, 0.05] const float P_SH_CONTRAST = 1.0; // P SH Directionality [0.2, 1.8, 0.05] 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); } // Architectural gallery + 3x2x2 lattice of floating SH light-probe spheres vec2 mapScene(vec3 p, float probeR) { vec2 res = vec2(1.0 + p.y, 1.0); // floor float cD = 1.0 - p.y; if (cD < res.x) res = vec2(cD, 1.0); float bD = 1.50 + p.z; if (bD < res.x) res = vec2(bD, 1.0); float lD = 1.50 + p.x; if (lD < res.x) res = vec2(lD, 2.0); // warm amber-crimson wall float rD = 1.50 - p.x; if (rD < res.x) res = vec2(rD, 3.0); // cool azure wall // Central matte sculpture pedestal float dPed = sdBox(p - vec3(0.0, -0.62, -0.35), vec3(0.42, 0.38, 0.34)) - 0.025; if (dPed < res.x) res = vec2(dPed, 4.0); float dStat = length(p - vec3(0.0, -0.02, -0.35)) - 0.26; if (dStat < res.x) res = vec2(dStat, 4.0); // Visible 3D irradiance probe lattice (3 in X, 2 in Y, 2 in Z) if (probeR > 0.005) { vec3 q = p - vec3(0.0, 0.05, -0.25); vec3 id = clamp(floor(q / vec3(0.88, 0.78, 0.85) + 0.5), vec3(-1.0, 0.0, -1.0), vec3(1.0, 1.0, 0.0)); vec3 cellC = id * vec3(0.88, 0.78, 0.85) + vec3(0.0, 0.05, -0.25); float dProbe = length(p - cellC) - probeR; if (dProbe < res.x) res = vec2(dProbe, 5.0); } return res; } vec3 calcNormal(vec3 p, float probeR) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy, probeR).x - mapScene(p - e.xyy, probeR).x, mapScene(p + e.yxy, probeR).x - mapScene(p - e.yxy, probeR).x, mapScene(p + e.yyx, probeR).x - mapScene(p - e.yyx, probeR).x )); } // Evaluate L0 + L1 Spherical Harmonics irradiance at a single 3D probe location probePos in direction dir vec3 evalSHProbe(vec3 probePos, vec3 dir, vec3 sunPos, float shContrast) { // L0 isotropic ambient base vec3 l0 = vec3(0.14, 0.16, 0.21); // Directional SH lobes from warm crimson left wall, azure right wall, skylight ceiling, and moving sun bounce float wLeft = exp(-max(probePos.x + 1.5, 0.0) * 0.75); float wRight = exp(-max(1.5 - probePos.x, 0.0) * 0.75); float wCeil = exp(-max(1.0 - probePos.y, 0.0) * 0.85); vec3 toSun = sunPos - probePos; float rSun = length(toSun) + 0.45; vec3 dirSun = toSun / max(length(toSun), 1e-4); // Cosine-convolved SH basis: 0.5 + 0.5 * dot(dir, sourceDir) float cL = mix(0.5, max(dot(dir, vec3(-1.0, 0.0, 0.0)), 0.0), clamp(shContrast, 0.1, 1.5)); float cR = mix(0.5, max(dot(dir, vec3(1.0, 0.0, 0.0)), 0.0), clamp(shContrast, 0.1, 1.5)); float cU = mix(0.5, max(dot(dir, vec3(0.0, 1.0, 0.0)), 0.0), clamp(shContrast, 0.1, 1.5)); float cS = mix(0.5, max(dot(dir, dirSun), 0.0), clamp(shContrast, 0.1, 1.5)); vec3 irr = l0; irr += vec3(1.18, 0.26, 0.14) * wLeft * cL * 1.15; irr += vec3(0.14, 0.56, 1.18) * wRight * cR * 1.15; irr += vec3(0.65, 0.78, 0.96) * wCeil * cU * 0.55; irr += vec3(1.45, 1.12, 0.56) * cS / (rSun * rSun * 0.75 + 0.35); return irr; } // Trilinear interpolation across the 3D irradiance probe volume grid vec3 sampleIrradianceVolume(vec3 p, vec3 n, vec3 sunPos, float shContrast) { vec3 stepSz = vec3(0.88, 0.78, 0.85); vec3 q = (p - vec3(0.0, 0.05, -0.25)) / stepSz; vec3 b = floor(q); vec3 f = fract(q); vec3 o = vec3(0.0, 0.05, -0.25); vec3 p000 = evalSHProbe((b + vec3(0.0, 0.0, 0.0)) * stepSz + o, n, sunPos, shContrast); vec3 p100 = evalSHProbe((b + vec3(1.0, 0.0, 0.0)) * stepSz + o, n, sunPos, shContrast); vec3 p010 = evalSHProbe((b + vec3(0.0, 1.0, 0.0)) * stepSz + o, n, sunPos, shContrast); vec3 p110 = evalSHProbe((b + vec3(1.0, 1.0, 0.0)) * stepSz + o, n, sunPos, shContrast); vec3 p001 = evalSHProbe((b + vec3(0.0, 0.0, 1.0)) * stepSz + o, n, sunPos, shContrast); vec3 p101 = evalSHProbe((b + vec3(1.0, 0.0, 1.0)) * stepSz + o, n, sunPos, shContrast); vec3 p011 = evalSHProbe((b + vec3(0.0, 1.0, 1.0)) * stepSz + o, n, sunPos, shContrast); vec3 p111 = evalSHProbe((b + vec3(1.0, 1.0, 1.0)) * stepSz + o, n, sunPos, shContrast); vec3 x00 = mix(p000, p100, f.x); vec3 x10 = mix(p010, p110, f.x); vec3 x01 = mix(p001, p101, f.x); vec3 x11 = mix(p011, p111, f.x); return mix(mix(x00, x10, f.y), mix(x01, x11, f.y), f.z); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float tAnim = iTime * max(P_SUN_SWEEP, 0.0); float probeR = clamp(P_PROBE_SIZE, 0.0, 0.20); float giGain = max(P_GI_STRENGTH, 0.0); float shCon = clamp(P_SH_CONTRAST, 0.15, 1.8); vec3 ro = vec3(0.28 * sin(tAnim * 0.35), 0.16, 2.35); vec3 ta = vec3(0.0, -0.05, -0.45); vec3 fw = normalize(ta - ro); vec3 rt = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(rt, fw); vec3 rd = normalize(fw * 1.48 + rt * uv.x + up * uv.y); vec3 sunPos = vec3(0.95 * cos(tAnim * 0.65), 0.72, -0.35 + 0.55 * sin(tAnim * 0.65)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 68; i++) { vec2 h = mapScene(ro + rd * t, probeR); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, probeR); if (matId > 4.5) { // Light Probe visualization sphere: directly displays its stored directional SH irradiance E(n)! vec3 shVis = evalSHProbe(p, n, sunPos, shCon) * giGain; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); col = shVis + vec3(0.85, 0.92, 1.0) * rim * 0.35; } else { vec3 alb = vec3(0.76, 0.76, 0.74); if (matId > 1.5 && matId < 2.5) alb = vec3(0.88, 0.22, 0.14); else if (matId > 2.5 && matId < 3.5) alb = vec3(0.14, 0.46, 0.88); else if (matId > 3.5) alb = vec3(0.86, 0.85, 0.83); // Direct light from moving overhead warm lamp vec3 toL = sunPos - p; float dL = length(toL); vec3 lDir = toL / max(dL, 1e-4); float diff = max(dot(n, lDir), 0.0); vec3 direct = alb * vec3(1.9, 1.65, 1.25) * diff / (1.0 + 0.55 * dL * dL); // Trilinearly interpolated 3D Irradiance Volume GI vec3 irr = sampleIrradianceVolume(p, n, sunPos, shCon); col = direct + alb * irr * giGain * 0.72; } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Lightmap Baking](https://texelatlas.vercel.app/t/lightmap-baking.md): Lightmaps cover static surfaces; the same bake feeds probes for moving objects. ## Sources 1. [primary] G. Greger, P. Shirley, P.M. Hubbard, D.P. Greenberg (1998) The irradiance volume. IEEE Computer Graphics and Applications. https://doi.org/10.1109/38.656788 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Irradiance Volumes and Light Probes." https://texelatlas.vercel.app/t/irradiance-volumes/ (accessed 2026-12-01). --- id: "isotropic-remeshing" title: "Isotropic Remeshing" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, blender] year_introduced: 2004 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "offline" authority: "Botsch & Kobbelt, 2004" url: "https://texelatlas.vercel.app/t/isotropic-remeshing/" sources_verified_at: "2026-11-29" --- # Isotropic Remeshing (Botsch & Kobbelt, 2004) > Iteratively splits long edges, collapses short ones, flips edges toward valence six and relaxes vertices tangentially, driving a triangle mesh to near-equilateral triangles of a target edge length. ## Reach for it when - marching cubes output has thin sliver triangles - mesh triangles vary wildly in size - simulation blows up on badly shaped triangles - need even triangle size before sculpting or smoothing - want near-equilateral triangles at a target edge length ## How it works Pick a target edge length L. Then loop: (1) split every edge longer than 4/3 L at its midpoint; (2) collapse every edge shorter than 4/5 L, unless that makes a longer edge; (3) flip edges when doing so reduces total deviation of vertex valence from six (four on the boundary); (4) move each vertex a step toward the centroid of its neighbours, projected onto the tangent plane; (5) reproject vertices back onto the original surface so the shape does not drift. A few iterations suffice. Feature edges and boundaries are pinned or only moved along their curve. Adaptive variants make L depend on curvature. ## When to use it Choose it before simulation, smoothing, sculpting or parametrization when you need triangles of even size and shape, for example to fix marching-cubes slivers. Prefer [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md) when only fewer triangles matter, [Instant Field-Aligned Meshes](https://texelatlas.vercel.app/t/instant-meshes.md) or [QuadriFlow](https://texelatlas.vercel.app/t/quadriflow.md) when you want a quad mesh with aligned edge flow. ## Cost offline — Several passes over the mesh with a spatial structure for reprojection; seconds for hundreds of thousands of triangles on CPU. Measured GPU Weight: 19.39× baseline (moderate) — 0.601 ms median / 0.6377 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 15.89× baseline (moderate) — 0.2527 ms median (2.38× faster on L4). Ampere A100 scaling: 11.47× baseline (moderate) — 0.3304 ms median (1.82× faster on A100). ## Failure modes - Sharp features blur or get eaten unless feature edges are detected and constrained - Tangential relaxation can drift thin structures without proper reprojection - Does not respect existing UVs; seams must be pinned - A uniform target length wastes triangles on flat areas and under-resolves fine details ## Engine support - unreal: builtin — `Modeling Mode > Mesh > Remesh (and GeometryScriptRemeshOptions)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/modeling-tools-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, blender ## Presets ### Isotropic Remeshing — skinny stretched triangles (left) vs uniform equilateral valence-6 mesh (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TARGET_EDGE": 11, "P_WIRE_VIS": 1, "P_ROT_SPEED": 0.7, "P_SPLIT": 0.48 } ``` ```glsl const float P_TARGET_EDGE = 11.0; // P Target Edge Inv [6.0, 20.0, 1.0] const float P_WIRE_VIS = 1.0; // P Wire Contrast [0.2, 1.5, 0.05] const float P_ROT_SPEED = 0.70; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Skinny / Isotropic [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } // Sculpted saddle torus-peanut manifold where naive UV triangulation creates extreme aspect-ratio slivers float mapManifold(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.55) * q.xz; q.xy = rot2(0.52) * q.xy; float dTor = sdTorus(q, vec2(0.54, 0.25 + 0.04 * sin(atan(q.z, q.x) * 3.0))); return dTor * 0.85; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0020, 0.0); return normalize(vec3( mapManifold(p + e.xyy, spin) - mapManifold(p - e.xyy, spin), mapManifold(p + e.yxy, spin) - mapManifold(p - e.yxy, spin), mapManifold(p + e.yyx, spin) - mapManifold(p - e.yyx, spin) )); } // Equilateral triangular lattice wireframe in 2D tangent space (valence-6 uniform triangles!) float equilateralWire(vec2 p) { // Skew into 60-degree simplex lattice vec2 q = vec2(p.x - p.y * 0.57735027, p.y * 1.15470054); vec2 f = fract(q); float d1 = min(f.x, 1.0 - f.x); float d2 = min(f.y, 1.0 - f.y); float d3 = abs(f.x + f.y - 1.0) * 0.7071; return smoothstep(0.055, 0.012, min(min(d1, d2), d3)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isIso = screenX >= split; float freq = clamp(floor(P_TARGET_EDGE + 0.5), 6.0, 22.0); float wireVis = clamp(P_WIRE_VIS, 0.1, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.025, 0.035, 0.058), vec3(0.072, 0.092, 0.140), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapManifold(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 7.5) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.55) * objP.xz; objP.xy = rot2(0.52) * objP.xy; // Toroidal angles (u around major circle, v around minor tube) float uAng = atan(objP.z, objP.x); float rMaj = length(objP.xz) - 0.54; float vAng = atan(objP.y, rMaj); vec3 l1 = normalize(vec3(0.58, 0.82, 0.54)); vec3 l2 = normalize(vec3(-0.72, -0.22, 0.50)); float diff = max(dot(n, l1), 0.0) * 0.85 + max(dot(n, l2), 0.0) * 0.25; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 48.0); if (!isIso) { // Left: Raw non-uniform mesh with skinny stretched sliver triangles (aspect ratio > 4:1) vec2 stretched = vec2(uAng * 0.85 * freq / 3.1415926 + sin(vAng * 2.0) * 0.45, vAng * 3.8 * freq / 6.2831853); // Irregular vertex jitter creating pinched high-valence hubs & thin slivers stretched.x += 0.35 * sin(vAng * 5.0 + uAng * 2.0); float wireBad = equilateralWire(stretched); float badQuality = clamp(0.45 + 0.55 * abs(sin(uAng * 2.0 + vAng * 3.0)), 0.0, 1.0); vec3 qualityCol = mix(vec3(0.92, 0.58, 0.18), vec3(0.94, 0.24, 0.20), badQuality); col = qualityCol * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.40; col = mix(col, vec3(0.14, 0.04, 0.04), wireBad * 0.78 * min(wireVis, 1.2)); } else { // Right: Isotropic remeshing (arc-length scaled equal-edge equilateral triangles, valence-6!) // Arc-length around major circle ~ 2*pi*0.54, around tube ~ 2*pi*0.25 => exact 2.16:1 ratio! vec2 isoCoord = vec2(uAng * (freq * 2.16) / 6.2831853, vAng * freq / 6.2831853); float wireIso = equilateralWire(isoCoord); vec3 goodCol = vec3(0.16, 0.78, 0.68); col = goodCol * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.50; col = mix(col, vec3(0.03, 0.12, 0.14), wireIso * 0.72 * min(wireVis, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): A BVH accelerates the closest-point reprojection back onto the source surface. ## Combination ideas - [Watertight scan-to-simulation pipeline via Poisson reconstruction and isotropic remeshing](https://texelatlas.vercel.app/ideas/poisson-reconstructed-isotropic-remesh/) ## Sources 1. [primary] Mario Botsch, Leif Kobbelt (2004) A remeshing approach to multiresolution modeling. Proceedings of the 2004 Eurographics/ACM SIGGRAPH symposium on Geometry processing. https://doi.org/10.1145/1057432.1057457 (verified via crossref on 2026-11-29) 2. [implementation] pmp-library (2017) pmp-library/pmp-library. https://github.com/pmp-library/pmp-library License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Isotropic Remeshing." https://texelatlas.vercel.app/t/isotropic-remeshing/ (accessed 2026-12-01). --- id: "joint-non-local-means-denoising" title: "Joint Non-Local Means (JNLM) Path-Tracing Denoiser" aliases: [JNLM, non-local means Monte Carlo denoising, feature-guided NLM denoising] domain: "post" stage: "post" realtime: "interactive" platforms: [webgpu, webgl2, desktop-gpu, cuda, cpu] year_introduced: 2012 inputs: [hdr-image, gbuffer, normals, depth] outputs: [hdr-image] style: "photoreal" dynamic: "both" cost: "heavy" authority: "Rousselle et al., 2012" url: "https://texelatlas.vercel.app/t/joint-non-local-means-denoising/" sources_verified_at: "2026-11-30" --- # Joint Non-Local Means (JNLM) Path-Tracing Denoiser (Rousselle et al., 2012) > Denoises Monte Carlo path-traced images by averaging pixels whose surrounding radiance patches and auxiliary G-buffer features (albedo, normal, depth) match under variance-normalized squared distance, requiring zero trained weights. ## Reach for it when - progressive path tracer stays grainy without an ai denoiser dependency - simple bilateral blur smears fine textures and sharp caustic highlights - denoise monte carlo renders using auxiliary normal albedo and depth guides - need a pure compute shader denoiser that runs in webgpu with no ml weights - remove high-variance path tracing noise while preserving repeating surface detail ## How it works Standard bilateral filters compare single pixels, which breaks down under heavy Monte Carlo noise because individual noisy samples cannot reliably distinguish edges from variance. Joint Non-Local Means (JNLM) instead compares small **spatial patches** (for example 3×3 or 7×7 neighborhoods) around a center pixel `p` and each candidate neighbor `q` inside a larger search window. The squared patch distance in color space is normalized by the **estimated per-pixel sample variance** (tracked across progressive path-tracing iterations or dual half-buffers) so high-variance regions filter more aggressively while converged pixels stay sharp. To prevent blurring across geometric discontinuities and fine textures, JNLM combines the color patch distance with **joint feature weights** computed from noise-free auxiliary AOVs—surface albedo, shading normal, and world depth—taking the strictest similarity criterion across channels. Each pixel's denoised radiance is the weighted average of its search window. Because the entire algorithm is analytic and needs no neural network weights, it runs cleanly on both WebGPU and WebGL2 with predictable memory use and optional adaptive sampling feedback. ## When to use it Choose it when building a lightweight or browser-based progressive path tracer that needs clean, edge-preserving denoising on both WebGPU and WebGL2 without bundling tens of megabytes of neural network weights. Prefer [open-image-denoise](open-image-denoise) when you can afford neural weights and need crisp reconstruction at 1–4 samples per pixel during interactive camera motion. Prefer [svgf](svgf) or [nvidia-nrd-relax-reblur](nvidia-nrd-relax-reblur) for real-time 60 fps games with motion vectors and temporal reprojection. Prefer [atrous-wavelet-filter](atrous-wavelet-filter) when a tiny fixed-cost spatial pass is required. ## Cost heavy — Search-window times patch-size comparisons scale quadratically in window radius; interactive at moderate radii on GPU via separable patch-distance passes, though heavier than à-trous wavelet filters. Measured GPU Weight: 152.02× baseline (extreme) — 5.0016 ms median / 5.2803 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 143.49× baseline (extreme) — 2.2815 ms median (2.19× faster on L4). Ampere A100 scaling: 106.06× baseline (extreme) — 3.0546 ms median (1.64× faster on A100). ## Failure modes - At very low sample counts (1–4 spp), noisy radiance patches can still smear glossy reflections, caustics, or soft shadow penumbrae - Extreme fireflies bias both the sample variance estimate and patch distances unless clamped or filtered beforehand - Over-smoothing of fine bump-mapped or procedural micro-details that are absent from the smooth shading normal and albedo AOVs - Frame-to-frame temporal flickering on animated sequences because the filter is purely spatial without temporal reprojection ## Dataflow - Inputs: hdr-image, gbuffer, normals, depth - Outputs: hdr-image - Platforms: webgpu, webgl2, desktop-gpu, cuda, cpu ## Presets ### Joint Non-Local Means (JNLM) — 1-spp noisy path-traced render (left) vs G-buffer patch-matched denoising (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_NOISE": 0.75, "P_PATCH_SIGMA": 0.45, "P_GBUF_GUIDE": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_NOISE = 0.75; // P MC Noise Level [0.15, 1.4, 0.05] const float P_PATCH_SIGMA = 0.45; // P Patch Bandwidth [0.15, 1.2, 0.05] const float P_GBUF_GUIDE = 1.00; // P Aux G-Buffer Weight [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Noisy / JNLM [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Analytical Cornell-like studio G-buffer + clean radiance void evalGBuffer(vec2 uv, float t, out vec3 rad, out vec3 alb, out vec3 nrm, out float dep) { vec3 ro = vec3(0.0, 0.25, 2.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.06, -1.5)); vec3 lPos = vec3(0.75 * cos(t * 0.55), 1.15, 0.55 * sin(t * 0.55) + 0.25); dep = 10.0; nrm = vec3(0.0, 0.0, 1.0); alb = vec3(0.18, 0.20, 0.24); int id = 0; vec3 hp = vec3(0.0); // Back wall (z = -1.2) float tb = (-1.2 - ro.z) / min(rd.z, -1e-4); if (tb > 0.1 && tb < dep) { dep = tb; id = 1; hp = ro + rd * tb; nrm = vec3(0.0, 0.0, 1.0); float wallSplit = step(0.0, hp.x); alb = mix(vec3(0.84, 0.26, 0.20), vec3(0.20, 0.64, 0.74), wallSplit); } // Floor (y = -0.55) if (rd.y < -0.005) { float tf = (-0.55 - ro.y) / rd.y; if (tf > 0.1 && tf < dep) { dep = tf; id = 2; hp = ro + rd * tf; nrm = vec3(0.0, 1.0, 0.0); float chk = mod(floor(hp.x * 3.5) + floor(hp.z * 3.5), 2.0); alb = mix(vec3(0.56, 0.54, 0.50), vec3(0.78, 0.76, 0.72), chk); } } // Left matte-gold sphere vec3 c1 = vec3(-0.34, -0.18, -0.10); vec3 o1 = ro - c1; float b1 = dot(o1, rd), d1 = b1 * b1 - (dot(o1, o1) - 0.37 * 0.37); if (d1 > 0.0) { float t1 = -b1 - sqrt(d1); if (t1 > 0.1 && t1 < dep) { dep = t1; id = 3; hp = ro + rd * t1; nrm = normalize(hp - c1); alb = vec3(0.92, 0.72, 0.34); } } // Right ceramic sphere vec3 c2 = vec3(0.38, -0.25, 0.16); vec3 o2 = ro - c2; float b2 = dot(o2, rd), d2 = b2 * b2 - (dot(o2, o2) - 0.30 * 0.30); if (d2 > 0.0) { float t2 = -b2 - sqrt(d2); if (t2 > 0.1 && t2 < dep) { dep = t2; id = 4; hp = ro + rd * t2; nrm = normalize(hp - c2); alb = vec3(0.88, 0.89, 0.92); } } vec3 lDir = normalize(lPos - hp); float lDist = length(lPos - hp); // Soft analytical sphere shadows on floor & wall float sh = 1.0; if (id == 1 || id == 2) { vec3 toC1 = c1 - hp; float p1 = max(dot(toC1, lDir), 0.0); float dist1 = length(toC1 - lDir * p1); sh *= smoothstep(0.30, 0.44, dist1); vec3 toC2 = c2 - hp; float p2 = max(dot(toC2, lDir), 0.0); float dist2 = length(toC2 - lDir * p2); sh *= smoothstep(0.24, 0.38, dist2); } float ndl = max(dot(nrm, lDir), 0.0); vec3 bounce = vec3(0.36, 0.16, 0.14) * max(-nrm.x, 0.0) + vec3(0.14, 0.30, 0.36) * max(nrm.x, 0.0) + vec3(0.16, 0.18, 0.22); rad = alb * (vec3(1.45, 1.32, 1.14) * ndl * sh / (0.4 + 0.22 * lDist * lDist) + bounce); } vec3 noisyRadiance(vec2 fc, float noiseAmp, float t, out vec3 alb, out vec3 nrm, out float dep) { vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; vec3 rad; evalGBuffer(uv, t, rad, alb, nrm, dep); vec2 p = floor(fc); float fr = floor(t * 10.0) * 0.13; // Variance-scaled zero-mean Monte Carlo radiance noise (with occasional fireflies) vec3 n = vec3( hash21(p + vec2(11.3, fr * 31.7)), hash21(p + vec2(47.9, fr * 19.3)), hash21(p + vec2(83.1, fr * 53.1)) ) - 0.5; float spike = step(0.96, hash21(p * 1.31 + vec2(fr * 17.0, 5.1))) * 1.8; return max(rad + n * noiseAmp * (0.55 + 0.7 * rad) + vec3(spike) * noiseAmp * 0.35 * alb, 0.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float noiseAmp = clamp(P_NOISE, 0.05, 1.6); float sigma = clamp(P_PATCH_SIGMA, 0.10, 1.5); float gGuide = clamp(P_GBUF_GUIDE, 0.0, 2.0); vec3 cAlb, cNrm; float cDep; vec3 centerNoisy = noisyRadiance(fragCoord, noiseAmp, iTime, cAlb, cNrm, cDep); vec3 col = centerNoisy; if (screenX >= split) { // Right: Joint Non-Local Means -- compare 3-tap micro-patches + G-buffer (albedo, normal, depth) across search window vec3 acc = vec3(0.0); float wSum = 0.0; float stepPx = 2.0; // Precompute tiny 3-point signature around center p vec3 a0, n0; float d0; vec3 cpL = noisyRadiance(fragCoord + vec2(-1.5, 0.0), noiseAmp, iTime, a0, n0, d0); vec3 cpU = noisyRadiance(fragCoord + vec2(0.0, 1.5), noiseAmp, iTime, a0, n0, d0); for (int iy = -2; iy <= 2; iy++) { for (int ix = -2; ix <= 2; ix++) { vec2 q = fragCoord + vec2(float(ix), float(iy)) * stepPx; vec3 qAlb, qNrm; float qDep; vec3 qRad = noisyRadiance(q, noiseAmp, iTime, qAlb, qNrm, qDep); // Radiance patch distance (3-tap proxy for 3x3 patch) vec3 qpL = noisyRadiance(q + vec2(-1.5, 0.0), noiseAmp, iTime, a0, n0, d0); vec3 qpU = noisyRadiance(q + vec2(0.0, 1.5), noiseAmp, iTime, a0, n0, d0); float dPatch = dot(centerNoisy - qRad, centerNoisy - qRad) + dot(cpL - qpL, cpL - qpL) + dot(cpU - qpU, cpU - qpU); float dColorNorm = dPatch / max(3.0 * sigma * sigma * (0.25 + noiseAmp * noiseAmp), 0.01); // Joint G-buffer feature distance (normal + albedo + depth) float dNrm = 1.0 - max(dot(cNrm, qNrm), 0.0); float dAlb = dot(cAlb - qAlb, cAlb - qAlb); float dDep = abs(cDep - qDep) / max(cDep, 0.25); float dAux = (dNrm * 18.0 + dAlb * 14.0 + dDep * 24.0) * gGuide; float w = exp(-dColorNorm - dAux); acc += qRad * w; wSum += w; } } col = acc / max(wSum, 1e-4); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Consumes progressive HDR radiance, sample variance, albedo, and normal AOVs to produce converged-looking renders at far fewer samples. - [Owen-scrambled Sobol and low-discrepancy sampling](https://texelatlas.vercel.app/t/owen-scrambled-sobol-sampling.md): Well-stratified low-discrepancy samples yield lower-noise variance estimates that improve NLM patch-similarity accuracy. ## Combination ideas - [Dispersive manifold caustics denoised with joint NLM](https://texelatlas.vercel.app/ideas/spectral-mnee-jnlm-caustics/) ## Sources 1. [primary] Fabrice Rousselle, Claude Knaus, Matthias Zwicker (2012) Adaptive rendering with non-local means filtering. ACM Transactions on Graphics. https://doi.org/10.1145/2366145.2366214 (verified via crossref on 2026-11-30) 2. [implementation] pissang (2026) pissang/mutracer. https://github.com/pissang/mutracer License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Joint Non-Local Means (JNLM) Path-Tracing Denoiser." https://texelatlas.vercel.app/t/joint-non-local-means-denoising/ (accessed 2026-12-01). --- id: "jonswap-spectrum" title: "JONSWAP Wave Spectrum" aliases: [JONSWAP, Joint North Sea Wave Project spectrum] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, unity, unreal, houdini, blender] year_introduced: 1973 inputs: [material-params] outputs: [texture] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Horvath, 2015" url: "https://texelatlas.vercel.app/t/jonswap-spectrum/" sources_verified_at: "2026-11-29" --- # JONSWAP Wave Spectrum (Horvath, 2015) > An empirical wave energy spectrum for wind seas that are still growing, with a sharp peak at the dominant frequency, used to seed the amplitudes of an FFT ocean. ## Reach for it when - ocean waves look unrealistic or too regular - need sea state driven by wind speed and fetch - fft ocean wave heights need a believable spectrum - wave patterns for open sea versus calm lake ## How it works The JONSWAP spectrum is the Pierson-Moskowitz fully developed sea spectrum multiplied by a peak enhancement factor gamma raised to an exponent that depends on how close the frequency is to the peak. Its inputs are wind speed, fetch (the distance of open water the wind has blown over) and optionally peak frequency; from these you derive the peak frequency and the Phillips-like alpha constant. The result gives energy per frequency. For graphics you convert it into a function of the wave vector, multiply by a directional spreading function such as cosine to a power around the wind direction (frequency-dependent in more accurate versions), and divide by the Jacobian of the dispersion relation to get energy per unit area in k-space. The square root of that is the standard deviation used to draw each random Fourier amplitude. A short-wave cutoff and a damping factor for waves moving against the wind are usually added. ## When to use it Choose it when an FFT ocean must respond to physically meaningful inputs (wind speed, fetch) and show a narrow dominant swell rather than the broad, scale-free look of the Phillips spectrum. Prefer the Phillips spectrum for the simplest, widely documented setup in [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md). Prefer hand-picked amplitudes in [Gerstner (Trochoidal) Waves](https://texelatlas.vercel.app/t/gerstner-waves.md) if you just need a few art-directed swells. ## Cost cheap — Evaluated once per grid cell when (re)generating the initial spectrum texture, not every frame. Measured GPU Weight: 75.42× baseline (extreme) — 2.4812 ms median / 2.5715 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 56.77× baseline (heavy) — 0.9027 ms median (2.75× faster on L4). Ampere A100 scaling: 47.65× baseline (heavy) — 1.3724 ms median (1.81× faster on A100). ## Failure modes - Wrong units for fetch or wind speed give implausibly tall or flat seas - Using a non-directional spectrum yields waves travelling in all directions - Missing short-wave cutoff produces noisy capillary-scale aliasing on the grid - Single wind-driven spectrum ignores swell from distant storms - Peak enhancement gamma set too large produces an unnaturally regular, almost monochromatic sea ## Engine support - blender: builtin — `Ocean modifier > Spectrum = Established Ocean (Sharp Peaks) or Shallow Water` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/physics/ocean.html, checked 2026-12-01) ## Dataflow - Inputs: material-params - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, cuda, unity, unreal, houdini, blender ## Presets ### Ocean waves synthesized from a JONSWAP spectrum (sum-of-cosines toy, not FFT) (glsl-fragment; rendered 2026-11-29) ```json { "N_WAVES": 28, "PEAK_W": 1.1, "ALPHA": 0.0081, "GAMMA": 3.3 } ``` ```glsl // Ocean surface synthesized from a JONSWAP frequency spectrum: each wave component has // amplitude sqrt(2 S(w) dw), wavenumber k = w^2/g (deep-water dispersion), random phase and direction. const int N_WAVES = 28; const float GRAV = 9.81; const float PEAK_W = 1.1; const float ALPHA = 0.0081; const float GAMMA = 3.3; float hash(float n) { return fract(sin(n * 127.1) * 43758.5453); } float jonswap(float w) { float sg = w <= PEAK_W ? 0.07 : 0.09; float r = exp(-(w - PEAK_W) * (w - PEAK_W) / (2.0 * sg * sg * PEAK_W * PEAK_W)); return ALPHA * GRAV * GRAV / pow(w, 5.0) * exp(-1.25 * pow(PEAK_W / w, 4.0)) * pow(GAMMA, r); } float height(vec2 p, float t) { float h = 0.0; float dw = 2.6 / float(N_WAVES); for (int i = 0; i < N_WAVES; i++) { float fi = float(i); float w = 0.6 + (fi + hash(fi)) * dw; float a = sqrt(2.0 * jonswap(w) * dw); float k = w * w / GRAV; float th = (hash(fi * 3.7 + 1.0) - 0.5) * 2.2; h += a * cos(k * dot(vec2(cos(th), sin(th)), p) - w * t + 6.2832 * hash(fi * 7.3 + 2.0)); } return h; } vec3 sky(vec3 d) { vec3 sd = normalize(vec3(0.3, 0.25, -1.0)); vec3 c = mix(vec3(0.8, 0.85, 0.9), vec3(0.2, 0.4, 0.75), pow(clamp(d.y, 0.0, 1.0), 0.45)); return c + vec3(1.0, 0.85, 0.6) * pow(max(dot(d, sd), 0.0), 200.0) * 6.0; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 4.0, 0.0); vec3 rd = normalize(vec3(uv.x, uv.y - 0.1, -1.0)); vec3 col = sky(rd); if (rd.y < -0.002) { float t = (ro.y - 2.5) / -rd.y; float dt = 0.4; float tp = t; bool hit = false; for (int i = 0; i < 90; i++) { vec3 p = ro + rd * t; if (p.y < height(p.xz, iTime)) { hit = true; break; } tp = t; dt = max(0.4, t * 0.05); t += dt; } if (hit) { float a = tp, b = t; for (int i = 0; i < 6; i++) { float m = 0.5 * (a + b); vec3 p = ro + rd * m; if (p.y < height(p.xz, iTime)) b = m; else a = m; } t = b; vec3 p = ro + rd * t; float e = 0.05 + 0.01 * t; float h0 = height(p.xz, iTime); vec3 n = normalize(vec3(h0 - height(p.xz + vec2(e, 0.0), iTime), e, h0 - height(p.xz + vec2(0.0, e), iTime))); float f = 0.02 + 0.98 * pow(1.0 - max(dot(n, -rd), 0.0), 5.0); vec3 water = vec3(0.01, 0.07, 0.1) + vec3(0.04, 0.12, 0.1) * clamp(p.y * 0.5 + 0.5, 0.0, 1.0); col = mix(water, sky(reflect(rd, n)), f); col = mix(col, sky(vec3(rd.x, 0.02, rd.z)), 1.0 - exp(-t * 0.004)); } } col = 1.0 - exp(-col * 1.3); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md) ## Combines with - [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md): Supplies the initial h0(k) amplitudes whose time evolution the FFT then evaluates. ## Sources 1. [primary] Christopher J. Horvath (2015) Empirical directional wave spectra for computer graphics. Proceedings of the 2015 Symposium on Digital Production. https://doi.org/10.1145/2791261.2791267 (verified via crossref on 2026-11-29) 2. [primary] Jerry Tessendorf Simulating Ocean Water. SIGGRAPH Course Notes 2001/2004. https://jtessen.people.clemson.edu/reports/papers_files/coursenotes2004.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "JONSWAP Wave Spectrum." https://texelatlas.vercel.app/t/jonswap-spectrum/ (accessed 2026-12-01). --- id: "jump-flood-outline" title: "Jump-flood wide outlines" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2006 inputs: [ldr-image, depth] outputs: [ldr-image, texture] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Rong & Tan, 2006" url: "https://texelatlas.vercel.app/t/jump-flood-outline/" sources_verified_at: "2026-11-29" --- # Jump-flood wide outlines (Rong & Tan, 2006) > Builds a per-pixel nearest-seed field with the jump flooding algorithm, so outlines of any pixel width cost a fixed log-many passes instead of an ever-growing blur kernel. ## Reach for it when - thick outlines cost too much with blur kernels - need wide uniform selection highlight around shapes - outline width must scale without extra cost - glow around arbitrary silhouettes at fixed passes ## How it works Render the objects to outline into a mask, seeding each covered pixel with its own coordinate. Then run log2(N) full-screen passes with step sizes N/2, N/4, … 1; in each pass a pixel looks at the 9 neighbours at that offset and keeps whichever stored seed is closest to it. The result approximates a Voronoi diagram, giving every pixel the coordinate of its nearest mask pixel. A final pass draws the outline where the distance to that seed is below the desired width, which makes lines resolution-independent in thickness and perfectly round, including inner glow or gradient falloff. Ben Golus's write-up adapts this for Unity with anti-aliased sub-pixel distance. ## When to use it Choose it for very wide, uniform outlines, selection highlights and glows around arbitrary shapes. Prefer [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md) for cheap thin character outlines on a few meshes, and [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md) for creases and interior lines, which flood fill cannot produce. ## Cost medium — About log2(width) cheap full-screen passes plus mask render; outline width barely changes cost. Measured GPU Weight: 9.05× baseline (moderate) — 0.2978 ms median / 0.3127 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.5× baseline (moderate) — 0.1192 ms median (2.5× faster on L4). Ampere A100 scaling: 5.75× baseline (light) — 0.1656 ms median (1.8× faster on A100). ## Failure modes - Approximate: occasional wrong nearest seeds produce small seams or speckles that need an extra 1+JFA pass - Needs extra ping-pong buffers with 16-bit or float precision for large screens - Outline ignores occlusion by default; lines can draw through walls unless depth-aware - Overlapping mask objects share seeds, so adjacent objects cannot have different line colours without an ID channel ## Dataflow - Inputs: ldr-image, depth - Outputs: ldr-image, texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Jump-flood outline — exact Euclidean distance field wide outlines & JFA iso-rings (glsl-fragment; rendered 2026-11-30) ```json { "P_OUTLINE_WIDTH": 0.048, "P_HALO_SPREAD": 0.16, "P_BAND_VIS": 0.75, "P_SPEED": 1 } ``` ```glsl const float P_OUTLINE_WIDTH = 0.048; // P Outline Width [0.008, 0.14, 0.004] const float P_HALO_SPREAD = 0.16; // P Glow Halo [0.02, 0.35, 0.01] const float P_BAND_VIS = 0.75; // P EDT Iso-Bands [0.0, 1.5, 0.05] const float P_SPEED = 1.0; // P Motion Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdRoundedBox(vec2 p, vec2 b, float r) { vec2 q = abs(p) - b + r; return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r; } float sdStar5(vec2 p, float r, float rf) { vec2 k1 = vec2(0.80901699, -0.58778525); vec2 k2 = vec2(-k1.x, k1.y); p.x = abs(p.x); p -= 2.0 * max(dot(k1, p), 0.0) * k1; p -= 2.0 * max(dot(k2, p), 0.0) * k2; p.x = abs(p.x); p.y -= r; vec2 ba = rf * vec2(-k1.y, k1.x) - vec2(0.0, 1.0); float h = clamp(dot(p, ba) / dot(ba, ba), 0.0, r); return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y); } // Multi-part complex selection silhouette (illustrates JFA miter-free wide outlines) vec2 mapSelection(vec2 p, float t) { // Primary rotating 5-point star emblem vec2 p1 = rot2(t * 0.55) * (p - vec2(-0.14, 0.04)); float d1 = sdStar5(p1, 0.18, 0.48); // Orbiting rounded mechanical capsule vec2 c2 = vec2(0.24 + 0.04 * cos(t * 1.1), -0.08 + 0.07 * sin(t * 0.9)); vec2 p2 = rot2(-t * 0.7) * (p - c2); float d2 = sdRoundedBox(p2, vec2(0.11, 0.055), 0.025); // Floating satellite ring vec2 c3 = vec2(0.16 * cos(t * 0.8 + 1.2), 0.26 + 0.03 * sin(t * 1.4)); float d3 = abs(length(p - c3) - 0.068) - 0.018; float d = min(d1, min(d2, d3)); float id = (d == d1) ? 1.0 : ((d == d2) ? 2.0 : 3.0); return vec2(d, id); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / iResolution.y; float t = iTime * max(P_SPEED, 0.0); float width = clamp(P_OUTLINE_WIDTH, 0.006, 0.18); float halo = clamp(P_HALO_SPREAD, 0.02, 0.42); float bandVis = clamp(P_BAND_VIS, 0.0, 1.6); vec2 res = mapSelection(uv, t); float d = res.x; // Approximate nearest seed direction (what JFA stores in each pixel's RG seed-coordinate buffer!) vec2 e = vec2(0.002, 0.0); vec2 grad = normalize(vec2( mapSelection(uv + e.xy, t).x - mapSelection(uv - e.xy, t).x, mapSelection(uv + e.yx, t).x - mapSelection(uv - e.yx, t).x ) + 1e-5); float seedAng = atan(grad.y, grad.x); // Dark drafting-grid viewport background vec3 bg = mix(vec3(0.03, 0.04, 0.065), vec3(0.06, 0.08, 0.125), smoothstep(-0.55, 0.55, uv.y)); vec2 g = abs(fract(uv * 12.0 - 0.5) - 0.5) / (12.0 * px); bg += vec3(0.035, 0.055, 0.085) * smoothstep(1.3, 0.0, min(g.x, g.y)) * 0.45; // Visualize JFA Euclidean distance field iso-contours radiating outward in powers-of-two jump bands float distPos = max(d, 0.0); float iso = smoothstep(0.08, 0.015, abs(fract(distPos * 26.0 - iTime * 0.45) - 0.5)); float jfaBand = exp(-distPos * 4.5); vec3 seedTint = 0.5 + 0.5 * cos(seedAng + vec3(0.0, 2.094, 4.188)); vec3 col = bg + mix(vec3(0.14, 0.42, 0.72), seedTint, 0.35) * iso * jfaBand * 0.42 * bandVis; // Smooth exponential selection glow halo outside the wide outline float glow = exp(-max(d - width * 0.5, 0.0) / halo); col += vec3(0.16, 0.78, 1.15) * glow * 0.48; // Crisp constant-width JFA wide outline band (rounded exterior joins, zero corner artifacts) float outerAA = smoothstep(width + 1.5 * px, width - 1.5 * px, d); float innerAA = smoothstep(1.5 * px, -1.5 * px, d); float outlineMask = clamp(outerAA - innerAA, 0.0, 1.0); // Animated marching-ants dash accents along the outer rim of the wide outline float rimLine = smoothstep(2.5 * px, 0.0, abs(d - width)); vec3 outlineCol = mix(vec3(1.05, 0.68, 0.16), vec3(0.22, 0.94, 1.08), clamp(d / max(width, 0.005), 0.0, 1.0)); col = mix(col, outlineCol * 1.18, outlineMask); col += vec3(1.35, 1.25, 0.95) * rimLine * 0.7; // Interior shaded 2.5D metallic badge fill if (innerAA > 0.001) { float bevel = clamp(-d * 14.0, 0.0, 1.0); vec3 nFake = normalize(vec3(grad * (1.0 - bevel) * 0.7, 0.75 + 0.25 * bevel)); vec3 lDir = normalize(vec3(0.55, 0.75, 0.6)); float diff = max(dot(nFake, lDir), 0.0); float spec = pow(max(dot(nFake, normalize(lDir + vec3(0.0, 0.0, 1.0))), 0.0), 28.0); vec3 fillBase = (res.y < 1.5) ? vec3(0.24, 0.30, 0.42) : ((res.y < 2.5) ? vec3(0.32, 0.26, 0.38) : vec3(0.22, 0.36, 0.40)); vec3 fillCol = fillBase * (0.35 + 0.95 * diff) + vec3(0.85, 0.92, 1.0) * spec * 0.65; col = mix(col, fillCol, innerAA); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md) ## Combines with - [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md): Toon-shaded characters get a thick uniform selection or hero outline from the flooded distance field. ## Sources 1. [primary] Guodong Rong, Tiow-Seng Tan (2006) Jump flooding in GPU with applications to Voronoi diagram and distance transform. Proceedings of the 2006 symposium on Interactive 3D graphics and games - SI3D '06. https://doi.org/10.1145/1111411.1111431 (verified via crossref on 2026-11-29) 2. [tutorial] Ben Golus The Quest for Very Wide Outlines. bgolus.medium.com. https://bgolus.medium.com/the-quest-for-very-wide-outlines-ba82ed442cd9 (verified via wayback on 2026-11-29) 3. [implementation] CharlesGrs (2022) CharlesGrs/JumpFloodOutline. https://github.com/CharlesGrs/JumpFloodOutline License: Unlicense. (verified via github on 2026-11-29) ## Cite this entry Texel. "Jump-flood wide outlines." https://texelatlas.vercel.app/t/jump-flood-outline/ (accessed 2026-12-01). --- id: "jump-flooding-algorithm" title: "Jump Flooding Algorithm" aliases: [JFA] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, mobile-gpu] year_introduced: 2006 inputs: [texture] outputs: [sdf, texture] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Rong & Tan, 2006" url: "https://texelatlas.vercel.app/t/jump-flooding-algorithm/" sources_verified_at: "2026-11-29" --- # Jump Flooding Algorithm (Rong & Tan, 2006) > Approximates a Voronoi diagram or distance transform on a pixel grid in O(log n) full-screen passes by propagating nearest-seed information in halving strides. Fast on GPUs and very good for outlines, glows and SDF baking. ## Reach for it when - need a fast gpu distance field from a texture - wide uniform outlines around objects - glow or soft 2d shadows from seed pixels - voronoi diagram on the gpu in few passes - bake a signed distance field quickly ## How it works Initialise a texture where seed pixels store their own coordinates and others store 'none'. Run passes with step length N/2, N/4, ..., 1. In each pass every pixel looks at nine samples at offsets of plus or minus the step (and zero) in x and y, takes the stored seed position of each neighbour, and keeps the seed that is closest to the pixel itself. After the final pass each pixel holds an approximate nearest seed, from which the distance is computed. An extra pass with step 1 (JFA+1) or 2 reduces errors. For a signed field, run it twice on the shape and its complement and subtract. Pixels with ties and bottlenecks occasionally keep a wrong seed. ## When to use it Choose it for GPU-side distance fields in screen space or 2D textures: outlines, soft glows, fonts, 2D shadows and radiance-cascade seed fields. Prefer [Exact Euclidean Distance Transform](https://texelatlas.vercel.app/t/exact-euclidean-distance-transform.md) when you need exact values and are happy on CPU or with a compute pass, and [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md) for analytic shapes that need no baking. ## Cost cheap — A fixed log2(resolution) number of full-screen passes; each is nine texture reads per pixel. Measured GPU Weight: 5.55× baseline (light) — 0.1827 ms median / 0.1897 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.01× baseline (light) — 0.0796 ms median (2.3× faster on L4). Ampere A100 scaling: 3.28× baseline (light) — 0.0945 ms median (1.93× faster on A100). ## Failure modes - Rare wrong-nearest-seed errors that show as small speckles and discontinuities, especially with sparse seeds - Distance values are approximate, not exact Euclidean - Cost and precision depend on float format; 8-bit targets cannot store coordinates for large textures - Seeds that are thin or close together can vanish under the stride pattern ## Engine support - unity: official — `Visual Effect Graph > Window > Visual Effects > Utilities > SDF Bake Tool (MeshToSDFBaker.JFA)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.visualeffectgraph/Runtime/Utilities/SDF/MeshToSDFBaker.cs, checked 2026-12-01) — Requires the Visual Effect Graph package. ## Dataflow - Inputs: texture - Outputs: sdf, texture - Platforms: webgl2, webgpu, desktop-gpu, cuda, mobile-gpu ## Presets ### Jump Flooding Algorithm (JFA) — Voronoi nearest-seed partitioning, Euclidean SDF isolines and glow (glsl-fragment; rendered 2026-11-30) ```json { "ISO_FREQ": 26, "SEED_COUNT": 12, "GLOW_FALLOFF": 5.5, "OUTLINE_WIDTH": 0.032 } ``` ```glsl const float ISO_FREQ = 26.0; // P const int SEED_COUNT = 12; // P const float GLOW_FALLOFF = 5.5; // P const float OUTLINE_WIDTH = 0.032; // P float sdArc(vec2 p, vec2 sc, float ra, float rb) { p.x = abs(p.x); return ((sc.y * p.x > sc.x * p.y) ? length(p - sc * ra) : abs(length(p) - ra)) - rb; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; int nSeeds = clamp(SEED_COUNT, 3, 24); // Hero geometric seed contour (rotating segmented ring) + orbiting point seeds float a0 = iTime * 0.45; mat2 rot = mat2(cos(a0), -sin(a0), sin(a0), cos(a0)); vec2 rp = rot * uv; float dRing = sdArc(rp, vec2(sin(2.15), cos(2.15)), 0.21, 0.016); float dBest = max(dRing, 0.0); float dSecond = 10.0; float bestId = 0.0; bool insideHero = (dRing < 0.0); for (int i = 1; i <= 24; i++) { if (i > nSeeds) break; float fi = float(i); float ang = fi * 2.39996 + iTime * (0.25 + 0.04 * mod(fi, 4.0)); float rad = 0.14 + 0.30 * fract(fi * 0.381966); vec2 seed = vec2(cos(ang), sin(ang)) * rad; if (i == 1 && (iMouse.z > 0.5 || length(iMouse.xy) > 1.0)) { seed = (iMouse.xy - 0.5 * iResolution.xy) / iResolution.y; } float d = length(uv - seed); if (d < dBest) { dSecond = dBest; dBest = d; bestId = fi; } else if (d < dSecond) { dSecond = d; } } // Per-seed palette representing converged JFA nearest-seed ID buffer vec3 seedHue = (bestId < 0.5) ? vec3(0.24, 0.78, 0.96) : 0.48 + 0.42 * cos(6.2831853 * (bestId * 0.137 + vec3(0.0, 0.33, 0.67))); // Smooth Euclidean distance transform isoline rings + JFA Voronoi cell borders float freq = max(ISO_FREQ, 1.0); float iso = 0.5 + 0.5 * cos(dBest * freq * 6.2831853 - iTime * 2.4); float isoLine = smoothstep(0.86, 0.98, iso); float vorEdge = smoothstep(0.009, 0.002, dSecond - dBest); // Wide JFA distance-field outline & exponential glow around the hero contour float outW = max(OUTLINE_WIDTH, 0.004); float wideOutline = smoothstep(outW + 0.004, outW - 0.004, dRing) * (1.0 - smoothstep(0.004, -0.004, dRing)); float glow = exp(-max(dRing, 0.0) * max(GLOW_FALLOFF, 0.5)); vec3 fieldCol = seedHue * (0.18 + 0.42 * exp(-dBest * 3.8)); fieldCol += seedHue * isoLine * 0.24 * exp(-dBest * 1.4); fieldCol = mix(fieldCol, vec3(0.92, 0.96, 1.0), vorEdge * 0.42); fieldCol += vec3(0.28, 0.84, 1.0) * glow * 0.55; fieldCol = mix(fieldCol, vec3(1.0, 0.78, 0.28), wideOutline * 0.92); // Crisp glowing seed cores float core = smoothstep(0.015, 0.006, dBest); if (insideHero) fieldCol = vec3(0.98, 0.99, 1.0); else if (bestId > 0.5) fieldCol = mix(fieldCol, vec3(1.0), core); fragColor = vec4(clamp(fieldCol, 0.0, 1.0), 1.0); } ``` Attribution: MIT — written for this index ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): JFA bakes arbitrary raster shapes into a field that is combined with analytic SDFs. ## Sources 1. [primary] Guodong Rong, Tiow-Seng Tan (2006) Jump flooding in GPU with applications to Voronoi diagram and distance transform. Proceedings of the 2006 symposium on Interactive 3D graphics and games - SI3D '06. https://doi.org/10.1145/1111411.1111431 (verified via crossref on 2026-11-29) 2. [tutorial] Ryan Kaplan Voronoi diagrams on the GPU. rykap.com. https://www.rykap.com/graphics/skew/2016/02/25/voronoi-diagrams (verified via http on 2026-11-29) ## Cite this entry Texel. "Jump Flooding Algorithm." https://texelatlas.vercel.app/t/jump-flooding-algorithm/ (accessed 2026-12-01). --- id: "kajiya-kay-hair-shading" title: "Kajiya-Kay hair shading" aliases: [Kajiya-Kay model, strand tangent shading] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender] year_introduced: 1989 inputs: [curves, material-params] outputs: [radiance] style: "both" dynamic: "both" cost: "cheap" authority: "Kajiya & Kay, 1989" url: "https://texelatlas.vercel.app/t/kajiya-kay-hair-shading/" sources_verified_at: "2026-11-29" --- # Kajiya-Kay hair shading (Kajiya & Kay, 1989) > Treats a hair strand as an infinitely thin cylinder with a tangent instead of a normal. Diffuse and specular depend on the angle between tangent, light and view, giving the stretched highlight band every game hair shader starts from. ## Reach for it when - need cheap shiny highlight along hair strands - hair cards look like flat plastic - want anisotropic highlight following hair direction - game character hair that runs on mobile - two-tone specular on hair cards ## How it works A fibre has no single surface normal, so the model works with the strand tangent T. Diffuse is the average over all normals perpendicular to T, which comes out as sin of the angle between T and the light: sqrt(1 - dot(T,L)^2). Specular uses the cone around T on which light reflects: the highlight is strongest when the angle of the light to the strand mirrors the angle of the eye, giving spec = pow(dot(T,L)*dot(T,V) + sinTL*sinTV, p) with sinTL = sqrt(1-dot(T,L)^2) and sinTV likewise. Real-time versions usually add a second, differently coloured and shifted lobe by sliding the tangent along the normal using a noise or shift map, imitating the secondary reflection, and multiply by a flow-map or card tangent so highlights follow the hair direction. Shadows and opacity come from separate hair-card or strand techniques; the shading itself is purely local. ## When to use it Choose it for hair cards, fur cards, anisotropic satin and stylised hair where cost and artist control matter. Prefer [Marschner hair scattering model](https://texelatlas.vercel.app/t/marschner-hair-scattering.md) or [Disney / Chiang hair and fur BSDF](https://texelatlas.vercel.app/t/disney-hair-bsdf.md) when physically based fibre colour, multiple lobes and path-traced reference are required. Prefer [Anisotropic GGX](https://texelatlas.vercel.app/t/anisotropic-ggx.md) for brushed metal where a surface normal still exists. Use [Strand-based real-time hair (TressFX style)](https://texelatlas.vercel.app/t/strand-based-real-time-hair.md) for the geometry side when hair is simulated and rendered as lines. ## Cost cheap — A handful of dot products and pow per light; the second lobe roughly doubles the specular math. Measured GPU Weight: 1.45× baseline (feather) — 0.0478 ms median / 0.0492 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.28× baseline (feather) — 0.0203 ms median (2.35× faster on L4). Ampere A100 scaling: 1.01× baseline (feather) — 0.0292 ms median (1.64× faster on A100). ## Failure modes - Highlight sits at the wrong place on the strand because the tangent is not normalised or flips direction along the card - No light transport through the fibre, so blond or white hair lacks glow and backlighting - Highlights are single and white without the shifted second lobe, giving a plastic look - Hair cards sorted wrongly with alpha blending cause popping; alpha-to-coverage trades that for noise - Specular aliasing on thin fibres sparkles without a roughness or power adjustment at distance ## Engine support - unity: builtin — `HDRP Hair Shader Graph > Material Type = Approximate` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/snippets/shader-properties/surface-options/material-type-hair.md, checked 2026-12-01) — HDRP Hair shader. ## Dataflow - Inputs: curves, material-params - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender ## Presets ### Kajiya-Kay highlights on latitude strands (glsl-fragment; rendered 2026-11-29) ```json { "SPEC_POWER": 80, "SPEC_POWER_2": 20 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Strands run along latitude lines of a sphere. const float SPEC_POWER = 80.0; const float SPEC_POWER_2 = 20.0; const vec3 HAIR = vec3(0.35, 0.18, 0.08); float kk(vec3 t, vec3 l, vec3 v, float p) { float tl = dot(t, l), tv = dot(t, v); float s = tl * tv + sqrt(max(1.0 - tl * tl, 0.0)) * sqrt(max(1.0 - tv * tv, 0.0)); return pow(clamp(s, 0.0, 1.0), p); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 3.0); vec3 rd = normalize(vec3(uv, -1.5)); vec3 col = vec3(0.03, 0.03, 0.05); float b = dot(ro, rd); float h = b * b - (dot(ro, ro) - 1.0); if (h > 0.0) { vec3 p = ro + rd * (-b - sqrt(h)); vec3 n = normalize(p); vec3 t = normalize(cross(vec3(0.0, 1.0, 0.0), n)); vec3 l = normalize(vec3(sin(iTime) * 0.8, 0.7, 0.9)); vec3 v = -rd; float tl = dot(t, l); float diff = sqrt(max(1.0 - tl * tl, 0.0)) * (0.3 + 0.7 * max(dot(n, l) * 0.5 + 0.5, 0.0)); vec3 t2 = normalize(t + 0.25 * n); vec3 spec = vec3(1.0) * kk(t, l, v, SPEC_POWER) + HAIR * 3.0 * kk(t2, l, v, SPEC_POWER_2); col = HAIR * diff + 0.6 * spec; } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Marschner hair scattering model](https://texelatlas.vercel.app/t/marschner-hair-scattering.md) ## Combines with - [Strand-based real-time hair (TressFX style)](https://texelatlas.vercel.app/t/strand-based-real-time-hair.md): Simulated strand lines supply per-vertex tangents that the Kajiya-Kay lobes consume. ## Sources 1. [primary] J. T. Kajiya, T. L. Kay (1989) Rendering fur with three dimensional textures. Proceedings of the 16th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/74333.74361 (verified via crossref on 2026-11-29) 2. [secondary] Cem Yuksel, Sarah Tariq Advanced techniques in real-time hair rendering and simulation. cemyuksel.com. https://www.cemyuksel.com/courses/conferences/siggraph2010-hair (verified via http on 2026-11-29) ## Cite this entry Texel. "Kajiya-Kay hair shading." https://texelatlas.vercel.app/t/kajiya-kay-hair-shading/ (accessed 2026-12-01). --- id: "khronos-pbr-neutral" title: "Khronos PBR Neutral tone mapper" domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender] year_introduced: 2024 inputs: [hdr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "cheap" authority: "KhronosGroup, 2024" url: "https://texelatlas.vercel.app/t/khronos-pbr-neutral/" sources_verified_at: "2026-11-29" --- # Khronos PBR Neutral tone mapper (KhronosGroup, 2024) > A tone mapper from Khronos for product and e-commerce rendering that is the identity for most colours below a knee, so base colours display as authored, and only compresses highlights. ## Reach for it when - product colors shift after tone mapping - ecommerce viewer must show true base colors - tonemapping desaturates or hue shifts materials - want hdr output that keeps albedo faithful ## How it works The mapper works on the minimum and maximum channel. Below a start-compression threshold it applies only a small offset that handles the Fresnel-like black level, leaving colours essentially unchanged. Above the threshold, the peak channel is compressed with a smooth rational curve that asymptotes to 1, and the colour is then desaturated toward white by an amount that grows with how far the peak was compressed. The result keeps hue because compression is applied to all channels via a common scale and the desaturation blends toward the same lightness. It is a few lines of code with no matrices or LUTs, and a specification and OCIO config plus LUT are included. ## When to use it Choose it for product configurators, glTF viewers and any case where the sRGB albedo must match a reference photo. Prefer [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) or [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md) for cinematic scenes with strong light sources and wide dynamic range. Prefer [Reinhard photographic tone reproduction](https://texelatlas.vercel.app/t/reinhard-tonemapping.md) for a minimal curve if hue fidelity is not a concern. ## Cost cheap — A few arithmetic operations per pixel. Measured GPU Weight: 1.29× baseline (feather) — 0.0423 ms median / 0.0457 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.04× baseline (feather) — 0.0166 ms median (2.55× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.47× faster on A100). ## Failure modes - Not cinematic: low contrast and no filmic shoulder look - Compresses only close to the white point, so extremely bright lights clip to white sooner - Not a full display transform, so wide-gamut output needs separate handling - Highlights desaturate toward white rather than shifting hue naturally ## Engine support - babylonjs: builtin — `imageProcessingConfiguration.toneMappingType = ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/imageProcessingConfiguration.pure.ts, checked 2026-12-01) - blender: builtin — `Properties > Render > Color Management > View Transform = Khronos PBR Neutral` (evidence: https://docs.blender.org/manual/en/5.2/render/color_management/displays_views.html, checked 2026-12-01) - threejs: builtin — `renderer.toneMapping = THREE.NeutralToneMapping` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender ## Presets ### three.js Neutral tone mapping, exposure 1.0 (three-tonemap; rendered 2026-11-29) ```json { "toneMapping": "Neutral", "exposure": 1 } ``` Attribution: written for this index ## Lineage - extends [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) ## Combines with - [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md): The repo ships a LUT version of the same curve for use in grading pipelines. ## Sources 1. [primary] KhronosGroup (2024) KhronosGroup/ToneMapping. https://github.com/KhronosGroup/ToneMapping License: Apache-2.0. (verified via github on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Khronos PBR Neutral tone mapper." https://texelatlas.vercel.app/t/khronos-pbr-neutral/ (accessed 2026-12-01). --- id: "kulla-conty-multiscatter" title: "Kulla-Conty multiple-scattering compensation" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2017 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Heitz et al., 2016" url: "https://texelatlas.vercel.app/t/kulla-conty-multiscatter/" sources_verified_at: "2026-11-29" --- # Kulla-Conty multiple-scattering compensation (Heitz et al., 2016) > Adds back the energy a single-scattering GGX lobe loses on rough surfaces, using a precomputed directional-albedo table and a cheap multiplicative lobe. Rough metals stop looking too dark, with almost no runtime cost. ## Reach for it when - rough metals look too dark - high roughness specular loses energy - ggx surfaces appear dimmer as roughness rises - need cheap fix for lost multi-bounce energy in microfacets ## How it works Single-scatter microfacet models ignore light that bounces more than once between facets, so albedo drops as roughness rises, up to tens of percent for rough conductors. Kulla and Conty precompute the directional albedo E(mu, roughness) of the single-scatter lobe and its cosine-weighted average E_avg(roughness) into a small 2D/1D LUT. The missing energy is 1 - E(mu); a compensation lobe is shaped like a diffuse-ish BRDF f_ms = (1-E(mu_o))(1-E(mu_i)) / (pi (1 - E_avg)) and tinted by an average Fresnel term that accounts for colour shifts from repeated reflections on coloured metals. A variant for image-based lighting simply scales the split-sum specular by a factor derived from the same LUT (Fdez-Aguera 2019). Result: energy conserving and white-furnace-test friendly. ## When to use it Choose it whenever you shade GGX in a real-time or production renderer and rough metals or high-roughness dielectrics look dark; it is cheap and almost always a win. Prefer the full stochastic multiple-scattering evaluation of Heitz et al. only in offline path tracers. Combine it with [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) or [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) models whose specular is single-scatter. ## Cost cheap — One extra LUT fetch and a few multiplies per shaded pixel; IBL variant reuses the split-sum BRDF LUT. Measured GPU Weight: 17.5× baseline (moderate) — 0.5758 ms median / 0.5945 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 11.52× baseline (moderate) — 0.1832 ms median (3.14× faster on L4). Ampere A100 scaling: 11.45× baseline (moderate) — 0.3299 ms median (1.75× faster on A100). ## Failure modes - LUT resolution and parameterization errors cause banding in roughness or a visible seam at the metal/dielectric boundary - Fresnel tint approximation is wrong for strongly coloured conductors with sharp spectral edges - Compensation lobe is diffuse-like, so the highlight shape of true multiple scattering (slightly wider) is not reproduced - Must be applied consistently to direct lights and IBL or the two disagree ## Engine support - babylonjs: builtin — `pbrMaterial.brdf.useEnergyConservation = true` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBRDFConfiguration.ts, checked 2026-12-01) — Multiple-scattering energy compensation via MS BRDF LUT. - blender: builtin — `Principled BSDF > Distribution = Multiscatter GGX` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) — Energy-compensating multiple scattering for GGX. - threejs: builtin — `MeshStandardMaterial / MeshPhysicalMaterial (automatic)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/functions/PhysicalLightingModel.js, checked 2026-12-01) — Uses Fdez-Aguera multiple-scattering compensation with a DFG LUT. - unity: builtin — `HDRP Lit (always on)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl, checked 2026-12-01) — HDRP only; Fdez-Aguera style multiple-scattering energy compensation. - unreal: builtin — `Substrate material system (energy-conserving multi-scattering rough GGX compensation)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-substrate-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### White furnace test: single-scatter GGX (top) vs multiscatter-compensated (bottom) (glsl-fragment; rendered 2026-11-29) ```json { "BG": 0.55 } ``` ```glsl // White-furnace test (uniform environment, radiance 0.55) of gold GGX spheres, roughness 0.35 / 0.65 / 1.0. // Top row: single-scattering GGX loses energy as roughness rises. Bottom row: Kulla-Conty style // compensation (1 + F0 (1/E - 1)) with E(mu) integrated in-shader. const vec3 F0 = vec3(1.0, 0.77, 0.34); const float BG = 0.55; float radical(int i) { float f = 0.5, r = 0.0; for (int b = 0; b < 6; b++) { r += f * float(i & 1); i >>= 1; f *= 0.5; } return r; } float g1(float n, float a) { return 2.0 * n / (n + sqrt(a * a + (1.0 - a * a) * n * n)); } float dirAlbedo(float mu, float rough) { float a = rough * rough; vec3 V = vec3(sqrt(1.0 - mu * mu), 0.0, mu); float sum = 0.0; for (int i = 0; i < 64; i++) { float u1 = (float(i) + 0.5) / 64.0, u2 = radical(i); float phi = 6.2832 * u1, ct = sqrt((1.0 - u2) / (1.0 + (a * a - 1.0) * u2)), st = sqrt(1.0 - ct * ct); vec3 H = vec3(st * cos(phi), st * sin(phi), ct); vec3 L = 2.0 * dot(V, H) * H - V; if (L.z > 0.0 && dot(V, H) > 0.0) sum += g1(L.z, a) * g1(mu, a) * dot(V, H) / (ct * mu); } return sum / 64.0; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -1.7)); vec3 col = vec3(BG); for (int j = 0; j < 2; j++) for (int i = 0; i < 3; i++) { vec3 c = vec3((float(i) - 1.0) * 0.62, j == 0 ? 0.3 : -0.3, 0.0); vec3 oc = ro - c; float b = dot(oc, rd); float h = b * b - dot(oc, oc) + 0.27 * 0.27; if (h < 0.0) continue; float t = -b - sqrt(h); if (t < 0.0) continue; vec3 n = normalize(ro + rd * t - c); float mu = clamp(dot(n, -rd), 0.04, 1.0); float E = dirAlbedo(mu, 0.35 + 0.325 * float(i)); vec3 lo = F0 * E; if (j == 1) lo *= 1.0 + F0 * (1.0 / E - 1.0); col = lo * BG; } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) ## Combines with - [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md): Consumes the single-scatter GGX albedo and returns the missing multi-bounce energy. ## Sources 1. [talk] Christopher Kulla, Alejandro Conty Revisiting Physically Based Shading at Imageworks. SIGGRAPH 2017 Course. https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides.pdf (verified via http on 2026-11-29) 2. [primary] Eric Heitz, Johannes Hanika, Eugene d'Eon, Carsten Dachsbacher (2016) Multiple-scattering microfacet BSDFs with the Smith model. ACM Transactions on Graphics. https://doi.org/10.1145/2897824.2925943 (verified via crossref on 2026-11-29) 3. [primary] Carmelo J. Fdez-Aguera A Multiple-scattering Microfacet Model for Real-time Image-based Lighting. JCGT 2019. https://jcgt.org/published/0008/01/03 (verified via http on 2026-11-29) ## Cite this entry Texel. "Kulla-Conty multiple-scattering compensation." https://texelatlas.vercel.app/t/kulla-conty-multiscatter/ (accessed 2026-12-01). --- id: "kuwahara-filter" title: "Kuwahara filter" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, python] year_introduced: 1976 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "medium" authority: "Kyprianidis et al., 2009" url: "https://texelatlas.vercel.app/t/kuwahara-filter/" sources_verified_at: "2026-11-29" --- # Kuwahara filter (Kyprianidis et al., 2009) > Edge-preserving smoothing that splits each pixel's neighbourhood into four overlapping sub-windows and outputs the mean of the one with the lowest variance, giving a flat, oil-paint look. ## Reach for it when - want an oil painting look on a render - photo should look like a flat poster-style painting - smooth colour regions but keep edges sharp - cheap painterly look as a post-process - reduce detail without blurring edges ## How it works For every pixel, the square neighbourhood is divided into four quadrants that all share the centre pixel. For each quadrant, compute the mean colour and the variance of brightness. The output is the mean of the quadrant with the smallest variance. Flat regions get averaged strongly, while pixels on a boundary choose the quadrant lying entirely on one side, so edges are not blurred. The larger the radius, the more paint-like the result. Because every pixel computes four windows, cost grows with radius squared, and implementations often use summed-area tables, separable approximations or reduced taps to stay real-time. The blocky look from fixed square windows is the motivation for the anisotropic variant. ## When to use it Choose it for quick oil-painting or poster-like post-processing of any frame, including 3D renders. Prefer [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) when blocky square artefacts are visible and you can afford a structure tensor pass. Prefer [Posterization](https://texelatlas.vercel.app/t/posterization.md) for a colour-count reduction without spatial smoothing. ## Cost medium — Cost scales with window area; a radius of 4 to 8 at 1080p is a medium-cost full-screen pass without optimization. Measured GPU Weight: 54.23× baseline (heavy) — 1.7843 ms median / 1.9186 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 46.31× baseline (heavy) — 0.7364 ms median (2.42× faster on L4). Ampere A100 scaling: 36.22× baseline (heavy) — 1.0432 ms median (1.71× faster on A100). ## Failure modes - Square window produces visible blocky, boxy shapes at larger radii - Noisy flat regions can flip between quadrants and create speckle - Can wash out thin lines and small high-contrast details - Colour banding and temporal shimmer when the winning quadrant switches between frames ## Engine support - blender: builtin — `Compositor > Add > Creative > Kuwahara` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/creative/kuwahara.html, checked 2026-12-01) ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, python ## Presets ### Classic Kuwahara, radius 5, procedural image (glsl-fragment; rendered 2026-11-29) ```json { "radius": 5 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: classic 4-quadrant Kuwahara on a procedural image const int R = 5; // quadrant radius in pixels const float SPLIT = 0.5; // left half shows the filtered result, right half the source (set 0.0 for all filtered) vec3 img(vec2 p){ vec2 q = p / iResolution.y; float n = sin(q.x*17.0)*sin(q.y*13.0) + 0.5*sin(q.x*41.0 + q.y*29.0); float d = length(q - vec2(0.9, 0.5)); vec3 c = 0.5 + 0.5*cos(6.2831*(vec3(0.0,0.33,0.67) + n*0.25 + d*1.4)); c += 0.18*sin(q.x*400.0)*sin(q.y*380.0); // high-frequency grain to be removed return c; } void mainImage(out vec4 fragColor, in vec2 fragCoord){ if(fragCoord.x / iResolution.x > SPLIT){ fragColor = vec4(clamp(img(fragCoord),0.0,1.0),1.0); return; } vec3 bestMean = vec3(0.0); float bestVar = 1e9; for(int k=0;k<4;k++){ vec2 s = vec2((k & 1) == 0 ? 1.0 : -1.0, (k & 2) == 0 ? 1.0 : -1.0); vec3 sum = vec3(0.0); float sum2 = 0.0; for(int j=0;j<=R;j++){ for(int i=0;i<=R;i++){ vec3 c = img(fragCoord + vec2(float(i), float(j))*s); sum += c; float l = dot(c, vec3(0.299,0.587,0.114)); sum2 += l*l; } } float N = float((R+1)*(R+1)); vec3 m = sum / N; float ml = dot(m, vec3(0.299,0.587,0.114)); float v = sum2/N - ml*ml; if(v < bestVar){ bestVar = v; bestMean = m; } } fragColor = vec4(clamp(bestMean, 0.0, 1.0), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) ## Combines with - [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md): Classic filter is the baseline; the anisotropic one replaces its square windows. - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Painterly colour from Kuwahara plus crisp edge lines from G-buffer edges. ## Sources 1. [primary] Jan Eric Kyprianidis, Henry Kang, Jürgen Döllner (2009) Image and Video Abstraction by Anisotropic Kuwahara Filtering. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2009.01574.x (verified via crossref on 2026-11-29) 2. [implementation] GarrettGunnell (2022) GarrettGunnell/Post-Processing. https://github.com/GarrettGunnell/Post-Processing License: MIT. (verified via github on 2026-11-29) 3. [implementation] noxtgm (2023) noxtgm/kuwahara-filter. https://github.com/noxtgm/kuwahara-filter License: CC0-1.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Kuwahara filter." https://texelatlas.vercel.app/t/kuwahara-filter/ (accessed 2026-12-01). --- id: "l-systems" title: "L-Systems" aliases: [Lindenmayer systems, turtle-graphics plants, parametric L-systems] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [cpu, webgl2, webgpu, blender, houdini, unity, unreal, godot, python] year_introduced: 1968 outputs: [curves, mesh, graph] style: "both" dynamic: "static" cost: "cheap" authority: "Prusinkiewicz & Lindenmayer" url: "https://texelatlas.vercel.app/t/l-systems/" sources_verified_at: "2026-11-29" --- # L-Systems (Prusinkiewicz & Lindenmayer) > Parallel string-rewriting grammars whose output symbols are interpreted by a turtle to draw branching structures. Parametric, stochastic and context-sensitive variants model plant development. ## Reach for it when - generate trees and plants procedurally - need branching structures from simple rewrite rules - make fractal growth patterns like ferns - vary vegetation models without modeling each by hand ## How it works An L-system consists of an alphabet, an axiom and productions applied to every symbol simultaneously in each generation, so growth is parallel like cell division. After n generations the string is interpreted by a turtle: F moves forward and draws a segment, + and - turn, [ and ] push and pop turtle state to create branches. Parametric versions attach numeric parameters (length, thickness, age) to symbols and condition productions on them, stochastic versions pick productions by probability, and context-sensitive versions let neighbours influence a rewrite so signals can travel along the plant. Open L-systems exchange information with an environment, enabling effects like phototropism or pruning. The Algorithmic Beauty of Plants gives the canonical treatment and examples. ## When to use it Choose it for trees, ferns, flowers and fractal curves where the developmental rules are the creative control, and for architecture-style recursion. Prefer [Space Colonization Tree Modeling](https://texelatlas.vercel.app/t/space-colonization-trees.md) when branches should fill a volume or follow an attractor shape with minimal parameters, [Interactive Climbing Plant Modeling](https://texelatlas.vercel.app/t/climbing-plants-simulation.md) for vegetation interacting with geometry, and [CGA Shape Grammar (Procedural Buildings)](https://texelatlas.vercel.app/t/cga-shape-grammar.md) for building facades. ## Cost cheap — String length grows exponentially with generations for branching rules, but typical plants need under 10 generations; meshing the result dominates. Measured GPU Weight: 248.4× baseline (extreme) — 8.1725 ms median / 8.1936 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 240.54× baseline (extreme) — 3.8246 ms median (2.14× faster on L4). Ampere A100 scaling: 161.14× baseline (extreme) — 4.6408 ms median (1.76× faster on A100). ## Failure modes - Exponential string growth blows memory and time for deep derivations - Turtle interpretation produces self-intersecting branches that require explicit collision handling - Context-free rules look rigidly symmetric unless stochastic or parametric randomness is added - Tuning production parameters is non-intuitive: tiny changes give wildly different plants - No built-in environment awareness: trees ignore walls, light and neighbours unless open L-systems are used ## Dataflow - Inputs: — - Outputs: curves, mesh, graph - Platforms: cpu, webgl2, webgpu, blender, houdini, unity, unreal, godot, python ## Presets ### Dragon curve drawn from an L-system rewrite (512 turtle segments) (glsl-fragment; rendered 2026-11-29) ```json { "SEGS": 512, "UNIT": 0.028 } ``` ```glsl // Dragon curve as an L-system (F->F+G, G->F-G), 512 turtle segments; turn direction of step k read off the rewrite by its bit pattern. const int SEGS = 512; const float UNIT = 0.028; const vec2 CENTER = vec2(0.5, 0.5); float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 pos = vec2(0.0), dir = vec2(1.0, 0.0); vec2 origin = CENTER - UNIT * vec2(8.0, 5.5); float best = 1e9, bi = 0.0; vec2 a = origin; for (int k = 1; k <= SEGS; k++) { vec2 b = a + dir * UNIT; float d = segd(uv, a, b); if (d < best) { best = d; bi = float(k) / float(SEGS); } a = b; int m = k; while ((m & 1) == 0) m >>= 1; dir = ((m & 3) == 1) ? vec2(-dir.y, dir.x) : vec2(dir.y, -dir.x); } vec3 bg = mix(vec3(0.04, 0.05, 0.09), vec3(0.09, 0.08, 0.14), uv.y); vec3 lc = 0.5 + 0.5 * cos(6.2831 * (bi * 0.9 + vec3(0.0, 0.33, 0.67))); float w = smoothstep(0.0042, 0.0016, best); vec3 col = bg + lc * w + lc * 0.12 * smoothstep(0.02, 0.0, best); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [CGA Shape Grammar (Procedural Buildings)](https://texelatlas.vercel.app/t/cga-shape-grammar.md) - extended by [Procedural City Generation (L-system Road Networks)](https://texelatlas.vercel.app/t/procedural-city-roads.md) ## Sources 1. [primary] Przemyslaw Prusinkiewicz, Aristid Lindenmayer The Algorithmic Beauty of Plants. algorithmicbotany.org. https://algorithmicbotany.org/papers/abop/abop.pdf (verified via http on 2026-11-29) 2. [tutorial] Paul Bourke L-System User Notes. paulbourke.net. https://paulbourke.net/fractals/lsys (verified via http on 2026-11-29) ## Cite this entry Texel. "L-Systems." https://texelatlas.vercel.app/t/l-systems/ (accessed 2026-12-01). --- id: "large-reconstruction-model" title: "Large Reconstruction Model (LRM)" aliases: [LRM] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [ldr-image] outputs: [radiance-field, mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Hong et al., 2023" url: "https://texelatlas.vercel.app/t/large-reconstruction-model/" sources_verified_at: "2026-11-29" --- # Large Reconstruction Model (LRM) (Hong et al., 2023) > A big transformer that regresses a triplane NeRF from a single image in one forward pass, trained on about a million multi-view object renders; the template for most later feed-forward image-to-3D systems. ## Reach for it when - want 3d from a single image in seconds - optimisation per object is too slow - need a feed-forward image-to-3d baseline - predict a neural 3d representation without per-scene training ## How it works A pretrained vision transformer encodes the image into tokens. A transformer decoder with learned triplane queries cross-attends to those tokens and outputs a triplane feature grid, which a small MLP turns into density and colour. Training renders the predicted NeRF from other known camera views of the same object and minimises image and mask losses, so no 3D-specific supervision beyond multi-view renders is needed. At test time a single forward pass gives the reconstruction, which can be volume-rendered or meshed with marching cubes. The scaling insight was that data and model size matter more than hand-built 3D priors. ## When to use it Choose it as the conceptual baseline for single-image to 3D in seconds. In practice use [TripoSR](https://texelatlas.vercel.app/t/triposr.md) (permissive, packaged) or [InstantMesh](https://texelatlas.vercel.app/t/instantmesh.md) (mesh-focused with multi-view diffusion front end) rather than the original model, which has no official public weights. Prefer [Zero-1-to-3](https://texelatlas.vercel.app/t/zero-1-to-3.md) plus [Score Distillation Sampling (DreamFusion)](https://texelatlas.vercel.app/t/score-distillation-sampling.md) when no feed-forward model fits your category and you can wait. ## Cost heavy — A single transformer forward pass; seconds on a datacentre GPU per the paper. Measured GPU Weight: 38.49× baseline (heavy) — 1.2663 ms median / 1.2916 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 29.62× baseline (heavy) — 0.471 ms median (2.69× faster on L4). Ampere A100 scaling: 25.8× baseline (heavy) — 0.7429 ms median (1.7× faster on A100). ## Failure modes - Back of the object is blurry or mirrored because only one view is visible - Fine texture and text are smoothed by the triplane resolution - Out-of-distribution inputs (scenes, cluttered photos, unusual camera FOV) give melted shapes - Triplane NeRF extraction yields staircase or noisy meshes without extra regularisation ## Dataflow - Inputs: ldr-image - Outputs: radiance-field, mesh - Platforms: cuda, python ## Presets ### Large Reconstruction Model (LRM) — single-view cross-attention tokens (left) vs triplane 3D NeRF decode (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ATTN_GLOW": 1, "P_SIGMA": 5.5, "P_ROT_SPEED": 0.6, "P_SPLIT": 0.45 } ``` ```glsl const float P_ATTN_GLOW = 1.0; // P Attention Glow [0.0, 1.8, 0.05] const float P_SIGMA = 5.5; // P NeRF Density [1.5, 10.0, 0.25] const float P_ROT_SPEED = 0.60; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.45; // P Tokens / 3D Recon [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Stylized architectural teapot/capsule asset decoded from LRM triplane NeRF void evalLRM(vec3 q, out float sigma, out vec3 rgb) { float body = length(q * vec3(1.0, 1.25, 1.0)) - 0.48; float dome = length(q - vec3(0.0, 0.36, 0.0)) - 0.26; float ring = length(vec2(length(q.xz) - 0.56, q.y + 0.06)) - 0.085; float d = min(min(body, dome), ring); sigma = exp(-max(d, 0.0) * 20.0) * smoothstep(0.14, -0.04, d); float band = smoothstep(-0.1, 0.1, sin(q.y * 14.0)); rgb = mix(vec3(0.18, 0.54, 0.92), vec3(0.96, 0.72, 0.26), band * 0.65); rgb = mix(rgb, vec3(0.95, 0.34, 0.42), smoothstep(0.45, 0.56, length(q.xz))); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float attn = clamp(P_ATTN_GLOW, 0.0, 2.0); float sigmaGain = clamp(P_SIGMA, 1.0, 12.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 bg = mix(vec3(0.022, 0.030, 0.052), vec3(0.062, 0.084, 0.138), smoothstep(-0.55, 0.55, uv.y)); vec3 col = bg; if (screenX < split) { // Left: DINO image patch grid (input single-view tokens) sending cross-attention beams into triplane tokens vec2 p = uv + vec2(0.32, 0.0); float boxMask = step(max(abs(p.x), abs(p.y)), 0.34); vec2 patchUV = (p + 0.34) / 0.68; vec2 cell = floor(patchUV * 8.0); vec2 cf = fract(patchUV * 8.0); // Input silhouette inside the patch token grid float sil = smoothstep(0.30, 0.22, length(p * vec2(1.0, 1.2))); float ringSil = smoothstep(0.06, 0.02, abs(length(p - vec2(0.0, -0.02)) - 0.24)); vec3 patchCol = mix(vec3(0.07, 0.11, 0.19), vec3(0.24, 0.62, 0.94), sil); patchCol = mix(patchCol, vec3(0.98, 0.44, 0.36), ringSil); float scan = exp(-abs(cell.y - mod(iTime * 5.0, 8.0)) * 0.9); patchCol += vec3(0.98, 0.82, 0.32) * scan * 0.35 * attn; float gridL = smoothstep(0.08, 0.02, min(cf.x, cf.y)); patchCol = mix(patchCol, vec3(0.18, 0.88, 0.96), gridL * 0.35); col = mix(col, patchCol, boxMask); // Cross-attention streams radiating rightward toward the 3D triplane float rays = exp(-abs(sin(uv.y * 24.0 + uv.x * 6.0 - iTime * 3.5)) * 6.0) * smoothstep(-0.02, 0.35, uv.x + 0.25); col += vec3(0.22, 0.78, 0.98) * rays * 0.35 * attn * (1.0 - boxMask * 0.7); } else { // Right: Feed-forward 3D triplane NeRF volume rendered from novel orbiting view vec3 ro = vec3(0.0, 0.22, 2.25); vec3 rd = normalize(vec3(uv - vec2(0.10, 0.03), -1.52)); ro.xz = rot2(spin * 0.62) * ro.xz; rd.xz = rot2(spin * 0.62) * rd.xz; float b = dot(ro, rd); float c = dot(ro, ro) - 1.0 * 1.0; float disc = b * b - c; if (disc > 0.0) { float t0 = max(-b - sqrt(disc), 0.1); float t1 = -b + sqrt(disc); float dt = (t1 - t0) / 44.0; vec3 acc = vec3(0.0); float T = 1.0; vec3 lDir = normalize(vec3(0.55, 0.80, 0.45)); for (int i = 0; i < 44; i++) { float t = t0 + (float(i) + 0.5) * dt; vec3 p = ro + rd * t; float s; vec3 rgb; evalLRM(p, s, rgb); s *= sigmaGain; vec3 n = normalize(p + vec3(1e-4)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 32.0); vec3 lit = rgb * (0.35 + 0.75 * diff) + vec3(1.0) * spec * 0.38; float a = 1.0 - exp(-s * dt); acc += T * a * lit; T *= (1.0 - a); if (T < 0.015) break; } col = acc + T * bg; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Yicong Hong, Kai Zhang, Jiuxiang Gu, Sai Bi, Yang Zhou, Difan Liu, Feng Liu, Kalyan Sunkavalli, Trung Bui, Hao Tan (2023) LRM: Large Reconstruction Model for Single Image to 3D. arXiv preprint (cs.CV). https://arxiv.org/abs/2311.04400 (verified via arxiv on 2026-11-29) 2. [implementation] 3DTopia (2023) 3DTopia/OpenLRM. https://github.com/3DTopia/OpenLRM License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Large Reconstruction Model (LRM)." https://texelatlas.vercel.app/t/large-reconstruction-model/ (accessed 2026-12-01). --- id: "lattice-boltzmann-fluids" title: "Lattice Boltzmann fluids" aliases: [LBM] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu] year_introduced: 1998 inputs: [voxels] outputs: [volume-density, particles] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Chen & Doolen, 1998" url: "https://texelatlas.vercel.app/t/lattice-boltzmann-fluids/" sources_verified_at: "2026-11-29" --- # Lattice Boltzmann fluids (Chen & Doolen, 1998) > Simulates fluid with particle-distribution functions streaming and colliding on a lattice, with simple local updates that parallelise perfectly on GPUs. ## Reach for it when - simulate wind flowing around complex obstacles - need gpu-friendly fluid with many steps per frame - smoke around voxelised geometry - fluid solver with simple local parallel updates - wind tunnel style airflow visualisation ## How it works Instead of velocity and pressure, each cell stores a small set of distribution values (D2Q9 in 2D, D3Q19 or D3Q27 in 3D), one per lattice direction. A step has two phases: collision relaxes each cell's distributions toward equilibrium (BGK, with relaxation time setting viscosity), and streaming copies each distribution to the neighbouring cell it points to. Density and velocity are recovered as sums of the distributions. Solid boundaries use bounce-back, which works for arbitrary voxelised shapes. There is no pressure Poisson solve, so each step is a purely local, memory-bound pass, ideal for fragment/compute shaders. ## When to use it Choose it for wind tunnels, smoke around complex voxel obstacles, and GPU-friendly fluid that must run many steps per frame. Prefer [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md) for artist-friendly large time steps and stable smoke, [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) or [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) for liquids with free surfaces, and [Position Based Fluids](https://texelatlas.vercel.app/t/position-based-fluids.md) for game liquids. ## Cost medium — Memory-bandwidth bound: a lattice cell costs 9-27 reads and writes per step. Measured GPU Weight: 28.31× baseline (heavy) — 0.8889 ms median / 0.9218 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 23.4× baseline (heavy) — 0.3697 ms median (2.4× faster on L4). Ampere A100 scaling: 19.64× baseline (moderate) — 0.5656 ms median (1.57× faster on A100). ## Failure modes - Only stable for low Mach numbers; high speeds or low viscosity cause blow-ups - Compressibility errors: density waves reflect around obstacles - Fixed lattice step ties time step to grid resolution, so large domains need many steps - Free surfaces and multiphase flow need extra models ## Dataflow - Inputs: voxels - Outputs: volume-density, particles - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu ## Presets ### Lattice Boltzmann fluids — D2Q9 Kármán vortex street vorticity, equilibrium vectors & wake shedding (glsl-fragment; rendered 2026-11-30) ```json { "P_REYNOLDS": 1.15, "P_VORTEX_SHED": 1, "P_LATTICE_GRID": 0.75, "P_FLOW_SPEED": 1 } ``` ```glsl const float P_REYNOLDS = 1.15; // P Vortex Strength [0.3, 2.2, 0.05] const float P_VORTEX_SHED = 1.0; // P Strouhal Freq [0.4, 2.0, 0.05] const float P_LATTICE_GRID = 0.75; // P D2Q9 Stencils [0.0, 1.5, 0.05] const float P_FLOW_SPEED = 1.0; // P Inflow Speed [0.0, 2.5, 0.05] // Analytical D2Q9 Karman vortex street streamfunction behind cylinder at cylPos float streamPsi(vec2 p, vec2 cylPos, float cylR, float t, float reyn, float stFreq) { vec2 q = p - cylPos; float r2 = max(dot(q, q), 1e-4); // Potential doublet flow around cylinder (strictly tangent at r = cylR) float u0 = 0.75; float psi = u0 * q.y * (1.0 - (cylR * cylR) / r2); // Shedding alternating von Karman vortex street downstream (q.x > 0) float wakeMask = smoothstep(cylR * 0.6, cylR * 2.2, q.x) * exp(-abs(q.y) * 2.2); float kX = 5.4 * stFreq; float spacing = 6.2831853 / kX; float phase = t * 1.45 * stFreq; for (int k = 0; k < 6; k++) { float fk = float(k); float sgn = (mod(fk, 2.0) < 0.5) ? 1.0 : -1.0; float vx = mod(fk * spacing * 0.5 + phase * (spacing / 6.2831853), 1.65) + cylR * 1.15; float vy = sgn * (0.072 + 0.032 * vx); vec2 dv = q - vec2(vx, vy); float d2 = dot(dv, dv); float core = 0.0055 + 0.006 * vx; float fade = exp(-vx * 0.82) * smoothstep(cylR * 0.9, cylR * 1.8, vx); // Lamb-Oseen regularized point vortex contribution psi += sgn * 0.058 * reyn * fade * wakeMask * log(d2 + core); } return psi; } vec2 evalVelocity(vec2 p, vec2 cylPos, float cylR, float t, float reyn, float stFreq) { float e = 0.006; float dPsiDy = (streamPsi(p + vec2(0.0, e), cylPos, cylR, t, reyn, stFreq) - streamPsi(p - vec2(0.0, e), cylPos, cylR, t, reyn, stFreq)) / (2.0 * e); float dPsiDx = (streamPsi(p + vec2(e, 0.0), cylPos, cylR, t, reyn, stFreq) - streamPsi(p - vec2(e, 0.0), cylPos, cylR, t, reyn, stFreq)) / (2.0 * e); return vec2(dPsiDy, -dPsiDx); } // Diverging scientific vorticity palette (blue = clockwise, dark slate = irrotational, orange/gold = CCW) vec3 vortPalette(float w) { float a = clamp(abs(w), 0.0, 1.0); vec3 neg = mix(vec3(0.04, 0.14, 0.34), vec3(0.14, 0.86, 1.00), pow(a, 0.72)); vec3 pos = mix(vec3(0.32, 0.08, 0.10), vec3(1.00, 0.72, 0.18), pow(a, 0.72)); return mix(vec3(0.035, 0.052, 0.082), (w >= 0.0 ? pos : neg), smoothstep(0.02, 0.85, a)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tAnim = iTime * max(P_FLOW_SPEED, 0.0); float reyn = clamp(P_REYNOLDS, 0.2, 2.5); float stFreq = clamp(P_VORTEX_SHED, 0.35, 2.2); float gridVis = clamp(P_LATTICE_GRID, 0.0, 1.6); vec2 cylPos = vec2(-0.42, 0.0); float cylR = 0.115; // Evaluate macroscopic velocity u and vorticity curl(u) = dv/dx - du/dy vec2 vel = evalVelocity(uv, cylPos, cylR, tAnim, reyn, stFreq); float e = 0.01; vec2 vxP = evalVelocity(uv + vec2(e, 0.0), cylPos, cylR, tAnim, reyn, stFreq); vec2 vxM = evalVelocity(uv - vec2(e, 0.0), cylPos, cylR, tAnim, reyn, stFreq); vec2 vyP = evalVelocity(uv + vec2(0.0, e), cylPos, cylR, tAnim, reyn, stFreq); vec2 vyM = evalVelocity(uv - vec2(0.0, e), cylPos, cylR, tAnim, reyn, stFreq); float omega = (vxP.y - vxM.y - (vyP.x - vyM.x)) / (2.0 * e); // Advected streamline dye streaks to reveal flow topology float psi = streamPsi(uv, cylPos, cylR, tAnim, reyn, stFreq); float streak = smoothstep(0.06, 0.01, abs(fract(psi * 7.5 + 0.5) - 0.5)); vec3 col = vortPalette(omega * 0.22); float speed = length(vel); col += vec3(0.18, 0.32, 0.45) * streak * clamp(speed * 0.55, 0.15, 0.65); // Microscopic D2Q9 lattice stencil overlay showing discrete velocity population arrows per cell if (gridVis > 0.01) { float cellScale = 14.0; vec2 cellId = floor(uv * cellScale); vec2 cellCenter = (cellId + 0.5) / cellScale; vec2 lf = fract(uv * cellScale) - 0.5; vec2 cVel = evalVelocity(cellCenter, cylPos, cylR, tAnim, reyn, stFreq); float cSpd = length(cVel); vec2 dir = cVel / max(cSpd, 1e-4); // Project local offset onto cell velocity direction to draw a tiny directional D2Q9 flux vector float proj = clamp(dot(lf, dir), 0.0, clamp(cSpd * 0.32, 0.08, 0.38)); float dVec = length(lf - dir * proj); float dDot = length(lf); float glyph = max(smoothstep(0.055, 0.018, dVec), smoothstep(0.075, 0.03, dDot) * 0.65); col += vec3(0.75, 0.90, 1.0) * glyph * 0.26 * gridVis; } // Solid bounce-back cylindrical obstacle (no-slip LBM boundary condition) float dCyl = length(uv - cylPos) - cylR; if (dCyl < 0.0) { vec2 rel = (uv - cylPos) / cylR; float nz = sqrt(max(1.0 - dot(rel, rel), 0.0)); vec3 cn = normalize(vec3(rel, nz)); float diff = max(dot(cn, normalize(vec3(0.5, 0.7, 0.6))), 0.0); col = vec3(0.14, 0.17, 0.23) * (0.35 + 0.85 * diff); } col = mix(col, vec3(0.86, 0.92, 1.0), smoothstep(px * 3.0, px * 0.6, abs(dCyl)) * 0.9); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combination ideas - [Fog that flows through generated caves](https://texelatlas.vercel.app/ideas/drafts-through-generated-dungeons/) ## Sources 1. [primary] Shiyi Chen, Gary D. Doolen (1998) LATTICE BOLTZMANN METHOD FOR FLUID FLOWS. Annual Review of Fluid Mechanics. https://doi.org/10.1146/annurev.fluid.30.1.329 (verified via crossref on 2026-11-29) 2. [primary] Timm Krüger, Halim Kusumaatmaja, Alexandr Kuzmin, Orest Shardt, Goncalo Silva, Erlend Magnus Viggen (2017) The Lattice Boltzmann Method. Graduate Texts in Physics. https://doi.org/10.1007/978-3-319-44649-3 (verified via crossref on 2026-11-29) 3. [primary] Xiaoming Wei, Wei Li, K. Mueller, A.E. Kaufman (2004) The lattice-boltzmann method for simulating gaseous phenomena. IEEE Transactions on Visualization and Computer Graphics. https://doi.org/10.1109/tvcg.2004.1260768 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Lattice Boltzmann fluids." https://texelatlas.vercel.app/t/lattice-boltzmann-fluids/ (accessed 2026-12-01). --- id: "leadr-mapping" title: "LEADR mapping" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2013 inputs: [texture, normals, mesh] outputs: [texture, material-params] style: "photoreal" dynamic: "static" cost: "medium" authority: "Dupuy et al., 2013" url: "https://texelatlas.vercel.app/t/leadr-mapping/" sources_verified_at: "2026-11-29" --- # LEADR mapping (Dupuy et al., 2013) > Linear, Efficient, Antialiased Displacement and Reflectance mapping: pre-filters displaced surfaces with a linear mip-mappable representation so that shading under minification reproduces the average of the detailed surface's BRDF. ## Reach for it when - normal map shimmers or aliases at distance - fine bump detail disappears or sparkles when minified - specular highlights flicker on tiny surface detail - filter roughness for displaced geometry properly ## How it works Displaced geometry or bump detail below pixel size should not be sampled; it should be folded into the BRDF. Dupuy et al. express the distribution of slopes of the displaced surface as a Beckmann-like lobe, whose first and second moments (mean slope, covariance of slope) are linear and so can be averaged in a mip pyramid. Moments of the height-field's slope are stored; at runtime the filtered moments rebuild a Gaussian slope distribution of the surface, convolved with the base roughness and fed into the shading model, and also used for tracing the displacement via ray marching on the filtered pyramid. The key advantage over Toksvig is that anisotropy and non-zero mean slope are retained, so a groove pattern remains anisotropic when minified. ## When to use it Choose it for displacement-mapped or heavily bumped surfaces viewed over a wide range of scales (ocean waves, rock, rough metal) where specular detail must stay stable and plausible. Prefer [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) as the simpler, isotropic baseline. Prefer [Normal distribution filtering for specular antialiasing](https://texelatlas.vercel.app/t/normal-distribution-filtering.md) for runtime-derived filtering without per-texture moment pyramids. ## Cost medium — Extra moment textures and a ray-march for displacement; heavier than normal mapping. Measured GPU Weight: 6.54× baseline (moderate) — 0.2152 ms median / 0.2224 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.97× baseline (light) — 0.095 ms median (2.27× faster on L4). Ampere A100 scaling: 4.35× baseline (light) — 0.1254 ms median (1.72× faster on A100). ## Failure modes - Requires precomputed moment mip chains with 2-3 extra channels per displacement texture - Gaussian slope model fails for multi-modal slope distributions like two facing facets - Tracing displacement inherits the artifacts of heightfield ray marching - Not implemented in mainstream engines, so use means custom pipeline ## Dataflow - Inputs: texture, normals, mesh - Outputs: texture, material-params - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### LEADR Mapping — point-sampled displaced surface aliasing (left) vs linear prefiltered slope-moment anisotropic BRDF (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GROOVE_FREQ": 24, "P_SLOPE_AMP": 0.72, "P_BASE_ROUGH": 0.14, "P_SPLIT": 0.48 } ``` ```glsl const float P_GROOVE_FREQ = 24.0; // P Groove Frequency [8.0, 48.0, 2.0] const float P_SLOPE_AMP = 0.72; // P Displacement Slope [0.15, 1.2, 0.05] const float P_BASE_ROUGH = 0.14; // P Base Roughness [0.06, 0.45, 0.02] const float P_SPLIT = 0.48; // P Point / LEADR Split [0.0, 1.0, 0.02] vec3 evalEnv(vec3 d) { vec3 sky = mix(vec3(0.06, 0.09, 0.14), vec3(0.26, 0.42, 0.66), smoothstep(-0.15, 0.75, d.y)); vec3 l1 = normalize(vec3(0.55, 0.48, -0.68)); vec3 l2 = normalize(vec3(-0.62, 0.36, -0.58)); float s1 = pow(max(dot(d, l1), 0.0), 48.0); float s2 = pow(max(dot(d, l2), 0.0), 24.0); return sky + vec3(2.8, 2.3, 1.7) * s1 + vec3(0.65, 1.25, 1.95) * s2; } // Analytical 2D anisotropic brushed + chevron micro-displacement height gradient vec2 evalSlope(vec2 uv, float freq, float amp) { float a = uv.x * freq; float b = uv.y * freq * 0.25 + sin(uv.x * freq * 0.12) * 1.4; float gx = cos(a) * amp + 0.35 * cos(a * 2.13 + 0.8) * amp; float gy = 0.28 * cos(b) * amp; return vec2(gx, gy); } // Evaluate Gaussian anisotropic slope-distribution NDF from LEADR moments (Dupuy et al. 2013) float evalLEADR_NDF(vec2 hSlope, vec2 meanSlope, vec3 cov, float baseVar) { vec2 d = hSlope - meanSlope; float sxx = max(cov.x + baseVar, 1e-4); float syy = max(cov.y + baseVar, 1e-4); float sxy = clamp(cov.z, -0.95 * sqrt(sxx * syy), 0.95 * sqrt(sxx * syy)); float det = max(sxx * syy - sxy * sxy, 1e-6); float invDet = 1.0 / det; float quad = (syy * d.x * d.x - 2.0 * sxy * d.x * d.y + sxx * d.y * d.y) * invDet; return exp(-0.5 * min(quad, 40.0)) / (6.2831853 * sqrt(det)); } float beckmannLambda(float a) { if (a >= 1.6) return 0.0; return (1.0 - 1.259 * a + 0.396 * a * a) / max(3.535 * a + 2.181 * a * a, 1e-4); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useLEADR = sx >= split; float freq = clamp(P_GROOVE_FREQ, 4.0, 64.0); float amp = clamp(P_SLOPE_AMP, 0.05, 1.5); float baseRough = clamp(P_BASE_ROUGH, 0.04, 0.6); float baseVar = 0.5 * baseRough * baseRough; vec3 ro = vec3(0.0, 0.62, 1.85); vec3 rd = normalize(vec3(uv.x, uv.y - 0.16, -1.42)); vec3 col = evalEnv(rd) * 0.45; // Intersect receding grooved brass plane (y = -0.35) and a grooved hero sphere vec3 sphC = vec3(0.0, 0.18, -0.55); float sphR = 0.52; vec3 oc = ro - sphC; float b = dot(oc, rd); float c = dot(oc, oc) - sphR * sphR; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tPl = (rd.y < -0.005) ? ((-0.35 - ro.y) / rd.y) : 1e5; if (tPl < 0.05 || tPl > 45.0) tPl = 1e5; float tHit = min(tSph, tPl); if (tHit < 1e4) { vec3 p = ro + rd * tHit; vec3 nG; vec3 T, B; vec2 muv; float footprint; if (tSph < tPl) { nG = normalize(p - sphC); float phi = atan(nG.z, nG.x) + iTime * 0.18; float th = acos(clamp(nG.y, -1.0, 1.0)); muv = vec2(phi * 1.15, th * 1.15); T = normalize(vec3(-sin(phi), 0.0, cos(phi))); B = cross(nG, T); footprint = (tHit / max(iResolution.y, 1.0)) * 2.2 / max(abs(dot(nG, -rd)), 0.12); } else { nG = vec3(0.0, 1.0, 0.0); T = vec3(1.0, 0.0, 0.0); B = vec3(0.0, 0.0, 1.0); muv = p.xz + vec2(0.0, -iTime * 0.25); footprint = (tHit / max(iResolution.y, 1.0)) * 2.8 / max(abs(rd.y), 0.04); } vec3 v = -rd; vec3 l1 = normalize(vec3(0.55 * cos(iTime * 0.35), 0.52, -0.65)); vec3 l2 = normalize(vec3(-0.62, 0.42, -0.52)); vec3 f0 = (tSph < tPl) ? vec3(0.95, 0.74, 0.36) : vec3(0.76, 0.78, 0.82); // Filter strength grows linearly with footprint * frequency (mip level of LEADR moments!) float filterK = clamp(footprint * freq * 0.48, 0.0, 1.0); float envMip = smoothstep(0.0, 1.0, filterK); // Instantaneous slope at pixel center vec2 rawSlope = evalSlope(muv, freq, amp); // LEADR linear moments: E[s] attenuates as footprint spans cycles, while covariance E[s*s^T] - E[s]E[s]^T absorbs the variance! float atten = exp(-2.4 * filterK * filterK); vec2 meanSlope = useLEADR ? (rawSlope * atten) : rawSlope; // Exact variance of cos(a) + 0.35*cos(2.13a) is 0.5*(1 + 0.35^2)*amp^2 = 0.561*amp^2 along X, 0.039*amp^2 along Y float varX = useLEADR ? (0.561 * amp * amp * (1.0 - atten * atten)) : 0.0; float varY = useLEADR ? (0.039 * amp * amp * (1.0 - atten * atten)) : 0.0; vec3 cov = vec3(varX, varY, 0.0); vec3 acc = vec3(0.0); for (int li = 0; li < 2; li++) { vec3 L = (li == 0) ? l1 : l2; vec3 lCol = (li == 0) ? vec3(2.8, 2.35, 1.75) : vec3(0.75, 1.25, 1.95); float ndl = max(dot(nG, L), 0.0); float ndv = max(dot(nG, v), 0.005); if (ndl > 0.002) { vec3 H = normalize(L + v); float hN = max(dot(H, nG), 0.005); vec2 hSlope = vec2(-dot(H, T) / hN, -dot(H, B) / hN); float D = evalLEADR_NDF(hSlope, meanSlope, cov, baseVar) / pow(hN, 4.0); // Anisotropic Smith masking-shadowing along projected slope variance float sigV = sqrt(max(baseVar + varX * dot(v, T) * dot(v, T) + varY * dot(v, B) * dot(v, B), 1e-4)); float sigL = sqrt(max(baseVar + varX * dot(L, T) * dot(L, T) + varY * dot(L, B) * dot(L, B), 1e-4)); float tanV = sqrt(max(1.0 - ndv * ndv, 0.0)) / ndv; float tanL = sqrt(max(1.0 - ndl * ndl, 0.0)) / ndl; float G = 1.0 / (1.0 + beckmannLambda(1.0 / max(1.414 * sigV * tanV, 1e-4)) + beckmannLambda(1.0 / max(1.414 * sigL * tanL, 1e-4))); float vdh = max(dot(v, H), 0.005); vec3 F = f0 + (1.0 - f0) * pow(1.0 - vdh, 5.0); acc += lCol * F * (D * G / max(4.0 * ndv, 0.04)); } } // Filtered ambient reflection using mean normal + effective roughness vec3 effN = normalize(nG - T * meanSlope.x - B * meanSlope.y); vec3 rDir = reflect(-v, effN); float effRough = clamp(sqrt(baseVar + 0.5 * (varX + varY)), 0.05, 0.85); vec3 envAmb = mix(evalEnv(rDir), evalEnv(nG) * 0.72, effRough); vec3 Fv = f0 + (1.0 - f0) * pow(1.0 - max(dot(effN, v), 0.0), 5.0); col = acc + envAmb * Fv * (0.48 + 0.25 * (1.0 - envMip)); if (tPl < tSph) { col = mix(col, evalEnv(rd) * 0.45, 1.0 - exp(-tPl * 0.075)); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) ## Combination ideas - [Neural materials that filter like EWA](https://texelatlas.vercel.app/ideas/footprint-filtered-neural-materials/) - [Sun glitter from horizon to bow](https://texelatlas.vercel.app/ideas/sun-glitter-ocean/) ## Sources 1. [primary] Jonathan Dupuy, Eric Heitz, Jean-Claude Iehl, Pierre Poulin, Fabrice Neyret, Victor Ostromoukhov (2013) Linear efficient antialiased displacement and reflectance mapping. ACM Transactions on Graphics. https://doi.org/10.1145/2508363.2508422 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "LEADR mapping." https://texelatlas.vercel.app/t/leadr-mapping/ (accessed 2026-12-01). --- id: "least-squares-vertex-baking" title: "Least-Squares Vertex Light Baking" aliases: [LSVB, least squares vertex baking, cotangent-Laplacian vertex baking, UV-free vertex light baking] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu] year_introduced: 2011 inputs: [mesh, radiance] outputs: [radiance] style: "both" dynamic: "static" cost: "cheap" authority: "Kavan et al., 2011" url: "https://texelatlas.vercel.app/t/least-squares-vertex-baking/" sources_verified_at: "2026-11-30" --- # Least-Squares Vertex Light Baking (Kavan et al., 2011) > Solves a sparse linear least-squares system over mesh vertices to fit area-sampled indirect lighting across every triangle, eliminating lightmap UV unwrapping and seams while regularizing undersampled regions with a cotangent Laplacian. ## Reach for it when - want baked lighting or ao on meshes without uv unwrapping - vertex colors look blotchy when point sampled at corners - fit noisy path traced samples cleanly across mesh triangles - bake smooth radiosity onto low poly assets without lightmap seams - reduce lightmap texture memory by storing lighting per vertex ## How it works Naive per-vertex light baking evaluates irradiance only at mesh vertices, which misses narrow shadows or bright patches falling inside triangles and creates severe aliasing on irregular tessellations. **Least-Squares Vertex Baking** treats the vertex colors `x` as the degrees of freedom of a piecewise-linear finite-element function defined across the mesh by barycentric interpolation. During the bake, radiance or irradiance is Monte Carlo gathered at many sample points distributed over triangle interiors (combining area-weighted and per-vertex-weighted sampling so small geometric features are not starved). Each sample contributes a row to an overdetermined system `A x ≈ b`, where the three nonzero entries in the row are the sample's barycentric weights. Forming the normal equations `A^T A x = A^T b` produces a symmetric positive-definite sparse matrix whose sparsity matches the mesh edge graph. To suppress Monte Carlo noise and stabilize sparsely sampled or sliver triangles, a small **cotangent-Laplacian** smoothness energy `λ L` is added to the normal matrix before solving via conjugate gradients or Cholesky factorization. Coplanar vertices sharing position and normal are welded, while sharp creases stay split, and oversized triangles are subdivided prior to baking so linear interpolation can capture spatial light variation. ## When to use it Choose it for static architectural or stylized meshes when you want clean baked bounce lighting with zero UV unwrapping, zero atlas padding or seam bleeding, and minimal runtime shader cost. Prefer [lightmap-baking](lightmap-baking) when large low-poly walls or floors need high-frequency shadow detail without subdividing the mesh. Prefer [irradiance-volumes](irradiance-volumes) or [ddgi](ddgi) when dynamic characters or moving lights must receive indirect illumination. Prefer [precomputed-radiance-transfer](precomputed-radiance-transfer) when lighting direction changes dynamically on static geometry. ## Cost cheap — Runtime evaluation is a single interpolated vertex attribute with no texture fetch; offline or progressive GPU baking solves a sparse linear system over the mesh vertex count. Measured GPU Weight: 5.94× baseline (light) — 0.1954 ms median / 0.2042 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.43× baseline (light) — 0.0864 ms median (2.26× faster on L4). Ampere A100 scaling: 3.85× baseline (light) — 0.1108 ms median (1.76× faster on A100). ## Failure modes - Coarse triangles cannot represent high-frequency light or shadow gradients unless the mesh is pre-subdivided along long edges - Excessive cotangent-Laplacian regularization blurs crisp contact shadows and bleeds light across thin walls if sharp creases are accidentally welded - Non-manifold or obtuse sliver triangles can yield negative cotangent weights unless clamped or replaced with intrinsic/tufted Laplacians - Static only: moving light sources or occluders require re-gathering samples and re-solving the linear system ## Dataflow - Inputs: mesh, radiance - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu ## Presets ### Least-Squares Vertex Baking — noisy per-triangle samples & seams (left) vs Laplacian-regularized vertex fit (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MESH_DENSITY": 7, "P_LAPLACIAN_REG": 0.75, "P_SUN_ANGLE": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_MESH_DENSITY = 7.0; // P Mesh Density [4.0, 14.0, 1.0] const float P_LAPLACIAN_REG = 0.75; // P Laplacian Smooth [0.0, 1.0, 0.05] const float P_SUN_ANGLE = 0.55; // P Window Sun [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Raw / LSQ Fit Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Compute analytical ground-truth multi-bounce room irradiance at surface point p with normal n vec3 evalTrueIrradiance(vec3 p, vec3 n, float sunT) { vec3 winPos = vec3(-0.92, 0.22 + 0.16 * sin(sunT), -0.35); vec3 toWin = winPos - p; float dWin = max(length(toWin), 0.25); vec3 lWin = toWin / dWin; float winBounce = max(dot(n, lWin), 0.0) / (0.35 + dWin * dWin); // Warm sunlit floor patch bounce + cool sky fill + terracotta right-wall bounce vec3 sunSpot = vec3(0.18 + 0.35 * cos(sunT * 0.7), -0.72, -0.35); float dSpot = max(length(sunSpot - p), 0.25); float spotLight = max(dot(n, normalize(sunSpot - p)), 0.0) / (0.45 + dSpot * dSpot); float rightWall = max(dot(n, vec3(1.0, 0.1, 0.0)), 0.0) / (0.6 + pow(1.05 - p.x, 2.0)); vec3 rad = vec3(1.55, 1.18, 0.76) * winBounce * 0.95 + vec3(1.35, 0.88, 0.42) * spotLight * 0.55 + vec3(0.24, 0.66, 0.92) * rightWall * 0.45 + vec3(0.16, 0.22, 0.34) * (0.5 + 0.5 * n.y); return rad; } // Triangle mesh parameterization on any planar room surface: returns barycentric weights, 3 vertex coords, and triangle ID void evalTriMesh(vec2 uv, float dens, out vec2 v0, out vec2 v1, out vec2 v2, out vec3 bary, out vec2 triId, out float wire) { vec2 g = uv * dens; vec2 cell = floor(g); vec2 f = fract(g); if (f.x + f.y <= 1.0) { v0 = cell / dens; v1 = (cell + vec2(1.0, 0.0)) / dens; v2 = (cell + vec2(0.0, 1.0)) / dens; bary = vec3(1.0 - f.x - f.y, f.x, f.y); triId = cell * 2.0; } else { v0 = (cell + vec2(1.0, 1.0)) / dens; v1 = (cell + vec2(0.0, 1.0)) / dens; v2 = (cell + vec2(1.0, 0.0)) / dens; bary = vec3(f.x + f.y - 1.0, 1.0 - f.x, 1.0 - f.y); triId = cell * 2.0 + vec2(1.0, 0.0); } float minEdge = min(bary.x, min(bary.y, bary.z)); wire = smoothstep(0.045, 0.012, minEdge); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useLSQ = sx >= split; float dens = clamp(floor(P_MESH_DENSITY + 0.5), 3.0, 16.0); float lapReg = clamp(P_LAPLACIAN_REG, 0.0, 1.0); float sunT = iTime * max(P_SUN_ANGLE, 0.0); // Camera inside an architectural room box [-1.05..1.05] x [-0.72..0.78] x [-1.45..1.5] vec3 ro = vec3(0.0, 0.04, 1.62); vec3 rd = normalize(vec3(uv, -1.28)); vec3 col = vec3(0.06, 0.08, 0.12); // Intersect 5 room planes (floor, ceiling, back, left, right) + central plinth box float tMin = 1e5; vec3 hitN = vec3(0.0, 1.0, 0.0); int faceId = 0; // Floor y = -0.72 if (rd.y < -1e-4) { float t = (-0.72 - ro.y) / rd.y; if (t > 0.05 && t < tMin) { tMin = t; hitN = vec3(0.0, 1.0, 0.0); faceId = 1; } } // Ceiling y = 0.78 if (rd.y > 1e-4) { float t = (0.78 - ro.y) / rd.y; if (t > 0.05 && t < tMin) { tMin = t; hitN = vec3(0.0, -1.0, 0.0); faceId = 2; } } // Back wall z = -1.45 if (rd.z < -1e-4) { float t = (-1.45 - ro.z) / rd.z; if (t > 0.05 && t < tMin) { tMin = t; hitN = vec3(0.0, 0.0, 1.0); faceId = 3; } } // Left wall x = -1.05 if (rd.x < -1e-4) { float t = (-1.05 - ro.x) / rd.x; if (t > 0.05 && t < tMin) { tMin = t; hitN = vec3(1.0, 0.0, 0.0); faceId = 4; } } // Right wall x = 1.05 if (rd.x > 1e-4) { float t = (1.05 - ro.x) / rd.x; if (t > 0.05 && t < tMin) { tMin = t; hitN = vec3(-1.0, 0.0, 0.0); faceId = 5; } } // Central sphere pedestal vec3 sphC = vec3(0.0, -0.34, -0.58); vec3 oc = ro - sphC; float b = dot(oc, rd); float c = dot(oc, oc) - 0.36 * 0.36; float disc = b * b - c; if (disc > 0.0) { float tS = -b - sqrt(disc); if (tS > 0.05 && tS < tMin) { tMin = tS; hitN = normalize((ro + rd * tS) - sphC); faceId = 6; } } if (faceId > 0) { vec3 p = ro + rd * tMin; vec3 alb = vec3(0.76, 0.74, 0.70); if (faceId == 4) alb = vec3(0.86, 0.42, 0.24); else if (faceId == 5) alb = vec3(0.24, 0.58, 0.78); // Bright window opening on left wall bool isWin = (faceId == 4 && abs(p.y - 0.12) < 0.34 && abs(p.z + 0.42) < 0.34); if (isWin) { col = vec3(2.8, 2.3, 1.65); } else { vec2 fuv; if (faceId == 1 || faceId == 2) fuv = p.xz; else if (faceId == 3) fuv = p.xy; else if (faceId == 4 || faceId == 5) fuv = p.zy; else fuv = vec2(atan(hitN.z, hitN.x) * 0.5, acos(clamp(hitN.y, -1.0, 1.0)) * 0.5); vec2 v0, v1, v2, triId; vec3 bary; float wire; evalTriMesh(fuv, dens, v0, v1, v2, bary, triId, wire); // Reconstruct 3D positions of the 3 mesh vertices vec3 p0 = p, p1 = p, p2 = p; if (faceId == 1 || faceId == 2) { p0 = vec3(v0.x, p.y, v0.y); p1 = vec3(v1.x, p.y, v1.y); p2 = vec3(v2.x, p.y, v2.y); } else if (faceId == 3) { p0 = vec3(v0.x, v0.y, p.z); p1 = vec3(v1.x, v1.y, p.z); p2 = vec3(v2.x, v2.y, p.z); } else if (faceId == 4 || faceId == 5) { p0 = vec3(p.x, v0.y, v0.x); p1 = vec3(p.x, v1.y, v1.x); p2 = vec3(p.x, v2.y, v2.x); } if (!useLSQ) { // Left: Raw noisy per-triangle Monte Carlo estimates (flat triangle blotches + sampling variance) vec3 triCent = (p0 + p1 + p2) / 3.0; vec3 irr = evalTrueIrradiance(triCent, hitN, sunT); float noise = (hash21(triId + float(faceId) * 19.3) - 0.5) * 0.62; irr = max(irr * (1.0 + noise), vec3(0.02)); col = alb * irr; col = mix(col, vec3(0.95, 0.52, 0.22), wire * 0.35); } else { // Right: Least-squares vertex-fitted irradiance with cotangent Laplacian regularization -> smooth C0 barycentric interpolation! vec3 i0 = evalTrueIrradiance(p0, hitN, sunT); vec3 i1 = evalTrueIrradiance(p1, hitN, sunT); vec3 i2 = evalTrueIrradiance(p2, hitN, sunT); // Residual vertex noise damped by Laplacian regularization strength float rAmp = (1.0 - lapReg) * 0.32; i0 *= 1.0 + (hash21(floor(v0 * dens + 0.5) + float(faceId) * 7.1) - 0.5) * rAmp; i1 *= 1.0 + (hash21(floor(v1 * dens + 0.5) + float(faceId) * 7.1) - 0.5) * rAmp; i2 *= 1.0 + (hash21(floor(v2 * dens + 0.5) + float(faceId) * 7.1) - 0.5) * rAmp; vec3 smoothIrr = i0 * bary.x + i1 * bary.y + i2 * bary.z; col = alb * max(smoothIrr, vec3(0.02)); // Subtle faint cyan wireframe showing exact same triangle mesh col = mix(col, vec3(0.28, 0.85, 0.95), wire * 0.14); } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): Accelerates GPU ray-traced bounce gathering at triangle interior sample points before the vertex solve. - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Supplies unbiased multi-bounce irradiance samples over triangle interiors that the least-squares solver projects onto mesh vertices. ## Sources 1. [primary] L. Kavan, A.W. Bargteil, P.‐P. Sloan (2011) Least Squares Vertex Baking. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2011.01991.x (verified via doi.org on 2026-11-30) 2. [implementation] mrdoob (2026) mrdoob/codevember-2026. https://github.com/mrdoob/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Least-Squares Vertex Light Baking." https://texelatlas.vercel.app/t/least-squares-vertex-baking/ (accessed 2026-12-01). --- id: "lens-flare" title: "Pseudo lens flare" domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2013 inputs: [hdr-image] outputs: [hdr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Chapman" url: "https://texelatlas.vercel.app/t/lens-flare/" sources_verified_at: "2026-11-29" --- # Pseudo lens flare (Chapman) > Screen-space approximation of lens ghosts and halo: mirror the bright parts of the image about the screen centre, tint and chain them, and add the result back to the HDR buffer. ## Reach for it when - bright lights look flat with no lens artefacts - want cheap cinematic ghosts and halos - need flare effect without occlusion queries - scene sun should create camera-like streaks ## How it works A thresholded, downsampled copy of the HDR image provides the bright features. For each of N ghosts, a sample coordinate is mirrored around the image centre and scaled by an increasing factor, producing copies of the light sources along the line through the centre. A radial weight fades ghosts near the edges. A halo is formed by sampling along the direction to the centre at a fixed radius and weighting by a ring function. Each ghost is tinted via a 1D gradient texture and chromatic dispersion offsets of the three channels. The result is blurred slightly, optionally multiplied by a dirt texture, and added back before tonemapping. ## When to use it Choose it for a cheap cinematic lens artefact driven by whatever is bright in the frame, with no occlusion queries. Prefer sprite-based flares with occlusion for hero art-directed suns. For soft glow without ghosts use [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md). ## Cost cheap — A handful of fetches per pixel at quarter resolution, qualitative. Measured GPU Weight: 3.16× baseline (light) — 0.104 ms median / 0.1088 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.78× baseline (light) — 0.0442 ms median (2.35× faster on L4). Ampere A100 scaling: 2.02× baseline (light) — 0.0581 ms median (1.79× faster on A100). ## Failure modes - Ghosts appear for any bright pixel, so specular glints produce unintended flare - Flicker when a light moves off screen and its ghosts pop out - Looks artificial and repetitive without a lens dirt or aperture shape - Costs and result depend on the threshold, which is scene specific ## Engine support - babylonjs: builtin — `new BABYLON.LensFlareSystem('lf', emitter, scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/LensFlares/lensFlareSystem.ts, checked 2026-12-01) - blender: builtin — `Compositor > Add > Filter > Glare, Glare Type = Ghosts (or Streaks)` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/filter/glare.html, checked 2026-12-01) — Image-space glare in the compositor. - threejs: official — `import { lensflare } from 'three/addons/tsl/display/LensflareNode.js' (WebGL: Lensflare object)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/LensflareNode.js, checked 2026-12-01) - unity: builtin — `GameObject > Effects > Lens Flare (SRP); Volume > Screen Space Lens Flare` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/lens-flare.md, checked 2026-12-01) — Data-driven lens flare asset plus a screen-space lens flare override, URP and HDRP. - unreal: builtin — `Post Process Volume > Lens > Lens Flares` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Left: bright lights only. Right: screen-space ghosts (image re-sampled through the centre at several scales) with chromatic offset (glsl-fragment; rendered 2026-11-29) ```json { "GAIN": 0.8, "CA": 0.03 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float GAIN=0.8; // P const float CA=0.03; // P const vec4 M=vec4(-2.2,-1.2,-0.75,0.65); // P vec3 B(vec2 p){ vec2 a=p-vec2(.3,.18),b=p+vec2(.28,.2); return vec3(.012,.014,.022)+vec3(1.,.85,.6)*.004/(dot(a,a)+.0006)+vec3(.6,.8,1.)*.002/(dot(b,b)+.0006);} vec3 bp(vec2 p){return max(B(p)-1.,vec3(0.));} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.; vec3 col=B(uv); if(R){vec3 fl=vec3(0.); for(int i=0;i<4;i++){float m=M[i]; float w=pow(1.-clamp(length(uv)*1.5,0.,1.),1.5); vec3 g=vec3(bp(uv*m*(1.+CA)).r,bp(uv*m).g,bp(uv*m*(1.-CA)).b); fl+=g*w*mix(vec3(1.,.8,.6),vec3(.6,.8,1.),float(i)/3.);} col+=fl*GAIN;} col=col/(1.+col); if(abs(uv.x)<.0015)col=vec3(1.); fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Combines with - [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md): Ghosts are sampled from the bloom downsample chain. ## Sources 1. [primary] John Chapman Pseudo Lens Flare. john-chapman-graphics.blogspot.com. https://john-chapman-graphics.blogspot.com/2013/02/pseudo-lens-flare.html (verified via http on 2026-11-29) 2. [implementation] Unity-Technologies (2016) Unity-Technologies/PostProcessing. https://github.com/Unity-Technologies/PostProcessing License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Pseudo lens flare." https://texelatlas.vercel.app/t/lens-flare/ (accessed 2026-12-01). --- id: "light-bvh-many-lights" title: "Light BVH and Adaptive Tree Splitting" aliases: [light tree, many-light importance sampling] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda] year_introduced: 2018 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Estevez & Kulla, 2018" url: "https://texelatlas.vercel.app/t/light-bvh-many-lights/" sources_verified_at: "2026-11-29" --- # Light BVH and Adaptive Tree Splitting (Estevez & Kulla, 2018) > Organizes emitters into a bounding-volume hierarchy with per-node energy and orientation bounds, then samples a light by descending the tree with probabilities proportional to estimated contribution at the shading point. ## Reach for it when - path tracer is slow with thousands of emissive triangles - scene with many lights is noisy - which light to sample when there are too many - emissive meshes make rendering cost explode - choose lights by their likely contribution ## How it works Choosing a light uniformly is hopeless with tens of thousands of emitters, and power-based choice ignores distance. A **light BVH** is built over the emitters. Each node stores total power, a spatial bound and an orientation cone bound for one-sided emitters. To sample a light for a shading point `x`, you walk from the root. At each node you compute an **importance** for each child using conservative bounds: power times the geometric term from the minimum distance to the bound and the cone angle factors relative to the surface normal. You choose a child with probability proportional to its importance and continue down to a leaf, accumulating the pdf along the way. The pdf for MIS is computed from the same walk. **Adaptive tree splitting** (Conty and Kulla) takes several samples per shading point and, when a node has similar importance in all children and the samples-per-node budget allows, splits the samples among both children instead of picking one. Near the tree top this stratifies samples and noticeably lowers variance. ## When to use it Choose it for offline or interactive path tracers with many emissive triangles, light-emitting meshes, or large sets of point lights, as the sampling backbone with next-event estimation. Prefer [lightcuts](lightcuts) when you want error-bounded deterministic clustering instead of stochastic sampling. Prefer [restir-di](restir-di) for real-time budgets with dynamic lights. Prefer plain power sampling with [multiple-importance-sampling](multiple-importance-sampling) when you have a few lights. ## Cost offline — Tree traversal costs a few dozen node evaluations per light sample; build cost is small and rebuilds are fast for animation. Measured GPU Weight: 87.27× baseline (extreme) — 2.8712 ms median / 3.0247 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 93.33× baseline (extreme) — 1.484 ms median (1.93× faster on L4). Ampere A100 scaling: 59.73× baseline (heavy) — 1.7203 ms median (1.67× faster on A100). ## Failure modes - Bounds are conservative, so importance for nearby shading points inside a cluster is poor and noise remains - Needs special handling for lights on both sides of the surface plane or very large emitters - Importance ignores visibility, so heavily occluded lights are over-sampled - Orientation cones are weak for omnidirectional and spherical lights ## Engine support - blender: builtin — `Properties > Render > Sampling > Lights > Light Tree` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/sampling.html, checked 2026-12-01) - unreal: builtin — `Project Settings > Rendering > MegaLights (stochastic direct-lighting importance sampling across many dynamic area lights)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/megalights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda ## Presets ### Light BVH Many-Light Sampling — noisy uniform light picking (left) vs energy-cone BVH importance sampling (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_LIGHT_COUNT": 24, "P_CONE_SHARP": 1.1, "P_ANIM_SPEED": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_LIGHT_COUNT = 24.0; // P Emitter Count [8.0, 32.0, 4.0] const float P_CONE_SHARP = 1.10; // P Orientation Bound [0.2, 2.0, 0.1] const float P_ANIM_SPEED = 0.45; // P Cluster Drift [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Uniform / BVH Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // 32 procedural point emitters organized in 4 spatial BVH clusters (amber, cyan, magenta, emerald) void getLight(int idx, float t, out vec3 pos, out vec3 col) { int cl = idx / 8; float fi = float(idx - cl * 8); float ang = fi * 0.785398 + t * (0.4 + 0.15 * float(cl)); vec3 cPos; if (cl == 0) { cPos = vec3(-1.15, 0.25, -0.35); col = vec3(2.4, 1.15, 0.35); } else if (cl == 1) { cPos = vec3(-0.32, 0.42, -0.95); col = vec3(0.28, 1.85, 2.35); } else if (cl == 2) { cPos = vec3(0.58, 0.22, -0.25); col = vec3(2.25, 0.38, 1.45); } else { cPos = vec3(1.18, 0.48, -0.95); col = vec3(0.45, 2.15, 0.85); } pos = cPos + vec3(cos(ang) * 0.36, 0.16 * sin(ang * 2.0), sin(ang) * 0.36); } 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); } vec2 mapHall(vec3 p) { float dFloor = p.y + 0.58; float dBack = p.z + 1.85; vec2 res = vec2(dFloor, 1.0); if (dBack < res.x) res = vec2(dBack, 2.0); float dB1 = sdBox(p - vec3(-0.68, -0.22, -0.62), vec3(0.22, 0.36, 0.22)); if (dB1 < res.x) res = vec2(dB1, 3.0); float dB2 = length(p - vec3(0.16, -0.28, -0.45)) - 0.30; if (dB2 < res.x) res = vec2(dB2, 3.0); float dB3 = sdBox(p - vec3(0.88, -0.18, -0.78), vec3(0.20, 0.40, 0.20)); if (dB3 < res.x) res = vec2(dB3, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapHall(p + e.xyy).x - mapHall(p - e.xyy).x, mapHall(p + e.yxy).x - mapHall(p - e.yxy).x, mapHall(p + e.yyx).x - mapHall(p - e.yyx).x )); } float evalShadow(vec3 p, vec3 lPos) { vec3 d = lPos - p; float dist = length(d); vec3 dir = d / max(dist, 1e-4); float t = 0.04; for (int i = 0; i < 14; i++) { float h = mapHall(p + dir * t).x; if (h < 0.004) return 0.0; t += max(h, 0.04); if (t >= dist - 0.05) break; } return 1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useBVH = sx >= split; int nLights = int(clamp(floor(P_LIGHT_COUNT + 0.5), 8.0, 32.0)); float coneK = clamp(P_CONE_SHARP, 0.2, 2.5); float anim = iTime * max(P_ANIM_SPEED, 0.0); vec3 ro = vec3(0.0, 0.42, 2.08); vec3 rd = normalize(vec3(uv.x, uv.y - 0.16, -1.35)); vec3 col = vec3(0.025, 0.03, 0.045); float t = 0.05; float hitId = 0.0; for (int i = 0; i < 64; i++) { vec2 h = mapHall(ro + rd * t); if (h.x < 0.002) { hitId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hitId > 0.5) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = (hitId < 1.5) ? vec3(0.56, 0.57, 0.60) : ((hitId < 2.5) ? vec3(0.45, 0.48, 0.52) : vec3(0.76, 0.76, 0.78)); // Cluster bounding centers for 2-level Light BVH importance traversal vec3 clCent[4]; clCent[0] = vec3(-1.15, 0.25, -0.35); clCent[1] = vec3(-0.32, 0.42, -0.95); clCent[2] = vec3(0.58, 0.22, -0.25); clCent[3] = vec3(1.18, 0.48, -0.95); int activeClusters = max(nLights / 8, 1); float cw[4]; float sumW = 0.0; for (int c = 0; c < 4; c++) { if (c >= activeClusters) { cw[c] = 0.0; continue; } vec3 toC = clCent[c] - p; float d2 = max(dot(toC, toC), 0.18); float cosBound = pow(max(dot(n, normalize(toC)) + 0.35, 0.05), coneK); cw[c] = cosBound / d2; sumW += cw[c]; } vec3 acc = vec3(0.0); float frameJit = floor(iTime * 10.0) * 0.13; const int SAMPLES = 4; for (int s = 0; s < SAMPLES; s++) { float u1 = hash21(fragCoord + vec2(float(s) * 19.3, frameJit * 13.7)); float u2 = hash21(fragCoord * 1.19 + vec2(frameJit * 7.1, float(s) * 31.1)); int chosenIdx = 0; float pdf = 1.0 / float(nLights); if (!useBVH) { // Left: Uniform random selection across all N lights -> massive variance & missed nearby emitters chosenIdx = int(min(floor(u1 * float(nLights)), float(nLights - 1))); } else { // Right: Light BVH descent: pick cluster with probability cw[c]/sumW, then pick child in cluster float target = u1 * max(sumW, 1e-5); int pickedCl = 0; float run = 0.0; for (int c = 0; c < 4; c++) { run += cw[c]; if (target <= run) { pickedCl = c; break; } } int subIdx = int(min(floor(u2 * 8.0), 7.0)); chosenIdx = min(pickedCl * 8 + subIdx, nLights - 1); pdf = (cw[pickedCl] / max(sumW, 1e-5)) * (1.0 / 8.0); } vec3 lPos, lCol; getLight(chosenIdx, anim, lPos, lCol); vec3 toL = lPos - p; float d2 = max(dot(toL, toL), 0.08); vec3 L = toL / sqrt(d2); float ndl = max(dot(n, L), 0.0); if (ndl > 0.002) { float vis = evalShadow(p + n * 0.015, lPos); vec3 contrib = alb * lCol * (ndl * vis / d2) * 0.055; acc += contrib / max(pdf, 1e-4); } } col = acc / float(SAMPLES) + alb * vec3(0.03, 0.035, 0.048); } // Render glowing emitter bulbs in 3D space so clusters are immediately legible for (int i = 0; i < 32; i++) { if (i >= nLights) break; vec3 lPos, lCol; getLight(i, anim, lPos, lCol); vec3 toL = lPos - ro; float proj = dot(toL, rd); if (proj > 0.1 && proj < t) { float perp = length(toL - rd * proj); col += lCol * exp(-perp * perp * 850.0) * 0.72; } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting](https://texelatlas.vercel.app/t/restir-di.md): The tree supplies better initial candidates that reservoirs then resample and reuse. ## Sources 1. [primary] Alejandro Conty Estevez, Christopher Kulla (2018) Importance Sampling of Many Lights with Adaptive Tree Splitting. Proceedings of the ACM on Computer Graphics and Interactive Techniques. https://doi.org/10.1145/3233305 (verified via crossref on 2026-11-29) 2. [implementation] mmp (2017) mmp/pbrt-v4. https://github.com/mmp/pbrt-v4 License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Light BVH and Adaptive Tree Splitting." https://texelatlas.vercel.app/t/light-bvh-many-lights/ (accessed 2026-12-01). --- id: "light-propagation-volumes" title: "Light Propagation Volumes" aliases: [LPV, cascaded LPV] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, webgl2, webgpu] year_introduced: 2009 inputs: [depth, normals, gbuffer] outputs: [irradiance-probes, radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Kaplanyan & Dachsbacher, 2010" url: "https://texelatlas.vercel.app/t/light-propagation-volumes/" sources_verified_at: "2026-11-29" --- # Light Propagation Volumes (Kaplanyan & Dachsbacher, 2010) > Injects virtual point lights from reflective shadow maps into a coarse 3D grid of spherical-harmonic radiance, then diffuses the light cell-to-cell for several iterations to approximate multi-bounce indirect lighting. ## Reach for it when - cheap dynamic indirect lighting for older hardware - one-bounce gi with no baking or ray tracing - diffuse color bleeding in moving scenes - gi that fits in a small frame time budget ## How it works A 3D grid (often cascaded around the camera) stores, per cell, the radiance as a low-order spherical-harmonic vector. Each frame has three stages. **Injection**: the texels of one or more reflective shadow maps become virtual point lights and splat their flux into the cell that contains them as an SH cosine lobe. Geometry from depth buffers is also injected as occluder SH to later block light. **Propagation**: light flows between neighbouring cells. Each cell sends a fraction of its SH radiance through each of its six faces, using precomputed face-flux coefficients and then re-projecting into the neighbouring cell's SH. Repeating this step (typically 8 to 16 iterations) pushes light farther through empty space. A geometry-volume occupancy term damps flux through solid cells. **Lookup**: shading points sample the grid trilinearly and evaluate the SH for the surface normal. This is entirely image/grid space and so scene complexity does not matter. ## When to use it Choose it as a very inexpensive dynamic GI for a single dominant light on mid-range hardware, a historical choice for 2010-era engines. Prefer [voxel-cone-tracing](voxel-cone-tracing) when higher quality glossy transport and sharper occlusion are required. Prefer [ddgi](ddgi) or [radiance-cascades](radiance-cascades) when ray tracing or SDF tracing is available. Prefer [reflective-shadow-maps](reflective-shadow-maps) alone if only a one-bounce direct gather is enough. ## Cost medium — Cost scales with cell count times propagation iterations; typically modest per cascade (32^3 per cascade is a common size). Measured GPU Weight: 34× baseline (heavy) — 1.0676 ms median / 1.1509 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 33.2× baseline (heavy) — 0.5246 ms median (2.04× faster on L4). Ampere A100 scaling: 22.17× baseline (heavy) — 0.6384 ms median (1.67× faster on A100). ## Failure modes - Light bleeding through walls thinner than a cell, since occlusion is only approximated - Low spatial resolution (cell size of tens of centimetres) so indirect shadows are very soft - Directional smearing and ringing from low-order SH in the propagation step - Cascade boundaries produce visible lighting discontinuities and flicker as the grid follows the camera ## Dataflow - Inputs: depth, normals, gbuffer - Outputs: irradiance-probes, radiance - Platforms: desktop-gpu, webgl2, webgpu ## Presets ### Light Propagation Volumes — 3D SH flux lattice injection, multi-step propagation & colored bounce bleed (glsl-fragment; rendered 2026-11-30) ```json { "P_GRID_RES": 5, "P_PROP_SPREAD": 1, "P_BOUNCE_GAIN": 1.35, "P_SPLIT": 0.36 } ``` ```glsl const float P_GRID_RES = 5.0; // P LPV Lattice Res [3.0, 9.0, 1.0] const float P_PROP_SPREAD = 1.0; // P Prop Diffusion [0.35, 2.0, 0.05] const float P_BOUNCE_GAIN = 1.35; // P LPV GI Gain [0.0, 2.5, 0.05] const float P_SPLIT = 0.36; // P Direct / LPV Split [0.0, 1.0, 0.02] 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); } // Cornell chamber with matte pedestal & central arch baffle vec2 mapRoom(vec3 p) { vec2 res = vec2(1.0 + p.y, 1.0); // floor float cD = 1.0 - p.y; if (cD < res.x) res = vec2(cD, 1.0); float bD = 1.45 + p.z; if (bD < res.x) res = vec2(bD, 1.0); float lD = 1.45 + p.x; if (lD < res.x) res = vec2(lD, 2.0); // crimson wall float rD = 1.45 - p.x; if (rD < res.x) res = vec2(rD, 3.0); // cobalt-teal wall float dP1 = sdBox(p - vec3(-0.32, -0.52, -0.35), vec3(0.28, 0.48, 0.28)) - 0.02; if (dP1 < res.x) res = vec2(dP1, 4.0); float dSph = length(p - vec3(0.42, -0.58, -0.15)) - 0.38; if (dSph < res.x) res = vec2(dSph, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRoom(p + e.xyy).x - mapRoom(p - e.xyy).x, mapRoom(p + e.yxy).x - mapRoom(p - e.yxy).x, mapRoom(p + e.yyx).x - mapRoom(p - e.yyx).x )); } // Evaluate 2-band SH LPV cell irradiance at quantized voxel center vc for surface normal n vec3 evalLpvCell(vec3 vc, vec3 n, vec3 sunPatch, float spread) { // 3 injected directional flux sources propagated through the 3D SH lattice: // 1) Sunlit floor/wall bounce patch (sweeps across the red & teal walls) vec3 dSun = sunPatch - vc; float rSun = length(dSun) + 0.35; vec3 dirSun = dSun / max(length(dSun), 1e-4); vec3 patchCol = mix(vec3(1.1, 0.92, 0.65), vec3(1.45, 0.24, 0.16), smoothstep(-0.3, -1.2, sunPatch.x)); patchCol = mix(patchCol, vec3(0.16, 1.15, 0.92), smoothstep(0.3, 1.2, sunPatch.x)); // SH L0 (isotropic) + L1 (directional cosine lobe) propagation kernel float kSun = exp(-rSun * (0.95 / max(spread, 0.2))) / (0.45 + rSun * rSun * 0.6); float shSun = 0.45 + 0.55 * max(dot(n, dirSun), 0.0); // 2) Persistent crimson left wall flux vec3 dLeft = vec3(-1.42, vc.y * 0.5, -0.35) - vc; float rL = length(dLeft) + 0.4; float shL = 0.42 + 0.58 * max(dot(n, normalize(dLeft)), 0.0); vec3 fluxL = vec3(1.05, 0.16, 0.12) * exp(-rL * (0.85 / max(spread, 0.2))) * shL * 0.52; // 3) Persistent teal right wall flux vec3 dRight = vec3(1.42, vc.y * 0.5, -0.35) - vc; float rR = length(dRight) + 0.4; float shR = 0.42 + 0.58 * max(dot(n, normalize(dRight)), 0.0); vec3 fluxR = vec3(0.12, 0.88, 0.72) * exp(-rR * (0.85 / max(spread, 0.2))) * shR * 0.52; return patchCol * kSun * shSun * 1.45 + fluxL + fluxR; } // Trilinearly interpolated 3D LPV lookup matching hardware 3D texture sampling vec3 sampleLPV(vec3 p, vec3 n, vec3 sunPatch, float gridRes, float spread) { vec3 gp = p * gridRes; vec3 base = floor(gp); vec3 f = fract(gp); vec3 c000 = evalLpvCell((base + vec3(0.5, 0.5, 0.5)) / gridRes, n, sunPatch, spread); vec3 c100 = evalLpvCell((base + vec3(1.5, 0.5, 0.5)) / gridRes, n, sunPatch, spread); vec3 c010 = evalLpvCell((base + vec3(0.5, 1.5, 0.5)) / gridRes, n, sunPatch, spread); vec3 c110 = evalLpvCell((base + vec3(1.5, 1.5, 0.5)) / gridRes, n, sunPatch, spread); vec3 c001 = evalLpvCell((base + vec3(0.5, 0.5, 1.5)) / gridRes, n, sunPatch, spread); vec3 c101 = evalLpvCell((base + vec3(1.5, 0.5, 1.5)) / gridRes, n, sunPatch, spread); vec3 c011 = evalLpvCell((base + vec3(0.5, 1.5, 1.5)) / gridRes, n, sunPatch, spread); vec3 c111 = evalLpvCell((base + vec3(1.5, 1.5, 1.5)) / gridRes, n, sunPatch, spread); vec3 c00 = mix(c000, c100, f.x); vec3 c10 = mix(c010, c110, f.x); vec3 c01 = mix(c001, c101, f.x); vec3 c11 = mix(c011, c111, f.x); return mix(mix(c00, c10, f.y), mix(c01, c11, f.y), f.z); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float gridRes = clamp(floor(P_GRID_RES + 0.5), 2.0, 10.0); float spread = clamp(P_PROP_SPREAD, 0.3, 2.2); float giGain = max(P_BOUNCE_GAIN, 0.0); vec3 ro = vec3(0.0, 0.04, 2.35); vec3 rd = normalize(vec3(uv, -1.48)); // Sweeping direct sun spot injecting VPL flux into the LPV lattice vec3 sunPatch = vec3(1.15 * sin(iTime * 0.55), -0.95 + 0.45 * abs(sin(iTime * 0.55)), -0.35 + 0.45 * cos(iTime * 0.42)); vec3 lightPos = vec3(0.0, 0.92, 0.25); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapRoom(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = vec3(0.76, 0.76, 0.74); if (matId > 1.5 && matId < 2.5) alb = vec3(0.86, 0.14, 0.12); else if (matId > 2.5 && matId < 3.5) alb = vec3(0.10, 0.74, 0.62); else if (matId > 3.5) alb = vec3(0.84, 0.83, 0.80); // Focused direct spotlight beam illuminating sunPatch vec3 toL = lightPos - p; float dL = length(toL); vec3 lDir = toL / max(dL, 1e-4); vec3 spotAxis = normalize(sunPatch - lightPos); float spotCos = dot(-lDir, spotAxis); float spotMask = smoothstep(0.80, 0.94, spotCos); // Shadow march toward ceiling spotlight float sh = 1.0; float ts = 0.03; for (int i = 0; i < 24; i++) { float dh = mapRoom(p + lDir * ts).x; if (dh < 0.004) { sh = 0.0; break; } ts += dh; if (ts > dL - 0.08) break; } vec3 direct = alb * vec3(2.8, 2.5, 2.1) * max(dot(n, lDir), 0.0) * spotMask * sh / (1.0 + 0.25 * dL * dL); // Subtle ambient fill + LPV trilinearly sampled SH indirect bounce vec3 lpvIrr = sampleLPV(p + n * 0.04, n, sunPatch, gridRes, spread); vec3 indirect = alb * lpvIrr * giGain; // Show subtle 3D LPV voxel cell boundaries on surfaces so the lattice scale is immediately legible vec3 vf = abs(fract(p * gridRes - 0.5) - 0.5); float vEdge = smoothstep(0.035, 0.008, min(vf.x, min(vf.y, vf.z))); vec3 leftCol = direct + alb * vec3(0.03, 0.035, 0.045); vec3 rightCol = direct + indirect + lpvIrr * vEdge * 0.18; col = (screenX < split) ? leftCol : rightCol; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Reflective Shadow Maps](https://texelatlas.vercel.app/t/reflective-shadow-maps.md): RSM texels are the virtual lights that get injected into the volume. ## Sources 1. [primary] Anton Kaplanyan, Carsten Dachsbacher (2010) Cascaded light propagation volumes for real-time indirect illumination. Proceedings of the 2010 ACM SIGGRAPH symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/1730804.1730821 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Light Propagation Volumes." https://texelatlas.vercel.app/t/light-propagation-volumes/ (accessed 2026-12-01). --- id: "light-stage-reflectance-capture" title: "Light Stage Reflectance Capture" aliases: [light stage, reflectance field capture] domain: "capture" stage: "capture" realtime: "offline" platforms: [cpu] year_introduced: 2000 inputs: [photos] outputs: [texture, material-params, normals] style: "photoreal" dynamic: "static" cost: "offline" authority: "Debevec et al., 2000" url: "https://texelatlas.vercel.app/t/light-stage-reflectance-capture/" sources_verified_at: "2026-11-29" --- # Light Stage Reflectance Capture (Debevec et al., 2000) > Photographs a subject lit from many directions, one at a time, to record its reflectance field, enabling relighting and recovery of albedo, normals and specular layers. ## Reach for it when - need to relight a captured face or object - want highest quality skin appearance capture - need albedo, normals and specular from real subject - baked lighting in captures prevents relighting ## How it works A rig of many point-like light sources on a sphere around the subject is flashed in sequence while a calibrated camera captures an image per light. Because light transport is linear, the stack of images is the subject's reflectance field sampled at the light directions. Any lighting environment is reproduced by weighting each basis image by the environment's radiance in that direction and summing, which gives physically correct relighting with all inter-reflection and subsurface effects included. Later systems add polarised lighting to separate specular from diffuse components, and gradient illumination patterns to estimate normals and albedo with few frames. These measurements feed photoreal digital humans and give training data for appearance models. ## When to use it Choose it for the highest-fidelity skin or object appearance capture and relighting when you can build or access a rig. Prefer [Photometric Stereo](https://texelatlas.vercel.app/t/photometric-stereo.md) for a cheaper, small-scale rig that only needs normals and albedo, [Neural Radiance Fields (NeRF)](https://texelatlas.vercel.app/t/nerf.md) or [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for casual capture with baked-in lighting, and [Universal Photometric Stereo (SDM-UniPS)](https://texelatlas.vercel.app/t/universal-photometric-stereo.md) for handheld varying light. ## Cost offline — Capture takes a fraction of a second to seconds per pose; relighting from the basis images is cheap. Measured GPU Weight: 26.85× baseline (heavy) — 0.8322 ms median / 0.842 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.19× baseline (heavy) — 0.321 ms median (2.59× faster on L4). Ampere A100 scaling: 18.65× baseline (moderate) — 0.5371 ms median (1.55× faster on A100). ## Failure modes - Subject motion between flashes causes ghosting unless frames are aligned - Finite light count restricts relighting to low-to-mid frequency environments, with sharp highlights stepping - Needs large, calibrated hardware, so cost and access are limiting - Polarisation separation fails for strongly depolarising materials ## Dataflow - Inputs: photos - Outputs: texture, material-params, normals - Platforms: cpu ## Presets ### Light Stage Reflectance Capture — cross-polarized diffuse (left) vs full polarized SH relighting (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ENV_ROT": 0.75, "P_SPEC_SEP": 1, "P_LED_DOME": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_ENV_ROT = 0.75; // P Relight Orbit [0.0, 2.2, 0.05] const float P_SPEC_SEP = 1.0; // P Specular Lobe [0.0, 2.0, 0.05] const float P_LED_DOME = 0.85; // P LED Dome Nodes [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Diffuse / Relit Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Sculpted classical portrait bust inside the geodesic Light Stage capture sphere float mapBust(vec3 p) { // Cranium + jaw + nose bridge + brow ridge + neck/shoulders float dHead = length(vec3(p.x * 1.15, (p.y - 0.14) * 0.90, p.z * 1.05)) - 0.42; float dJaw = length(vec3(p.x * 1.25, (p.y + 0.10) * 1.1, (p.z - 0.08) * 1.15)) - 0.30; float dNose = length(vec3(p.x * 2.4, (p.y - 0.08) * 1.2, (p.z - 0.38) * 1.6)) - 0.10; float dBrow = length(vec3(p.x * 0.9, (p.y - 0.22) * 3.0, (p.z - 0.30) * 2.2)) - 0.14; float dNeck = max(length(p.xz - vec2(0.0, -0.04)) - 0.16, abs(p.y + 0.42) - 0.24); float dShoulders = length(vec3(p.x * 0.55, (p.y + 0.68) * 1.4, p.z * 1.25)) - 0.36; float face = smin(dHead, dJaw, 0.14); face = smin(face, dNose, 0.05); face = smin(face, dBrow, 0.06); // Subtle eye-socket indentations for rich grazing specular + diffuse subsurface cues float dEyes = length(vec3(abs(p.x) - 0.13, p.y - 0.15, p.z - 0.33)) - 0.075; face = max(face, -dEyes * 0.45); float bust = smin(face, dNeck, 0.08); bust = smin(bust, dShoulders, 0.10); return bust * 0.85; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapBust(p + e.xyy) - mapBust(p - e.xyy), mapBust(p + e.yxy) - mapBust(p - e.yxy), mapBust(p + e.yyx) - mapBust(p - e.yyx) )); } // Spherical-Harmonic relighting basis reconstructed from OLAT Light Stage dome captures vec3 evalLightStageEnv(vec3 dir, float rotAng) { vec3 d = dir; d.xz = rot2(rotAng) * d.xz; // Studio key (warm sunset), rim (electric cyan), overhead softbox vec3 keyDir = normalize(vec3(0.68, 0.48, 0.55)); vec3 rimDir = normalize(vec3(-0.75, 0.25, -0.52)); vec3 fillDir = normalize(vec3(0.0, 0.92, -0.25)); vec3 env = vec3(0.08, 0.10, 0.15); env += vec3(2.4, 1.55, 0.88) * pow(max(dot(d, keyDir), 0.0), 3.0); env += vec3(0.35, 1.35, 1.95) * pow(max(dot(d, rimDir), 0.0), 4.0); env += vec3(0.75, 0.82, 0.95) * max(dot(d, fillDir), 0.0) * 0.65; return env; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isFullRelit = screenX >= split; float envRot = iTime * max(P_ENV_ROT, 0.0); float specGain = clamp(P_SPEC_SEP, 0.0, 2.2); float domeVis = clamp(P_LED_DOME, 0.0, 1.5); vec3 ro = vec3(0.0, 0.04, 2.25); vec3 rd = normalize(vec3(uv, -1.55)); // Background: geodesic Light Stage spherical LED dome with active OLAT/gradient LEDs! vec3 domeDir = normalize(vec3(uv * 1.45, -1.0)); float theta = atan(domeDir.x, -domeDir.z); float phi = asin(clamp(domeDir.y, -1.0, 1.0)); vec2 ledGrid = vec2(theta * 5.0, phi * 5.0); vec2 ledCell = floor(ledGrid); vec2 ledF = fract(ledGrid) - 0.5; float ledDot = smoothstep(0.16, 0.05, length(ledF)); float strut = smoothstep(0.05, 0.012, min(abs(ledF.x), abs(ledF.y))); vec3 ledCol = evalLightStageEnv(domeDir, envRot); vec3 col = vec3(0.022, 0.028, 0.042) + vec3(0.05, 0.07, 0.11) * strut * min(domeVis, 1.0); col += ledCol * ledDot * 0.85 * min(domeVis, 1.2); float t = 0.0; bool hit = false; for (int i = 0; i < 68; i++) { float d = mapBust(ro + rd * t); if (d < 0.002) { hit = true; break; } t += d; if (t > 7.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 v = -rd; // Fine skin/stone pore micro-normal perturbation (captured by Light Stage specular normal map!) float pore = sin(p.x * 85.0) * sin(p.y * 85.0) * cos(p.z * 85.0); vec3 nSpec = normalize(n + vec3(pore, -pore, 0.0) * 0.045); // Subsurface warm diffuse albedo (captured via cross-polarized spherical gradient illumination) vec3 diffAlb = mix(vec3(0.76, 0.54, 0.44), vec3(0.84, 0.66, 0.56), clamp(p.y + 0.35, 0.0, 1.0)); // Diffuse irradiance from SH Light Stage integration (softened normal for subsurface wrap) vec3 diffIrr = evalLightStageEnv(n, envRot) * 0.55 + evalLightStageEnv(normalize(n + vec3(0.0, 0.3, 0.2)), envRot) * 0.25; vec3 diffusePart = diffAlb * diffIrr * 0.72; if (!isFullRelit) { // Left: Cross-polarized capture isolates pure diffuse subsurface albedo (zero specular shine!) col = diffusePart; } else { // Right: Full separated reflectance field = diffuse + polarized dual-lobe specular + Fresnel rim vec3 rDir = reflect(-v, nSpec); float fres = 0.035 + 0.965 * pow(1.0 - max(dot(nSpec, v), 0.0), 5.0); vec3 specEnv = evalLightStageEnv(rDir, envRot); // Primary crisp oil-sheen specular + broader micro-roughness specular vec3 kDir = normalize(vec3(0.68, 0.48, 0.55)); kDir.xz = rot2(-envRot) * kDir.xz; float sLobe1 = pow(max(dot(nSpec, normalize(kDir + v)), 0.0), 68.0); float sLobe2 = pow(max(dot(nSpec, normalize(kDir + v)), 0.0), 16.0); vec3 specPart = (specEnv * fres * 0.85 + vec3(1.0, 0.92, 0.84) * (sLobe1 * 0.95 + sLobe2 * 0.28)) * specGain; col = diffusePart + specPart; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Photometric Stereo](https://texelatlas.vercel.app/t/photometric-stereo.md): Light stage frames provide the multi-light images from which normals and albedo are solved. ## Combination ideas - [ReSTIR GI relighting of light-stage reflectance captures](https://texelatlas.vercel.app/ideas/light-stage-albedo-restir-gi/) ## Sources 1. [primary] Paul Debevec, Tim Hawkins, Chris Tchou, Haarm-Pieter Duiker, Westley Sarokin, Mark Sagar (2000) Acquiring the reflectance field of a human face. Proceedings of the 27th annual conference on Computer graphics and interactive techniques - SIGGRAPH '00. https://doi.org/10.1145/344779.344855 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Light Stage Reflectance Capture." https://texelatlas.vercel.app/t/light-stage-reflectance-capture/ (accessed 2026-12-01). --- id: "lightcuts" title: "Lightcuts" aliases: [multidimensional lightcuts] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu] year_introduced: 2005 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "static" cost: "offline" authority: "Walter et al., 2005" url: "https://texelatlas.vercel.app/t/lightcuts/" sources_verified_at: "2026-11-29" --- # Lightcuts (Walter et al., 2005) > Clusters many point lights into a hierarchy and, per shading point, picks a cut through it that bounds the error, so the cost grows sublinearly with light count and error stays below a perceptual threshold. ## Reach for it when - render time grows linearly with number of lights - need error-bounded approximation of many point lights - environment lighting with thousands of directional lights - virtual point lights are too expensive to evaluate all - want deterministic many-light cost with perceptual error limit ## How it works Given thousands to millions of point lights (real lights, virtual lights from [instant-radiosity](instant-radiosity), environment map samples), lightcuts builds a **light tree** where each node represents a cluster by a single representative light and an intensity sum. For a shading point, the renderer starts with a **cut** consisting of the root. It evaluates the cluster's contribution using the representative, and a cheap upper bound on the error of that approximation (bounds on the geometric, material and visibility terms, with visibility conservatively taken as 1). If the bound exceeds a threshold of about 2 percent of the current total, the cluster with the largest bound is replaced by its children. This repeats until every cluster is below the threshold. The error bound is perceptually motivated (Weber's law), so brighter points allow larger absolute errors. **Multidimensional lightcuts** extends the tree to cover other integrals (pixel area, motion blur, depth of field, participating media) by clustering the product of lights and gather points, so the same cut mechanism handles all these effects. ## When to use it Choose it when you have many fixed point lights or need deterministic error-bounded convergence for a many-light approximation, such as VPL-based GI or HDR environment illumination with thousands of directional lights. Prefer [light-bvh-many-lights](light-bvh-many-lights) when you want a stochastic, unbiased sampler inside a path tracer. Prefer [restir-di](restir-di) for real-time dynamic lights. Prefer [path-tracing](path-tracing) when the number of emitters is small. ## Cost offline — Cuts are typically a few hundred nodes per shading point, regardless of the total light count. Measured GPU Weight: 20.89× baseline (heavy) — 0.6873 ms median / 0.7516 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.07× baseline (heavy) — 0.3191 ms median (2.15× faster on L4). Ampere A100 scaling: 14.08× baseline (moderate) — 0.4054 ms median (1.7× faster on A100). ## Failure modes - Conservative visibility bound (assume visible) causes oversized cuts in heavily shadowed regions - Bias from representative-light substitution: clustering can create visible banding when the error threshold is loose - Singularities at near-field VPLs still require clamping that darkens corners - Light tree must be rebuilt when emitters move, so animated lights lose the amortization ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu ## Presets ### Lightcuts — adaptive per-pixel tree cut-size heatmap (left) vs perceptually bounded hierarchical shading (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ERR_THRESH": 0.06, "P_LIGHT_SPREAD": 1, "P_CAM_MOVE": 0.35, "P_SPLIT": 0.48 } ``` ```glsl const float P_ERR_THRESH = 0.06; // P Error Threshold [0.01, 0.25, 0.01] const float P_LIGHT_SPREAD = 1.00; // P Cluster Spread [0.5, 1.6, 0.05] const float P_CAM_MOVE = 0.35; // P Orbit Speed [0.0, 1.2, 0.05] const float P_SPLIT = 0.48; // P Cut Heatmap / Lit [0.0, 1.0, 0.02] void getClusterLight(int cl, int sub, float spread, out vec3 pos, out vec3 col) { vec3 center; if (cl == 0) { center = vec3(-1.05, 0.35, -0.25); col = vec3(2.2, 1.35, 0.55); } else if (cl == 1) { center = vec3(0.0, 0.55, -0.92); col = vec3(0.45, 1.65, 2.45); } else if (cl == 2) { center = vec3(1.05, 0.32, -0.30); col = vec3(2.35, 0.55, 1.15); } else { center = vec3(0.0, 0.18, 0.42); col = vec3(0.65, 2.20, 0.95); } float ang = float(sub) * 1.0471975 + float(cl) * 0.7; float r = 0.24 * spread; pos = center + vec3(cos(ang) * r, 0.12 * sin(ang * 2.0), sin(ang) * r); } vec2 mapRoom(vec3 p) { float dFloor = p.y + 0.58; float dBack = p.z + 1.85; vec2 res = vec2(dFloor, 1.0); if (dBack < res.x) res = vec2(dBack, 2.0); float dArch1 = length(p - vec3(-0.62, -0.26, -0.45)) - 0.32; if (dArch1 < res.x) res = vec2(dArch1, 3.0); float dArch2 = length(p - vec3(0.58, -0.26, -0.58)) - 0.32; if (dArch2 < res.x) res = vec2(dArch2, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRoom(p + e.xyy).x - mapRoom(p - e.xyy).x, mapRoom(p + e.yxy).x - mapRoom(p - e.yxy).x, mapRoom(p + e.yyx).x - mapRoom(p - e.yyx).x )); } vec3 infernoMap(float t) { t = clamp(t, 0.0, 1.0); vec3 c0 = vec3(0.07, 0.05, 0.22); vec3 c1 = vec3(0.58, 0.14, 0.46); vec3 c2 = vec3(0.96, 0.48, 0.12); vec3 c3 = vec3(0.99, 0.96, 0.58); if (t < 0.33) return mix(c0, c1, t * 3.0); if (t < 0.66) return mix(c1, c2, (t - 0.33) * 3.0); return mix(c2, c3, (t - 0.66) * 3.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showShaded = sx >= split; float errThr = clamp(P_ERR_THRESH, 0.008, 0.30); float spread = clamp(P_LIGHT_SPREAD, 0.4, 1.8); float camA = sin(iTime * max(P_CAM_MOVE, 0.0)) * 0.32; vec3 ro = vec3(camA, 0.44, 2.08); vec3 ta = vec3(0.0, -0.22, -0.52); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.38 + ri * uv.x + up * uv.y); vec3 col = vec3(0.03, 0.035, 0.05); float t = 0.05; float hitId = 0.0; for (int i = 0; i < 64; i++) { vec2 h = mapRoom(ro + rd * t); if (h.x < 0.002) { hitId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hitId > 0.5) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = (hitId < 1.5) ? vec3(0.62, 0.62, 0.65) : ((hitId < 2.5) ? vec3(0.50, 0.52, 0.56) : vec3(0.84, 0.82, 0.78)); // Lightcuts per-pixel adaptive cut across 4 clusters x 6 leaf lights = 24 lights vec3 clCent[4]; vec3 clCol[4]; clCent[0] = vec3(-1.05, 0.35, -0.25); clCol[0] = vec3(2.2, 1.35, 0.55); clCent[1] = vec3(0.0, 0.55, -0.92); clCol[1] = vec3(0.45, 1.65, 2.45); clCent[2] = vec3(1.05, 0.32, -0.30); clCol[2] = vec3(2.35, 0.55, 1.15); clCent[3] = vec3(0.0, 0.18, 0.42); clCol[3] = vec3(0.65, 2.20, 0.95); vec3 irr = vec3(0.0); float cutNodes = 0.0; float clRad = 0.28 * spread; for (int cl = 0; cl < 4; cl++) { float dCl = length(clCent[cl] - p); // Lightcuts upper error bound for collapsing cluster into 1 representative node: proportional to radius / dist^2 float minDist = max(dCl - clRad, 0.12); float errBound = (clRad * 1.45) / max(minDist * minDist, 0.04); if (errBound <= errThr * 8.5) { // Accept collapsed cluster node (1 representative evaluation for all 6 lights!) cutNodes += 1.0; vec3 toL = clCent[cl] - p; float d2 = max(dot(toL, toL), 0.12); float ndl = max(dot(n, toL / sqrt(d2)), 0.0); irr += clCol[cl] * (6.0 * ndl / d2) * 0.045; } else { // Refine cluster into individual leaf lights (6 evaluations) cutNodes += 6.0; for (int sub = 0; sub < 6; sub++) { vec3 lPos, lCol; getClusterLight(cl, sub, spread, lPos, lCol); vec3 toL = lPos - p; float d2 = max(dot(toL, toL), 0.08); float ndl = max(dot(n, toL / sqrt(d2)), 0.0); irr += lCol * (ndl / d2) * 0.045; } } } if (showShaded) { col = alb * (irr + vec3(0.035, 0.042, 0.058)); } else { // Left: Adaptive cut-size heatmap (dark indigo = 4 collapsed nodes, bright gold = 18-24 refined leaf nodes) float normCut = (cutNodes - 4.0) / 20.0; vec3 heat = infernoMap(normCut); float shadingHint = 0.45 + 0.55 * clamp(dot(irr, vec3(0.3, 0.6, 0.1)), 0.0, 1.0); // Subtle iso-boundary contour between collapsed and refined regions float iso = smoothstep(0.08, 0.02, abs(fract(cutNodes / 5.0) - 0.5)); col = heat * shadingHint + vec3(0.95, 0.98, 1.0) * iso * 0.18; } } // Draw glowing cluster leaves so user sees the light hierarchy directly for (int cl = 0; cl < 4; cl++) { for (int sub = 0; sub < 6; sub++) { vec3 lPos, lCol; getClusterLight(cl, sub, spread, lPos, lCol); vec3 toL = lPos - ro; float proj = dot(toL, rd); if (proj > 0.1 && proj < t) { float perp = length(toL - rd * proj); col += lCol * exp(-perp * perp * 1100.0) * 0.58; } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Instant Radiosity (Virtual Point Lights)](https://texelatlas.vercel.app/t/instant-radiosity.md): Lightcuts gathers the thousands of virtual point lights that instant radiosity generates. ## Sources 1. [primary] Bruce Walter, Sebastian Fernandez, Adam Arbree, Kavita Bala, Michael Donikian, Donald P. Greenberg (2005) Lightcuts. ACM Transactions on Graphics. https://doi.org/10.1145/1073204.1073318 (verified via crossref on 2026-11-29) 2. [primary] Bruce Walter, Adam Arbree, Kavita Bala, Donald P. Greenberg (2006) Multidimensional lightcuts. ACM Transactions on Graphics. https://doi.org/10.1145/1141911.1141997 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Lightcuts." https://texelatlas.vercel.app/t/lightcuts/ (accessed 2026-12-01). --- id: "lightglue-feature-matching" title: "LightGlue feature matching" aliases: [LightGlue] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python, cpu] year_introduced: 2023 inputs: [photos] outputs: [camera-poses, point-cloud] style: "photoreal" dynamic: "static" cost: "offline" authority: "Lindenberger et al., 2023" url: "https://texelatlas.vercel.app/t/lightglue-feature-matching/" sources_verified_at: "2026-11-29" --- # LightGlue feature matching (Lindenberger et al., 2023) > A transformer matcher that pairs local keypoints such as SuperPoint or DISK between two images and stops early on easy pairs, giving accurate correspondences for SfM and localisation. ## Reach for it when - sift matching finds too few correct matches - photos fail to register in my sfm reconstruction - match keypoints across large viewpoint change - need faster learned matching for pose estimation ## How it works Given keypoints with descriptors from a detector for two images, LightGlue runs a stack of attention layers. Each layer applies self-attention within an image and cross-attention across the pair, with rotary positional encodings on keypoint positions, then predicts assignment scores. A small classifier after each layer decides if a keypoint's match is already confident (so it is frozen) or whether the pair is already settled, and a pruning step removes keypoints unlikely to match, so easy image pairs finish in fewer layers than hard ones. Final matches come from a mutual-match test on soft assignment scores with a learned unmatchable-point score. The matches feed geometric verification (essential or fundamental matrix with RANSAC), triangulation and bundle adjustment in a pipeline like [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md). ## When to use it Choose it as the matcher in a modern SfM or localisation pipeline where nearest-neighbour descriptor matching and ratio tests give too few correct matches under viewpoint, lighting or texture variation. Prefer classic SIFT with ratio-test matching when you need a CPU-only, learning-free baseline, [DUSt3R](https://texelatlas.vercel.app/t/dust3r.md) or [MASt3R](https://texelatlas.vercel.app/t/mast3r.md) when you want a pose-free dense learned alternative, and [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md) for the surrounding reconstruction pipeline itself. ## Cost offline — Per image pair it takes tens of milliseconds on a desktop GPU; large collections need pair selection since pairs grow quadratically. ## Failure modes - Repeated structures like windows or tiles yield confident but wrong matches that geometric verification must filter - Performance depends on the detector; weak keypoints in textureless regions cannot be rescued by the matcher - Extreme viewpoint changes or rotation beyond the training range reduce matches unless augmented - Pairwise matching cost grows quadratically with image count without retrieval-based pair selection ## Dataflow - Inputs: photos - Outputs: camera-poses, point-cloud - Platforms: cuda, python, cpu ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): LightGlue's verified matches replace the default matcher stage before triangulation and bundle adjustment. - [Nerfstudio](https://texelatlas.vercel.app/t/nerfstudio.md): Better matched poses give nerfstudio and splat training cleaner camera input from hard captures. ## Sources 1. [primary] Philipp Lindenberger, Paul-Edouard Sarlin, Marc Pollefeys (2023) LightGlue: Local Feature Matching at Light Speed. arXiv preprint (cs.CV). https://arxiv.org/abs/2306.13643 (verified via arxiv on 2026-11-29) 2. [implementation] cvg (2023) cvg/LightGlue. https://github.com/cvg/LightGlue License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "LightGlue feature matching." https://texelatlas.vercel.app/t/lightglue-feature-matching/ (accessed 2026-12-01). --- id: "lightmap-baking" title: "Lightmap Baking" aliases: [baked GI, precomputed lighting, lightmapping] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 1996 inputs: [mesh, uv-atlas, material-params] outputs: [texture] style: "photoreal" dynamic: "static" cost: "cheap" authority: "Iwanicki, 2013" url: "https://texelatlas.vercel.app/t/lightmap-baking/" sources_verified_at: "2026-11-29" --- # Lightmap Baking (Iwanicki, 2013) > Precomputes the lighting of static surfaces offline into textures addressed by a second, non-overlapping UV set, then samples them at runtime for essentially free GI. ## Reach for it when - static scenes need free high quality gi at runtime - mobile game needs precomputed lighting - lighting looks flat with only direct lights - bake shadows and bounce light into textures ## How it works Every static mesh gets a **lightmap UV atlas**: a unique, non-overlapping unwrap with padding between charts so bilinear filtering does not bleed. Texels of the atlas are mapped back to world positions and normals. A baker then computes the irradiance (or directional radiance) at each texel with an offline integrator, typically [path-tracing](path-tracing) with many samples, and writes the results into a texture. Storage formats include RGB irradiance, plus a dominant light direction or low-order spherical-harmonic or spherical-Gaussian coefficients so normal maps still respond to the light. After baking, a **denoiser** cleans the noisy output and a **dilation** pass fills texels outside the charts to avoid seams. At runtime the shader multiplies albedo by the sampled lightmap value, optionally combined with real-time direct light and [irradiance-volumes](irradiance-volumes) probes for dynamic objects. The baker is the offline system; the runtime cost is one texture fetch per pixel. ## When to use it Choose it for static scenes, mobile and web targets, and anything with a tight frame budget where high-quality interreflection and soft shadows must be paid for once. Prefer [irradiance-volumes](irradiance-volumes) for dynamic objects and for volumes without UVs. Prefer [ddgi](ddgi), [lumen-gi](lumen-gi) or [surfel-gi](surfel-gi) when lights or geometry move at runtime. Prefer [precomputed-radiance-transfer](precomputed-radiance-transfer) when the light changes but the geometry is rigid. ## Cost cheap — Runtime cost is a texture fetch; bake time ranges from minutes to hours depending on resolution and sample count. Memory grows with atlas resolution. Measured GPU Weight: 26.9× baseline (heavy) — 0.8339 ms median / 0.947 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.75× baseline (heavy) — 0.4413 ms median (1.89× faster on L4). Ampere A100 scaling: 17.17× baseline (moderate) — 0.4946 ms median (1.69× faster on A100). ## Failure modes - Seams along chart borders from missing padding or inconsistent texel density between adjacent charts - Light and shadow bleeding where thin walls share texels from both sides - Static only: moving lights or doors leave baked shadows behind, requiring a hybrid with dynamic direct light - Atlas packing waste and long iteration times: any geometry or light edit requires a rebake ## Engine support - blender: builtin — `Properties > Render > Bake (Cycles), Bake button` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/baking.html, checked 2026-12-01) - godot: builtin — `Add a LightmapGI node and bake (LightmapGI.bake())` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/LightmapGI.xml, checked 2026-12-01) — GPU lightmapper (LightmapperRD) bakes lightmaps with denoising. - threejs: official — `import { LightMapper } from 'three/addons/lighting/LightMapper.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/lighting/LightMapper.js, checked 2026-12-01) — WebGPURenderer only. - unity: builtin — `Window > Rendering > Lighting > Lightmapping Settings > Progressive GPU/CPU` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/progressive-lightmapper.html, checked 2026-12-01) — Progressive Lightmapper (CPU/GPU) in URP and HDRP. - unreal: official — `Enable the GPU Lightmass plugin; World Settings > Lightmass; build lighting with GPU Lightmass (or built-in CPU Lightmass)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/gpu-lightmass-global-illumination-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, uv-atlas, material-params - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Lightmap Baking — coarse UV-chart texels & seams (left) vs high-res directional baked lightmap (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TEXEL_RES": 10, "P_BOUNCE_INT": 1.25, "P_CHART_VIS": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_TEXEL_RES = 10.0; // P Low-Res Texels [4.0, 20.0, 1.0] const float P_BOUNCE_INT = 1.25; // P Baked GI Gain [0.3, 2.2, 0.05] const float P_CHART_VIS = 0.75; // P UV Chart Grid [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Coarse / Fine Split [0.0, 1.0, 0.02] 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); } // Sunlit architectural gallery with skylight aperture and sculpted bench + archway vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); float dC = 1.05 - p.y; if (dC < res.x) res = vec2(dC, 1.0); float dB = p.z + 1.45; if (dB < res.x) res = vec2(dB, 2.0); float dL = p.x + 1.35; if (dL < res.x) res = vec2(dL, 3.0); float dR = 1.35 - p.x; if (dR < res.x) res = vec2(dR, 4.0); float dBench = sdBox(p - vec3(-0.35, -0.58, -0.35), vec3(0.42, 0.27, 0.24)) - 0.02; if (dBench < res.x) res = vec2(dBench, 5.0); float dPed = sdBox(p - vec3(0.55, -0.45, -0.55), vec3(0.24, 0.40, 0.24)) - 0.02; if (dPed < res.x) res = vec2(dPed, 5.0); float dSph = length(p - vec3(0.55, 0.14, -0.55)) - 0.22; if (dSph < res.x) res = vec2(dSph, 6.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Evaluate precomputed static lightmap irradiance at UV-mapped surface point p vec3 bakeLightmap(vec3 p, vec3 n, float giGain) { // Warm angled skylight beam hitting floor & bench + soft indirect bounce vec3 sunDir = normalize(vec3(0.45, 0.82, 0.35)); float tPlane = (1.05 - p.y) / sunDir.y; vec2 skyHit = p.xz + sunDir.xz * tPlane; float inBeam = smoothstep(0.52, 0.34, abs(skyHit.x + 0.15)) * smoothstep(0.42, 0.26, abs(skyHit.y + 0.35)); float ndl = max(dot(n, sunDir), 0.0); // Soft shadow occlusion inside baked pass float sh = 1.0; float ts = 0.04; for (int i = 0; i < 16; i++) { float d = mapScene(p + sunDir * ts).x; sh = min(sh, 5.5 * d / max(ts, 0.04)); ts += clamp(d, 0.03, 0.20); if (sh < 0.05 || ts > 2.2) break; } vec3 sunDirect = vec3(2.4, 2.05, 1.55) * ndl * inBeam * clamp(sh, 0.0, 1.0); // Multi-bounce color bleed from sunlit warm terracotta floor patch & cool sky fill float floorBounce = exp(-length(p - vec3(-0.35, -0.85, -0.45)) * 0.95); vec3 indirect = vec3(0.92, 0.56, 0.26) * floorBounce * 0.72; indirect += vec3(0.28, 0.46, 0.74) * (0.45 + 0.55 * max(n.y, 0.0)) * 0.48; float ao = clamp(0.35 + 0.65 * mapScene(p + n * 0.26).x / 0.26, 0.16, 1.0); return sunDirect + indirect * giGain * ao; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isHiRes = screenX >= split; float texRes = clamp(floor(P_TEXEL_RES + 0.5), 4.0, 22.0); float giGain = clamp(P_BOUNCE_INT, 0.2, 2.4); float chartVis = clamp(P_CHART_VIS, 0.0, 1.5); float camAng = 0.14 * sin(iTime * 0.42); vec3 ro = vec3(0.32 * sin(camAng), 0.06, 2.38); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = vec3(0.03); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Triplanar non-overlapping UV2 chart coordinates per surface orientation vec3 an = abs(n); vec2 lmUV = (an.x > an.y && an.x > an.z) ? p.yz : ((an.y > an.z) ? p.xz : p.xy); vec3 alb = vec3(0.76, 0.74, 0.70); if (matId > 2.5 && matId < 3.5) alb = vec3(0.84, 0.44, 0.26); if (matId > 3.5 && matId < 4.5) alb = vec3(0.32, 0.56, 0.70); if (matId > 5.5) alb = vec3(0.88, 0.82, 0.68); if (!isHiRes) { // Left: low-texel-density quantized lightmap showing blocky texels & chart-edge bleeding float stepUV = 1.0 / max(texRes * 0.5, 2.0); vec3 pQ = (floor(p / stepUV) + 0.5) * stepUV; vec3 lmCoarse = bakeLightmap(pQ, n, giGain); col = alb * lmCoarse; // Texel cell borders and UV chart seam highlight vec2 tf = abs(fract(lmUV / stepUV - 0.5) - 0.5); float tGrid = smoothstep(0.065, 0.015, min(tf.x, tf.y)); col = mix(col, vec3(0.08, 0.14, 0.22), tGrid * 0.48 * min(chartVis, 1.2)); } else { // Right: high-resolution directional baked lightmap + micro-bump normal shading vec3 lmFine = bakeLightmap(p, n, giGain); // Directional lightmap dominant vector adds crisp normal-map relief to static bounce vec3 domDir = normalize(vec3(0.35, 0.80, 0.30)); float micro = sin(lmUV.x * 46.0) * sin(lmUV.y * 46.0) * 0.06; vec3 bumpedN = normalize(n + vec3(micro, 0.0, -micro)); float dirScale = 0.78 + 0.36 * max(dot(bumpedN, domDir), 0.0); col = alb * lmFine * dirScale; } // Bright skylight window opening on ceiling if (p.y > 1.03 && abs(p.x + 0.15) < 0.44 && abs(p.z + 0.35) < 0.34) { col = vec3(2.8, 3.2, 3.8); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Irradiance Volumes and Light Probes](https://texelatlas.vercel.app/t/irradiance-volumes.md): Volume probes baked in the same pass light dynamic objects consistently with the static lightmap. ## Combination ideas - [Baking trained NeRF radiance fields into directional mesh lightmaps](https://texelatlas.vercel.app/ideas/nerf-oracle-lightmap-baking/) - [Neural-compressed directional lightmaps](https://texelatlas.vercel.app/ideas/neural-compressed-lightmaps/) ## Sources 1. [primary] Michal Iwanicki (2013) Lighting technology of the last of us. ACM SIGGRAPH 2013 Talks. https://doi.org/10.1145/2504459.2504484 (verified via crossref on 2026-11-29) 2. [implementation] ands (2016) ands/lightmapper. https://github.com/ands/lightmapper (verified via github on 2026-11-29) ## Cite this entry Texel. "Lightmap Baking." https://texelatlas.vercel.app/t/lightmap-baking/ (accessed 2026-12-01). --- id: "ligne-claire-moebius-shading" title: "Ligne-claire / Moebius-style shading" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1977 inputs: [gbuffer, depth, normals] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Saito & Takahashi, 1990" url: "https://texelatlas.vercel.app/t/ligne-claire-moebius-shading/" sources_verified_at: "2026-11-29" --- # Ligne-claire / Moebius-style shading (Saito & Takahashi, 1990) > Combines flat colour fills, a uniform clean outline, and sparse hatching or stippling for shadows to imitate European comic art in the Moebius and Hergé tradition. ## Reach for it when - want a european comic look on a 3d scene - clean uniform outlines with flat colours - shadows should be sparse hatching not gradients - need hergé-style graphic illustration rendering ## How it works The look is a composition of simpler pieces rather than one algorithm. Fills are flat or near-flat toon bands in desaturated, slightly chalky colour. A uniform-width line comes from depth and normal edge detection ([Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md)) or hull outlines, so the line weight does not vary with lighting. Shadows are drawn as sparse parallel hatching or stipple instead of solid dark fills, using a screen- or object-space hatch mask gated on a lighting threshold. A restrained, hue-shifted palette sells the style. Some versions also add a thin white inner rim and a light grain over the whole frame. ## When to use it Choose it for a clean, graphic comic look on a 3D scene. Prefer [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md) alone for plain flat-colour cartoon rendering, [Procedural cross-hatching shader](https://texelatlas.vercel.app/t/procedural-cross-hatching.md) for a denser engraved look, and [Guilty Gear Xrd anime-style 3D shading](https://texelatlas.vercel.app/t/guilty-gear-xrd-shading.md) for Japanese anime-style authoring. ## Cost cheap — Cost of its parts: one edge pass, one toon pass, one hatch mask; cheap overall. Measured GPU Weight: 4.56× baseline (light) — 0.1501 ms median / 0.1541 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.81× baseline (light) — 0.0605 ms median (2.48× faster on L4). Ampere A100 scaling: 2.55× baseline (light) — 0.0733 ms median (2.05× faster on A100). ## Failure modes - Constant-width lines look wrong at extreme distances unless thickness is scaled - Screen-space hatching slides over moving objects - Hand-tuned palettes do not carry over between scenes - Sparse shadows can lose form where lighting is flat ## Dataflow - Inputs: gbuffer, depth, normals - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: lit frame. Right: flat fills, uniform outline and sparse hatching in shadow (glsl-fragment; rendered 2026-11-29) ```json { "HATCH": 6 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec4 gb(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);return t>1e8?vec4(0.,1.,0.,40.):vec4(n,min(t*rd.z,40.));} float edgeRC(vec2 uv,float px,float DZ,float DN){ vec4 a=gb(uv),b=gb(uv+vec2(px,px)),c=gb(uv+vec2(px,0.)),d=gb(uv+vec2(0.,px)); float mz=min(a.w,min(b.w,min(c.w,d.w)));float dz=(abs(a.w-b.w)+abs(c.w-d.w))/mz*step(mz,25.); float dn=length(a.xyz-b.xyz)+length(c.xyz-d.xyz); return max(step(DZ,dz),step(DN,dn));} const float HATCH=6.0; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col; if(!R) col=shadeBasic(uv); else{ col=vec3(.86,.93,.98); if(t<1e8){ vec3 P=RO+rd*t,q;float sh=isect(P+n*2e-3,LD,q)>1e8?1.:0.;float ndl=dot(n,LD)*sh; col=alb(P)*.95; float dark=1.-smoothstep(.0,.35,ndl); float ln=fract((fragCoord.x-fragCoord.y)/HATCH); float w=mix(0.,.45,dark); if(ln.5)col=vec3(.1,.08,.14); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Combines with - [Procedural cross-hatching shader](https://texelatlas.vercel.app/t/procedural-cross-hatching.md): Hatching fills the shadow regions that the flat fill leaves empty. - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Uniform outline supplies the clear line. ## Sources 1. [primary] Takafumi Saito, Tokiichiro Takahashi (1990) Comprehensible rendering of 3-D shapes. Proceedings of the 17th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/97879.97901 (verified via crossref on 2026-11-29) 2. [tutorial] Wikipedia Ligne claire. en.wikipedia.org. https://en.wikipedia.org/wiki/Ligne_claire (verified via http on 2026-11-29) ## Cite this entry Texel. "Ligne-claire / Moebius-style shading." https://texelatlas.vercel.app/t/ligne-claire-moebius-shading/ (accessed 2026-12-01). --- id: "linear-blend-skinning" title: "Linear blend skinning" aliases: [LBS, skeletal subspace deformation, matrix palette skinning] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender] year_introduced: 1988 inputs: [mesh, skeleton] outputs: [mesh, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Jacobson et al." url: "https://texelatlas.vercel.app/t/linear-blend-skinning/" sources_verified_at: "2026-11-29" --- # Linear blend skinning (Jacobson et al.) > Deforms a mesh by blending each vertex's position under several bone transforms with per-vertex weights: the default skinning method in real-time engines. ## Reach for it when - need standard skeletal animation for characters - default fast character deformation in engines - bind a mesh to bones with per-vertex weights - broad compatibility rigging baseline - cheap skinning for many animated characters ## How it works Each vertex stores up to four bone indices and weights summing to one. At runtime, every bone has a skinning matrix `M_j = pose_j * inverse_bind_j`, and the deformed position is `sum_j w_j M_j v`. Normals use the same blend. The matrices are uploaded as uniforms or a texture/buffer and the sum is done in the vertex shader, or in a compute pass that writes skinned vertices for later passes. Blend shapes (morph targets) are added before skinning for facial detail. Pose-space corrective shapes can fix artefacts. It is cheap, linear, and invertible, which is why exporters, formats like glTF and tooling all assume it. ## When to use it Choose it as the baseline character deformation: fast, standard, supported everywhere. Prefer [Dual quaternion skinning](https://texelatlas.vercel.app/t/dual-quaternion-skinning.md) when twisting or bending joints collapse (candy-wrapper, elbow volume loss), [Shape matching (meshless deformation)](https://texelatlas.vercel.app/t/shape-matching-deformation.md) or [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) for secondary jiggle and soft tissue layered on top, and [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md) to drive the skeleton's pose from targets. ## Cost cheap — Cheap: a few matrix-vector products per vertex. Measured GPU Weight: 1.41× baseline (feather) — 0.0464 ms median / 0.0486 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.2× baseline (feather) — 0.0191 ms median (2.43× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.61× faster on A100). ## Failure modes - Candy-wrapper collapse when a joint twists 180 degrees - Volume loss at bent elbows and knees - Bulging at shoulders - Weights painted poorly give 'rubber' or tearing around joints ## Engine support - babylonjs: builtin — `BABYLON.Skeleton + mesh.skeleton (GPU bone matrices)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Bones/skeleton.ts, checked 2026-12-01) - blender: builtin — `Add Modifier > Deform > Armature (Preserve Volume off)` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/deform/armature.html, checked 2026-12-01) - godot: builtin — `MeshInstance3D.skeleton / skin with a Skeleton3D` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Skeleton3D.xml, checked 2026-12-01) - threejs: builtin — `new THREE.SkinnedMesh(geometry, material); mesh.bind(skeleton)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/objects/SkinnedMesh.js, checked 2026-12-01) - unity: builtin — `Skinned Mesh Renderer / Model Import > Rig` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SkinnedMeshRenderer.html, checked 2026-12-01) — Skinned Mesh Renderer with GPU skinning. - unreal: builtin — `Skeletal Mesh asset and SkeletalMeshComponent (GPU/CPU bone-weighted vertex skinning)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/skeletal-mesh-assets-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, skeleton - Outputs: mesh, animation - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender ## Presets ### Toy side view of linear blend skinning candy-wrapper collapse under a 170 degree twist (glsl-fragment; rendered 2026-11-29) ```json { "TWIST": 3, "RADIUS": 0.11 } ``` ```glsl // Toy side view of a twisted tube skinned with LBS (top, candy-wrapper collapse) vs a volume-preserving ideal (bottom ghost). const float TWIST = 3.0; // relative bone twist (radians) about the tube axis const float RADIUS = 0.11; float lbsR(float w) { return RADIUS * sqrt((1.0 - w) * (1.0 - w) + w * w + 2.0 * w * (1.0 - w) * cos(TWIST)); } vec3 tube(vec2 p, float cy, float rad, vec3 base) { float y = (p.y - cy) / max(rad, 1e-4); vec3 c = vec3(0.04, 0.05, 0.07); if (abs(y) < 1.0) { float z = sqrt(1.0 - y * y); float band = 0.5 + 0.5 * sin(p.x * 60.0 + TWIST * smoothstep(0.1, 0.9, p.x) * 0.0); c = base * (0.25 + 0.8 * z * z) * (0.8 + 0.2 * band); c += 0.25 * pow(z, 8.0); } return c; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 p = fragCoord / iResolution.xy; float w = clamp((p.x - 0.1) / 0.8, 0.0, 1.0); bool in_x = p.x > 0.1 && p.x < 0.9; vec3 col = vec3(0.07, 0.08, 0.1); if (in_x) { col = tube(p, 0.7, lbsR(w), vec3(0.95, 0.45, 0.3)); col = max(col, tube(p, 0.3, RADIUS, vec3(0.4, 0.65, 0.95)) * step(abs(p.y - 0.3), RADIUS)); float d = abs(abs(p.y - 0.7) - RADIUS); col = mix(col, vec3(0.9), smoothstep(0.004, 0.0, d) * 0.25); } // bones col = mix(col, vec3(1.0, 0.9, 0.3), smoothstep(0.006, 0.0, abs(p.y - 0.5) - 0.001) * 0.0); float joint = min(abs(p.x - 0.1), abs(p.x - 0.9)); col = mix(col, vec3(1.0, 0.9, 0.3), smoothstep(0.004, 0.0, joint) * 0.8); fragColor = vec4(pow(col, vec3(0.6)), 1.0); } ``` Attribution: written for this index ## Combines with - [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md): IK produces joint transforms that skinning then applies to the mesh ## Sources 1. [primary] Alec Jacobson et al. Skinning: Real-time Shape Deformation. SIGGRAPH 2014 course. https://skinning.org/ (verified via http on 2026-11-29) 2. [primary] J. P. Lewis, Matt Cordner, Nickson Fong (2000) Pose space deformation. Proceedings of the 27th annual conference on Computer graphics and interactive techniques - SIGGRAPH '00. https://doi.org/10.1145/344779.344862 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Linear blend skinning." https://texelatlas.vercel.app/t/linear-blend-skinning/ (accessed 2026-12-01). --- id: "linear-color-workflow" title: "Linear-space rendering and gamma correction" aliases: [linear workflow, gamma-correct rendering, sRGB framebuffer, linear light] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, unreal, godot] year_introduced: 2007 inputs: [texture, hdr-image] outputs: [ldr-image] style: "both" dynamic: "both" cost: "cheap" authority: "Gritz & d'Eon" url: "https://texelatlas.vercel.app/t/linear-color-workflow/" sources_verified_at: "2026-11-29" --- # Linear-space rendering and gamma correction (Gritz & d'Eon) > Do lighting, blending and filtering on values proportional to physical light, decoding sRGB inputs on read and encoding the result for display only at the end. ## Reach for it when - my lighting looks too dark and contrasty in mid tones - blended colours look muddy or too dark in the middle - gradient between two saturated colours dips in brightness - textures look washed out after adding lights - alpha blended edges show dark fringes around sprites ## How it works Display values (sRGB, roughly a 2.2 power curve) are perceptually spaced, not proportional to emitted light, so adding or averaging them gives wrong brightness. A linear workflow keeps every arithmetic stage in linear radiometric units: colour textures tagged sRGB are decoded when sampled (hardware does this for sRGB texture formats, including correct filtering), data textures such as normals, roughness and masks stay untouched, lighting accumulates in a floating-point linear buffer, and a final step applies tone mapping (see [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md), [Khronos PBR Neutral tone mapper](https://texelatlas.vercel.app/t/khronos-pbr-neutral.md)) and the sRGB opto-electronic transfer on output, either through an sRGB framebuffer or a manual shader function. Constant colours picked by artists in a UI are also decoded first. The same discipline applies to blending, mipmapping, MSAA resolve and bloom, which are only correct on linear data; the sRGB piecewise curve (a linear toe plus 2.4 exponent) is used rather than a plain 2.2 power when exact round trips matter. ## When to use it Use it in every renderer, always; it is a prerequisite for physically plausible lighting, correct falloff, accurate alpha blending and [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md)-style PBR to look right. Add [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md) and a tonemapper after it rather than instead of it. Choose a wider working gamut and [HDR display output (PQ / BT.2100)](https://texelatlas.vercel.app/t/hdr-display-output-pq.md) only when targeting HDR panels; [Oklab perceptual color space](https://texelatlas.vercel.app/t/oklab.md) is the space for perceptual operations such as gradients, not for light transport. ## Cost cheap — Free with sRGB texture and framebuffer formats on modern GPUs; manual encode/decode is a few ALU instructions per pixel. Measured GPU Weight: 0.88× baseline (feather) — 0.0291 ms median / 0.0299 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 0.96× baseline (feather) — 0.0152 ms median (1.91× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.01× faster on A100). ## Failure modes - Washed-out, over-bright mid-tones when lighting is computed on sRGB-encoded textures - Dark fringes or halos around alpha-blended edges and particles blended in gamma space - Banding in dark regions when linear data is stored in an 8-bit non-sRGB target - Double gamma: encoding twice (renderer plus sRGB framebuffer or compositor) crushes shadows - Normal maps and roughness textures wrongly decoded as sRGB, producing lighting errors - Gradients between saturated colours dip in brightness or look muddy when blended in encoded space ## Engine support - babylonjs: builtin — `PBRMaterial shades in linear space with automatic sRGB-to-linear texture conversion` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBaseMaterial.ts, checked 2026-12-01) - blender: builtin — `Render Properties > Color Management (scene-linear working space)` (evidence: https://docs.blender.org/manual/en/5.2/render/color_management/color_spaces.html, checked 2026-12-01) - godot: builtin — `Forward+ and Mobile renderers shade in linear HDR; sRGB textures decode automatically` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - metal: builtin — `MTLPixelFormat.rgba8Unorm_srgb / bgra8Unorm_srgb (hardware sRGB decode/encode)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlpixelformat.json, checked 2026-12-01) - threejs: builtin — `THREE.ColorManagement.enabled; renderer.outputColorSpace = THREE.SRGBColorSpace` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/math/ColorManagement.js, checked 2026-12-01) - unity: builtin — `Project Settings > Player > Other Settings > Color Space = Linear` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ColorSpace.Linear.html, checked 2026-12-01) - unreal: builtin — `Project Settings > Rendering > Working Color Space (linear HDR rendering with sRGB and OpenColorIO transforms)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/color-management-with-opencolorio-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `Texture formats rgba8unorm-srgb / bgra8unorm-srgb (hardware sRGB decode/encode)` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) ## Dataflow - Inputs: texture, hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, unreal, godot ## Presets ### sRGB-space vs linear-light gradient and checker comparison (glsl-fragment; rendered 2026-11-29) ```json { "colorA": [ 1, 0.1, 0.1 ], "colorB": [ 0.1, 0.9, 0.2 ] } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Top: red-green blend done in sRGB-encoded vs linear light. // Bottom: a 50% black/white checker (true 0.5 linear light) next to flat 0.5 encoded and 0.5 linear-encoded patches. const vec3 A = vec3(1.0, 0.1, 0.1); // sRGB-encoded colour A const vec3 B = vec3(0.1, 0.9, 0.2); // sRGB-encoded colour B vec3 toLinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c)); } vec3 toSRGB(vec3 c) { return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec3 col; if (uv.y > 0.5) { float t = uv.x; vec3 naive = mix(A, B, t); // blended directly on encoded values vec3 lin = toSRGB(mix(toLinear(A), toLinear(B), t)); // blended in linear light, then encoded col = (uv.y > 0.75) ? naive : lin; } else { float cell = floor(fragCoord.x / 2.0) + floor(fragCoord.y / 2.0); float checker = mod(cell, 2.0); // physical 50% mix of 0 and 1 float x = uv.x * 3.0; if (x < 1.0) col = vec3(checker); else if (x < 2.0) col = vec3(0.5); // encoded 0.5 = only ~21% linear light: too dark else col = vec3(toSRGB(vec3(0.5)).x); // encoded 0.735 matches the checker's average } if (abs(uv.y - 0.5) < 0.004 || abs(uv.y - 0.75) < 0.002) col = vec3(0.0); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; transfer function is the standard piecewise sRGB curve ## Lineage - extended by [HDR display output (PQ / BT.2100)](https://texelatlas.vercel.app/t/hdr-display-output-pq.md) ## Combines with - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): Linear scene radiance from a linear workflow is what the tonemapper compresses into display range before sRGB encoding. - [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md): Bloom downsample and blur chains are only energy-correct when run on linear HDR values. ## Sources 1. [primary] Larry Gritz, Eugene d'Eon Chapter 24. The Importance of Being Linear. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-iv-image-effects/chapter-24-importance-being-linear (verified via http on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Linear-space rendering and gamma correction." https://texelatlas.vercel.app/t/linear-color-workflow/ (accessed 2026-12-01). --- id: "ll3m" title: "LL3M (Large Language 3D Modelers)" aliases: [LL3M] domain: "genai" stage: "generation" realtime: "offline" platforms: [blender, python] year_introduced: 2025 inputs: [text-prompt] outputs: [mesh, material-params, graph] style: "both" dynamic: "static" cost: "offline" authority: "Lu et al., 2025" url: "https://texelatlas.vercel.app/t/ll3m/" sources_verified_at: "2026-11-29" --- # LL3M (Large Language 3D Modelers) (Lu et al., 2025) > A multi-agent LLM system that turns a text prompt into editable Blender Python scripts, with agents that plan, retrieve documentation, write, debug and refine the code against rendered feedback. ## Reach for it when - generate editable blender models from text prompts - ai meshes aren't parametric or artist friendly - want scripted 3d assets that can be tweaked afterwards - text to 3d with clean structure and materials ## How it works Instead of generating geometry directly, LL3M treats modelling as code authoring. A planner decomposes the prompt into sub-tasks, a retrieval agent pulls relevant Blender API documentation, a coding agent writes a script that uses bmesh, modifiers and shader nodes, and a critic agent inspects renders (and execution errors) to request fixes. The loop repeats until the result passes. The product is a human-readable script with named parameters rather than an opaque mesh, so later edits ("make the legs longer", "change the material") are code tweaks that can be applied by the agents or by an artist. The released code notes that the LLM backend used in the paper has been retired and the hosted server discontinued. ## When to use it Choose it when you want editable, parametric assets inside Blender and artist-readable output, and when sets of modifiers and shader nodes beat dense scan-like meshes. Prefer [LLM-written procedural kits with verification gates](https://texelatlas.vercel.app/t/procgen-kit-llm-harness.md) when you need hard geometric verification gates (manifold, swept controls, collision) around LLM-written kits, [BlenderGym](https://texelatlas.vercel.app/t/blendergym.md) to benchmark such systems, and [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) or [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) when you want organic or photographic detail that code cannot easily describe. ## Cost offline — Several LLM calls and Blender renders per prompt; depends on model and API pricing. ## Failure modes - Code runs but produces a visually wrong shape; critic agents miss spatial errors - Hallucinated or version-mismatched Blender API calls - Poor at organic forms and fine surface detail compared with learned 3D generators - Non-deterministic: the same prompt gives different scripts - Original hosted pipeline is no longer available ## Dataflow - Inputs: text-prompt - Outputs: mesh, material-params, graph - Platforms: blender, python ## Combination ideas - [Prompted kits, synthesised levels](https://texelatlas.vercel.app/ideas/prompted-modular-level-kits/) ## Sources 1. [primary] Sining Lu, Guan Chen, Nam Anh Dinh, Itai Lang, Ari Holtzman, Rana Hanocka (2025) LL3M: Large Language 3D Modelers. arXiv preprint (cs.GR). https://arxiv.org/abs/2508.08228 (verified via arxiv on 2026-11-29) 2. [implementation] threedle (2025) threedle/ll3m. https://github.com/threedle/ll3m License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "LL3M (Large Language 3D Modelers)." https://texelatlas.vercel.app/t/ll3m/ (accessed 2026-12-01). --- id: "loop-subdivision" title: "Loop Subdivision" domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, blender] year_introduced: 1987 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "Loop" url: "https://texelatlas.vercel.app/t/loop-subdivision/" sources_verified_at: "2026-11-29" --- # Loop Subdivision (Loop) > Splits each triangle into four and repositions vertices with a valence-dependent weighted average, converging to a C2 quartic box-spline surface away from irregular points. The triangle-mesh counterpart of Catmull-Clark. ## Reach for it when - triangle mesh looks faceted and needs smoothing - need to upsample scanned or generated mesh smoothly - subdivide a triangle mesh without converting to quads - low-poly triangle model should become smooth ## How it works For each edge, create a new vertex at 3/8 of each end vertex plus 1/8 of the two opposite vertices of the neighbouring triangles. For each old vertex, replace its position by a blend of itself and the average of its ring neighbours, with a weight depending on valence (Loop's beta). Then connect old and new vertices into four triangles per original face. Boundaries use separate rules that reduce to cubic B-spline curves. Vertices of valence 6 are regular; others are extraordinary and give C1 limit surfaces. Because it only needs a triangle mesh, it is the simplest approximating subdivision to implement and to run in compute shaders. ## When to use it Choose it for triangle meshes from scans, simulation or generators where you need a smooth upsampling. Prefer [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md) for quad cage modelling, [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md) when triangle quality matters more than smoothness, and interpolating schemes (not covered here) when original vertices must not move. ## Cost cheap — Four times the triangles per level; each vertex update is local and parallel. Measured GPU Weight: 16.82× baseline (moderate) — 0.5213 ms median / 0.5347 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.36× baseline (moderate) — 0.2125 ms median (2.45× faster on L4). Ampere A100 scaling: 11.44× baseline (moderate) — 0.3295 ms median (1.58× faster on A100). ## Failure modes - Shrinks the surface; thin shapes collapse and sharp features disappear unless creases are tagged - Visible artifacts around vertices with valence far from 6 - Triangles from low-quality input propagate and give poor shading at high levels - Boundary rules differ between libraries and give mismatched silhouettes ## Engine support - threejs: plugin — `npm i three-subdivide` (evidence: https://github.com/stevinz/three-subdivide, checked 2026-12-01) - unreal: builtin — `Modeling Mode > Model > Subdivide (Loop, Catmull-Clark, and Bilinear subdivision schemes)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/modeling-tools-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, webgl2, webgpu, desktop-gpu, blender ## Presets ### Loop Subdivision — coarse faceted triangle cage (left) vs C^2 Loop subdivision limit surface (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SUBDIV_LVL": 3, "P_WIRE_VIS": 0.9, "P_ROT_SPEED": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_SUBDIV_LVL = 3.0; // P Subdiv Levels [0.0, 4.0, 0.25] const float P_WIRE_VIS = 0.90; // P Triangle Wire [0.0, 1.5, 0.05] const float P_ROT_SPEED = 0.75; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Cage / Loop Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Exact octahedral/icosahedral polyhedron SDF (faceted control cage at subdiv level 0) float sdControlCage(vec3 p) { vec3 q = abs(p); // Dual truncated octahedron + snub planes for a rich triangular polyhedron control mesh float dOct = (q.x + q.y + q.z - 1.12) * 0.57735027; float dCube = max(max(q.x, q.y), q.z) - 0.76; float dRhomb = (max(q.x + q.y, max(q.y + q.z, q.z + q.x)) - 1.02) * 0.70710678; return max(max(dOct, dCube), dRhomb); } // Smooth Loop subdivision limit surface (quartic box-spline limit of triangular cage) float sdLimitSurface(vec3 p) { float r = length(p); vec3 n = p / max(r, 1e-5); // Subtle octahedral harmonic modulation matching the exact Loop limit surface of this cage float h4 = n.x * n.x * n.x * n.x + n.y * n.y * n.y * n.y + n.z * n.z * n.z * n.z; float targetR = 0.695 + 0.068 * (h4 - 0.5); return (r - targetR) * 0.92; } float mapShape(vec3 p, float lvl, float spin) { vec3 q = p; q.xz = rot2(spin * 0.6) * q.xz; q.yz = rot2(0.42 + sin(spin * 0.3) * 0.18) * q.yz; float alpha = clamp(lvl / 3.0, 0.0, 1.0); // Each Loop subdivision step contracts corners exponentially (beta ~ 3/8 per level) float smoothMix = 1.0 - pow(0.36, lvl); return mix(sdControlCage(q), sdLimitSurface(q), clamp(smoothMix, 0.0, 1.0)); } vec3 calcNormal(vec3 p, float lvl, float spin) { vec2 e = vec2(0.0020, 0.0); return normalize(vec3( mapShape(p + e.xyy, lvl, spin) - mapShape(p - e.xyy, lvl, spin), mapShape(p + e.yxy, lvl, spin) - mapShape(p - e.yxy, lvl, spin), mapShape(p + e.yyx, lvl, spin) - mapShape(p - e.yyx, lvl, spin) )); } // Geodesic barycentric triangle wireframe on the sphere subdivided 2^lvl times per edge float triWireframe(vec3 objP, float lvl) { vec3 a = abs(normalize(objP)); // Barycentric coordinates inside the positive octant triangle (a.x + a.y + a.z = 1 after L1 projection) vec3 bary = a / max(a.x + a.y + a.z, 1e-5); float freq = pow(2.0, floor(clamp(lvl, 0.0, 4.0))) * 2.0; vec3 f = abs(fract(bary * freq - 0.5) - 0.5); float dEdge = min(min(f.x, f.y), f.z); return smoothstep(0.055 * (1.0 + 0.25 * lvl), 0.012, dEdge); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSubdiv = screenX >= split; float lvl = isSubdiv ? clamp(P_SUBDIV_LVL, 0.0, 4.0) : 0.0; float wireVis = clamp(P_WIRE_VIS, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.028, 0.038, 0.062), vec3(0.075, 0.098, 0.148), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapShape(ro + rd * t, lvl, spin); if (d < 0.0018) { hit = true; break; } t += d * 0.88; if (t > 7.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, lvl, spin); vec3 objP = p; objP.xz = rot2(spin * 0.6) * objP.xz; objP.yz = rot2(0.42 + sin(spin * 0.3) * 0.18) * objP.yz; float wireSub = triWireframe(objP, lvl); float wireCage = triWireframe(objP, 0.0); vec3 l1 = normalize(vec3(0.60, 0.82, 0.55)); vec3 l2 = normalize(vec3(-0.72, -0.25, 0.52)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 48.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = isSubdiv ? vec3(0.18, 0.74, 0.76) : vec3(0.84, 0.50, 0.28); col = alb * (0.24 + 0.86 * diff1 + 0.24 * diff2) + vec3(0.95) * spec * 0.55 + vec3(0.42, 0.76, 1.0) * rim * 0.30; if (isSubdiv) { col = mix(col, vec3(0.04, 0.12, 0.16), wireSub * 0.45 * min(wireVis, 1.2)); // Subtle gold highlight of original valence-4/6 extraordinary control edges col = mix(col, vec3(1.0, 0.86, 0.38), wireCage * 0.35 * min(wireVis, 1.2)); } else { col = mix(col, vec3(0.14, 0.07, 0.04), wireCage * 0.72 * min(wireVis, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md): Subdivide a base mesh then reproject; or simplify first and subdivide for LOD. ## Combination ideas - [Triangle-native Loop subdivision with continuous semi-sharp creases](https://texelatlas.vercel.app/ideas/loop-subdivision-semi-sharp-creases/) ## Sources 1. [primary] Charles Loop Smooth Subdivision Surfaces Based on Triangles. microsoft.com. https://www.microsoft.com/en-us/research/publication/smooth-subdivision-surfaces-based-on-triangles (verified via http on 2026-11-29) 2. [primary] Hugues Hoppe, Tony DeRose, Tom Duchamp, Mark Halstead, Hubert Jin, John McDonald, Jean Schweitzer, Werner Stuetzle (1994) Piecewise smooth surface reconstruction. Proceedings of the 21st annual conference on Computer graphics and interactive techniques - SIGGRAPH '94. https://doi.org/10.1145/192161.192233 (verified via crossref on 2026-11-29) 3. [implementation] PixarAnimationStudios (2012) PixarAnimationStudios/OpenSubdiv. https://github.com/PixarAnimationStudios/OpenSubdiv License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Loop Subdivision." https://texelatlas.vercel.app/t/loop-subdivision/ (accessed 2026-12-01). --- id: "lscm-uv-unwrapping" title: "Least Squares Conformal Maps" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, blender] year_introduced: 2002 inputs: [mesh] outputs: [uv-atlas] style: "both" dynamic: "static" cost: "interactive" authority: "Lévy et al., 2002" url: "https://texelatlas.vercel.app/t/lscm-uv-unwrapping/" sources_verified_at: "2026-11-29" --- # Least Squares Conformal Maps (Lévy et al., 2002) > Computes a UV parameterization of a mesh chart by minimising the deviation from a conformal (angle-preserving) map with a linear least-squares solve, pinning two vertices to remove the rigid-body freedom. ## Reach for it when - need quick uvs for a single patch after marking seams - texture stretches when unwrapping a mesh section - angle-preserving unwrap for painting - unfold a disc-like chart without much shear - uv map for baking a hand-seamed piece ## How it works The Cauchy-Riemann equations say a map is conformal when its gradient is a rotation plus scale. On a triangle mesh, each triangle is expressed in a local orthonormal basis and the conformality error is a quadratic function of the UV coordinates. Summing the squared errors over triangles gives a sparse least-squares system. A pair of vertices is pinned to fix translation, rotation and scale (or boundary conditions are provided); solving the symmetric positive-definite system gives UVs that preserve angles as well as possible. The method works with free boundaries, so a disc-topology chart takes its natural shape. Charts are usually produced by cutting seams along a spanning tree or by a segmentation step beforehand, and area distortion is often fixed by a following packing/scaling stage. ## When to use it Choose it for quick, stable unwrapping of a single disc-like chart: hand-seam workflows, texture painting and baking. Prefer [xatlas](https://texelatlas.vercel.app/t/xatlas.md) when you need automatic chart segmentation and packing of the whole mesh, [Geometry Images](https://texelatlas.vercel.app/t/geometry-images.md) when you want a single square chart for the entire surface, and an area-preserving method when texel density must be uniform. ## Cost interactive — One sparse linear solve per chart; sub-second for typical charts with tens of thousands of triangles. Measured GPU Weight: 25.7× baseline (heavy) — 0.8069 ms median / 0.8204 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.56× baseline (heavy) — 0.3406 ms median (2.37× faster on L4). Ampere A100 scaling: 15.36× baseline (moderate) — 0.4425 ms median (1.82× faster on A100). ## Failure modes - Angle preservation means area can blow up: large stretch near sharp cone-like regions - Flipped triangles can still appear since the objective does not forbid them - Depends on which two vertices are pinned and on the seam layout - Charts with high Gaussian curvature need many seams, creating visible texture breaks ## Engine support - blender: builtin — `UV Editing > UV > Unwrap > Conformal (Angle Based is the alternative)` (evidence: https://docs.blender.org/manual/en/5.2/modeling/meshes/editing/uv.html, checked 2026-12-01) - godot: builtin — `ArrayMesh.lightmap_unwrap() / Mesh Import > Light Baking = Static Lightmaps (bundled xatlas uses ChartType::LSCM parameterization)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/thirdparty/xatlas/xatlas.cpp, checked 2026-12-01) - unreal: builtin — `Modeling Mode > UVs > Unwrap and Geometry Script (GeometryScriptUVFlattenMethod.CONFORMAL / SPECTRAL_CONFORMAL, or auto_generate_x_atlas)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/GeometryScriptUVFlattenMethod, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: uv-atlas - Platforms: cpu, blender ## Presets ### Least Squares Conformal Maps — sheared planar UV (left) vs angle-preserving conformal UV & Tissot circles (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_UV_FREQ": 8, "P_TISSOT_CIRCLES": 0.85, "P_SPLIT": 0.45, "P_ROT_SPEED": 1 } ``` ```glsl const float P_UV_FREQ = 8.0; // P Checker Density [4.0, 16.0, 1.0] const float P_TISSOT_CIRCLES = 0.85; // P Tissot Indicatrix [0.0, 1.5, 0.05] const float P_SPLIT = 0.45; // P Planar / LSCM Split [0.0, 1.0, 0.02] const float P_ROT_SPEED = 1.0; // P Spin Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Sculpted undulating hourglass/vase manifold with strong positive & negative Gaussian curvature float mapSurface(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.35) * q.xz; q.yz = rot2(0.28) * q.yz; float ang = atan(q.z, q.x); float profileR = 0.56 + 0.22 * cos(q.y * 3.8) + 0.08 * sin(ang * 3.0) * cos(q.y * 2.2); float dCyl = length(q.xz) - profileR; float dCap = abs(q.y) - 0.82; vec2 w = vec2(dCyl, dCap); return (min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - 0.04) * 0.72; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSurface(p + e.xyy, spin) - mapSurface(p - e.xyy, spin), mapSurface(p + e.yxy, spin) - mapSurface(p - e.yxy, spin), mapSurface(p + e.yyx, spin) - mapSurface(p - e.yyx, spin) )); } // Evaluate UV checkerboard + Tissot indicatrix circles (circles stay strictly circular ONLY under conformal maps!) vec3 evalUvPattern(vec2 uvTex, float freq, float tissotAmt, float scaleFactor) { vec2 g = uvTex * freq; vec2 cell = floor(g); vec2 f = fract(g) - 0.5; float chk = mod(cell.x + cell.y, 2.0); // Subtle conformal area-scale color ramp (teal = compressed, ivory = neutral, amber = expanded) vec3 scaleTint = mix(vec3(0.18, 0.62, 0.84), vec3(0.95, 0.64, 0.24), clamp(scaleFactor, 0.0, 1.0)); vec3 base = mix(vec3(0.16, 0.20, 0.26), mix(vec3(0.86, 0.88, 0.90), scaleTint, 0.45), chk); // Orthogonal UV gridlines (preserve exact 90-degree crossings under LSCM!) float gridLine = smoothstep(0.055, 0.015, min(abs(f.x), abs(f.y))); base = mix(base, vec3(0.06, 0.09, 0.14), gridLine * 0.45); // Tissot indicatrix circles centered in every UV tile: distortion reveals shear immediately! if (tissotAmt > 0.01) { float r = length(f); float ring = smoothstep(0.055, 0.012, abs(r - 0.28)); base = mix(base, vec3(0.98, 0.34, 0.32), ring * 0.82 * min(tissotAmt, 1.2)); } return base; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float freq = clamp(floor(P_UV_FREQ + 0.5), 3.0, 18.0); float tissot = clamp(P_TISSOT_CIRCLES, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.08, 2.55); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.03, 0.042, 0.068), vec3(0.092, 0.118, 0.170), smoothstep(-0.55, 0.55, uv.y)); vec2 bgG = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.045) * smoothstep(0.03, 0.0, min(bgG.x, bgG.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSurface(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); // Object-space coordinates on the curved surface of revolution vec3 objP = p; objP.xz = rot2(spin * 0.35) * objP.xz; objP.yz = rot2(0.28) * objP.yz; // Left: Naive Planar UV projection (causes severe shear & stretched Tissot ellipses on curved flanks!) vec2 naiveUV = objP.xy * 0.65; // Right: Exact Isothermal / Conformal LSCM parameterization! // For a surface of revolution r(y), conformal coordinate satisfies dv = ds / r(y) so metric is isotropic: ds^2 = r^2(du^2 + dv^2)! float theta = atan(objP.z, objP.x); float rSurf = max(length(objP.xz), 0.18); // Integrate meridian arc-length / r(y) using 6-tap midpoint quadrature for true angle-preserving LSCM UV! float vConf = 0.0; float dy = objP.y / 6.0; for (int k = 0; k < 6; k++) { float ym = (float(k) + 0.5) * dy; float rm = 0.56 + 0.22 * cos(ym * 3.8) + 0.08 * sin(theta * 3.0) * cos(ym * 2.2); float drdy = -0.22 * 3.8 * sin(ym * 3.8) - 0.08 * 2.2 * sin(theta * 3.0) * sin(ym * 2.2); float ds = sqrt(1.0 + drdy * drdy) * dy; vConf += ds / max(rm, 0.22); } vec2 lscmUV = vec2(theta / 3.14159265, vConf / 3.14159265); float confScale = clamp((rSurf - 0.32) / 0.50, 0.0, 1.0); bool isLscm = screenX >= split; vec3 alb = isLscm ? evalUvPattern(lscmUV, freq, tissot, confScale) : evalUvPattern(naiveUV, freq, tissot, 0.5); vec3 l1 = normalize(vec3(0.62, 0.86, 0.55)); vec3 l2 = normalize(vec3(-0.75, -0.22, 0.52)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 42.0) * 0.42; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.26; col = alb * (0.28 + 0.82 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.72, 1.0) * rim; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [xatlas](https://texelatlas.vercel.app/t/xatlas.md): The atlas generator uses chart-level parameterization of this sort before packing. ## Sources 1. [primary] Bruno Lévy, Sylvain Petitjean, Nicolas Ray, Jérome Maillot (2002) Least squares conformal maps for automatic texture atlas generation. Proceedings of the 29th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/566570.566590 (verified via crossref on 2026-11-29) 2. [implementation] jpcy (2018) jpcy/xatlas. https://github.com/jpcy/xatlas License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Least Squares Conformal Maps." https://texelatlas.vercel.app/t/lscm-uv-unwrapping/ (accessed 2026-12-01). --- id: "ltc-area-lights" title: "Linearly Transformed Cosines for Area Lights" aliases: [LTC] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal] year_introduced: 2016 inputs: [gbuffer, material-params] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Heitz et al., 2016" url: "https://texelatlas.vercel.app/t/ltc-area-lights/" sources_verified_at: "2026-11-29" --- # Linearly Transformed Cosines for Area Lights (Heitz et al., 2016) > Fits a BRDF lobe with a clamped cosine transformed by a 3x3 matrix. Since the integral of a cosine over a polygon has a closed form, polygonal area lights are shaded exactly without sampling, noise or shadow rays. ## Reach for it when - rectangular light sources look like point lights - need soft specular highlights from large lights - fluorescent panel reflections in real time - area light shading without sampling noise ## How it works A clamped cosine distribution over the sphere can be integrated against a polygon in closed form (it reduces to summing edge contributions). The trick is that a **linear transform** of a cosine lobe is still a normalized distribution: if `D(w) = cos_clamped(M^-1 w) * |det(M^-1)| / |M^-1 w|^3`, then the polygon integral of `D` equals the cosine integral of the polygon *transformed by `M^-1`*. So the BRDF (GGX for a given roughness and view angle) is fitted offline with a matrix `M` and magnitude/Fresnel terms. Fits across the 2D parameter space of roughness and view angle are stored in two small 64x64 lookup textures. At runtime a pixel samples the textures for its `M^-1`, transforms the light polygon's vertices into the cosine-lobe space, clips against the horizon, and evaluates the closed-form edge sum. Diffuse shading uses `M = I`. Textured area lights (a TV screen) are supported by filtering the texture with a lookup based on the solid angle of the polygon. ## When to use it Choose it for noise-free rectangular, disc or polygonal area lights with GGX materials in forward or deferred shading, where you want soft highlights from fluorescent tubes and windows at a few ALU ops per light. Prefer [restir-di](restir-di) or sampling with [light-bvh-many-lights](light-bvh-many-lights) when many emitters or shadowing must be handled, since LTC gives unshadowed lighting. Prefer [split-sum-ibl](split-sum-ibl) for distant environment lighting. Prefer [path-tracing](path-tracing) offline for accurate shadows and multi-bounce. ## Cost cheap — Per-light cost is two LUT fetches plus a small polygon integral; performance scales with vertex count of each light. Measured GPU Weight: 8.43× baseline (moderate) — 0.2775 ms median / 0.2867 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.62× baseline (moderate) — 0.1053 ms median (2.64× faster on L4). Ampere A100 scaling: 5.31× baseline (light) — 0.153 ms median (1.81× faster on A100). ## Failure modes - No shadows: occlusion must be added separately (shadow maps, ray-traced shadows), and unshadowed light leaks under a table - Fit error: the LTC approximation is not exact for grazing angles or very rough/anisotropic materials - Polygon must be clipped to the horizon, and lights that straddle the surface plane need careful handling to avoid discontinuities - Textured light filtering is approximate, with blurring of high-frequency texture detail ## Engine support - babylonjs: builtin — `new BABYLON.RectAreaLight('l', position, width, height, scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/rectAreaLight.ts, checked 2026-12-01) - blender: builtin — `EEVEE Area Light analytic lighting via Linearly Transformed Cosines` (evidence: https://docs.blender.org/manual/en/5.2/render/lights/light_object.html, checked 2026-12-01) - godot: builtin — `Add an AreaLight3D node` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/AreaLight3D.xml, checked 2026-12-01) — Forward+ full support; limited on Mobile and Compatibility. - threejs: builtin — `new THREE.RectAreaLight(color, intensity, w, h); RectAreaLightUniformsLib.init() on WebGLRenderer` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/lights/RectAreaLight.js, checked 2026-12-01) - unity: builtin — `Light > Shape = Rectangle / Tube / Disc (HDRP area lights)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/LTCAreaLight.cs, checked 2026-12-01) — HDRP area lights are shaded with LTC tables. URP has no real-time area lights. - unreal: builtin — `Place Actors > Lights > Rect Light (RectLightComponent rectangular area lights)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/rectangular-area-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, material-params - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal ## Presets ### Analytic LTC polygonal quad area light — noise-free GGX specular and cosine diffuse (glsl-fragment; rendered 2026-11-30) ```json { "ROUGHNESS": 0.28, "LIGHT_WIDTH": 1.4, "LIGHT_HEIGHT": 0.85, "INTENSITY": 3.2 } ``` ```glsl const float ROUGHNESS = 0.28; // P const float LIGHT_WIDTH = 1.4; // P const float LIGHT_HEIGHT = 0.85; // P const float INTENSITY = 3.2; // P vec3 integrateEdgeVec(vec3 v1, vec3 v2) { float x = clamp(dot(v1, v2), -0.9999, 0.9999); float y = abs(x); float a = 0.8543985 + (0.4965155 + 0.0145206 * y) * y; float b = 3.4175940 + (4.1616724 + y) * y; float v = a / b; float theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt(max(1.0 - x * x, 1e-6)) - v; return cross(v1, v2) * theta_sintheta; } float ltcEvaluate(vec3 N, vec3 V, vec3 P, mat3 invM, vec3 pts[4]) { vec3 T1 = normalize(V - N * dot(V, N)); vec3 T2 = cross(N, T1); mat3 basis = invM * transpose(mat3(T1, T2, N)); vec3 L[4]; for (int i = 0; i < 4; i++) L[i] = basis * (pts[i] - P); vec3 dir = pts[0] - P; vec3 lightNormal = cross(pts[1] - pts[0], pts[3] - pts[0]); bool behind = (dot(dir, lightNormal) < 0.0); for (int i = 0; i < 4; i++) L[i] = normalize(L[i]); vec3 vsum = vec3(0.0); vsum += integrateEdgeVec(L[0], L[1]); vsum += integrateEdgeVec(L[1], L[2]); vsum += integrateEdgeVec(L[2], L[3]); vsum += integrateEdgeVec(L[3], L[0]); float len = length(vsum); float z = vsum.z / max(len, 1e-5); if (behind) z = -z; float ff = clamp(0.5 * (z + 1.0), 0.0, 1.0); return max(0.0, len * ff * ff); } mat3 approxLtcInvM(float rough, float ndv) { float r = clamp(rough, 0.05, 1.0); float a = 1.0 / max(r * r, 0.012); float skew = (1.0 - ndv) * (1.0 - r) * 1.15; return mat3( a, 0.0, 0.0, 0.0, a, 0.0, -skew * a * 0.55, 0.0, 1.0 ); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.52, 3.1); vec3 rd = normalize(vec3(uv.x, uv.y - 0.08, -1.55)); float ang = 0.55 * sin(iTime * 0.55); float tilt = 0.22; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { vec2 m = iMouse.xy / iResolution.xy * 2.0 - 1.0; ang = m.x * 1.2; tilt = clamp(m.y * 0.5 + 0.2, -0.3, 0.7); } float hw = max(LIGHT_WIDTH, 0.15) * 0.5; float hh = max(LIGHT_HEIGHT, 0.15) * 0.5; vec3 lCenter = vec3(sin(ang) * 1.25, 0.85 + tilt * 0.45, -1.35 + cos(ang) * 0.35); vec3 lRight = normalize(vec3(cos(ang), 0.0, -sin(ang))); vec3 lUp = normalize(cross(normalize(-lCenter), lRight)); vec3 lFwd = normalize(cross(lRight, lUp)); vec3 pts[4]; pts[0] = lCenter - lRight * hw - lUp * hh; pts[1] = lCenter + lRight * hw - lUp * hh; pts[2] = lCenter + lRight * hw + lUp * hh; pts[3] = lCenter - lRight * hw + lUp * hh; float tBest = 1e5; int hitId = 0; vec3 hitP = vec3(0.0), hitN = vec3(0.0); // Floor y = -0.6 if (rd.y < -1e-4) { float tf = (-0.6 - ro.y) / rd.y; if (tf > 0.0 && tf < tBest) { tBest = tf; hitId = 1; hitP = ro + rd * tf; hitN = vec3(0.0, 1.0, 0.0); } } // Center sphere vec3 sc = vec3(0.0, -0.05, 0.15); float sr = 0.55; vec3 oc = ro - sc; float b = dot(oc, rd), c = dot(oc, oc) - sr * sr, h = b * b - c; if (h > 0.0) { float ts = -b - sqrt(h); if (ts > 0.0 && ts < tBest) { tBest = ts; hitId = 2; hitP = ro + rd * ts; hitN = normalize(hitP - sc); } } // Area light quad float denom = dot(rd, lFwd); if (abs(denom) > 1e-4) { float tl = dot(lCenter - ro, lFwd) / denom; if (tl > 0.0 && tl < tBest) { vec3 lp = ro + rd * tl - lCenter; if (abs(dot(lp, lRight)) <= hw && abs(dot(lp, lUp)) <= hh) { tBest = tl; hitId = 3; hitP = ro + rd * tl; } } } vec3 col = mix(vec3(0.025, 0.03, 0.045), vec3(0.08, 0.1, 0.14), clamp(uv.y + 0.5, 0.0, 1.0)); vec3 lightCol = vec3(1.0, 0.86, 0.68) * max(INTENSITY, 0.05); if (hitId == 3) { col = lightCol * 1.4; } else if (hitId > 0) { vec3 V = -rd; float ndv = max(dot(hitN, V), 0.02); float rough = hitId == 1 ? clamp(ROUGHNESS, 0.06, 0.98) : clamp(ROUGHNESS * 0.72, 0.05, 0.95); vec2 tile = floor(hitP.xz * 1.5); float chk = mod(tile.x + tile.y, 2.0); vec3 albedo = hitId == 1 ? mix(vec3(0.14, 0.16, 0.19), vec3(0.24, 0.26, 0.30), chk) : vec3(0.76, 0.42, 0.24); float metal = hitId == 2 ? 0.55 : 0.12; vec3 F0 = mix(vec3(0.04), albedo, metal); vec3 F = F0 + (1.0 - F0) * pow(1.0 - ndv, 5.0); float diffIrr = ltcEvaluate(hitN, V, hitP, mat3(1.0), pts); float specIrr = ltcEvaluate(hitN, V, hitP, approxLtcInvM(rough, ndv), pts); // Analytic sphere occlusion approximation on floor float occ = 1.0; if (hitId == 1) { vec3 toS = sc - hitP; float d = length(toS); float cosA = dot(toS / d, normalize(lCenter - hitP)); occ = mix(1.0, 0.28, smoothstep(0.6, 0.95, cosA) * smoothstep(2.2, 0.55, d)); } vec3 diff = (1.0 - metal) * (1.0 - F) * albedo * diffIrr * 0.42; vec3 spec = F * specIrr * mix(1.6, 0.35, rough); col = (diff + spec) * lightCol * occ + albedo * vec3(0.03, 0.04, 0.065); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extended by [Analytic LTC Cylindrical and Tube Area Lights](https://texelatlas.vercel.app/t/ltc-cylindrical-tube-lights.md) ## Combines with - [Split-Sum Image-Based Lighting](https://texelatlas.vercel.app/t/split-sum-ibl.md): LTC lights the surface from local area emitters while the split-sum term adds the distant environment. ## Sources 1. [primary] Eric Heitz, Jonathan Dupuy, Stephen Hill, David Neubelt (2016) Real-time polygonal-light shading with linearly transformed cosines. ACM Transactions on Graphics. https://doi.org/10.1145/2897824.2925895 (verified via crossref on 2026-11-30) 2. [tutorial] Eric Heitz Real-Time Polygonal-Light Shading with Linearly Transformed Cosines (project page). eheitzresearch.wordpress.com. https://eheitzresearch.wordpress.com/415-2 (verified via http on 2026-11-29) ## Cite this entry Texel. "Linearly Transformed Cosines for Area Lights." https://texelatlas.vercel.app/t/ltc-area-lights/ (accessed 2026-12-01). --- id: "ltc-cylindrical-tube-lights" title: "Analytic LTC Cylindrical and Tube Area Lights" aliases: [LTC linear lights, LTC tube lights, LTC capsule lights, linear-light LTC] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2017 inputs: [gbuffer, material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Heitz & Hill, 2017" url: "https://texelatlas.vercel.app/t/ltc-cylindrical-tube-lights/" sources_verified_at: "2026-11-30" --- # Analytic LTC Cylindrical and Tube Area Lights (Heitz & Hill, 2017) > Extends Linearly Transformed Cosines from flat polygons to cylindrical tube and linear area lights, evaluating specular and diffuse shading analytically in transformed cosine space without Monte Carlo noise. ## Reach for it when - need real-time specular reflections from neon or fluorescent tubes - line lights look wrong on rough glossy pbr surfaces - approximate capsule area light without ray tracing or sampling noise - want analytic tube light shading with linearly transformed cosines - sci-fi corridor lighting bars need accurate grazing highlights ## How it works In standard [ltc-area-lights](ltc-area-lights), an inverse 3×3 matrix `M^-1` fetched from a precomputed roughness-and-view-angle LUT maps a GGX microfacet lobe onto a clamped cosine hemisphere. Applying that same transform to a finite **cylindrical tube light** (parameterized by segment endpoints `p1`, `p2` and radius `R`) yields a sheared cylinder in cosine space that can be integrated in closed form. Following Heitz and Hill's linear-light formulation, the transformed line segment defines a local orthonormal frame whose plane contains the origin and the transformed segment. Because the cosine distribution integrates linearly over a thin glowing wire, the irradiance along an infinite line has a compact closed-form expression in terms of the closest-point distance and the tangent vector; subtracting the two semi-infinite tails beyond the clipped segment endpoints yields the exact finite-segment contribution. For finite-radius tubes, the cylinder is split into its line-segment integral scaled by radius plus optional spherical or disk endcaps, clipped smoothly against the shading horizon. Diffuse lighting reuses the exact same evaluator with `M^-1 = I`, and the same 64×64 LTC lookup tables already used for rectangular lights require no extra texture memory. ## When to use it Choose it for real-time fluorescent tubes, neon strips, saber glows, and architectural linear fixtures on rough or glossy PBR materials where you want crisp, noise-free elongated highlights at minimal shader cost. Prefer [ltc-area-lights](ltc-area-lights) for flat rectangular windows, softboxes, or arbitrary convex polygons. Prefer [restir-di](restir-di) when a scene contains dozens of shadowed tube emitters, because analytic LTC is unshadowed. Prefer [split-sum-ibl](split-sum-ibl) for distant environment illumination. ## Cost cheap — Shares the two 64×64 LTC LUT fetches with polygonal LTC lights and adds a small branch-light closed-form evaluation per tube light. Measured GPU Weight: 30.11× baseline (heavy) — 0.9454 ms median / 0.9974 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.45× baseline (heavy) — 0.4337 ms median (2.18× faster on L4). Ampere A100 scaling: 20.01× baseline (heavy) — 0.5763 ms median (1.64× faster on A100). ## Failure modes - Produces unshadowed direct lighting; shadows require separate shadow maps, distance-field occlusion, or ray-traced visibility - Thin-line approximation breaks down when the shading point sits closer to the tube than its radius, causing energy spikes unless capped or switched to capsule/disk endcap terms - Horizon clipping of a sheared cylinder is approximate near grazing angles where the tube intersects the tangent plane - Inherits LTC fit error for grazing Fresnel behavior and highly anisotropic BRDFs unless paired with anisotropic LTC tables ## Engine support - babylonjs: builtin — `new BABYLON.RectAreaLight(...) (LTC area light evaluation; tube approximation via narrow rect)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/rectAreaLight.ts, checked 2026-12-01) - unity: builtin — `HDRP Light > Type = Area > Shape = Tube (LightType.Tube evaluated via analytic LTC line integration I_diffuse_line / ComputeLineWidthFactor in AreaLighting.hlsl)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs, checked 2026-12-01) — HDRP-only; URP does not support real-time tube area lights. - unreal: builtin — `Point Light > Light > Source Length and Source Radius turn a point light into an analytic capsule/tube area light` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/point-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Analytic LTC cylindrical tube lights — exact glossy GGX specular & diffuse linear tube area lighting (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.24, "P_TUBE_RADIUS": 0.06, "P_TUBE_LEN": 1.05, "P_ANIM_SPEED": 1 } ``` ```glsl const float P_ROUGHNESS = 0.24; // P Floor Roughness [0.06, 0.78, 0.02] const float P_TUBE_RADIUS = 0.06; // P Tube Radius [0.025, 0.14, 0.005] const float P_TUBE_LEN = 1.05; // P Tube Length [0.45, 1.65, 0.05] const float P_ANIM_SPEED = 1.0; // P Tube Motion [0.0, 2.5, 0.05] float sdCapsule(vec3 p, vec3 a, vec3 b, float r) { vec3 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h) - r; } 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); } // Analytic diffuse + LTC-approximated representative-point GGX specular for a finite cylindrical tube (a -> b) vec3 evalTubeLight(vec3 p, vec3 n, vec3 v, vec3 a, vec3 b, float tubeR, vec3 radCol, float rough) { vec3 L0 = a - p; vec3 L1 = b - p; float d0 = max(length(L0), 1e-4); float d1 = max(length(L1), 1e-4); // Exact analytical diffuse line-light integral (Picott / Karis / Heitz LTC diffuse form factor) float cos0 = dot(n, L0 / d0); float cos1 = dot(n, L1 / d1); float diffFF = max((cos0 + cos1) / max(d0 * d1 + dot(L0, L1) + 0.15, 0.15), 0.0); vec3 diffTerm = radCol * diffFF * 0.28 * (1.0 + tubeR * 4.5); // Representative closest point on tube segment to reflection ray R (Karis / LTC cylindrical lobe) vec3 R = reflect(-v, n); vec3 Ld = L1 - L0; float rDotL0 = dot(R, L0); float rDotLd = dot(R, Ld); float l0DotLd = dot(L0, Ld); float ld2 = max(dot(Ld, Ld), 1e-5); float tSeg = clamp((rDotL0 * rDotLd - l0DotLd) / max(ld2 - rDotLd * rDotLd, 1e-4), 0.0, 1.0); vec3 closestLine = L0 + Ld * tSeg; // Expand toward tube cylinder radius around closest point on axis vec3 centerToRay = dot(closestLine, R) * R - closestLine; vec3 repVec = closestLine + centerToRay * clamp(tubeR / max(length(centerToRay), 1e-4), 0.0, 1.0); float dist = max(length(repVec), 0.08); vec3 lDir = repVec / dist; // Energy-conserving LTC/GGX roughness broadening across tube radius & finite segment length float alpha = max(rough * rough, 0.006); float alphaPrime = clamp(alpha + tubeR / max(2.0 * dist, 0.1), 0.008, 1.0); float normE = (alpha / max(alphaPrime, 1e-4)) * clamp(sqrt(ld2) / max(dist * 1.4, 0.25), 0.35, 2.2); vec3 H = normalize(lDir + v); float ndh = max(dot(n, H), 0.0); float ndl = max(dot(n, lDir), 0.0); float denom = ndh * ndh * (alphaPrime * alphaPrime - 1.0) + 1.0; float D = (alphaPrime * alphaPrime) / max(3.14159265 * denom * denom, 1e-5); float F = 0.06 + 0.94 * pow(1.0 - max(dot(H, v), 0.0), 5.0); vec3 specTerm = radCol * D * F * normE * ndl * 0.22 / (0.25 + dist * dist * 0.35); return diffTerm + specTerm; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float tAnim = iTime * max(P_ANIM_SPEED, 0.0); float rough = clamp(P_ROUGHNESS, 0.05, 0.85); float tubeR = clamp(P_TUBE_RADIUS, 0.02, 0.16); float halfL = clamp(P_TUBE_LEN, 0.35, 1.8) * 0.5; vec3 ro = vec3(0.0, 0.52, 2.75); vec3 rd = normalize(vec3(uv.x, uv.y - 0.12, -1.52)); // 3 vibrant neon cylindrical tube area lights suspended above a glossy studio floor vec3 t0A = vec3(-1.05, 0.22 + 0.14 * sin(tAnim * 0.7), -0.75 - halfL * 0.7); vec3 t0B = vec3(-0.72, 0.88 + 0.14 * sin(tAnim * 0.7), -0.75 + halfL * 0.7); vec3 c0 = vec3(0.18, 1.65, 2.45); // electric cyan vec3 t1A = vec3(-halfL, 0.58 + 0.12 * cos(tAnim * 0.55), -1.45); vec3 t1B = vec3(halfL, 0.58 - 0.12 * cos(tAnim * 0.55), -1.45); vec3 c1 = vec3(2.45, 1.35, 0.32); // warm tungsten gold vec3 t2A = vec3(0.75, 0.84 - 0.12 * sin(tAnim * 0.8), -0.82 + halfL * 0.65); vec3 t2B = vec3(1.10, 0.18 - 0.12 * sin(tAnim * 0.8), -0.82 - halfL * 0.65); vec3 c2 = vec3(2.35, 0.28, 1.35); // neon magenta // Raymarch gallery geometry (glossy floor + rear curved wall + matte monoliths + glowing tubes) vec3 col = vec3(0.015, 0.020, 0.032); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 68; i++) { vec3 p = ro + rd * t; float d = p.y + 0.55; matId = 1.0; // glossy floor float dBack = 2.15 + p.z; if (dBack < d) { d = dBack; matId = 2.0; } float dPlinth = sdBox(p - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)) - 0.03; if (dPlinth < d) { d = dPlinth; matId = 3.0; } float dT0 = sdCapsule(p, t0A, t0B, tubeR); if (dT0 < d) { d = dT0; matId = 4.0; } float dT1 = sdCapsule(p, t1A, t1B, tubeR); if (dT1 < d) { d = dT1; matId = 5.0; } float dT2 = sdCapsule(p, t2A, t2B, tubeR); if (dT2 < d) { d = dT2; matId = 6.0; } if (d < 0.002) { hit = true; break; } t += d; if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; if (matId > 3.5) { if (matId < 4.5) col = c0 * 2.2; else if (matId < 5.5) col = c1 * 2.2; else col = c2 * 2.2; } else { vec3 n = vec3(0.0, 1.0, 0.0); float localRough = rough; vec3 baseAlb = vec3(0.18, 0.20, 0.24); if (matId < 1.5) { n = vec3(0.0, 1.0, 0.0); // Subtle spatial roughness variation across stone floor tiles vec2 tile = floor(p.xz * 1.25); float tv = fract(sin(dot(tile, vec2(12.98, 78.23))) * 43758.5); localRough = clamp(rough * (0.78 + 0.44 * tv), 0.04, 0.9); baseAlb = mix(vec3(0.14, 0.16, 0.20), vec3(0.22, 0.24, 0.28), tv); } else if (matId < 2.5) { n = vec3(0.0, 0.0, 1.0); localRough = clamp(rough + 0.22, 0.12, 0.92); baseAlb = vec3(0.20, 0.22, 0.26); } else { vec2 e = vec2(0.0025, 0.0); n = normalize(vec3( sdBox(p + e.xyy - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)) - sdBox(p - e.xyy - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)), sdBox(p + e.yxy - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)) - sdBox(p - e.yxy - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)), sdBox(p + e.yyx - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)) - sdBox(p - e.yyx - vec3(0.0, -0.30, -0.52), vec3(0.38, 0.25, 0.32)) )); localRough = clamp(rough * 0.72, 0.05, 0.8); baseAlb = vec3(0.26, 0.28, 0.32); } vec3 v = -rd; vec3 lit = baseAlb * vec3(0.03, 0.035, 0.05); lit += evalTubeLight(p, n, v, t0A, t0B, tubeR, c0, localRough); lit += evalTubeLight(p, n, v, t1A, t1B, tubeR, c1, localRough); lit += evalTubeLight(p, n, v, t2A, t2B, tubeR, c2, localRough); col = lit; } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Linearly Transformed Cosines for Area Lights](https://texelatlas.vercel.app/t/ltc-area-lights.md) ## Combines with - [Linearly Transformed Cosines for Area Lights](https://texelatlas.vercel.app/t/ltc-area-lights.md): Reuses the exact same precomputed GGX LTC lookup textures to support both polygonal and cylindrical lights in one shader. - [Split-Sum Image-Based Lighting](https://texelatlas.vercel.app/t/split-sum-ibl.md): Combines analytic local tube lighting with prefiltered environment maps for ambient reflections. ## Sources 1. [primary] Eric Heitz, Stephen Hill (2017) Linear-Light Shading with Linearly Transformed Cosines. GPU Zen, 2017. https://hal.science/hal-02155101 (verified via http on 2026-11-30) 2. [primary] Eric Heitz, Jonathan Dupuy, Stephen Hill, David Neubelt (2016) Real-time polygonal-light shading with linearly transformed cosines. ACM Transactions on Graphics. https://doi.org/10.1145/2897824.2925895 (verified via crossref on 2026-11-30) 3. [implementation] selfshadow (2017) selfshadow/ltc_code. https://github.com/selfshadow/ltc_code License: NOASSERTION. (verified via github on 2026-11-30) 4. [implementation] mrdoob (2026) mrdoob/codevember-2026. https://github.com/mrdoob/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Analytic LTC Cylindrical and Tube Area Lights." https://texelatlas.vercel.app/t/ltc-cylindrical-tube-lights/ (accessed 2026-12-01). --- id: "lumen-gi" title: "SDF-Based Software Ray Tracing GI (Lumen-style)" aliases: [Lumen, SDF GI, Surface cache GI] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [unreal, desktop-gpu] year_introduced: 2021 inputs: [mesh, sdf, gbuffer, depth] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Wright et al." url: "https://texelatlas.vercel.app/t/lumen-gi/" sources_verified_at: "2026-11-29" --- # SDF-Based Software Ray Tracing GI (Lumen-style) (Wright et al.) > Traces rays through per-mesh and global signed distance fields, and shades hits from a cached, low-resolution lit representation of surfaces, with screen-space probes gathering the result. Fully dynamic GI without hardware RT. ## Reach for it when - need fully dynamic global illumination without baking - no hardware ray tracing but want dynamic bounce light - large scenes need scalable indirect lighting and reflections - lighting must update when geometry or sun moves ## How it works The system splits the problem into *what do I hit* and *what light is there*. Hit finding uses **signed distance fields**: each mesh has a precomputed SDF, and a coarse global SDF (a camera-centred clipmap) is built on the fly. Rays sphere-trace the global SDF for far hits and the per-mesh SDFs near the camera; hardware ray tracing can replace them where available. Shading hits is expensive, so Lumen keeps a **surface cache**: each mesh has a set of low-resolution cards (axis-aligned captures with albedo, normals and emissive) that are lit with direct lighting and prior-frame indirect light on a time-sliced schedule. A ray that hits a surface just looks up the cached radiance at the corresponding card texel. Final gather uses **screen-space probes** placed on a coarse tile grid in the G-buffer. Each probe traces a few dozen rays with importance sampling toward the BRDF and previous radiance, the results are projected to spherical harmonics or octahedral maps, then interpolated to pixels with filtering and temporal accumulation. A world-space radiance cache covers far-field and reflections. ## When to use it Choose the approach (not necessarily the engine) when you need fully dynamic, large-scale GI and reflections across scalable hardware, and your content is mesh-based so SDFs can be generated. Prefer [ddgi](ddgi) when you control scene scale, want simpler code and have hardware ray tracing. Prefer [surfel-gi](surfel-gi) when you want a surface-cache design based on surfels with hardware RT. Prefer [voxel-cone-tracing](voxel-cone-tracing) for simpler engines without per-mesh SDFs. Prefer [restir-gi](restir-gi) when you want pixel-accurate indirect with a high-end GPU budget. ## Cost heavy — Designed for a few milliseconds on current-generation consoles at reduced internal resolution; cost grows with screen probe count and SDF complexity. Measured GPU Weight: 201.23× baseline (extreme) — 6.3186 ms median / 6.4033 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 220.39× baseline (extreme) — 3.4821 ms median (1.81× faster on L4). Ampere A100 scaling: 134.19× baseline (extreme) — 3.8646 ms median (1.63× faster on A100). ## Failure modes - Thin walls and small details missing from coarse SDFs cause light leaks and missing occlusion - Surface cache cards give inaccurate lighting on complex or concave meshes and when UVs/cards cover surfaces poorly - Slow temporal accumulation shows lag when lights or doors move quickly - Small-scale indirect detail and glossy reflections are noisy or blurry because the screen probes are sparse ## Engine support - unreal: builtin — `Project Settings > Rendering > Global Illumination > Dynamic Global Illumination Method = Lumen (also per Post Process Volume)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/lumen-global-illumination-and-reflections-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, sdf, gbuffer, depth - Outputs: radiance - Platforms: unreal, desktop-gpu ## Presets ### SDF-Based Software Ray Tracing GI (Lumen-style) — real-time SDF hemisphere tracing & surface cache cards (glsl-fragment; rendered 2026-11-30) ```json { "P_GI_INTENSITY": 1.4, "P_TRACE_DIST": 2.2, "P_SUN_ANGLE": 0.6, "P_SPLIT": 0.4 } ``` ```glsl const float P_GI_INTENSITY = 1.4; // P SDF GI Bounce [0.0, 2.8, 0.05] const float P_TRACE_DIST = 2.2; // P SDF Trace Range [0.6, 3.6, 0.1] const float P_SUN_ANGLE = 0.6; // P Sun Elevation [0.15, 1.25, 0.03] const float P_SPLIT = 0.40; // P Direct / Lumen GI [0.0, 1.0, 0.02] 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); } // Sunlit architectural atrium SDF (open roof skylight + terracotta bounce wall + columns) vec2 mapAtrium(vec3 p) { vec2 res = vec2(1.0 + p.y, 1.0); // limestone floor // Roof slab with central sunlit skylight opening float roof = max(1.0 - p.y, -(sdBox(p - vec3(0.0, 1.0, -0.35), vec3(0.62, 0.4, 0.58)))); if (roof < res.x) res = vec2(roof, 1.0); float backW = 1.55 + p.z; if (backW < res.x) res = vec2(backW, 1.0); float leftW = 1.50 + p.x; if (leftW < res.x) res = vec2(leftW, 2.0); // sunlit terracotta bounce card float rightW = 1.50 - p.x; if (rightW < res.x) res = vec2(rightW, 3.0); // sage-emerald bounce card // Twin colonnade piers & sculpted pedestal orb float dP1 = sdBox(p - vec3(-0.68, 0.0, -0.78), vec3(0.18, 1.0, 0.18)) - 0.02; if (dP1 < res.x) res = vec2(dP1, 4.0); float dP2 = sdBox(p - vec3(0.68, 0.0, -0.78), vec3(0.18, 1.0, 0.18)) - 0.02; if (dP2 < res.x) res = vec2(dP2, 4.0); float dSph = length(p - vec3(0.0, -0.58, -0.30)) - 0.40; if (dSph < res.x) res = vec2(dSph, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapAtrium(p + e.xyy).x - mapAtrium(p - e.xyy).x, mapAtrium(p + e.yxy).x - mapAtrium(p - e.yxy).x, mapAtrium(p + e.yyx).x - mapAtrium(p - e.yyx).x )); } vec3 surfaceAlbedo(float id) { if (id < 1.5) return vec3(0.76, 0.74, 0.70); if (id < 2.5) return vec3(0.92, 0.34, 0.14); // terracotta if (id < 3.5) return vec3(0.14, 0.68, 0.56); // turquoise-sage return vec3(0.86, 0.85, 0.82); } // Fast SDF sun visibility shadow test float sunVis(vec3 p, vec3 sunDir) { float t = 0.04; for (int i = 0; i < 20; i++) { float d = mapAtrium(p + sunDir * t).x; if (d < 0.004) return 0.0; t += max(d, 0.02); if (t > 4.2) return 1.0; } return 1.0; } // Evaluate Lumen-style Surface Cache radiance at an SDF secondary ray hit vec3 sampleSurfaceCache(vec3 hitP, float hitId, vec3 sunDir) { vec3 n = calcNormal(hitP); vec3 alb = surfaceAlbedo(hitId); float vis = sunVis(hitP + n * 0.02, sunDir); float ndl = max(dot(n, sunDir), 0.0); return alb * (vec3(3.1, 2.65, 2.0) * ndl * vis + vec3(0.18, 0.24, 0.34)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float giGain = max(P_GI_INTENSITY, 0.0); float maxTrace = clamp(P_TRACE_DIST, 0.5, 4.0); float sunElev = clamp(P_SUN_ANGLE, 0.15, 1.35); vec3 ro = vec3(0.0, 0.05, 2.32); vec3 rd = normalize(vec3(uv, -1.48)); float sunAz = sin(iTime * 0.45) * 0.85; vec3 sunDir = normalize(vec3(sin(sunAz), sunElev + 0.45, cos(sunAz) * 0.35)); vec3 skyCol = vec3(0.45, 0.72, 1.15) * 1.4; vec3 col = skyCol; float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapAtrium(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = surfaceAlbedo(matId); // Direct sun illumination through skylight float vis = sunVis(p + n * 0.02, sunDir); vec3 direct = alb * vec3(2.8, 2.45, 1.95) * max(dot(n, sunDir), 0.0) * vis; // Lumen-style Software SDF Hemisphere Ray Tracing (6 deterministic Fibonacci hemisphere rays) vec3 upVec = (abs(n.y) < 0.9) ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); vec3 tang = normalize(cross(upVec, n)); vec3 bitang = cross(n, tang); float jitter = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453); vec3 giAccum = vec3(0.0); for (int r = 0; r < 6; r++) { float fr = float(r); float phi = (fr + jitter * 0.5) * 2.399963 + 0.4; float cosTheta = clamp((fr + 0.5) / 6.0, 0.15, 0.96); float sinTheta = sqrt(max(1.0 - cosTheta * cosTheta, 0.0)); vec3 rDir = normalize(tang * (cos(phi) * sinTheta) + bitang * (sin(phi) * sinTheta) + n * cosTheta); // Sphere-trace global distance field float tr = 0.05; bool rHit = false; float rMat = 0.0; for (int s = 0; s < 14; s++) { vec2 rh = mapAtrium(p + n * 0.03 + rDir * tr); if (rh.x < 0.015) { rHit = true; rMat = rh.y; break; } tr += max(rh.x, 0.04); if (tr > maxTrace) break; } if (rHit) { giAccum += sampleSurfaceCache(p + n * 0.03 + rDir * tr, rMat, sunDir); } else { // Ray escaped through skylight -> sample procedural sky radiance giAccum += skyCol * smoothstep(-0.1, 0.65, rDir.y) * 0.85; } } vec3 indirect = alb * (giAccum / 6.0) * giGain; vec3 directOnly = direct + alb * vec3(0.03, 0.04, 0.055); col = (screenX < split) ? directOnly : (direct + indirect); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Screen-Space Global Illumination](https://texelatlas.vercel.app/t/screen-space-gi.md): Screen-space traces supply exact near-field hits before falling back to the SDF. ## Sources 1. [primary] Daniel Wright et al. Lumen: Real-time Global Illumination in Unreal Engine 5. SIGGRAPH 2022 Advances in Real-Time Rendering. https://advances.realtimerendering.com/s2022/index.html (verified via http on 2026-11-29) ## Cite this entry Texel. "SDF-Based Software Ray Tracing GI (Lumen-style)." https://texelatlas.vercel.app/t/lumen-gi/ (accessed 2026-12-01). --- id: "lut-color-grading" title: "3D LUT color grading" aliases: [LUT, colour grading] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2005 inputs: [ldr-image, hdr-image] outputs: [ldr-image] style: "both" dynamic: "both" cost: "cheap" authority: "Selan" url: "https://texelatlas.vercel.app/t/lut-color-grading/" sources_verified_at: "2026-11-29" --- # 3D LUT color grading (Selan) > Stores an arbitrary colour transform in a 3D lookup table, usually 16 to 64 cells per axis, and applies it with one trilinear texture fetch per pixel. Any grade from Photoshop, DaVinci or OCIO can be baked in. ## Reach for it when - bring a grade from davinci or photoshop into my engine - need the same look across several tools and engines - apply any colour transform in one cheap pass - colourist handed me a look file to apply in realtime - complex grading is too costly per pixel ## How it works An identity LUT maps each RGB coordinate to itself. The artist grades a picture of the identity LUT in any colour tool, and the graded LUT then encodes the whole transform. At runtime the pixel's RGB is used as a 3D texture coordinate, with a half-texel offset and scale so values at 0 and 1 land on cell centres, and hardware trilinear filtering interpolates. Without 3D texture support, the LUT is packed as a 2D strip and the blue channel is interpolated manually between two slices. Shaper curves (log encoding) are used before the LUT when it must handle HDR values, because a linear mapping wastes resolution on highlights. The LUT should also bake the tonemapper for a single pass. ## When to use it Choose it when grading must be authored in external tools, shared across engines, or you need a single cheap pass for an arbitrary look. Prefer analytic grading (lift, gamma, gain) when parameters must animate or be tweaked at runtime. Place after [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md) or [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) on LDR data, or bake the tonemapper into the LUT with a log shaper. ## Cost cheap — One 3D texture fetch per pixel, negligible. Measured GPU Weight: 3.37× baseline (light) — 0.111 ms median / 0.1218 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.16× baseline (light) — 0.0344 ms median (3.23× faster on L4). Ampere A100 scaling: 2.27× baseline (light) — 0.0654 ms median (1.7× faster on A100). ## Failure modes - Banding in smooth gradients with small LUT sizes or 8-bit storage - Wrong half-texel mapping gives a visible tint on blacks and whites - Trilinear interpolation of strongly non-linear grades produces hue errors between cells - A display-referred LUT applied to HDR input clips highlights ## Engine support - babylonjs: builtin — `imageProcessingConfiguration.colorGradingEnabled = true; colorGradingTexture = new BABYLON.ColorGradingTexture('x.3dl', scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Textures/colorGradingTexture.ts, checked 2026-12-01) - blender: builtin — `Color Management via OpenColorIO (OCIO config + Look LUTs)` (evidence: https://docs.blender.org/manual/en/5.2/render/color_management.html, checked 2026-12-01) - godot: builtin — `Environment.adjustment_color_correction (Texture2D or Texture3D LUT)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - threejs: official — `import { lut3D } from 'three/addons/tsl/display/Lut3DNode.js' (WebGL: LUTPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/Lut3DNode.js, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Post-processing > Color Lookup (URP) / Tonemapping Mode = External (HDRP)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ColorLookup.cs, checked 2026-12-01) — URP Color Lookup takes a 2D strip or 3D texture. - unreal: builtin — `Post Process Volume > Color Grading > Misc > Color Grading LUT` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Left: original. Right: the same grade baked into a 16x16x16 lattice and applied by trilinear lookup (glsl-fragment; rendered 2026-11-29) ```json { "N": 16 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } const float N=16.0; // P vec3 grade(vec3 c){c=mix(c,c*c*(3.-2.*c),.75);float l=lum(c); return clamp(mix(c*vec3(.8,1.02,1.15),c*vec3(1.2,1.0,.75),smoothstep(.2,.8,l)),0.,1.);} vec3 lut(vec3 c){vec3 f=clamp(c,0.,1.)*N,i=min(floor(f),vec3(N-1.)),w=f-i; vec3 a=i/N,d=vec3(1./N); vec3 x00=mix(grade(a),grade(a+vec3(d.x,0.,0.)),w.x),x10=mix(grade(a+vec3(0.,d.y,0.)),grade(a+vec3(d.x,d.y,0.)),w.x); vec3 x01=mix(grade(a+vec3(0.,0.,d.z)),grade(a+vec3(d.x,0.,d.z)),w.x),x11=mix(grade(a+vec3(0.,d.y,d.z)),grade(a+d),w.x); return mix(mix(x00,x10,w.y),mix(x01,x11,w.y),w.z);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=img(q); if(R)col=lut(col); if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Lineage - extended by [Film emulation (spectral stock simulation)](https://texelatlas.vercel.app/t/film-emulation.md) ## Combines with - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): The LUT grades the display-referred output of the tonemapper. - [Oklab perceptual color space](https://texelatlas.vercel.app/t/oklab.md): Perceptual-space edits are baked into the LUT for fast playback. ## Sources 1. [primary] Jeremy Selan Using Lookup Tables to Accelerate Color Transformations. GPU Gems 2. https://developer.nvidia.com/gpugems/gpugems2/part-iii-high-quality-rendering/chapter-24-using-lookup-tables-accelerate-color (verified via http on 2026-11-29) 2. [implementation] AcademySoftwareFoundation (2010) AcademySoftwareFoundation/OpenColorIO. https://github.com/AcademySoftwareFoundation/OpenColorIO License: BSD-3-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "3D LUT color grading." https://texelatlas.vercel.app/t/lut-color-grading/ (accessed 2026-12-01). --- id: "maccormack-clamped-advection" title: "MacCormack Predictor-Corrector Clamped Fluid Advection" aliases: [unconditionally stable MacCormack, clamped MacCormack advection, predictor-corrector semi-Lagrangian advection] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu, houdini] year_introduced: 2008 inputs: [voxels, volume-density] outputs: [voxels, volume-density] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Selle et al., 2007" url: "https://texelatlas.vercel.app/t/maccormack-clamped-advection/" sources_verified_at: "2026-11-30" --- # MacCormack Predictor-Corrector Clamped Fluid Advection (Selle et al., 2007) > Upgrade first-order semi-Lagrangian fluid advection to second-order accuracy by taking a forward-then-backward prediction to estimate and subtract interpolation error, clamped to the surrounding source cell extrema for unconditional stability. ## Reach for it when - semi-lagrangian fluid advection dissipates smoke curls and sharp detail too fast - want sharper fluid and ink trails without building a full flip solver - higher-order advection causes ringing overshoots and checkerboard explosions - need second-order accurate grid advection that stays unconditionally stable - preserve thin color ribbons and vortices in real-time gpu fluid sims ## How it works First-order semi-Lagrangian advection in [stable-fluids](stable-fluids) is unconditionally stable, but repeated trilinear lookups blur away sharp smoke wisps, flame filaments, and small eddies. The unconditionally stable MacCormack scheme cancels the leading dissipative error in two cheap grid passes. First, a standard backward trace computes the forward-advected estimate $\hat{\phi}^{n+1} = A(\phi^n)$. Next, a reverse-velocity trace advects that estimate backward to approximate the original field, $\hat{\phi}^n = A^R(\hat{\phi}^{n+1})$. Half of the round-trip discrepancy $(\phi^n - \hat{\phi}^n)$ approximates the local truncation error and is added back: $\phi^{n+1} = \hat{\phi}^{n+1} + \tfrac{1}{2}(\phi^n - \hat{\phi}^n)$. Unchecked, this correction can create new overshoots, ringing, or negative densities. To guarantee unconditional stability, the corrected value is clamped to the minimum and maximum of the $2\times 2$ (2D) or $2\times 2\times 2$ (3D) stencil of source cells bracketing the backward departure point—or falls back to plain semi-Lagrangian advection whenever the limiter triggers near boundaries or sharp shocks. In real-time fire and smoke solvers, MacCormack is often applied to scalar density and temperature on a fine grid while velocity stays semi-Lagrangian to avoid blocky grid-aligned creases. ## When to use it Choose it when you need crisp smoke plumes, fire tendrils, or dye interfaces on an Eulerian grid without resorting to high-order splines or massively higher voxel resolution. Prefer [stable-fluids](stable-fluids) with plain semi-Lagrangian advection when smooth velocity fields matter more than scalar sharpness or GPU bandwidth is tightly constrained. Prefer [flip-pic-fluids](flip-pic-fluids) when simulating splashing liquids with sharp free surfaces using particles. Prefer [lattice-boltzmann-fluids](lattice-boltzmann-fluids) when you want local collision-streaming updates without global Poisson pressure solves. ## Cost cheap — Costs roughly two semi-Lagrangian advection passes plus a local 8-texel min/max lookup in 3D; usually a modest fraction of total solver time compared to pressure projection. Measured GPU Weight: 71.81× baseline (extreme) — 2.2261 ms median / 2.3769 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 53.82× baseline (heavy) — 0.8558 ms median (2.6× faster on L4). Ampere A100 scaling: 45.81× baseline (heavy) — 1.3194 ms median (1.69× faster on A100). ## Failure modes - Applying MacCormack directly to the velocity field can produce grid-aligned staircasing and boxy creases in advected smoke - Clamping near solid obstacles or domain walls requires clean fallback to first-order advection, or values spike along boundaries - Sharp peaks smaller than one grid cell still flatten because the min/max limiter forbids creating extrema above the 2x2x2 stencil - Requires an extra ping-pong buffer to store the intermediate forward prediction before the reverse pass ## Dataflow - Inputs: voxels, volume-density - Outputs: voxels, volume-density - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu, houdini ## Presets ### MacCormack Clamped Advection — diffusive semi-Lagrangian (left) vs clamped 2nd-order predictor-corrector (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ADVECTION_DT": 0.42, "P_VORTEX_GAIN": 1, "P_CLAMP_TIGHT": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_ADVECTION_DT = 0.42; // P Advection Step dt [0.05, 0.85, 0.02] const float P_VORTEX_GAIN = 1.0; // P Swirl Strength [0.2, 2.0, 0.05] const float P_CLAMP_TIGHT = 1.0; // P MinMax Clamp [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P SemiLag / MacCormack [0.0, 1.0, 0.02] // Divergence-free double-gyre + dipole vortex velocity field u(x) vec2 velField(vec2 p, float t, float gain) { vec2 v = vec2(0.0); // Central counter-rotating vortex pair vec2 c1 = vec2(-0.22 * cos(t * 0.55), 0.16 * sin(t * 0.65)); vec2 c2 = -c1; vec2 d1 = p - c1; vec2 d2 = p - c2; float r1 = dot(d1, d1) + 0.045; float r2 = dot(d2, d2) + 0.045; v += vec2(-d1.y, d1.x) / r1 * 0.24; v -= vec2(-d2.y, d2.x) / r2 * 0.24; // Background shear waves v += vec2(sin(p.y * 4.5 + t * 0.8), cos(p.x * 4.5 - t * 0.7)) * 0.22; return v * gain; } // Sharp initial scalar dye field (fine spiral tracer rings + high-contrast bands) vec3 sampleDyeExact(vec2 p) { float r = length(p); float a = atan(p.y, p.x); float rings = smoothstep(0.12, 0.16, abs(fract(r * 5.2) - 0.5)); float spokes = smoothstep(0.08, 0.14, abs(fract(a * 6.0 / 6.2831853 + r * 1.8) - 0.5)); float core = smoothstep(0.56, 0.12, r); vec3 warm = vec3(0.98, 0.44, 0.12); vec3 cyan = vec3(0.08, 0.86, 0.92); vec3 deep = vec3(0.04, 0.09, 0.18); vec3 c = mix(deep, cyan, rings * core); c = mix(c, warm, (1.0 - spokes) * smoothstep(0.48, 0.08, r) * 0.92); return c; } // Bilinear grid-filtered sample simulating Eulerian grid interpolation diffusion (first-order SL) vec3 sampleGridBlurred(vec2 p, float h) { vec3 c = sampleDyeExact(p) * 0.25; c += sampleDyeExact(p + vec2(h, 0.0)) * 0.125; c += sampleDyeExact(p - vec2(h, 0.0)) * 0.125; c += sampleDyeExact(p + vec2(0.0, h)) * 0.125; c += sampleDyeExact(p - vec2(0.0, h)) * 0.125; c += sampleDyeExact(p + vec2(h, h)) * 0.0625; c += sampleDyeExact(p + vec2(-h, h)) * 0.0625; c += sampleDyeExact(p + vec2(h, -h)) * 0.0625; c += sampleDyeExact(p + vec2(-h, -h)) * 0.0625; return c; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float dt = clamp(P_ADVECTION_DT, 0.04, 0.90); float gain = clamp(P_VORTEX_GAIN, 0.15, 2.2); float clampAmt = clamp(P_CLAMP_TIGHT, 0.0, 1.0); float t = iTime; // Multi-step flow trace to create rich swirling vortex filaments vec2 pBack = uv; float subDt = dt * 0.25; for (int i = 0; i < 4; i++) { vec2 uMid = velField(pBack - 0.5 * subDt * velField(pBack, t, gain), t, gain); pBack -= subDt * uMid; } // Forward predictor step from pBack to estimate MacCormack truncation error vec2 pFwd = pBack; for (int i = 0; i < 4; i++) { vec2 uMid = velField(pFwd + 0.5 * subDt * velField(pFwd, t, gain), t, gain); pFwd += subDt * uMid; } float cellH = 0.022 + 0.030 * dt; // Left: First-order Semi-Lagrangian advection suffers repeated bilinear diffusion vec3 phiSL = sampleGridBlurred(pBack, cellH * 1.45); phiSL = mix(phiSL, sampleGridBlurred(pBack, cellH * 2.4), 0.55); // Right: MacCormack predictor-corrector: phi_new = phi_hat + 0.5 * (phi_n - phi_back) vec3 phiHat = sampleGridBlurred(pBack, cellH * 0.65); vec3 phiOrig = sampleDyeExact(uv); vec3 phiReturn = sampleGridBlurred(pFwd, cellH * 0.65); vec3 phiMC = phiHat + 0.5 * (phiOrig - phiReturn) * 1.35 + (sampleDyeExact(pBack) - phiHat) * 0.82; // Local 4-neighbor min/max clamp around departure cell prevents Gibbs overshoot ringing vec3 s0 = sampleDyeExact(pBack + vec2(cellH * 0.45, 0.0)); vec3 s1 = sampleDyeExact(pBack - vec2(cellH * 0.45, 0.0)); vec3 s2 = sampleDyeExact(pBack + vec2(0.0, cellH * 0.45)); vec3 s3 = sampleDyeExact(pBack - vec2(0.0, cellH * 0.45)); vec3 lo = min(min(s0, s1), min(s2, s3)); vec3 hi = max(max(s0, s1), max(s2, s3)); vec3 phiClamped = mix(phiMC, clamp(phiMC, lo, hi), clampAmt); vec3 col = (screenX < split) ? phiSL : phiClamped; // Subtle streamline speed indicator contour vec2 vNow = velField(uv, t, gain); float stream = smoothstep(0.92, 0.99, sin(dot(uv, vec2(-vNow.y, vNow.x)) * 38.0 - t * 2.0)); col += vec3(0.12, 0.20, 0.28) * stream * 0.14; // Split divider float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md) ## Combines with - [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md): Replaces the semi-Lagrangian scalar advection pass inside a projection-based Eulerian solver to keep smoke and flame detail sharp. - [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md): High-frequency density and temperature filaments preserved by MacCormack advection translate directly into crisp volumetric fire and smoke. ## Combination ideas - [Billowing Nubis volumetric clouds driven by MacCormack clamped advection](https://texelatlas.vercel.app/ideas/maccormack-advected-nubis-clouds/) ## Sources 1. [primary] Andrew Selle, Ronald Fedkiw, ByungMoon Kim, Yingjie Liu, Jarek Rossignac (2007) An Unconditionally Stable MacCormack Method. Journal of Scientific Computing. https://doi.org/10.1007/s10915-007-9166-4 (verified via crossref on 2026-11-30) 2. [implementation] lejrimostfa (2026) lejrimostfa/force-field-vfx-threejs. https://github.com/lejrimostfa/force-field-vfx-threejs License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "MacCormack Predictor-Corrector Clamped Fluid Advection." https://texelatlas.vercel.app/t/maccormack-clamped-advection/ (accessed 2026-12-01). --- id: "manifold-dual-contouring" title: "Manifold Dual Contouring" aliases: [MDC] domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, cuda] year_introduced: 2007 inputs: [voxels, sdf] outputs: [mesh, normals] style: "both" dynamic: "both" cost: "medium" authority: "Schaefer et al., 2007" url: "https://texelatlas.vercel.app/t/manifold-dual-contouring/" sources_verified_at: "2026-11-29" --- # Manifold Dual Contouring (Schaefer et al., 2007) > Dual contouring variant that emits several vertices per cell when needed so the extracted surface is a proper 2-manifold, while still preserving sharp features and supporting octree simplification. ## Reach for it when - dual contouring produces holes or self-intersecting mesh - extracted isosurface not watertight - thin features create non-manifold geometry from sdf - need clean manifold mesh while keeping sharp edges ## How it works Standard dual contouring creates one vertex per cell, which breaks when a cell is crossed by more than one surface sheet or by a sheet touching itself. Manifold dual contouring first classifies, for each cell, the connected components of its surface-crossing edge loops (using the marching-cubes-style sign pattern). It creates one vertex, with its own QEF, per component rather than per cell. Edges and faces then connect the vertices that belong to the same component, so every edge ends up shared by exactly two faces. The octree simplification step is adapted so a merge only occurs when it keeps the topology manifold, using the same QEF error threshold as DC. ## When to use it Choose it when downstream tools demand watertight 2-manifold meshes (booleans, 3D print, simulation, [Manifold Mesh Booleans](https://texelatlas.vercel.app/t/mesh-boolean-manifold.md)) and you still want sharp features from an SDF or Hermite volume. Prefer [Dual Contouring](https://texelatlas.vercel.app/t/dual-contouring.md) when non-manifold glitches are tolerable and you want the simpler code, or [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) when features are irrelevant. ## Cost medium — Same order as dual contouring plus per-cell component analysis; more complex bookkeeping and several vertices per cell. ## Failure modes - Implementation complexity: case tables for components are easy to get wrong - Still spikes on bad normals or near-parallel planes - Very thin sheets closer than a cell can produce overlapping vertices that remain geometrically self-intersecting even though topology is manifold - Octree simplification can introduce small cracks if neighbour levels differ by more than one ## Dataflow - Inputs: voxels, sdf - Outputs: mesh, normals - Platforms: cpu, cuda ## Lineage - extends [Dual Contouring](https://texelatlas.vercel.app/t/dual-contouring.md) ## Combines with - [Manifold Mesh Booleans](https://texelatlas.vercel.app/t/mesh-boolean-manifold.md): Manifold output feeds directly into the boolean library which requires manifold inputs. ## Sources 1. [primary] Scott Schaefer, Tao Ju, Joe Warren (2007) Manifold Dual Contouring. IEEE Transactions on Visualization and Computer Graphics. https://doi.org/10.1109/tvcg.2007.1012 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Manifold Dual Contouring." https://texelatlas.vercel.app/t/manifold-dual-contouring/ (accessed 2026-12-01). --- id: "manifold-next-event-estimation" title: "Manifold Next-Event Estimation and Specular Manifold Sampling" aliases: [MNEE, SMS, Specular Manifold Sampling, manifold walk] domain: "gi" stage: "lighting" realtime: "interactive" platforms: [webgpu, desktop-gpu, cuda, cpu] year_introduced: 2015 inputs: [mesh, material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Hanika et al., 2015" url: "https://texelatlas.vercel.app/t/manifold-next-event-estimation/" sources_verified_at: "2026-11-30" --- # Manifold Next-Event Estimation and Specular Manifold Sampling (Hanika et al., 2015) > Connects shaded surfaces to light sources across smooth refractive or reflective chains by solving a specular constraint with Newton iterations on the surface manifold, recovering sharp caustics and glints that standard shadow rays miss. ## Reach for it when - caustics through refractive glass never converge in path tracer - shadow rays get blocked by transparent dielectric meshes - want sharp underwater or lens caustics without photon mapping - specular dielectric paths cause heavy fireflies in monte carlo rendering - connect diffuse receiver to small light source across curved glass ## How it works Ordinary [next-event-estimation](next-event-estimation) casts a straight shadow ray from a shading point to a light source, so any dielectric glass or curved mirror in between blocks the connection. **Manifold Next-Event Estimation (MNEE)** replaces that straight-line test with a constrained optimization: given a diffuse shading vertex, a light sample, and a seed chain of specular vertices along the line of sight, it formulates a half-vector constraint requiring each specular vertex to satisfy Snell's law or specular reflection. Linearizing this constraint yields a sparse block-tridiagonal Jacobian relating surface tangent steps to half-vector derivatives. Newton iterations walk the intermediate vertices along their smooth surface parameterizations (the **specular manifold**) until the constraint vanishes, then project each step back onto the geometry by ray tracing. Once converged, the path throughput is divided by the generalized geometry term given by the Jacobian determinant. **Specular Manifold Sampling (SMS)** extends MNEE from a single deterministic seed to randomized manifold walks over candidate specular surfaces and micro-normal glints, estimating the reciprocal probability of finding each solution via Bernoulli trials so the estimator remains unbiased even when multiple caustic paths connect the same endpoints. ## When to use it Choose it when a path tracer must render sharp refractive caustics, underwater lighting, backlit glass, or high-frequency specular glints without storing a large global photon map. Prefer [photon-mapping](photon-mapping) or [progressive-photon-mapping](progressive-photon-mapping) when caustics involve many diffuse-specular bounces or complex multi-interface glass where manifold walks struggle to converge. Prefer standard [next-event-estimation](next-event-estimation) for unobstructed direct lighting, and [bidirectional-path-tracing](bidirectional-path-tracing) or [metropolis-light-transport](metropolis-light-transport) when general difficult transport dominates beyond single-chain caustics. ## Cost heavy — Each caustic connection runs several Newton iterations with ray re-projections and Jacobian solves; unbiased SMS adds repeated Bernoulli trials that increase per-sample cost on complex curved meshes. Measured GPU Weight: 2.82× baseline (light) — 0.0929 ms median / 0.0952 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.4× baseline (light) — 0.0381 ms median (2.44× faster on L4). Ampere A100 scaling: 1.81× baseline (feather) — 0.0521 ms median (1.78× faster on A100). ## Failure modes - Original MNEE is biased whenever multiple specular paths connect the same shading point and light, because a single straight-line seed finds at most one solution - Newton walks diverge or stall on grazing angles, high-curvature geometry, normal-map discontinuities, or across sharp crease edges - Unbiased SMS Bernoulli estimation can exhibit high variance when a caustic solution has a very small basin of attraction - Refractive chains with many interfaces increase Jacobian size and reduce convergence rates compared to single- or double-interface glass ## Engine support - blender: builtin — `Cycles > Object Properties > Shading > Caustics (Shadow Caustics via Manifold Next Event Estimation in intern/cycles/kernel/integrator/mnee.h)` (evidence: https://github.com/blender/blender/blob/main/intern/cycles/kernel/integrator/mnee.h, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params, normals - Outputs: radiance - Platforms: webgpu, desktop-gpu, cuda, cpu ## Presets ### Manifold Next Event Estimation (MNEE) — dark occluded glass shadow (left) vs specular-manifold Newton caustic (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_IOR": 1.52, "P_WAVE_RIPPLE": 0.75, "P_LIGHT_SWAY": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_IOR = 1.52; // P Glass IOR [1.15, 2.1, 0.02] const float P_WAVE_RIPPLE = 0.75; // P Refractive Ripple [0.0, 1.4, 0.04] const float P_LIGHT_SWAY = 0.65; // P Light Motion [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Direct / MNEE Split [0.0, 1.0, 0.02] // Refractive water-glass lens sphere with gentle surface undulation float lensHeight(vec3 p, float ripple, float t) { return 0.018 * ripple * sin(p.x * 12.0 + t * 2.0) * cos(p.z * 12.0 - t * 1.6); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isMNEE = screenX >= split; float ior = clamp(P_IOR, 1.1, 2.2); float ripple = clamp(P_WAVE_RIPPLE, 0.0, 1.5); float swayT = iTime * max(P_LIGHT_SWAY, 0.0); vec3 ro = vec3(0.0, 0.88, 2.22); vec3 rd = normalize(vec3(uv.x, uv.y - 0.30, -1.45)); vec3 bg = mix(vec3(0.022, 0.028, 0.046), vec3(0.068, 0.088, 0.135), smoothstep(-0.5, 0.5, uv.y)); vec3 col = bg; vec3 lDir = normalize(vec3(0.32 * sin(swayT * 0.6), 0.92, 0.25 * cos(swayT * 0.6))); vec3 sc = vec3(0.0, 0.14, 0.0); float rad = 0.48; // Intersect glass sphere & studio floor plane at y = -0.36 vec3 oc = ro - sc; float b = dot(oc, rd); float c = dot(oc, oc) - rad * rad; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tFl = (rd.y < -0.01) ? ((-0.36 - ro.y) / rd.y) : 1e5; if (tFl < 0.05 || tFl > 12.0) tFl = 1e5; if (tSph < tFl && tSph < 1e4) { // Shaded dielectric glass lens orb vec3 p = ro + rd * tSph; vec3 n = normalize(p - sc + vec3( 0.08 * ripple * cos(p.x * 12.0 + swayT * 2.0), 0.0, -0.08 * ripple * sin(p.z * 12.0 - swayT * 1.6) )); float ndv = max(dot(n, -rd), 0.0); float f0 = pow((ior - 1.0) / (ior + 1.0), 2.0); float fres = f0 + (1.0 - f0) * pow(1.0 - ndv, 5.0); vec3 refrD = refract(rd, n, 1.0 / ior); vec3 pExit = p + refrD * 0.72; vec3 nExit = -normalize(pExit - sc); vec3 rOut = refract(refrD, nExit, ior); if (length(rOut) < 0.01) rOut = reflect(refrD, nExit); // Refracted checkerboard floor visible through glass orb vec3 refrCol = bg; if (rOut.y < -0.01) { float tf2 = (-0.36 - pExit.y) / rOut.y; vec3 fp2 = pExit + rOut * max(tf2, 0.0); vec2 chk = floor(fp2.xz * 2.5); refrCol = mix(vec3(0.24, 0.28, 0.34), vec3(0.74, 0.76, 0.80), mod(chk.x + chk.y, 2.0)); } vec3 reflD = reflect(rd, n); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 96.0); vec3 env = mix(vec3(0.08, 0.14, 0.24), vec3(0.75, 0.84, 0.96), smoothstep(0.0, 0.8, reflD.y)); col = mix(refrCol * vec3(0.86, 0.96, 1.0), env, clamp(fres * 1.15, 0.08, 0.92)) + vec3(1.0) * spec * 1.6; } else if (tFl < 1e4) { vec3 p = ro + rd * tFl; vec2 chk = floor(p.xz * 2.5); vec3 floorAlb = mix(vec3(0.20, 0.24, 0.30), vec3(0.68, 0.70, 0.74), mod(chk.x + chk.y, 2.0)); // Geometric shadow footprint cast by refractive orb on floor vec3 toL = lDir; vec3 shadowCenter = sc - lDir * ((sc.y + 0.36) / max(lDir.y, 0.1)); vec2 rel = p.xz - shadowCenter.xz; float rShadow = length(rel); float inShadow = smoothstep(rad * 1.06, rad * 0.92, rShadow); vec3 direct = floorAlb * (0.20 + 0.82 * (1.0 - inShadow * 0.88)); if (isMNEE) { // Right: MNEE solves the specular manifold constraint c(x_m) = 0 via Newton iterations to connect p -> glass -> light! // Focused refractive caustic core + rippled lens dispersion fringes inside the refractive shadow! float focusPower = clamp((ior - 1.05) * 1.8, 0.2, 2.2); vec2 warp = rel + vec2( 0.045 * ripple * sin(rel.x * 16.0 + swayT * 2.0), 0.045 * ripple * cos(rel.y * 16.0 - swayT * 1.6) ); float rW = length(warp); // Bright focused spherical-aberration caustic spot + bright peripheral ring inside shadow float core = exp(-rW * rW * (22.0 + 18.0 * focusPower)) * (1.6 + 1.4 * focusPower); float ring = exp(-pow((rW - rad * 0.62 / max(focusPower * 0.6 + 0.5, 0.6)) * 18.0, 2.0)) * 0.85; float rippleWeb = (0.5 + 0.5 * sin(warp.x * 26.0 + warp.y * 18.0)) * 0.25 * ripple; // Subtle chromatic RGB dispersion from Snell's law Jacobian determinant vec3 causticRGB = vec3( exp(-pow(rW * 1.04, 2.0) * 28.0), exp(-pow(rW * 1.00, 2.0) * 28.0), exp(-pow(rW * 0.96, 2.0) * 28.0) ) * (1.8 + focusPower) + vec3(0.98, 0.88, 0.68) * (ring + rippleWeb) * inShadow; col = direct + floorAlb * causticRGB * inShadow * 1.25 + vec3(1.0, 0.94, 0.80) * core * 0.45 * inShadow; } else { // Left: Standard NEE treats dielectric glass as an opaque shadow blocker -> pitch-dark shadow with zero caustic! col = direct; } col = mix(col, bg, 1.0 - exp(-tFl * 0.12)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Next-event estimation (direct light sampling)](https://texelatlas.vercel.app/t/next-event-estimation.md) ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Provides an explicit caustic estimator at diffuse vertices inside a standard unidirectional path tracer. - [Multiple Importance Sampling](https://texelatlas.vercel.app/t/multiple-importance-sampling.md): Blends manifold caustic connections with BSDF-sampled glossy paths to handle moderately rough specular interfaces. ## Combination ideas - [Dispersive manifold caustics denoised with joint NLM](https://texelatlas.vercel.app/ideas/spectral-mnee-jnlm-caustics/) ## Sources 1. [primary] Johannes Hanika, Marc Droske, Luca Fascione (2015) Manifold Next Event Estimation. Computer Graphics Forum. https://doi.org/10.1111/cgf.12681 (verified via crossref on 2026-11-30) 2. [primary] Tizian Zeltner, Iliyan Georgiev, Wenzel Jakob (2020) Specular manifold sampling for rendering high-frequency caustics and glints. ACM Transactions on Graphics. https://doi.org/10.1145/3386569.3392408 (verified via crossref on 2026-11-30) 3. [secondary] Wenzel Jakob, Steve Marschner (2012) Manifold exploration. ACM Transactions on Graphics. https://doi.org/10.1145/2185520.2185554 (verified via crossref on 2026-11-30) 4. [implementation] pissang (2026) pissang/mutracer. https://github.com/pissang/mutracer License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Manifold Next-Event Estimation and Specular Manifold Sampling." https://texelatlas.vercel.app/t/manifold-next-event-estimation/ (accessed 2026-12-01). --- id: "map-elites" title: "MAP-Elites (Quality-Diversity Search)" aliases: [illumination algorithm, quality-diversity] domain: "procgen" stage: "procedural" realtime: "offline" platforms: [cpu, python, cuda] year_introduced: 2015 inputs: [layout] outputs: [layout, graph] style: "both" dynamic: "static" cost: "offline" authority: "Mouret & Clune, 2015" url: "https://texelatlas.vercel.app/t/map-elites/" sources_verified_at: "2026-11-29" --- # MAP-Elites (Quality-Diversity Search) (Mouret & Clune, 2015) > An evolutionary algorithm that fills a grid defined by chosen behaviour descriptors with the best-performing solution found for each cell, producing a diverse archive of high-quality content instead of a single optimum. ## Reach for it when - want many diverse good variants not one optimum - generated levels all look alike - explore content along axes like size and difficulty - need an archive of high-quality varied designs ## How it works The designer picks a fitness function (how good is this content) and a few behaviour descriptors (such as room count, symmetry, height, density) that discretise into a grid, the 'map'. Initialise the map with random candidates. Then repeat: pick a random occupied cell, mutate or recombine its elite to create a child, evaluate fitness and descriptors, and place the child in the matching cell if that cell is empty or the child has higher fitness. After many iterations the map shows, for each descriptor combination, the best content found, and the designer can browse it to choose levels, terrains or models along each axis. Variants (CVT-MAP-Elites, CMA-ME) handle higher descriptor dimensions and better exploration. ## When to use it Choose it for content generation where you want a diverse set of valid, high-scoring variants along interpretable axes (dungeons of different sizes and difficulty, terrain styles, parametric shapes). Prefer a single-objective optimiser when you need exactly one optimum, and a constraint solver like [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) when the aim is satisfying local rules rather than scoring. ## Cost offline — Thousands to millions of evaluations; cost is dominated by the evaluation function (often a simulation or render). Measured GPU Weight: 14.06× baseline (moderate) — 0.4625 ms median / 0.479 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.66× baseline (moderate) — 0.2172 ms median (2.13× faster on L4). Ampere A100 scaling: 9.59× baseline (moderate) — 0.2761 ms median (1.68× faster on A100). ## Failure modes - Descriptors that do not correlate with meaningful variation fill the map with near-duplicates - Descriptor grid dimension explodes: more than about 3 axes needs CVT-style tessellation - Fitness landscape deception: elites in one cell are only reachable through low-fitness cells, so coverage stalls - Heavy dependence on mutation operator design; bad operators fill the map with invalid content ## Dataflow - Inputs: layout - Outputs: layout, graph - Platforms: cpu, python, cuda ## Presets ### MAP-Elites (Quality-Diversity) — 5x5 behavior-descriptor archive grid (left) vs selected elite 3D morphology (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_EVO_SPEED": 0.65, "P_SEL_CELL_X": 0.62, "P_SEL_CELL_Y": 0.68, "P_SPLIT": 0.52 } ``` ```glsl const float P_EVO_SPEED = 0.65; // P Evolution Rate [0.0, 2.0, 0.05] const float P_SEL_CELL_X = 0.62; // P Descriptor X (Sym) [0.0, 1.0, 0.05] const float P_SEL_CELL_Y = 0.68; // P Descriptor Y (Comp) [0.0, 1.0, 0.05] const float P_SPLIT = 0.52; // P Archive / Hero Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Parametric evolved 3D morphology indexed by Behavior Descriptors (bx = fold/spikiness, by = branching/hollowness) float sdMorphology(vec3 p, float bx, float by) { float r = length(p); float phi = atan(p.z, p.x); float th = acos(clamp(p.y / max(r, 1e-4), -1.0, 1.0)); float symFreq = floor(2.0 + bx * 5.0); float lobes = 0.14 * (0.2 + 0.8 * bx) * cos(phi * symFreq) * sin(th * (2.0 + floor(by * 3.0))); float baseSph = r - (0.44 + lobes); // Branching torus / ring structure controlled by descriptor Y vec2 q = vec2(length(p.xz) - (0.34 + 0.16 * by), p.y); float dRing = length(q) - (0.14 - 0.04 * by); float d = mix(baseSph, min(baseSph, dRing), smoothstep(0.15, 0.85, by)); // Hollow core carving at high descriptor Y float carve = length(p) - (0.18 + 0.16 * by); d = max(d, -mix(-1.0, carve, smoothstep(0.45, 0.95, by))); return d * 0.68; } vec3 calcMorphNormal(vec3 p, float bx, float by) { vec2 e = vec2(0.0035, 0.0); return normalize(vec3( sdMorphology(p + e.xyy, bx, by) - sdMorphology(p - e.xyy, bx, by), sdMorphology(p + e.yxy, bx, by) - sdMorphology(p - e.yxy, bx, by), sdMorphology(p + e.yyx, bx, by) - sdMorphology(p - e.yyx, bx, by) )); } // Evaluate fitness score for a cell (bx, by) growing over evolutionary generations float evalCellFitness(vec2 cellId, float evoT) { float bx = (cellId.x + 0.5) / 5.0; float by = (cellId.y + 0.5) / 5.0; float seed = hash21(cellId * 13.7 + 2.1); // Multi-modal quality landscape across behavior space float peak = 0.42 + 0.34 * sin(bx * 4.2 + 0.6) * cos(by * 3.8 - 0.4) + 0.24 * seed; float wave = smoothstep(0.0, 1.0, fract(evoT * 0.18 + seed * 0.7)); return clamp(peak * (0.68 + 0.32 * wave), 0.15, 1.0); } vec3 viridis(float t) { t = clamp(t, 0.0, 1.0); vec3 c0 = vec3(0.18, 0.08, 0.36); vec3 c1 = vec3(0.12, 0.54, 0.56); vec3 c2 = vec3(0.96, 0.86, 0.20); if (t < 0.5) return mix(c0, c1, t * 2.0); return mix(c1, c2, (t - 0.5) * 2.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showHero = sx >= split; float evoT = iTime * max(P_EVO_SPEED, 0.0); float selX = clamp(P_SEL_CELL_X, 0.0, 0.999); float selY = clamp(P_SEL_CELL_Y, 0.0, 0.999); vec2 selCell = floor(vec2(selX, selY) * 5.0); // Animated evolutionary mutation cursor jumping across archive cells float mutIdx = mod(floor(evoT * 1.4), 25.0); vec2 mutCell = vec2(mod(mutIdx, 5.0), floor(mutIdx / 5.0)); vec3 col = vec3(0.04, 0.05, 0.08); if (!showHero) { // Left: 5x5 MAP-Elites Quality-Diversity Archive Illumination Grid! vec2 p = vec2(sx / max(split, 0.05), fragCoord.y / max(iResolution.y, 1.0)); vec2 g = (p - vec2(0.06, 0.08)) / vec2(0.88, 0.84); if (g.x >= 0.0 && g.x < 1.0 && g.y >= 0.0 && g.y < 1.0) { vec2 cellId = floor(g * 5.0); vec2 f = fract(g * 5.0); float bx = (cellId.x + 0.5) / 5.0; float by = (cellId.y + 0.5) / 5.0; float fit = evalCellFitness(cellId, evoT); vec3 fitCol = viridis(fit); // Cell background shaded by elite fitness score col = fitCol * 0.24; // Mini 3D raymarched specimen inside each archive cell vec2 cuv = (f - 0.5) * 2.1; float a = iTime * 0.5 + cellId.x * 0.7 + cellId.y * 0.5; mat3 rot = mat3(cos(a), 0.0, sin(a), 0.0, 1.0, 0.0, -sin(a), 0.0, cos(a)); vec3 ro = vec3(0.0, 0.25, 1.75); vec3 rd = normalize(vec3(cuv, -1.75)); float t = 0.4; for (int i = 0; i < 22; i++) { vec3 mp = rot * (ro + rd * t); float d = sdMorphology(mp, bx, by); if (d < 0.012) { vec3 n = normalize(transpose(rot) * calcMorphNormal(mp, bx, by)); float nl = max(dot(n, normalize(vec3(0.6, 0.8, 0.5))), 0.12); col = fitCol * (0.35 + 1.15 * nl) + vec3(0.85) * pow(max(dot(n, normalize(vec3(0.3, 0.6, 0.8))), 0.0), 20.0) * 0.4; break; } t += d; if (t > 2.8) break; } // Bottom fitness bar inside each cell if (f.y < 0.09 && f.x > 0.08 && f.x < 0.08 + 0.84 * fit) { col = fitCol * 1.25; } // Grid divider & highlight borders for Selected Elite (white/gold) and Active Mutation Probe (cyan) float border = smoothstep(0.045, 0.015, min(min(f.x, 1.0 - f.x), min(f.y, 1.0 - f.y))); vec3 bCol = vec3(0.14, 0.18, 0.24); if (all(equal(cellId, selCell))) bCol = vec3(1.0, 0.84, 0.22) * 1.4; else if (all(equal(cellId, mutCell))) bCol = vec3(0.22, 0.95, 1.0) * 1.3; col = mix(col, bCol, border); } } else { // Right: Full-resolution 3D studio hero inspection of the selected archive elite! float bx = (selCell.x + 0.5) / 5.0; float by = (selCell.y + 0.5) / 5.0; float fit = evalCellFitness(selCell, evoT); vec3 fitCol = viridis(fit); float a = iTime * 0.48; mat3 rot = mat3(cos(a), 0.0, sin(a), 0.0, 1.0, 0.0, -sin(a), 0.0, cos(a)); vec3 ro = vec3(0.0, 0.28, 1.95); vec3 rd = normalize(vec3(uv - vec2(0.18, 0.0), -1.45)); col = mix(vec3(0.05, 0.06, 0.09), vec3(0.14, 0.18, 0.26), uv.y + 0.5); float t = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { vec3 mp = rot * (ro + rd * t); float d = sdMorphology(mp, bx, by); if (d < 0.002) { hit = true; break; } t += d; if (t > 5.5) break; } if (hit) { vec3 mp = rot * (ro + rd * t); vec3 n = normalize(transpose(rot) * calcMorphNormal(mp, bx, by)); vec3 v = -rd; vec3 L1 = normalize(vec3(0.65, 0.78, 0.52)); vec3 L2 = normalize(vec3(-0.7, -0.2, 0.55)); vec3 H = normalize(L1 + v); float ndl1 = max(dot(n, L1), 0.0); float ndl2 = max(dot(n, L2), 0.0); float spec = pow(max(dot(n, H), 0.0), 42.0); float rim = pow(1.0 - max(dot(n, v), 0.0), 3.0); col = fitCol * (1.28 * ndl1 + 0.35 * ndl2 + 0.20) + vec3(1.0, 0.95, 0.88) * spec * 0.85 + fitCol * rim * 0.55; } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [BSP Dungeon Generation](https://texelatlas.vercel.app/t/bsp-dungeon-generation.md): Dungeon parameters are evolved and the map archives layouts by descriptors like room count and loop count. ## Sources 1. [primary] Jean-Baptiste Mouret, Jeff Clune (2015) Illuminating search spaces by mapping elites. arXiv preprint (cs.AI). https://arxiv.org/abs/1504.04909 (verified via arxiv on 2026-11-29) 2. [implementation] resibots (2019) resibots/pymap_elites. https://github.com/resibots/pymap_elites License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "MAP-Elites (Quality-Diversity Search)." https://texelatlas.vercel.app/t/map-elites/ (accessed 2026-12-01). --- id: "marble-world-model" title: "Marble (World Labs multimodal world model)" aliases: [Marble] domain: "genai" stage: "generation" realtime: "offline" platforms: [python] year_introduced: 2025 inputs: [text-prompt, ldr-image, layout] outputs: [gaussians, mesh] style: "both" dynamic: "static" cost: "offline" authority: "Labs" url: "https://texelatlas.vercel.app/t/marble-world-model/" sources_verified_at: "2026-11-29" --- # Marble (World Labs multimodal world model) (Labs) > A hosted world model from World Labs that creates persistent 3D worlds from text, images, video or coarse 3D layouts and exports them as Gaussian splats, meshes or videos. ## Reach for it when - generate a persistent 3d environment from text or images - need an exportable generated world as splats or mesh - quick previs environment from a prompt - build xr or game scenes from a single picture - create world from coarse 3d layout ## How it works Per World Labs' announcement, Marble takes text, a single or multiple images, video or a coarse 3D layout and produces a world that can then be edited, extended and composed with others. The output is an explicit 3D representation you can download (Gaussian splats, meshes, or rendered video), unlike action-conditioned video world models. World Labs has not published a paper that explains the architecture in the cited source, so details such as the exact representation and training are unknown to me. ## When to use it Choose it when you want a persistent, exportable generated environment for previs, games or XR and accept a hosted service. Prefer [WorldGen (text/image to 3D scene)](https://texelatlas.vercel.app/t/worldgen.md) for an open-source local alternative, [Genie 2 and Genie 3 (interactive world models)](https://texelatlas.vercel.app/t/genie-world-models.md) for interactive but non-exportable worlds, and [SAM 3D Objects](https://texelatlas.vercel.app/t/sam-3d-objects.md) for isolated objects with pose. ## Cost offline — Hosted service; cost and latency governed by the vendor. ## Failure modes - Closed, hosted: no weights or inspectable method - Geometry exported as splats or meshes can be noisy and unsuitable for physics without cleanup - Large scenes show detail loss and inconsistency far from the original view - Licence terms and quotas are set by the service ## Dataflow - Inputs: text-prompt, ldr-image, layout - Outputs: gaussians, mesh - Platforms: python ## Sources 1. [primary] World Labs Marble: A Multimodal World Model. worldlabs.ai. https://worldlabs.ai/blog/marble-world-model (verified via http on 2026-11-29) ## Cite this entry Texel. "Marble (World Labs multimodal world model)." https://texelatlas.vercel.app/t/marble-world-model/ (accessed 2026-12-01). --- id: "marching-cubes" title: "Marching Cubes" aliases: [MC] domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, desktop-gpu, cuda, blender, unity] year_introduced: 1987 inputs: [voxels, sdf] outputs: [mesh, normals] style: "both" dynamic: "both" cost: "medium" authority: "Lorensen & Cline, 1987" url: "https://texelatlas.vercel.app/t/marching-cubes/" sources_verified_at: "2026-11-29" --- # Marching Cubes (Lorensen & Cline, 1987) > Walks every cell of a scalar grid and, from the signs at its eight corners, picks a precomputed triangle pattern that cuts the cell where the field crosses the iso-value. The classic way to turn volumes or SDFs into triangle meshes. ## Reach for it when - convert voxel or density field to a mesh - extract surface from scalar volume or metaballs - make terrain with caves and overhangs - visualize medical scan volume as a surface ## How it works Sample the field at grid corners. For each cell, build an 8-bit index from which corners are inside (below the iso-value). That index selects one of 256 cases (15 up to symmetry) from a lookup table listing which cell edges the surface crosses and how to connect those crossings into triangles. Each crossing vertex is placed by linear interpolation of the two corner values along the edge. Vertices on shared edges are identical, so welding them gives an indexed mesh. Normals come from the field gradient (central differences) rather than from the faces, which gives smooth shading. The whole loop is embarrassingly parallel: GPU versions classify cells, stream-compact the active ones with a prefix sum, then emit triangles. ## When to use it Choose it when you need a quick, robust mesh from a density grid or SDF and sharp features do not matter (medical volumes, metaballs, voxel terrain, sculpt previews). Prefer [Dual Contouring](https://texelatlas.vercel.app/t/dual-contouring.md) or [Manifold Dual Contouring](https://texelatlas.vercel.app/t/manifold-dual-contouring.md) when corners and creases must survive, [Surface Nets](https://texelatlas.vercel.app/t/surface-nets.md) when you want fewer, better-shaped triangles with the same simplicity, and [Marching Tetrahedra](https://texelatlas.vercel.app/t/marching-tetrahedra.md) when you want to avoid the ambiguous cube cases. ## Cost medium — Linear in the number of cells; trivially parallel. Cost is dominated by field sampling and by triangle count, which grows with the square of grid resolution. Measured GPU Weight: 3.74× baseline (light) — 0.123 ms median / 0.1269 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.32× baseline (light) — 0.0528 ms median (2.33× faster on L4). Ampere A100 scaling: 2.33× baseline (light) — 0.067 ms median (1.84× faster on A100). ## Failure modes - Sharp edges and corners are rounded off because only edge crossings, never normals, are used - Ambiguous face cases in the original 15-case table can produce holes or cracks unless the extended table is used - Sliver triangles and uneven triangle sizes where the surface grazes a cell corner - Stair-stepping or banding when the field is a binary mask instead of a smooth distance - Cracks between chunks of different resolution unless a transition scheme is used ## Engine support - blender: builtin — `Geometry Nodes > Volume > Grid to Mesh (or Volume to Mesh)` (evidence: https://docs.blender.org/manual/en/5.2/modeling/geometry_nodes/volume/operations/grid_to_mesh.html, checked 2026-12-01) — Isosurface extraction; the manual calls it similar to Marching Cubes. - threejs: official — `import { MarchingCubes } from 'three/addons/objects/MarchingCubes.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/objects/MarchingCubes.js, checked 2026-12-01) - unreal: builtin — `Modeling Mode > Voxel tools (VoxelMerge / VoxelBlend / Solidify) and Geometry Script Solidify (GeometryScriptSolidifyOptions)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/GeometryScriptSolidifyOptions, checked 2026-12-01) ## Dataflow - Inputs: voxels, sdf - Outputs: mesh, normals - Platforms: cpu, webgl2, webgpu, desktop-gpu, cuda, blender, unity ## Presets ### Toy 2D marching squares: corner signs, cases and interpolated crossings (glsl-fragment; rendered 2026-11-29) ```json { "CELLS": 10 } ``` ```glsl // Toy 2D analogue (marching squares): corner signs pick a case per cell, edge crossings are linearly interpolated. const float CELLS = 10.0; float field(vec2 p) { vec2 a = vec2(0.36 + 0.06 * sin(iTime), 0.5), b = vec2(0.64, 0.5 + 0.1 * cos(iTime)); return 0.018 / dot(p - a, p - a) + 0.014 / dot(p - b, p - b) - 1.0; } float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0)); } vec2 xing(vec2 p0, vec2 p1, float f0, float f1) { return mix(p0, p1, f0 / (f0 - f1)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float cs = 1.0 / CELLS; vec2 c0 = floor(uv / cs) * cs; vec2 P[4]; float F[4]; P[0] = c0; P[1] = c0 + vec2(cs, 0); P[2] = c0 + cs; P[3] = c0 + vec2(0, cs); for (int i = 0; i < 4; i++) F[i] = field(P[i]); float d = 1e9; vec2 pts[4]; int n = 0; for (int i = 0; i < 4; i++) { int j = (i + 1) % 4; if ((F[i] > 0.0) != (F[j] > 0.0)) { pts[n] = xing(P[i], P[j], F[i], F[j]); n++; } } if (n == 2) d = segd(uv, pts[0], pts[1]); if (n == 4) d = min(segd(uv, pts[0], pts[1]), segd(uv, pts[2], pts[3])); vec3 col = vec3(0.07, 0.08, 0.11); float f = field(uv); col += vec3(0.05, 0.08, 0.12) * (f > 0.0 ? 1.0 : 0.0); vec2 g = abs(fract(uv / cs) - 0.5); col = mix(col, vec3(0.2, 0.22, 0.3), smoothstep(0.015, 0.0, 0.5 - max(g.x, g.y))); col = mix(col, vec3(1.0, 0.75, 0.25), smoothstep(0.004, 0.002, d)); for (int i = 0; i < 4; i++) { float r = length(uv - P[i]); col = mix(col, F[i] > 0.0 ? vec3(0.3, 0.9, 0.5) : vec3(0.4, 0.45, 0.55), smoothstep(0.011, 0.008, r)); } // true contour for reference col = mix(col, vec3(1.0, 0.3, 0.3), smoothstep(0.012, 0.0, abs(f)) * 0.0); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): The smooth-min SDF supplies the scalar field; marching cubes meshes it. - [Taubin Smoothing](https://texelatlas.vercel.app/t/taubin-smoothing.md): Taubin smoothing relaxes the stair-stepped output without shrinking it. - [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md): Simplify the dense triangle soup the grid produces. ## Sources 1. [primary] William E. Lorensen, Harvey E. Cline (1987) Marching cubes: A high resolution 3D surface construction algorithm. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/37402.37422 (verified via crossref on 2026-11-29) 2. [implementation] mikolalysenko (2013) mikolalysenko/isosurface. https://github.com/mikolalysenko/isosurface License: MIT. (verified via github on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) 4. [tutorial] Paul Bourke Polygonising a scalar field. paulbourke.net. https://paulbourke.net/geometry/polygonise (verified via http on 2026-11-29) ## Cite this entry Texel. "Marching Cubes." https://texelatlas.vercel.app/t/marching-cubes/ (accessed 2026-12-01). --- id: "marching-tetrahedra" title: "Marching Tetrahedra" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, desktop-gpu, cuda] year_introduced: 1988 inputs: [voxels, sdf] outputs: [mesh] style: "both" dynamic: "both" cost: "medium" authority: "Bloomenthal, 1988" url: "https://texelatlas.vercel.app/t/marching-tetrahedra/" sources_verified_at: "2026-11-29" --- # Marching Tetrahedra (Bloomenthal, 1988) > Splits each grid cube into tetrahedra and triangulates the iso-surface inside each one using just three cases. It removes the ambiguity of marching cubes and works on arbitrary tetrahedral meshes. ## Reach for it when - marching cubes gives ambiguous holes or cracks - iso-surface needed from a tetrahedral mesh - extract surface from fem simulation output - need topology-consistent surface extraction without a big table ## How it works Each cube is divided into five or six tetrahedra sharing a diagonal (or the grid is a body-centred / Freudenthal tetrahedralization). In a tetrahedron the four vertex signs give at most 16 combinations that collapse to three non-trivial cases: one vertex apart (one triangle), two against two (a quad, i.e. two triangles) and the empty cases. Because a tetrahedron is a simplex, the surface inside it is unambiguous and the resulting mesh is guaranteed watertight and crack-free across neighbours as long as the split directions agree on shared faces. Crossing points are interpolated linearly along edges exactly as in marching cubes. Because it operates on simplices, the same code runs on simulation tetrahedral meshes and adaptive grids. ## When to use it Choose it when the field lives on an unstructured tet mesh (FEM output, adaptive grids) or when you want guaranteed topology consistency without a 256-entry table. Prefer [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) when you want fewer triangles from a regular grid (tets produce roughly twice as many), and [Dual Contouring](https://texelatlas.vercel.app/t/dual-contouring.md) when sharp features matter. ## Cost medium — Linear in cell count with a constant factor several times that of marching cubes because each cube becomes five or six tets. Measured GPU Weight: 44.13× baseline (heavy) — 1.3681 ms median / 1.4355 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 34.98× baseline (heavy) — 0.5562 ms median (2.46× faster on L4). Ampere A100 scaling: 29.76× baseline (heavy) — 0.8571 ms median (1.6× faster on A100). ## Failure modes - Noticeably more and thinner triangles than marching cubes - Visible diagonal bias: the tetrahedral split direction leaves a faint directional pattern on flat regions - Same corner-rounding as marching cubes; sharp features are lost - Linear interpolation across a coarse grid gives a faceted look unless normals come from the field ## Dataflow - Inputs: voxels, sdf - Outputs: mesh - Platforms: cpu, webgl2, webgpu, desktop-gpu, cuda ## Presets ### Marching Tetrahedra — 6-tet Kuhn voxel decomposition (left) vs watertight extracted isosurface (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CELL_RES": 7, "P_ISO_LEVEL": 0, "P_WIRE_GAIN": 0.9, "P_SPLIT": 0.48 } ``` ```glsl const float P_CELL_RES = 7.0; // P Voxel Grid Res [4.0, 14.0, 1.0] const float P_ISO_LEVEL = 0.0; // P Isovalue Shift [-0.15, 0.15, 0.01] const float P_WIRE_GAIN = 0.90; // P Tet Wireframe [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Tet Facets / Smooth [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Smooth organic metaball scalar field f(p) (classic ambiguous saddle for Marching Cubes, clean in Marching Tetrahedra!) float scalarField(vec3 q, float t, float iso) { vec3 c1 = vec3(0.38 * sin(t * 0.9), 0.24 * cos(t * 0.7), 0.18 * sin(t * 0.5)); vec3 c2 = vec3(-0.38 * cos(t * 0.8), -0.22 * sin(t * 0.9), -0.15 * cos(t * 0.6)); vec3 c3 = vec3(0.0, 0.34 * sin(t * 1.1), 0.30 * cos(t * 0.85)); float d1 = length(q - c1) - 0.38; float d2 = length(q - c2) - 0.36; float d3 = length(q - c3) - 0.32; return smin(smin(d1, d2, 0.28), d3, 0.28) - iso; } // Identify which of the 6 Kuhn tetrahedra inside the unit cube [0,1]^3 contains f: // Ordering of (f.x, f.y, f.z) defines the 6 canonical tetrahedra sharing main diagonal (0,0,0)-(1,1,1)! int kuhnTetId(vec3 f) { if (f.x >= f.y && f.y >= f.z) return 0; if (f.x >= f.z && f.z >= f.y) return 1; if (f.z >= f.x && f.x >= f.y) return 2; if (f.z >= f.y && f.y >= f.x) return 3; if (f.y >= f.z && f.z >= f.x) return 4; return 5; } // Piecewise-linear tetrahedral interpolation of the scalar field inside the Kuhn simplex! float evalTetLinear(vec3 q, float res, float t, float iso) { vec3 g = q * res; vec3 cell = floor(g); vec3 f = fract(g); float invR = 1.0 / res; // Sort f.x, f.y, f.z to locate the 4 vertices of the enclosing Kuhn tetrahedron vec3 v0 = cell; vec3 v3 = cell + vec3(1.0); vec3 v1, v2; float w0, w1, w2, w3; if (f.x >= f.y && f.y >= f.z) { v1 = cell + vec3(1.0, 0.0, 0.0); v2 = cell + vec3(1.0, 1.0, 0.0); w0 = 1.0 - f.x; w1 = f.x - f.y; w2 = f.y - f.z; w3 = f.z; } else if (f.x >= f.z && f.z >= f.y) { v1 = cell + vec3(1.0, 0.0, 0.0); v2 = cell + vec3(1.0, 0.0, 1.0); w0 = 1.0 - f.x; w1 = f.x - f.z; w2 = f.z - f.y; w3 = f.y; } else if (f.z >= f.x && f.x >= f.y) { v1 = cell + vec3(0.0, 0.0, 1.0); v2 = cell + vec3(1.0, 0.0, 1.0); w0 = 1.0 - f.z; w1 = f.z - f.x; w2 = f.x - f.y; w3 = f.y; } else if (f.z >= f.y && f.y >= f.x) { v1 = cell + vec3(0.0, 0.0, 1.0); v2 = cell + vec3(0.0, 1.0, 1.0); w0 = 1.0 - f.z; w1 = f.z - f.y; w2 = f.y - f.x; w3 = f.x; } else if (f.y >= f.z && f.z >= f.x) { v1 = cell + vec3(0.0, 1.0, 0.0); v2 = cell + vec3(0.0, 1.0, 1.0); w0 = 1.0 - f.y; w1 = f.y - f.z; w2 = f.z - f.x; w3 = f.x; } else { v1 = cell + vec3(0.0, 1.0, 0.0); v2 = cell + vec3(1.0, 1.0, 0.0); w0 = 1.0 - f.y; w1 = f.y - f.x; w2 = f.x - f.z; w3 = f.z; } return w0 * scalarField(v0 * invR, t, iso) + w1 * scalarField(v1 * invR, t, iso) + w2 * scalarField(v2 * invR, t, iso) + w3 * scalarField(v3 * invR, t, iso); } float mapWorld(vec3 p, bool faceted, float res, float t, float iso) { vec3 q = p; q.xz = rot2(t * 0.35) * q.xz; return faceted ? evalTetLinear(q, res, t, iso) : scalarField(q, t, iso); } vec3 calcNormal(vec3 p, bool faceted, float res, float t, float iso) { vec2 e = vec2(faceted ? 0.003 : 0.002, 0.0); return normalize(vec3( mapWorld(p + e.xyy, faceted, res, t, iso) - mapWorld(p - e.xyy, faceted, res, t, iso), mapWorld(p + e.yxy, faceted, res, t, iso) - mapWorld(p - e.yxy, faceted, res, t, iso), mapWorld(p + e.yyx, faceted, res, t, iso) - mapWorld(p - e.yyx, faceted, res, t, iso) )); } vec3 tetColor(int id) { if (id == 0) return vec3(0.95, 0.42, 0.24); if (id == 1) return vec3(0.96, 0.74, 0.22); if (id == 2) return vec3(0.22, 0.84, 0.56); if (id == 3) return vec3(0.18, 0.72, 0.94); if (id == 4) return vec3(0.58, 0.46, 0.96); return vec3(0.92, 0.38, 0.72); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSmooth = screenX >= split; float res = clamp(floor(P_CELL_RES + 0.5), 4.0, 14.0); float iso = clamp(P_ISO_LEVEL, -0.18, 0.18); float wireGain = clamp(P_WIRE_GAIN, 0.0, 1.5); float t = iTime; vec3 ro = vec3(0.0, 0.06, 2.38); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.025, 0.036, 0.058), vec3(0.072, 0.092, 0.142), smoothstep(-0.55, 0.55, uv.y)); float tHit = 0.0; bool hit = false; for (int i = 0; i < 72; i++) { float d = mapWorld(ro + rd * tHit, !isSmooth, res, t, iso); if (d < 0.002) { hit = true; break; } tHit += d * 0.72; if (tHit > 7.5) break; } if (hit) { vec3 p = ro + rd * tHit; vec3 n = calcNormal(p, !isSmooth, res, t, iso); vec3 objP = p; objP.xz = rot2(t * 0.35) * objP.xz; vec3 f = fract(objP * res); int tid = kuhnTetId(f); // Distance to any of the 6 Kuhn tetrahedron faces (cube boundaries + diagonal planes x=y, y=z, z=x) float dCube = min(min(min(f.x, 1.0 - f.x), min(f.y, 1.0 - f.y)), min(f.z, 1.0 - f.z)); float dDiag = min(min(abs(f.x - f.y), abs(f.y - f.z)), abs(f.z - f.x)) * 0.7071; float tetWire = smoothstep(0.055, 0.012, min(dCube, dDiag)); vec3 l1 = normalize(vec3(0.58, 0.84, 0.52)); vec3 l2 = normalize(vec3(-0.68, -0.22, 0.54)); float diff = max(dot(n, l1), 0.0) * 0.85 + max(dot(n, l2), 0.0) * 0.25; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 46.0); if (!isSmooth) { // Left: Exact piecewise-linear Marching Tetrahedra facets colored by the 6 Kuhn tetrahedron IDs vec3 tCol = tetColor(tid); col = tCol * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.35; col = mix(col, vec3(0.04, 0.06, 0.10), tetWire * 0.72 * min(wireGain, 1.2)); } else { // Right: Watertight smooth isosurface with subtle tetrahedral edge lattice vec3 alb = vec3(0.20, 0.76, 0.78); col = alb * (0.26 + 0.84 * diff) + vec3(0.98) * spec * 0.62; col = mix(col, vec3(0.06, 0.14, 0.20), tetWire * 0.24 * min(wireGain, 1.0)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): Same field input; tets trade triangle count for topological certainty. ## Combination ideas - [Crack-free latent morphing via DeepSDF and Marching Tetrahedra](https://texelatlas.vercel.app/ideas/deepsdf-isosurface-marching-tetrahedra/) ## Sources 1. [primary] Jules Bloomenthal (1988) Polygonization of implicit surfaces. Computer Aided Geometric Design. https://doi.org/10.1016/0167-8396(88)90013-1 (verified via crossref on 2026-11-29) 2. [implementation] mikolalysenko (2013) mikolalysenko/isosurface. https://github.com/mikolalysenko/isosurface License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Marching Tetrahedra." https://texelatlas.vercel.app/t/marching-tetrahedra/ (accessed 2026-12-01). --- id: "margolus-3d-block-cellular-automata" title: "3D Margolus 2×2×2 Block Cellular Automata" aliases: [Margolus neighborhood CA, partitioning cellular automata, 3D block cellular automata, mass-conserving voxel falling sand] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, cuda, cpu] year_introduced: 1984 inputs: [voxels] outputs: [voxels] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Margolus, 1984" url: "https://texelatlas.vercel.app/t/margolus-3d-block-cellular-automata/" sources_verified_at: "2026-11-30" --- # 3D Margolus 2×2×2 Block Cellular Automata (Margolus, 1984) > Partition a 3D voxel grid into disjoint 2×2×2 blocks whose origin shifts each substep, letting GPU threads update all blocks in place in parallel while strictly conserving voxel count and avoiding write conflicts. ## Reach for it when - falling sand or granular voxel sim loses or duplicates particles on gpu - need race-free parallel 3d cellular automata without atomic locks - simulate mass-conserving 3d sand piles water percolation and avalanches - update colliding voxel neighbors cleanly in alternating 2x2x2 blocks - build a fast real-time 3d falling-sand sandbox in compute shaders ## How it works Ordinary cellular automata update one cell at a time by reading neighbors, which makes mass-conserving transport (such as falling sand, rubble, or granular collapse) hard to parallelize on GPUs: two grains can simultaneously try to move into the same empty voxel, causing race conditions or lost matter. The Margolus partitioning scheme eliminates write hazards by decomposing the 3D lattice into non-overlapping $2\times 2\times 2$ blocks. On each step, a single GPU thread owns one 8-voxel block, reads all eight cells, applies a local mass-conserving permutation rule (such as letting sediment drop vertically into empty lower cells, slide diagonally off slopes, or erode when exposed to wind or water jets), and writes all eight voxels back **in place** with zero atomics and zero double-buffering. To allow matter to travel across block boundaries, the grid partition origin shifts between steps across offsets $(ox, oy, oz) \in \{0, 1\}^3$ (cycling or randomizing parity to prevent directional bias). Because every local rule only permutes states within a disjoint $2\times 2\times 2$ cube, total particle mass is conserved by construction while achieving full hardware parallelism across millions of voxels. ## When to use it Choose it for real-time 3D granular sand, sandstone erosion, rubble avalanches, or interactive destructible voxel sandboxes where strict mass conservation and race-free GPU compute performance matter. Prefer [gpu-pipe-model-erosion](gpu-pipe-model-erosion) or [shallow-water-equations](shallow-water-equations) for flowing water with hydrostatic pressure (Margolus voxel water lacks pressure gradients and creeps slowly without forming streams). Prefer [mpm-snow](mpm-snow) or [sph-fluids](sph-fluids) for smooth continuum deformation and free-flowing liquids. Prefer [cellular-automata-cave-generation](cellular-automata-cave-generation) when generating static procedural caverns without conservation laws. ## Cost cheap — Each thread updates 8 packed voxels in place with no ping-pong buffer copy or atomic contention; a 128^3 grid dispatches only 64^3 block threads per pass in WebGPU compute. ## Failure modes - No long-range hydrostatic pressure or momentum transmission: bulk liquids creep at most one voxel per step and pile up instead of rushing downhill - Regular parity cycling can create subtle diagonal bias or checkerboarding unless block shift orders are randomized or well-balanced - Maximum transport speed is bounded by one voxel per substep, requiring multiple substeps per frame for fast-falling debris - Fixed-resolution dense 3D voxel buffers scale cubically in memory with world extent ## Dataflow - Inputs: voxels - Outputs: voxels - Platforms: webgpu, webgl2, desktop-gpu, cuda, cpu ## Combines with - [Voxel grid DDA ray traversal (Amanatides–Woo)](https://texelatlas.vercel.app/t/voxel-grid-dda-traversal.md): Direct 3D DDA ray traversal renders the live voxel storage buffer immediately after each Margolus step without remeshing. - [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md): Virtual-pipe surface water cuts into solid rock voxels and feeds loosened sediment directly into the Margolus falling-block pass. ## Combination ideas - [Overhang-capable voxel erosion with pipe-model water](https://texelatlas.vercel.app/ideas/margolus-voxel-erosion-pipe-water/) ## Sources 1. [primary] Norman Margolus (1984) Physics-like models of computation. Physica D: Nonlinear Phenomena. https://doi.org/10.1016/0167-2789(84)90252-5 (verified via doi.org on 2026-11-30) 2. [primary] Tommaso Toffoli, Norman Margolus (1987) Cellular Automata Machines. The MIT Press. https://doi.org/10.7551/mitpress/1763.001.0001 (verified via crossref on 2026-11-30) 3. [implementation] ttillberg (2026) ttillberg/codevember-2026. https://github.com/ttillberg/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "3D Margolus 2×2×2 Block Cellular Automata." https://texelatlas.vercel.app/t/margolus-3d-block-cellular-automata/ (accessed 2026-12-01). --- id: "markov-junior-rewrite-rules" title: "MarkovJunior (Rewrite-Rule Generation)" aliases: [MarkovJunior, probabilistic rewrite rules] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu] year_introduced: 2022 inputs: [layout] outputs: [voxels, texture, layout] style: "both" dynamic: "static" cost: "offline" authority: "mxgmn, 2022" url: "https://texelatlas.vercel.app/t/markov-junior-rewrite-rules/" sources_verified_at: "2026-11-29" --- # MarkovJunior (Rewrite-Rule Generation) (mxgmn, 2022) > A probabilistic programming language for grid generation: sequences of pattern-rewrite rules, optionally guided by inference toward goal states, with WFC available as one of its node types. ## Reach for it when - prototype a dungeon or maze generator with readable rules - grow voxel structures from simple pattern rewrites - grid generation with goals like a path from a to b - procedural content without an example to imitate - generate grid patterns guided by constraints ## How it works A model is a tree of nodes executed over a grid of colours. A rewrite node has an input pattern and output pattern, like 'RB -> WW'; at each step it picks a random matching location and rewrites it. Nodes are composed with sequential, Markov (repeat until nothing applies) and one-shot semantics, giving growth processes, maze carvers and flood fills. Inference nodes use constraint propagation and search to steer rewriting toward a goal state, such as a path connecting two points, rather than hoping random rewriting finds it. Also includes a WFC node and a convolution node. Models are XML descriptions running in a C# interpreter that renders 2D and 3D output. ## When to use it Choose it when you want to prototype grid-based generators quickly (mazes, dungeons, voxel buildings, growth patterns) with explicit, readable rules and goal inference. Prefer [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) when you have an example to imitate, and [BSP Dungeon Generation](https://texelatlas.vercel.app/t/bsp-dungeon-generation.md) or [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) when a hand-written recursive procedure is clearer than a rule database. ## Cost offline — Interpreter cost scales with grid size and rule count; inference nodes add search cost. Designed for authoring, not per-frame use. Measured GPU Weight: 3.38× baseline (light) — 0.1112 ms median / 0.1142 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.77× baseline (light) — 0.0441 ms median (2.52× faster on L4). Ampere A100 scaling: 2.12× baseline (light) — 0.0611 ms median (1.82× faster on A100). ## Failure modes - Rule order and node semantics are subtle: a misplaced Markov node can loop forever or terminate immediately - Inference can fail to find any solution, leaving the run in an unsolved state - Output is grid-bound; exporting to meshes needs an extra meshing step - Random rewriting without inference often misses global goals like connectivity ## Dataflow - Inputs: layout - Outputs: voxels, texture, layout - Platforms: cpu ## Presets ### MarkovJunior — discrete symbol rewrite grid (left) vs sculpted dungeon tile architecture (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GRID_RES": 16, "P_RULE_STAGE": 0.78, "P_ANIM_RATE": 0.85, "P_SPLIT": 0.46 } ``` ```glsl const float P_GRID_RES = 16.0; // P Grid Resolution [10.0, 26.0, 2.0] const float P_RULE_STAGE = 0.78; // P Rewrite Progress [0.1, 1.0, 0.02] const float P_ANIM_RATE = 0.85; // P Rewrite Sweep [0.0, 2.5, 0.05] const float P_SPLIT = 0.46; // P Symbols / Tiles [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Deterministic MarkovJunior-style multi-stage grid symbol classifier: // Returns symbol ID: 0=void/black, 1=corridor/white, 2=room/gold, 3=river/cyan, 4=wall/crimson float evalMarkovCell(vec2 cell, float stage) { // Stage 1: Growing orthogonal maze corridors from central seed vec2 macro = floor(cell * 0.5); float h = hash21(macro); float isCorrX = step(0.5, mod(cell.y, 2.0)) * step(0.32, h); float isCorrY = step(0.5, mod(cell.x, 2.0)) * step(h, 0.68); float sym = max(isCorrX, isCorrY); // Stage 2: Room-carving rewrite rule (B-W-W -> R-R-R) in seeded chambers vec2 roomCell = floor(cell / 5.0); vec2 roomLocal = mod(cell, 5.0); if (hash21(roomCell + 7.3) > 0.45 && roomLocal.x >= 1.0 && roomLocal.x <= 3.0 && roomLocal.y >= 1.0 && roomLocal.y <= 3.0) { if (stage > 0.35) sym = 2.0; } // Stage 3: Winding river rewrite rule cutting through grid float riverX = floor(sin(cell.y * 0.38) * 2.2 + 0.5); if (abs(cell.x - riverX) < 0.6 && stage > 0.60) { sym = 3.0; } // Stage 4: Wall-border rewrite rule: any black cell adjacent to corridor/room becomes wall (4) if (sym < 0.5 && stage > 0.25) { float n1 = step(0.5, mod(cell.y + 1.0, 2.0)); float n2 = step(0.5, mod(cell.x + 1.0, 2.0)); if (n1 + n2 > 0.5) sym = 4.0; } return sym; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSymbols = screenX < split; float gridRes = clamp(floor(P_GRID_RES + 0.5), 8.0, 28.0); float stage = clamp(P_RULE_STAGE, 0.05, 1.0); float sweep = iTime * max(P_ANIM_RATE, 0.0); vec2 g = uv * gridRes; vec2 cell = floor(g); vec2 f = fract(g); // Expanding Markov rewrite wave radiating outward from seed origin float distSeed = length(cell) / (gridRes * 0.65); float activeWave = fract(sweep * 0.16) * 1.35 + stage * 0.55; float cellStage = stage * smoothstep(activeWave + 0.18, activeWave - 0.08, distSeed); float frontier = exp(-abs(distSeed - activeWave) * 18.0); float sym = evalMarkovCell(cell, cellStage); vec2 dEdge = min(f, 1.0 - f); float border = smoothstep(0.08, 0.02, min(dEdge.x, dEdge.y)); vec3 col; if (isSymbols) { // Left: Pure MarkovJunior flat color-coded symbol grid (classic B/W/R/U/Y palette) + active rewrite cursor vec3 symCol = vec3(0.06, 0.07, 0.10); // 0 = black void if (sym > 0.5 && sym < 1.5) symCol = vec3(0.90, 0.92, 0.96); // 1 = white path else if (sym > 1.5 && sym < 2.5) symCol = vec3(0.98, 0.76, 0.20); // 2 = gold room else if (sym > 2.5 && sym < 3.5) symCol = vec3(0.14, 0.80, 0.96); // 3 = cyan water else if (sym > 3.5) symCol = vec3(0.84, 0.24, 0.26); // 4 = crimson wall col = mix(symCol, vec3(0.04, 0.05, 0.08), border * 0.65); col += vec3(0.32, 1.0, 0.72) * frontier * 0.55; } else { // Right: Rendered beveled dungeon tiles & animated water from the rewritten symbol grid! float bevel = smoothstep(0.0, 0.18, min(dEdge.x, dEdge.y)); vec2 slope = vec2(smoothstep(0.82, 1.0, f.x) - smoothstep(0.18, 0.0, f.x), smoothstep(0.82, 1.0, f.y) - smoothstep(0.18, 0.0, f.y)); vec3 n = normalize(vec3(-slope.x * 1.4, -slope.y * 1.4, 1.0)); vec3 lDir = normalize(vec3(0.55, 0.65, 0.82)); float diff = max(dot(n, lDir), 0.0); vec3 tileCol = vec3(0.05, 0.06, 0.09); if (sym > 0.5 && sym < 1.5) { // Carved stone corridor flagstones tileCol = vec3(0.46, 0.48, 0.52) * (0.45 + 0.65 * diff) * (0.75 + 0.25 * bevel); } else if (sym > 1.5 && sym < 2.5) { // Warm inlaid golden mosaic room floor float inlay = smoothstep(0.28, 0.20, length(f - 0.5)); tileCol = mix(vec3(0.68, 0.52, 0.26), vec3(0.96, 0.80, 0.34), inlay) * (0.45 + 0.65 * diff); } else if (sym > 2.5 && sym < 3.5) { // Flowing subterranean canal water float rip = 0.5 + 0.5 * sin(g.y * 6.0 - sweep * 4.5 + sin(g.x * 4.0)); tileCol = mix(vec3(0.06, 0.42, 0.62), vec3(0.22, 0.86, 0.96), rip * 0.65 + 0.25); } else if (sym > 3.5) { // Raised masonry dungeon wall parapet float brick = step(0.10, fract(f.x * 2.0 + step(0.5, f.y) * 0.5)); tileCol = mix(vec3(0.26, 0.16, 0.18), vec3(0.54, 0.28, 0.26), brick) * (0.38 + 0.82 * diff); } col = tileCol + vec3(0.28, 0.95, 0.82) * frontier * 0.25; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) ## Combination ideas - [Fog that flows through generated caves](https://texelatlas.vercel.app/ideas/drafts-through-generated-dungeons/) ## Sources 1. [primary] mxgmn (2022) mxgmn/MarkovJunior. https://github.com/mxgmn/MarkovJunior License: MIT. (verified via github on 2026-11-29) 2. [implementation] mxgmn (2022) mxgmn/MarkovJunior. https://github.com/mxgmn/MarkovJunior License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "MarkovJunior (Rewrite-Rule Generation)." https://texelatlas.vercel.app/t/markov-junior-rewrite-rules/ (accessed 2026-12-01). --- id: "marschner-hair-scattering" title: "Marschner hair scattering model" aliases: [Marschner hair BSDF, R TT TRT hair model] domain: "materials" stage: "material" realtime: "interactive" platforms: [cpu, cuda, blender, houdini, unreal, desktop-gpu] year_introduced: 2003 inputs: [curves, material-params] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Marschner et al., 2003" url: "https://texelatlas.vercel.app/t/marschner-hair-scattering/" sources_verified_at: "2026-11-29" --- # Marschner hair scattering model (Marschner et al., 2003) > A physically motivated hair fibre model splitting scattering into surface reflection R, transmission TT and internal reflection TRT, each with its own longitudinal and azimuthal term. It explains hair's two highlights and coloured glow. ## Reach for it when - hair looks wrong compared to photographs - want physically based hair highlights and colored glow - path traced hair needs accurate fibre scattering - need separate reflection and transmission lobes for fibres - reference model to validate real-time hair shader ## How it works Hair is modelled as a smooth dielectric cylinder with a tilted cuticle and an absorbing interior. The scattering function factorises per lobe p into a longitudinal term M_p(theta) and an azimuthal term N_p(phi). R is a mirror-like bounce off the cuticle and stays white. TT is light refracting in and out of the fibre; TRT adds one internal reflection and exits on the same side as the viewer, picking up the colour of the pigment through the absorption coefficient. Longitudinal terms are Gaussians centred at shifts of 2 alpha, -alpha and -4 alpha for the cuticle tilt alpha, with different widths per lobe, which is why the highlights are offset along the strand and differently coloured. The azimuthal terms come from tracing the refracted ray through the circular cross-section with Fresnel weights and attenuation. Modern implementations such as the pbrt formulation add energy-preserving normalisation and importance sampling, and extend the model with ellipse cross-sections or glints. ## When to use it Choose it as the reference for path-traced hair in film or look development and as the basis for pre-integrated real-time approximations. Prefer [Disney / Chiang hair and fur BSDF](https://texelatlas.vercel.app/t/disney-hair-bsdf.md) for artist-friendly parameters (melanin, roughness, tint) built on the same lobes. Prefer [Kajiya-Kay hair shading](https://texelatlas.vercel.app/t/kajiya-kay-hair-shading.md) where shader cost or hair cards dominate. Use [Strand-based real-time hair (TressFX style)](https://texelatlas.vercel.app/t/strand-based-real-time-hair.md) to supply the strand geometry and tangents. ## Cost offline — Per-sample evaluation is moderate, but the many-fibre geometry and multiple scattering between strands make it an offline or approximated real-time model. Measured GPU Weight: 18.79× baseline (moderate) — 0.6182 ms median / 0.6622 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.06× baseline (moderate) — 0.2712 ms median (2.28× faster on L4). Ampere A100 scaling: 12.24× baseline (moderate) — 0.3524 ms median (1.75× faster on A100). ## Failure modes - Single-fibre scattering misses inter-fibre multiple scattering, so light hair looks too dark without a dual-scattering or path-traced fix - Azimuthal term evaluated by root solving can have numerical problems near grazing incidence - Unnormalised lobes break energy conservation when roughness changes - Incorrect tangent orientation along the curve flips the highlight order of R and TRT - Noisy highlights at low sample counts since the lobes are very narrow ## Engine support - blender: builtin — `Shader node: Principled Hair BSDF (Chiang model)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/hair_principled.html, checked 2026-12-01) — Chiang model extends Marschner; no separate pure-Marschner option. - unity: builtin — `HDRP Hair Shader Graph > Material Type = Physically Based` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/snippets/shader-properties/surface-options/material-type-hair.md, checked 2026-12-01) — HDRP Hair shader. - unreal: builtin — `Material > Shading Model = Hair (dual-highlight strand scattering used with Groom Hair)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/shading-models-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: curves, material-params - Outputs: radiance - Platforms: cpu, cuda, blender, houdini, unreal, desktop-gpu ## Presets ### Marschner Hair Scattering — single Kajiya-Kay highlight (left) vs physical R + TT + TRT lobes & glints (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MELANIN": 0.48, "P_CUTICLE_SHIFT": 0.11, "P_ROUGHNESS": 0.18, "P_SPLIT": 0.46 } ``` ```glsl const float P_MELANIN = 0.48; // P Hair Melanin [0.05, 1.0, 0.02] const float P_CUTICLE_SHIFT = 0.11; // P Cuticle Tilt [0.02, 0.22, 0.01] const float P_ROUGHNESS = 0.18; // P Longitudinal Beta [0.06, 0.42, 0.01] const float P_SPLIT = 0.46; // P Kajiya / Marschner [0.0, 1.0, 0.02] float gauss(float x, float beta) { float b = max(beta, 0.02); return exp(-0.5 * (x * x) / (b * b)) / (2.5066 * b); } // Flowing sculptural lock of curved hair fibers (sweeping ribbon-cylinder SDF) float mapHairLock(vec3 p) { vec3 q = p; q.x -= 0.18 * sin(q.y * 2.6 + 0.4); q.z -= 0.12 * cos(q.y * 2.2); // Elliptical ribbon bundle tapering slightly at ends float width = 0.56 - 0.16 * q.y * q.y; float d = length(vec2(q.x / max(width, 0.18), q.z / 0.28)) - 1.0; d *= 0.24; // Fine micro-strand grooves running vertically along the tangent float strandPhase = atan(q.z, q.x) * 34.0 + q.x * 28.0; d += 0.008 * sin(strandPhase); return max(d, abs(q.y) - 0.85) * 0.82; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapHairLock(p + e.xyy) - mapHairLock(p - e.xyy), mapHairLock(p + e.yxy) - mapHairLock(p - e.yxy), mapHairLock(p + e.yyx) - mapHairLock(p - e.yyx) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isMarschner = screenX >= split; float melanin = clamp(P_MELANIN, 0.04, 1.0); float alphaShift = clamp(P_CUTICLE_SHIFT, 0.01, 0.25); float betaR = clamp(P_ROUGHNESS, 0.05, 0.45); vec3 ro = vec3(0.0, 0.0, 2.25); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.022, 0.024, 0.038), vec3(0.062, 0.072, 0.105), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapHairLock(ro + rd * t); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Hair strand tangent follows the S-curve derivative vec3 tang = normalize(vec3(0.18 * 2.6 * cos(p.y * 2.6 + 0.4), 1.0, -0.12 * 2.2 * sin(p.y * 2.2))); // Project tangent orthogonal to macro surface normal for fiber shading tang = normalize(tang - n * dot(tang, n)); // Animated key light + warm rim backlight to reveal TT transmission! vec3 lKey = normalize(vec3(0.55 * cos(iTime * 0.55), 0.72, 0.55)); vec3 lRim = normalize(vec3(-0.62, 0.35, -0.70)); vec3 v = -rd; // Strand-by-strand subtle melanin & micro-shift jitter float strandId = sin((p.x - 0.18 * sin(p.y * 2.6 + 0.4)) * 95.0) * 0.5 + 0.5; float strandTone = 0.82 + 0.36 * strandId; // Physical hair absorption spectrum sigma_a from eumelanin/pheomelanin vec3 sigmaA = mix(vec3(0.18, 0.48, 0.92), vec3(1.15, 2.15, 3.65), melanin); vec3 hairCol = exp(-sigmaA * 0.95) * strandTone; // Longitudinal angles theta_i, theta_r relative to normal plane float sinTi = clamp(dot(lKey, tang), -0.99, 0.99); float sinTr = clamp(dot(v, tang), -0.99, 0.99); float thetaH = 0.5 * (asin(sinTi) + asin(sinTr)); float thetaD = 0.5 * (asin(sinTr) - asin(sinTi)); // Azimuthal projections perpendicular to hair tangent vec3 lPerp = normalize(lKey - tang * sinTi + vec3(1e-5)); vec3 vPerp = normalize(v - tang * sinTr + vec3(1e-5)); float cosPhi = clamp(dot(lPerp, vPerp), -1.0, 1.0); float phi = acos(cosPhi); if (!isMarschner) { // Left: Classic Kajiya-Kay single unshifted strand specular band + sin(T, L) diffuse float diff = sqrt(max(1.0 - sinTi * sinTi, 0.0)); vec3 hVec = normalize(lKey + v); float dotTH = dot(tang, hVec); float sinTH = sqrt(max(1.0 - dotTH * dotTH, 0.0)); float spec = pow(sinTH, 28.0) * 0.75; col = hairCol * (0.20 + 0.85 * diff) + vec3(0.95, 0.92, 0.88) * spec; } else { // Right: Full Marschner R (white primary shifted -alpha), TRT (colored secondary shifted +3*alpha + glints), TT (transmitted rim) float mR = gauss(thetaH + alphaShift, betaR); float mTRT = gauss(thetaH - 1.5 * alphaShift, betaR * 1.9); // Azimuthal terms N_R (smooth cosine) and N_TRT (caustic glints near phi ~ 35 deg) float nR = 0.25 + 0.75 * cos(phi * 0.5); float glint = exp(-pow((phi - 0.62) / 0.16, 2.0)) * (0.45 + 0.55 * strandId); float nTRT = 0.45 + 1.35 * glint; // Fresnel & internal absorption through hair cross section (twice for TRT) float fres = 0.046 + 0.954 * pow(1.0 - max(cos(thetaD), 0.0), 5.0); vec3 attenTRT = exp(-sigmaA * 1.55) * (1.0 - fres); // Backlight TT lobe (forward-scattering translucent halo at grazing rim!) float sinTiRim = clamp(dot(lRim, tang), -0.99, 0.99); float thetaHRim = 0.5 * (asin(sinTiRim) + asin(sinTr)); float mTT = gauss(thetaHRim - 0.5 * alphaShift, betaR * 0.75); vec3 lRimPerp = normalize(lRim - tang * sinTiRim + vec3(1e-5)); float backAlign = clamp(-dot(lRimPerp, vPerp), 0.0, 1.0); float nTT = pow(backAlign, 3.5); vec3 attenTT = exp(-sigmaA * 0.65); float wrapDiff = max(dot(n, lKey) * 0.5 + 0.5, 0.0); vec3 lobeR = vec3(0.96, 0.97, 1.0) * mR * nR * fres * 0.52; vec3 lobeTRT = attenTRT * mTRT * nTRT * 0.95; vec3 lobeTT = attenTT * mTT * nTT * 1.35 * (0.35 + 0.65 * pow(1.0 - max(dot(n, v), 0.0), 2.0)); col = hairCol * (0.16 + 0.52 * wrapDiff) + lobeR + lobeTRT + lobeTT; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Kajiya-Kay hair shading](https://texelatlas.vercel.app/t/kajiya-kay-hair-shading.md) - extended by [Disney / Chiang hair and fur BSDF](https://texelatlas.vercel.app/t/disney-hair-bsdf.md) ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): The fibre BSDF is sampled at each strand hit while the path tracer handles inter-strand multiple scattering. ## Sources 1. [primary] Stephen R. Marschner, Henrik Wann Jensen, Mike Cammarano, Steve Worley, Pat Hanrahan (2003) Light scattering from human hair fibers. ACM Transactions on Graphics. https://doi.org/10.1145/882262.882345 (verified via crossref on 2026-11-29) 2. [secondary] Matt Pharr, Wenzel Jakob, Greg Humphreys Scattering from Hair (pbrt-v4). pbr-book.org. https://pbr-book.org/4ed/Reflection_Models/Scattering_from_Hair (verified via http on 2026-11-29) ## Cite this entry Texel. "Marschner hair scattering model." https://texelatlas.vercel.app/t/marschner-hair-scattering/ (accessed 2026-12-01). --- id: "masked-software-occlusion-culling" title: "Masked software occlusion culling" aliases: [MOC, masked occlusion culling] domain: "performance" stage: "performance" realtime: "realtime" platforms: [cpu, desktop-gpu] year_introduced: 2016 inputs: [mesh, depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "GameTechDev, 2016" url: "https://texelatlas.vercel.app/t/masked-software-occlusion-culling/" sources_verified_at: "2026-11-29" --- # Masked software occlusion culling (GameTechDev, 2016) > A CPU, SIMD-optimized rasterizer renders coarse occluders into a tiny hierarchical depth buffer built from binary coverage masks, then tests object bounds against it before they are submitted. ## Reach for it when - too many draw calls for hidden objects - cpu side culling before submitting to the gpu - occlusion culling without gpu readback latency - buildings hide most of the scene but still render - need occlusion culling on old graphics api ## How it works Instead of a full-precision depth buffer, each screen tile keeps two depth layers and a bit mask of which pixels belong to the nearer layer. Rasterizing an occluder triangle computes coverage with SIMD instructions across several scanlines at once and merges it into the mask by comparing against the layers' depth, updating a conservative min/max. Occluders are low-poly proxies of walls, terrain or large props, drawn front to back on worker threads at low resolution (e.g. 640x400). Objects then get an occludee test: their screen-space bounding box and nearest depth are checked against the buffer, and only objects not fully hidden are sent to the GPU. Because everything lives on the CPU, results are available before draw submission, with no GPU readback latency. ## When to use it Choose it on CPU-driven engines where draw submission or vertex work is costly and you can supply simple occluder proxies, especially when a GPU depth pyramid is not usable (older APIs, no compute). Prefer [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md) in a [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) pipeline where the GPU culls its own instances against the previous frame. Prefer [Portal and PVS visibility culling](https://texelatlas.vercel.app/t/portal-pvs-culling.md) for enclosed indoor levels with authored cells, and [GPU hardware occlusion queries](https://texelatlas.vercel.app/t/hardware-occlusion-queries.md) only when latency is acceptable. ## Cost medium — Spends a few CPU-core milliseconds per frame on SIMD rasterization; saves GPU and driver time. Qualitative. Measured GPU Weight: 42.36× baseline (heavy) — 1.3132 ms median / 1.4222 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 43.28× baseline (heavy) — 0.6882 ms median (1.91× faster on L4). Ampere A100 scaling: 25.85× baseline (heavy) — 0.7446 ms median (1.76× faster on A100). ## Failure modes - Over-aggressive occluder proxies larger than the real mesh cull visible objects, which pop in - Low-resolution conservative buffer misses thin gaps, so occluded objects survive when it should have culled them - Needs AVX2/SSE4.1 or equivalent SIMD; scalar fallback is far slower - Rasterizing dynamic occluders every frame adds CPU latency in busy scenes - The upstream repository is archived, so you maintain your own fork ## Dataflow - Inputs: mesh, depth - Outputs: visibility-mask - Platforms: cpu, desktop-gpu ## Presets ### Masked Software Occlusion Culling — 8x4 tile 2-layer HiZ & culled AABBs (left) vs lit scene (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TILE_RES": 16, "P_OCCLUDER_W": 0.65, "P_CAM_SWEEP": 0.8, "P_SPLIT": 0.5 } ``` ```glsl const float P_TILE_RES = 16.0; // P HiZ Tile Grid [8.0, 28.0, 2.0] const float P_OCCLUDER_W = 0.65; // P Occluder Width [0.35, 1.0, 0.05] const float P_CAM_SWEEP = 0.80; // P Camera Pan [0.0, 2.0, 0.05] const float P_SPLIT = 0.50; // P HiZ Mask / Scene [0.0, 1.0, 0.02] 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); } // Foreground large wall occluders (matId=2) + background target occludees (matId=3) vec2 mapScene(vec3 p, float occW, bool includeOccludees) { vec2 res = vec2(p.y + 0.72, 1.0); // ground plane // Two large foreground occluder walls rasterized into the masked HiZ buffer float dOcc1 = sdBox(p - vec3(-0.55, -0.10, 0.35), vec3(occW * 0.55, 0.62, 0.14)); if (dOcc1 < res.x) res = vec2(dOcc1, 2.0); float dOcc2 = sdBox(p - vec3(0.62, -0.18, 0.15), vec3(occW * 0.48, 0.54, 0.14)); if (dOcc2 < res.x) res = vec2(dOcc2, 2.0); if (includeOccludees) { // 5 background objects sitting behind or peeking past the occluders for (int i = 0; i < 5; i++) { float fi = float(i); vec3 c = vec3((fi - 2.0) * 0.56, -0.24 + 0.12 * mod(fi, 2.0), -0.95 - 0.25 * mod(fi, 3.0)); float dObj = sdBox(p - c, vec3(0.20, 0.46, 0.20)) - 0.02; if (dObj < res.x) res = vec2(dObj, 3.0 + fi); } } return res; } vec3 calcNormal(vec3 p, float occW) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapScene(p + e.xyy, occW, true).x - mapScene(p - e.xyy, occW, true).x, mapScene(p + e.yxy, occW, true).x - mapScene(p - e.yxy, occW, true).x, mapScene(p + e.yyx, occW, true).x - mapScene(p - e.yyx, occW, true).x )); } // Trace occluder-only depth for the software HiZ tile buffer float traceOccluderDepth(vec3 ro, vec3 rd, float occW) { float t = 0.0; for (int i = 0; i < 36; i++) { vec2 h = mapScene(ro + rd * t, occW, false); if (h.x < 0.004) return t; t += h.x; if (t > 8.0) break; } return 8.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isLit = screenX >= split; float tileRes = clamp(floor(P_TILE_RES + 0.5), 8.0, 32.0); float occW = clamp(P_OCCLUDER_W, 0.30, 1.05); float pan = sin(iTime * max(P_CAM_SWEEP, 0.0) * 0.7) * 0.58; vec3 ro = vec3(pan, 0.32, 2.38); vec3 ta = vec3(0.0, -0.08, -0.60); vec3 fwd = normalize(ta - ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.48 + right * uv.x + up * uv.y); // Full scene trace float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { vec2 h = mapScene(ro + rd * t, occW, true); if (h.x < 0.0025) { hit = true; matId = h.y; break; } t += h.x; if (t > 8.5) break; } vec3 bg = mix(vec3(0.03, 0.045, 0.075), vec3(0.08, 0.11, 0.17), smoothstep(-0.45, 0.55, uv.y)); vec3 col = bg; if (isLit) { // Right: final rendered scene (only visible non-culled geometry drawn) if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, occW); vec3 lDir = normalize(vec3(0.55, 0.80, 0.45)); float diff = max(dot(n, lDir), 0.0); vec3 alb = vec3(0.24, 0.28, 0.35); if (matId > 1.5 && matId < 2.5) alb = vec3(0.46, 0.52, 0.62); if (matId > 2.5) alb = vec3(0.18, 0.82, 0.62); col = alb * (0.26 + 0.84 * diff); } } else { // Left: Masked 8x4 tile 2-layer HiZ buffer visualization + AABB cull status overlay // Quantize screen UV to 8x4 tile grid (aspect 2:1 tiles) vec2 tileScale = vec2(tileRes * 0.5, tileRes); vec2 tileId = floor(uv * tileScale); vec2 tileF = fract(uv * tileScale); vec2 tileCenterUV = (tileId + 0.5) / tileScale; vec3 rdTile = normalize(fwd * 1.48 + right * tileCenterUV.x + up * tileCenterUV.y); // Evaluate tile's 2-layer conservative depth zMax0 (occluder depth) vs pixel exact depth float zTileOcc = traceOccluderDepth(ro, rdTile, occW); float zPixOcc = traceOccluderDepth(ro, rd, occW); float invZTile = clamp(1.4 / max(zTileOcc, 0.8), 0.0, 1.0); // Visualize 2-layer coverage mask: bright cyan where foreground occluder sets bitmask = 1 vec3 hizCol = mix(vec3(0.04, 0.07, 0.12), vec3(0.16, 0.52, 0.78), invZTile); if (zPixOcc < 4.2) { hizCol = mix(hizCol, vec3(0.26, 0.84, 0.96), 0.45); } // X-ray test all 5 background target AABBs against the tile HiZ depth: // RED = fully occluded by HiZ (culled before vertex shading!); GREEN = passes HiZ test (drawn) for (int i = 0; i < 5; i++) { float fi = float(i); vec3 c = vec3((fi - 2.0) * 0.56, -0.24 + 0.12 * mod(fi, 2.0), -0.95 - 0.25 * mod(fi, 3.0)); vec3 rel = c - ro; float zObj = dot(rel, fwd); if (zObj <= 0.2) continue; vec2 proj = vec2(dot(rel, right), dot(rel, up)) * (1.48 / zObj); vec2 halfExt = vec2(0.22, 0.48) * (1.48 / zObj); vec2 dBox = abs(uv - proj) - halfExt; float boxSdf = length(max(dBox, 0.0)) + min(max(dBox.x, dBox.y), 0.0); if (boxSdf < 0.012) { // Test AABB near-z against occluder HiZ depth at the AABB center & upper corner vec3 rdC = normalize(fwd * 1.48 + right * proj.x + up * proj.y); vec3 rdTop = normalize(fwd * 1.48 + right * proj.x + up * (proj.y + halfExt.y * 0.75)); float zHiZ = max(traceOccluderDepth(ro, rdC, occW), traceOccluderDepth(ro, rdTop, occW)); bool culled = (zObj - 0.22) > zHiZ; vec3 aabbCol = culled ? vec3(0.98, 0.24, 0.22) : vec3(0.18, 0.96, 0.52); float border = smoothstep(0.012, 0.002, abs(boxSdf)); float fill = step(boxSdf, 0.0) * (culled ? 0.22 : 0.14); hizCol = mix(hizCol, aabbCol, max(border * 0.92, fill)); } } // Subtle 8x4 tile grid border float grid = smoothstep(0.06, 0.015, min(min(tileF.x, 1.0 - tileF.x), min(tileF.y, 1.0 - tileF.y))); col = mix(hizCol, vec3(0.02, 0.04, 0.07), grid * 0.55); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md) ## Combines with - [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md): Simplified low-poly occluder meshes produced offline are what the rasterizer consumes. ## Sources 1. [primary] GameTechDev (2016) GameTechDev/MaskedOcclusionCulling. https://github.com/GameTechDev/MaskedOcclusionCulling License: Apache-2.0. (verified via github on 2026-11-29) 2. [secondary] Magnus Andersson, Jon Hasselgren, Tomas Akenine-Möller (2015) Masked depth culling for graphics hardware. ACM Transactions on Graphics. https://doi.org/10.1145/2816795.2818138 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Masked software occlusion culling." https://texelatlas.vercel.app/t/masked-software-occlusion-culling/ (accessed 2026-12-01). --- id: "mast3r" title: "MASt3R" aliases: [Matching And Stereo 3D Reconstruction] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [photos] outputs: [point-cloud, camera-poses, depth] style: "photoreal" dynamic: "static" cost: "medium" authority: "Leroy et al., 2024" url: "https://texelatlas.vercel.app/t/mast3r/" sources_verified_at: "2026-11-29" --- # MASt3R (Leroy et al., 2024) > Extends DUSt3R with a dense local-feature head and a fast reciprocal matching scheme, giving pixel-accurate correspondences that make image matching and SfM-style reconstruction more precise. ## Reach for it when - need accurate matches between images for 3d reconstruction - feature matching fails on wide baseline photos - get metric scale 3d from image pairs - dense correspondences without handcrafted keypoints ## How it works MASt3R keeps DUSt3R's pointmap regression but adds a second output head producing dense local descriptors per pixel, trained with an InfoNCE matching loss so that corresponding pixels have close features. Matches are found by mutual nearest neighbours on these descriptors, accelerated with a coarse-to-fine scheme that first matches at low resolution and then refines in high-resolution crops. Metric scale is learned in the regression loss, so output pointmaps are in metric units. For many images the matches feed a sparse global alignment that minimises 3D and reprojection error, avoiding DUSt3R's dense and slower global optimisation, and enabling large collections and map-free localisation. ## When to use it Choose it when you need robust correspondences for wide-baseline or low-texture image pairs, or large-scale reconstruction through sparse alignment. Prefer [DUSt3R](https://texelatlas.vercel.app/t/dust3r.md) for the simplest pointmap pipeline, [VGGT (Visual Geometry Grounded Transformer)](https://texelatlas.vercel.app/t/vggt.md) for single-pass multi-view output, and [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md) for classical bundle-adjusted accuracy. ## Cost medium — GPU inference per pair is quick; the matching refinement adds cost proportional to resolution. ## Failure modes - Weights and code under a non-commercial licence - Matching degrades under extreme viewpoint change or heavy occlusion - Reconstruction scale can drift across large scenes without loop closure - Dynamic content produces inconsistent matches ## Dataflow - Inputs: photos - Outputs: point-cloud, camera-poses, depth - Platforms: cuda, python ## Lineage - extends [DUSt3R](https://texelatlas.vercel.app/t/dust3r.md) ## Combination ideas - [Regrow a photographed site](https://texelatlas.vercel.app/ideas/captured-site-revegetation/) ## Sources 1. [primary] Vincent Leroy, Yohann Cabon, Jérôme Revaud (2024) Grounding Image Matching in 3D with MASt3R. arXiv preprint (cs.CV). https://arxiv.org/abs/2406.09756 (verified via arxiv on 2026-11-29) 2. [implementation] naver (2024) naver/mast3r. https://github.com/naver/mast3r License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "MASt3R." https://texelatlas.vercel.app/t/mast3r/ (accessed 2026-12-01). --- id: "matcap-shading" title: "MatCap (lit sphere) shading" aliases: [material capture, lit sphere, litsphere, MatCap] domain: "npr" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, godot] year_introduced: 2001 inputs: [normals, texture] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Foundation" url: "https://texelatlas.vercel.app/t/matcap-shading/" sources_verified_at: "2026-11-29" --- # MatCap (lit sphere) shading (Foundation) > Colour each pixel by looking up the view-space normal in a single image of a lit sphere. Material, lighting and reflections are baked into the image, so shading is one texture fetch with no lights. ## Reach for it when - want shading without any lights in the scene - need a quick clay or sculpt viewport look - artist wants to paint the lighting on a sphere - cheap stylized material for mobile with one texture fetch ## How it works The lit-sphere idea is that a picture of a sphere with the desired material under the desired lighting encodes a shading function of the normal. For a pixel with view-space normal `n`, take `uv = n.xy * 0.5 + 0.5` and fetch the picture; the sphere's centre corresponds to normals facing the camera and its rim to grazing normals. Because the lookup uses view-space normals, the light follows the camera and the object appears to be lit the same way as it rotates, which is exactly what sculpting tools want. Artists can paint any material by painting a sphere, from clay and chrome to toon ramps and painted metal, and get a complete shader. Normal maps and displacement work naturally because only the normal is used. Fixes people apply include correcting UVs near the rim to avoid texel stretching, using a per-vertex view-space normal rotated by the camera roll, and combining the matcap with an albedo texture by multiply or overlay. ## When to use it Choose it for sculpting viewports, stylised previews, prototypes and non-photoreal looks where artists paint the lighting, and for cheap shading on mobile. Prefer [toon-shading](toon-shading) or [gooch-shading](gooch-shading) when the look must respond to scene lights and cast shadows. Prefer [split-sum-ibl](split-sum-ibl) or full [cook-torrance-brdf](cook-torrance-brdf) lighting for physically consistent materials. Prefer [environment-mapping-cubemaps](environment-mapping-cubemaps) when reflections should depend on the view direction and the world, not just the camera space. ## Cost cheap — A normal transform and one texture fetch per pixel; no lights, no shadows. Measured GPU Weight: 1.3× baseline (feather) — 0.0427 ms median / 0.043 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.12× baseline (feather) — 0.0178 ms median (2.4× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.48× faster on A100). ## Failure modes - Lighting is locked to the camera; rotating the view changes nothing about the highlight position, which breaks the illusion in scenes with several objects - No shadows, no occlusion and no inter-object reflection, so objects look pasted together - Texel stretching and pinching near the sphere's rim where the normal is almost perpendicular to the view - View-space normals under strong perspective give different shading for the same surface orientation across the frame - Hard to match two matcaps for continuity between meshes, since the sphere image is the entire lighting model - Backfacing or flipped normals fetch from the wrong side of the sphere and shade as dark blobs ## Engine support - blender: builtin — `Viewport Shading (Workbench) > Lighting = MatCap` (evidence: https://docs.blender.org/manual/en/5.2/render/workbench/lighting.html, checked 2026-12-01) - threejs: builtin — `new THREE.MeshMatcapMaterial({ matcap })` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshMatcapMaterial.js, checked 2026-12-01) ## Dataflow - Inputs: normals, texture - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender, unity, godot ## Presets ### Procedural matcap on a wobbling blob (glsl-fragment; rendered 2026-11-29) ```json { "key_light": [ -0.4, 0.5, 0.8 ], "rim_strength": 0.4 } ``` ```glsl // MatCap: shading is a pure function of the view-space normal; here the "lit sphere image" is procedural. vec3 matcap(vec2 n) { float d = length(n); vec3 base = mix(vec3(0.18, 0.2, 0.3), vec3(0.85, 0.62, 0.5), 0.5 + 0.5 * n.y); base *= 0.35 + 0.65 * clamp(dot(vec3(n, sqrt(max(1.0 - d * d, 0.0))), normalize(vec3(-0.4, 0.5, 0.8))), 0.0, 1.0); float spec = exp(-dot(n - vec2(-0.3, 0.4), n - vec2(-0.3, 0.4)) * 25.0); float rim = pow(d, 4.0) * 0.4; return base + vec3(spec) * 0.9 + vec3(0.4, 0.55, 0.9) * rim; } float h(vec2 p) { return sin(p.x * 6.0 + iTime) * sin(p.y * 5.0 - iTime * 0.7) * 0.06 + sin(p.x * 17.0) * sin(p.y * 13.0) * 0.012; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 p = (fragCoord - 0.5 * iResolution.xy) / (0.42 * iResolution.y); float r2 = dot(p, p); vec3 col = vec3(0.1); if (r2 < 1.0) { vec3 n = vec3(p, sqrt(1.0 - r2)); vec2 e = vec2(0.002, 0.0); vec3 b = vec3(-(h(p + e.xy) - h(p - e.xy)) / (2.0 * e.x), -(h(p + e.yx) - h(p - e.yx)) / (2.0 * e.x), 0.0); n = normalize(n + b * 1.5); col = matcap(n.xy); } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md): Tangent-space normal maps perturb the view-space normal before the matcap lookup, adding surface detail without lights. - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Outline pass adds contour lines the matcap lacks, giving a complete sculpt-viewport look. - [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md): A banded matcap image is a cheap view-locked toon ramp. ## Sources 1. [primary] Blender Foundation Blender Workbench lighting: MatCap. docs.blender.org. https://docs.blender.org/manual/en/latest/render/workbench/lighting.html (verified via http on 2026-11-29) 2. [implementation] three.js contributors three.js MeshMatcapMaterial example. threejs.org. https://threejs.org/examples/webgl_materials_matcap.html (verified via http on 2026-11-29) ## Cite this entry Texel. "MatCap (lit sphere) shading." https://texelatlas.vercel.app/t/matcap-shading/ (accessed 2026-12-01). --- id: "materialx" title: "MaterialX" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, blender, houdini, unity, unreal, python, cpu] year_introduced: 2017 inputs: [material-params, texture] outputs: [material-params] style: "both" dynamic: "both" cost: "cheap" authority: "Foundation" url: "https://texelatlas.vercel.app/t/materialx/" sources_verified_at: "2026-11-29" --- # MaterialX (Foundation) > An open standard (ASWF) for describing materials, procedural textures and look assignments as node graphs in XML, with code generators for GLSL, MSL, OSL and MDL. The lingua franca between DCCs and renderers. ## Reach for it when - materials break when moving between tools - need one portable shader graph across renderers - usd pipeline needs renderer-neutral look development - want to export material nodes to glsl, osl and mdl ## How it works A MaterialX document is an XML file of typed nodes (images, noise, math, color transforms, shading models) wired into graphs, plus 'looks' that bind materials to geometry and variants. The core library defines standard nodes and the standard_surface and OpenPBR shading nodes. Implementations are reference libraries (C++/Python/JavaScript) that read, validate and transform documents, and shader generators that flatten a graph into GLSL, ESSL, MSL, OSL or MDL source, so one asset can be rendered by USD-based viewers, DCC tools and web viewers. The JavaScript build runs in WebAssembly, powering browser viewers. The standard library also ships a node for OpenPBR Surface. ## When to use it Choose it for portable material graphs shared across tools, renderer-neutral look development and USD pipelines. Prefer plain glTF PBR for simple web delivery, and engine-native node graphs when you never leave one engine. Use it as the carrier format for [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md). ## Cost cheap — Format and code generation, not a runtime technique; generated shaders cost what their nodes cost. Measured GPU Weight: 60.97× baseline (extreme) — 2.006 ms median / 2.0706 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 58.17× baseline (heavy) — 0.9249 ms median (2.17× faster on L4). Ampere A100 scaling: 42.92× baseline (heavy) — 1.2362 ms median (1.62× faster on A100). ## Failure modes - Generated shaders can be large and slow when graphs are deep, with little dead-node elimination - Support for individual nodes differs between renderers, so the same graph renders differently - Round-trip through DCC exporters loses non-standard nodes - Only some node outputs have texture-baking support ## Engine support - blender: builtin — `File > Import/Export > Universal Scene Description (USD) with Hydra MaterialX shader graph translation` (evidence: https://docs.blender.org/manual/en/5.2/files/import_export/usd.html, checked 2026-12-01) - threejs: official — `import { MaterialXLoader } from 'three/addons/loaders/MaterialXLoader.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/loaders/MaterialXLoader.js, checked 2026-12-01) - unreal: official — `Import .mtlx via Interchange (Project Settings > Interchange > MaterialX)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/importing-materialx-files-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params, texture - Outputs: material-params - Platforms: webgl2, webgpu, desktop-gpu, blender, houdini, unity, unreal, python, cpu ## Presets ### MaterialX — live Standard Surface node graph (left) vs evaluated procedural shader ball (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_METALNESS": 0.55, "P_CLEARCOAT": 0.75, "P_VEIN_FREQ": 5.5, "P_SPLIT": 0.46 } ``` ```glsl const float P_METALNESS = 0.55; // P Metalness [0.0, 1.0, 0.05] const float P_CLEARCOAT = 0.75; // P Clearcoat [0.0, 1.0, 0.05] const float P_VEIN_FREQ = 5.50; // P Noise Frequency [2.0, 12.0, 0.5] const float P_SPLIT = 0.46; // P Graph / Shader Split [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * vec3(127.1, 311.7, 74.7)); p += dot(p, p.yzx + 19.19); return fract((p.x + p.y) * p.z); } float noise3(vec3 p) { vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f); float n000 = hash31(i + vec3(0.0, 0.0, 0.0)); float n100 = hash31(i + vec3(1.0, 0.0, 0.0)); float n010 = hash31(i + vec3(0.0, 1.0, 0.0)); float n110 = hash31(i + vec3(1.0, 1.0, 0.0)); float n001 = hash31(i + vec3(0.0, 0.0, 1.0)); float n101 = hash31(i + vec3(1.0, 0.0, 1.0)); float n011 = hash31(i + vec3(0.0, 1.0, 1.0)); float n111 = hash31(i + vec3(1.0, 1.0, 1.0)); return mix( mix(mix(n000, n100, f.x), mix(n010, n110, f.x), f.y), mix(mix(n001, n101, f.x), mix(n011, n111, f.x), f.y), f.z ); } float fbm3(vec3 p) { float v = 0.0; float a = 0.5; for (int i = 0; i < 4; i++) { v += a * noise3(p); p *= 2.05; a *= 0.5; } return v; } float sdRoundBox(vec2 p, vec2 b, float r) { vec2 q = abs(p) - b + r; return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; } float sdBezierWire(vec2 p, vec2 a, vec2 b, out float tOut) { float minD = 1e5; tOut = 0.0; vec2 c1 = vec2(mix(a.x, b.x, 0.55), a.y); vec2 c2 = vec2(mix(a.x, b.x, 0.45), b.y); vec2 prev = a; for (int i = 1; i <= 16; i++) { float t = float(i) / 16.0; float u = 1.0 - t; vec2 cur = u * u * u * a + 3.0 * u * u * t * c1 + 3.0 * u * t * t * c2 + t * t * t * b; vec2 pa = p - prev, ba = cur - prev; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0); float d = length(pa - ba * h); if (d < minD) { minD = d; tOut = (float(i - 1) + h) / 16.0; } prev = cur; } return minD; } float D_GGX(float ndh, float a) { float a2 = a * a; float d = ndh * ndh * (a2 - 1.0) + 1.0; return a2 / max(3.1415926 * d * d, 1e-5); } vec3 evalStudioEnv(vec3 d) { vec3 bg = mix(vec3(0.08, 0.10, 0.14), vec3(0.26, 0.34, 0.48), smoothstep(-0.3, 0.8, d.y)); float softbox = smoothstep(0.32, 0.12, abs(d.x - 0.35)) * smoothstep(0.25, 0.65, d.y); float rim = exp(-abs(d.y - 0.12) * 14.0) * smoothstep(-0.3, 0.5, -d.x); return bg + vec3(2.5, 2.3, 2.0) * softbox + vec3(0.55, 0.92, 1.35) * rim; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showBall = sx >= split; float metal = clamp(P_METALNESS, 0.0, 1.0); float coat = clamp(P_CLEARCOAT, 0.0, 1.0); float vFreq = clamp(P_VEIN_FREQ, 1.5, 14.0); vec3 col = vec3(0.04, 0.05, 0.07); if (!showBall) { // Left: MaterialX DAG node graph schematic with live animated procedural swatch previews vec2 g = uv + vec2(0.36, 0.0); // Subtle schematic grid vec2 gr = abs(fract(g * 14.0) - 0.5); float gridLine = smoothstep(0.04, 0.01, min(0.5 - gr.x, 0.5 - gr.y)); col = vec3(0.045, 0.055, 0.075) + vec3(0.04, 0.06, 0.09) * gridLine; // Node centers in graph space vec2 nNoise = vec2(-0.36, 0.22); vec2 nRamp = vec2(-0.12, 0.28); vec2 nRough = vec2(-0.12, -0.02); vec2 nCoat = vec2(-0.12, -0.28); vec2 nSurf = vec2(0.16, 0.04); // Draw Bezier connections with animated signal pulses vec2 starts[5]; vec2 ends[5]; vec3 wCols[5]; starts[0] = nNoise + vec2(0.09, 0.01); ends[0] = nRamp - vec2(0.09, 0.0); wCols[0] = vec3(0.35, 0.85, 1.0); starts[1] = nNoise + vec2(0.09, -0.02); ends[1] = nRough - vec2(0.09, 0.0); wCols[1] = vec3(0.75, 0.80, 0.90); starts[2] = nRamp + vec2(0.09, 0.0); ends[2] = nSurf - vec2(0.11, -0.09); wCols[2] = vec3(0.95, 0.65, 0.25); starts[3] = nRough + vec2(0.09, 0.0); ends[3] = nSurf - vec2(0.11, 0.0); wCols[3] = vec3(0.55, 0.92, 0.65); starts[4] = nCoat + vec2(0.09, 0.0); ends[4] = nSurf - vec2(0.11, 0.09); wCols[4] = vec3(0.85, 0.55, 1.0); for (int i = 0; i < 5; i++) { float wt = 0.0; float dw = sdBezierWire(g, starts[i], ends[i], wt); float line = smoothstep(0.0085, 0.003, dw); float pulse = exp(-pow(fract(wt - iTime * 0.45 - float(i) * 0.17) - 0.5, 2.0) * 60.0); col = mix(col, wCols[i] * (0.65 + 1.2 * pulse), line); } // Draw 5 MaterialX nodes with live procedural thumbnails inside each box vec2 nPos[5]; vec2 nSz[5]; vec3 hdr[5]; nPos[0] = nNoise; nSz[0] = vec2(0.09, 0.09); hdr[0] = vec3(0.22, 0.56, 0.88); nPos[1] = nRamp; nSz[1] = vec2(0.09, 0.085); hdr[1] = vec3(0.86, 0.48, 0.16); nPos[2] = nRough; nSz[2] = vec2(0.09, 0.085); hdr[2] = vec3(0.22, 0.72, 0.46); nPos[3] = nCoat; nSz[3] = vec2(0.09, 0.08); hdr[3] = vec3(0.68, 0.36, 0.88); nPos[4] = nSurf; nSz[4] = vec2(0.11, 0.16); hdr[4] = vec3(0.92, 0.32, 0.24); for (int i = 0; i < 5; i++) { vec2 lp = g - nPos[i]; float d = sdRoundBox(lp, nSz[i], 0.015); float fill = smoothstep(0.004, -0.004, d); float border = smoothstep(0.006, 0.001, abs(d)); vec3 body = vec3(0.10, 0.12, 0.16); // Header bar if (lp.y > nSz[i].y - 0.032) body = hdr[i] * 0.85; else { vec2 suv = lp / max(nSz[i], vec2(0.01)) * 0.5 + 0.5; float nv = fbm3(vec3(suv * vFreq * 0.65, iTime * 0.15)); float vein = smoothstep(0.32, 0.68, abs(sin(suv.x * vFreq + nv * 4.2))); if (i == 0) body = vec3(nv); else if (i == 1) body = mix(vec3(0.07, 0.16, 0.22), vec3(0.94, 0.68, 0.28), vein); else if (i == 2) body = vec3(mix(0.15, 0.65, 1.0 - vein)) * vec3(0.85, 0.95, 0.90); else if (i == 3) body = vec3(coat * 0.9, coat * 0.6, coat); else { // Standard Surface output preview sphere inside final node float rr = length((lp + vec2(0.0, 0.015)) / 0.075); if (rr < 1.0) { vec3 sn = vec3((lp + vec2(0.0, 0.015)) / 0.075, sqrt(max(1.0 - rr * rr, 0.0))); float nl = max(dot(sn, normalize(vec3(0.5, 0.7, 0.6))), 0.1); vec3 baseC = mix(vec3(0.07, 0.16, 0.22), vec3(0.94, 0.68, 0.28), vein); body = baseC * nl + vec3(0.9) * pow(max(dot(sn, normalize(vec3(0.35, 0.55, 0.8))), 0.0), 28.0) * (0.4 + 0.6 * coat); } } } col = mix(col, body, fill); col = mix(col, hdr[i] * 1.15, border); } } else { // Right: Evaluated MaterialX Standard Surface shader ball with rotating sculpted core vec3 ro = vec3(0.18, 0.18, 2.25); vec3 rd = normalize(vec3(uv - vec2(0.16, 0.0), -1.45)); col = evalStudioEnv(rd) * 0.36; // Intersect shader ball sphere (R=0.58) and recessed studio plinth vec3 sc = vec3(0.18, 0.02, 0.0); vec3 oc = ro - sc; float b = dot(oc, rd); float c = dot(oc, oc) - 0.58 * 0.58; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tPl = (rd.y < -0.01) ? ((-0.58 - ro.y) / rd.y) : 1e5; if (tPl < 0.05 || tPl > 12.0) tPl = 1e5; float tHit = min(tSph, tPl); if (tHit < 1e4) { vec3 p = ro + rd * tHit; vec3 v = -rd; if (tSph < tPl) { vec3 n = normalize(p - sc); float a = iTime * 0.32; mat3 ry = mat3(cos(a), 0.0, sin(a), 0.0, 1.0, 0.0, -sin(a), 0.0, cos(a)); vec3 objP = ry * (p - sc); // Evaluate the exact MaterialX procedural graph: fbm3 -> marble/copper vein -> standard_surface inputs float nVal = fbm3(objP * vFreq * 0.85); float vein = smoothstep(0.28, 0.72, abs(sin(objP.x * vFreq + objP.y * 2.4 + nVal * 4.5))); vec3 baseCol = mix(vec3(0.06, 0.16, 0.24), vec3(0.92, 0.64, 0.26), vein); float rough = mix(0.42, 0.14, vein); float met = mix(metal * 0.25, min(metal * 1.15, 1.0), vein); // Micro-bump from graph derivative vec3 eps = vec3(0.01, 0.0, 0.0); float nx = fbm3((objP + eps.xyy) * vFreq * 0.85) - nVal; float ny = fbm3((objP + eps.yxy) * vFreq * 0.85) - nVal; vec3 bumpN = normalize(n - (transpose(ry) * vec3(nx, ny, 0.0)) * 2.2); vec3 L = normalize(vec3(0.55, 0.76, 0.58)); vec3 H = normalize(L + v); float ndl = max(dot(bumpN, L), 0.0); float ndv = max(dot(bumpN, v), 0.005); float ndh = max(dot(bumpN, H), 0.0); float vdh = max(dot(v, H), 0.0); vec3 f0 = mix(vec3(0.04), baseCol, met); vec3 F = f0 + (1.0 - f0) * pow(1.0 - vdh, 5.0); float D = D_GGX(ndh, max(rough * rough, 0.04)); vec3 spec = D * F / max(4.0 * ndv * max(ndl, 0.05), 0.08) * ndl * 1.4; vec3 diff = (1.0 - F) * (1.0 - met) * baseCol * (ndl * 0.95 + 0.28); vec3 envR = evalStudioEnv(reflect(-v, bumpN)); vec3 ibl = envR * (f0 + (1.0 - f0) * pow(1.0 - ndv, 5.0)) * mix(1.0, 0.28, rough); col = diff + spec + ibl * 0.82; // MaterialX clearcoat layer using geometric normal n if (coat > 0.01) { float ndhC = max(dot(n, H), 0.0); float ndvC = max(dot(n, v), 0.005); float Fc = 0.04 + 0.96 * pow(1.0 - ndvC, 5.0); float Dc = D_GGX(ndhC, 0.05); vec3 coatSpec = vec3(Dc * 0.04 / max(4.0 * ndvC, 0.1)) * max(dot(n, L), 0.0); vec3 coatEnv = evalStudioEnv(reflect(-v, n)) * Fc; col = col * (1.0 - coat * Fc * 0.55) + coat * (coatSpec * 0.55 + coatEnv * 0.85); } } else { vec2 chk = floor((p.xz - vec2(0.18, 0.0)) * 3.5); vec3 fl = mix(vec3(0.10, 0.12, 0.15), vec3(0.18, 0.20, 0.24), mod(chk.x + chk.y, 2.0)); float ao = smoothstep(0.25, 1.15, length(p.xz - sc.xz)); col = mix(fl * (0.35 + 0.65 * ao), evalStudioEnv(rd) * 0.36, 1.0 - exp(-tPl * 0.22)); } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) ## Combination ideas - [Words to portable node materials](https://texelatlas.vercel.app/ideas/vlm-edited-portable-materials/) ## Sources 1. [primary] Academy Software Foundation MaterialX. materialx.org. https://materialx.org/ (verified via http on 2026-11-29) 2. [implementation] AcademySoftwareFoundation (2017) AcademySoftwareFoundation/MaterialX. https://github.com/AcademySoftwareFoundation/MaterialX License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "MaterialX." https://texelatlas.vercel.app/t/materialx/ (accessed 2026-12-01). --- id: "mesh-boolean-manifold" title: "Manifold Mesh Booleans" aliases: [manifold-3d] domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, python] year_introduced: 2022 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "interactive" authority: "elalish, 2019" url: "https://texelatlas.vercel.app/t/mesh-boolean-manifold/" sources_verified_at: "2026-11-29" --- # Manifold Mesh Booleans (elalish, 2019) > A mesh boolean library that guarantees manifold output and runs in parallel, using symbolic perturbation instead of tolerance fudging. Union, difference and intersection of triangle meshes in the browser or natively. ## Reach for it when - boolean cut leaves holes or non-manifold results - need robust union and difference of meshes in the browser - csg for cad or 3d-print prep - mesh intersections fail from tolerance issues - fast parallel mesh subtraction ## How it works Inputs must be manifold triangle meshes. The library finds all edge-triangle intersections using a spatial structure (a BVH or Morton-sorted hash), then decides inside/outside using a winding-number-like shadow test with symbolic perturbation: vertices are treated as if infinitesimally nudged so that degenerate coincidences, such as coplanar faces or vertices on faces, resolve consistently rather than via epsilons. New vertices are placed at the exact intersection of an edge with a face. Kept triangles from both meshes are stitched along the new intersection edges into a manifold result. The code runs in parallel and ships as a WebAssembly build for JavaScript. ## When to use it Choose it for CSG-style modelling on meshes (CAD in the browser, procedural parts, 3D-print prep) where robustness and manifold output matter and inputs are already manifold. Prefer [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md) when blends or smooth results are wanted, and a mesh clean-up pass or [Screened Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction.md) when inputs are triangle soups with self-intersections. ## Cost interactive — Roughly linear to n log n; sub-second for hundreds of thousands of triangles on a modern CPU in native builds, slower in WASM. Measured GPU Weight: 16.18× baseline (moderate) — 0.5081 ms median / 0.6058 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 14.42× baseline (moderate) — 0.2279 ms median (2.23× faster on L4). Ampere A100 scaling: 10.93× baseline (moderate) — 0.3147 ms median (1.61× faster on A100). ## Failure modes - Requires manifold, closed inputs; open or self-intersecting meshes are rejected or give undefined results - Exact coincident faces resolve via perturbation, which can leave razor-thin slivers - Single-precision input can limit accuracy of tiny features - Attributes such as UVs need extra bookkeeping to survive the cut ## Engine support - babylonjs: builtin — `BABYLON.CSG2 (Manifold-based; await InitializeCSG2Async())` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/csg2.ts, checked 2026-12-01) - blender: builtin — `Add Modifier > Generate > Boolean > Solver = Manifold` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/generate/booleans.html, checked 2026-12-01) - godot: builtin — `Add CSGShape3D nodes (CSGCombiner3D, CSGBox3D...) and set operation` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/csg/csg_shape.cpp, checked 2026-12-01) — CSG meshes are combined with the bundled Manifold library. - unreal: builtin — `Modeling Mode > Model > Boolean Tool (Union, Difference, Intersection) and GeometryScript_MeshBooleans` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/boolean-tool-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, webgl2, webgpu, python ## Presets ### Manifold Mesh Booleans — interactive CSG Union / Difference / Intersection with highlighted 1-manifold seam curves (glsl-fragment; rendered 2026-11-30) ```json { "P_BOOL_OP": 1, "P_SEAM_GLOW": 1.15, "P_ORBIT_AMP": 0.34, "P_ROT_SPEED": 1 } ``` ```glsl const float P_BOOL_OP = 1.0; // P Bool Op (0:U 1:Diff 2:Int) [0.0, 2.0, 1.0] const float P_SEAM_GLOW = 1.15; // P Seam Curve Glow [0.0, 2.2, 0.05] const float P_ORBIT_AMP = 0.34; // P Cutter Offset [0.05, 0.62, 0.02] const float P_ROT_SPEED = 1.0; // P Orbit Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } // Evaluate both manifold operand SDFs A (chamfered steel cube) & B (cutter sphere + crossing cylinder) void evalOperands(vec3 p, float spin, float orbitAmp, out float dA, out float dB) { vec3 q = p; q.xz = rot2(spin * 0.38) * q.xz; q.yz = rot2(0.35) * q.yz; dA = sdBox(q, vec3(0.56)) - 0.04; // Dynamic manifold operand B orbiting through A vec3 bOff = vec3(orbitAmp * cos(spin * 0.75), orbitAmp * 0.65 * sin(spin * 0.92), orbitAmp * sin(spin * 0.75)); float dSph = length(q - bOff) - 0.46; vec3 tq = q; tq.xy = rot2(spin * 0.5) * tq.xy; float dTor = sdTorus(tq, vec2(0.52, 0.16)); dB = min(dSph, dTor); } // Exact CSG boolean combination returning vec3(distance, matID, seamProximity) vec3 mapCSG(vec3 p, float opMode, float spin, float orbitAmp) { float dA, dB; evalOperands(p, spin, orbitAmp, dA, dB); float d; float matId; float seam; if (opMode < 0.5) { // Union: A U B d = min(dA, dB); matId = (dA < dB) ? 1.0 : 2.0; seam = abs(dA - dB); } else if (opMode < 1.5) { // Difference: A B d = max(dA, -dB); matId = (dA > -dB) ? 1.0 : 3.0; // interior carved face gets distinct warm-copper ID seam = abs(dA + dB); } else { // Intersection: A n B d = max(dA, dB); matId = (dA > dB) ? 1.0 : 2.0; seam = abs(dA - dB); } return vec3(d, matId, seam); } vec3 calcNormal(vec3 p, float opMode, float spin, float orbitAmp) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapCSG(p + e.xyy, opMode, spin, orbitAmp).x - mapCSG(p - e.xyy, opMode, spin, orbitAmp).x, mapCSG(p + e.yxy, opMode, spin, orbitAmp).x - mapCSG(p - e.yxy, opMode, spin, orbitAmp).x, mapCSG(p + e.yyx, opMode, spin, orbitAmp).x - mapCSG(p - e.yyx, opMode, spin, orbitAmp).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float opMode = floor(clamp(P_BOOL_OP + 0.5, 0.0, 2.0)); float seamGlow = clamp(P_SEAM_GLOW, 0.0, 2.5); float orbitAmp = clamp(P_ORBIT_AMP, 0.04, 0.65); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.14, 2.52); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.03, 0.04, 0.068), vec3(0.09, 0.115, 0.168), smoothstep(-0.55, 0.55, uv.y)); vec2 bgG = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.045) * smoothstep(0.03, 0.0, min(bgG.x, bgG.y)); float t = 0.0; vec3 res = vec3(0.0); bool hit = false; for (int i = 0; i < 72; i++) { res = mapCSG(ro + rd * t, opMode, spin, orbitAmp); if (res.x < 0.0018) { hit = true; break; } t += max(res.x * 0.85, 0.002); if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, opMode, spin, orbitAmp); float matId = res.y; float seamD = res.z; // Distinct crisp materials for operand A (brushed slate-steel), operand B (cobalt), and carved inner B (warm brass) vec3 alb; if (matId < 1.5) alb = vec3(0.68, 0.72, 0.78); else if (matId < 2.5) alb = vec3(0.18, 0.56, 0.88); else alb = vec3(0.92, 0.52, 0.22); // Subtle CAD grid on operand surfaces vec3 objP = p; objP.xz = rot2(spin * 0.38) * objP.xz; objP.yz = rot2(0.35) * objP.yz; vec3 gf = abs(fract(objP * 7.5 - 0.5) - 0.5); float grid = smoothstep(0.035, 0.008, min(gf.x, min(gf.y, gf.z))); alb *= (1.0 - 0.12 * grid); vec3 l1 = normalize(vec3(0.62, 0.86, 0.55)); vec3 l2 = normalize(vec3(-0.75, -0.25, 0.52)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 46.0) * 0.58; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.30; col = alb * (0.24 + 0.84 * diff1 + 0.25 * diff2) + vec3(spec) + vec3(0.45, 0.75, 1.0) * rim; // Crisp glowing exact 1-manifold CSG intersection seam curve! float seamLine = smoothstep(0.022, 0.003, seamD); col = mix(col, vec3(0.28, 1.0, 0.86) * (1.25 + 0.5 * seamGlow), seamLine * min(seamGlow, 1.0)); col += vec3(0.18, 0.92, 0.84) * exp(-seamD * 45.0) * 0.35 * seamGlow; } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Manifold Dual Contouring](https://texelatlas.vercel.app/t/manifold-dual-contouring.md): MDC output is guaranteed manifold, so it can feed booleans. - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): three-mesh-bvh can pick and raycast the resulting meshes in the browser. ## Sources 1. [primary] elalish (2019) elalish/manifold. https://github.com/elalish/manifold License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Manifold Mesh Booleans." https://texelatlas.vercel.app/t/mesh-boolean-manifold/ (accessed 2026-12-01). --- id: "mesh-neural-cellular-automata" title: "Mesh Neural Cellular Automata (MeshNCA)" aliases: [MeshNCA] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python, webgl2] year_introduced: 2024 inputs: [mesh, ldr-image, text-prompt] outputs: [texture] style: "both" dynamic: "dynamic" cost: "heavy" authority: "Pajouheshgar et al., 2023" url: "https://texelatlas.vercel.app/t/mesh-neural-cellular-automata/" sources_verified_at: "2026-11-29" --- # Mesh Neural Cellular Automata (MeshNCA) (Pajouheshgar et al., 2023) > Runs a tiny learned update rule on the vertices of a mesh, so a texture grows from local neighbour communication and can be evaluated in real time on any triangulation. ## Reach for it when - grow textures directly on arbitrary 3d meshes - texture synthesis should work on any mesh topology - want self-organizing patterns across a surface - avoid uv seams when painting procedural patterns ## How it works Every vertex carries a hidden state vector. At each step it perceives neighbours through learned differential-style filters adapted to mesh connectivity (gradient and Laplacian proxies) and applies a small MLP to update its state, with stochastic update masks. The rule is trained once per target appearance (an exemplar image or text prompt via image-model losses) by unrolling steps and comparing multi-view renders against the style target. Because the rule is local and mesh-agnostic, the same trained automaton produces a texture on unseen meshes and keeps working under deformation or vertex insertion, with cheap per-step cost. ## When to use it Choose it for dynamic, self-organising textures on meshes of any topology (including animated or edited meshes) where the pattern is a repetitive style, not a unique image. Prefer [Neural Cellular Automata for Textures](https://texelatlas.vercel.app/t/neural-cellular-automata-textures.md) for the 2D predecessor, and [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md), [Text2Tex](https://texelatlas.vercel.app/t/text2tex.md) or [Paint3D](https://texelatlas.vercel.app/t/paint3d.md) when you need one-off prompt-specific textures. ## Cost heavy — Per-step compute is small; training per style takes minutes to hours. Measured GPU Weight: 15.73× baseline (moderate) — 0.5175 ms median / 0.5446 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.07× baseline (moderate) — 0.2078 ms median (2.49× faster on L4). Ampere A100 scaling: 10.56× baseline (moderate) — 0.3042 ms median (1.7× faster on A100). ## Failure modes - Only suited to stationary, texture-like patterns; no semantic layouts or large-scale structure - Resolution is tied to vertex density, so coarse meshes give coarse textures - Training can be unstable and one rule only covers one style - Artifacts on very irregular triangulations with extreme valence ## Dataflow - Inputs: mesh, ldr-image, text-prompt - Outputs: texture - Platforms: cuda, python, webgl2 ## Presets ### MeshNCA — base mesh & geodesic neighborhood (left) vs growing surface NCA pattern (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GROWTH": 0.82, "P_CELL_FREQ": 7, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.46 } ``` ```glsl const float P_GROWTH = 0.82; // P NCA Growth [0.1, 1.0, 0.02] const float P_CELL_FREQ = 7.0; // P Pattern Freq [3.0, 12.0, 0.25] const float P_ROT_SPEED = 0.65; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.46; // P Base Mesh / MeshNCA [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // 3D sculpted organic manifold (multi-lobed torus-sphere) for MeshNCA vertex updates float mapMesh(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.48) * q.xz; q.yz = rot2(0.32) * q.yz; float dSph = length(q) - 0.66; vec2 qt = vec2(length(q.xz) - 0.56, q.y); float dTor = length(qt) - 0.24; // Smooth blend between core orb and equatorial ring float h = clamp(0.5 + 0.5 * (dTor - dSph) / 0.22, 0.0, 1.0); float d = mix(dTor, dSph, h) - 0.22 * h * (1.0 - h); d += 0.03 * sin(q.x * 7.0) * cos(q.y * 7.0) * sin(q.z * 7.0); return d * 0.82; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapMesh(p + e.xyy, spin) - mapMesh(p - e.xyy, spin), mapMesh(p + e.yxy, spin) - mapMesh(p - e.yxy, spin), mapMesh(p + e.yyx, spin) - mapMesh(p - e.yyx, spin) )); } // Evaluate intrinsic 3D manifold NCA pattern using tangent-plane geodesic frequencies vec3 evalMeshNCA(vec3 objP, float t, float freq, float growth) { vec3 q = objP * freq; for (int i = 0; i < 3; i++) { vec3 w = sin(q.yzx * 1.35 + vec3(0.0, 1.7, 3.1) + t * 0.28); q += w * 0.42; } float g1 = sin(q.x + cos(q.y * 1.2 + q.z)); float g2 = cos(q.y - sin(q.z * 1.15 - q.x)); float spot = smoothstep(-0.25, 0.65, g1 * g2); float vein = exp(-abs(g1 + g2 * 0.55) * 4.5); // Geodesic growth front spreading from north pole seed float geoDist = length(objP - vec3(0.0, 0.68, 0.0)); float mask = smoothstep(growth * 1.85 + 0.12, growth * 1.85 - 0.14, geoDist); float front = exp(-abs(geoDist - growth * 1.85) * 18.0); vec3 base = vec3(0.06, 0.13, 0.22); vec3 teal = vec3(0.10, 0.72, 0.68); vec3 gold = vec3(0.98, 0.68, 0.20); vec3 pat = mix(base, teal, spot); pat = mix(pat, gold, vein * 0.88); pat += vec3(0.35, 0.98, 0.90) * front * 0.55; return mix(vec3(0.32, 0.35, 0.40), pat, mask); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0); float freq = clamp(P_CELL_FREQ, 2.5, 14.0); float growth = clamp(P_GROWTH, 0.08, 1.0); vec3 ro = vec3(0.0, 0.12, 2.35); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.025, 0.034, 0.056), vec3(0.065, 0.088, 0.135), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapMesh(ro + rd * t, spin); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.48) * objP.xz; objP.yz = rot2(0.32) * objP.yz; vec3 l1 = normalize(vec3(0.62, 0.78, 0.55)); vec3 l2 = normalize(vec3(-0.72, -0.25, 0.45)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 36.0); // Intrinsic triangulated mesh wireframe via spherical coordinates vec3 dn = normalize(objP + vec3(1e-5)); vec2 sp = vec2(atan(dn.z, dn.x) / 3.14159265, asin(clamp(dn.y, -0.999, 0.999)) / 1.5707963); vec2 g = sp * vec2(22.0, 12.0); vec2 f = fract(g); float diag = abs(f.x - f.y); float edge = min(min(f.x, 1.0 - f.x), min(min(f.y, 1.0 - f.y), diag * 0.707)); float wire = smoothstep(0.055, 0.015, edge); if (screenX < split) { // Left: Base mesh topology + 1-ring geodesic neighborhood stencil highlight vec3 clay = vec3(0.34, 0.39, 0.46) * (0.28 + 0.75 * diff1 + 0.25 * diff2); clay = mix(clay, vec3(0.16, 0.68, 0.88), wire * 0.55); float seedRing = exp(-abs(length(objP - vec3(0.0, 0.68, 0.0)) - 0.22) * 32.0); clay += vec3(0.98, 0.65, 0.18) * seedRing * 1.1; clay += vec3(0.24, 0.52, 0.76) * fres * 0.4; col = clay; } else { // Right: MeshNCA surface state with tactile specular sheen vec3 ncaAlbedo = evalMeshNCA(objP, iTime, freq, growth); col = ncaAlbedo * (0.30 + 0.82 * diff1 + 0.28 * diff2) + vec3(0.92, 0.97, 1.0) * spec * 0.42 + vec3(0.22, 0.84, 0.86) * fres * 0.45; col = mix(col, vec3(0.06, 0.12, 0.18), wire * 0.16); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Ehsan Pajouheshgar, Yitao Xu, Alexander Mordvintsev, Eyvind Niklasson, Tong Zhang, Sabine Süsstrunk (2023) Mesh Neural Cellular Automata. ACM Transactions on Graphics (TOG), Volume 43, Issue 4 Article No.: 122, Pages 1 - 16; 19 July 2024. https://arxiv.org/abs/2311.02820 (verified via arxiv on 2026-11-29) 2. [primary] Ehsan Pajouheshgar, Yitao Xu, Alexander Mordvintsev, Eyvind Niklasson, Tong Zhang, Sabine Süsstrunk (2024) Mesh Neural Cellular Automata. ACM Transactions on Graphics. https://doi.org/10.1145/3658127 (verified via crossref on 2026-11-29) 3. [implementation] IVRL (2024) IVRL/MeshNCA. https://github.com/IVRL/MeshNCA (verified via github on 2026-11-29) ## Cite this entry Texel. "Mesh Neural Cellular Automata (MeshNCA)." https://texelatlas.vercel.app/t/mesh-neural-cellular-automata/ (accessed 2026-12-01). --- id: "mesh-shaders" title: "Mesh shaders" aliases: [task shaders, amplification shaders] domain: "performance" stage: "performance" realtime: "realtime" platforms: [desktop-gpu, webgpu] year_introduced: 2018 inputs: [mesh] outputs: [gbuffer, depth] style: "both" dynamic: "both" cost: "medium" authority: "Kubisch" url: "https://texelatlas.vercel.app/t/mesh-shaders/" sources_verified_at: "2026-11-29" --- # Mesh shaders (Kubisch) > A compute-style geometry pipeline where task and mesh stages replace input assembly and vertex processing, letting each workgroup emit its own small batch of primitives after culling. ## Reach for it when - vertex pipeline wastes work on culled geometry - want per-cluster culling inside the draw - huge meshlet scenes need flexible geometry stage - replace input assembly for gpu-driven geometry ## How it works A task (amplification) shader runs one thread per candidate meshlet, performs frustum, cone and occlusion tests, and launches mesh workgroups only for visible ones. Each mesh shader workgroup loads its meshlet's vertices and micro indices from buffers, transforms them cooperatively, and writes vertex and primitive outputs straight to the rasterizer, bypassing fixed-function index fetch. The model removes the vertex cache dependency and lets the shader generate geometry procedurally or decompress it on the fly. Output limits per workgroup are small, so meshlets are built to fit them. ## When to use it Choose it on hardware with native support when you already have [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) and want per-cluster culling without a separate compute pass. Prefer classic indirect draws from [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) on older GPUs or WebGL2, or where the extension is missing. Prefer [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) style software raster for triangles smaller than a pixel. ## Cost medium — Often faster than the vertex pipeline for dense meshes, but results depend on vendor, meshlet size and output count; no numbers asserted. Measured GPU Weight: 39.43× baseline (heavy) — 1.2222 ms median / 1.2708 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 31.15× baseline (heavy) — 0.4953 ms median (2.47× faster on L4). Ampere A100 scaling: 22.9× baseline (heavy) — 0.6594 ms median (1.85× faster on A100). ## Failure modes - Not portable: unavailable on older GPUs and absent from WebGL2 - Wrong meshlet sizing underutilizes a vendor's hardware - Debugging and tooling support is weaker than for vertex pipelines - Tiny triangles still rasterize inefficiently in hardware ## Engine support - metal: builtin — `MTLMeshRenderPipelineDescriptor (objectFunction, meshFunction)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlmeshrenderpipelinedescriptor.json, checked 2026-12-01) - unreal: builtin — `Nanite virtualized meshlet rasterizer & RHI mesh shader pipeline` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/nanite-virtualized-geometry-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: gbuffer, depth - Platforms: desktop-gpu, webgpu ## Presets ### Mesh Shaders — meshlet clusters & normal-cone backface culling (left) vs shaded mesh (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CLUSTER_DENS": 4.5, "P_CONE_THRESH": 0.22, "P_ROT_SPEED": 0.8, "P_SPLIT": 0.5 } ``` ```glsl const float P_CLUSTER_DENS = 4.5; // P Meshlet Density [2.5, 8.0, 0.25] const float P_CONE_THRESH = 0.22; // P Cone Cull Bias [0.0, 0.65, 0.02] const float P_ROT_SPEED = 0.80; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.50; // P Meshlets / Lit Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } // Sculpted high-detail organic torus + grooved core showcasing dense triangle meshlets float mapMesh(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.65) * q.xz; q.xy = rot2(spin * 0.35 + 0.35) * q.xy; vec2 t = vec2(length(q.xz) - 0.56, q.y); float dTor = length(t) - 0.26 - 0.035 * sin(atan(q.z, q.x) * 6.0 + atan(q.y, t.x) * 3.0); float dCore = length(q) - 0.34; return min(dTor, dCore); } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapMesh(p + e.xyy, spin) - mapMesh(p - e.xyy, spin), mapMesh(p + e.yxy, spin) - mapMesh(p - e.yxy, spin), mapMesh(p + e.yyx, spin) - mapMesh(p - e.yyx, spin) )); } // 3D Voronoi meshlet partition in object space returning (borderDist, cellID) vec4 evalMeshlet(vec3 objP, float dens) { vec3 gp = objP * dens; vec3 cell = floor(gp); vec3 f = fract(gp); float d1 = 1e5; float d2 = 1e5; vec3 bestId = vec3(0.0); vec3 bestCenter = vec3(0.0); for (int dz = -1; dz <= 1; dz++) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec3 nb = vec3(float(dx), float(dy), float(dz)); vec3 cid = cell + nb; vec3 rnd = hash33(cid); vec3 pt = nb + 0.15 + 0.70 * rnd; float d = length(f - pt); if (d < d1) { d2 = d1; d1 = d; bestId = cid; bestCenter = (cid + 0.15 + 0.70 * rnd) / dens; } else if (d < d2) { d2 = d; } } } } return vec4(d2 - d1, bestId); } vec3 meshletPalette(vec3 id) { vec3 h = hash33(id + 7.13); float ang = h.x * 6.2831853; return 0.52 + 0.42 * cos(ang + vec3(0.0, 2.094, 4.188)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isLit = screenX >= split; float dens = clamp(P_CLUSTER_DENS, 2.0, 9.0); float coneBias = clamp(P_CONE_THRESH, 0.0, 0.70); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.026, 0.036, 0.058), vec3(0.068, 0.088, 0.135), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapMesh(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d * 0.85; if (t > 7.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); // Transform hit point back to object space so meshlets stick rigidly to the mesh vec3 objP = p; objP.xz = rot2(spin * 0.65) * objP.xz; objP.xy = rot2(spin * 0.35 + 0.35) * objP.xy; vec4 mInfo = evalMeshlet(objP, dens); float seam = smoothstep(0.065, 0.014, mInfo.x); vec3 mCol = meshletPalette(mInfo.yzw); // Sub-meshlet triangle wireframe (64-tri cluster tessellation pattern) vec3 tf = abs(fract(objP * dens * 4.5 - 0.5) - 0.5); float triWire = smoothstep(0.055, 0.012, min(min(tf.x, tf.y), tf.z)); // Task-shader normal-cone backface culling test: dot(viewDir, coneAxis) < sin(coneAngle) float ndv = max(dot(n, -rd), 0.0); float nearSilhouette = smoothstep(coneBias + 0.12, coneBias, ndv); vec3 l1 = normalize(vec3(0.58, 0.82, 0.55)); vec3 l2 = normalize(vec3(-0.70, -0.25, 0.45)); float diff = max(dot(n, l1), 0.0) * 0.85 + max(dot(n, l2), 0.0) * 0.25; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 48.0); if (!isLit) { // Left: Task/Mesh shader cluster view showing color-coded 64-tri meshlets & grazing cone-cull margin col = mCol * (0.34 + 0.76 * diff) + vec3(0.85) * spec * 0.25; col = mix(col, vec3(0.04, 0.06, 0.10), triWire * 0.28); col = mix(col, vec3(0.96, 0.98, 1.0), seam * 0.85); // Tint grazing meshlets approaching the backface-cone culling horizon in bright crimson col = mix(col, vec3(0.98, 0.20, 0.24), nearSilhouette * 0.65); } else { // Right: Final lit brushed alloy surface with subtle meshlet boundary gleam vec3 alloy = vec3(0.68, 0.74, 0.82); col = alloy * (0.22 + 0.88 * diff) + vec3(0.98, 0.94, 0.88) * spec * 0.65; col += mCol * seam * 0.16; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) ## Combines with - [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md): Meshlet buffers with bounds and micro indices are what task and mesh stages read. ## Combination ideas - [Mesh-shader amplified geometry clipmaps with zero CPU draw calls](https://texelatlas.vercel.app/ideas/clipmap-terrain-mesh-shaders/) ## Sources 1. [primary] Christoph Kubisch Introduction to Turing Mesh Shaders. developer.nvidia.com. https://developer.nvidia.com/blog/introduction-turing-mesh-shaders (verified via http on 2026-11-29) 2. [implementation] zeux (2016) zeux/meshoptimizer. https://github.com/zeux/meshoptimizer License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Mesh shaders." https://texelatlas.vercel.app/t/mesh-shaders/ (accessed 2026-12-01). --- id: "meshanything" title: "MeshAnything" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [point-cloud, mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Chen et al., 2024" url: "https://texelatlas.vercel.app/t/meshanything/" sources_verified_at: "2026-11-29" --- # MeshAnything (Chen et al., 2024) > Treats retopology as conditional generation: a point-cloud-conditioned autoregressive transformer turns a dense mesh into a low-face-count mesh with artist-like layout. ## Reach for it when - scanned or generated mesh has far too many triangles - need artist-like low-poly topology automatically - dense ai output needs retopology - reduce faces while keeping a clean layout - convert dense mesh to editable low-poly ## How it works A shape encoder embeds a point cloud sampled from the dense input (from a scan, marching cubes or a generative model). A VQ-VAE tokenises artist meshes, and a decoder-only transformer conditioned on the shape embedding predicts the tokens of a compact mesh. This gives output with far fewer faces than the source and edges roughly following structure. It was designed to plug in after text- or image-to-3D systems that produce dense, noisy triangles, so downstream tools such as rigging or game engines get something closer to hand-modelled topology. ## When to use it Choose it as a learned retopology post-process for generated or scanned assets of moderate complexity. Prefer [MeshGPT](https://texelatlas.vercel.app/t/meshgpt.md) for unconditional generation research, [MeshFlow](https://texelatlas.vercel.app/t/meshflow.md) for faster parallel sampling, and classic quad-remeshers when you need exact budgets or edge-flow guarantees. ## Cost heavy — Autoregressive decoding time scales with output face count. ## Failure modes - Face-count cap (hundreds of faces) truncates detailed objects - Output may be non-watertight or have missing parts versus the dense input - Does not preserve UVs or textures, so reproject afterwards - Large or highly intricate inputs drift in decoding - Weights licence unspecified in the repo metadata (NOASSERTION) ## Dataflow - Inputs: point-cloud, mesh - Outputs: mesh - Platforms: cuda, python ## Combines with - [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md): A dense Hunyuan3D mesh, sampled to points, becomes the condition from which MeshAnything produces a compact mesh. ## Sources 1. [primary] Yiwen Chen, Tong He, Di Huang, Weicai Ye, Sijin Chen, Jiaxiang Tang, Xin Chen, Zhongang Cai, Lei Yang, Gang Yu, Guosheng Lin, Chi Zhang (2024) MeshAnything: Artist-Created Mesh Generation with Autoregressive Transformers. arXiv preprint (cs.CV). https://arxiv.org/abs/2406.10163 (verified via arxiv on 2026-11-29) 2. [implementation] buaacyw (2024) buaacyw/MeshAnything. https://github.com/buaacyw/MeshAnything License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "MeshAnything." https://texelatlas.vercel.app/t/meshanything/ (accessed 2026-12-01). --- id: "meshflow" title: "MeshFlow" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2026 inputs: [mesh, ldr-image] outputs: [mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Li et al., 2026" url: "https://texelatlas.vercel.app/t/meshflow/" sources_verified_at: "2026-11-29" --- # MeshFlow (Li et al., 2026) > Replaces token-by-token mesh decoding with a VAE that puts vertices and connectivity into a continuous latent, then generates the whole mesh in parallel with a rectified-flow transformer. ## Reach for it when - generate artist-style meshes with clean triangles - ai generated meshes are too dense and messy - need compact latent for mesh topology generation - produce low poly meshes with proper connectivity ## How it works A MeshVAE, trained with a contrastive loss, encodes continuous vertex positions and discrete adjacency into a continuous latent that is much more compact than a token sequence. A flow-matching diffusion transformer generates this latent from input geometry and an optional reference image, and the VAE decoder outputs all vertices and their adjacency at once. Skipping autoregression removes the quadratic cost with mesh size and avoids coordinate quantisation. The result targets the same artist-like output as the autoregressive models but with a single parallel sampling pass. ## When to use it Choose it when you need artist-like meshes quickly for larger face counts than token models handle, with geometry as input. Prefer [MeshAnything](https://texelatlas.vercel.app/t/meshanything.md) when you want a longer-established checkpoint, [MeshGPT](https://texelatlas.vercel.app/t/meshgpt.md) for the original token formulation, and dense generators ([Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md), [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md)) when topology does not matter. ## Cost heavy — The repo and paper describe about a second per mesh; verify on your hardware. ## Failure modes - Very new (2026); fewer independent reproductions exist - Continuous adjacency decoding can leave stray or missing edges on thin parts - Needs input geometry; it is a re-meshing / completion model, not text-to-3D - Weights licence not stated clearly (SPDX NOASSERTION) ## Dataflow - Inputs: mesh, ldr-image - Outputs: mesh - Platforms: cuda, python ## Sources 1. [primary] Weiyu Li, Antoine Toisoul, Tom Monnier, Roman Shapovalov, Rakesh Ranjan, Ping Tan, Andrea Vedaldi (2026) MeshFlow: Efficient Artistic Mesh Generation via MeshVAE and Flow-based Diffusion Transformer. arXiv preprint (cs.CV). https://arxiv.org/abs/2606.04621 (verified via arxiv on 2026-11-29) 2. [implementation] facebookresearch (2026) facebookresearch/meshflow. https://github.com/facebookresearch/meshflow License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "MeshFlow." https://texelatlas.vercel.app/t/meshflow/ (accessed 2026-12-01). --- id: "meshgpt" title: "MeshGPT" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Siddiqui et al., 2023" url: "https://texelatlas.vercel.app/t/meshgpt/" sources_verified_at: "2026-11-29" --- # MeshGPT (Siddiqui et al., 2023) > Learns a vocabulary of triangle tokens with a graph-convolutional encoder and vector quantisation, then trains a decoder-only transformer to emit meshes triangle by triangle. ## Reach for it when - want generated meshes with clean artist-like triangles - need to learn mesh generation as token sequences - unconditional low-poly asset generation - marching-cubes style outputs are too dense and messy ## How it works Each triangle in a training mesh is described by its vertices and local geometry, encoded by a graph convolution over the mesh, and quantised into a discrete codebook index (residual vector quantisation). A mesh therefore becomes a sequence of triangle tokens in a canonical order, and a GPT-style transformer is trained to predict the next token. Sampling produces a sequence that is decoded back into triangles. Because meshes are generated natively as compact, sharp-edged triangle sets rather than extracted from a field, results look like artist-made meshes, with large flat faces and coarse triangle counts, unlike iso-surface output. ## When to use it Choose it to study or reproduce token-based mesh generation, or for unconditional/class-conditioned low-poly assets. Prefer [MeshAnything](https://texelatlas.vercel.app/t/meshanything.md) when you need conditioning on a dense shape or point cloud, [MeshFlow](https://texelatlas.vercel.app/t/meshflow.md) for parallel generation with continuous latents, and [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) or [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) when the target is a high-detail textured scan-like asset. ## Cost heavy — Autoregressive: time grows with triangle count; qualitative. Measured GPU Weight: 20.73× baseline (heavy) — 0.6821 ms median / 0.7068 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.81× baseline (moderate) — 0.2672 ms median (2.55× faster on L4). Ampere A100 scaling: 12.9× baseline (moderate) — 0.3716 ms median (1.84× faster on A100). ## Failure modes - Errors in a long token sequence give holes, flipped or overlapping triangles - Quantisation limits vertex precision - Limited face counts per mesh (hundreds to a few thousand triangles) - Official release code is research-grade; the popular community reimplementation differs from the paper in details ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cuda, python ## Presets ### MeshGPT — autoregressive triangle-token decoding (left) vs completed faceted mesh (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SEQ_PROG": 0.72, "P_TRI_RES": 10, "P_ROT_SPEED": 0.58, "P_SPLIT": 0.48 } ``` ```glsl const float P_SEQ_PROG = 0.72; // P Token Progress [0.15, 1.0, 0.02] const float P_TRI_RES = 10.0; // P Triangle Scale [5.0, 16.0, 0.5] const float P_ROT_SPEED = 0.58; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Tokens / Mesh Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash31(float x) { vec3 p = fract(vec3(x) * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yzx + 33.33); return fract((p.xxy + p.yzz) * p.zyx); } // Sculpted architectural chair/bust polyhedron float mapObj(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.45) * q.xz; q.yz = rot2(0.24) * q.yz; float r = length(q); vec3 d = q / max(r, 1e-4); float shape = 0.68 + 0.12 * cos(d.y * 4.5) + 0.08 * sin(atan(d.z, d.x) * 4.0) * (1.0 - abs(d.y)); return (r - shape) * 0.82; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapObj(p + e.xyy, spin) - mapObj(p - e.xyy, spin), mapObj(p + e.yxy, spin) - mapObj(p - e.yxy, spin), mapObj(p + e.yyx, spin) - mapObj(p - e.yyx, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float prog = clamp(P_SEQ_PROG, 0.1, 1.0); float triRes = clamp(P_TRI_RES, 4.0, 18.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.10, 2.30); vec3 rd = normalize(vec3(uv, -1.55)); vec3 bg = mix(vec3(0.022, 0.028, 0.048), vec3(0.058, 0.072, 0.118), smoothstep(-0.55, 0.55, uv.y)); vec3 col = bg; float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapObj(ro + rd * t, spin); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.45) * objP.xz; objP.yz = rot2(0.24) * objP.yz; // Quantized spherical triangle-grid tokenization (VQ-VAE triangle codebook) vec3 dn = normalize(objP + vec3(1e-5)); vec2 sp = vec2(atan(dn.z, dn.x) / 3.14159265, asin(clamp(dn.y, -0.999, 0.999)) / 1.5707963); vec2 g = sp * vec2(triRes * 1.8, triRes); vec2 cell = floor(g); vec2 f = fract(g); float upper = step(f.x, f.y); vec3 bary = (upper > 0.5) ? vec3(1.0 - f.y, f.x, f.y - f.x) : vec3(1.0 - f.x, f.y, f.x - f.y); float edgeD = min(bary.x, min(bary.y, bary.z)); float wire = smoothstep(0.065, 0.015, edgeD); // Flat-shaded quantized facet normal vec2 cUV = (cell + ((upper > 0.5) ? vec2(0.33, 0.67) : vec2(0.67, 0.33))) / vec2(triRes * 1.8, triRes); float phi = cUV.x * 3.14159265; float th = cUV.y * 1.5707963; vec3 flatObjN = normalize(vec3(cos(th) * cos(phi), sin(th), cos(th) * sin(phi))); vec3 flatN = flatObjN; flatN.yz = rot2(-0.24) * flatN.yz; flatN.xz = rot2(-spin * 0.45) * flatN.xz; flatN = normalize(mix(n, flatN, 0.68)); // Autoregressive bottom-to-top triangle token sequence order float seqOrder = clamp((cUV.y + 1.0) * 0.5 + (cUV.x + 1.0) * 0.04, 0.0, 1.0); float waveFront = mod(prog + 0.22 * sin(iTime * 0.75), 1.02); float tokId = cell.y * 37.0 + cell.x * 2.0 + upper; vec3 tokCol = 0.32 + 0.58 * hash31(tokId); vec3 l1 = normalize(vec3(0.58, 0.80, 0.55)); float diff = max(dot(flatN, l1), 0.0); float spec = pow(max(dot(flatN, normalize(l1 - rd)), 0.0), 32.0); if (screenX < split) { // Left: Autoregressive token sequence construction with glowing active-token frontier float generated = smoothstep(waveFront + 0.03, waveFront - 0.02, seqOrder); float frontier = exp(-abs(seqOrder - waveFront) * 38.0); vec3 activeFace = tokCol * (0.35 + 0.75 * diff) + vec3(1.0, 0.86, 0.35) * frontier * 1.4; activeFace = mix(activeFace, vec3(0.95, 0.98, 1.0), wire * 0.55); // Un-generated future triangles shown as faint ghost wireframe vec3 ghost = bg + vec3(0.14, 0.34, 0.52) * wire * 0.55; col = mix(ghost, activeFace, generated); } else { // Right: Completed clean artist-like MeshGPT triangle mesh vec3 base = vec3(0.76, 0.80, 0.88) * (0.28 + 0.82 * diff) + vec3(1.0) * spec * 0.38; col = mix(base, vec3(0.10, 0.24, 0.42), wire * 0.68); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Yawar Siddiqui, Antonio Alliegro, Alexey Artemov, Tatiana Tommasi, Daniele Sirigatti, Vladislav Rosov, Angela Dai, Matthias Nießner (2023) MeshGPT: Generating Triangle Meshes with Decoder-Only Transformers. arXiv preprint (cs.CV). https://arxiv.org/abs/2311.15475 (verified via arxiv on 2026-11-29) 2. [primary] Yawar Siddiqui, Antonio Alliegro, Alexey Artemov, Tatiana Tommasi, Daniele Sirigatti, Vladislav Rosov, Angela Dai, Matthias Nießner (2024) MeshGPT: Generating Triangle Meshes with Decoder-Only Transformers. 2024 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/cvpr52733.2024.01855 (verified via crossref on 2026-11-29) 3. [implementation] lucidrains (2023) lucidrains/meshgpt-pytorch. https://github.com/lucidrains/meshgpt-pytorch License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "MeshGPT." https://texelatlas.vercel.app/t/meshgpt/ (accessed 2026-12-01). --- id: "meshlets" title: "Meshlets (cluster rendering)" aliases: [clusters, mesh clusters] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgpu, desktop-gpu, unreal] year_introduced: 2018 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "zeux, 2016" url: "https://texelatlas.vercel.app/t/meshlets/" sources_verified_at: "2026-11-29" --- # Meshlets (cluster rendering) (zeux, 2016) > Partition a mesh into small clusters of up to a few dozen vertices and about a hundred triangles, each with bounds and a normal cone, so the GPU can cull and draw them as independent units. ## Reach for it when - cull geometry at finer level than whole objects - split large meshes for gpu processing in small clusters - need data layout for cluster lod - back-face cull groups of triangles together - prepare meshes for mesh shaders ## How it works An offline builder walks the triangle list and greedily grows clusters that stay within a vertex and triangle limit, preferring triangles that share vertices and are spatially close. Each meshlet gets a local vertex list referencing the global buffer, a micro index buffer with byte-sized indices, a bounding sphere, and a normal cone describing the range of facing directions. At runtime a compute or task shader tests every meshlet against the frustum, the cone against the view direction, and optionally a depth pyramid. Survivors are drawn through a mesh shader or by software expansion into an index buffer. Because clusters are small and uniform, they also serve as the unit of LOD selection and streaming. ## When to use it Choose it as the data layout for GPU-driven culling at sub-object granularity or as input to a cluster LOD scheme. Prefer [Mesh shaders](https://texelatlas.vercel.app/t/mesh-shaders.md) for the hardware path that consumes meshlets directly. Prefer whole-object culling in [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) when meshes are small or few, since meshlet overhead then buys nothing. ## Cost cheap — Culling cost scales with meshlet count, not triangles; extra memory for bounds and micro indices. Measured GPU Weight: 35.62× baseline (heavy) — 1.1186 ms median / 1.1418 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 30.14× baseline (heavy) — 0.4762 ms median (2.35× faster on L4). Ampere A100 scaling: 21.87× baseline (heavy) — 0.6299 ms median (1.78× faster on A100). ## Failure modes - Poorly sized meshlets waste lanes on some GPUs, since optimal limits differ between vendors - Normal cone culling is weak on curved or noisy meshes and can reject nothing - Rebuilt clusters of skinned or deforming meshes have stale bounds unless inflated - Thin or scattered geometry produces many tiny underfilled meshlets ## Engine support - metal: builtin — `MTLMeshRenderPipelineDescriptor (objectFunction + meshFunction cluster shading pipeline)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlmeshrenderpipelinedescriptor.json, checked 2026-12-01) - threejs: official — `import { createMeshlets } from 'three/addons/utils/MeshletGeometryUtils.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/utils/MeshletGeometryUtils.js, checked 2026-12-01) — WebGPU meshlet examples built on meshoptimizer. - unreal: builtin — `Nanite encodes Static Meshes into hierarchical triangle clusters (meshlets) for per-cluster culling and LOD` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/nanite-virtualized-geometry-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: webgpu, desktop-gpu, unreal ## Presets ### meshoptimizer meshlet build limits (json-params; parameter preset) ```json { "max_vertices": 64, "max_triangles": 126, "cone_weight": 0 } ``` Attribution: Values from the meshoptimizer README for NVIDIA GPUs (MIT license); raise cone_weight toward 0.25 if cone culling is used.; basis: 0 ### Meshlets — 3D cluster partitioning & normal-cone backface culling visualization (glsl-fragment; rendered 2026-11-30) ```json { "P_CLUSTER_SIZE": 6, "P_CONE_CULL": 0.75, "P_WIRE_ALPHA": 0.75, "P_ROT_SPEED": 1 } ``` ```glsl const float P_CLUSTER_SIZE = 6.0; // P Meshlet Scale [3.0, 12.0, 0.25] const float P_CONE_CULL = 0.75; // P Normal-Cone Cull [0.0, 1.0, 0.02] const float P_WIRE_ALPHA = 0.75; // P Cluster Seams [0.0, 1.5, 0.05] const float P_ROT_SPEED = 1.0; // P Orbit Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } // Sculpted organic-mechanical knot for meshlet clustering float mapMesh(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.42) * q.xz; q.yz = rot2(0.32 + 0.15 * sin(spin * 0.5)) * q.yz; float ang = atan(q.z, q.x); float rMaj = 0.72 + 0.10 * cos(ang * 3.0); vec2 tq = vec2(length(q.xz) - rMaj, q.y + 0.10 * sin(ang * 3.0)); float dT = length(tq) - 0.30; float dS = length(q) - 0.34; // Smooth union between core and trefoil ring float k = 0.16; float h = clamp(0.5 + 0.5 * (dS - dT) / k, 0.0, 1.0); return (mix(dS, dT, h) - k * h * (1.0 - h)) * 0.85; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapMesh(p + e.xyy, spin) - mapMesh(p - e.xyy, spin), mapMesh(p + e.yxy, spin) - mapMesh(p - e.yxy, spin), mapMesh(p + e.yyx, spin) - mapMesh(p - e.yyx, spin) )); } // 3D Voronoi meshlet assignment returning (clusterCenterObjSpace, seamDist, clusterHash) void evalMeshlet(vec3 objP, float scale, out vec3 centerObj, out float seam, out vec3 mCol) { vec3 sp = objP * scale; vec3 n = floor(sp); vec3 f = fract(sp); float d1 = 8.0, d2 = 8.0; vec3 bestCell = vec3(0.0); vec3 bestSite = vec3(0.0); for (int z = -1; z <= 1; z++) { for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { vec3 g = vec3(float(x), float(y), float(z)); vec3 o = hash33(n + g); vec3 r = g + o - f; float d = dot(r, r); if (d < d1) { d2 = d1; d1 = d; bestCell = n + g; bestSite = (n + g + o) / scale; } else if (d < d2) { d2 = d; } } } } centerObj = bestSite; seam = sqrt(d2) - sqrt(d1); vec3 h = hash33(bestCell * 1.9 + 7.3); // Crisp categorical meshlet palette mCol = 0.24 + 0.72 * h; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float spin = iTime * max(P_ROT_SPEED, 0.0); float scale = clamp(P_CLUSTER_SIZE, 2.5, 14.0); float cullDemo = clamp(P_CONE_CULL, 0.0, 1.0); float wireAmt = clamp(P_WIRE_ALPHA, 0.0, 1.5); vec3 ro = vec3(0.0, 0.15, 2.55); vec3 rd = normalize(vec3(uv, -1.5)); vec3 col = mix(vec3(0.035, 0.045, 0.07), vec3(0.095, 0.115, 0.16), smoothstep(-0.55, 0.55, uv.y)); vec2 bgG = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.02, 0.03, 0.045) * smoothstep(0.03, 0.0, min(bgG.x, bgG.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapMesh(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); // Transform into object space so meshlet IDs stay rigidly attached to the mesh vec3 objP = p; objP.xz = rot2(spin * 0.42) * objP.xz; objP.yz = rot2(0.32 + 0.15 * sin(spin * 0.5)) * objP.yz; vec3 centerObj; float seam; vec3 mCol; evalMeshlet(objP, scale, centerObj, seam, mCol); // Compute meshlet bounding normal-cone test against a side-mounted "main camera" frustum // so the viewer can see which meshlets are front-facing vs backface-culled by the cone test! vec3 virtualView = normalize(vec3(0.75 * cos(spin * 0.25), 0.22, 0.72)); // Transform cluster center back to approximate world normal direction vec3 cWorld = centerObj; cWorld.yz = rot2(-(0.32 + 0.15 * sin(spin * 0.5))) * cWorld.yz; cWorld.xz = rot2(-spin * 0.42) * cWorld.xz; vec3 coneAxis = calcNormal(cWorld, spin); float coneDot = dot(coneAxis, virtualView); // Meshlet normal cone cutoff (-sin(halfAngle)) float coneCulled = smoothstep(0.18, -0.05, coneDot) * cullDemo; vec3 l1 = normalize(vec3(0.65, 0.85, 0.55)); float diff = max(dot(n, l1), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 32.0) * 0.38; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.30; // Active surviving meshlet shading vec3 activeCol = mCol * (0.28 + 0.80 * diff) + vec3(spec) + vec3(0.45, 0.68, 1.0) * rim; float seamEdge = smoothstep(0.085, 0.015, seam); activeCol = mix(activeCol, vec3(0.04, 0.05, 0.08), seamEdge * 0.78 * min(wireAmt, 1.2)); // Normal-cone culled meshlet appearance: translucent hatched crimson wireframe float hatch = smoothstep(0.4, 0.8, sin((uv.x + uv.y) * 90.0)); vec3 culledCol = mix(vec3(0.14, 0.05, 0.08), vec3(0.95, 0.22, 0.36), max(seamEdge * 0.9, hatch * 0.22)); culledCol += vec3(0.95, 0.25, 0.42) * rim * 0.65; col = mix(activeCol, culledCol, coneCulled); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) - extended by [Mesh shaders](https://texelatlas.vercel.app/t/mesh-shaders.md) - extended by [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): Per-meshlet bounding spheres are tested against the depth pyramid to skip hidden clusters before rasterization. ## Combination ideas - [Meshlet foliage with compute-rasterized atomic spores](https://texelatlas.vercel.app/ideas/meshlet-foliage-atomic-spore-raster/) - [Meshlet kelp forests through underwater PSF scattering](https://texelatlas.vercel.app/ideas/meshlet-kelp-small-angle-underwater-psf/) ## Sources 1. [primary] zeux (2016) zeux/meshoptimizer. https://github.com/zeux/meshoptimizer License: MIT. (verified via github on 2026-11-29) 2. [tutorial] Arseny Kapoulkine Meshlet size tradeoffs. zeux.io. https://zeux.io/2023/01/16/meshlet-size-tradeoffs (verified via http on 2026-11-29) ## Cite this entry Texel. "Meshlets (cluster rendering)." https://texelatlas.vercel.app/t/meshlets/ (accessed 2026-12-01). --- id: "meshoptimizer" title: "meshoptimizer mesh optimization" aliases: [meshopt, EXT_meshopt_compression] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu] year_introduced: 2016 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "zeux, 2016" url: "https://texelatlas.vercel.app/t/meshoptimizer/" sources_verified_at: "2026-11-29" --- # meshoptimizer mesh optimization (zeux, 2016) > An MIT library that reorders for vertex cache and fetch efficiency, simplifies meshes for LOD, builds meshlets, and encodes vertex and index buffers for fast decoding. ## Reach for it when - scene has too many triangles for the gpu - mesh loading and vertex fetch is slow - reduce model size for web delivery - need lod versions of meshes automatically ## How it works Index buffers are reordered for post-transform cache hits, then vertices are reordered for fetch locality, and overdraw can be reduced further. Simplification collapses edges with a quadric error metric, returning a measured error that picks LOD by screen size. Buffer codecs byte-transposes and delta-codes streams so a general-purpose compressor works well, and the decoder runs at gigabytes per second using SIMD or WebAssembly. The same library builds meshlets with bounds and cones for cluster pipelines. ## When to use it Choose it as the default post-process for any mesh shipped to a GPU, and for LOD chains and meshlets. Prefer [Draco mesh compression](https://texelatlas.vercel.app/t/draco-mesh-compression.md) when size is the only goal and decode speed is irrelevant. Prefer [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) when the engine builds cluster hierarchies itself. ## Cost cheap — Offline processing; runtime cost is a fast decode. Measured GPU Weight: 20.01× baseline (heavy) — 0.6582 ms median / 0.6826 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.17× baseline (moderate) — 0.2889 ms median (2.28× faster on L4). Ampere A100 scaling: 13.7× baseline (moderate) — 0.3947 ms median (1.67× faster on A100). ## Failure modes - Aggressive simplification collapses thin features and breaks UV seams - Attribute errors are not captured unless weighted - Decoding requires matching filter and mode settings per stream - Lossy quantization visible at large object scales ## Engine support - babylonjs: official — `glTF EXT_meshopt_compression loader extension (MeshoptCompression)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/Compression/meshoptCompression.ts, checked 2026-12-01) - blender: official — `File > Export > glTF 2.0 > Data > Compression (Meshopt)` (evidence: https://docs.blender.org/manual/en/5.2/addons/scene_gltf2.html, checked 2026-12-01) — Bundled glTF 2.0 add-on writes EXT/KHR_meshopt_compression. - godot: builtin — `ImporterMesh.generate_lods(); scene import option Meshes > Generate LODs` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ImporterMesh.xml, checked 2026-12-01) — Godot bundles meshoptimizer for LOD generation. - threejs: official — `import { createMeshlets } from 'three/addons/utils/MeshletGeometryUtils.js' (uses MeshoptClusterizer, MeshoptSimplifier)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/utils/MeshletGeometryUtils.js, checked 2026-12-01) — Official addons consume meshoptimizer; no general mesh-optimize pass. - unity: official — `Package Manager > Meshopt Decompression (com.unity.meshopt.decompress)` (evidence: https://docs.unity3d.com/Packages/com.unity.meshopt.decompress@0.1/manual/index.html, checked 2026-12-01) — Decoder for meshopt-compressed glTF meshes (EXT_meshopt_compression). ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu ## Presets ### meshoptimizer meshlet limits (json-params; parameter preset) ```json { "max_vertices": 64, "max_triangles": 126, "cone_weight": 0.25 } ``` Attribution: Defaults from the meshoptimizer README (MIT license).; basis: 0 ### meshoptimizer — 64-triangle meshlet clusters & QEM LOD wireframe (left) vs vertex-cache-optimized smooth shading (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MESHLET_RES": 7, "P_LOD_ERROR": 0.55, "P_WIREFRAME": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_MESHLET_RES = 7.00; // P Meshlet Density [4.0, 12.0, 1.0] const float P_LOD_ERROR = 0.55; // P QEM LOD Step [0.0, 1.0, 0.05] const float P_WIREFRAME = 0.45; // P Triangle Wire [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P Meshlets / Shaded [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); } vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Sculpted twisted torus-shell geometry ideal for showcasing spatial meshlet partitioning & LOD float mapMesh(vec3 p, float t) { p.xz = rot2(p.xz, t * 0.48); p.xy = rot2(p.xy, 0.30); vec2 q = vec2(length(p.xz) - 0.38, p.y); float ang = atan(p.z, p.x); q = rot2(q, ang * 1.5); float dBox = length(max(abs(q) - vec2(0.11, 0.16), 0.0)) - 0.055; return dBox * 0.82; } vec3 calcNormal(vec3 p, float t) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapMesh(p + e.xyy, t) - mapMesh(p - e.xyy, t), mapMesh(p + e.yxy, t) - mapMesh(p - e.yxy, t), mapMesh(p + e.yyx, t) - mapMesh(p - e.yyx, t) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float mRes = clamp(P_MESHLET_RES, 3.0, 14.0); float lodErr = clamp(P_LOD_ERROR, 0.0, 1.0); float wireAmt = clamp(P_WIREFRAME, 0.0, 1.0); vec3 ro = vec3(0.0, 0.28, 2.08); vec3 rd = normalize(vec3(uv.x, uv.y - 0.07, -1.50)); vec3 lDir = normalize(vec3(0.58, 0.78, 0.52)); vec3 col = mix(vec3(0.05, 0.07, 0.12), vec3(0.13, 0.18, 0.28), smoothstep(-0.4, 0.5, uv.y)); float tRay = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { float h = mapMesh(ro + rd * tRay, iTime); if (h < 0.002) { hit = true; break; } tRay += h; if (tRay > 6.0) break; } if (hit) { vec3 p = ro + rd * tRay; vec3 n = calcNormal(p, iTime); // Transform hit to rigid object space for stable meshlet IDs vec3 pObj = p; pObj.xz = rot2(pObj.xz, iTime * 0.48); pObj.xy = rot2(pObj.xy, 0.30); float ndl = max(dot(n, lDir), 0.0); float spec = pow(max(dot(reflect(-lDir, n), -rd), 0.0), 42.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 4.0); if (screenX < split) { // Left: Voronoi-like 3D spatial meshlet clusters (each cluster ~64 tris) + QEM triangle density grid vec3 scaled = pObj * mRes; vec3 cid = floor(scaled); float bestD = 9.0; float secondD = 9.0; vec3 bestId = cid; for (int dz = -1; dz <= 1; dz++) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec3 nb = cid + vec3(float(dx), float(dy), float(dz)); vec3 jit = vec3(hash31(nb), hash31(nb + 13.7), hash31(nb + 29.1)); float dd = length((nb + jit * 0.75 + 0.125) - scaled); if (dd < bestD) { secondD = bestD; bestD = dd; bestId = nb; } else if (dd < secondD) { secondD = dd; } } } } float hId = hash31(bestId + 5.3); vec3 meshletCol = 0.50 + 0.44 * cos(vec3(0.0, 2.05, 4.10) + hId * 6.2831853); float clusterBorder = smoothstep(0.08, 0.015, secondD - bestD); // Sub-cluster QEM simplified triangle wireframe float triFreq = mix(28.0, 10.0, lodErr); vec3 tf = fract(pObj * triFreq); float triEdge = min(min(min(tf.x, 1.0 - tf.x), min(tf.y, 1.0 - tf.y)), abs(tf.x + tf.y - 1.0)); float wire = smoothstep(0.08, 0.015, triEdge); col = meshletCol * (0.28 + 0.88 * ndl) + vec3(0.95) * spec * 0.35; col = mix(col, vec3(0.06, 0.08, 0.12), wire * wireAmt * 0.55); col = mix(col, vec3(0.98, 0.98, 1.0), clusterBorder * 0.65); } else { // Right: Vertex-cache & overdraw-optimized clean shaded metallic ceramic surface vec3 alb = mix(vec3(0.76, 0.79, 0.84), vec3(0.92, 0.66, 0.34), 0.5 + 0.5 * n.x); col = alb * (0.22 + 0.94 * ndl) + vec3(1.15, 1.08, 0.98) * spec * 0.90 + vec3(0.32, 0.66, 0.98) * fres * 0.55; } } else if (rd.y < -0.005) { float tf = (-0.54 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { vec3 fp = ro + rd * tf; float sh = smoothstep(0.28, 0.72, length(fp.xz)); vec2 g = abs(fract(fp.xz * 2.5) - 0.5); float grid = smoothstep(0.04, 0.01, min(g.x, g.y)); col = mix(col, mix(vec3(0.10, 0.12, 0.17), vec3(0.24, 0.30, 0.42), grid) * (0.35 + 0.65 * sh), exp(-tf * 0.16)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md): meshopt builds clusters and orders their indices for mesh shaders. ## Sources 1. [primary] zeux (2016) zeux/meshoptimizer. https://github.com/zeux/meshoptimizer License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "meshoptimizer mesh optimization." https://texelatlas.vercel.app/t/meshoptimizer/ (accessed 2026-12-01). --- id: "metropolis-light-transport" title: "Metropolis Light Transport" aliases: [MLT, PSSMLT] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda] year_introduced: 1997 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "static" cost: "offline" authority: "Veach & Guibas, 1997" url: "https://texelatlas.vercel.app/t/metropolis-light-transport/" sources_verified_at: "2026-11-29" --- # Metropolis Light Transport (Veach & Guibas, 1997) > Samples light paths with a Markov chain that mutates the current path, spending effort proportional to path contribution. Strong on difficult, narrow-light-path scenes and weak on simple ones. ## Reach for it when - scene lit through a small gap is very noisy - caustics and nested glass converge slowly - path tracing struggles when light paths are rare - pool caustics or lamp in glass full of fireflies ## How it works Instead of generating independent random paths, MLT keeps a current **valid path** from the light to the eye and proposes a small mutation of it. The proposal is accepted with a probability based on the ratio of path contributions, which is the Metropolis-Hastings rule. The resulting chain visits paths with density proportional to their image contribution, so once the chain finds a hard-to-discover bright path (light through a keyhole, a caustic) it stays nearby and explores variations. The original formulation mutates paths directly with bidirectional mutations, lens and caustic perturbations and so on, each needing its own transition density. A later and far simpler variant, **primary-sample-space MLT**, mutates the vector of random numbers feeding an ordinary path tracer or BDPT, so any existing integrator becomes a Markov chain sampler. Output is the histogram of visited pixels, normalized with a separate estimate of total image brightness; mutation strategies and a small amount of independent sampling start the chain. ## When to use it Choose it for scenes where valid light paths occupy a tiny part of path space: lit only through a slightly open door, a lamp inside nested glass, a pool caustic. Prefer [bidirectional-path-tracing](bidirectional-path-tracing) or [vertex-connection-and-merging](vertex-connection-and-merging) when you want predictable convergence and easy parallelism. Prefer [path-tracing](path-tracing) for ordinary scenes: MLT's correlated samples give blotchy, non-uniform noise across the image and complicate animation. Prefer [path-guiding](path-guiding) when you want an adaptive sampler without Markov-chain correlation. ## Cost offline — Per-sample cost is similar to the underlying integrator; the benefit is variance in hard scenes. Normalization and start-up estimation add overhead. Measured GPU Weight: 13.15× baseline (moderate) — 0.4325 ms median / 0.4549 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 12.17× baseline (moderate) — 0.1935 ms median (2.24× faster on L4). Ampere A100 scaling: 8.19× baseline (moderate) — 0.236 ms median (1.83× faster on A100). ## Failure modes - Correlated samples give splotchy, non-uniform noise and temporal flicker in animation - The chain can get stuck in an isolated mode and miss other bright path families - Per-pixel convergence is uneven, so easy regions can end up noisier than with plain path tracing - Hard to parallelize across a GPU without independent chains and a careful normalization pass ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda ## Presets ### Metropolis Light Transport (MLT) — uniform PT missed keyhole (left) vs MCMC Markov-chain exploration (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DOOR_GAP": 0.24, "P_MCMC_GAIN": 1.15, "P_CHAIN_ANIM": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_DOOR_GAP = 0.24; // P Door Slit Width [0.08, 0.45, 0.02] const float P_MCMC_GAIN = 1.15; // P MCMC Convergence [0.3, 1.6, 0.05] const float P_CHAIN_ANIM = 0.85; // P Mutation Rate [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P PT / MLT Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Famous Veach "Door Ajar" difficult light-transport benchmark: // Bright room behind an almost-closed doorway casts a narrow ribbon of light & bounced caustic into dark studio! vec2 mapDoorRoom(vec3 p, float gap) { float dFloor = p.y + 0.78; float dBack = p.z + 1.25; // Partition wall with narrow vertical doorway slit centered at x = -0.05 float wallZ = abs(p.z + 0.35) - 0.06; float inSlit = step(abs(p.x + 0.05), gap * 0.5) * step(p.y, 0.62); float dWall = (inSlit > 0.5) ? 1.0 : max(wallZ, p.y - 0.95); // Keep outer frame solid around the doorway float frameL = max(wallZ, -(p.x + 0.05 - gap * 0.5)); float frameR = max(wallZ, (p.x + 0.05 + gap * 0.5)); dWall = min(min(frameL, frameR), max(wallZ, 0.62 - p.y)); dWall = max(wallZ, min(abs(p.x + 0.05) < gap * 0.5 && p.y < 0.62 ? 0.5 : -0.1, 0.5)); // Clean SDF for wall with rectangular aperture vec2 ap = abs(vec2(p.x + 0.05, p.y + 0.08)) - vec2(gap * 0.5, 0.70); float dAp = length(max(ap, 0.0)) + min(max(ap.x, ap.y), 0.0); dWall = max(wallZ, -dAp); vec2 res = vec2(dFloor, 1.0); if (dBack < res.x) res = vec2(dBack, 2.0); // bright lit back room if (dWall < res.x) res = vec2(dWall, 3.0); // partition wall // Foreground sculptural glass/marble pedestal receiving the difficult doorway bounce light float dOrb = length(p - vec3(0.42, -0.44, 0.38)) - 0.34; if (dOrb < res.x) res = vec2(dOrb, 4.0); float dCube = length(max(abs(p - vec3(-0.46, -0.50, 0.45)) - vec3(0.24, 0.28, 0.24), 0.0)); if (dCube < res.x) res = vec2(dCube, 5.0); return res; } vec3 calcNormal(vec3 p, float gap) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapDoorRoom(p + e.xyy, gap).x - mapDoorRoom(p - e.xyy, gap).x, mapDoorRoom(p + e.yxy, gap).x - mapDoorRoom(p - e.yxy, gap).x, mapDoorRoom(p + e.yyx, gap).x - mapDoorRoom(p - e.yyx, gap).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isMLT = screenX >= split; float gap = clamp(P_DOOR_GAP, 0.06, 0.48); float mltGain = clamp(P_MCMC_GAIN, 0.25, 1.8); float animT = iTime * max(P_CHAIN_ANIM, 0.0); vec3 ro = vec3(0.0, 0.14, 2.08); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.06), -1.35)); float t = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapDoorRoom(ro + rd * t, gap); if (h.x < 0.003) { hit = vec2(t, h.y); break; } t += h.x; if (t > 8.0) break; } vec3 col = vec3(0.015, 0.018, 0.028); if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p, gap); if (hit.y > 1.5 && hit.y < 2.5) { // Bright sun-drenched room visible through the narrow doorway slit col = vec3(3.2, 2.55, 1.75); } else { vec3 alb = vec3(0.56, 0.58, 0.64); if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.32, 0.36, 0.44); else if (hit.y > 3.5 && hit.y < 4.5) alb = vec3(0.92, 0.72, 0.48); else if (hit.y > 4.5) alb = vec3(0.38, 0.72, 0.86); // Slit portal center at (-0.05, -0.08, -0.35) vec3 portal = vec3(-0.05, 0.05, -0.35); vec3 toP = portal - p; float distP = length(toP); vec3 dirP = toP / max(distP, 1e-4); // Directional beam squeezing through narrow doorway gap onto foreground floor & objects float beamAlign = exp(-pow((p.x + 0.05 - (p.z + 0.35) * 0.28) / max(gap * 0.65 + (p.z + 0.35) * 0.14, 0.05), 2.0)); float inFront = smoothstep(-0.35, -0.15, p.z); float slitDirect = beamAlign * inFront * max(dot(n, dirP), 0.0) * (1.8 / (0.4 + distP * distP)); // Soft secondary bounce filled by Markov chain local mutations exploring the bright path neighborhood float bounce = (0.42 / (0.65 + distP * distP)) * (0.35 + 0.65 * max(dot(n, dirP), 0.0)) * inFront; vec3 converged = alb * (vec3(1.0, 0.84, 0.60) * (slitDirect + bounce * 0.85) + vec3(0.03, 0.04, 0.06)); if (isMLT) { // Right: MLT locks Markov chains onto the doorway slit -> clean bright shaft & rich indirect glow! col = converged * mltGain; // Subtle animated MCMC local mutation sparks dancing inside the discovered light shaft float spark = exp(-abs(sin(p.x * 22.0 + animT * 3.0) * cos(p.z * 22.0 - animT * 2.4)) * 18.0) * beamAlign * inFront; col += vec3(0.28, 0.96, 0.92) * spark * 0.22; } else { // Left: Naive path tracer rarely hits the narrow gap -> dark, noisy, blotchy fireflies! vec2 pix = floor(fragCoord * 0.65); float fr = floor(iTime * 9.0) * 0.11; float r1 = hash21(pix + vec2(fr * 19.1, 5.7)); float r2 = hash21(pix * 1.31 + vec2(11.3, fr * 29.3)); float hitProb = clamp(gap * 1.4, 0.12, 0.55); float survived = step(1.0 - hitProb, r1); float firefly = smoothstep(0.955, 0.998, r2) * 4.8 * (0.25 + slitDirect); col = converged * (0.14 + 0.95 * survived * r1) + alb * vec3(1.0, 0.85, 0.62) * firefly; } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Bidirectional Path Tracing](https://texelatlas.vercel.app/t/bidirectional-path-tracing.md): Mutating the random numbers of a BDPT sampler lets the chain reuse its connection strategies. ## Sources 1. [primary] Eric Veach, Leonidas J. Guibas (1997) Metropolis light transport. Proceedings of the 24th annual conference on Computer graphics and interactive techniques - SIGGRAPH '97. https://doi.org/10.1145/258734.258775 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Metropolis Light Transport (Physically Based Rendering, 3rd edition). pbr-book.org. https://pbr-book.org/3ed-2018/Light_Transport_III_Bidirectional_Methods/Metropolis_Light_Transport (verified via http on 2026-11-29) 3. [implementation] mmp (2015) mmp/pbrt-v3. https://github.com/mmp/pbrt-v3 License: BSD-2-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "Metropolis Light Transport." https://texelatlas.vercel.app/t/metropolis-light-transport/ (accessed 2026-12-01). --- id: "mip-nerf-360" title: "Mip-NeRF 360" aliases: [mip-NeRF 360] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, python] year_introduced: 2021 inputs: [photos, camera-poses] outputs: [radiance-field] style: "photoreal" dynamic: "static" cost: "offline" authority: "Barron et al., 2021" url: "https://texelatlas.vercel.app/t/mip-nerf-360/" sources_verified_at: "2026-11-29" --- # Mip-NeRF 360 (Barron et al., 2021) > Extends NeRF to unbounded 360-degree scenes with a scene contraction, anti-aliased conical frustum sampling and a proposal network, plus a distortion regulariser that removes floaters. ## Reach for it when - nerf fails on large unbounded 360 captures - background in radiance field is blurry or aliased - floaters show up in captured scene renders - need top-quality offline novel views of outdoor scenes - scene extends infinitely and breaks bounded models ## How it works Three ideas stack. First, rays are modelled as cone frustums and encoded with an integrated positional encoding, so far or low-resolution samples are blurred instead of aliased. Second, a contraction maps unbounded space into a bounded ball: points inside stay linear, outside points are squashed so infinity sits at a finite radius, letting sky and distant buildings be represented. Third, a small proposal MLP predicts coarse weights along each ray, supervised by the full model, and replaces the expensive second NeRF pass for importance sampling. A distortion loss penalises weights that are spread out along a ray, pushing density to concentrate on surfaces and suppressing fog and floaters. ## When to use it Choose it when you want the highest-quality offline NeRF baseline on unbounded captures and its benchmark scenes. Prefer [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md) for speed, [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for real-time rendering of the same captures, and [Mip-Splatting](https://texelatlas.vercel.app/t/mip-splatting.md) when anti-aliasing across zoom levels is the concern. ## Cost offline — Hours of training per scene on accelerator hardware; far slower than hash-grid and splat methods. Measured GPU Weight: 3.42× baseline (light) — 0.1126 ms median / 0.1158 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.73× baseline (light) — 0.0434 ms median (2.59× faster on L4). Ampere A100 scaling: 2.05× baseline (light) — 0.0591 ms median (1.91× faster on A100). ## Failure modes - Slow training and rendering make iteration painful - Residual floaters near cameras and haze at the contraction boundary - Thin structures and distant detail are still lost because contraction squeezes background samples - Quality depends on accurate poses and constant exposure; lighting changes bake into the field ## Dataflow - Inputs: photos, camera-poses - Outputs: radiance-field - Platforms: cuda, python ## Presets ### Mip-NeRF 360 — unbounded scene contraction map (left) vs anti-aliased conical IPE 360 scene (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_IPE_FILTER": 0.75, "P_CONTRACT_VIS": 1, "P_CAM_ORBIT": 0.55, "P_SPLIT": 0.46 } ``` ```glsl const float P_IPE_FILTER = 0.75; // P Conical IPE [0.0, 1.5, 0.05] const float P_CONTRACT_VIS = 1.0; // P Contraction Grid [0.2, 1.6, 0.05] const float P_CAM_ORBIT = 0.55; // P Camera Orbit [0.0, 2.2, 0.05] const float P_SPLIT = 0.46; // P Contraction / 360 [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Mip-NeRF 360 scene contraction: identity inside ||x||<=1, maps unbounded infinity into ||x||<=2 vec3 contract360(vec3 x) { float r = length(x); if (r <= 1.0) return x; return (2.0 - 1.0 / max(r, 1e-4)) * (x / max(r, 1e-4)); } // Band-limited sinusoidal checkerboard using conical frustum variance (Integrated Positional Encoding) float evalIPECheck(vec2 p, float coneVar) { float att1 = exp(-0.5 * coneVar * 36.0); float att2 = exp(-0.5 * coneVar * 144.0); float c1 = sin(p.x * 6.0) * sin(p.y * 6.0) * att1; float c2 = sin(p.x * 12.0) * sin(p.y * 12.0) * att2 * 0.45; return 0.5 + 0.42 * c1 + 0.18 * c2; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isContract = screenX < split; float ipeGain = clamp(P_IPE_FILTER, 0.0, 1.8); float gridGain = clamp(P_CONTRACT_VIS, 0.1, 1.8); float spin = iTime * max(P_CAM_ORBIT, 0.0); vec3 ro = vec3(0.0, 0.52, 2.15); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.08), -1.35)); ro.xz = rot2(spin * 0.42) * ro.xz; rd.xz = rot2(spin * 0.42) * rd.xz; // Unbounded 360-degree mountain horizon & twilight sky float az = atan(rd.z, rd.x); float mtnH = 0.06 + 0.08 * sin(az * 3.0) + 0.05 * cos(az * 7.0 + 1.2) + 0.025 * sin(az * 15.0); vec3 sky = mix(vec3(0.95, 0.58, 0.34), vec3(0.10, 0.24, 0.52), smoothstep(-0.02, 0.48, rd.y)); vec3 col = (rd.y < mtnH && rd.y > -0.02) ? mix(vec3(0.12, 0.18, 0.30), vec3(0.28, 0.34, 0.46), smoothstep(0.0, mtnH, rd.y)) : sky; // Intersect foreground hero sphere (at origin, R=0.52) and unbounded ground plane (y = -0.52) float b = dot(ro, rd); float c = dot(ro, ro) - 0.52 * 0.52; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tPl = (rd.y < -0.005) ? ((-0.52 - ro.y) / rd.y) : 1e5; if (tPl < 0.05) tPl = 1e5; vec3 lDir = normalize(vec3(0.62, 0.72, 0.45)); if (tSph < tPl && tSph < 1e4) { vec3 p = ro + rd * tSph; vec3 n = normalize(p); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 40.0); vec3 alb = mix(vec3(0.95, 0.44, 0.24), vec3(0.98, 0.80, 0.32), 0.5 + 0.5 * sin(p.y * 10.0 + p.x * 8.0)); col = alb * (0.28 + 0.82 * diff) + vec3(1.0) * spec * 0.48; } else if (tPl < 1e4) { vec3 p = ro + rd * tPl; float rWorld = length(p); // Conical frustum radius grows linearly with ray distance t float coneR = tPl * 0.0045 * ipeGain; float coneVar = coneR * coneR; if (isContract) { // Left: Mip-NeRF 360 contracted space visualization (shows ||x||=1 core boundary + contracted radial shells!) vec3 pc = contract360(p); float rc = length(pc); float unitBoundary = exp(-abs(rWorld - 1.0) * 14.0); float shells = smoothstep(0.08, 0.02, abs(fract(rc * 6.0) - 0.5)); float spokes = smoothstep(0.06, 0.015, abs(fract(atan(pc.z, pc.x) * 12.0 / 6.2831853) - 0.5)); vec3 zoneCol = (rWorld <= 1.0) ? vec3(0.16, 0.78, 0.94) : mix(vec3(0.18, 0.36, 0.78), vec3(0.82, 0.28, 0.76), clamp(rc - 1.0, 0.0, 1.0)); col = zoneCol * (0.25 + 0.55 * max(shells, spokes * 0.7) * gridGain); col += vec3(1.0, 0.84, 0.24) * unitBoundary * 1.35; col = mix(col, sky, 1.0 - exp(-tPl * 0.04)); } else { // Right: Anti-aliased conical IPE unbounded ground plane + subtle foreground reflection float pat = evalIPECheck(p.xz, coneVar); vec3 gCol = mix(vec3(0.14, 0.20, 0.28), vec3(0.74, 0.78, 0.84), pat); // Soft contact shadow under foreground orb float sh = smoothstep(0.32, 0.78, length(p.xz)); gCol *= (0.42 + 0.58 * sh); col = mix(gCol, sky, 1.0 - exp(-tPl * 0.055)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Neural Radiance Fields (NeRF)](https://texelatlas.vercel.app/t/nerf.md) ## Sources 1. [primary] Jonathan T. Barron, Ben Mildenhall, Dor Verbin, Pratul P. Srinivasan, Peter Hedman (2021) Mip-NeRF 360: Unbounded Anti-Aliased Neural Radiance Fields. arXiv preprint (cs.CV). https://arxiv.org/abs/2111.12077 (verified via arxiv on 2026-11-29) 2. [implementation] google-research (2022) google-research/multinerf. https://github.com/google-research/multinerf License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Mip-NeRF 360." https://texelatlas.vercel.app/t/mip-nerf-360/ (accessed 2026-12-01). --- id: "mip-splatting" title: "Mip-Splatting" domain: "capture" stage: "capture" realtime: "realtime" platforms: [cuda, desktop-gpu] year_introduced: 2023 inputs: [photos, camera-poses, point-cloud] outputs: [gaussians] style: "photoreal" dynamic: "static" cost: "medium" authority: "Yu et al., 2023" url: "https://texelatlas.vercel.app/t/mip-splatting/" sources_verified_at: "2026-11-29" --- # Mip-Splatting (Yu et al., 2023) > Fixes 3DGS aliasing under zoom changes by bounding Gaussian size with a 3D filter tied to sampling frequency and replacing the screen-space dilation with a 2D Mip filter. ## Reach for it when - gaussian splats flicker or alias when zooming out - splat renders look bloated at different resolutions - thin gaussians look too bright at distance - 3d gaussian scene breaks at different zoom levels ## How it works 3DGS adds a fixed screen-space dilation to every projected Gaussian, which over-brightens thin ones when zooming out and leaves strong aliasing when zooming in. Mip-Splatting attacks both. A 3D smoothing filter limits each Gaussian's maximum frequency based on the highest sampling rate it was observed at across training cameras, so primitives cannot become sharper than any view can resolve. At render time, the old dilation is swapped for a 2D box-like Mip filter that approximates the pixel's area integral, mimicking a physical pixel footprint. Both filters are convolved analytically into the Gaussian's covariance, so the rasteriser stays the same and cost is essentially unchanged. ## When to use it Choose it when the output will be viewed at different resolutions or focal lengths than training, e.g. zoom-out thumbnails or high-resolution close-ups. Prefer plain [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) when views match training and you want the broadest tool support, and [StopThePop (Sorted Gaussian Splatting)](https://texelatlas.vercel.app/t/stopthepop.md) for the orthogonal sort-popping problem. ## Cost medium — Same rasteriser as 3DGS; small extra cost from filter computation. Measured GPU Weight: 9.02× baseline (moderate) — 0.2796 ms median / 0.2832 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.36× baseline (moderate) — 0.117 ms median (2.39× faster on L4). Ampere A100 scaling: 5.89× baseline (light) — 0.1697 ms median (1.65× faster on A100). ## Failure modes - Filtered Gaussians slightly blur very fine texture at the training resolution - Does not fix popping from depth-sort order - Needs the stored per-Gaussian sampling-rate statistics, so older trained scenes must be retrained - Same floaters and non-surface geometry as 3DGS ## Dataflow - Inputs: photos, camera-poses, point-cloud - Outputs: gaussians - Platforms: cuda, desktop-gpu ## Presets ### Mip-Splatting — unregularized 3DGS zoom aliasing (left) vs 3D smoothing + 2D Mip filter (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ZOOM_DIST": 1, "P_MIP_FILTER": 0.35, "P_SPLAT_FREQ": 18, "P_SPLIT": 0.48 } ``` ```glsl const float P_ZOOM_DIST = 1.0; // P Camera Zoom [0.4, 2.2, 0.05] const float P_MIP_FILTER = 0.35; // P 2D Mip Filter s [0.05, 0.8, 0.02] const float P_SPLAT_FREQ = 18.0; // P Splat Density [10.0, 30.0, 1.0] const float P_SPLIT = 0.48; // P Raw 3DGS / MipSplat [0.0, 1.0, 0.02] vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isMip = screenX >= split; float zoom = clamp(P_ZOOM_DIST, 0.35, 2.4); float mipS = clamp(P_MIP_FILTER, 0.04, 0.85); float freq = clamp(floor(P_SPLAT_FREQ + 0.5), 10.0, 32.0); // Receding perspective plane tiled with thousands of fine anisotropic 3D Gaussian splats! // Far distance compresses splats below the Nyquist pixel sampling rate -> severe aliasing in raw 3DGS! vec3 ro = vec3(0.0, 0.95 * zoom, 2.2 * zoom - iTime * 0.45); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.12), -1.45)); vec3 sky = mix(vec3(0.035, 0.050, 0.082), vec3(0.10, 0.15, 0.24), smoothstep(-0.15, 0.5, uv.y)); vec3 col = sky; if (rd.y < -0.008) { float t = -ro.y / rd.y; if (t > 0.0 && t < 32.0) { vec3 p = ro + rd * t; vec2 gCoord = p.xz * (freq * 0.22); vec2 cell = floor(gCoord); vec2 f = fract(gCoord); // Pixel footprint in splat-grid space grows linearly with depth t and grazing angle 1/|rd.y| float pixFootprint = t * freq * 0.0024 / max(abs(rd.y), 0.06); // Gather 3x3 neighboring Gaussian splats on the receding surface vec3 accum = vec3(0.0); float wSum = 0.0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec2 nb = vec2(float(dx), float(dy)); vec2 cid = cell + nb; vec2 rnd = hash22(cid); vec2 center = nb + 0.2 + 0.6 * rnd; vec2 d = f - center; // Anisotropic splat covariance variance sigma^2 in cell space float sigBase = 0.018 + 0.014 * rnd.x; float gVal; if (!isMip) { // Left: Raw 3DGS with fixed small screen-space dilation (causes needle-like dilation & moire shimmer!) // Point-sampling a narrow Gaussian below pixel size aliases violently with depth float dilate = max(sigBase, 0.006); float aliasPhase = sin(cid.x * 1.7 + cid.y * 2.3 + iTime * 0.4); float shimmer = 1.0 + 0.85 * smoothstep(0.18, 1.1, pixFootprint) * aliasPhase; // Raw 3DGS without energy-preserving Mip compensation over-brightens/bloats distant splats gVal = exp(-0.5 * dot(d, d) / dilate) * clamp(shimmer, 0.15, 2.2); } else { // Right: Mip-Splatting (Yu et al. 2024): // Convolve 2D covariance with pixel-footprint Mip filter s*I AND normalize amplitude by sqrt(det0 / detMip)! float sigMip = sigBase + mipS * pixFootprint * pixFootprint * 0.35; float energyNorm = sqrt(sigBase / max(sigMip, 1e-5)); gVal = energyNorm * exp(-0.5 * dot(d, d) / max(sigMip, 1e-5)); } // Alternating vibrant teal/coral/gold splat albedo pattern to make aliasing unmistakable float pat = mod(cid.x + cid.y, 2.0); vec3 sCol = mix(vec3(0.14, 0.82, 0.90), vec3(0.98, 0.54, 0.18), pat); sCol = mix(sCol, vec3(0.95, 0.88, 0.32), step(0.75, rnd.y) * 0.65); accum += gVal * sCol; wSum += gVal; } } // Smooth analytical Mip-filtered far-field limit (average albedo of the tile distribution) vec3 meanAlb = vec3(0.58, 0.68, 0.52); float mipBlend = isMip ? smoothstep(0.35, 1.45, pixFootprint) : 0.0; vec3 splatSurface = mix(accum * 0.72 + vec3(0.04, 0.06, 0.10) * max(1.0 - wSum, 0.0), meanAlb * 0.76, mipBlend); // Subtle Nyquist horizon marker line where splat size drops below 1 pixel float nyquistLine = smoothstep(0.08, 0.015, abs(pixFootprint - 0.42)); splatSurface = mix(splatSurface, vec3(1.0, 0.92, 0.38), nyquistLine * 0.42); float fog = 1.0 - exp(-t * t * 0.0025); col = mix(splatSurface, sky, clamp(fog, 0.0, 0.90)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combination ideas - [Scale-consistent volumetric fog shafts through Mip-Splatting scenes](https://texelatlas.vercel.app/ideas/mip-splat-froxel-fog-occlusion/) ## Sources 1. [primary] Zehao Yu, Anpei Chen, Binbin Huang, Torsten Sattler, Andreas Geiger (2023) Mip-Splatting: Alias-free 3D Gaussian Splatting. arXiv preprint (cs.CV). https://arxiv.org/abs/2311.16493 (verified via arxiv on 2026-11-29) 2. [implementation] autonomousvision (2023) autonomousvision/mip-splatting. https://github.com/autonomousvision/mip-splatting License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Mip-Splatting." https://texelatlas.vercel.app/t/mip-splatting/ (accessed 2026-12-01). --- id: "mipmapping-anisotropic-filtering" title: "Mipmapping and anisotropic texture filtering" aliases: [trilinear filtering, EWA filtering, mip chain] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender] year_introduced: 1983 inputs: [texture, uv-atlas] outputs: [texture] style: "both" dynamic: "both" cost: "cheap" authority: "Williams, 1983" url: "https://texelatlas.vercel.app/t/mipmapping-anisotropic-filtering/" sources_verified_at: "2026-11-29" --- # Mipmapping and anisotropic texture filtering (Williams, 1983) > Texture minification fundamentals: a prefiltered mip pyramid chosen by screen-space derivatives (bilinear, trilinear), then anisotropic sampling that takes several taps along the footprint's long axis, with EWA as the high-quality reference. ## Reach for it when - textures shimmer and sparkle in the distance - ground texture blurry at grazing view angles - moire patterns on checkerboard or fine patterns - need to choose trilinear versus anisotropic sampling - alpha tested leaves vanish when far away ## How it works A mip chain stores the texture at half resolution repeatedly, each level a box or better prefiltered average. At shading time the hardware measures how many texels fall inside one pixel from the UV derivatives and picks level lambda = log2 of that footprint size; trilinear filtering blends the two nearest levels. The catch is that a pixel footprint on a receding floor is a long thin ellipse, while the mip level is sized for the long axis, so everything gets blurred in the short direction. Anisotropic filtering instead picks the level from the short axis and takes N taps spread along the long axis (N capped at 2x to 16x). Heckbert's elliptical weighted average fits an ellipse in texture space and sums texels with a Gaussian-like weight, the quality reference that hardware approximates. Compute-shader or ray-traced renderers must supply their own derivatives or ray differentials since implicit derivatives only exist in fragment quads. ## When to use it Always enable mipmaps on sampled colour textures; add 8x-16x anisotropy for ground, roads and walls seen at grazing angles. Use [Block texture compression (BC7 / ASTC)](https://texelatlas.vercel.app/t/block-texture-compression.md) or [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md) so the mip chain stays small. Prefer [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) or [Normal distribution filtering for specular antialiasing](https://texelatlas.vercel.app/t/normal-distribution-filtering.md) for normal maps and roughness, because plain averaged normals lose specular energy. Prefer virtual texturing or manual LOD when streaming matters more than filtering. For lookups inside ray-tracing shaders, compute ray differentials explicitly. ## Cost cheap — Hardware sampler cost; anisotropy multiplies texture taps and bandwidth by up to the max ratio. Measured GPU Weight: 2.64× baseline (light) — 0.0868 ms median / 0.0912 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.28× baseline (light) — 0.0362 ms median (2.4× faster on L4). Ampere A100 scaling: 1.9× baseline (feather) — 0.0547 ms median (1.59× faster on A100). ## Failure modes - Textures not generated or non-power-of-two edge cases leave shimmering at distance - Premultiplied alpha or sRGB data averaged in the wrong space darkens or tints lower mips - Alpha-tested foliage fades out in higher mips unless alpha coverage is preserved - Normal maps averaged naively flatten and remove highlights, see toksvig-mipmapping - Anisotropic filtering cannot fix derivative problems such as non-uniform control flow, producing seams at discontinuities - Tiled atlases bleed neighbour tiles into lower mips without gutters ## Engine support - babylonjs: builtin — `texture.anisotropicFilteringLevel = 16` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Textures/baseTexture.pure.ts, checked 2026-12-01) - blender: builtin — `Preferences > Viewport > Textures > Anisotropic Filtering` (evidence: https://docs.blender.org/manual/en/5.2/editors/preferences/viewport.html, checked 2026-12-01) — Viewport only. - godot: builtin — `BaseMaterial3D.texture_filter = TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC; Project Settings > Rendering > Textures > Default Filters > Anisotropic Filtering Level` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - metal: builtin — `MTLSamplerDescriptor.maxAnisotropy; MTLBlitCommandEncoder.generateMipmaps(for:)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlsamplerdescriptor.json, checked 2026-12-01) - threejs: builtin — `texture.anisotropy = renderer.capabilities.getMaxAnisotropy()` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/textures/Texture.js, checked 2026-12-01) - unity: builtin — `Texture Import Settings > Generate Mip Maps, Aniso Level; Texture.anisoLevel` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Texture-anisoLevel.html, checked 2026-12-01) - unreal: builtin — `Texture Editor > Level of Detail > Mip Gen Settings (TMGS_*) and Filter (Anisotropic / r.MaxAnisotropy)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/texture-format-support-and-settings-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `GPUSamplerDescriptor: mipmapFilter: 'linear', maxAnisotropy: 16` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Mip chain generation is manual (no built-in generateMipmaps). ## Dataflow - Inputs: texture, uv-atlas - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, blender ## Presets ### Mipmapping & Anisotropic Filtering — blurry isotropic trilinear mips (left) vs crisp multi-tap anisotropic filtering (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ANISO_TAPS": 8, "P_TEX_FREQ": 1.6, "P_CAM_PITCH": 0.22, "P_SPLIT": 0.48 } ``` ```glsl const float P_ANISO_TAPS = 8.0; // P Anisotropic Taps [2.0, 16.0, 2.0] const float P_TEX_FREQ = 1.60; // P Tile Frequency [0.8, 3.0, 0.1] const float P_CAM_PITCH = 0.22; // P Grazing Pitch [0.08, 0.45, 0.02] const float P_SPLIT = 0.48; // P Trilinear / Aniso Split [0.0, 1.0, 0.02] // Analytically band-limited procedural texture at a given isotropic mip level 'lod' vec3 evalTexMip(vec2 p, float lod) { float blur = exp2(max(lod, 0.0)) * 0.065; // Checkerboard filtered via analytical box/Gaussian attenuation per harmonic vec2 s = sin(p * 6.2831853); float att1 = exp(-blur * blur * 18.0); float att2 = exp(-blur * blur * 65.0); float chk = 0.5 + 0.5 * clamp((s.x * s.y) * 6.0, -1.0, 1.0) * att1; // Fine architectural grout lines & calibration target rings inside each tile vec2 f = fract(p) - 0.5; float r = length(f); float ring = exp(-pow((r - 0.26) / max(0.032 + blur * 0.4, 0.01), 2.0)) * att2; float lines = (exp(-pow(abs(f.x) / max(0.018 + blur * 0.35, 0.01), 2.0)) + exp(-pow(abs(f.y) / max(0.018 + blur * 0.35, 0.01), 2.0))) * 0.5 * att2; vec3 tileA = vec3(0.14, 0.20, 0.28); vec3 tileB = vec3(0.84, 0.82, 0.76); vec3 base = mix(tileA, tileB, chk); base = mix(base, vec3(0.96, 0.44, 0.14), clamp(ring, 0.0, 1.0)); base = mix(base, vec3(0.12, 0.78, 0.88), clamp(lines * 0.75, 0.0, 1.0)); return base; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useAniso = sx >= split; float freq = clamp(P_TEX_FREQ, 0.5, 4.0); float pitch = clamp(P_CAM_PITCH, 0.06, 0.55); int taps = int(clamp(floor(P_ANISO_TAPS + 0.5), 2.0, 16.0)); // Camera skimming low over an infinite textured corridor floor vec3 ro = vec3(0.28 * sin(iTime * 0.35), 0.52, iTime * 0.65); float cp = cos(pitch), sp = sin(pitch); vec3 rd0 = normalize(vec3(uv.x, uv.y, -1.35)); vec3 rd = vec3(rd0.x, rd0.y * cp - rd0.z * sp, rd0.y * sp + rd0.z * cp); vec3 sky = mix(vec3(0.74, 0.82, 0.92), vec3(0.14, 0.28, 0.54), smoothstep(-0.02, 0.42, rd.y)); vec3 col = sky; if (rd.y < -0.002) { float t = -ro.y / rd.y; vec3 p = ro + rd * t; vec2 texUV = p.xz * freq; // Analytical screen-space footprint Jacobian (dUV/dx, dUV/dy) via adjacent ray differentials vec2 duvX = vec2(1.0 / max(iResolution.y, 1.0), 0.0); vec2 duvY = vec2(0.0, 1.0 / max(iResolution.y, 1.0)); vec3 rdX0 = normalize(vec3(uv.x + duvX.x, uv.y, -1.35)); vec3 rdX = vec3(rdX0.x, rdX0.y * cp - rdX0.z * sp, rdX0.y * sp + rdX0.z * cp); vec3 rdY0 = normalize(vec3(uv.x, uv.y + duvY.y, -1.35)); vec3 rdY = vec3(rdY0.x, rdY0.y * cp - rdY0.z * sp, rdY0.y * sp + rdY0.z * cp); vec2 pX = (ro + rdX * (-ro.y / min(rdX.y, -0.001))).xz * freq; vec2 pY = (ro + rdY * (-ro.y / min(rdY.y, -0.001))).xz * freq; vec2 ddx = pX - texUV; vec2 ddy = pY - texUV; float lenX = length(ddx); float lenY = length(ddy); float majorLen = max(lenX, lenY); float minorLen = max(min(lenX, lenY), 1e-5); vec2 majorAxis = (lenX >= lenY) ? ddx : ddy; if (!useAniso) { // Isotropic trilinear mipmap: picks LOD from major axis -> wipes out sharp detail along minor axis! float isoLod = log2(max(majorLen * 14.0, 1.0)); col = evalTexMip(texUV, isoLod); } else { // Anisotropic filtering: chooses LOD from minor axis and integrates N taps along major axis float maxAniso = float(taps); float ratio = min(majorLen / minorLen, maxAniso); float anisoLod = log2(max((majorLen / max(ratio, 1.0)) * 14.0, 1.0)); vec3 acc = vec3(0.0); for (int i = 0; i < 16; i++) { if (i >= taps) break; float fi = (float(i) + 0.5) / float(taps) - 0.5; acc += evalTexMip(texUV + majorAxis * fi, anisoLod); } col = acc / float(taps); } // Subtle distance aerial fade float fog = 1.0 - exp(-t * 0.042); col = mix(col, sky, clamp(fog, 0.0, 1.0)); } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md): Mipped normal-map lengths shrink with distance; Toksvig converts that loss into extra roughness at each level. ## Sources 1. [primary] Lance Williams (1983) Pyramidal parametrics. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/964967.801126 (verified via crossref on 2026-11-29) 2. [primary] Ned Greene, Paul Heckbert (1986) Creating Raster Omnimax Images from Multiple Perspective Views Using the Elliptical Weighted Average Filter. IEEE Computer Graphics and Applications. https://doi.org/10.1109/mcg.1986.276738 (verified via crossref on 2026-11-29) 3. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Image Texture (pbrt-v4). pbr-book.org. https://www.pbr-book.org/4ed/Textures_and_Materials/Image_Texture (verified via http on 2026-11-29) ## Cite this entry Texel. "Mipmapping and anisotropic texture filtering." https://texelatlas.vercel.app/t/mipmapping-anisotropic-filtering/ (accessed 2026-12-01). --- id: "modal-bessel-chladni-plate-vibration" title: "Analytical Modal Synthesis of Vibrating Circular Plates and Membranes" aliases: [Chladni eigenmode synthesis, Bessel modal vibration, analytical modal surface and sound synthesis] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, cpu] year_introduced: 1998 inputs: [mesh, particles] outputs: [animation, heightfield, particles] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Doel & Pai, 1998" url: "https://texelatlas.vercel.app/t/modal-bessel-chladni-plate-vibration/" sources_verified_at: "2026-11-30" --- # Analytical Modal Synthesis of Vibrating Circular Plates and Membranes (Doel & Pai, 1998) > Decompose circular membrane or plate vibration into analytical Bessel-function eigenmodes driven by independent damped harmonic oscillators, enabling exact real-time surface displacement, Chladni sand-grain migration, and synchronized audio. ## Reach for it when - simulate sand or particles collecting along acoustic cymatics nodal lines - compute standing wave vibration modes on circular drums or metal plates - drive real-time shader patterns and forces from audio resonance frequencies - morph smoothly between resonant chladni harmonic figures interactively - need analytic bessel eigenmode displacements without full fem simulation ## How it works Solving the 2D wave or biharmonic plate PDE on a fine grid at audio rates (several kilohertz) is expensive and prone to numerical dispersion. For canonical geometries like a clamped circular membrane or free circular Chladni plate, the linear vibration modes have closed-form analytical basis functions $\Phi_{m,n}(r, \theta) = J_m(\alpha_{m,n} r / R)\,\cos(m\theta + \phi)$ built from Bessel functions $J_m$ and their zeros $\alpha_{m,n}$. Instead of integrating a dense mesh, the solver advances a compact bank of $K$ (typically 20–40) decoupled modal oscillators, each tracking scalar displacement $q_k$ and velocity $\dot{q}_k$ with its natural frequency $\omega_k$, modal damping, and external exciter forcing. At any point $(r, \theta)$ on the surface, instantaneous height and vertical velocity are simply linear sums $\sum_k q_k \Phi_k(r,\theta)$ and $\sum_k \dot{q}_k \Phi_k(r,\theta)$. Because each mode evolves stably at fixed high-frequency substeps (e.g., 4,800 Hz), the same modal state simultaneously drives vertex displacement, audio synthesis at a virtual contact pickup, and GPU particle contacts where bouncing sand grains migrate off energetic antinodes and settle cleanly along quiet nodal rings and spokes. ## When to use it Choose it when simulating resonant acoustic plates, drumheads, Chladni sand figures, bells, or rigid-body impact audio where clean eigenmodes and exact frequency response matter. Prefer [position-based-dynamics](position-based-dynamics) or [xpbd](xpbd) when simulating large nonlinear deformations, folds, or tearing cloth where linear superposition breaks down. Prefer [fixed-timestep-integration](fixed-timestep-integration) with explicit finite differences on a grid when modeling arbitrary cut-out shapes without precomputed eigenmodes. ## Cost cheap — Advancing 30–40 scalar modal oscillators is negligible even at kilohertz substeps; GPU cost is dominated by evaluating the mode sum per particle or per display-field texel. Measured GPU Weight: 5.03× baseline (light) — 0.1579 ms median / 0.1623 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 4.04× baseline (light) — 0.0639 ms median (2.47× faster on L4). Ampere A100 scaling: 3.14× baseline (light) — 0.0905 ms median (1.74× faster on A100). ## Failure modes - Linear modal superposition assumes small displacements and breaks down under large nonlinear stretching, buckling, or plastic deformation - Truncating the modal bank to a finite number of modes omits high-frequency overtones and sharp localized impact transients - Analytical Bessel basis functions apply only to idealized circular/annular geometries; irregular plates require an offline finite-element eigenproblem solve - Uniformly tensioned membranes follow the wave equation while stiff metal Chladni plates follow the biharmonic equation with different overtone spacing and boundary conditions ## Dataflow - Inputs: mesh, particles - Outputs: animation, heightfield, particles - Platforms: webgpu, webgl2, desktop-gpu, cpu ## Presets ### Modal Bessel Chladni plate — analytical circular eigenmodes J_m(k r) cos(m θ) & sand nodal accumulation (glsl-fragment; rendered 2026-11-30) ```json { "P_MODE_M": 3, "P_MODE_N": 2, "P_SAND_DENSITY": 1, "P_MODE_MIX": 0.45 } ``` ```glsl const float P_MODE_M = 3.0; // P Angular Mode m [1.0, 7.0, 1.0] const float P_MODE_N = 2.0; // P Radial Mode n [1.0, 5.0, 1.0] const float P_SAND_DENSITY = 1.0; // P Sand Grains [0.2, 2.0, 0.05] const float P_MODE_MIX = 0.45; // P Dual-Mode Beat [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(234.34, 435.345)); p += dot(p, p + 34.23); return fract(p.x * p.y); } // Accurate cylindrical Bessel function J_m(x) via power series (small x) & Hankel asymptotic (large x) float besselJ(int m, float x) { float ax = max(abs(x), 1e-5); float fm = float(m); if (ax < 8.5) { float term = 1.0; for (int k = 1; k <= 7; k++) { if (k > m) break; term *= (0.5 * ax) / float(k); } float sum = term; float x2 = -0.25 * ax * ax; for (int k = 1; k <= 12; k++) { float fk = float(k); term *= x2 / (fk * (fk + fm)); sum += term; } return sum; } return sqrt(0.63661977 / ax) * cos(ax - fm * 1.5707963 - 0.78539816); } // Analytical circular Chladni eigenmode u(r, theta) = J_m(k_{m,n} * r) * cos(m * theta) float evalPlateMode(vec2 p, float mFloat, float nFloat, float t, float modeMix) { float r = length(p); float theta = atan(p.y, p.x); int m1 = int(clamp(floor(mFloat + 0.5), 1.0, 7.0)); int m2 = int(clamp(floor(mFloat + 2.5), 1.0, 7.0)); // Asymptotic McMahon root approximation for clamped/free circular plate radial wavenumber k_{m,n} float k1 = (nFloat + 0.5 * float(m1) - 0.15) * 3.14159265; float k2 = (max(nFloat - 0.5, 1.0) + 0.5 * float(m2) - 0.15) * 3.14159265; float u1 = besselJ(m1, k1 * r) * cos(float(m1) * (theta + t * 0.18)); float u2 = besselJ(m2, k2 * r) * cos(float(m2) * (theta - t * 0.14) + 0.65); float blend = modeMix * (0.5 + 0.5 * sin(t * 0.65)); return mix(u1, u2, blend) * 2.4; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float mF = clamp(P_MODE_M, 1.0, 7.0); float nF = clamp(P_MODE_N, 1.0, 5.0); float sandGain = clamp(P_SAND_DENSITY, 0.1, 2.2); float mMix = clamp(P_MODE_MIX, 0.0, 1.0); // Dark acoustic bench backdrop with subtle harmonic pressure ripples outside the brass plate float plateR = 0.43; float r = length(uv); vec3 col = mix(vec3(0.025, 0.032, 0.048), vec3(0.06, 0.075, 0.105), smoothstep(0.75, 0.25, r)); if (r > plateR) { float waveOut = sin((r - plateR) * 46.0 - iTime * 4.5) * exp(-(r - plateR) * 6.5); col += vec3(0.12, 0.34, 0.54) * max(waveOut, 0.0) * 0.45; } if (r < plateR) { vec2 p = uv / plateR; // Normalized unit disk coordinate float u = evalPlateMode(p, mF, nF, iTime, mMix); // Compute analytical surface gradient of vibrating mode for subtle specular deflection float eps = 0.008; float ux = evalPlateMode(p + vec2(eps, 0.0), mF, nF, iTime, mMix) - u; float uy = evalPlateMode(p + vec2(0.0, eps), mF, nF, iTime, mMix) - u; vec3 n = normalize(vec3(-ux * 1.4, -uy * 1.4, 1.0)); // Brushed spun-brass circular plate finish float radialGrain = 0.5 + 0.5 * sin(r * 420.0 + 2.0 * hash21(floor(fragCoord * 0.5))); vec3 brassBase = mix(vec3(0.24, 0.19, 0.12), vec3(0.42, 0.33, 0.20), radialGrain * 0.35); // Subtle modal phase tinting (positive antinodes warm gold, negative antinodes cool indigo) vec3 modeTint = (u >= 0.0) ? vec3(0.85, 0.52, 0.18) : vec3(0.18, 0.52, 0.85); vec3 plateAlb = mix(brassBase, modeTint, clamp(abs(u) * 0.36, 0.0, 0.45)); vec3 lDir = normalize(vec3(0.55, 0.72, 0.85)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir + vec3(0.0, 0.0, 1.0))), 0.0), 36.0); col = plateAlb * (0.34 + 0.78 * diff) + vec3(0.95, 0.84, 0.58) * spec * 0.45; // Fine white quartz sand grains accumulating sharply on Chladni nodal lines (|u| -> 0)! float nodalBand = exp(-abs(u) * 14.5); float fineNoise = hash21(floor(fragCoord * 0.85)); float grainNoise = hash21(floor(fragCoord * 1.45) + 17.3); float sandPile = smoothstep(0.18, 0.85, nodalBand * (0.65 + 0.85 * fineNoise) * sandGain); float sparseDust = step(0.82, grainNoise) * smoothstep(0.08, 0.55, nodalBand) * 0.55 * sandGain; vec3 sandCol = vec3(0.98, 0.96, 0.90) * (0.85 + 0.25 * grainNoise); col = mix(col, sandCol, clamp(sandPile + sparseDust, 0.0, 0.96)); // Central mechanical exciter bolt float dBolt = length(uv); col = mix(col, vec3(0.68, 0.72, 0.78), smoothstep(0.022, 0.015, dBolt)); col = mix(col, vec3(0.18, 0.20, 0.24), smoothstep(0.010, 0.006, dBolt)); } // Beveled metallic plate rim col = mix(col, vec3(0.85, 0.72, 0.46), smoothstep(px * 4.0, px * 0.8, abs(r - plateR)) * 0.92); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md): Evaluated modal height and velocity impulses bounce tens of thousands of sand grains toward quiet Chladni nodal patterns. - [Thin-film iridescence](https://texelatlas.vercel.app/t/thin-film-iridescence.md): Cycle-averaged modal amplitude gradients stir a 2D optical-thickness fluid layer to visualize resonances as iridescent soap fringes. ## Combination ideas - [Chladni-vibrated iridescent soap film](https://texelatlas.vercel.app/ideas/chladni-driven-iridescent-soap-film/) ## Sources 1. [primary] Kees van den Doel, Dinesh K. Pai (1998) The Sounds of Physical Shapes. Presence: Teleoperators and Virtual Environments. https://doi.org/10.1162/105474698565794 (verified via crossref on 2026-11-30) 2. [primary] James F. O'Brien, Chen Shen, Christine M. Gatchalian (2002) Synthesizing sounds from rigid-body simulations. Proceedings of the 2002 ACM SIGGRAPH/Eurographics symposium on Computer animation. https://doi.org/10.1145/545261.545290 (verified via crossref on 2026-11-30) 3. [implementation] mrdoob (2026) mrdoob/codevember-2026. https://github.com/mrdoob/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Analytical Modal Synthesis of Vibrating Circular Plates and Membranes." https://texelatlas.vercel.app/t/modal-bessel-chladni-plate-vibration/ (accessed 2026-12-01). --- id: "model-synthesis" title: "Model Synthesis" aliases: [example-based model synthesis, Merrell model synthesis] domain: "procgen" stage: "procedural" realtime: "offline" platforms: [cpu, python] year_introduced: 2007 inputs: [voxels, mesh] outputs: [voxels, mesh] style: "both" dynamic: "static" cost: "offline" authority: "Merrell, 2007" url: "https://texelatlas.vercel.app/t/model-synthesis/" sources_verified_at: "2026-11-29" --- # Model Synthesis (Merrell, 2007) > Generates large 3D models from a small example by growing the output in modifiable chunks while ensuring every local neighbourhood appears in the input; the direct predecessor of WFC. ## Reach for it when - need to generate large buildings from a small example model - want constraint-controlled 3d structure generation - wave collapse fails on very large outputs - synthesise architecture that follows user constraints ## How it works The example model is analysed into local neighbourhood relations: which cell labels may be adjacent along each axis. The output volume is initialised with all labels possible, then filled by an order of assignment (e.g. one chunk or slice at a time) where each cell chooses a label compatible with already-assigned neighbours; constraint propagation removes impossible labels from unassigned cells. Merrell's insight was to modify small regions at a time so a dead end only forces re-doing that region (a limited form of local backtracking), keeping the process tractable. The 2007 paper applies it to polyhedral structures with adjacency via shared faces; the 2011 follow-up extends it to a general procedural modeling algorithm and adds user constraints like shape, connectivity and symmetries. ## When to use it Choose it for 3D structure generation (buildings, architecture, bridges) from an example model with explicit user constraints, or when you want a deterministic, chunked solver for very large outputs. Prefer [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) for entropy-driven, mostly 2D tile and bitmap synthesis with huge community tooling, and [CGA Shape Grammar (Procedural Buildings)](https://texelatlas.vercel.app/t/cga-shape-grammar.md) when buildings should follow an explicit grammar instead of an example. ## Cost offline — Dominated by constraint propagation across the volume; scaled by chunk size and example complexity. Measured GPU Weight: 66.39× baseline (extreme) — 2.1842 ms median / 2.2517 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 61.92× baseline (extreme) — 0.9846 ms median (2.22× faster on L4). Ampere A100 scaling: 44.39× baseline (heavy) — 1.2785 ms median (1.71× faster on A100). ## Failure modes - Output only reproduces local patterns of the input, so large-scale composition is incoherent without extra constraints - Poorly chosen adjacency relations over-constrain the solver and yield contradictions - Chunked solving can show seams or repeated motifs at chunk boundaries - Needs cleanly voxelised or grid-aligned examples: arbitrary meshes need a labelling step ## Dataflow - Inputs: voxels, mesh - Outputs: voxels, mesh - Platforms: cpu, python ## Presets ### Model Synthesis — adjacency-constrained tile graph (left) vs grown 3D modular city blocks (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CITY_SCALE": 2.2, "P_CHUNK_WAVE": 0.85, "P_CAM_ORBIT": 0.35, "P_SPLIT": 0.46 } ``` ```glsl const float P_CITY_SCALE = 2.2; // P Module Density [1.2, 3.6, 0.1] const float P_CHUNK_WAVE = 0.85; // P Chunk Growth [0.2, 1.0, 0.02] const float P_CAM_ORBIT = 0.35; // P Orbit Speed [0.0, 1.8, 0.05] const float P_SPLIT = 0.46; // P Adjacency / 3D City [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Adjacency-consistent architectural module selector (Merrell 2007 Model Synthesis): // Guarantees roads align seamlessly with neighbors, courtyards border towers, and bridges span canals! vec2 evalModule(vec2 cell) { // Periodic road & canal spines guarantee global topological connectivity across chunks float isRoadX = step(abs(mod(cell.y + 2.0, 4.0) - 2.0), 0.1); float isRoadZ = step(abs(mod(cell.x + 2.0, 4.0) - 2.0), 0.1); if (isRoadX + isRoadZ > 0.5) { return vec2(0.06, 1.0); // 1 = road/plaza tile } // Inside city blocks, neighbor-coherent tower height from smoothed hash float h = hash21(cell); float hNbr = hash21(cell + vec2(1.0, 0.0)); float tiers = floor(mix(h, hNbr, 0.35) * 4.0 + 1.0); float height = 0.16 + tiers * 0.18; float kind = (tiers >= 3.0) ? 3.0 : 2.0; // 2 = mid-rise terrace, 3 = spire tower return vec2(height, kind); } vec2 mapCity(vec3 p, float scale) { vec2 g = p.xz * scale; vec2 cell = floor(g); vec2 f = fract(g) - 0.5; vec2 modInfo = evalModule(cell); // Ground plaza plane vec2 res = vec2(p.y + 0.45, 1.0); // Extruded architectural module box inside each grid cell float halfW = (modInfo.y > 2.5) ? 0.34 : 0.41; vec3 b = vec3(halfW / scale, modInfo.x, halfW / scale); vec3 lp = vec3(f.x / scale, p.y + 0.45 - modInfo.x, f.y / scale); vec3 q = abs(lp) - b; float dBox = length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - 0.008; // Limit step size near cell boundaries for artifact-free raymarching across grid float edgeLim = (0.5 - max(abs(f.x), abs(f.y))) / scale + 0.04; float dMod = min(dBox, edgeLim); if (dMod < res.x) res = vec2(dMod, modInfo.y); return res; } vec3 calcNormal(vec3 p, float scale) { vec2 e = vec2(0.004, 0.0); return normalize(vec3( mapCity(p + e.xyy, scale).x - mapCity(p - e.xyy, scale).x, mapCity(p + e.yxy, scale).x - mapCity(p - e.yxy, scale).x, mapCity(p + e.yyx, scale).x - mapCity(p - e.yyx, scale).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isGraph = screenX < split; float scale = clamp(P_CITY_SCALE, 1.0, 3.8); float chunkW = clamp(P_CHUNK_WAVE, 0.15, 1.0); float spin = iTime * max(P_CAM_ORBIT, 0.0) * 0.35; vec3 ro = vec3(0.0, 1.55, 2.65); vec3 rd = normalize(vec3(uv.x, uv.y - 0.44, -1.35)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 sky = mix(vec3(0.86, 0.72, 0.58), vec3(0.16, 0.32, 0.58), smoothstep(-0.08, 0.52, rd.y)); vec3 col = sky; float t = 0.2; vec2 hit = vec2(1e5, 0.0); for (int i = 0; i < 68; i++) { vec2 h = mapCity(ro + rd * t, scale); if (h.x < 0.004) { hit = vec2(t, h.y); break; } t += max(h.x * 0.72, 0.015); if (t > 12.0) break; } if (hit.x < 1e4) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p, scale); vec3 sunDir = normalize(vec3(0.62, 0.75, 0.42)); float diff = max(dot(n, sunDir), 0.0); vec2 g = p.xz * scale; vec2 cell = floor(g); vec2 f = fract(g); vec2 dCell = min(f, 1.0 - f); float gridLine = smoothstep(0.06, 0.015, min(dCell.x, dCell.y)); if (isGraph) { // Left: Modifiable-chunk tile-adjacency state visualization (color-coded by tile prototype & chunk boundary) vec3 tileCol = vec3(0.14, 0.24, 0.36); if (hit.y > 1.5 && hit.y < 2.5) tileCol = vec3(0.18, 0.72, 0.88); else if (hit.y > 2.5) tileCol = vec3(0.96, 0.58, 0.20); // Chunk boundary box highlight every 4x4 modules vec2 chunkF = fract(cell / 4.0); float chunkEdge = smoothstep(0.08, 0.02, min(min(chunkF.x, 1.0 - chunkF.x), min(chunkF.y, 1.0 - chunkF.y))); float scan = exp(-abs(length(p.xz) - fract(iTime * 0.18) * 3.8 * chunkW) * 6.0); col = tileCol * (0.38 + 0.72 * diff) + vec3(0.95, 0.98, 1.0) * gridLine * 0.35 + vec3(0.24, 1.0, 0.76) * (chunkEdge * 0.35 + scan * 0.45); } else { // Right: Shaded modular limestone/terracotta synthesized city with lit window facades! vec3 alb = vec3(0.32, 0.34, 0.38); // road plaza if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.84, 0.76, 0.66); else if (hit.y > 2.5) alb = vec3(0.76, 0.64, 0.54); // Terracotta rooftop cap if (n.y > 0.8 && hit.y > 1.5) alb = mix(alb, vec3(0.76, 0.36, 0.24), 0.72); // Procedural facade windows on vertical walls float winMask = 0.0; if (abs(n.y) < 0.3 && hit.y > 1.5) { vec2 wUV = fract(vec2((p.x + p.z) * scale * 4.0, p.y * 12.0)); winMask = step(0.24, wUV.x) * step(wUV.x, 0.76) * step(0.25, wUV.y) * step(wUV.y, 0.78); alb = mix(alb, vec3(0.14, 0.22, 0.32), winMask * 0.75); } col = alb * (0.26 + 0.88 * diff) + vec3(0.98, 0.80, 0.42) * winMask * 0.18; } col = mix(col, sky, 1.0 - exp(-hit.x * 0.075)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) ## Combination ideas - [Prompted kits, synthesised levels](https://texelatlas.vercel.app/ideas/prompted-modular-level-kits/) ## Sources 1. [primary] Paul Merrell (2007) Example-based model synthesis. Proceedings of the 2007 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1230100.1230119 (verified via crossref on 2026-11-29) 2. [primary] P Merrell, D Manocha (2011) Model Synthesis: A General Procedural Modeling Algorithm. IEEE Transactions on Visualization and Computer Graphics. https://doi.org/10.1109/tvcg.2010.112 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Model Synthesis." https://texelatlas.vercel.app/t/model-synthesis/ (accessed 2026-12-01). --- id: "moge" title: "MoGe (Monocular Geometry Estimation)" aliases: [MoGe] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [photos] outputs: [point-cloud, depth, normals] style: "photoreal" dynamic: "both" cost: "medium" authority: "Wang et al., 2024" url: "https://texelatlas.vercel.app/t/moge/" sources_verified_at: "2026-11-29" --- # MoGe (Monocular Geometry Estimation) (Wang et al., 2024) > Predicts an affine-invariant 3D point map from a single image, from which depth, normals, mask and field of view are derived, trained with optimal-alignment and multi-scale geometry losses. ## Reach for it when - want a point cloud and normals from one photo - need camera field of view estimated from an image - single-image geometry that stays clean at edges - recover 3d points without multiple views - estimate intrinsics along with depth ## How it works MoGe takes an image through a DINOv2 ViT and predicts, for every pixel, a 3D point in camera space, defined only up to an unknown global scale and shift. Training handles this ambiguity with a robust optimal alignment step that finds the best shift and scale for the prediction before comparing it to ground truth, using a strategy that limits the influence of outliers. Additional multi-scale local geometry losses encourage correct local surface shape, not just correct global positions. Because the output is a point map, camera focal length and a field-of-view estimate can be recovered by a fit, and normals computed from the surface. A later MoGe-2 variant adds metric scale. ## When to use it Choose it when you need clean single-image geometry with intrinsics, such as a point cloud or normals for a photo. Prefer [Depth Pro](https://texelatlas.vercel.app/t/depth-pro.md) when you need metric depth, [Depth Anything V2](https://texelatlas.vercel.app/t/depth-anything-v2.md) for fast relative depth, and [VGGT (Visual Geometry Grounded Transformer)](https://texelatlas.vercel.app/t/vggt.md) for multi-view data. Its normals can be integrated with [Bilateral Normal Integration](https://texelatlas.vercel.app/t/bilateral-normal-integration.md). ## Cost medium — Single ViT forward pass; interactive on a modern GPU. ## Failure modes - Scale and shift are ambiguous in the base model, so point clouds are not metric - Thin structures, glass and mirrors produce wrong geometry - Per-frame inference is temporally inconsistent in video - Check repo for weight licences before commercial use ## Dataflow - Inputs: photos - Outputs: point-cloud, depth, normals - Platforms: cuda, python ## Combination ideas - [Bounce light inside a photograph](https://texelatlas.vercel.app/ideas/photo-bounce-relighting/) ## Sources 1. [primary] Ruicheng Wang, Sicheng Xu, Cassie Dai, Jianfeng Xiang, Yu Deng, Xin Tong, Jiaolong Yang (2024) MoGe: Unlocking Accurate Monocular Geometry Estimation for Open-Domain Images with Optimal Training Supervision. arXiv preprint (cs.CV). https://arxiv.org/abs/2410.19115 (verified via arxiv on 2026-11-29) 2. [implementation] microsoft (2024) microsoft/MoGe. https://github.com/microsoft/MoGe License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "MoGe (Monocular Geometry Estimation)." https://texelatlas.vercel.app/t/moge/ (accessed 2026-12-01). --- id: "moller-trumbore-ray-triangle" title: "Möller–Trumbore ray-triangle intersection" aliases: [Moller-Trumbore, MT intersection] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, cuda] year_introduced: 1997 inputs: [mesh] outputs: [depth] style: "both" dynamic: "both" cost: "cheap" authority: "Möller & Trumbore, 1997" url: "https://texelatlas.vercel.app/t/moller-trumbore-ray-triangle/" sources_verified_at: "2026-11-29" --- # Möller–Trumbore ray-triangle intersection (Möller & Trumbore, 1997) > Tests a ray against a triangle by solving for the hit distance and two barycentric coordinates in one go, with no precomputed plane and no extra per-triangle storage beyond the three vertices. ## Reach for it when - need to know which triangle a mouse ray hits - ray casting against a triangle mesh for picking - getting barycentric coordinates of a ray hit - writing my own ray tracer leaf test - cpu raycast misses thin triangle edges ## How it works A point on the triangle is `A + u(B-A) + v(C-A)`, and a point on the ray is `O + tD`. Setting them equal gives a 3x3 linear system in (t, u, v). Cramer's rule solves it with two cross products and a handful of dot products: one cross of the ray direction with an edge yields the determinant, and a second cross yields the numerators for v and t. The determinant also tells you whether the ray is parallel to the triangle. You reject early when u falls outside [0,1] or u+v exceeds 1, so most misses cost one cross product. The result is the distance t plus barycentrics, which you can reuse to interpolate normals, UVs or vertex colours. Because it stores nothing but the vertices it fits mesh storage as-is, which is why BVH leaves in CPU and GPU tracers use it as the primitive test. ## When to use it Choose it as the default leaf test for ray tracing, picking and CPU collision queries over triangle soups. Prefer [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md) when you want it already wired into a BVH for three.js picking, and [SAH BVH construction](https://texelatlas.vercel.app/t/sah-bvh-construction.md) for the acceleration structure around it. Prefer watertight intersection variants when thin-edge leaks between adjacent triangles are unacceptable. Prefer [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md) when the surface is an SDF instead of a mesh. ## Cost cheap — A few dozen flops per test; in practice traversal and memory access dominate, not this test. Measured GPU Weight: 5.73× baseline (light) — 0.1885 ms median / 0.1913 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 4.62× baseline (light) — 0.0734 ms median (2.57× faster on L4). Ampere A100 scaling: 3.56× baseline (light) — 0.1024 ms median (1.84× faster on A100). ## Failure modes - Rays passing exactly through a shared edge or vertex can slip through both neighbouring triangles because of rounding, leaving pinholes - Grazing rays with a tiny determinant give noisy t and barycentrics; the epsilon threshold also discards legitimate near-parallel hits - Self-intersection acne when secondary rays start on a surface without an offset or t-min - Single-precision error grows far from the origin, so large world coordinates make hits jitter unless vertices are rebased ## Engine support - babylonjs: builtin — `ray.intersectsTriangle() / scene.pick` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Culling/ray.core.ts, checked 2026-12-01) - blender: builtin — `Cycles ray-triangle intersection kernel in intern/cycles/kernel/geom/triangle_intersect.h` (evidence: https://github.com/blender/blender/blob/main/intern/cycles/kernel/geom/triangle_intersect.h, checked 2026-12-01) - godot: builtin — `Geometry3D.ray_intersects_triangle(from, dir, a, b, c)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/core/math/geometry_3d.h, checked 2026-12-01) — Engine source implements the Moller-Trumbore edge/determinant form. - threejs: builtin — `Ray.intersectTriangle() / Raycaster` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/math/Ray.js, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: depth - Platforms: cpu, webgl2, webgpu, desktop-gpu, cuda ## Presets ### Möller–Trumbore picking a spinning tetrahedron (glsl-fragment; rendered 2026-11-29) ```json { "eps": 0.000001, "spin": 0.6 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Moller-Trumbore ray/triangle test on a spinning tetrahedron. const float EPS = 1e-6; const float SPIN = 0.6; bool mollerTrumbore(vec3 o, vec3 d, vec3 a, vec3 b, vec3 c, out float t, out vec2 uv) { vec3 e1 = b - a, e2 = c - a; vec3 p = cross(d, e2); float det = dot(e1, p); if (abs(det) < EPS) return false; // ray parallel to triangle plane float inv = 1.0 / det; vec3 s = o - a; float u = dot(s, p) * inv; if (u < 0.0 || u > 1.0) return false; vec3 q = cross(s, e1); float v = dot(d, q) * inv; if (v < 0.0 || u + v > 1.0) return false; t = dot(e2, q) * inv; uv = vec2(u, v); return t > EPS; } mat3 rotY(float a) { float c = cos(a), s = sin(a); return mat3(c, 0., -s, 0., 1., 0., s, 0., c); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.6, 3.2); vec3 rd = normalize(vec3(p, -1.6)); mat3 R = rotY(iTime * SPIN); vec3 V[4]; V[0] = R * vec3( 1.0, -0.7, 0.8); V[1] = R * vec3(-1.0, -0.7, 0.8); V[2] = R * vec3( 0.0, -0.7, -1.0); V[3] = R * vec3( 0.0, 1.0, 0.0); int I[12] = int[12](0,2,1, 0,1,3, 1,2,3, 2,0,3); float best = 1e9; vec3 col = mix(vec3(0.05, 0.07, 0.12), vec3(0.35, 0.45, 0.6), p.y + 0.5); for (int f = 0; f < 4; f++) { vec3 a = V[I[3*f]], b = V[I[3*f+1]], c = V[I[3*f+2]]; float t; vec2 uv; if (mollerTrumbore(ro, rd, a, b, c, t, uv) && t < best) { best = t; vec3 n = normalize(cross(b - a, c - a)); float lit = 0.25 + 0.75 * max(dot(n, normalize(vec3(0.5, 0.8, 0.6))), 0.0); vec3 base = 0.5 + 0.5 * cos(6.2831 * (float(f) / 4.0 + vec3(0.0, 0.33, 0.67))); float w = 1.0 - uv.x - uv.y; float edge = smoothstep(0.0, 0.04, min(min(uv.x, uv.y), w)); col = base * lit * mix(0.35, 1.0, edge); } } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [SAH BVH construction](https://texelatlas.vercel.app/t/sah-bvh-construction.md): The BVH culls most triangles and hands the surviving leaves to the Möller–Trumbore test. - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): Provides ray, closest-point and shape casts over indexed meshes using this test at the leaves. ## Sources 1. [primary] Tomas Möller, Ben Trumbore (1997) Fast, Minimum Storage Ray-Triangle Intersection. Journal of Graphics Tools. https://doi.org/10.1080/10867651.1997.10487468 (verified via crossref on 2026-11-29) 2. [implementation] gkjohnson (2018) gkjohnson/three-mesh-bvh. https://github.com/gkjohnson/three-mesh-bvh License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Möller–Trumbore ray-triangle intersection." https://texelatlas.vercel.app/t/moller-trumbore-ray-triangle/ (accessed 2026-12-01). --- id: "moment-shadow-maps" title: "Moment Shadow Maps" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2015 inputs: [depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Peters & Klein, 2015" url: "https://texelatlas.vercel.app/t/moment-shadow-maps/" sources_verified_at: "2026-11-29" --- # Moment Shadow Maps (Peters & Klein, 2015) > Stores four power moments of depth per texel so that filtered shadow maps give a tight bound on visibility, avoiding most of the light bleeding of variance shadow maps. ## Reach for it when - variance shadow maps still leak light - need filterable shadows with accurate occlusion - soft shadow prefiltering without bleeding artifacts - high quality blurred shadows on modest gpu memory ## How it works Where VSM keeps two moments, moment shadow mapping stores the first four (z, z^2, z^3, z^4), usually after a small optimised linear transform that improves quantisation in 16-bit targets. Moments are linear, so the map is blurred or mipmapped like any texture. At shade time the filtered moments define a canonical distribution, and a short closed-form solve (a Cholesky decomposition and a quadratic or cubic root find) yields the extremal fraction of the footprint that can be in front of the receiver, which is the shadow intensity. The extra moments encode more of the depth histogram than a mean and variance, which is why overlapping occluders no longer produce large leaks. ## When to use it Choose it when you want filterable soft shadows and plain VSM or EVSM bleed visibly, and you can afford a four-channel target. Prefer [Exponential Variance Shadow Maps](https://texelatlas.vercel.app/t/exponential-variance-shadow-maps.md) when you prefer simpler shader maths, [Percentage-Closer Soft Shadows](https://texelatlas.vercel.app/t/percentage-closer-soft-shadows.md) for contact hardening, and [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) when a depth-only map is mandatory. ## Cost cheap — Four channels per texel plus a blur pass; shading includes a small per-pixel solve, more arithmetic than VSM. Measured GPU Weight: 6.7× baseline (moderate) — 0.2203 ms median / 0.2353 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.85× baseline (moderate) — 0.1089 ms median (2.02× faster on L4). Ampere A100 scaling: 4.77× baseline (light) — 0.1375 ms median (1.6× faster on A100). ## Failure modes - Residual leaks and ringing when the moment problem is near-singular - Needs a positive bias on moments to keep the solver stable - Higher memory per cascade than VSM - Float16 storage requires the paper's optimised transform ## Engine support - unity: builtin — `HDRP Asset > Lighting > Shadows > Directional Shadow Filtering = Improved Moment Shadows` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs, checked 2026-12-01) — HDRP only, directional lights (Improved Moment Shadows). ## Dataflow - Inputs: depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Moment Shadow Maps (MSM) — 2-moment VSM light bleeding under stacked occluders (left) vs 4-moment Hamburger MSM (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FILTER_RAD": 0.75, "P_LIGHT_SWEEP": 0.55, "P_BLEED_DEMO": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_FILTER_RAD = 0.75; // P Filter Penumbra [0.2, 1.5, 0.05] const float P_LIGHT_SWEEP = 0.55; // P Light Motion [0.0, 1.6, 0.05] const float P_BLEED_DEMO = 0.85; // P Occluder Depth Gap [0.2, 1.2, 0.05] const float P_SPLIT = 0.48; // P VSM Bleed / 4-MSM [0.0, 1.0, 0.02] // Evaluate light-space depth map of two vertically stacked occluders (classic VSM light-bleeding stress test!) float shadowDepthMap(vec2 lp, float gap) { float zFloor = 2.60; // Upper floating slab at closer depth (z = 1.15 - gap * 0.35) float dTop = max(abs(lp.x - 0.14) - 0.32, abs(lp.y - 0.04) - 0.22); // Lower bar closer to floor (z = 2.05) overlapping upper slab's penumbra! float dBot = max(abs(lp.x + 0.10) - 0.42, abs(lp.y + 0.02) - 0.26); float z = zFloor; if (dBot < 0.0) z = min(z, 2.02); if (dTop < 0.0) z = min(z, 1.12 - gap * 0.32); return z; } // 4-moment Hamburger Moment Shadow Map closed-form Cholesky + quadratic solver (Peters & Klein 2015) float computeMSM4(vec4 b, float zf) { // Small bias toward uniform distribution for numerical stability float alpha = 0.002; vec4 m = mix(b, vec4(0.5, 0.333333, 0.25, 0.2), alpha); float L21D11 = m.y - m.x * m.x; float D11 = max(L21D11, 1e-5); float L21 = (m.z - m.x * m.y) / D11; float D22 = max(m.w - m.y * m.y - L21 * (m.z - m.x * m.y), 1e-5); // Solve symmetric positive-definite 3x3 Hankel system for quadratic c0 + c1*z + c2*z^2 = 0 vec3 zVec = vec3(1.0, zf, zf * zf); float c0 = zVec.x; float c1 = (zVec.y - m.x * c0) / D11; float c2 = (zVec.z - m.y * c0 - (m.z - m.x * m.y) * c1) / D22; float p1 = c1 - L21 * c2; float p0 = c0 - m.x * p1 - m.y * c2; // Find roots z2, z3 of p2*z^2 + p1*z + p0 = 0 float A = c2; float B = p1; float C = p0; float disc = max(B * B - 4.0 * A * C, 0.0); float sD = sqrt(disc); float r1 = (-B - sD) / (2.0 * A + sign(A) * 1e-6); float r2 = (-B + sD) / (2.0 * A + sign(A) * 1e-6); float z2 = min(r1, r2); float z3 = max(r1, r2); if (zf <= z2) return 0.0; if (zf <= z3) { float num = zf * z3 - m.x * (zf + z3) + m.y; float den = max((z3 - z2) * (zf - z2), 1e-5); return clamp(num / den, 0.0, 1.0); } float num = z2 * z3 - m.x * (z2 + z3) + m.y; float den = max((zf - z2) * (zf - z3), 1e-5); return clamp(1.0 - num / den, 0.0, 1.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float filtR = clamp(P_FILTER_RAD, 0.15, 1.6) * 0.09; float gap = clamp(P_BLEED_DEMO, 0.15, 1.3); float t = iTime * max(P_LIGHT_SWEEP, 0.0); vec3 ro = vec3(0.0, 0.95, 1.85); vec3 rd = normalize(vec3(uv.x, uv.y - 0.42, -1.35)); vec3 lDir = normalize(vec3(0.24 * sin(t * 0.6), 0.95, 0.18 * cos(t * 0.5))); vec3 col = mix(vec3(0.08, 0.11, 0.17), vec3(0.22, 0.30, 0.44), smoothstep(-0.3, 0.5, uv.y)); // Intersect receiver courtyard floor (y = -0.45) and the two floating caster slabs float tMin = 1e5; int hitId = 0; vec3 hp = vec3(0.0); vec3 hn = vec3(0.0, 1.0, 0.0); if (rd.y < -0.005) { float tf = (-0.45 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { tMin = tf; hitId = 1; hp = ro + rd * tf; hn = vec3(0.0, 1.0, 0.0); } } // Two floating occluder slabs above the floor vec3 invR = 1.0 / (rd + vec3(1e-6)); for (int k = 0; k < 2; k++) { vec3 bc = (k == 0) ? vec3(-0.10, 0.08, 0.02) : vec3(0.14, 0.56 + gap * 0.16, -0.04); vec3 br = (k == 0) ? vec3(0.36, 0.045, 0.22) : vec3(0.28, 0.045, 0.18); vec3 t0 = (bc - br - ro) * invR; vec3 t1 = (bc + br - ro) * invR; vec3 tn = min(t0, t1), tf = max(t0, t1); float tNear = max(max(tn.x, tn.y), tn.z); float tFar = min(min(tf.x, tf.y), tf.z); if (tFar > max(tNear, 0.05) && tNear < tMin) { tMin = tNear; hitId = 2 + k; hp = ro + rd * tNear; vec3 lp = (hp - bc) / br; vec3 ap = abs(lp); hn = (ap.x > ap.y && ap.x > ap.z) ? vec3(sign(lp.x), 0.0, 0.0) : (ap.y > ap.z ? vec3(0.0, sign(lp.y), 0.0) : vec3(0.0, 0.0, sign(lp.z))); } } if (hitId == 1) { // Project floor point into light-space coordinates & integrate 5x5 pre-filtered shadow moments! vec2 lp = hp.xz + (hp.y + 0.45) * lDir.xz / max(lDir.y, 0.2) + vec2(0.16 * sin(t * 0.6), 0.08 * cos(t * 0.5)); float zNorm = 0.84; // Normalized depth of receiver floor in [0, 1] vec4 moments = vec4(0.0); float wSum = 0.0; for (int j = -2; j <= 2; j++) { for (int i = -2; i <= 2; i++) { vec2 off = vec2(float(i), float(j)) * filtR * 0.55; float zRaw = shadowDepthMap(lp + off, gap); float z = clamp(zRaw / 3.0, 0.05, 0.98); float w = exp(-dot(vec2(float(i), float(j)), vec2(float(i), float(j))) * 0.26); moments += vec4(z, z * z, z * z * z, z * z * z * z) * w; wSum += w; } } moments /= max(wSum, 1e-4); float lit = 1.0; if (screenX < split) { // Left: 2-Moment Variance Shadow Map (Chebyshev inequality -> severe light bleeding between stacked occluders!) float mu = moments.x; float variance = max(moments.y - mu * mu, 0.0004); float d = max(zNorm - mu, 0.0); float pMax = variance / (variance + d * d); lit = (zNorm <= mu + 0.005) ? 1.0 : pMax; } else { // Right: 4-Moment Hamburger Moment Shadow Map -> tight upper bound eliminates light bleeding! float occ = computeMSM4(moments, zNorm); lit = 1.0 - occ; } vec2 g = hp.xz * 3.0; float chk = mod(floor(g.x) + floor(g.y), 2.0); vec3 floorAlb = mix(vec3(0.62, 0.60, 0.56), vec3(0.82, 0.80, 0.75), chk); col = floorAlb * (vec3(0.18, 0.24, 0.34) + vec3(1.25, 1.14, 0.96) * lit); col = mix(vec3(0.08, 0.11, 0.17), col, exp(-tMin * 0.12)); } else if (hitId >= 2) { vec3 alb = (hitId == 2) ? vec3(0.24, 0.62, 0.84) : vec3(0.92, 0.48, 0.22); float ndl = max(dot(hn, lDir), 0.0); col = alb * (0.26 + 0.92 * ndl); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Variance Shadow Maps](https://texelatlas.vercel.app/t/variance-shadow-maps.md) ## Combination ideas - [Fog shafts that do not flicker](https://texelatlas.vercel.app/ideas/prefiltered-shadows-in-fog/) ## Sources 1. [primary] Christoph Peters, Reinhard Klein (2015) Moment shadow mapping. Proceedings of the 19th Symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/2699276.2699277 (verified via crossref on 2026-11-29) 2. [tutorial] Christoph Peters Moment Shadow Mapping. momentsingraphics.de. https://momentsingraphics.de/I3D2015.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Moment Shadow Maps." https://texelatlas.vercel.app/t/moment-shadow-maps/ (accessed 2026-12-01). --- id: "motion-matching" title: "Motion matching" domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, unity, unreal, godot] year_introduced: 2016 inputs: [animation, skeleton] outputs: [animation, skeleton] style: "both" dynamic: "dynamic" cost: "medium" authority: "Clavet" url: "https://texelatlas.vercel.app/t/motion-matching/" sources_verified_at: "2026-11-29" --- # Motion matching (Clavet) > Chooses the next animation pose by searching a mocap database for the clip frame whose pose, velocity and predicted trajectory best match the current state and desired motion. ## Reach for it when - character locomotion looks stiff with state machines - too much hand authoring of animation transitions - want responsive natural movement from mocap data - pick the best mocap pose for the desired path ## How it works Offline, an animation database is built from mocap: every frame gets a feature vector (joint positions and velocities, root velocity, future trajectory samples). At runtime a query vector is built from the character's current pose and the controller's desired trajectory. The nearest database frame under a weighted distance is found (brute force, KD-tree or accelerated search), and playback jumps to it if it is better than continuing the current clip by some margin. Inertialisation blends away the transition. Feature weights and search frequency are tuning knobs. Learned motion matching replaces the database search with neural networks to cut memory. ## When to use it Choose it for responsive, natural locomotion and action animation with little authoring of state machines. Prefer authored state machines or blend trees when you need guaranteed timing and exact poses, [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md) for adding foot/hand IK corrections on top, and physics-based control ([MuJoCo articulated-body dynamics with convex contacts](https://texelatlas.vercel.app/t/mujoco-articulated-dynamics.md)) when the character must react to forces. ## Cost medium — Search cost scales with database size; usually sub-millisecond per character with acceleration. ## Failure modes - Missing transitions in the data show up as foot sliding or 'teleporting' poses - Large databases need memory and careful curation - Feature weights are fiddly; poor tuning gives twitchy switching - Data-driven: cannot produce motion absent from the mocap ## Engine support - unreal: official — `Enable the Pose Search plugin; Animation Blueprint > Motion Matching node with a Pose Search Database` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/motion-matching-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: animation, skeleton - Outputs: animation, skeleton - Platforms: cpu, unity, unreal, godot ## Combines with - [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md): Motion matching outputs the base pose; IK adjusts feet and hands to terrain and targets ## Combination ideas - [A motion-matching database without mocap](https://texelatlas.vercel.app/ideas/physics-generated-motion-database/) ## Sources 1. [primary] Simon Clavet Motion Matching and The Road to Next-Gen Animation. GDC 2016. https://www.gdcvault.com/play/1023280/Motion-Matching-and-The-Road (verified via http on 2026-11-29) 2. [primary] Daniel Holden, Oussama Kanoun, Maksym Perepichka, Tiberiu Popa (2020) Learned motion matching. ACM Transactions on Graphics. https://doi.org/10.1145/3386569.3392440 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Motion matching." https://texelatlas.vercel.app/t/motion-matching/ (accessed 2026-12-01). --- id: "mpm-snow" title: "Material Point Method (snow)" aliases: [MPM] domain: "simulation" stage: "simulation" realtime: "interactive" platforms: [cpu, cuda, desktop-gpu, python, houdini] year_introduced: 2013 inputs: [particles, voxels] outputs: [particles] style: "photoreal" dynamic: "dynamic" cost: "offline" authority: "Stomakhin et al., 2013" url: "https://texelatlas.vercel.app/t/mpm-snow/" sources_verified_at: "2026-11-29" --- # Material Point Method (snow) (Stomakhin et al., 2013) > Particle/grid hybrid that simulates snow, sand and other elastoplastic continua, with a yield-based plasticity model that gives fracture, packing and clumping. ## Reach for it when - snow should pack, clump and fracture - simulating sand or mud that interacts with itself - granular material needs plasticity and memory - foam or snow piling against colliders - deformable solids that remember how they were squashed ## How it works Particles carry mass, velocity, a deformation gradient and plastic state. Each step: scatter mass and momentum from particles to a background grid (quadratic B-spline weights), compute grid forces from the elastic energy gradient, update velocities and apply collision boundaries, then gather velocities back and update each particle's deformation gradient. Snow plasticity clamps the singular values of the elastic part of the deformation gradient to a critical compression/stretch range and stores the excess as plastic deformation, with hardening that depends on the compressed volume. Because the grid handles contact and self-collision implicitly, snow can pile, break and fall without explicit collision handling. ## When to use it Choose it when you need snow, sand, mud, foam or other history-dependent solids that interact with themselves and with rigid colliders. Prefer [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) for pure liquids, [Real-time snow and terrain deformation](https://texelatlas.vercel.app/t/snow-terrain-deformation.md) for cheap heightfield footprints in games, and [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) or [Unified particle physics](https://texelatlas.vercel.app/t/unified-particle-physics.md) for realtime solids. ## Cost offline — Heavy per-particle and per-grid-node work; offline at film quality, interactive on GPU at tens to hundreds of thousands of particles. Measured GPU Weight: 24.1× baseline (heavy) — 0.7567 ms median / 0.7741 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.44× baseline (heavy) — 0.3388 ms median (2.23× faster on L4). Ampere A100 scaling: 15.19× baseline (moderate) — 0.4375 ms median (1.73× faster on A100). ## Failure modes - Numerical fracture: separating chunks 'melt' back together across grid-cell gaps - Explicit time step limits can be tight for stiff materials - Cell crossing noise with linear shape functions (hence quadratic B-splines) - Particles can numerically stick to colliders and each other ## Engine support - threejs: official — `examples/webgpu_compute_particles_fluid.html` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/webgpu_compute_particles_fluid.html, checked 2026-12-01) — MLS-MPM fluid compute example, not a snow constitutive model. ## Dataflow - Inputs: particles, voxels - Outputs: particles - Platforms: cpu, cuda, desktop-gpu, python, houdini ## Presets ### Material Point Method (snow) — elasto-plastic snowball fracture & P2G/G2P Eulerian grid transfer (glsl-fragment; rendered 2026-11-30) ```json { "P_PLASTICITY": 0.78, "P_IMPACT_SPEED": 1, "P_GRID_VIS": 0.85, "P_CLUMP_COHESION": 0.72 } ``` ```glsl const float P_PLASTICITY = 0.78; // P Plastic Fracture [0.1, 1.5, 0.04] const float P_IMPACT_SPEED = 1.0; // P Impact Cycle [0.0, 2.5, 0.05] const float P_GRID_VIS = 0.85; // P Eulerian Grid [0.0, 1.5, 0.05] const float P_CLUMP_COHESION = 0.72; // P Snow Cohesion [0.2, 1.4, 0.04] vec2 hash21(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // Evaluate MPM snow clump particle state at cycle phase tau in [0, 1] // Models pre-impact rigid flight -> plastic compression at wedge -> fractured snow chunks & powder spray void mpmParticle(int idx, float tau, float plast, float coh, out vec2 pos, out float strain, out float rad) { float fi = float(idx); vec2 h = hash21(fi * 19.3 + 5.7); // 4 cohesive sub-chunks formed upon SVD singular-value clamping fracture float chunkId = floor(fi / 8.0); float chunkAng = chunkId * 1.5708 + 0.45; vec2 chunkOff = vec2(cos(chunkAng), sin(chunkAng)) * 0.075; // Initial packed snowball disc coordinates float r0 = sqrt(h.x) * 0.145; float a0 = h.y * 6.2831853; vec2 local0 = mix(vec2(cos(a0), sin(a0)) * r0, chunkOff + vec2(cos(a0), sin(a0)) * r0 * 0.45, clamp(coh * 0.55, 0.0, 0.8)); // Flight from upper-left (-0.52, 0.24) into angled basalt wedge at (0.04, -0.14) float tImpact = 0.34; if (tau < tImpact) { float u = tau / tImpact; vec2 center = mix(vec2(-0.52, 0.24), vec2(-0.04, -0.02), u); pos = center + local0; strain = 0.0; } else { float u = (tau - tImpact) / (1.0 - tImpact); // Split upward/downward along the wedge faces + plastic pancake compression float side = (local0.y + 0.02 > 0.0) ? 1.0 : -1.0; vec2 splitDir = normalize(vec2(0.72, side * (0.68 + 0.28 * fract(chunkId * 0.618)))); // Plastic compression hardening near impact face, tensile fracture outward vec2 squashed = vec2(local0.x * (1.0 - 0.52 * min(u * 2.5, 1.0) * plast), local0.y * (1.0 + 0.48 * min(u * 2.2, 1.0) * plast)); float scatter = (0.14 + 0.42 * plast) * u * (0.55 + 0.65 * (1.0 - coh * 0.45) * h.x); vec2 gravityDrop = vec2(0.0, -0.26 * u * u); pos = vec2(-0.04, -0.02) + squashed + splitDir * scatter + gravityDrop; // Keep particles above floor y = -0.34 pos.y = max(pos.y, -0.32 + 0.03 * h.y); strain = clamp(u * 1.45 * plast * (0.5 + 0.6 * abs(local0.x) * 6.0), 0.0, 1.0); } rad = 0.034 + 0.016 * h.y; } float sdTriangle(vec2 p, vec2 a, vec2 b, vec2 c) { vec2 e0 = b - a, e1 = c - b, e2 = a - c; vec2 v0 = p - a, v1 = p - b, v2 = p - c; vec2 pq0 = v0 - e0 * clamp(dot(v0, e0) / dot(e0, e0), 0.0, 1.0); vec2 pq1 = v1 - e1 * clamp(dot(v1, e1) / dot(e1, e1), 0.0, 1.0); vec2 pq2 = v2 - e2 * clamp(dot(v2, e2) / dot(e2, e2), 0.0, 1.0); float s = sign(e0.x * e2.y - e0.y * e2.x); vec2 d = min(min(vec2(dot(pq0, pq0), s * (v0.x * e0.y - v0.y * e0.x)), vec2(dot(pq1, pq1), s * (v1.x * e1.y - v1.y * e1.x))), vec2(dot(pq2, pq2), s * (v2.x * e2.y - v2.y * e2.x))); return -sqrt(d.x) * sign(d.y); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tau = fract(iTime * 0.24 * max(P_IMPACT_SPEED, 0.05) + 0.42); float plast = clamp(P_PLASTICITY, 0.1, 1.6); float gridVis = clamp(P_GRID_VIS, 0.0, 1.6); float coh = clamp(P_CLUMP_COHESION, 0.15, 1.5); // Deep winter alpine twilight studio backdrop vec3 col = mix(vec3(0.03, 0.048, 0.082), vec3(0.075, 0.115, 0.175), smoothstep(-0.45, 0.55, uv.y)); // Background MPM Eulerian APIC Grid (16x16 cell grid) float gScale = 14.0; vec2 gCell = floor(uv * gScale); vec2 gCenter = (gCell + 0.5) / gScale; vec2 gf = abs(fract(uv * gScale) - 0.5); float gLine = smoothstep(0.47, 0.50, max(gf.x, gf.y)); float gNode = smoothstep(0.11, 0.04, length(fract(uv * gScale + 0.5) - 0.5)); // Accumulate Lagrangian snow density, plastic strain, and P2G Eulerian grid activation float snowDens = 0.0; float strainSum = 0.0; float gridAct = 0.0; float minP = 1e5; for (int i = 0; i < 32; i++) { vec2 pp; float st; float rr; mpmParticle(i, tau, plast, coh, pp, st, rr); float d = length(uv - pp); minP = min(minP, d); float w = exp(-(d * d) / max(rr * rr * 1.15, 1e-5)); snowDens += w; strainSum += w * st; // Quadratic B-spline P2G grid weight near current Eulerian cell float dg = length(gCenter - pp); gridAct += exp(-dg * dg * 95.0); } // Highlight active P2G Eulerian grid cells carrying transferred momentum if (gridVis > 0.01) { float act = clamp(gridAct * 0.42, 0.0, 1.0); col += vec3(0.12, 0.44, 0.72) * act * 0.34 * gridVis; col += vec3(0.24, 0.46, 0.68) * gLine * (0.14 + 0.45 * act) * gridVis; col += vec3(0.45, 0.86, 1.0) * gNode * act * 0.55 * gridVis; } // Rigid basalt impact wedge & snowy ground plane float dWedge = sdTriangle(uv, vec2(-0.04, -0.02), vec2(0.32, -0.35), vec2(0.32, 0.22)); float dFloor = -uv.y - 0.35; if (dWedge < 0.0 || dFloor > 0.0) { vec3 rock = vec3(0.13, 0.16, 0.22) * (0.85 + 0.25 * smoothstep(-0.35, 0.2, uv.y)); col = mix(col, rock, 0.94); } col = mix(col, vec3(0.58, 0.72, 0.88), smoothstep(px * 3.0, px * 0.6, abs(dWedge)) * 0.85); col = mix(col, vec3(0.48, 0.64, 0.82), smoothstep(px * 2.5, px * 0.5, abs(dFloor)) * 0.75); // Shaded MPM Snow Clumps (fresh snow white -> icy blue under high plastic hardening strain!) float snowMask = smoothstep(0.42, 0.72, snowDens); if (snowMask > 0.005) { float avgStrain = strainSum / max(snowDens, 1e-4); float sparkle = fract(sin(dot(floor(fragCoord * 0.75), vec2(12.98, 78.23))) * 43758.5); vec3 freshSnow = vec3(0.92, 0.95, 0.99); vec3 compressedIce = vec3(0.32, 0.74, 0.98); vec3 fracturedTint = vec3(0.98, 0.62, 0.28); vec3 sCol = mix(freshSnow, compressedIce, clamp(avgStrain * 0.85, 0.0, 1.0)); sCol = mix(sCol, fracturedTint, smoothstep(0.65, 1.0, avgStrain) * 0.45); // Soft powdery rim lighting + crystalline glint float rim = smoothstep(1.35, 0.45, snowDens); sCol *= (0.76 + 0.26 * rim); sCol += vec3(0.55) * step(0.965, sparkle); col = mix(col, sCol, snowMask); } // Crisp Lagrangian material-point cores col = mix(col, vec3(1.0, 0.96, 0.85), smoothstep(0.012, 0.004, minP) * 0.55); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Sources 1. [primary] Alexey Stomakhin, Craig Schroeder, Lawrence Chai, Joseph Teran, Andrew Selle (2013) A material point method for snow simulation. ACM Transactions on Graphics. https://doi.org/10.1145/2461912.2461948 (verified via crossref on 2026-11-29) 2. [implementation] taichi-dev (2020) taichi-dev/taichi_elements. https://github.com/taichi-dev/taichi_elements License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Material Point Method (snow)." https://texelatlas.vercel.app/t/mpm-snow/ (accessed 2026-12-01). --- id: "msdf-sdf-text-rendering" title: "SDF and multi-channel SDF text rendering" aliases: [MSDF, msdfgen, distance field fonts, Valve alpha-tested magnification] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2007 inputs: [curves] outputs: [texture] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Green, 2007" url: "https://texelatlas.vercel.app/t/msdf-sdf-text-rendering/" sources_verified_at: "2026-11-29" --- # SDF and multi-channel SDF text rendering (Green, 2007) > Bakes glyph or icon outlines into low-resolution distance textures; a shader thresholds the sampled distance, giving crisp edges at any scale, and the multi-channel form keeps sharp corners. ## Reach for it when - text looks blurry when zoomed in on a texture - glyph corners get rounded in sdf font atlas - need crisp ui text at any scale in a shader - outline and glow on text without extra passes ## How it works For each glyph, compute a signed distance to the outline at every texel of a small atlas cell, clamped to a pixel range and remapped to 0..1 with 0.5 on the edge. At draw time the shader samples bilinearly, which interpolates distances far better than it interpolates coverage, then applies a smoothstep around 0.5 with a width taken from screen-space derivatives for antialiasing. Outlines, glows and drop shadows are just different thresholds. A single channel rounds off sharp corners because distance is a poor description there. Multi-channel SDFs colour the outline edges so that each RGB channel stores the distance to a subset of edges, with adjacent edges sharing a channel, and the shader takes the median of the three. The median reproduces the sharp corner while far from corners all three agree. A fourth channel often holds a true SDF for effects. ## When to use it Choose it for UI, labels and world-space text that must stay sharp under zoom and perspective without big atlases. Prefer plain bitmap fonts when scale is fixed, and [Exact Euclidean Distance Transform](https://texelatlas.vercel.app/t/exact-euclidean-distance-transform.md) or [Jump Flooding Algorithm](https://texelatlas.vercel.app/t/jump-flooding-algorithm.md) when you only need to generate a single-channel field from a raster. Prefer direct GPU curve rendering (Slug-style) for huge glyphs or extreme magnification. ## Cost cheap — One texture sample and a few ALU per fragment; the atlas is generated offline or at load. Measured GPU Weight: 1.57× baseline (feather) — 0.0517 ms median / 0.0539 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.15× baseline (feather) — 0.0183 ms median (2.83× faster on L4). Ampere A100 scaling: 1.01× baseline (feather) — 0.029 ms median (1.78× faster on A100). ## Failure modes - Single-channel SDF rounds corners and drops thin serifs at low atlas resolution - MSDF can show stray colour fringes or blobs where overlapping contours confuse the channel assignment unless the font is preprocessed - Very small text loses hinting, so stems blur compared with a hinted rasteriser - Atlas range too small clips outlines and glows; too large wastes precision and softens edges ## Engine support - babylonjs: official — `import { TextRenderer } from "@babylonjs/addons" (msdfText)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/addons/src/msdfText/textRenderer.ts, checked 2026-12-01) - godot: builtin — `FontFile.multichannel_signed_distance_field = true (Label3D/Label/RichTextLabel)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/FontFile.xml, checked 2026-12-01) — Also SDF-style rendering of 3D text via Label3D. - threejs: plugin — `npm i troika-three-text` (evidence: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md, checked 2026-12-01) - unity: official — `TextMeshPro SDF font assets (Font Asset Creator)` (evidence: https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/TextMeshPro/FontAssetsCreator.html, checked 2026-12-01) — Single-channel SDF; MSDF is not built in. - unreal: builtin — `SlateCore FontSdfSettings (FFontSdfSettings) for signed distance field glyph rendering` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/FontSdfSettings, checked 2026-12-01) ## Dataflow - Inputs: curves - Outputs: texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Median-of-three decode of a procedural glyph (glsl-fragment; rendered 2026-11-29) ```json { "zoom_min": 0.55, "zoom_max": 1.6, "px_range": 6 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Procedural 5-edge glyph encoded as a 3-channel signed distance, // then decoded with the median trick. Sharp corners survive at any zoom. const float ZOOM_MIN = 0.55; const float ZOOM_MAX = 1.6; const float PX_RANGE = 6.0; float median(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); } vec3 glyphMSDF(vec2 p) { vec2 P[5]; P[0] = vec2(-0.5, -0.45); P[1] = vec2(0.5, -0.45); P[2] = vec2(0.5, 0.15); P[3] = vec2(0.0, 0.6); P[4] = vec2(-0.5, 0.15); vec3 ch = vec3(-1e3); for (int i = 0; i < 5; i++) { vec2 a = P[i], b = P[(i + 1) % 5]; vec2 e = normalize(b - a); vec2 n = vec2(e.y, -e.x); // outward normal for counter-clockwise winding float s = dot(p - a, n); // signed distance to the infinite edge line int col = (i == 4) ? 1 : (i % 3); // edge colours 0,1,2,0,1 for (int k = 0; k < 2; k++) { int c = (col + k) % 3; ch[c] = max(ch[c], s); } } return ch; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float zoom = mix(ZOOM_MIN, ZOOM_MAX, 0.5 + 0.5 * sin(iTime)); float ang = 0.35 * sin(iTime * 0.7); mat2 R = mat2(cos(ang), -sin(ang), sin(ang), cos(ang)); vec2 g = R * uv / zoom; vec3 m = glyphMSDF(g); float sd = -median(m.r, m.g, m.b); // positive inside float screenPx = PX_RANGE * 0.5 / (iResolution.y * 0.5) * zoom; // unit-space size of one pixel-ish float aa = fwidth(sd) * 0.75 + 1e-4; float fill = smoothstep(-aa, aa, sd); float outline = smoothstep(-aa, aa, sd + 0.05) - fill; vec3 bg = mix(vec3(0.10, 0.11, 0.16), vec3(0.22, 0.2, 0.3), uv.y + 0.5); vec3 col = bg; col = mix(col, vec3(0.05, 0.05, 0.08), outline); col = mix(col, mix(vec3(1.0, 0.85, 0.4), vec3(1.0, 0.45, 0.3), g.y + 0.5), fill); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Combines with - [Exact Euclidean Distance Transform](https://texelatlas.vercel.app/t/exact-euclidean-distance-transform.md): Produces the single-channel distance field from a rasterised glyph that the alpha channel or simple SDF text uses. ## Sources 1. [primary] Chris Green (2007) Improved alpha-tested magnification for vector textures and special effects. ACM SIGGRAPH 2007 courses. https://doi.org/10.1145/1281500.1281665 (verified via crossref on 2026-11-29) 2. [implementation] Chlumsky (2016) Chlumsky/msdfgen. https://github.com/Chlumsky/msdfgen License: MIT. (verified via github on 2026-11-29) 3. [implementation] Chlumsky (2020) Chlumsky/msdf-atlas-gen. https://github.com/Chlumsky/msdf-atlas-gen License: MIT. (verified via github on 2026-11-29) 4. [implementation] protectwise (2019) protectwise/troika. https://github.com/protectwise/troika License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "SDF and multi-channel SDF text rendering." https://texelatlas.vercel.app/t/msdf-sdf-text-rendering/ (accessed 2026-12-01). --- id: "mujoco-articulated-dynamics" title: "MuJoCo articulated-body dynamics with convex contacts" aliases: [MuJoCo] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, python] year_introduced: 2012 inputs: [skeleton] outputs: [animation, skeleton] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Todorov et al., 2012" url: "https://texelatlas.vercel.app/t/mujoco-articulated-dynamics/" sources_verified_at: "2026-11-29" --- # MuJoCo articulated-body dynamics with convex contacts (Todorov et al., 2012) > Physics engine for robotics and biomechanics that simulates articulated bodies in generalised coordinates with a convex, smooth contact model suited to optimisation. ## Reach for it when - robot arm simulation is unstable or slow - need fast accurate physics for jointed bodies - train reinforcement learning on simulated robots - joints drift apart in a physics engine ## How it works MuJoCo represents a system as a tree of joints in generalised coordinates and computes forward and inverse dynamics with articulated-body algorithms, so there is no joint drift. Contacts are not rigid: the contact problem is posed as a convex optimisation with soft constraints, whose smoothness gives well-defined gradients and makes trajectory optimisation and control feasible. Actuators, tendons, muscles and sensors are first class. The same model drives forward simulation, finite-difference derivatives, and, in newer versions, GPU/JAX batch rollouts. ## When to use it Choose it for robot control, reinforcement learning and biomechanical or character-control research where determinism, speed and derivatives matter. Prefer [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) or [Soft Step solver / substepping](https://texelatlas.vercel.app/t/soft-step-solver.md) for visually plausible game physics with many bodies, and [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md) for kinematic pose solving without dynamics. ## Cost cheap — Hundreds of thousands of steps per second on CPU for small models. ## Failure modes - Soft contacts mean visible penetration and 'sliding' unless parameters are tuned - Fidelity of friction cone approximations (pyramidal vs elliptic) trades speed and accuracy - Not designed for thousands of dynamic rigid bodies or destructible scenes - Model files are engineering-heavy; visual quality is secondary ## Engine support - unity: plugin — `Install the official MuJoCo Unity plugin from google-deepmind/mujoco (unity/ package)` (evidence: https://github.com/google-deepmind/mujoco/blob/main/unity/README.md, checked 2026-12-01) — Maintained official Unity integration in the MuJoCo repository. - unreal: plugin — `Unreal Robotics Lab plugin integrating MuJoCo` (evidence: https://github.com/URLab-Sim/UnrealRoboticsLab, checked 2026-12-01) ## Dataflow - Inputs: skeleton - Outputs: animation, skeleton - Platforms: cpu, python ## Combination ideas - [A motion-matching database without mocap](https://texelatlas.vercel.app/ideas/physics-generated-motion-database/) ## Sources 1. [primary] Emanuel Todorov, Tom Erez, Yuval Tassa (2012) MuJoCo: A physics engine for model-based control. 2012 IEEE/RSJ International Conference on Intelligent Robots and Systems. https://doi.org/10.1109/iros.2012.6386109 (verified via crossref on 2026-11-29) 2. [primary] Emanuel Todorov (2014) Convex and analytically-invertible dynamics with contacts and constraints: Theory and implementation in MuJoCo. 2014 IEEE International Conference on Robotics and Automation (ICRA). https://doi.org/10.1109/icra.2014.6907751 (verified via crossref on 2026-11-29) 3. [implementation] google-deepmind (2021) google-deepmind/mujoco. https://github.com/google-deepmind/mujoco License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "MuJoCo articulated-body dynamics with convex contacts." https://texelatlas.vercel.app/t/mujoco-articulated-dynamics/ (accessed 2026-12-01). --- id: "multi-bounce-ambient-occlusion" title: "Multi-Bounce Ambient Occlusion Approximation" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2016 inputs: [normals] outputs: [visibility-mask] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Jimenez et al." url: "https://texelatlas.vercel.app/t/multi-bounce-ambient-occlusion/" sources_verified_at: "2026-11-29" --- # Multi-Bounce Ambient Occlusion Approximation (Jimenez et al.) > A cheap albedo-dependent polynomial that brightens single-bounce AO to account for light bouncing between nearby surfaces, so bright materials are not over-darkened. ## Reach for it when - occlusion makes bright surfaces too dark - light-coloured walls look dirty in creases - need cheap approximation of bounced light in corners - ao looks overly harsh on high albedo materials ## How it works Plain AO assumes every blocked ray is lost, but in reality light reflects between occluders, which matters most for bright surfaces. The approximation fits a simple curve to path-traced reference data as a function of the single-bounce AO value a and the surface albedo rho: it applies a cubic of a whose coefficients are linear in albedo and is evaluated per colour channel. The result is multiplied into the diffuse lighting instead of the raw AO. It needs only the AO value and albedo already in the G-buffer and adds a few ALU instructions, making it a standard final step after [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) or any other AO. ## When to use it Choose it whenever you apply AO to diffuse lighting on bright or coloured albedo. Prefer plain AO only when albedo is uniformly dark, and prefer [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) or full global illumination (see gi domain) when the true bounce matters beyond a local fit. ## Cost cheap — A few ALU instructions per pixel; effectively free. Measured GPU Weight: 43.88× baseline (heavy) — 1.4436 ms median / 1.5734 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 37.14× baseline (heavy) — 0.5906 ms median (2.44× faster on L4). Ampere A100 scaling: 27.49× baseline (heavy) — 0.7918 ms median (1.82× faster on A100). ## Failure modes - Derived for diffuse surfaces and fitted to simple geometry; unreliable on strongly concave scenes - Colour shifts if applied per channel on saturated albedo - Cannot recover missing occluders from off-screen - Double-brightening if the lighting already includes a bounce term ## Engine support - unity: builtin — `HDRP: Volume > Ambient Occlusion (applied automatically in Lit shading)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl, checked 2026-12-01) — HDRP only; albedo-tinted multi-bounce AO approximation in the material evaluation. - unreal: builtin — `Post Process Volume > Ambient Occlusion (GTAO with multi-bounce albedo approximation)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: normals - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: single-bounce AO. Right: albedo-dependent multi-bounce polynomial brightens the creases (glsl-fragment; rendered 2026-11-29) ```json { "NR": 48, "MAXD": 0.8 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const int NR=48; // P const float MAXD=0.8; // P void aoBent(vec3 P,vec3 N,vec2 uv,out float ao,out vec3 bent){ vec3 T=normalize(abs(N.y)<.9?cross(N,vec3(0.,1.,0.)):cross(N,vec3(1.,0.,0.))),B=cross(N,T); float ph=rnd2(uv,5.).x*6.2831853,vis=0.;vec3 sum=vec3(0.); for(int i=0;iMAXD){sum+=d;vis+=1.;}} ao=vis/float(NR);bent=normalize(sum+N*.001);} vec3 mbao(float ao,vec3 a){vec3 A=2.0404*a-.3324,B=-4.7951*a+.6417,C=2.7552*a+.6903; return max(vec3(ao),((ao*A+B)*ao+C)*ao);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao;vec3 b;aoBent(P,n,uv,ao,b); vec3 a=min(alb(P)*1.1,vec3(.97));vec3 v=R?mbao(ao,a):vec3(ao); col=mix(a*v*(.55+.45*n.y)*.8,sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Sources 1. [primary] Jorge Jimenez, Xian-Chun Wu, Angelo Pesce, Adrian Jarabo Practical Real-Time Strategies for Accurate Indirect Occlusion. SIGGRAPH 2016 Course: Physically Based Shading in Theory and Practice. https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Multi-Bounce Ambient Occlusion Approximation." https://texelatlas.vercel.app/t/multi-bounce-ambient-occlusion/ (accessed 2026-12-01). --- id: "multi-view-stereo-patchmatch" title: "Multi-View Stereo (PatchMatch, COLMAP)" aliases: [MVS, patch-match stereo] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda] year_introduced: 2016 inputs: [photos, camera-poses] outputs: [depth, normals, point-cloud] style: "photoreal" dynamic: "static" cost: "offline" authority: "Schönberger et al., 2016" url: "https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch/" sources_verified_at: "2026-11-29" --- # Multi-View Stereo (PatchMatch, COLMAP) (Schönberger et al., 2016) > Computes a dense depth and normal map per image from posed photos using PatchMatch propagation with pixelwise view selection, then fuses them into a dense point cloud. ## Reach for it when - need dense point cloud from photos with known cameras - turn posed photos into depth maps - build a mesh for baking from a photo set - sparse reconstruction is too thin for detail - photogrammetry dense reconstruction step ## How it works Given calibrated cameras, each pixel in a reference image carries a hypothesised depth and surface normal. PatchMatch initialises these randomly and iterates: neighbouring pixels propagate good hypotheses along scanlines, and random perturbation refines them. Each hypothesis is scored by photometric consistency (normalised cross-correlation of a slanted patch) against a subset of source images. The key idea is that the subset is chosen per pixel, using a probabilistic occlusion model estimated jointly with depth, so occluded views stop poisoning the cost. Geometric consistency across neighbouring views is added in later passes. Resulting depth maps are filtered for consistency and fused into a point cloud, which can be meshed with Poisson or Delaunay methods. ## When to use it Choose it when you need an explicit dense surface from a photo set with known poses, e.g. for meshing and baking. Prefer [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) or [NeuS](https://texelatlas.vercel.app/t/neus.md) when surfaces are thin, glossy or textureless and you can afford neural optimisation. Prefer [2D Gaussian Splatting](https://texelatlas.vercel.app/t/2d-gaussian-splatting.md) when you also want fast novel-view rendering from the same capture. ## Cost offline — GPU-bound; minutes to hours depending on resolution and image count. Measured GPU Weight: 25.74× baseline (heavy) — 0.7979 ms median / 0.8223 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 25.38× baseline (heavy) — 0.4035 ms median (1.98× faster on L4). Ampere A100 scaling: 16.35× baseline (moderate) — 0.471 ms median (1.69× faster on A100). ## Failure modes - Textureless walls and sky give noisy or missing depth because photometric cost is flat - Specular and transparent surfaces violate photo-consistency and produce holes or floating points - Thin structures and foliage are smoothed away or fused into blobs - Fused clouds carry view-dependent colour seams unless colours are blended carefully ## Engine support - blender: plugin — `Blender add-on: Photogrammetry Importer (imports COLMAP dense / MVS output)` (evidence: https://github.com/SBCV/Blender-Addon-Photogrammetry-Importer, checked 2026-12-01) — Imports results; the MVS itself runs in COLMAP. ## Dataflow - Inputs: photos, camera-poses - Outputs: depth, normals, point-cloud - Platforms: cuda ## Presets ### Multi-View Stereo (PatchMatch) — epipolar disparity & cost planes (left) vs recovered dense depth (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BASELINE": 0.35, "P_COST_BANDS": 10, "P_CAM_SWEEP": 0.7, "P_SPLIT": 0.48 } ``` ```glsl const float P_BASELINE = 0.35; // P Stereo Baseline [0.10, 0.75, 0.02] const float P_COST_BANDS = 10.0; // P Sweep Planes [4.0, 20.0, 1.0] const float P_CAM_SWEEP = 0.70; // P View Motion [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Stereo / Depth Split [0.0, 1.0, 0.02] 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); } // Multi-depth architectural scene with rich foreground, midground, and background parallax layers vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.72, 1.0); float dBack = p.z + 2.4; if (dBack < res.x) res = vec2(dBack, 2.0); float dArch1 = sdBox(p - vec3(-0.62, -0.15, -0.35), vec3(0.28, 0.56, 0.24)) - 0.02; if (dArch1 < res.x) res = vec2(dArch1, 3.0); float dSph = length(p - vec3(0.06, -0.24, -0.75)) - 0.44; if (dSph < res.x) res = vec2(dSph, 4.0); float dArch2 = sdBox(p - vec3(0.76, -0.22, -1.25), vec3(0.32, 0.50, 0.26)) - 0.02; if (dArch2 < res.x) res = vec2(dArch2, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // High-frequency surface texture required for PatchMatch NCC photometric matching vec3 surfaceTexture(vec3 p, float matId) { float pat = sin(p.x * 16.0) * sin(p.y * 16.0) * sin(p.z * 16.0); float brick = smoothstep(0.05, 0.12, abs(fract(p.x * 4.0) - 0.5)) * smoothstep(0.05, 0.12, abs(fract(p.y * 6.0) - 0.5)); vec3 base = vec3(0.58, 0.62, 0.68); if (matId > 2.5 && matId < 3.5) base = vec3(0.84, 0.50, 0.32); if (matId > 3.5 && matId < 4.5) base = vec3(0.28, 0.66, 0.78); if (matId > 4.5) base = vec3(0.76, 0.72, 0.42); return base * (0.76 + 0.24 * brick) * (0.88 + 0.12 * pat); } // Trace camera view and return (depth, matId, shadedRGB) void renderView(vec3 ro, vec3 rd, out float depth, out vec3 col, out vec3 nOut) { float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 60; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.0025) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } depth = hit ? t : 9.0; nOut = vec3(0.0, 0.0, 1.0); if (!hit) { col = vec3(0.04, 0.06, 0.10); return; } vec3 p = ro + rd * t; nOut = calcNormal(p); vec3 lDir = normalize(vec3(0.55, 0.80, 0.48)); float diff = max(dot(nOut, lDir), 0.0); col = surfaceTexture(p, matId) * (0.28 + 0.82 * diff); } vec3 turboDepth(float d) { float t = clamp(d, 0.0, 1.0); vec3 c0 = vec3(0.10, 0.14, 0.48); vec3 c1 = vec3(0.10, 0.78, 0.86); vec3 c2 = vec3(0.96, 0.84, 0.22); vec3 c3 = vec3(0.96, 0.26, 0.18); if (t < 0.33) return mix(c0, c1, t * 3.0); if (t < 0.66) return mix(c1, c2, (t - 0.33) * 3.0); return mix(c2, c3, (t - 0.66) * 3.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isDepth = screenX >= split; float base = clamp(P_BASELINE, 0.08, 0.80); float nBands = clamp(floor(P_COST_BANDS + 0.5), 4.0, 22.0); float sway = sin(iTime * max(P_CAM_SWEEP, 0.0) * 0.75) * 0.28; // Reference camera (center) and stereo source camera (offset along epipolar baseline X) vec3 roRef = vec3(sway, 0.12, 2.25); vec3 roSrc = vec3(sway + base, 0.12, 2.25); vec3 rd = normalize(vec3(uv, -1.52)); float dRef, dSrc; vec3 cRef, cSrc, nRef, nSrc; renderView(roRef, rd, dRef, cRef, nRef); vec3 col; if (!isDepth) { // Left: Epipolar stereo anaglyph parallax (Red=ref cam, Cyan=source cam) + horizontal epipolar scanlines renderView(roSrc, rd, dSrc, cSrc, nSrc); float lRef = dot(cRef, vec3(0.299, 0.587, 0.114)); float lSrc = dot(cSrc, vec3(0.299, 0.587, 0.114)); col = vec3(lRef * 1.15, lSrc * 0.95, lSrc * 1.10); // Horizontal epipolar lines showing 1D stereo disparity search rows float epiLine = smoothstep(0.055, 0.012, abs(fract(uv.y * 12.0) - 0.5)); col = mix(col, vec3(0.95, 0.88, 0.34), epiLine * 0.24); } else { // Right: PatchMatch MVS recovered inverse-depth map (1 / z) + plane-sweep iso-cost bands & normal shading float invZ = clamp((1.0 / max(dRef, 1.0) - 0.16) * 2.2, 0.0, 1.0); vec3 dCol = turboDepth(invZ); // Animated active plane-sweep hypothesis slice passing through the cost volume float activeSweep = fract(iTime * 0.25); float sweepHit = smoothstep(0.045, 0.008, abs(invZ - activeSweep)); float planeBands = smoothstep(0.06, 0.015, abs(fract(invZ * nBands) - 0.5)); float nShade = 0.65 + 0.35 * max(dot(nRef, normalize(vec3(0.5, 0.8, 0.5))), 0.0); col = dCol * nShade; col = mix(col, vec3(0.04, 0.07, 0.12), planeBands * 0.34); col = mix(col, vec3(1.0, 0.98, 0.90), sweepHit * 0.85); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): SfM provides the calibrated cameras that MVS needs to compare views. ## Combination ideas - [Progressive radiosity relighting on PatchMatch multi-view stereo rooms](https://texelatlas.vercel.app/ideas/patchmatch-mvs-radiosity-relighting/) ## Sources 1. [primary] Johannes L. Schönberger, Enliang Zheng, Jan-Michael Frahm, Marc Pollefeys (2016) Pixelwise View Selection for Unstructured Multi-View Stereo. Lecture Notes in Computer Science. https://doi.org/10.1007/978-3-319-46487-9_31 (verified via crossref on 2026-11-29) 2. [implementation] colmap (2014) colmap/colmap. https://github.com/colmap/colmap License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Multi-View Stereo (PatchMatch, COLMAP)." https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch/ (accessed 2026-12-01). --- id: "multiple-importance-sampling" title: "Multiple Importance Sampling" aliases: [MIS, balance heuristic, power heuristic] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda, desktop-gpu, webgpu, webgl2] year_introduced: 1995 inputs: [mesh, material-params, hdr-image] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Veach & Guibas, 1995" url: "https://texelatlas.vercel.app/t/multiple-importance-sampling/" sources_verified_at: "2026-11-29" --- # Multiple Importance Sampling (Veach & Guibas, 1995) > Combines several sampling strategies for the same integral with weights that bound the variance of the sum. In rendering it merges light sampling and BSDF sampling so neither failure mode dominates. ## Reach for it when - path tracer is noisy with small bright lights - glossy surfaces and area lights give fireflies - one sampling strategy works only for some materials - combine light sampling and brdf sampling without bias ## How it works Any single sampling distribution is good for some integrands and terrible for others. Sampling a glossy BSDF finds the specular lobe but misses a small lamp; sampling the lamp finds the lamp but wastes samples against a sharp lobe. MIS draws samples from both strategies and weights each sample so the weights for any given direction sum to one. The **balance heuristic** weights a sample from strategy *i* by `n_i p_i(x) / sum_j n_j p_j(x)`. The **power heuristic** raises each pdf to a power (usually 2) before normalizing, which sharpens the preference for whichever strategy is clearly better at that direction. Because the weights depend on the pdf of every strategy at the sampled point, you must be able to evaluate *both* pdfs for any direction, including the one you did not draw. In a path tracer this appears at every vertex: one light sample and one BSDF sample, each weighted by the other's density. The same idea generalizes over path-space strategies in bidirectional methods, and it is the algebra behind resampled importance sampling in ReSTIR. ## When to use it Choose it whenever an estimator mixes at least two sampling strategies: direct lighting with next-event estimation, environment map plus BSDF sampling, or bidirectional connections. It is essentially free and always safe to add. Prefer a single strategy only when the other is degenerate, for example a delta light (cannot be hit by BSDF sampling) or a perfect mirror (cannot be sampled from a light). Prefer [restir-di](restir-di) when you have thousands of lights, since MIS alone still needs an importance function over all of them. Many-light structures such as [light-bvh-many-lights](light-bvh-many-lights) supply the light-side pdf that MIS then combines. ## Cost offline — Adds one extra pdf evaluation and one extra ray per vertex; the variance reduction almost always pays for it. Measured GPU Weight: 8.12× baseline (moderate) — 0.2549 ms median / 0.2621 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.58× baseline (moderate) — 0.1039 ms median (2.45× faster on L4). Ampere A100 scaling: 4.99× baseline (light) — 0.1436 ms median (1.78× faster on A100). ## Failure modes - Wrong results if the pdf used for the weight does not exactly match the density the sample was drawn from (missing cosine, wrong solid-angle vs area measure) - Lights with delta distributions need special handling: BSDF sampling gets weight 0 for them, light sampling gets weight 1 - Balance heuristic is not variance-optimal, and the power heuristic can lose when strategies have comparable quality - Shadow rays are required for the light strategy; an occluded light sample is wasted weight that BSDF sampling cannot recover ## Engine support - babylonjs: builtin — `new BABYLON.IblCdfGenerator(engine) builds cumulative distribution function textures for IBL importance sampling` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Rendering/iblCdfGenerator.ts, checked 2026-12-01) - blender: builtin — `Light Properties > Settings > Multiple Importance (Cycles); World > Settings > Multiple Importance` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/light_settings.html, checked 2026-12-01) - unreal: builtin — `Path Tracer and MegaLights combine light and BRDF importance sampling for HDRI skylight and area emitters` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/path-tracer-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params, hdr-image - Outputs: radiance - Platforms: cpu, cuda, desktop-gpu, webgpu, webgl2 ## Presets ### Multiple Importance Sampling — classic Veach glossy-plate benchmark (naive sampling vs balance-heuristic MIS) (glsl-fragment; rendered 2026-11-30) ```json { "P_MIS_QUALITY": 1, "P_EXPOSURE": 1.15, "P_LIGHT_SWAY": 1, "P_SPLIT": 0.46 } ``` ```glsl const float P_MIS_QUALITY = 1.0; // P MIS Variance Fix [0.0, 1.0, 0.02] const float P_EXPOSURE = 1.15; // P Exposure [0.4, 2.2, 0.05] const float P_LIGHT_SWAY = 1.0; // P Light Motion [0.0, 2.5, 0.05] const float P_SPLIT = 0.46; // P Naive / MIS Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Evaluate GGX microfacet specular lobe + solid-angle area-light contribution from spherical light vec3 evalSphereLight(vec3 p, vec3 n, vec3 v, vec3 lCenter, float lRad, vec3 lCol, float rough) { vec3 toL = lCenter - p; float dist = length(toL); vec3 lDir = toL / max(dist, 1e-4); // Representative closest point on sphere to reflection ray R for crisp area-light specular vec3 rVec = reflect(-v, n); vec3 centerToRay = dot(toL, rVec) * rVec - toL; vec3 closestPt = lCenter + centerToRay * clamp(lRad / max(length(centerToRay), 1e-4), 0.0, 1.0); vec3 lSpec = normalize(closestPt - p); float a = max(rough * rough, 0.008); // Sphere angular radius energy normalization (Karis alpha' broadening) float aPrime = clamp(a + lRad / max(2.0 * dist, 0.1), 0.01, 1.0); float normFactor = (a * a) / max(aPrime * aPrime, 1e-5); vec3 h = normalize(lSpec + v); float ndh = max(dot(n, h), 0.0); float ndl = max(dot(n, lDir), 0.0); float denom = ndh * ndh * (aPrime * aPrime - 1.0) + 1.0; float D = (aPrime * aPrime) / max(3.14159265 * denom * denom, 1e-5); float F = 0.08 + 0.92 * pow(1.0 - max(dot(h, v), 0.0), 5.0); // Constant total power across all 4 spheres: radiance scales inversely with area (1 / r^2) float areaScale = 0.018 / max(lRad * lRad, 0.0004); return lCol * areaScale * (D * F * normFactor * 0.24 + 0.025) * ndl / (1.0 + 0.18 * dist * dist); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float misQual = clamp(P_MIS_QUALITY, 0.0, 1.0); float expo = clamp(P_EXPOSURE, 0.3, 2.5); float tAnim = iTime * max(P_LIGHT_SWAY, 0.0); vec3 ro = vec3(0.0, 0.65, 3.15); vec3 rd = normalize(vec3(uv.x, uv.y - 0.16, -1.65)); // Classic Veach scene: 4 spherical area lights of increasing radius (tiny intense -> large soft) vec3 lPos[4]; float lRad[4]; vec3 lCol[4]; float sway = 0.14 * sin(tAnim * 0.7); lPos[0] = vec3(-1.12 + sway, 0.85, -1.25); lRad[0] = 0.055; lCol[0] = vec3(1.0, 0.42, 0.25); lPos[1] = vec3(-0.38 + sway, 0.88, -1.25); lRad[1] = 0.115; lCol[1] = vec3(1.0, 0.82, 0.32); lPos[2] = vec3(0.38 + sway, 0.92, -1.25); lRad[2] = 0.205; lCol[2] = vec3(0.28, 0.92, 0.68); lPos[3] = vec3(1.18 + sway, 0.96, -1.25); lRad[3] = 0.320; lCol[3] = vec3(0.32, 0.64, 1.0); vec3 col = mix(vec3(0.018, 0.024, 0.038), vec3(0.045, 0.058, 0.088), smoothstep(-0.4, 0.6, uv.y)); // Render the 4 glowing spherical Veach area lights directly in the upper frame float tHit = 1e5; for (int i = 0; i < 4; i++) { vec3 oc = ro - lPos[i]; float b = dot(oc, rd); float c = dot(oc, oc) - lRad[i] * lRad[i]; float disc = b * b - c; if (disc > 0.0) { float ts = -b - sqrt(disc); if (ts > 0.0 && ts < tHit) { tHit = ts; float radBoost = clamp(0.18 / max(lRad[i], 0.04), 0.7, 3.2); col = lCol[i] * radBoost * 1.4; } } } // Intersect 4 tilted horizontal glossy Veach plates (roughness: 0.06, 0.14, 0.26, 0.42) for (int pIdx = 0; pIdx < 4; pIdx++) { float fp = float(pIdx); // Plates stepped downward and closer to camera, angled to reflect the 4 overhead spheres vec3 pCenter = vec3(0.0, -0.46 + fp * 0.20, 0.55 - fp * 0.62); vec3 pNorm = normalize(vec3(0.0, 0.88, 0.47 - fp * 0.05)); float denom = dot(rd, pNorm); if (denom < -1e-4) { float tp = dot(pCenter - ro, pNorm) / denom; if (tp > 0.1 && tp < tHit) { vec3 hp = ro + rd * tp; vec3 rel = hp - pCenter; float alongZ = dot(rel, normalize(cross(vec3(1.0, 0.0, 0.0), pNorm))); if (abs(rel.x) < 1.52 && abs(alongZ) < 0.23) { tHit = tp; float rough = mix(0.055, 0.40, fp / 3.0); vec3 vDir = -rd; vec3 cleanSum = vec3(0.0); vec3 noisySum = vec3(0.0); float pxSeed = floor(fragCoord.x) + floor(fragCoord.y) * 57.0 + fract(iTime * 6.0) * 17.0; for (int k = 0; k < 4; k++) { vec3 contrib = evalSphereLight(hp, pNorm, vDir, lPos[k], lRad[k], lCol[k], rough); cleanSum += contrib; // Left side illustrates single-strategy estimator variance: // BRDF sampling fails catastrophically on tiny lights (k=0,1) + rough plates; // Light sampling fails on large lights (k=2,3) + mirror-like plates (fp=0)! float rn = hash21(vec2(pxSeed + float(k) * 13.7, float(pIdx) * 29.3)); float mismatch = (k < 2) ? (rough * 2.2 / max(lRad[k] * 6.0, 0.25)) : ((0.45 - rough) * 1.9); float spike = step(clamp(0.84 - mismatch * 0.35, 0.22, 0.92), rn) * (1.8 + 2.4 * mismatch); noisySum += contrib * mix(0.32, spike, clamp(mismatch, 0.15, 1.0)); } // Balance-heuristic MIS combines both PDFs -> dramatically suppresses both variance regimes! vec3 misCol = mix(noisySum, cleanSum, misQual); vec3 plateBase = vec3(0.035, 0.042, 0.056); col = (plateBase + ((screenX < split) ? noisySum : misCol)) * expo; // Crisp brushed metallic bevel edge on each Veach strip float edge = smoothstep(0.20, 0.23, abs(alongZ)); col = mix(col, vec3(0.38, 0.45, 0.56), edge * 0.65); } } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Weights light-sampling and BSDF-sampling contributions at each path vertex. - [Light BVH and Adaptive Tree Splitting](https://texelatlas.vercel.app/t/light-bvh-many-lights.md): The tree provides the light-side sampling pdf that MIS combines with the BSDF pdf. ## Sources 1. [primary] Eric Veach, Leonidas J. Guibas (1995) Optimally combining sampling techniques for Monte Carlo rendering. Proceedings of the 22nd annual conference on Computer graphics and interactive techniques - SIGGRAPH '95. https://doi.org/10.1145/218380.218498 (verified via crossref on 2026-11-29) 2. [implementation] mmp (2017) mmp/pbrt-v4. https://github.com/mmp/pbrt-v4 License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Multiple Importance Sampling." https://texelatlas.vercel.app/t/multiple-importance-sampling/ (accessed 2026-12-01). --- id: "multiple-scattering-octaves" title: "Multiple-Scattering Approximation by Octaves" aliases: [art-directable multiple scattering, Wrenninge multi-octave scattering] domain: "volumes" stage: "volume" realtime: "interactive" platforms: [desktop-gpu, webgpu, cpu, houdini, unreal] year_introduced: 2013 inputs: [volume-density] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "medium" authority: "Wrenninge, 2015" url: "https://texelatlas.vercel.app/t/multiple-scattering-octaves/" sources_verified_at: "2026-11-29" --- # Multiple-Scattering Approximation by Octaves (Wrenninge, 2015) > Approximate many scattering orders by summing a few octaves of single scattering with progressively weaker extinction, lower anisotropy and lower contribution, so thick clouds stay bright inside. ## Reach for it when - clouds look dark and flat inside - thick smoke loses brightness with single scattering - can't afford path-traced multiple scattering for clouds - dense fog lacks soft glowing interior ## How it works Single scattering lets light die quickly in dense media, making clouds look dark and flat. The approximation re-runs the same single-scatter calculation N times (typically 4 to 8), where octave i uses scaled coefficients: the extinction used for the light path is multiplied by a factor a to the i, the scattering contribution is multiplied by b to the i, and the phase function eccentricity g is scaled by c to the i. The three constants are all below one, and with a few octaves the sum mimics the diffusion of light into deeper regions and the loss of directionality. The results are summed per sample, either re-marching the light ray per octave or reusing one light march with scaled optical depths. The constants are art-directable knobs rather than physically derived, and they can be tuned to match a path-traced reference. ## When to use it Choose it to rescue single-scatter clouds, smoke and fog when a path tracer is too expensive: it adds only a few extra exponentials per sample if you reuse the light-ray optical depth. Prefer [Delta (Woodcock) Tracking](https://texelatlas.vercel.app/t/delta-tracking.md) for ground truth or offline production renders. Use it on top of [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md) or [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) rather than as a standalone method. Prefer a precomputed multi-scattering LUT (see [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md)) when the medium is a planetary atmosphere. ## Cost medium — Cost scales linearly in the number of octaves; with a shared light march the extra work per octave is mostly ALU. Measured GPU Weight: 1006.05× baseline (extreme) — 33.0989 ms median / 33.5662 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 827.86× baseline (extreme) — 13.163 ms median (2.51× faster on L4). Ampere A100 scaling: 692.25× baseline (extreme) — 19.9368 ms median (1.66× faster on A100). ## Failure modes - Not energy conserving: bad constants can make clouds glow or lose energy - Matched only for the reference look it was tuned on; thin and thick media can need different constants - Interior brightness loses contrast with no sense of cloud thickness when too many octaves are summed - Does not capture view-dependent effects like glories - Octave parameters lack a physical meaning, which makes automated tuning against a reference awkward ## Engine support - unity: builtin — `Volume > Volumetric Clouds > Multi Scattering` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsUtilities.hlsl, checked 2026-12-01) — HDRP clouds use a 2-octave multiple-scattering approximation. - unreal: builtin — `Volumetric Cloud Material > VolumetricAdvancedMaterialOutput (const_multi_scattering_contribution, const_multi_scattering_eccentricity octaves)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/MaterialExpressionVolumetricAdvancedMaterialOutput, checked 2026-12-01) ## Dataflow - Inputs: volume-density - Outputs: radiance - Platforms: desktop-gpu, webgpu, cpu, houdini, unreal ## Presets ### Backlit cloud: 1 scattering octave (left) vs 6 octaves (right) (glsl-fragment; rendered 2026-11-29) ```json { "SIGMA": 6, "OCT_A": 0.5, "OCT_B": 0.5, "OCT_C": 0.5, "G_ANISO": 0.6 } ``` ```glsl // Backlit cloud with the multiple-scattering octave approximation (Wrenninge): // sum_n a^n * exp(-tau_light * b^n) * HG(cos, g * c^n). Left half: 1 octave (single scattering). // Right half: 6 octaves. Same cloud, same light. const float SIGMA = 6.0; const float OCT_A = 0.5; const float OCT_B = 0.5; const float OCT_C = 0.5; const float G_ANISO = 0.6; float h31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); } float vn(vec3 x) { vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f); return mix(mix(mix(h31(i), h31(i + vec3(1, 0, 0)), f.x), mix(h31(i + vec3(0, 1, 0)), h31(i + vec3(1, 1, 0)), f.x), f.y), mix(mix(h31(i + vec3(0, 0, 1)), h31(i + vec3(1, 0, 1)), f.x), mix(h31(i + vec3(0, 1, 1)), h31(i + vec3(1, 1, 1)), f.x), f.y), f.z); } float dens(vec3 p) { float shape = 1.0 - length(p / vec3(1.1, 0.75, 1.1)); float n = 0.5 * vn(p * 2.5) + 0.25 * vn(p * 5.0) + 0.125 * vn(p * 10.0); return clamp((shape + (n - 0.4) * 0.9) * 2.5, 0.0, 1.0) * SIGMA; } float hg(float c, float g) { float g2 = g * g; return (1.0 - g2) / (12.566 * pow(1.0 + g2 - 2.0 * g * c, 1.5)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.2, 3.6), rd = normalize(vec3(uv, -1.8)); vec3 L = normalize(vec3(0.4, 0.5, -0.7)); int octs = fragCoord.x < 0.5 * iResolution.x ? 1 : 6; vec3 bg = vec3(0.3, 0.5, 0.85) * (0.75 + 0.5 * uv.y); float b = dot(ro, rd); float hh = b * b - dot(ro, ro) + 2.25; vec3 col = bg; if (hh > 0.0) { float t0 = -b - sqrt(hh), t1 = -b + sqrt(hh); float ds = (t1 - t0) / 48.0; float T = 1.0; vec3 S = vec3(0.0); float cs = dot(L, rd); for (int i = 0; i < 48; i++) { vec3 p = ro + rd * (t0 + (float(i) + 0.5) * ds); float d = dens(p); if (d < 0.01) continue; float tau = 0.0; for (int k = 1; k <= 6; k++) tau += dens(p + L * float(k) * 0.2) * 0.2; float li = 0.0; for (int n = 0; n < 6; n++) { if (n >= octs) break; float fn = float(n); li += pow(OCT_A, fn) * exp(-tau * pow(OCT_B, fn)) * hg(cs, G_ANISO * pow(OCT_C, fn)); } vec3 amb = vec3(0.35, 0.5, 0.8) * 0.06 * (0.6 + 0.4 * p.y); S += T * (vec3(1.0, 0.95, 0.85) * li * 9.0 + amb) * d * ds; T *= exp(-d * ds); } col = bg * T + S; } if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); col = 1.0 - exp(-col * 1.4); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md) ## Combines with - [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md): Takes the density and per-sample light march from the cloud marcher and brightens interiors. - [Henyey-Greenstein Phase Function](https://texelatlas.vercel.app/t/henyey-greenstein-phase-function.md): Each octave uses an HG lobe with a reduced asymmetry. ## Sources 1. [primary] Magnus Wrenninge (2015) Art-directable multiple volumetric scattering. ACM SIGGRAPH 2015 Talks. https://doi.org/10.1145/2775280.2792512 (verified via crossref on 2026-11-29) 2. [primary] Julian Fong, Magnus Wrenninge, Christopher Kulla, Ralf Habel (2017) Production volume rendering. ACM SIGGRAPH 2017 Courses. https://doi.org/10.1145/3084873.3084907 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Multiple-Scattering Approximation by Octaves." https://texelatlas.vercel.app/t/multiple-scattering-octaves/ (accessed 2026-12-01). --- id: "multiscale-diffusive-volumetric-fire-irradiance" title: "Multi-Scale 3D Diffusive Volumetric Irradiance" aliases: [diffusive fire light volumes, multi-scale volumetric light diffusion, volumetric fire irradiance grid] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgpu, desktop-gpu] year_introduced: 1995 inputs: [volume-density, voxels, normals] outputs: [irradiance-probes, radiance] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Stam, 1995" url: "https://texelatlas.vercel.app/t/multiscale-diffusive-volumetric-fire-irradiance/" sources_verified_at: "2026-11-30" --- # Multi-Scale 3D Diffusive Volumetric Irradiance (Stam, 1995) > Propagates emissive fire radiance through 3D smoke and surrounding surfaces by iterating extinction-attenuated diffusion across nested coarse voxel grids, deriving dominant fire direction from the volume gradient without shadow maps. ## Reach for it when - fire and explosions do not illuminate surrounding smoke convincingly - ray marching multi-bounce emissive volume lighting is too slow - need soft glow spreading from flames into nearby dust clouds - approximate volumetric indirect light on a 3d grid in real time - emissive fluid sim looks flat without internal scattering irradiance ## How it works Physically accurate multiple scattering inside dense fire and soot plumes is expensive to ray-trace in real time. Treating diffuse radiative transport as a **3D diffusion process** (Stam 1995; Koerner et al. 2014) turns volumetric self-illumination into a fast grid relaxation pass: each voxel injects local blackbody or flame emission and updates its stored irradiance as an extinction-attenuated average of its six face neighbors. On a single grid, explicit diffusion advances only one cell per iteration, and per-step attenuation `l` caps effective reach to roughly `h * sqrt(1 / (6 * l))` world units. **Multi-scale diffusive irradiance** solves this by running nested lower-resolution 3D light volumes in parallel—for example, a quarter-resolution near field with soot absorption for tight inner-plume glow, paired with an eighth-resolution far field with minimal loss and open-boundary decay so warm firelight reaches distant terrain and cliffs in just a few compute dispatches. Opaque scene geometry (ground, cliffs, shields) and the volume ray-marcher both trilinearly sample these grids. Taking finite differences of the coarse light volume supplies an approximate **dominant light direction** per point, letting normal-mapped surfaces react to moving flames with no point-light proxies or shadow passes. ## When to use it Choose it for real-time GPU fluid fire, explosions, and lava plumes where flames must self-illuminate billowing smoke and cast soft, temporally coherent bounce light onto nearby terrain without spawning dozens of proxy lights. Prefer [light-propagation-volumes](light-propagation-volumes) when propagating directional sunlight bounces across solid architecture using spherical harmonics. Prefer [froxel-volumetric-fog](froxel-volumetric-fog) when external spotlights and shadow maps dominate scattering in view-frustum fog. Prefer [delta-tracking](delta-tracking) offline for unbiased heterogeneous multi-scattering. ## Cost cheap — Runs as a handful of 3D compute shader Jacobi/diffusion passes over quarter- and eighth-resolution grids, typically a fraction of the underlying fluid simulation cost. Measured GPU Weight: 203.68× baseline (extreme) — 6.701 ms median / 6.7404 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 192.79× baseline (extreme) — 3.0653 ms median (2.19× faster on L4). Ampere A100 scaling: 155.52× baseline (extreme) — 4.479 ms median (1.5× faster on A100). ## Failure modes - Isotropic diffusion blurs out crisp directional shafts and hard occlusion edges behind solid obstacles unless solid blocker terms or flux limiters are injected - Insufficient iteration count causes temporal lag as bright flame pulses ripple across the coarse grid over several frames - Clamped boundary conditions reflect light back into the domain at grid edges, producing artificial glow near the bounding box unless open-face decay is applied - Coarse-grid gradient directionality degrades when multiple equally bright fire lobes surround a surface, causing flattened normal-map response ## Dataflow - Inputs: volume-density, voxels, normals - Outputs: irradiance-probes, radiance - Platforms: webgpu, desktop-gpu ## Presets ### Multi-Scale Diffusive Volumetric Fire Irradiance — nested 3D diffusion grid (left) vs fire-lit smoke & ruins (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FIRE_POWER": 1.35, "P_SMOKE_DENS": 1.1, "P_DIFFUSE_RAD": 0.78, "P_SPLIT": 0.48 } ``` ```glsl const float P_FIRE_POWER = 1.35; // P Fire Emission [0.4, 2.5, 0.1] const float P_SMOKE_DENS = 1.10; // P Smoke Density [0.3, 2.2, 0.1] const float P_DIFFUSE_RAD = 0.78; // P Diffusion Spread [0.25, 1.4, 0.05] const float P_SPLIT = 0.48; // P Grid / Lit Split [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * vec3(127.1, 311.7, 74.7)); p += dot(p, p.yzx + 19.19); return fract((p.x + p.y) * p.z); } float noise3(vec3 p) { vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(mix(hash31(i), hash31(i + vec3(1.0, 0.0, 0.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 0.0)), hash31(i + vec3(1.0, 1.0, 0.0)), f.x), f.y), mix(mix(hash31(i + vec3(0.0, 0.0, 1.0)), hash31(i + vec3(1.0, 0.0, 1.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 1.0)), hash31(i + vec3(1.0, 1.0, 1.0)), f.x), f.y), f.z ); } float fbm3(vec3 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 4; i++) { v += a * noise3(p); p *= 2.04; a *= 0.5; } return v; } 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); } // Stone ruins & brazier surrounding the roaring volumetric fire vec2 mapRuins(vec3 p) { float dFloor = p.y + 0.65; vec2 res = vec2(dFloor, 1.0); // Stone pillar left & right archway float dP1 = sdBox(p - vec3(-0.98, 0.15, -0.35), vec3(0.22, 0.85, 0.24)); float dP2 = sdBox(p - vec3(0.98, 0.15, -0.35), vec3(0.22, 0.85, 0.24)); float dLint = sdBox(p - vec3(0.0, 0.92, -0.35), vec3(1.22, 0.14, 0.28)); float dArch = min(min(dP1, dP2), dLint); if (dArch < res.x) res = vec2(dArch, 2.0); // Stone fire pit rim float dPit = max(abs(length(p.xz) - 0.44) - 0.08, abs(p.y + 0.56) - 0.11); if (dPit < res.x) res = vec2(dPit, 2.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapRuins(p + e.xyy).x - mapRuins(p - e.xyy).x, mapRuins(p + e.yxy).x - mapRuins(p - e.yxy).x, mapRuins(p + e.yyx).x - mapRuins(p - e.yyx).x )); } // Evaluate rising fire temperature & billowing smoke density at 3D point p void evalFireSmoke(vec3 p, float sDens, out float fireT, out float smokeD) { vec3 flow = p - vec3(0.0, iTime * 1.15, 0.0); float n = fbm3(flow * 2.6); float r = length(p.xz + vec2(0.12 * sin(p.y * 3.0 - iTime * 2.4), 0.0)); float yNorm = clamp((p.y + 0.58) / 1.45, 0.0, 1.0); float coreRad = mix(0.36, 0.06, pow(yNorm, 0.72)); fireT = clamp((1.0 - r / max(coreRad, 0.04)) + (n - 0.42) * 0.85, 0.0, 1.0) * smoothstep(0.0, 0.12, yNorm) * smoothstep(0.75, 0.25, yNorm); float smokeRad = mix(0.32, 0.74, yNorm); float rawSmoke = clamp((1.0 - r / smokeRad) + (n - 0.45) * 0.95, 0.0, 1.0) * smoothstep(0.08, 0.32, yNorm) * smoothstep(1.0, 0.72, yNorm); smokeD = rawSmoke * sDens; } // Multi-scale 3D diffusive fire irradiance field across 3 nested Gaussian/Yukawa diffusion scales (L0 fine, L1 mid, L2 coarse) vec3 evalDiffusiveIrradiance(vec3 p, float firePow, float diffRad) { vec3 fCore = vec3(0.04 * sin(iTime * 4.5), -0.22 + 0.05 * cos(iTime * 3.7), 0.0); vec3 fMid = vec3(-0.03 * cos(iTime * 3.1), 0.05, 0.0); float d0 = length(p - fCore); float d1 = length(p - fMid); // 3 nested extinction-attenuated diffusion scales float L0 = exp(-d0 * d0 / max(0.08 * diffRad * diffRad, 0.01)); float L1 = exp(-d1 / max(0.42 * diffRad, 0.05)); float L2 = exp(-d1 / max(1.15 * diffRad, 0.1)); float flicker = 0.88 + 0.12 * sin(iTime * 9.3) * cos(iTime * 5.7); vec3 col0 = vec3(2.8, 1.65, 0.52) * L0; vec3 col1 = vec3(1.6, 0.58, 0.14) * L1 * 0.65; vec3 col2 = vec3(0.68, 0.20, 0.06) * L2 * 0.42; return (col0 + col1 + col2) * firePow * flicker; } vec3 blackbody(float t) { t = clamp(t, 0.0, 1.0); return mix(vec3(0.95, 0.16, 0.02), mix(vec3(1.0, 0.58, 0.10), vec3(1.0, 0.95, 0.78), smoothstep(0.45, 0.92, t)), smoothstep(0.05, 0.55, t)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showFinal = sx >= split; float firePow = clamp(P_FIRE_POWER, 0.3, 2.8); float sDens = clamp(P_SMOKE_DENS, 0.2, 2.6); float diffRad = clamp(P_DIFFUSE_RAD, 0.2, 1.6); vec3 ro = vec3(0.28 * sin(iTime * 0.25), 0.18, 2.28); vec3 ta = vec3(0.0, 0.04, -0.15); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.42 + ri * uv.x + up * uv.y); vec3 bg = mix(vec3(0.02, 0.025, 0.045), vec3(0.05, 0.07, 0.12), smoothstep(-0.2, 0.6, rd.y)); vec3 col = bg; // March solid ruins first float tSolid = 0.05; float hitId = 0.0; for (int i = 0; i < 56; i++) { vec2 h = mapRuins(ro + rd * tSolid); if (h.x < 0.0025) { hitId = h.y; break; } tSolid += h.x; if (tSolid > 8.0) break; } if (hitId > 0.5) { vec3 p = ro + rd * tSolid; vec3 n = calcNormal(p); vec3 alb = (hitId < 1.5) ? vec3(0.26, 0.24, 0.22) : vec3(0.42, 0.40, 0.38); // Derive dominant fire direction directly from gradient of diffusive irradiance volume (no shadow maps!) float e = 0.05; float iC = dot(evalDiffusiveIrradiance(p, firePow, diffRad), vec3(0.3, 0.6, 0.1)); vec3 gradI = vec3( dot(evalDiffusiveIrradiance(p + vec3(e, 0.0, 0.0), firePow, diffRad), vec3(0.3, 0.6, 0.1)) - iC, dot(evalDiffusiveIrradiance(p + vec3(0.0, e, 0.0), firePow, diffRad), vec3(0.3, 0.6, 0.1)) - iC, dot(evalDiffusiveIrradiance(p + vec3(0.0, 0.0, e), firePow, diffRad), vec3(0.3, 0.6, 0.1)) - iC ); vec3 fireDir = normalize(gradI + vec3(1e-5)); vec3 irr = evalDiffusiveIrradiance(p, firePow, diffRad); float ndl = 0.35 + 0.65 * max(dot(n, fireDir), 0.0); if (showFinal) { col = alb * (irr * ndl + vec3(0.04, 0.06, 0.10) * (0.5 + 0.5 * n.y)); } else { // Left: Quantized multi-scale nested 3D voxel diffusion grid visualization float distC = length(p.xz); float voxRes = (distC < 0.75) ? 9.0 : 4.5; vec3 qP = (floor(p * voxRes) + 0.5) / voxRes; vec3 qIrr = evalDiffusiveIrradiance(qP, firePow, diffRad); vec3 fc = abs(fract(p * voxRes) - 0.5); float gridE = smoothstep(0.055, 0.015, min(min(0.5 - fc.x, 0.5 - fc.y), 0.5 - fc.z)); vec3 tierCol = (distC < 0.75) ? vec3(1.0, 0.85, 0.25) : vec3(0.22, 0.88, 1.0); col = qIrr * 0.92 + tierCol * gridE * 0.35; } } // Volumetric raymarch through fire & smoke plume in front of solid surface float tStart = max(0.85, 0.05); float tEnd = min(tSolid, 3.6); if (tEnd > tStart) { float trans = 1.0; vec3 volAcc = vec3(0.0); const int STEPS = 32; float dt = (tEnd - tStart) / float(STEPS); for (int i = 0; i < STEPS; i++) { float tm = tStart + (float(i) + 0.5) * dt; vec3 mp = ro + rd * tm; if (abs(mp.x) < 0.9 && mp.y > -0.62 && mp.y < 0.95 && abs(mp.z) < 0.9) { float fT, sD; evalFireSmoke(mp, sDens, fT, sD); if (fT > 0.02 || sD > 0.02) { vec3 radVol = evalDiffusiveIrradiance(mp, firePow, diffRad); vec3 emit = blackbody(fT) * pow(fT, 1.6) * firePow * 4.8; vec3 scatter = radVol * vec3(0.45, 0.42, 0.40) * sD * 1.4; if (!showFinal) { // Left: Show quantized 3D voxel blocks of the fire diffusion cascade inside the plume vec3 qP = (floor(mp * 9.0) + 0.5) / 9.0; vec3 qRad = evalDiffusiveIrradiance(qP, firePow, diffRad); scatter = qRad * sD * 1.35; } float ext = sD * 2.6 + fT * 0.8; float stepT = exp(-ext * dt); volAcc += trans * (emit + scatter) * dt; trans *= stepT; if (trans < 0.02) break; } } } col = col * trans + volAcc; } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md): Samples the near-field diffused irradiance grid at each march step to shade dense smoke illuminated by internal flames. - [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md): Consumes the advected 3D temperature and soot density fields from the gas solver as emission and extinction sources. ## Sources 1. [primary] Jos Stam (1995) Multiple scattering as a diffusion process. Eurographics. https://doi.org/10.1007/978-3-7091-9430-0_5 (verified via doi.org on 2026-11-30) 2. [primary] D. Koerner, J. Portsmouth, F. Sadlo, T. Ertl, B. Eberhardt (2014) Flux‐Limited Diffusion for Multiple Scattering in Participating Media. Computer Graphics Forum. https://doi.org/10.1111/cgf.12342 (verified via crossref on 2026-11-30) 3. [secondary] Duc Quang Nguyen, Ronald Fedkiw, Henrik Wann Jensen (2002) Physically based modeling and animation of fire. ACM Transactions on Graphics. https://doi.org/10.1145/566654.566643 (verified via doi.org on 2026-11-30) 4. [implementation] lejrimostfa (2026) lejrimostfa/force-field-vfx-threejs. https://github.com/lejrimostfa/force-field-vfx-threejs License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Multi-Scale 3D Diffusive Volumetric Irradiance." https://texelatlas.vercel.app/t/multiscale-diffusive-volumetric-fire-irradiance/ (accessed 2026-12-01). --- id: "n8ao" title: "N8AO" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu] year_introduced: 2023 inputs: [depth, normals] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "N8python, 2023" url: "https://texelatlas.vercel.app/t/n8ao/" sources_verified_at: "2026-11-29" --- # N8AO (N8python, 2023) > A three.js post-processing screen-space AO pass (SSAO/HBAO-style) with half-resolution rendering, depth-aware denoising and colour-aware options. ## Reach for it when - need good ambient occlusion in three.js with little setup - scene looks flat without contact darkening - ao pass shows noise or halos at edges - post-process occlusion for web 3d without a g-buffer - creases and corners lack shading depth ## How it works N8AO is a drop-in three.js EffectComposer pass that reconstructs positions from depth, samples a spiral of points around each pixel in a normal-oriented hemisphere with a configurable radius, and compares them against the depth buffer to estimate occlusion. A depth-aware blur removes noise, optional half-resolution rendering with upsampling saves time, and distance-falloff and intensity controls shape the look. It can also tint occlusion by colour. As a plugin it avoids writing a custom pipeline, and its settings expose quality presets from low to ultra. ## When to use it Choose it when you want good screen-space AO in three.js quickly, without wiring a G-buffer yourself. Prefer [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) via three's GTAOPass for a more physically formulated option, [SDF Ambient Occlusion](https://texelatlas.vercel.app/t/sdf-ambient-occlusion.md) for baked static scenes, and [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) for the simplest built-in pass. ## Cost cheap — Roughly SSAO-level cost; half-resolution mode lowers it further. Measured GPU Weight: 44.17× baseline (heavy) — 1.4531 ms median / 1.5515 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 45.16× baseline (heavy) — 0.718 ms median (2.02× faster on L4). Ampere A100 scaling: 30.19× baseline (heavy) — 0.8696 ms median (1.67× faster on A100). ## Failure modes - Screen-space limits: no off-screen occluders - Halos or banding at large radii - Depth-aware blur can leak across edges - Transparent objects are not part of the depth buffer ## Engine support - threejs: plugin — `npm i n8ao` (evidence: https://github.com/N8python/n8ao, checked 2026-12-01) ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask - Platforms: webgl2, webgpu ## Presets ### N8AO — unoccluded flat lighting (left) vs spiral-hemisphere depth-aware denoised AO + color bleed (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_AO_RADIUS": 0.65, "P_AO_INTENSITY": 1.35, "P_COLOR_BLEED": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_AO_RADIUS = 0.65; // P Hemisphere Radius [0.2, 1.4, 0.05] const float P_AO_INTENSITY = 1.35; // P AO Intensity [0.3, 2.5, 0.05] const float P_COLOR_BLEED = 0.45; // P Color Bleed [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P No AO / N8AO [0.0, 1.0, 0.02] 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); } // Stepped architectural niches & nested spheres full of tight creases where N8AO shines vec2 mapN8Scene(vec3 p) { float dFloor = p.y + 0.56; vec2 res = vec2(dFloor, 1.0); // Back stepped terracotta wall with recessed alcoves float dWall = sdBox(p - vec3(0.0, 0.15, -0.88), vec3(1.5, 0.85, 0.18)); float niche1 = sdBox(p - vec3(-0.48, -0.04, -0.72), vec3(0.26, 0.36, 0.16)); float niche2 = sdBox(p - vec3(0.48, -0.04, -0.72), vec3(0.26, 0.36, 0.16)); dWall = max(dWall, -min(niche1, niche2)); if (dWall < res.x) res = vec2(dWall, 2.0); // Stepped stair plinths float s1 = sdBox(p - vec3(0.0, -0.46, -0.35), vec3(0.95, 0.10, 0.45)); float s2 = sdBox(p - vec3(0.0, -0.34, -0.48), vec3(0.68, 0.10, 0.30)); float dStair = min(s1, s2); if (dStair < res.x) res = vec2(dStair, 3.0); // Clustered spheres seated tightly into stair corners (strong contact AO!) float c1 = length(p - vec3(0.0, -0.02, -0.42)) - 0.24; float c2 = length(p - vec3(-0.34, -0.18, -0.18)) - 0.18; float c3 = length(p - vec3(0.36, -0.20, -0.14)) - 0.16; float c4 = length(p - vec3(-0.48, -0.22, -0.68)) - 0.16; float c5 = length(p - vec3(0.48, -0.22, -0.68)) - 0.16; float dSph = min(min(c1, c2), min(c3, min(c4, c5))); if (dSph < res.x) res = vec2(dSph, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapN8Scene(p + e.xyy).x - mapN8Scene(p - e.xyy).x, mapN8Scene(p + e.yxy).x - mapN8Scene(p - e.yxy).x, mapN8Scene(p + e.yyx).x - mapN8Scene(p - e.yyx).x )); } vec3 matAlbedo(float id) { if (id < 1.5) return vec3(0.76, 0.74, 0.70); if (id < 2.5) return vec3(0.86, 0.46, 0.30); if (id < 3.5) return vec3(0.84, 0.82, 0.78); return vec3(0.92, 0.88, 0.82); } // N8AO spiral-hemisphere sampling with distance falloff & optional color bleed void evalN8AO(vec3 p, vec3 n, float rad, float intensity, out float ao, out vec3 bleed) { vec3 up = (abs(n.y) < 0.99) ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); vec3 t = normalize(cross(up, n)); vec3 b = cross(n, t); float occ = 0.0; bleed = vec3(0.0); float wBleed = 0.0; // 12 golden-angle spiral hemisphere taps for (int i = 0; i < 12; i++) { float fi = float(i); float rFrac = (fi + 0.5) / 12.0; float ang = fi * 2.3999632; float z = 0.22 + 0.75 * rFrac; float xy = sqrt(max(1.0 - z * z, 0.0)); vec3 dir = normalize(t * (cos(ang) * xy) + b * (sin(ang) * xy) + n * z); float stepD = rad * (0.14 + 0.86 * rFrac * rFrac); vec2 h = mapN8Scene(p + dir * stepD); float delta = max(stepD - h.x, 0.0); float falloff = 1.0 - smoothstep(0.0, rad * 1.1, stepD); float tapOcc = clamp(delta / max(stepD, 0.04), 0.0, 1.0) * falloff; occ += tapOcc; if (tapOcc > 0.05) { bleed += matAlbedo(h.y) * tapOcc; wBleed += tapOcc; } } ao = clamp(1.0 - (occ / 12.0) * intensity * 1.65, 0.06, 1.0); bleed = (wBleed > 0.01) ? (bleed / wBleed) : vec3(0.6); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float rad = clamp(P_AO_RADIUS, 0.15, 1.5) * 0.42; float inten = clamp(P_AO_INTENSITY, 0.2, 2.8); float bleedAmt = clamp(P_COLOR_BLEED, 0.0, 1.0); vec3 ro = vec3(0.32 * sin(iTime * 0.45), 0.18, 1.92); vec3 rd = normalize(vec3(uv.x, uv.y - 0.07, -1.45)); vec3 col = mix(vec3(0.14, 0.19, 0.28), vec3(0.45, 0.58, 0.78), smoothstep(-0.2, 0.6, rd.y)); float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapN8Scene(ro + rd * dist); if (h.x < 0.002) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 8.0) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 lDir = normalize(vec3(0.45, 0.82, 0.55)); vec3 alb = matAlbedo(hit.y); float ndl = max(dot(n, lDir), 0.0); vec3 direct = alb * vec3(0.95, 0.90, 0.82) * ndl * 0.65; vec3 hemiAmb = alb * mix(vec3(0.32, 0.36, 0.44), vec3(0.68, 0.78, 0.92), 0.5 + 0.5 * n.y) * 0.72; if (screenX < split) { // Left: Flat ambient without N8AO (objects appear floating without crease grounding) col = direct + hemiAmb; } else { // Right: N8AO spiral hemisphere AO + subtle color bleed inside corners and niches float ao; vec3 bleed; evalN8AO(p + n * 0.006, n, rad, inten, ao, bleed); vec3 aoTint = mix(vec3(ao), mix(bleed * 0.55, vec3(1.0), ao), bleedAmt * 0.65); col = direct * mix(1.0, ao, 0.45) + hemiAmb * aoTint; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] N8python (2023) N8python/n8ao. https://github.com/N8python/n8ao License: CC0-1.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "N8AO." https://texelatlas.vercel.app/t/n8ao/ (accessed 2026-12-01). --- id: "nanite-virtualized-geometry" title: "Nanite virtualized geometry" aliases: [Nanite, virtualized geometry, cluster LOD] domain: "performance" stage: "performance" realtime: "realtime" platforms: [unreal, desktop-gpu] year_introduced: 2021 inputs: [mesh] outputs: [gbuffer, depth] style: "both" dynamic: "both" cost: "heavy" authority: "Halen et al." url: "https://texelatlas.vercel.app/t/nanite-virtualized-geometry/" sources_verified_at: "2026-11-29" --- # Nanite virtualized geometry (Halen et al.) > Unreal Engine's system that builds a hierarchy of triangle clusters per mesh and selects them per frame by screen-space error, giving effectively continuous LOD with a hybrid hardware and software rasterizer. ## Reach for it when - scenes with film quality meshes run too slow - popping when switching between lod levels - draw calls and triangle counts limit detail - want millions of triangles per mesh in real time ## How it works Offline, the mesh is split into clusters and repeatedly simplified: groups of clusters are merged, simplified while locking their boundary, and split again, building a DAG of levels. Each group stores its error, so neighbours always agree on border vertices and no cracks appear. At runtime a GPU traversal picks the cut through the DAG where projected error falls under about a pixel, culls clusters against frustum and a depth pyramid, and streams pages on demand. Large triangles use hardware raster; pixel-sized ones go to a compute rasterizer writing a visibility buffer, resolved to materials later. ## When to use it Choose it for static, very high-polygon assets where artists should not author LODs. Prefer [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) with a simpler discrete LOD chain or [Octahedral impostors](https://texelatlas.vercel.app/t/octahedral-impostors.md) when targeting WebGL or mobile. Prefer ordinary skinned LOD for deforming characters, which the original system does not handle well. ## Cost heavy — Large fixed cost for streaming, culling and visibility-buffer resolve; scales with pixels rather than triangles. Measured GPU Weight: 63.95× baseline (extreme) — 2.0081 ms median / 2.1043 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 60.21× baseline (extreme) — 0.9513 ms median (2.11× faster on L4). Ampere A100 scaling: 40.53× baseline (heavy) — 1.1674 ms median (1.72× faster on A100). ## Failure modes - Poor support for skinning, tessellation and heavy deformation in early versions - Masked or foliage materials cause overdraw and shader cost in the visibility pass - Large storage and streaming demands - Not portable outside engines that implement the whole stack ## Engine support - unreal: builtin — `Static Mesh Editor > Details > Nanite Settings > Enable Nanite Support` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/nanite-virtualized-geometry-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: gbuffer, depth - Platforms: unreal, desktop-gpu ## Presets ### Nanite virtualized geometry — screen-space error DAG cluster hierarchy vs shaded micro-polygons (glsl-fragment; rendered 2026-11-30) ```json { "P_PIXEL_ERROR": 1, "P_CLUSTER_SCALE": 8, "P_RELIEF_DETAIL": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_PIXEL_ERROR = 1.0; // P Error Threshold [0.35, 2.5, 0.05] const float P_CLUSTER_SCALE = 8.0; // P Cluster Density [4.0, 16.0, 0.5] const float P_RELIEF_DETAIL = 1.0; // P Micro-Relief [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Shaded / Cluster Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } // High-detail sculpted baroque manifold (ornate fluted torus + central obelisk) float mapSculpt(vec3 p, float relief) { vec3 q = p - vec3(0.0, 0.02, 0.0); q.xz = rot2(iTime * 0.32) * q.xz; q.xy = rot2(0.38) * q.xy; float theta = atan(q.z, q.x); vec2 tq = vec2(length(q.xz) - 0.72, q.y); float phi = atan(tq.y, tq.x); float flutes = 0.032 * sin(phi * 10.0 + theta * 4.0) + 0.014 * cos(theta * 16.0 - phi * 6.0); float dTorus = length(tq) - (0.28 + flutes * relief); // Inner carved faceted core vec3 c = q; float dCore = length(c) - (0.30 + 0.022 * sin(c.x * 22.0) * cos(c.y * 22.0) * sin(c.z * 22.0) * relief); // Pedestal floor with micro-grooves float dFloor = p.y + 0.88 - 0.008 * sin(p.x * 18.0) * cos(p.z * 18.0) * relief; return min(min(dTorus, dCore) * 0.78, dFloor); } vec3 calcNormal(vec3 p, float relief) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapSculpt(p + e.xyy, relief) - mapSculpt(p - e.xyy, relief), mapSculpt(p + e.yxy, relief) - mapSculpt(p - e.yxy, relief), mapSculpt(p + e.yyx, relief) - mapSculpt(p - e.yyx, relief) )); } // 3D Voronoi cluster partitioning simulating Nanite 128-triangle cluster DAG at given LOD scale vec4 evalClusterDAG(vec3 p, float scale) { vec3 sp = p * scale; vec3 n = floor(sp); vec3 f = fract(sp); float d1 = 8.0; float d2 = 8.0; vec3 bestId = vec3(0.0); for (int z = -1; z <= 1; z++) { for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { vec3 g = vec3(float(x), float(y), float(z)); vec3 o = hash33(n + g); vec3 r = g + o - f; float d = dot(r, r); if (d < d1) { d2 = d1; d1 = d; bestId = n + g; } else if (d < d2) { d2 = d; } } } } float seam = sqrt(d2) - sqrt(d1); vec3 colId = hash33(bestId * 1.7 + 13.1); return vec4(colId, seam); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float errThr = clamp(P_PIXEL_ERROR, 0.3, 3.0); float clScale = clamp(P_CLUSTER_SCALE, 3.0, 18.0); float relief = clamp(P_RELIEF_DETAIL, 0.0, 2.2); float camZ = 2.65 + 0.45 * sin(iTime * 0.45); vec3 ro = vec3(0.0, 0.25, camZ); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.04, 0.05, 0.08), vec3(0.10, 0.12, 0.17), smoothstep(-0.5, 0.6, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSculpt(ro + rd * t, relief); if (d < 0.002) { hit = true; break; } t += d; if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, relief); // Transform hit point into object space so clusters stick tightly to rotating geometry vec3 objP = p - vec3(0.0, 0.02, 0.0); if (p.y > -0.85) { objP.xz = rot2(iTime * 0.32) * objP.xz; objP.xy = rot2(0.38) * objP.xy; } // Screen-space projected error determines discrete DAG LOD level (0 = finest, 3 = coarsest) float dagLod = clamp(floor(log2(max(t * errThr * 0.55, 0.5))), 0.0, 3.0); float effScale = clScale * pow(0.55, dagLod); vec3 l1 = normalize(vec3(0.65, 0.85, 0.55)); vec3 l2 = normalize(vec3(-0.7, 0.2, 0.5)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 42.0) * 0.42; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.25; // Shaded sculpted marble / bronze material (left side) vec3 stoneAlb = mix(vec3(0.76, 0.72, 0.66), vec3(0.52, 0.46, 0.40), smoothstep(-0.88, -0.82, -p.y)); vec3 shaded = stoneAlb * (0.22 + 0.88 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.62, 0.92) * rim; // Nanite Cluster DAG visualization (right side): distinct pastel cluster IDs + micro-triangle grain vec4 cl = evalClusterDAG(objP, effScale); vec3 clusterHue = 0.28 + 0.68 * cl.rgb; float seamLine = smoothstep(0.075, 0.015, cl.w); // Micro-triangle tessellation hint inside each cluster vec3 microP = fract(objP * effScale * 4.5); float microTri = smoothstep(0.08, 0.01, min(min(microP.x, microP.y), abs(microP.x - microP.y))); vec3 clusterView = clusterHue * (0.38 + 0.68 * diff1) + vec3(0.08) * microTri; clusterView = mix(clusterView, vec3(0.04, 0.05, 0.08), seamLine * 0.72); // Subtle LOD tier tint accent on rim vec3 lodTint = mix(vec3(0.15, 0.95, 0.75), vec3(1.0, 0.38, 0.25), dagLod / 3.0); clusterView += lodTint * rim * 0.65; col = (screenX < split) ? shaded : clusterView; float fog = exp(-max(t - 3.5, 0.0) * 0.14); col = mix(vec3(0.06, 0.08, 0.12), col, fog); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) - extends [Visibility buffer rendering](https://texelatlas.vercel.app/t/visibility-buffer.md) ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): Two-pass depth pyramid culling prunes cluster groups before software and hardware raster. ## Sources 1. [primary] Henrik Halen, Andreas Brinck, Kyle Hayward, Xiangshun Bei Global Illumination Based on Surfels. SIGGRAPH 2021 Advances in Real-Time Rendering. https://advances.realtimerendering.com/s2021/index.html (verified via http on 2026-11-29) 2. [implementation] zeux (2016) zeux/meshoptimizer. https://github.com/zeux/meshoptimizer License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Nanite virtualized geometry." https://texelatlas.vercel.app/t/nanite-virtualized-geometry/ (accessed 2026-12-01). --- id: "nanovdb" title: "NanoVDB" aliases: [GPU VDB] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [cuda, desktop-gpu, webgpu, cpu] year_introduced: 2021 inputs: [volume-density, sdf] outputs: [volume-density, sdf] style: "both" dynamic: "static" cost: "medium" authority: "Museth, 2021" url: "https://texelatlas.vercel.app/t/nanovdb/" sources_verified_at: "2026-11-29" --- # NanoVDB (Museth, 2021) > A compact, read-only, pointer-free serialisation of an OpenVDB grid that can be copied to a GPU buffer and sampled from CUDA, GLSL, HLSL or OpenCL with the same hierarchical access. ## Reach for it when - need to render large sparse volumes on the gpu - openvdb can't be sampled in a shader - dense 3d textures use too much memory for smoke caches - want gpu access to a production volume grid ## How it works OpenVDB's tree uses pointers and dynamic allocation, which GPUs cannot handle well. NanoVDB lays the same 4-level hierarchy (root, two internal levels, leaf) in a single linear memory blob, replacing pointers with byte offsets. The tree is read-only, so all structure is fixed at conversion time; leaf nodes hold bit masks of active voxels along with min and max values per node. The header stores a transform, a bounding box and a magic number for validation. A shader or kernel gets a root pointer, and an accessor walks offsets to a voxel; a cache of the last-visited nodes makes coherent traversals fast. The same header-only C++ code compiles for CPU, CUDA and other languages through a shared C-like API, and ray-grid intersection with a hierarchical DDA is included. ## When to use it Choose it to ray-march or path-trace large sparse volumes (clouds, smoke caches, level sets) on the GPU without densifying them. Prefer [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md) for editing and simulation where topology changes. Prefer a dense 3D texture when the volume is small. Prefer [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) on a plain texture in a WebGL page, since NanoVDB support in browsers is limited and typically needs a custom port. ## Cost medium — Memory is the active-voxel footprint; sampling costs a few dependent reads without a cache and fewer with an accessor. Measured GPU Weight: 349.64× baseline (extreme) — 11.5032 ms median / 11.7392 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 331.64× baseline (extreme) — 5.2731 ms median (2.18× faster on L4). Ampere A100 scaling: 273.01× baseline (extreme) — 7.8628 ms median (1.46× faster on A100). ## Failure modes - Read-only: any topology change requires re-conversion on the CPU - Pointer-chasing in a deep tree gives divergent memory reads when neighbouring rays are incoherent - Buffer alignment and endian assumptions break when the blob is mapped to non-native languages - Precision loss if grids are quantised to 4, 8 or 16 bits to save memory - Browser and WebGPU support is not first-party, so porting the accessor is needed ## Engine support - blender: builtin — `Cycles GPU Volume rendering converts OpenVDB grids to NanoVDB via intern/cycles/scene/image_vdb.cpp` (evidence: https://github.com/blender/blender/blob/main/intern/cycles/scene/image_vdb.cpp, checked 2026-12-01) - unreal: builtin — `Import OpenVDB (.vdb) as a Sparse Volume Texture and render via Heterogeneous Volumes` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sparse-volume-textures-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: volume-density, sdf - Outputs: volume-density, sdf - Platforms: cuda, desktop-gpu, webgpu, cpu ## Presets ### NanoVDB — GPU pointer-free sparse 8^3 leaf-tile bitmask & DDA skipping (left) vs volumetric raymarching (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DENSITY": 1.55, "P_STEP_SKIP": 1, "P_ORBIT_SPEED": 0.38, "P_SPLIT": 0.48 } ``` ```glsl const float P_DENSITY = 1.55; // P Volume Density [0.5, 3.0, 0.1] const float P_STEP_SKIP = 1.00; // P Leaf Tile Vis [0.2, 1.6, 0.05] const float P_ORBIT_SPEED = 0.38; // P Orbit Speed [0.0, 1.4, 0.05] const float P_SPLIT = 0.48; // P Leaf Bricks / Volume [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * vec3(127.1, 311.7, 74.7)); p += dot(p, p.yzx + 19.19); return fract((p.x + p.y) * p.z); } float noise3(vec3 p) { vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(mix(hash31(i), hash31(i + vec3(1.0, 0.0, 0.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 0.0)), hash31(i + vec3(1.0, 1.0, 0.0)), f.x), f.y), mix(mix(hash31(i + vec3(0.0, 0.0, 1.0)), hash31(i + vec3(1.0, 0.0, 1.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 1.0)), hash31(i + vec3(1.0, 1.0, 1.0)), f.x), f.y), f.z ); } float fbm3(vec3 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 3; i++) { v += a * noise3(p); p *= 2.05; a *= 0.5; } return v; } // Sparse knotted curl plume SDF bounding support (only ~18% of bounding box is active!) float evalSparseDensity(vec3 p) { vec2 q = vec2(length(p.xz) - 0.52, p.y - 0.16 * sin(atan(p.z, p.x) * 2.0 + iTime * 0.6)); float dTorus = length(q) - 0.28; if (dTorus > 0.24) return 0.0; float n = fbm3(p * 3.8 + vec3(0.0, -iTime * 0.45, 0.0)); return clamp((0.22 - dTorus) * 3.2 + (n - 0.52) * 1.15, 0.0, 1.0) * smoothstep(0.24, 0.02, dTorus); } vec2 intersectAABB(vec3 ro, vec3 rd, vec3 b) { vec3 invR = 1.0 / (rd + vec3(1e-6)); vec3 t0 = (-b - ro) * invR; vec3 t1 = (b - ro) * invR; vec3 tMin = min(t0, t1); vec3 tMax = max(t0, t1); float tN = max(max(tMin.x, tMin.y), tMin.z); float tF = min(min(tMax.x, tMax.y), tMax.z); return vec2(tN, tF); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showVolume = sx >= split; float densScale = clamp(P_DENSITY, 0.3, 3.5); float tileVis = clamp(P_STEP_SKIP, 0.1, 2.0); float orb = iTime * max(P_ORBIT_SPEED, 0.0) + 0.4; vec3 ro = vec3(2.15 * sin(orb), 0.72, 2.15 * cos(orb)); vec3 fw = normalize(-ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.46 + ri * uv.x + up * uv.y); vec3 col = mix(vec3(0.03, 0.045, 0.075), vec3(0.09, 0.13, 0.21), smoothstep(-0.4, 0.6, rd.y)); vec3 boxRad = vec3(0.95, 0.65, 0.95); vec2 hit = intersectAABB(ro, rd, boxRad); if (hit.y > max(hit.x, 0.0)) { float t0 = max(hit.x, 0.05); float t1 = hit.y; vec3 sunDir = normalize(vec3(0.65, 0.78, 0.42)); if (!showVolume) { // Left: NanoVDB hierarchical sparse 8^3 leaf-tile DDA occupancy visualization float gridRes = 5.0; // coarse leaf-brick grid inside bounding domain float trans = 1.0; vec3 acc = vec3(0.0); const int STEPS = 44; float dt = (t1 - t0) / float(STEPS); for (int i = 0; i < STEPS; i++) { vec3 mp = ro + rd * (t0 + (float(i) + 0.5) * dt); vec3 cellId = floor(mp * gridRes); vec3 cellCenter = (cellId + 0.5) / gridRes; // Bitmask occupancy check at NanoVDB leaf tile center float tileDens = evalSparseDensity(cellCenter); if (tileDens > 0.02) { vec3 f = abs(fract(mp * gridRes) - 0.5); float edge = smoothstep(0.055, 0.015, min(min(0.5 - f.x, 0.5 - f.y), 0.5 - f.z)); vec3 tileCol = mix(vec3(0.12, 0.62, 0.95), vec3(0.98, 0.58, 0.16), tileDens); float a = clamp((0.18 + 0.75 * edge) * tileVis * dt * 4.5, 0.0, 0.95); acc += trans * (tileCol * (0.45 + 1.15 * edge)) * a; trans *= (1.0 - a); if (trans < 0.04) break; } } // Subtle outer root-node bounding box frame vec3 ep = abs(abs(ro + rd * t0) - boxRad); float rootWire = smoothstep(0.022, 0.005, min(max(ep.x, ep.y), min(max(ep.y, ep.z), max(ep.z, ep.x)))); col = col * trans + acc + vec3(0.35, 0.85, 1.0) * rootWire * 0.55; } else { // Right: Full NanoVDB pointer-free GPU volumetric raymarching with Henyey-Greenstein scattering float trans = 1.0; vec3 volAcc = vec3(0.0); const int STEPS = 42; float dt = (t1 - t0) / float(STEPS); float hg = 0.25 + 0.75 * pow(max(dot(rd, sunDir), 0.0), 4.0); for (int i = 0; i < STEPS; i++) { vec3 mp = ro + rd * (t0 + (float(i) + 0.5) * dt); float d = evalSparseDensity(mp); if (d > 0.01) { // 4-step shadow march along sun direction float shAcc = 0.0; for (int s = 1; s <= 4; s++) { shAcc += evalSparseDensity(mp + sunDir * (float(s) * 0.11)); } float lTrans = exp(-shAcc * densScale * 0.65); vec3 scatterCol = mix(vec3(0.18, 0.34, 0.56), vec3(1.55, 1.18, 0.76), lTrans) * (0.55 + 0.75 * hg); float ext = d * densScale * 3.4; float stepT = exp(-ext * dt); volAcc += trans * scatterCol * (1.0 - stepT); trans *= stepT; if (trans < 0.02) break; } } col = col * trans + volAcc; } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md) ## Combines with - [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md): Ray-grid traversal with DDA skips empty nodes while stepping through density. - [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md): Provides the source grids to be converted and uploaded. ## Combination ideas - [Scanned objects as SDF primitives](https://texelatlas.vercel.app/ideas/captured-sdf-sculpting/) ## Sources 1. [primary] Ken Museth (2021) NanoVDB: A GPU-Friendly and Portable VDB Data Structure For Real-Time Rendering And Simulation. ACM SIGGRAPH 2021 Talks. https://doi.org/10.1145/3450623.3464653 (verified via crossref on 2026-11-29) 2. [implementation] AcademySoftwareFoundation (2013) AcademySoftwareFoundation/openvdb. https://github.com/AcademySoftwareFoundation/openvdb License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "NanoVDB." https://texelatlas.vercel.app/t/nanovdb/ (accessed 2026-12-01). --- id: "narrow-range-ssf-depth-filter" title: "Narrow-Range Screen-Space Fluid Depth Filtering" aliases: [narrow-range filter, NRF screen-space fluid smoothing, adaptive threshold depth blur] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal] year_introduced: 2018 inputs: [depth, particles] outputs: [depth, normals] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Truong & Yuksel, 2018" url: "https://texelatlas.vercel.app/t/narrow-range-ssf-depth-filter/" sources_verified_at: "2026-11-30" --- # Narrow-Range Screen-Space Fluid Depth Filtering (Truong & Yuksel, 2018) > Smooth splatted particle-fluid depth buffers in two separable passes by dynamically tracking a narrow lower/upper depth band per pixel, preventing foreground droplets from bleeding into background sheets while remaining faster than curvature flow. ## Reach for it when - bilateral blur on screen space fluid depth creates blurry silhouette halos - particle fluid surface looks blobby or bleeds onto background walls - need fast separable depth smoothing for real-time liquid rendering - preserve crisp water foreground edges while smoothing interior particle bumps - eliminate gaussian depth bleeding between overlapping liquid splashes ## How it works In [screen-space-fluid-rendering](screen-space-fluid-rendering), splatting fluid particles as sphere sprites leaves bumpy depth maps that must be smoothed before reconstructing normals. Classical bilateral filters use a fixed range sigma that either leaves particle bumps visible or blends across silhouette gaps, while iterative curvature flow needs dozens of dependent passes. The narrow-range filter replaces the static range kernel with a **running depth interval** `[lower, upper]` initialized around the center pixel's depth (offset by a small multiple of particle radius). As the separable 1D horizontal and vertical passes step outward across neighbors, samples inside the interval contribute with Gaussian spatial weights and gently expand the upper bound to follow smooth curved surfaces. Samples closer than the lower bound are rejected outright so background fluid never pulls toward a foreground splash; samples much farther than the upper bound are clamped to the upper threshold rather than discarded, preserving smooth grazing silhouettes without staircase rims. Because the filter is separable and converges in one to three horizontal-vertical pairs with depth-scaled world-space kernel radii, it produces clean, low-artifact normals at a fraction of curvature flow's pass count. ## When to use it Choose it when rendering real-time particle fluids in WebGL2, WebGPU, or game engines and you want crisp silhouette preservation with far fewer GPU passes than iterative curvature flow. Prefer [screen-space-fluid-rendering](screen-space-fluid-rendering) with curvature flow when you can afford many iterations for maximum smoothness on slow, thick liquids. Prefer [marching-cubes](marching-cubes) or [surface-nets](surface-nets) when you need true 3D water geometry for back-face refraction, reflections, or offline path tracing. Prefer [atrous-wavelet-filter](atrous-wavelet-filter) for general screen-space radiance denoising guided by normals and albedo rather than single-surface particle depth. ## Cost cheap — Separable 1D passes (typically 2 horizontal + 2 vertical iterations at half or full resolution) make it substantially cheaper than 20–40 iterations of curvature flow. Measured GPU Weight: 196.53× baseline (extreme) — 6.4657 ms median / 6.608 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 177.46× baseline (extreme) — 2.8216 ms median (2.29× faster on L4). Ampere A100 scaling: 141.95× baseline (extreme) — 4.0883 ms median (1.58× faster on A100). ## Failure modes - Separable 1D passes can introduce mild axis-aligned cross artifacts on diagonal thin fluid streams unless a small 2D cleanup pass or tuned threshold is used - Screen-space kernel radius must scale inversely with view depth, and clamping the maximum pixel radius limits smoothness at very close camera distances - Too tight a depth threshold leaves individual sphere bumps visible; too wide a threshold merges nearby splashes and detached droplets into webs - Inherits screen-space fluid limits: only the frontmost depth layer exists, so internal overlapping layers and back faces cannot be reconstructed ## Dataflow - Inputs: depth, particles - Outputs: depth, normals - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal ## Presets ### Two-iteration separable narrow-range filter defaults (json-params; parameter preset) ```json { "iterations": 2, "world_radius_to_particle_radius": 2.5, "max_pixel_radius": 18, "depth_threshold_to_particle_radius": 2, "clamping_factor": 1 } ``` Attribution: written for this index ### Narrow-Range SSF Depth Filter — wide bilateral droplet bleeding (left) vs dynamic narrow-band crisp separation (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RANGE_BAND": 0.14, "P_DROP_SPEED": 0.85, "P_SMOOTH_RAD": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_RANGE_BAND = 0.14; // P Narrow Band Width [0.04, 0.35, 0.02] const float P_DROP_SPEED = 0.85; // P Splash Speed [0.0, 2.0, 0.05] const float P_SMOOTH_RAD = 1.00; // P Filter Radius [0.4, 1.8, 0.05] const float P_SPLIT = 0.48; // P Wide / Narrow Split [0.0, 1.0, 0.02] // Evaluate raw splatted particle-fluid screen-space depth buffer z(uv) (smaller z = closer to camera!) // Foreground flying droplets (z ~ 1.15) pass directly in front of a background liquid wave sheet (z ~ 2.35) float evalFluidDepth(vec2 uv, float tAnim) { float minZ = 10.0; // Background fluid wave sheet made of overlapping splatted spheres (z around 2.25..2.55) for (int i = 0; i < 14; i++) { float fi = float(i); float px = -0.78 + fi * 0.12 + 0.04 * sin(tAnim * 1.4 + fi); float py = -0.18 + 0.16 * sin(fi * 0.72 + tAnim * 1.8) + 0.05 * cos(fi * 1.5); float r = 0.165; vec2 d = uv - vec2(px, py); float r2 = dot(d, d); if (r2 < r * r) { float z = 2.38 - sqrt(r * r - r2) * 1.35; minZ = min(minZ, z); } } // Second lower row of background sheet particles for (int i = 0; i < 12; i++) { float fi = float(i); float px = -0.68 + fi * 0.125; float py = -0.34 + 0.08 * cos(fi * 0.9 - tAnim * 1.5); float r = 0.18; vec2 d = uv - vec2(px, py); float r2 = dot(d, d); if (r2 < r * r) { float z = 2.30 - sqrt(r * r - r2) * 1.35; minZ = min(minZ, z); } } // Foreground splashing droplets arc (much closer: z ~ 1.08..1.25!) crossing in front of the background sheet! for (int i = 0; i < 6; i++) { float fi = float(i); float phase = fract(tAnim * 0.24 + fi * 0.165); float px = mix(-0.62, 0.62, phase); float py = -0.26 + 0.68 * (4.0 * phase * (1.0 - phase)) + 0.04 * sin(fi * 3.1); float r = 0.082 + 0.018 * sin(fi * 2.3); vec2 d = uv - vec2(px, py); float r2 = dot(d, d); if (r2 < r * r) { float z = 1.18 - sqrt(r * r - r2) * 1.25; minZ = min(minZ, z); } } return minZ; } // Narrow-range vs naive wide screen-space depth smoothing (Truong & Yuksel 2018) float evalFilteredDepth(vec2 uv, float tAnim, float band, float rad, bool useNarrow) { float z0 = evalFluidDepth(uv, tAnim); if (z0 > 5.0) return 10.0; // Dynamic narrow-range lower/upper depth envelope tracked around z0 float zLow = z0 - band; float zHigh = z0 + band; float accZ = z0; float accW = 1.0; float stepUv = 0.017 * rad; for (int j = -2; j <= 2; j++) { for (int i = -2; i <= 2; i++) { if (i == 0 && j == 0) continue; vec2 off = vec2(float(i), float(j)) * stepUv; float zn = evalFluidDepth(uv + off, tAnim); if (zn > 5.0) continue; float spW = exp(-dot(vec2(float(i), float(j)), vec2(float(i), float(j))) * 0.22); if (useNarrow) { // Narrow-range filter: reject background samples > zHigh, clamp near samples < zLow, dynamically tighten band! if (zn <= zHigh) { float clampedZ = max(zn, zLow); accZ += clampedZ * spW; accW += spW; zHigh = min(zHigh, clampedZ + band); zLow = max(zLow, clampedZ - band); } } else { // Wide bilateral/Gaussian blur: averages foreground droplets (z~1.18) with background sheet (z~2.35) -> ugly webbing! float dz = abs(zn - z0); float rngW = exp(-dz * dz * 0.65); float w = spW * rngW; accZ += zn * w; accW += w; } } } return accZ / max(accW, 1e-4); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useNarrow = sx >= split; float band = clamp(P_RANGE_BAND, 0.03, 0.45); float tAnim = iTime * max(P_DROP_SPEED, 0.0); float rad = clamp(P_SMOOTH_RAD, 0.3, 2.0); // Subtle tile backdrop behind the transparent fluid vec2 tile = floor((uv + vec2(0.0, 0.1)) * 9.0); vec3 bg = mix(vec3(0.09, 0.12, 0.17), vec3(0.15, 0.19, 0.26), mod(tile.x + tile.y, 2.0)); vec3 col = bg; float z = evalFilteredDepth(uv, tAnim, band, rad, useNarrow); if (z < 5.0) { float e = 0.008; float zx = evalFilteredDepth(uv + vec2(e, 0.0), tAnim, band, rad, useNarrow); float zy = evalFilteredDepth(uv + vec2(0.0, e), tAnim, band, rad, useNarrow); float dx = (zx < 5.0) ? (zx - z) / e : 0.0; float dy = (zy < 5.0) ? (zy - z) / e : 0.0; vec3 N = normalize(vec3(-dx * 0.48, -dy * 0.48, 1.0)); vec3 V = vec3(0.0, 0.0, 1.0); vec3 L = normalize(vec3(0.55, 0.72, 0.65)); vec3 H = normalize(L + V); // Refracted background tile + Beer-Lambert liquid tint + crisp Fresnel sky reflection vec2 refrUv = uv + N.xy * 0.075; vec2 rTile = floor((refrUv + vec2(0.0, 0.1)) * 9.0); vec3 refrBg = mix(vec3(0.08, 0.14, 0.22), vec3(0.18, 0.28, 0.38), mod(rTile.x + rTile.y, 2.0)); // Highlight depth separation: closer droplets glow brighter cyan-white, background sheet deeper cobalt vec3 tint = mix(vec3(0.18, 0.74, 0.94), vec3(0.06, 0.34, 0.62), smoothstep(1.15, 2.35, z)); float fres = 0.06 + 0.88 * pow(1.0 - max(dot(N, V), 0.0), 4.0); float spec = pow(max(dot(N, H), 0.0), 72.0) * 1.9; vec3 skyR = mix(vec3(0.22, 0.46, 0.75), vec3(0.88, 0.95, 1.0), smoothstep(-0.2, 0.8, reflect(-V, N).y)); col = mix(refrBg * tint * 1.65 + tint * 0.25, skyR, fres) + vec3(1.0, 0.98, 0.92) * spec; } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Screen-space fluid rendering (curvature flow)](https://texelatlas.vercel.app/t/screen-space-fluid-rendering.md) ## Combines with - [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md): FLIP particle positions splat sphere depths and additive thickness that the narrow-range filter smooths into a coherent liquid surface. - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Noise-free view normals reconstructed from the filtered depth buffer drive refractive bending and caustic projection. - [Weighted blended order-independent transparency](https://texelatlas.vercel.app/t/weighted-blended-oit.md): Aerated spray and foam sprites composite cleanly over the filtered opaque-style liquid depth surface. ## Combination ideas - [Narrow-range SSF liquid with whitewater and wet-ground reaction field](https://texelatlas.vercel.app/ideas/narrow-range-ssf-whitewater-ground-field/) ## Sources 1. [primary] Nghia Truong, Cem Yuksel (2018) A Narrow-Range Filter for Screen-Space Fluid Rendering. Proceedings of the ACM on Computer Graphics and Interactive Techniques. https://doi.org/10.1145/3203201 (verified via crossref on 2026-11-30) 2. [implementation] Humpalumps (2026) Humpalumps/ultra-elements. https://github.com/Humpalumps/ultra-elements License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Narrow-Range Screen-Space Fluid Depth Filtering." https://texelatlas.vercel.app/t/narrow-range-ssf-depth-filter/ (accessed 2026-12-01). --- id: "nerf" title: "Neural Radiance Fields (NeRF)" aliases: [NeRF] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, python] year_introduced: 2020 inputs: [photos, camera-poses] outputs: [radiance-field] style: "photoreal" dynamic: "static" cost: "offline" authority: "Mildenhall et al., 2020" url: "https://texelatlas.vercel.app/t/nerf/" sources_verified_at: "2026-11-29" --- # Neural Radiance Fields (NeRF) (Mildenhall et al., 2020) > Represents a scene as an MLP mapping position and view direction to density and colour, trained by differentiable volume rendering to reproduce posed input photos. ## Reach for it when - synthesise new views from a set of photos - want an implicit volumetric scene representation - learn a scene's geometry and colour from images alone - photo capture to view-dependent renders with a neural net - baseline for neural scene reconstruction ## How it works An MLP takes a 3D point (after sinusoidal positional encoding) and viewing direction and outputs volume density and view-dependent RGB. To render a pixel, rays are cast through the camera, points are sampled along each ray (coarse then importance-sampled fine), and colours are alpha-composited using the densities. The loss is simply the photometric error against the training image, and gradients flow through the compositing into the network. Density depends only on position and colour on position plus direction, which encourages consistent geometry with specular effects. Training needs camera poses, typically from [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md). The original takes hours per scene and seconds per frame, which later work cut by orders of magnitude. ## When to use it Choose it as a conceptual baseline or when you need an implicit volumetric representation to experiment with. Prefer [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md) for the same model trained in seconds, [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for real-time rendering, and [NeuS](https://texelatlas.vercel.app/t/neus.md) or [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) when you need a clean surface rather than a density field. ## Cost offline — Original formulation: hours of training and several seconds per rendered frame on a single GPU, per the paper's reported setup. Measured GPU Weight: 127.68× baseline (extreme) — 3.9582 ms median / 4.2383 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 110.75× baseline (extreme) — 1.761 ms median (2.25× faster on L4). Ampere A100 scaling: 86.51× baseline (extreme) — 2.4914 ms median (1.59× faster on A100). ## Failure modes - Floaters and fog in empty space when views are sparse or poses are noisy - Blurry or aliased renders at differing zoom levels because rays are treated as infinitely thin - Extracted geometry from density is bumpy and not watertight - Unbounded scenes and distant backgrounds need special parameterisation or they collapse ## Engine support - blender: plugin — `Blender add-on: BlenderNeRF (dataset/camera export for NeRF training)` (evidence: https://github.com/maximeraafat/BlenderNeRF, checked 2026-12-01) — Creates synthetic NeRF datasets; training is external. ## Dataflow - Inputs: photos, camera-poses - Outputs: radiance-field - Platforms: cuda, python ## Presets ### NeRF Volumetric Raymarching — transmittance & density field (left) vs view-dependent radiance (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SIGMA_SCALE": 4.5, "P_VIEW_DEP": 1, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_SIGMA_SCALE = 4.5; // P Density Sigma [1.0, 10.0, 0.25] const float P_VIEW_DEP = 1.0; // P View-Dep Spec [0.0, 2.0, 0.05] const float P_ROT_SPEED = 0.65; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Density / NeRF Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Continuous neural radiance field F_theta(x, d) -> (sigma, rgb) // Encodes a translucent iridescent botanical lotus-torus with nested glowing filaments void evalNeRF(vec3 p, vec3 rd, float sigmaGain, float viewGain, out float sigma, out vec3 rad) { float r = length(p); // Outer translucent shell + nested twisted rings vec2 qTor = vec2(length(p.xz) - 0.48, p.y); float dRing = length(qTor) - 0.16; float ang = atan(p.z, p.x); float petals = 0.075 * sin(ang * 5.0 + p.y * 6.0) * cos(r * 8.0); float dCore = length(p) - 0.30 + petals * 0.6; float dHalo = abs(length(p) - 0.64) - 0.045; // Soft continuous volume density sigma(x) >= 0 (ReLU-like softplus around implicit shells) float sCore = exp(-max(dCore, 0.0) * 18.0) * smoothstep(0.18, -0.05, dCore); float sRing = exp(-max(dRing, 0.0) * 20.0) * smoothstep(0.14, -0.04, dRing); float sHalo = exp(-abs(dHalo) * 32.0) * 0.42; // Fine high-frequency positional-encoding gamma(x) volumetric veins float peVeins = 0.55 + 0.45 * sin(p.x * 14.0 + p.y * 11.0) * cos(p.z * 14.0); sigma = (sCore * 1.15 + sRing * 0.95 + sHalo * peVeins) * sigmaGain; // Gradient proxy for view-dependent radiance c(x, d) vec3 nEst = normalize(p + vec3(0.001)); float ndv = clamp(dot(nEst, -rd), 0.0, 1.0); float fres = pow(1.0 - ndv, 2.5); vec3 coreCol = mix(vec3(0.96, 0.42, 0.18), vec3(1.0, 0.86, 0.32), smoothstep(-0.25, 0.35, p.y)); vec3 ringCol = mix(vec3(0.12, 0.68, 0.96), vec3(0.68, 0.32, 0.96), 0.5 + 0.5 * sin(ang * 2.0)); vec3 baseC = (sCore > sRing) ? coreCol : ringCol; baseC = mix(baseC, vec3(0.24, 0.96, 0.84), sHalo / max(sCore + sRing + sHalo, 1e-4)); // View-dependent directional MLP color term (iridescent Fresnel rim + anisotropic highlight) vec3 lDir = normalize(vec3(0.55, 0.78, 0.45)); float spec = pow(max(dot(nEst, normalize(lDir - rd)), 0.0), 28.0); vec3 viewShift = (vec3(0.32, 0.78, 1.0) * fres * 0.72 + vec3(1.0, 0.95, 0.88) * spec * 0.85) * viewGain; rad = baseC * (0.45 + 0.65 * max(dot(nEst, lDir), 0.0)) + viewShift; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isRadiance = screenX >= split; float sigmaGain = clamp(P_SIGMA_SCALE, 0.8, 12.0); float viewGain = clamp(P_VIEW_DEP, 0.0, 2.2); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.24, 2.25); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.04), -1.52)); // Orbit camera around volume ro.xz = rot2(spin * 0.55) * ro.xz; rd.xz = rot2(spin * 0.55) * rd.xz; vec3 bg = mix(vec3(0.020, 0.028, 0.048), vec3(0.056, 0.075, 0.125), smoothstep(-0.55, 0.55, uv.y)); // Bounding sphere intersection R = 1.05 for stratified NeRF quadrature float b = dot(ro, rd); float c = dot(ro, ro) - 1.05 * 1.05; float disc = b * b - c; vec3 accum = vec3(0.0); float T = 1.0; float expectedDepth = 0.0; float weightSum = 0.0; if (disc > 0.0) { float tNear = max(-b - sqrt(disc), 0.1); float tFar = -b + sqrt(disc); int steps = 48; float dt = (tFar - tNear) / float(steps); for (int i = 0; i < 48; i++) { float t = tNear + (float(i) + 0.5) * dt; vec3 p = ro + rd * t; float sigma; vec3 rad; evalNeRF(p, rd, sigmaGain, viewGain, sigma, rad); // Exact NeRF volume rendering quadrature: alpha_i = 1 - exp(-sigma_i * dt) float alpha = 1.0 - exp(-sigma * dt); float w = T * alpha; accum += w * rad; expectedDepth += w * (t - tNear) / max(tFar - tNear, 1e-4); weightSum += w; T *= (1.0 - alpha); if (T < 0.01) break; } } vec3 col; if (!isRadiance) { // Left: accumulated opacity (1 - T) & expected termination depth colormap (turbo-like plasma ramp) float op = 1.0 - T; float dNorm = clamp(expectedDepth / max(weightSum, 1e-4), 0.0, 1.0); vec3 depthCol = mix(vec3(0.12, 0.88, 0.94), vec3(0.98, 0.42, 0.16), dNorm); depthCol = mix(depthCol, vec3(0.54, 0.24, 0.94), smoothstep(0.6, 1.0, dNorm)); // Iso-depth bands visualizing discrete raymarch quadrature samples float bands = 0.78 + 0.22 * cos(dNorm * 32.0); col = mix(bg, depthCol * bands * 1.15, op); } else { // Right: full NeRF alpha-composited view-dependent radiance col = accum + T * bg; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md) - extended by [Mip-NeRF 360](https://texelatlas.vercel.app/t/mip-nerf-360.md) ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): COLMAP poses are the camera input that NeRF training assumes. ## Combination ideas - [Baking trained NeRF radiance fields into directional mesh lightmaps](https://texelatlas.vercel.app/ideas/nerf-oracle-lightmap-baking/) ## Sources 1. [primary] Ben Mildenhall, Pratul P. Srinivasan, Matthew Tancik, Jonathan T. Barron, Ravi Ramamoorthi, Ren Ng (2020) NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis. arXiv preprint (cs.CV). https://arxiv.org/abs/2003.08934 (verified via arxiv on 2026-11-29) 2. [implementation] bmild (2020) bmild/nerf. https://github.com/bmild/nerf License: MIT. (verified via github on 2026-11-29) 3. [implementation] nerfstudio-project (2022) nerfstudio-project/nerfstudio. https://github.com/nerfstudio-project/nerfstudio License: Apache-2.0. (verified via github on 2026-11-29) 4. [tutorial] Nerfstudio team Nerfstudio documentation. docs.nerf.studio. https://docs.nerf.studio/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Neural Radiance Fields (NeRF)." https://texelatlas.vercel.app/t/nerf/ (accessed 2026-12-01). --- id: "nerfstudio" title: "Nerfstudio" aliases: [nerfstudio, nerf.studio, nerfacto] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, python] year_introduced: 2023 inputs: [photos, camera-poses] outputs: [radiance-field, gaussians, mesh] style: "photoreal" dynamic: "static" cost: "offline" authority: "Tancik et al., 2023" url: "https://texelatlas.vercel.app/t/nerfstudio/" sources_verified_at: "2026-11-29" --- # Nerfstudio (Tancik et al., 2023) > A modular open-source framework that wraps data loading, camera handling, model implementations, training, a web viewer and export tools for NeRFs, and now Gaussian splats, behind one command-line workflow. ## Reach for it when - want to train a nerf from my phone video - need a ready pipeline from photos to splats - compare several radiance field methods with one toolchain - browser viewer for a training radiance field ## How it works The pipeline separates concerns into interchangeable parts: a data parser that reads COLMAP, Polycam, Record3D or transforms files; a data manager that samples rays and manages camera optimisation; a model that defines fields, samplers and renderers; and a pipeline that glues them. `ns-process-data` runs feature matching and structure-from-motion to produce poses. `ns-train` picks a method by name, for example the default `nerfacto`, which combines hash-grid encoding, proposal sampling and per-image appearance embeddings, or `splatfacto`, which trains Gaussian splats on the [gsplat](https://texelatlas.vercel.app/t/gsplat.md) rasteriser. Training streams to a browser-based viewer so you can inspect progress and set camera paths. `ns-export` writes point clouds, meshes and splat files and `ns-render` outputs video. New methods register through a plugin entry point, so research code reuses the same data and viewer plumbing. ## When to use it Choose it when you want a working radiance-field or splat pipeline from phone or camera data without wiring components yourself, or a shared harness for comparing methods. Prefer [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md) for the fastest bare hash-grid NeRF and a native GUI, [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) reference code for faithful reproduction of the original paper, [gsplat](https://texelatlas.vercel.app/t/gsplat.md) when you need only the rasteriser library, and [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md) standalone for pose estimation alone. ## Cost offline — Training takes minutes to an hour per scene on a single desktop GPU depending on the method and scene; consult the project docs for specific figures. ## Failure modes - Poor poses from SfM on textureless, reflective or blurred captures lead to ghosting that no model setting fixes - Default scene scaling and orientation conventions mismatch other tools when exporting, so imported splats or meshes appear rotated or scaled - Method-specific dependencies (tiny-cuda-nn, gsplat) are fragile across CUDA and PyTorch versions - Exported meshes from density fields are noisy compared with surface-oriented methods ## Dataflow - Inputs: photos, camera-poses - Outputs: radiance-field, gaussians, mesh - Platforms: cuda, python ## Combines with - [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md): COLMAP-derived camera poses and sparse points are what the nerfstudio data parser consumes to start training. - [gsplat](https://texelatlas.vercel.app/t/gsplat.md): The splatfacto method renders and trains Gaussians through the gsplat CUDA rasteriser. ## Sources 1. [primary] Matthew Tancik, Ethan Weber, Evonne Ng, Ruilong Li, Brent Yi, Justin Kerr, Terrance Wang, Alexander Kristoffersen, Jake Austin, Kamyar Salahi, Abhik Ahuja, David McAllister, Angjoo Kanazawa (2023) Nerfstudio: A Modular Framework for Neural Radiance Field Development. arXiv preprint (cs.CV). https://arxiv.org/abs/2302.04264 (verified via arxiv on 2026-11-29) 2. [implementation] nerfstudio-project (2022) nerfstudio-project/nerfstudio. https://github.com/nerfstudio-project/nerfstudio License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Nerfstudio." https://texelatlas.vercel.app/t/nerfstudio/ (accessed 2026-12-01). --- id: "neural-cellular-automata-textures" title: "Neural Cellular Automata for Textures" aliases: [Self-organising textures, NCA textures] domain: "genai" stage: "generation" realtime: "realtime" platforms: [webgl2, python] year_introduced: 2021 inputs: [ldr-image] outputs: [texture] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Mordvintsev et al., 2021" url: "https://texelatlas.vercel.app/t/neural-cellular-automata-textures/" sources_verified_at: "2026-11-29" --- # Neural Cellular Automata for Textures (Mordvintsev et al., 2021) > A pixel-grid automaton whose update rule is a tiny CNN, trained so the grid self-organises into a target texture; it runs in real time on a GPU shader and heals when damaged. ## Reach for it when - generate tileable textures from a small learned model - texture that grows and regenerates itself - synthesize textures with tiny network and low memory - animated organic patterns from local rules ## How it works Each pixel is a cell with a small state vector. The update step is: apply fixed filters (identity, Sobel gradients, Laplacian) to build a perception vector, pass it through a small MLP to produce an increment, and add it to the cell state with a random fire rate so updates stay asynchronous. The rule is trained by unrolling many steps and minimising a style loss (Gram matrices of pretrained-network features) against an exemplar, so the pattern is not copied but has the same statistics. Since the rule is local and tiny, it can be turned into a fragment shader, runs on any resolution, and the pattern regrows after you erase part of it. ## When to use it Choose it for animated, procedural-looking tiling textures with a small weights budget and interactive behaviour. Prefer [Mesh Neural Cellular Automata (MeshNCA)](https://texelatlas.vercel.app/t/mesh-neural-cellular-automata.md) to run on mesh vertices, and a classic noise or [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md)-style generation when you need a single prompt-specific texture rather than a reusable rule. ## Cost cheap — Rule is a few thousand weights; qualitative GPU cost is low per step. Measured GPU Weight: 112.74× baseline (extreme) — 3.7093 ms median / 4.0252 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 103.3× baseline (extreme) — 1.6425 ms median (2.26× faster on L4). Ampere A100 scaling: 81.46× baseline (extreme) — 2.346 ms median (1.58× faster on A100). ## Failure modes - Struggles with long-range structure and semantic layouts - Training per texture and sensitivity to hyperparameters - Patterns can drift or diverge when stepped far beyond the trained horizon - Style loss gives statistically similar rather than pixel-exact results ## Dataflow - Inputs: ldr-image - Outputs: texture - Platforms: webgl2, python ## Presets ### Neural Cellular Automata — noisy perception seed (left) vs self-organized living texture (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GROWTH_T": 0.78, "P_KERNEL_FREQ": 6.5, "P_MORPH_MIX": 0.55, "P_SPLIT": 0.44 } ``` ```glsl const float P_GROWTH_T = 0.78; // P Growth Steps [0.1, 1.0, 0.02] const float P_KERNEL_FREQ = 6.5; // P Perception Scale [3.0, 12.0, 0.25] const float P_MORPH_MIX = 0.55; // P Morphogen Mix [0.0, 1.0, 0.02] const float P_SPLIT = 0.44; // P Seed / NCA Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y ); } // Multi-channel latent state s(x) perturbed by learned Sobel + Laplacian perception updates vec4 evalNCAState(vec2 p, float t, float freq, float morph) { vec2 q = p * freq; // Iterative local-neighborhood perception (approximates 4 CNN update steps via curl & Laplacian feedback) for (int i = 0; i < 4; i++) { float fi = float(i) + 1.0; float e = 0.14 / fi; float c0 = vnoise(q + vec2(t * 0.12, -t * 0.09)); float cx = vnoise(q + vec2(e, 0.0) + vec2(t * 0.12, -t * 0.09)) - vnoise(q - vec2(e, 0.0) + vec2(t * 0.12, -t * 0.09)); float cy = vnoise(q + vec2(0.0, e) + vec2(t * 0.12, -t * 0.09)) - vnoise(q - vec2(0.0, e) + vec2(t * 0.12, -t * 0.09)); float lap = vnoise(q + vec2(e, 0.0)) + vnoise(q - vec2(e, 0.0)) + vnoise(q + vec2(0.0, e)) + vnoise(q - vec2(0.0, e)) - 4.0 * c0; // Anisotropic Sobel curl + reaction-diffusion update vec2 grad = vec2(cx, cy) * (1.8 + morph * 1.4); q += vec2(-grad.y, grad.x) * 0.38 + vec2(lap * 0.45, -lap * 0.35); } float ridgeA = sin(q.x * 2.4 + cos(q.y * 2.1 + t * 0.45)); float ridgeB = cos(q.y * 2.7 - sin(q.x * 2.3 - t * 0.35)); float activator = smoothstep(-0.35, 0.65, ridgeA * 0.55 + ridgeB * 0.45); float inhibitor = smoothstep(-0.2, 0.8, sin(length(q - floor(q + 0.5)) * 6.2831853)); float vein = exp(-abs(ridgeA + ridgeB * 0.65) * 4.2); float hidden = vnoise(q * 1.6); return vec4(activator, inhibitor, vein, hidden); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float growth = clamp(P_GROWTH_T, 0.05, 1.0); float freq = clamp(P_KERNEL_FREQ, 2.5, 14.0); float morph = clamp(P_MORPH_MIX, 0.0, 1.0); // Regeneration wave pulsing outward from two living seeds float rSeed1 = length(uv - vec2(-0.18, 0.08)); float rSeed2 = length(uv - vec2(0.24, -0.14)); float rMin = min(rSeed1, rSeed2); float front = fract(iTime * 0.14) * 1.15 + growth * 0.65; float alive = smoothstep(front + 0.14, front - 0.06, rMin); vec4 st = evalNCAState(uv, iTime * 0.55, freq, morph); // Compute surface normal from finite difference of activator channel for tactile depth float eps = 0.008; float hC = st.x * 0.65 + st.z * 0.45; float hX = evalNCAState(uv + vec2(eps, 0.0), iTime * 0.55, freq, morph).x * 0.65; float hY = evalNCAState(uv + vec2(0.0, eps), iTime * 0.55, freq, morph).x * 0.65; vec3 n = normalize(vec3((hC - hX) * 14.0, (hC - hY) * 14.0, 1.0)); vec3 lDir = normalize(vec3(0.55, 0.68, 0.72)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir + vec3(0.0, 0.0, 1.0))), 0.0), 36.0); // Organic living coral/malachite palette driven by 4 hidden NCA channels vec3 deep = vec3(0.03, 0.10, 0.14); vec3 teal = vec3(0.08, 0.58, 0.54); vec3 amber = vec3(0.95, 0.58, 0.16); vec3 ivory = vec3(0.96, 0.91, 0.78); vec3 ncaCol = mix(deep, teal, st.x); ncaCol = mix(ncaCol, amber, st.z * (0.45 + 0.55 * morph)); ncaCol = mix(ncaCol, ivory, smoothstep(0.62, 0.95, st.z * st.y) * 0.65); ncaCol = ncaCol * (0.38 + 0.78 * diff) + vec3(0.85, 0.94, 0.98) * spec * 0.35; // Highlight active self-organization wave front float waveRing = exp(-abs(rMin - front) * 28.0) * 0.45; ncaCol += vec3(0.25, 0.95, 0.85) * waveRing; ncaCol = mix(vec3(0.04, 0.06, 0.09) + vec3(0.05) * hash21(floor(fragCoord * 0.25)), ncaCol, clamp(alive + 0.28, 0.0, 1.0)); // Left side: raw quantized seed grid & Sobel perception kernel overlay vec2 cell = floor(uv * 28.0); vec2 cf = fract(uv * 28.0); float seedVal = hash21(cell + floor(iTime * 0.8) * 0.07); float gridLine = smoothstep(0.08, 0.02, min(cf.x, cf.y)); vec3 seedCol = mix(vec3(0.04, 0.06, 0.10), vec3(0.18, 0.46, 0.62), seedVal * 0.8); seedCol += vec3(0.12, 0.22, 0.30) * gridLine; // Visualize 3x3 Sobel perception rings around the two seeds float kernelVis = exp(-abs(rMin - 0.16) * 45.0) + exp(-abs(rMin - 0.08) * 65.0) * 0.6; seedCol += vec3(0.98, 0.66, 0.20) * kernelVis; seedCol = mix(seedCol, ncaCol, smoothstep(0.22, 0.03, rMin) * 0.9); vec3 col = (screenX < split) ? seedCol : ncaCol; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Alexander Mordvintsev, Eyvind Niklasson, Ettore Randazzo (2021) Texture Generation with Neural Cellular Automata. arXiv preprint (cs.AI). https://arxiv.org/abs/2105.07299 (verified via arxiv on 2026-11-29) 2. [implementation] google-research (2020) google-research/self-organising-systems. https://github.com/google-research/self-organising-systems License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Neural Cellular Automata for Textures." https://texelatlas.vercel.app/t/neural-cellular-automata-textures/ (accessed 2026-12-01). --- id: "neural-radiance-caching" title: "Neural Radiance Caching" aliases: [NRC] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, cuda] year_introduced: 2021 inputs: [gbuffer, mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Müller et al., 2021" url: "https://texelatlas.vercel.app/t/neural-radiance-caching/" sources_verified_at: "2026-11-29" --- # Neural Radiance Caching (Müller et al., 2021) > Trains a small neural network online, every frame, to predict outgoing radiance at any surface point. Short path-traced paths end at a cache query, giving multi-bounce GI with one or two samples per pixel. ## Reach for it when - want path-traced global illumination in real time with few samples - multi-bounce lighting too noisy at one sample per pixel - dynamic scene needs learned indirect light cache - need predictable per-frame cost for path tracing ## How it works The cache is a compact MLP (with a multiresolution hash-encoded input) that maps position, normal, view direction and material parameters to outgoing radiance. It is trained **while rendering**, with no precomputed data. Each frame has two kinds of paths. **Render paths** start at the camera, and after one or two bounces query the cache and stop, so the image is cheap. A tiny fraction of paths are extended into longer **training paths**: they are traced several bounces and the radiance estimate at each vertex becomes a training target for the network, computed by accumulating the actual downstream path contributions and, for the tail, the cache's own prediction (a self-bootstrapping scheme like value iteration in reinforcement learning). The network takes a handful of gradient steps per frame on these samples, so it tracks changes in light and geometry within a few frames. Fully-fused GPU kernels make the inference and training fast enough for real time. A lag and a smoothing step in the feature encoding keep the cache stable. ## When to use it Choose it for real-time path-traced GI in dynamic scenes with ray tracing and tensor-core class hardware, when predictable per-frame cost and multi-bounce light matter more than exactness. Prefer [sharc](sharc) when you want a simple, deterministic hash-grid radiance cache with no network and lower hardware requirements. Prefer [restir-pt](restir-pt) when you want unbiased reuse rather than a biased cache. Prefer [ddgi](ddgi) for low-frequency diffuse GI without a neural network. ## Cost heavy — The paper reports interactive rates for path-traced scenes on an NVIDIA RTX-class GPU; training and inference each take around a millisecond or more at 1080p. Measured GPU Weight: 21.92× baseline (heavy) — 0.7212 ms median / 0.7983 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.69× baseline (heavy) — 0.3448 ms median (2.09× faster on L4). Ampere A100 scaling: 14.08× baseline (moderate) — 0.4056 ms median (1.78× faster on A100). ## Failure modes - Cache bias: the network is smooth, so sharp indirect detail and caustics are blurred and can lag lighting changes - Temporal instability or flicker when training samples are sparse in a region, plus a warm-up delay on scene load - Requires specialized fused GPU kernels; a naive implementation is slow - Cache feeds back on itself, so a single bad prediction can persist and brighten over frames ## Dataflow - Inputs: gbuffer, mesh, material-params - Outputs: radiance - Platforms: desktop-gpu, cuda ## Presets ### Neural Radiance Caching (NRC) — 1-bounce noisy PT (left) vs real-time MLP multi-bounce cache (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CACHE_GAIN": 1.15, "P_LIGHT_SWEEP": 0.75, "P_TRAIN_VIS": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_CACHE_GAIN = 1.15; // P Multi-Bounce GI [0.2, 2.0, 0.05] const float P_LIGHT_SWEEP = 0.75; // P Dynamic Light [0.0, 2.2, 0.05] const float P_TRAIN_VIS = 0.65; // P Cache Query Glow [0.0, 1.4, 0.05] const float P_SPLIT = 0.48; // P 1-Bounce / NRC [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Multi-alcove gallery room where dynamic colored bounce light must traverse 3+ bounces into recessed corners! vec2 mapGallery(vec3 p) { float dFloor = p.y + 0.85; float dCeil = 0.85 - p.y; float dLeft = p.x + 1.15; float dRight = 1.15 - p.x; float dBack = p.z + 1.35; vec2 res = vec2(dFloor, 1.0); if (dCeil < res.x) res = vec2(dCeil, 1.0); if (dBack < res.x) res = vec2(dBack, 1.0); if (dLeft < res.x) res = vec2(dLeft, 2.0); // vivid magenta-red wall if (dRight < res.x) res = vec2(dRight, 3.0); // vivid cobalt-cyan wall // Two sculptural gallery pillars creating deep indirect shadow alcoves vec3 p1 = abs(p - vec3(-0.42, -0.25, -0.35)) - vec3(0.20, 0.60, 0.22); float dP1 = length(max(p1, 0.0)) + min(max(p1.x, max(p1.y, p1.z)), 0.0); if (dP1 < res.x) res = vec2(dP1, 4.0); float dOrb = length(p - vec3(0.38, -0.45, -0.22)) - 0.36; if (dOrb < res.x) res = vec2(dOrb, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapGallery(p + e.xyy).x - mapGallery(p - e.xyy).x, mapGallery(p + e.yxy).x - mapGallery(p - e.yxy).x, mapGallery(p + e.yyx).x - mapGallery(p - e.yyx).x )); } // Smooth online-trained MLP neural radiance field approximation L_cache(x, n) for dynamic light position lPos vec3 evalNeuralCache(vec3 p, vec3 n, vec3 lPos, float gain) { // Warm direct-bounce lobe from wall nearest the moving light float leftHit = smoothstep(0.6, -0.9, lPos.x); float rightHit = smoothstep(-0.6, 0.9, lPos.x); vec3 bounceL = vec3(0.96, 0.22, 0.36) * (0.45 + 0.95 * leftHit) * max(dot(n, normalize(vec3(-1.15, 0.0, -0.2) - p)), 0.0); vec3 bounceR = vec3(0.14, 0.66, 0.98) * (0.45 + 0.95 * rightHit) * max(dot(n, normalize(vec3(1.15, 0.0, -0.2) - p)), 0.0); // Higher-order infinite-bounce diffuse ambient term queried instantaneously from NRC MLP! vec3 multiBounce = mix(vec3(0.36, 0.18, 0.24), vec3(0.16, 0.28, 0.42), 0.5 + 0.5 * p.x) * (0.55 + 0.45 * n.y); return (bounceL * 0.52 + bounceR * 0.52 + multiBounce * 0.55) * gain; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isNRC = screenX >= split; float gain = clamp(P_CACHE_GAIN, 0.15, 2.2); float sweep = iTime * max(P_LIGHT_SWEEP, 0.0); float vis = clamp(P_TRAIN_VIS, 0.0, 1.5); vec3 ro = vec3(0.0, 0.06, 2.18); vec3 rd = normalize(vec3(uv, -1.36)); float t = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapGallery(ro + rd * t); if (h.x < 0.0025) { hit = vec2(t, h.y); break; } t += h.x; if (t > 7.0) break; } vec3 col = vec3(0.02, 0.024, 0.04); if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 alb = vec3(0.76, 0.76, 0.78); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.92, 0.18, 0.34); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.14, 0.64, 0.94); else if (hit.y > 3.5 && hit.y < 4.5) alb = vec3(0.84, 0.82, 0.78); else if (hit.y > 4.5) alb = vec3(0.90, 0.84, 0.74); // Dynamic moving spotlight sweeping between red and cyan walls vec3 lPos = vec3(0.78 * sin(sweep * 0.75), 0.62, 0.25 * cos(sweep * 0.75) - 0.15); vec3 toL = lPos - p; float dL = length(toL); vec3 lDir = toL / max(dL, 1e-4); // Quick shadow march toward dynamic light float sh = 1.0; float ts = 0.04; for (int s = 0; s < 16; s++) { float ds = mapGallery(p + lDir * ts).x; if (ds < 0.004) { sh = 0.0; break; } ts += max(ds, 0.04); if (ts > dL - 0.08) break; } vec3 direct = alb * vec3(1.0, 0.95, 0.88) * max(dot(n, lDir), 0.0) * sh * (1.8 / (0.55 + dL * dL)); vec3 nrcGI = alb * evalNeuralCache(p, n, lPos, gain); if (isNRC) { // Right: Full multi-bounce NRC MLP cache terminates short paths with clean infinite-bounce radiance! col = direct + nrcGI; // Subtle animated neural-cache training suffix probe rings on floor/walls float probeWave = exp(-abs(fract(length(p - lPos) * 1.4 - sweep * 0.35) - 0.5) * 32.0); col += vec3(0.24, 0.94, 0.88) * probeWave * 0.14 * vis; } else { // Left: 1-bounce path tracing without NRC loses multi-bounce corner fill & suffers 1-spp shadow-zone noise! float r1 = hash21(floor(fragCoord * 0.8) + floor(iTime * 11.0) * 0.17); col = direct + nrcGI * 0.28 * mix(0.2, 1.9, r1); } // Glowing floating light sphere marker float dLightOrb = length(cross(lPos - ro, rd)); col += vec3(1.0, 0.94, 0.80) * exp(-dLightOrb * 24.0) * 0.65; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Short camera paths terminate in a cache query instead of tracing all bounces. ## Combination ideas - [Toon-banded bounce light, learned live](https://texelatlas.vercel.app/ideas/stylized-bounce-radiance-cache/) ## Sources 1. [primary] Thomas Müller, Fabrice Rousselle, Jan Novák, Alexander Keller (2021) Real-time neural radiance caching for path tracing. ACM Transactions on Graphics. https://doi.org/10.1145/3450626.3459812 (verified via crossref on 2026-11-29) 2. [implementation] NVIDIA-RTX (2024) NVIDIA-RTX/NRC. https://github.com/NVIDIA-RTX/NRC License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Neural Radiance Caching." https://texelatlas.vercel.app/t/neural-radiance-caching/ (accessed 2026-12-01). --- id: "neural-texture-compression" title: "Random-access neural texture compression" domain: "materials" stage: "material" realtime: "realtime" platforms: [desktop-gpu, cuda, python] year_introduced: 2023 inputs: [texture, material-params, uv-atlas] outputs: [texture] style: "photoreal" dynamic: "both" cost: "medium" authority: "Vaidyanathan et al., 2023" url: "https://texelatlas.vercel.app/t/neural-texture-compression/" sources_verified_at: "2026-11-29" --- # Random-access neural texture compression (Vaidyanathan et al., 2023) > Compresses a stack of material textures (albedo, normal, roughness...) into small latent feature grids plus a tiny MLP decoder evaluated per texel, with random access and mip filtering. Reaches much higher quality than block compression at similar sizes. ## Reach for it when - pbr material textures eat too much vram - texture download size is too big - block compression artefacts on high-res materials - store many material channels in few bytes - need higher quality than standard compressed textures at same size ## How it works Instead of independently BC-compressing each channel, Vaidyanathan et al. encode all channels of a material jointly into multi-resolution feature pyramids, quantised to a few bits per latent, and decode them with a small fully connected network run in the shader (inference on matrix hardware such as tensor cores). A texel lookup fetches the nearest latent neighbours at two pyramid levels, concatenates them with positional encoding, and the MLP outputs all material channels at once. Training minimises reconstruction error per material offline, with quantisation-aware optimisation; mip levels are encoded as separate pyramids so filtering is by decode-then-filter. Random access means no whole-image decompression is needed. An anisotropic-feature variant exists in the public afntc repo, which adapts the latent grid shape to the texture's directional structure. ## When to use it Choose it when VRAM or download size is the bottleneck for high-resolution PBR material sets and the target has matrix/ML hardware. Prefer [Block texture compression (BC7 / ASTC)](https://texelatlas.vercel.app/t/block-texture-compression.md) (BCn) or [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md) when you need universal hardware decode, cheap sampling or mobile support. ## Cost medium — Per-texel MLP inference raises shading cost over BCn fetches; practical with tensor-core class GPUs. Measured GPU Weight: 10.25× baseline (moderate) — 0.3373 ms median / 0.3507 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.44× baseline (moderate) — 0.1183 ms median (2.85× faster on L4). Ampere A100 scaling: 6.89× baseline (moderate) — 0.1985 ms median (1.7× faster on A100). ## Failure modes - Per-material training is required, so authoring pipelines slow down - Decoder cost multiplies with texture-sample count and aliasing from anisotropic filtering - High-frequency, noise-like detail reconstructs less faithfully than smooth content at low bitrates - Hardware limited to GPUs with efficient small-MLP inference; no baseline fallback ## Dataflow - Inputs: texture, material-params, uv-atlas - Outputs: texture - Platforms: desktop-gpu, cuda, python ## Presets ### Neural Texture Compression — 4x4 block-quantized BCn artifacts (left) vs latent feature-grid MLP decoder (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_LATENT_RES": 12, "P_MLP_GAIN": 1, "P_VIEW_ROT": 0.45, "P_SPLIT": 0.48 } ``` ```glsl const float P_LATENT_RES = 12.0; // P Latent Grid Res [6.0, 24.0, 2.0] const float P_MLP_GAIN = 1.00; // P MLP Sharpness [0.3, 1.6, 0.05] const float P_VIEW_ROT = 0.45; // P Orbit Speed [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Block / NTC Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Reference multi-channel PBR material (albedo, bump height, roughness) void evalRefMaterial(vec2 uv, out vec3 alb, out float h, out float rough) { vec2 cell = floor(uv * 5.0); vec2 f = fract(uv * 5.0) - 0.5; float r = length(f); float wave = sin(uv.x * 18.0 + sin(uv.y * 12.0) * 1.6) * 0.5 + 0.5; float rivet = smoothstep(0.22, 0.14, r); float seam = smoothstep(0.46, 0.485, max(abs(f.x), abs(f.y))); float id = hash21(cell); vec3 cA = vec3(0.14, 0.34, 0.46); vec3 cB = vec3(0.84, 0.48, 0.18); alb = mix(mix(cA, cB, wave * 0.75 + id * 0.25), vec3(0.92, 0.78, 0.42), rivet); alb = mix(alb, vec3(0.06, 0.07, 0.09), seam); h = (0.35 * wave + 0.55 * rivet) * (1.0 - seam); rough = mix(0.55, 0.16, rivet) + seam * 0.3; } // Encode compact 4D latent features at integer grid corner vec4 encodeLatent(vec2 gIdx, float res) { vec2 uv = gIdx / res; vec3 alb; float h; float r; evalRefMaterial(uv, alb, h, r); return vec4(dot(alb, vec3(0.3, 0.6, 0.1)), alb.r - alb.b, h, r); } // Tiny random-access NTC MLP decoder: bilinear latent + positional harmonics -> correlated PBR stack void decodeNTC(vec2 uv, float res, float sharp, out vec3 alb, out float h, out float rough) { vec2 p = uv * res; vec2 i = floor(p); vec2 f = fract(p); vec4 z00 = encodeLatent(i + vec2(0.0, 0.0), res); vec4 z10 = encodeLatent(i + vec2(1.0, 0.0), res); vec4 z01 = encodeLatent(i + vec2(0.0, 1.0), res); vec4 z11 = encodeLatent(i + vec2(1.0, 1.0), res); vec4 z = mix(mix(z00, z10, f.x), mix(z01, z11, f.x), f.y); // Layer 1 (4 hidden units with smooth GELU-like activation combining bilinear latent + local phase) vec2 ph = sin(uv * 31.415926); vec4 h1 = vec4( z.x * 1.45 + z.y * 0.65 + ph.x * 0.12 * sharp, z.y * 1.35 - z.x * 0.42 + ph.y * 0.12 * sharp, z.z * 1.60 + z.x * 0.35 - z.w * 0.55, z.w * 1.40 - z.z * 0.60 + 0.18 ); h1 = h1 * (0.5 + 0.5 * tanh(h1 * 1.4)); // Layer 2: blend decoded latent MLP with fine sub-grid synthesis vec3 refA; float refH; float refR; evalRefMaterial(uv, refA, refH, refR); vec3 mlpCol = clamp(vec3( 0.42 + 0.52 * h1.x + 0.45 * h1.y, 0.44 + 0.48 * h1.x - 0.12 * h1.y + 0.22 * h1.z, 0.40 + 0.42 * h1.x - 0.48 * h1.y ), 0.0, 1.0); float blend = clamp(0.35 + 0.55 * sharp, 0.2, 0.92); alb = mix(mlpCol, refA, blend); h = mix(clamp(h1.z * 0.85, 0.0, 1.0), refH, blend); rough = clamp(mix(h1.w * 0.75, refR, blend), 0.1, 0.9); } // Simulated 4x4 block-compressed (BCn) quantizer showing block endpoints & banding void decodeBCn(vec2 uv, float res, out vec3 alb, out float h, out float rough) { float blk = res * 0.85; vec2 bId = floor(uv * blk); vec2 bUv = (bId + 0.5) / blk; vec2 sub = floor(fract(uv * blk) * 4.0) / 4.0; vec3 a0, a1; float h0, h1; float r0, r1; evalRefMaterial(bUv - vec2(0.35) / blk, a0, h0, r0); evalRefMaterial(bUv + vec2(0.35) / blk, a1, h1, r1); vec3 ac; float hc; float rc; evalRefMaterial((bId + sub + 0.125) / blk, ac, hc, rc); // Project onto 2-bit (4-level) block endpoint ramp -> characteristic BC1/BC7 banding float t = clamp(dot(ac - a0, a1 - a0) / max(dot(a1 - a0, a1 - a0), 1e-4), 0.0, 1.0); float q = floor(t * 3.0 + 0.5) / 3.0; alb = mix(a0, a1, q); h = floor(hc * 4.0 + 0.5) / 4.0; rough = floor(rc * 4.0 + 0.5) / 4.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useNTC = sx >= split; float res = clamp(P_LATENT_RES, 4.0, 28.0); float sharp = clamp(P_MLP_GAIN, 0.2, 1.8); float rot = iTime * max(P_VIEW_ROT, 0.0); vec3 ro = vec3(0.0, 0.22, 2.25); vec3 rd = normalize(vec3(uv, -1.45)); vec3 col = mix(vec3(0.05, 0.06, 0.09), vec3(0.14, 0.18, 0.25), uv.y + 0.5); // Intersect hero sphere (upper) and flat close-up material strip (lower foreground) vec3 sc = vec3(0.0, 0.12, 0.0); vec3 oc = ro - sc; float b = dot(oc, rd); float c = dot(oc, oc) - 0.62 * 0.62; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tPl = (rd.y < -0.01) ? ((-0.52 - ro.y) / rd.y) : 1e5; if (tPl < 0.05 || tPl > 10.0) tPl = 1e5; float tHit = min(tSph, tPl); if (tHit < 1e4) { vec3 p = ro + rd * tHit; vec3 n, T, B; vec2 muv; if (tSph < tPl) { n = normalize(p - sc); float phi = atan(n.z, n.x) + rot; float th = acos(clamp(n.y, -1.0, 1.0)); muv = vec2(phi / 3.14159, th / 1.57079); T = normalize(vec3(-sin(phi), 0.0, cos(phi))); B = cross(n, T); } else { n = vec3(0.0, 1.0, 0.0); T = vec3(1.0, 0.0, 0.0); B = vec3(0.0, 0.0, 1.0); muv = p.xz * 0.42 + vec2(rot * 0.12, 0.0); } vec3 alb; float h, hx, hy, rough; float eps = 0.008; vec3 tmpA; float tmpR; if (useNTC) { decodeNTC(muv, res, sharp, alb, h, rough); decodeNTC(muv + vec2(eps, 0.0), res, sharp, tmpA, hx, tmpR); decodeNTC(muv + vec2(0.0, eps), res, sharp, tmpA, hy, tmpR); } else { decodeBCn(muv, res, alb, h, rough); decodeBCn(muv + vec2(eps, 0.0), res, tmpA, hx, tmpR); decodeBCn(muv + vec2(0.0, eps), res, tmpA, hy, tmpR); } vec3 bumpN = normalize(n - T * ((hx - h) / eps) * 0.085 - B * ((hy - h) / eps) * 0.085); vec3 v = -rd; vec3 L = normalize(vec3(0.6, 0.78, 0.55)); vec3 H = normalize(L + v); float ndl = max(dot(bumpN, L), 0.0); float ndh = max(dot(bumpN, H), 0.0); float spec = pow(ndh, mix(10.0, 96.0, 1.0 - rough)) * (1.0 - rough * 0.72); col = alb * (vec3(1.15, 1.08, 0.96) * ndl + vec3(0.24, 0.30, 0.42)) + vec3(1.0, 0.94, 0.85) * spec * 0.85; if (tPl < tSph) { col = mix(col, vec3(0.07, 0.09, 0.13), 1.0 - exp(-tPl * 0.22)); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Neural materials that filter like EWA](https://texelatlas.vercel.app/ideas/footprint-filtered-neural-materials/) - [Neural-compressed directional lightmaps](https://texelatlas.vercel.app/ideas/neural-compressed-lightmaps/) ## Sources 1. [primary] Karthik Vaidyanathan, Marco Salvi, Bartlomiej Wronski, Tomas Akenine-Moller, Pontus Ebelin, Aaron Lefohn (2023) Random-Access Neural Compression of Material Textures. ACM Transactions on Graphics. https://doi.org/10.1145/3592407 (verified via crossref on 2026-11-29) 2. [implementation] wrong-nebula (2026) wrong-nebula/afntc. https://github.com/wrong-nebula/afntc License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Random-access neural texture compression." https://texelatlas.vercel.app/t/neural-texture-compression/ (accessed 2026-12-01). --- id: "neuralangelo" title: "Neuralangelo" domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, python] year_introduced: 2023 inputs: [photos, camera-poses] outputs: [sdf, mesh] style: "photoreal" dynamic: "static" cost: "offline" authority: "Li et al., 2023" url: "https://texelatlas.vercel.app/t/neuralangelo/" sources_verified_at: "2026-11-29" --- # Neuralangelo (Li et al., 2023) > High-fidelity neural SDF reconstruction from posed photos using a hash-grid representation, numerical gradients for the Eikonal and normal terms, and coarse-to-fine resolution scheduling. ## Reach for it when - photogrammetry meshes are noisy and lack fine detail - reconstruct high fidelity surfaces from video - need detailed geometry from multi-view images - implicit surface reconstruction loses small details ## How it works It builds on NeuS-style SDF volume rendering but swaps the MLP for a multiresolution hash encoding to hold detail. The surface normals needed for regularisation are computed by finite differences with a step size tied to the grid cell, instead of analytic gradients through the hash lookup. Big steps smooth the loss, so early training updates many cells together and recovers coarse shape, while the step shrinks over training to reveal finer levels, which are progressively unlocked. This coarse-to-fine schedule prevents the high-frequency hash levels from fitting noise before the base shape exists. A mesh is extracted with marching cubes and can capture details like leaves, fabric and signage on building-scale scenes. ## When to use it Choose it when you need detailed meshes of large real scenes and have GPU hours to spare. Prefer [NeuS](https://texelatlas.vercel.app/t/neus.md) for small objects with simpler setup, [2D Gaussian Splatting](https://texelatlas.vercel.app/t/2d-gaussian-splatting.md) when optimisation time matters, and [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md) for a quick classical baseline. ## Cost offline — Many hours per scene on a high-memory GPU, per the reference setup; far above splat-based methods. Measured GPU Weight: 21.35× baseline (heavy) — 0.7023 ms median / 0.7294 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.23× baseline (moderate) — 0.2898 ms median (2.42× faster on L4). Ampere A100 scaling: 13.5× baseline (moderate) — 0.3889 ms median (1.81× faster on A100). ## Failure modes - Long training times and large memory footprint - Reflective and transparent surfaces create holes or bulges in the SDF - Poor pose accuracy produces doubled surfaces, since photometric fitting trusts the cameras - Reference code licence is non-commercial, limiting production use ## Dataflow - Inputs: photos, camera-poses - Outputs: sdf, mesh - Platforms: cuda, python ## Presets ### Neuralangelo — coarse analytical SDF (left) vs fine numerical-gradient hash-grid relief (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FINE_DETAIL": 0.9, "P_HASH_SCALE": 9, "P_ROT_SPEED": 0.52, "P_SPLIT": 0.48 } ``` ```glsl const float P_FINE_DETAIL = 0.90; // P Fine Hash Detail [0.1, 1.2, 0.04] const float P_HASH_SCALE = 9.0; // P Relief Freq [4.0, 16.0, 0.5] const float P_ROT_SPEED = 0.52; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Coarse / Neuralangelo [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Coarse base sculpture (classical marble fluted column & capital) float mapCoarse(vec3 q) { float rXZ = length(q.xz); float shaft = max(rXZ - (0.40 - 0.04 * q.y), abs(q.y) - 0.66); float cap = max(max(abs(q.x), abs(q.z)) - 0.50, abs(q.y - 0.62) - 0.10); float base = max(max(abs(q.x), abs(q.z)) - 0.52, abs(q.y + 0.62) - 0.10); return min(shaft, min(cap, base)) * 0.85; } // Fine Neuralangelo SDF with progressive high-frequency hash-grid carvings (flutes, volutes, rosettes) float mapFine(vec3 q, float detail, float freq) { float d = mapCoarse(q); float ang = atan(q.z, q.x); // Classical concave vertical fluting along the shaft float inShaft = smoothstep(0.55, 0.45, abs(q.y)); float flutes = -0.024 * abs(sin(ang * 8.0)) * inShaft; // Intricate carved frieze bands on capital & base float frieze = 0.016 * sin(q.x * freq * 2.2) * cos(q.z * freq * 2.2) * smoothstep(0.45, 0.55, abs(q.y)); // Fine stone chisel relief across surface float chisel = 0.008 * sin(q.y * freq * 2.5 + ang * 6.0) * cos(q.x * freq * 1.8); return d + (flutes + frieze + chisel) * detail; } // Numerical finite-difference gradient with progressive step size eps (core Neuralangelo technique!) vec3 calcNumericalNormal(vec3 q, float detail, float freq, float eps, bool fine) { vec2 e = vec2(eps, 0.0); if (fine) { return normalize(vec3( mapFine(q + e.xyy, detail, freq) - mapFine(q - e.xyy, detail, freq), mapFine(q + e.yxy, detail, freq) - mapFine(q - e.yxy, detail, freq), mapFine(q + e.yyx, detail, freq) - mapFine(q - e.yyx, detail, freq) )); } return normalize(vec3( mapCoarse(q + e.xyy) - mapCoarse(q - e.xyy), mapCoarse(q + e.yxy) - mapCoarse(q - e.yxy), mapCoarse(q + e.yyx) - mapCoarse(q - e.yyx) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isFine = screenX >= split; float detail = clamp(P_FINE_DETAIL, 0.05, 1.4); float freq = clamp(P_HASH_SCALE, 3.0, 18.0); float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.48; vec3 ro = vec3(0.0, 0.12, 2.28); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.02), -1.52)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 col = mix(vec3(0.025, 0.030, 0.048), vec3(0.068, 0.078, 0.116), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 60; i++) { vec3 p = ro + rd * t; float d = isFine ? mapFine(p, detail, freq) : mapCoarse(p); if (d < 0.002) { hit = true; break; } t += max(d * 0.78, 0.004); if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; // Left uses large coarse eps (smooth early training stage); right uses fine eps (converged Neuralangelo) float eps = isFine ? 0.003 : 0.035; vec3 n = calcNumericalNormal(p, detail, freq, eps, isFine); // Curvature proxy from difference between fine & coarse normals highlights carved stone relief! vec3 nCoarse = calcNumericalNormal(p, detail, freq, 0.04, false); float curv = clamp(length(n - nCoarse) * 2.2, 0.0, 1.0); vec3 l1 = normalize(vec3(0.65, 0.72, 0.52)); vec3 l2 = normalize(vec3(-0.68, -0.15, -0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 36.0); float ao = clamp(0.45 + 0.55 * (isFine ? mapFine(p + n * 0.08, detail, freq) : mapCoarse(p + n * 0.08)) / 0.08, 0.25, 1.0); // Carrara marble sculpture shading vec3 marble = mix(vec3(0.76, 0.74, 0.72), vec3(0.95, 0.92, 0.88), 0.5 + 0.5 * sin(p.x * 6.0 + p.y * 4.0)); if (!isFine) { // Subtle coarse hash-level wireframe on left vec3 cg = abs(fract(p * 4.0) - 0.5); float cw = smoothstep(0.04, 0.01, min(cg.x, min(cg.y, cg.z))); marble = mix(marble * 0.85, vec3(0.24, 0.76, 0.96), cw * 0.32); } else { marble = mix(marble, vec3(0.98, 0.86, 0.68), curv * 0.28); } col = marble * (0.24 + 0.82 * diff1 + 0.24 * diff2) * ao + vec3(1.0, 0.97, 0.92) * spec * 0.36; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [NeuS](https://texelatlas.vercel.app/t/neus.md) ## Combines with - [Instant NGP (Multiresolution Hash Encoding)](https://texelatlas.vercel.app/t/instant-ngp.md): Reuses the hash-grid encoding as the SDF feature backbone. ## Combination ideas - [Scanned objects as SDF primitives](https://texelatlas.vercel.app/ideas/captured-sdf-sculpting/) ## Sources 1. [primary] Zhaoshuo Li, Thomas Müller, Alex Evans, Russell H. Taylor, Mathias Unberath, Ming-Yu Liu, Chen-Hsuan Lin (2023) Neuralangelo: High-Fidelity Neural Surface Reconstruction. arXiv preprint (cs.CV). https://arxiv.org/abs/2306.03092 (verified via arxiv on 2026-11-29) 2. [implementation] NVlabs (2023) NVlabs/neuralangelo. https://github.com/NVlabs/neuralangelo License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Neuralangelo." https://texelatlas.vercel.app/t/neuralangelo/ (accessed 2026-12-01). --- id: "neus" title: "NeuS" aliases: [NeuS: neural implicit surfaces] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, python] year_introduced: 2021 inputs: [photos, camera-poses] outputs: [sdf, mesh] style: "photoreal" dynamic: "static" cost: "offline" authority: "Wang et al., 2021" url: "https://texelatlas.vercel.app/t/neus/" sources_verified_at: "2026-11-29" --- # NeuS (Wang et al., 2021) > Reconstructs surfaces as the zero level set of a signed distance network trained with an unbiased, occlusion-aware volume rendering formulation, giving cleaner geometry than density-based NeRF. ## Reach for it when - nerf geometry is noisy and not a real surface - need watertight surface from posed photos - thin or textureless parts fail in photogrammetry - want signed distance geometry instead of density fog ## How it works A network represents a signed distance function and a second network gives colour. For rendering, the SDF is converted to a volume weight along each ray through a logistic density of the signed distance, whose sharpness is a learned parameter. The key observation is that naive conversions bias the rendered surface away from the zero crossing; NeuS derives weights whose peak lies exactly at the first zero crossing and which respect occlusion. Training minimises photometric loss, optional mask loss and an Eikonal regulariser that keeps the field a true distance function. The mesh is extracted afterwards with marching cubes. The sharpness parameter anneals so early training is smooth and later training concentrates on the surface. ## When to use it Choose it for watertight object-scale surfaces from posed photos, particularly thin or textureless parts that photo-consistency matching misses. Prefer [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) for large scenes and fine detail, [2D Gaussian Splatting](https://texelatlas.vercel.app/t/2d-gaussian-splatting.md) for far faster optimisation, and [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md) when fast classical reconstruction suffices. ## Cost offline — Hours of training per object on one GPU in the reference implementation. Measured GPU Weight: 91.94× baseline (extreme) — 2.85 ms median / 3.0332 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 87.3× baseline (extreme) — 1.388 ms median (2.05× faster on L4). Ampere A100 scaling: 64.13× baseline (extreme) — 1.847 ms median (1.54× faster on A100). ## Failure modes - Smooth over-regularised geometry loses fine detail - Struggles with unbounded backgrounds unless a separate background model or masks are used - Specular surfaces confuse the colour network and distort SDF - Needs good masks or foreground priors to avoid spurious surfaces ## Dataflow - Inputs: photos, camera-poses - Outputs: sdf, mesh - Platforms: cuda, python ## Presets ### NeuS Neural Surface — early low-s logistic cloud (left) vs high-s unbiased SDF surface (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_INV_STD": 42, "P_NORMAL_VIS": 0.35, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_INV_STD = 42.0; // P Sharpness s [8.0, 90.0, 2.0] const float P_NORMAL_VIS = 0.35; // P Normal Tint [0.0, 1.0, 0.05] const float P_ROT_SPEED = 0.65; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Soft / Sharp s Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Neural SDF network f(x) representing a sculpted multi-handle ceramic vase float sdfField(vec3 p) { float body = length(vec3(p.x, (p.y + 0.05) * 0.78, p.z)) - 0.46; float waist = 0.08 * sin(p.y * 5.2 + 0.4); float dBody = body + waist; vec2 hL = vec2(length(p.xy - vec2(-0.42, 0.08)) - 0.18, p.z); vec2 hR = vec2(length(p.xy - vec2(0.42, 0.08)) - 0.18, p.z); float dHandles = min(length(hL) - 0.075, length(hR) - 0.075); return smin(dBody, dHandles, 0.10); } vec3 sdfNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( sdfField(p + e.xyy) - sdfField(p - e.xyy), sdfField(p + e.yxy) - sdfField(p - e.yxy), sdfField(p + e.yyx) - sdfField(p - e.yyx) )); } // Logistic sigmoid Phi_s(f) = 1 / (1 + exp(-s * f)) used by NeuS unbiased volume rendering float logisticPhi(float f, float s) { return 1.0 / (1.0 + exp(clamp(-s * f, -30.0, 30.0))); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isConverged = screenX >= split; float invS = isConverged ? clamp(P_INV_STD, 8.0, 95.0) : 7.5; float normTint = clamp(P_NORMAL_VIS, 0.0, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.14, 2.25); vec3 rd = normalize(vec3(uv, -1.52)); ro.xz = rot2(spin * 0.58) * ro.xz; rd.xz = rot2(spin * 0.58) * rd.xz; vec3 bg = mix(vec3(0.025, 0.034, 0.056), vec3(0.070, 0.092, 0.142), smoothstep(-0.55, 0.55, uv.y)); // Bounding sphere R = 0.98 float b = dot(ro, rd); float c = dot(ro, ro) - 0.98 * 0.98; float disc = b * b - c; vec3 accum = vec3(0.0); float T = 1.0; if (disc > 0.0) { float tNear = max(-b - sqrt(disc), 0.1); float tFar = -b + sqrt(disc); int steps = 56; float dt = (tFar - tNear) / float(steps); float prevF = sdfField(ro + rd * tNear); float prevPhi = logisticPhi(prevF, invS); vec3 l1 = normalize(vec3(0.58, 0.82, 0.55)); vec3 l2 = normalize(vec3(-0.68, -0.22, 0.52)); for (int i = 0; i < 56; i++) { float tNext = tNear + float(i + 1) * dt; vec3 pMid = ro + rd * (tNext - 0.5 * dt); float nextF = sdfField(ro + rd * tNext); float nextPhi = logisticPhi(nextF, invS); // Exact NeuS unbiased discrete opacity formula: // alpha_i = max((Phi_s(f(t_i)) - Phi_s(f(t_{i+1}))) / Phi_s(f(t_i)), 0) float alpha = clamp((prevPhi - nextPhi) / max(prevPhi, 1e-5), 0.0, 1.0); if (alpha > 0.002) { vec3 n = sdfNormal(pMid); float diff = max(dot(n, l1), 0.0) * 0.86 + max(dot(n, l2), 0.0) * 0.24; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 48.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 ceramic = isConverged ? vec3(0.84, 0.78, 0.72) : vec3(0.28, 0.76, 0.94); vec3 shaded = ceramic * (0.26 + 0.84 * diff) + vec3(0.98) * spec * 0.52 + vec3(0.36, 0.76, 1.0) * rim * 0.30; vec3 nCol = n * 0.5 + 0.5; vec3 sampleCol = mix(shaded, nCol, normTint * (isConverged ? 0.55 : 0.25)); accum += T * alpha * sampleCol; T *= (1.0 - alpha); if (T < 0.008) break; } prevF = nextF; prevPhi = nextPhi; } } vec3 col = accum + T * bg; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Neuralangelo](https://texelatlas.vercel.app/t/neuralangelo.md) ## Combination ideas - [Deformable XPBD soft bodies carved straight from NeuS captures](https://texelatlas.vercel.app/ideas/neus-captured-xpbd-soft-bodies/) ## Sources 1. [primary] Peng Wang, Lingjie Liu, Yuan Liu, Christian Theobalt, Taku Komura, Wenping Wang (2021) NeuS: Learning Neural Implicit Surfaces by Volume Rendering for Multi-view Reconstruction. arXiv preprint (cs.CV). https://arxiv.org/abs/2106.10689 (verified via arxiv on 2026-11-29) 2. [implementation] Totoro97 (2021) Totoro97/NeuS. https://github.com/Totoro97/NeuS License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "NeuS." https://texelatlas.vercel.app/t/neus/ (accessed 2026-12-01). --- id: "next-event-estimation" title: "Next-event estimation (direct light sampling)" aliases: [NEE, direct lighting sampling, explicit light sampling, shadow rays] domain: "gi" stage: "lighting" realtime: "interactive" platforms: [cuda, desktop-gpu, cpu, blender, webgpu, python] year_introduced: 1996 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "medium" authority: "Pharr et al." url: "https://texelatlas.vercel.app/t/next-event-estimation/" sources_verified_at: "2026-11-29" --- # Next-event estimation (direct light sampling) (Pharr et al.) > At every path vertex, trace a shadow ray toward a sampled point on a light instead of hoping a random bounce hits it. Direct illumination becomes low-variance and small lights stop producing fireflies. ## Reach for it when - path tracer is extremely noisy with small lights - fireflies from tiny bright emitters - direct lighting converges too slowly - light only found when random bounces hit it ## How it works A naive path tracer finds light only when a random bounce happens to hit an emitter, so small bright lights give extremely noisy images. Next-event estimation splits the rendering equation at each vertex: the direct term is estimated by choosing a point on a light, evaluating the BSDF and geometry for that direction, and casting a shadow ray to check visibility. The indirect term continues with the usual BSDF-sampled bounce. To avoid counting emission twice, the continued path must not add emitted light from a surface it hits directly after an NEE-sampled vertex, or the two strategies must be combined with [multiple-importance-sampling](multiple-importance-sampling) weights. The light is chosen by area, power or, with many lights, by a hierarchy ([light-bvh-many-lights](light-bvh-many-lights)); the sample pdf converts from area to solid angle with the usual `distance^2 / cos` factor. Specular chains are the exception: a delta BSDF cannot be sampled by NEE, so those vertices still rely on BSDF sampling and emission hits. ## When to use it Choose it in any path tracer that renders small or bright lights, area lights or HDRI environments (with importance sampling); it is the first change that makes a path tracer converge usably. Prefer [multiple-importance-sampling](multiple-importance-sampling) on top of it when the BSDF is glossy and lights are large, so neither strategy fails alone. Prefer [restir-di](restir-di) when there are thousands of lights and one sample per pixel. Prefer [bidirectional-path-tracing](bidirectional-path-tracing) or [metropolis-light-transport](metropolis-light-transport) when the shadow ray is blocked by glass and caustics matter. Plain [path-tracing](path-tracing) without NEE is acceptable only for large, uniformly bright environments. ## Cost medium — One extra shadow ray and BSDF evaluation per path vertex; usually far cheaper than the variance it removes. Measured GPU Weight: 35.89× baseline (heavy) — 1.1127 ms median / 1.1983 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 37.13× baseline (heavy) — 0.5903 ms median (1.88× faster on L4). Ampere A100 scaling: 22.41× baseline (heavy) — 0.6455 ms median (1.72× faster on A100). ## Failure modes - Double-counted emission when the BSDF-sampled bounce is allowed to add light already estimated by NEE - Black shadows behind glass or water because shadow rays cannot pass through refractive materials - Wrong pdf conversion between area and solid angle gives lights that are too bright or too dim by a distance-squared factor - Poor light selection with many lights makes noise worse than uniform sampling in large scenes - Light samples that cross the horizon of a shading normal produce negative or NaN contributions ## Engine support - blender: builtin — `Cycles samples lights directly by default; Light > Multiple Importance Sample` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/light_settings.html, checked 2026-12-01) — Always on in Cycles; MIS is a toggle. - unity: builtin — `HDRP Volume > Add Override > Ray Tracing > Path Tracing (PathTracingSurface.hlsl runs SampleLights direct-light shadow queries with MIS)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingSurface.hlsl, checked 2026-12-01) — HDRP-only path tracer. - unreal: builtin — `Path Tracer direct light sampling / multiple importance sampling` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/path-tracer-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cuda, desktop-gpu, cpu, blender, webgpu, python ## Presets ### Next-Event Estimation — blind BSDF light hits (left) vs explicit direct-light shadow rays (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_LIGHT_SIZE": 0.22, "P_NOISE_GAIN": 1, "P_BOUNCE_INT": 1.1, "P_SPLIT": 0.48 } ``` ```glsl const float P_LIGHT_SIZE = 0.22; // P Emitter Radius [0.08, 0.55, 0.02] const float P_NOISE_GAIN = 1.0; // P BSDF Variance [0.2, 2.0, 0.05] const float P_BOUNCE_INT = 1.1; // P Light Power [0.4, 2.2, 0.05] const float P_SPLIT = 0.48; // P Blind / NEE Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } 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); } vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); float dC = 1.0 - p.y; if (dC < res.x) res = vec2(dC, 1.0); float dB = p.z + 1.45; if (dB < res.x) res = vec2(dB, 1.0); float dL = p.x + 1.35; if (dL < res.x) res = vec2(dL, 1.0); float dR = 1.35 - p.x; if (dR < res.x) res = vec2(dR, 1.0); // Sculpted sphere + pedestal casting crisp penumbra from the small area light float dSph = length(p - vec3(0.0, -0.35, -0.22)) - 0.36; if (dSph < res.x) res = vec2(dSph, 2.0); float dCol = sdBox(p - vec3(-0.62, -0.45, -0.58), vec3(0.22, 0.40, 0.22)) - 0.02; if (dCol < res.x) res = vec2(dCol, 3.0); float dCol2 = sdBox(p - vec3(0.66, -0.55, -0.45), vec3(0.24, 0.30, 0.24)) - 0.02; if (dCol2 < res.x) res = vec2(dCol2, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } float softShadow(vec3 ro, vec3 rd, float maxT, float k) { float res = 1.0; float t = 0.03; for (int i = 0; i < 24; i++) { float h = mapScene(ro + rd * t).x; res = min(res, k * h / max(t, 1e-4)); t += clamp(h, 0.02, 0.18); if (res < 0.01 || t > maxT) break; } return clamp(res, 0.0, 1.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isNEE = screenX >= split; float lRad = clamp(P_LIGHT_SIZE, 0.07, 0.58); float noiseGain = clamp(P_NOISE_GAIN, 0.15, 2.2); float power = clamp(P_BOUNCE_INT, 0.3, 2.4); vec3 lPos = vec3(0.32 * sin(iTime * 0.7), 0.96, -0.25); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); if (p.y > 0.98 && length(p.xz - lPos.xz) < lRad) { col = vec3(3.8, 3.3, 2.6) * power; } else { vec3 alb = vec3(0.68, 0.70, 0.74); if (matId > 1.5 && matId < 2.5) alb = vec3(0.86, 0.56, 0.24); if (matId > 2.5) alb = vec3(0.30, 0.62, 0.76); vec3 lVec = lPos - p; float lDist = length(lVec); vec3 lDir = lVec / max(lDist, 1e-4); float ndl = max(dot(n, lDir), 0.0); float cosL = max(dot(vec3(0.0, -1.0, 0.0), -lDir), 0.0); // Solid angle subtended by the small area light omega = A * cosL / d^2 float area = 3.1415926 * lRad * lRad; float solidAngle = clamp(area * cosL / (lDist * lDist + 0.08), 0.004, 1.2); float sh = softShadow(p + n * 0.012, lDir, lDist - 0.05, 2.2 / max(lRad, 0.08)); // Ground-truth direct illumination (constant total radiant power regardless of light radius) vec3 directClean = alb * vec3(2.8, 2.45, 1.95) * power * ndl * cosL * sh / (lDist * lDist + 0.45); vec3 amb = alb * vec3(0.08, 0.10, 0.13) * clamp(0.45 + 0.55 * mapScene(p + n * 0.24).x / 0.24, 0.2, 1.0); if (!isNEE) { // Left: Naive unguided BSDF sampling. Hit probability scales with solidAngle / pi! // Smaller light => tiny hit chance => huge weight (1 / pHit) fireflies & mostly black pixels! float pHit = clamp(solidAngle * 1.45 / max(noiseGain, 0.2), 0.04, 0.85); vec2 rnd = hash22(floor(fragCoord * 0.8) + fract(iTime * 6.7) * 23.1); float didHit = step(1.0 - pHit, rnd.x); float estimator = didHit / max(pHit, 0.06); float spike = pow(rnd.y, 4.0) * 1.8 * didHit / max(lRad * 3.0, 0.25); col = amb + directClean * (estimator * 0.72 + spike * 0.35); } else { // Right: Explicit Next-Event Estimation shadow ray samples the emitter directly with low variance float jitter = (hash21(floor(fragCoord) + fract(iTime * 3.1) * 17.0) - 0.5) * 0.06 * lRad; col = amb + directClean * (1.0 + jitter); } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md) - extended by [Manifold Next-Event Estimation and Specular Manifold Sampling](https://texelatlas.vercel.app/t/manifold-next-event-estimation.md) ## Combines with - [Multiple Importance Sampling](https://texelatlas.vercel.app/t/multiple-importance-sampling.md): NEE and BSDF sampling each estimate the direct term; MIS weights blend them so whichever strategy has the better pdf dominates. - [Light BVH and Adaptive Tree Splitting](https://texelatlas.vercel.app/t/light-bvh-many-lights.md): Supplies the light-selection pdf so NEE scales to scenes with many emitters. - [Owen-scrambled Sobol and low-discrepancy sampling](https://texelatlas.vercel.app/t/owen-scrambled-sobol-sampling.md): Low-discrepancy points choose the light and surface sample per vertex, reducing the remaining variance. ## Sources 1. [primary] Matt Pharr, Wenzel Jakob, Greg Humphreys A Better Path Tracer. Physically Based Rendering 4th ed., 13.4. https://pbr-book.org/4ed/Light_Transport_I_Surface_Reflection/A_Better_Path_Tracer (verified via http on 2026-11-29) 2. [implementation] mmp (2017) mmp/pbrt-v4. https://github.com/mmp/pbrt-v4 License: Apache-2.0. (verified via github on 2026-11-29) 3. [implementation] NVIDIAGameWorks (2017) NVIDIAGameWorks/Falcor. https://github.com/NVIDIAGameWorks/Falcor License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Next-event estimation (direct light sampling)." https://texelatlas.vercel.app/t/next-event-estimation/ (accessed 2026-12-01). --- id: "normal-distribution-filtering" title: "Normal distribution filtering for specular antialiasing" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2016 inputs: [normals, gbuffer] outputs: [material-params] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Kaplanyan et al., 2016" url: "https://texelatlas.vercel.app/t/normal-distribution-filtering/" sources_verified_at: "2026-11-29" --- # Normal distribution filtering for specular antialiasing (Kaplanyan et al., 2016) > Kaplanyan and Hill filter the microfacet normal distribution over a pixel footprint using the screen-space variation of the half vector, widening roughness only where normals change. Fixes specular aliasing from geometry and normal maps with no precomputation. ## Reach for it when - specular highlights shimmer and sparkle on normal maps - bumpy surfaces alias when moving or minified - geometric normal variation causes specular noise - need shader-only fix for flickering glossy surfaces - roughness should widen where normals change quickly ## How it works Treat the half-vector variation across a pixel as a Gaussian footprint in the 2D slope space of the half vector and convolve it with the BRDF's own normal distribution. For a Gaussian-like D this is just the sum of two covariances, so effective roughness grows with the footprint size; for GGX a conservative remapping is used. The footprint is computed analytically from screen-space derivatives of the half vector (ddx/ddy), then clamped to avoid over-blur. The method needs no texture preprocessing, handles interpolated vertex normals, normal maps and anisotropic cases, and adds a few instructions per pixel. Tokuyoshi and Kaplanyan (2019) refined it with a kernel-roughness model suited to GGX and fixed over-blurring on smooth surfaces. ## When to use it Choose it as the default specular antialiasing for deferred and forward renderers using GGX when you want a shader-only fix that also covers geometric normal variation. Prefer [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) when you can bake per-mip roughness and need nothing at runtime. Prefer [LEADR mapping](https://texelatlas.vercel.app/t/leadr-mapping.md) for displaced surfaces needing mean-slope handling. ## Cost cheap — Derivative-based footprint estimate and a couple of arithmetic operations per pixel. Measured GPU Weight: 22.83× baseline (heavy) — 0.751 ms median / 0.7857 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.22× baseline (moderate) — 0.2897 ms median (2.59× faster on L4). Ampere A100 scaling: 15.04× baseline (moderate) — 0.4332 ms median (1.73× faster on A100). ## Failure modes - Screen-space derivatives are quad-based and noisy at silhouettes and on small triangles - Over-blurring of legitimately sharp highlights if the clamp is too loose - Cannot recover detail lost in minified normal maps, only hides the aliasing - Differs between deferred and forward unless half vector is reconstructed identically ## Engine support - babylonjs: builtin — `pbrMaterial.enableSpecularAntiAliasing = true (screen-space normal derivative variance filtering in pbrHelperFunctions.fx)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBaseMaterial.pure.ts, checked 2026-12-01) - blender: builtin — `Cycles > Light Paths > Filter Glossy (roughness mollification for specular antialiasing)` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/light_paths.html, checked 2026-12-01) - godot: builtin — `Project Settings > Rendering > Anti Aliasing > Screen Space Roughness Limiter > Enabled` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ProjectSettings.xml, checked 2026-12-01) — Screen-space roughness limiter for specular aliasing. - unity: builtin — `HDRP Asset > Material > Specular Anti-aliasing; Lit > Geometric Specular AA` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Geometric-Specular-Anti-Aliasing.md, checked 2026-12-01) — HDRP only (screen-space variance and threshold based). - unreal: builtin — `Texture Editor > Composite Texture with CompositeTextureMode = CTM_NORMAL_ROUGHNESS_TO_ALPHA (filters normal variance into roughness mips)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/CompositeTextureMode, checked 2026-12-01) ## Dataflow - Inputs: normals, gbuffer - Outputs: material-params - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Normal Distribution Filtering — specular firefly aliasing (left) vs Kaplanyan-Hill half-vector variance filtering (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.12, "P_FILTER_K": 1.25, "P_FLUTE_FREQ": 18, "P_SPLIT": 0.48 } ``` ```glsl const float P_ROUGHNESS = 0.12; // P Base Roughness [0.05, 0.45, 0.02] const float P_FILTER_K = 1.25; // P NDF Filter Gain [0.2, 2.5, 0.05] const float P_FLUTE_FREQ = 18.0; // P Flute Frequency [8.0, 32.0, 2.0] const float P_SPLIT = 0.48; // P Raw / Filtered Split [0.0, 1.0, 0.02] float sdFlutedObj(vec3 p, float freq) { float a = atan(p.z, p.x); float flutes = 0.028 * sin(a * freq + p.y * 8.0) * smoothstep(0.95, 0.2, abs(p.y)); float dSph = length(p) - (0.62 + flutes); return dSph * 0.72; } vec3 calcNormal(vec3 p, float freq) { vec2 e = vec2(0.0018, 0.0); return normalize(vec3( sdFlutedObj(p + e.xyy, freq) - sdFlutedObj(p - e.xyy, freq), sdFlutedObj(p + e.yxy, freq) - sdFlutedObj(p - e.yxy, freq), sdFlutedObj(p + e.yyx, freq) - sdFlutedObj(p - e.yyx, freq) )); } float D_GGX(float ndh, float alpha) { float a2 = alpha * alpha; float d = ndh * ndh * (a2 - 1.0) + 1.0; return a2 / max(3.1415926 * d * d, 1e-5); } vec3 evalEnv(vec3 d) { vec3 sky = mix(vec3(0.05, 0.07, 0.11), vec3(0.20, 0.30, 0.46), smoothstep(-0.2, 0.8, d.y)); float strip = exp(-abs(d.y - 0.35) * 16.0) * (0.5 + 0.5 * sin(atan(d.z, d.x) * 4.0)); return sky + vec3(2.4, 2.1, 1.8) * strip; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useNDF = sx >= split; float rough = clamp(P_ROUGHNESS, 0.04, 0.55); float fGain = clamp(P_FILTER_K, 0.1, 3.0); float freq = clamp(P_FLUTE_FREQ, 6.0, 36.0); float spin = iTime * 0.45; mat3 rot = mat3(cos(spin), 0.0, sin(spin), 0.0, 1.0, 0.0, -sin(spin), 0.0, cos(spin)); vec3 ro = vec3(0.0, 0.12, 2.15); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = evalEnv(rd) * 0.42; float t = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = rot * (ro + rd * t); float d = sdFlutedObj(p, freq); if (d < 0.0018) { hit = true; break; } t += d; if (t > 6.0) break; } if (hit) { vec3 wp = ro + rd * t; vec3 op = rot * wp; vec3 nObj = calcNormal(op, freq); vec3 n = normalize(transpose(rot) * nObj); vec3 v = -rd; // Estimate screen-space normal/half-vector variance across pixel footprint (Kaplanyan & Hill 2016) float pixSize = (t / max(iResolution.y, 1.0)) * 1.45 / max(abs(dot(n, v)), 0.15); vec3 up = abs(n.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); vec3 T = normalize(cross(up, n)); vec3 B = cross(n, T); vec3 nDx = normalize(transpose(rot) * calcNormal(rot * (wp + T * pixSize), freq)); vec3 nDy = normalize(transpose(rot) * calcNormal(rot * (wp + B * pixSize), freq)); vec3 dndx = nDx - n; vec3 dndy = nDy - n; float varN = (dot(dndx, dndx) + dot(dndy, dndy)) * 0.5; float baseA = rough * rough; float filtA = useNDF ? sqrt(clamp(baseA * baseA + fGain * varN * 2.4, 1e-4, 0.85)) : baseA; vec3 l1 = normalize(vec3(0.65, 0.72, 0.55)); vec3 l2 = normalize(vec3(-0.72, 0.35, 0.48)); vec3 f0 = vec3(0.86, 0.89, 0.94); vec3 acc = vec3(0.0); for (int li = 0; li < 2; li++) { vec3 L = (li == 0) ? l1 : l2; vec3 lCol = (li == 0) ? vec3(2.9, 2.5, 2.0) : vec3(0.65, 1.35, 2.25); float ndl = max(dot(n, L), 0.0); float ndv = max(dot(n, v), 0.005); if (ndl > 0.002) { vec3 H = normalize(L + v); float ndh = max(dot(n, H), 0.0); float vdh = max(dot(v, H), 0.0); float D = D_GGX(ndh, filtA); vec3 F = f0 + (1.0 - f0) * pow(1.0 - vdh, 5.0); float G = 1.0 / max(4.0 * ndl * ndv, 0.06); // Unfiltered side exhibits harsh sub-pixel specular spiking on steep ridges float spike = useNDF ? 1.0 : (1.0 + 1.45 * smoothstep(0.02, 0.14, varN)); acc += lCol * F * D * G * ndl * 0.35 * spike; } } vec3 rDir = reflect(-v, n); vec3 envRefl = mix(evalEnv(rDir), evalEnv(n) * 0.65, clamp(sqrt(filtA), 0.0, 0.9)); vec3 Fv = f0 + (1.0 - f0) * pow(1.0 - max(dot(n, v), 0.0), 5.0); col = acc + envRefl * Fv * 0.55 + vec3(0.08, 0.10, 0.14) * (0.5 + 0.5 * n.y); } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) ## Sources 1. [primary] Anton S. Kaplanyan, Stephen Hill, Anjul Patney, Aaron Lefohn (2016) Filtering Distributions of Normals for Shading Antialiasing. Eurographics/ ACM SIGGRAPH Symposium on High Performance Graphics. https://doi.org/10.2312/hpg.20161201 (verified via doi.org on 2026-11-29) 2. [primary] Yusuke Tokuyoshi, Anton S. Kaplanyan (2019) Improved geometric specular antialiasing. Proceedings of the ACM SIGGRAPH Symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/3306131.3317026 (verified via doi.org on 2026-11-29) ## Cite this entry Texel. "Normal distribution filtering for specular antialiasing." https://texelatlas.vercel.app/t/normal-distribution-filtering/ (accessed 2026-12-01). --- id: "normal-map-baking" title: "High-to-low-poly normal map baking" aliases: [normal baking, detail transfer] domain: "materials" stage: "material" realtime: "interactive" platforms: [desktop-gpu, blender, cpu, webgl2, unity] year_introduced: 1998 inputs: [mesh, uv-atlas] outputs: [texture, normals] style: "both" dynamic: "static" cost: "offline" authority: "Teixeira" url: "https://texelatlas.vercel.app/t/normal-map-baking/" sources_verified_at: "2026-11-29" --- # High-to-low-poly normal map baking (Teixeira) > Captures the surface detail of a dense mesh into a tangent-space normal map on a simplified one by casting from low-poly surface points to the high-poly surface, so cheap geometry shades like the sculpt. ## Reach for it when - want detail of a sculpt on a low poly mesh - baked normal map looks skewed or wavy - need to transfer high poly detail to game asset - dark seams appear along uv edges after baking - setting up a cage for bake rays ## How it works Both meshes share a pose and the low-poly mesh needs a unique, non-overlapping UV layout. For every texel of the low-poly UV atlas, find its 3D point and interpolated normal, then find the matching point on the high-poly surface. Ray casting along or against the normal out to a cage distance is the common method; a GPU version rasterises the high-poly mesh in the low-poly's UV space and compares attributes. The high-poly normal at the hit is transformed into the low-poly tangent frame and packed as rgb = n*0.5+0.5. The tangent frame used for baking has to be the one the runtime uses, so synchronised tangent generation ([Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md)) is mandatory. A cage, an inflated copy of the low mesh, bounds the ray start and avoids hits on the wrong layer. The same pass can emit ambient occlusion, curvature, position and thickness maps from the same hits. ## When to use it Choose it for any game character, prop or hard-surface asset where the visible detail is sculpted or modelled at high density. Prefer displacement or [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) when silhouette detail is needed. Prefer [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) for depth parallax on the baked result. Use [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md) or [Instant Field-Aligned Meshes](https://texelatlas.vercel.app/t/instant-meshes.md) to produce the low-poly target, and [xatlas](https://texelatlas.vercel.app/t/xatlas.md) for UVs. For purely procedural detail, skip baking and use [Surface gradient based bump mapping framework](https://texelatlas.vercel.app/t/surface-gradient-bump-mapping.md) in the shader. ## Cost offline — Bake time depends on ray counts and mesh size; runtime cost is one texture fetch. Measured GPU Weight: 7.06× baseline (moderate) — 0.2324 ms median / 0.2465 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.99× baseline (light) — 0.0952 ms median (2.44× faster on L4). Ampere A100 scaling: 4.96× baseline (light) — 0.1428 ms median (1.63× faster on A100). ## Failure modes - Skewed or wavy lines when the cage or ray direction is mismatched to the low-poly normals - Floating geometry gets baked onto the wrong surface when rays hit the nearest layer - Seam breaks at UV islands with different tangent handedness, and mirrored UVs bake incorrectly - Hard edges on the low-poly need split normals or UV islands, otherwise gradients smear across the edge - Baked in a different tangent basis from the one used at runtime gives lighting that looks inverted - Texel padding too small causes dark halos when mips are generated ## Engine support - blender: builtin — `Render Properties > Bake (Cycles) > Bake Type = Normal, with Selected to Active` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/baking.html, checked 2026-12-01) - unreal: builtin — `Modeling Mode > Bake > Bake Textures (or GeometryScript_Bake normal map baking)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/GeometryScript_Bake, checked 2026-12-01) ## Dataflow - Inputs: mesh, uv-atlas - Outputs: texture, normals - Platforms: desktop-gpu, blender, cpu, webgl2, unity ## Presets ### Normal Map Baking — low-poly mesh & tangent-space normal map (left) vs high-to-low baked shading (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SCULPT_DEPTH": 0.85, "P_RIVET_FREQ": 6, "P_SPIN_SPEED": 0.42, "P_SPLIT": 0.48 } ``` ```glsl const float P_SCULPT_DEPTH = 0.85; // P Sculpt Relief [0.2, 1.6, 0.05] const float P_RIVET_FREQ = 6.0; // P Panel Density [3.0, 10.0, 1.0] const float P_SPIN_SPEED = 0.42; // P Turntable Speed [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Cage / Baked Split [0.0, 1.0, 0.02] // Low-poly beveled cube-octahedron base mesh float sdLowPoly(vec3 p) { vec3 ap = abs(p); float dBox = max(ap.x, max(ap.y, ap.z)) - 0.52; float dOct = (ap.x + ap.y + ap.z - 0.82) * 0.57735; return max(dBox, dOct); } // High-poly sculpted height detail projected onto each face's local tangent coordinates float evalSculptHeight(vec2 uv, float freq) { vec2 c = abs(uv) - 0.36; float bevelPanel = smoothstep(0.04, -0.04, max(c.x, c.y)); vec2 g = fract(uv * freq) - 0.5; float rivet = smoothstep(0.20, 0.08, length(g)) * step(0.24, max(abs(uv.x), abs(uv.y))) * step(max(abs(uv.x), abs(uv.y)), 0.40); float emblem = smoothstep(0.03, -0.01, abs(length(uv) - 0.18)); float groove = smoothstep(0.022, 0.005, abs(uv.x)) * step(abs(uv.y), 0.32) + smoothstep(0.022, 0.005, abs(uv.y)) * step(abs(uv.x), 0.32); return bevelPanel * 0.35 + rivet * 0.55 + emblem * 0.42 - clamp(groove, 0.0, 1.0) * 0.32; } vec3 evalBakedTangentNormal(vec2 uv, float freq, float depth) { float e = 0.006; float h = evalSculptHeight(uv, freq); float hx = evalSculptHeight(uv + vec2(e, 0.0), freq); float hy = evalSculptHeight(uv + vec2(0.0, e), freq); return normalize(vec3(-(hx - h) / e * 0.045 * depth, -(hy - h) / e * 0.045 * depth, 1.0)); } vec3 calcLowNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( sdLowPoly(p + e.xyy) - sdLowPoly(p - e.xyy), sdLowPoly(p + e.yxy) - sdLowPoly(p - e.yxy), sdLowPoly(p + e.yyx) - sdLowPoly(p - e.yyx) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showBaked = sx >= split; float depth = clamp(P_SCULPT_DEPTH, 0.1, 2.0); float freq = clamp(floor(P_RIVET_FREQ + 0.5), 2.0, 12.0); float a = iTime * max(P_SPIN_SPEED, 0.0) + 0.45; float bAng = 0.36; mat3 ry = mat3(cos(a), 0.0, sin(a), 0.0, 1.0, 0.0, -sin(a), 0.0, cos(a)); mat3 rx = mat3(1.0, 0.0, 0.0, 0.0, cos(bAng), -sin(bAng), 0.0, sin(bAng), cos(bAng)); mat3 rot = rx * ry; vec3 ro = vec3(0.0, 0.04, 2.15); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.06, 0.07, 0.10), vec3(0.16, 0.20, 0.28), uv.y + 0.5); float t = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { vec3 op = rot * (ro + rd * t); float d = sdLowPoly(op); if (d < 0.0018) { hit = true; break; } t += d; if (t > 6.0) break; } if (hit) { vec3 op = rot * (ro + rd * t); vec3 nObj = calcLowNormal(op); // Project local face UV and tangent basis on each faceted face vec3 an = abs(nObj); vec2 fuv; vec3 tObj, bObj; if (an.x >= an.y && an.x >= an.z) { fuv = op.zy; tObj = vec3(0.0, 0.0, 1.0); bObj = vec3(0.0, 1.0, 0.0); } else if (an.y >= an.x && an.y >= an.z) { fuv = op.xz; tObj = vec3(1.0, 0.0, 0.0); bObj = vec3(0.0, 0.0, 1.0); } else { fuv = op.xy; tObj = vec3(1.0, 0.0, 0.0); bObj = vec3(0.0, 1.0, 0.0); } // Orthogonalize tangent frame for chamfered octant faces tObj = normalize(tObj - nObj * dot(tObj, nObj)); bObj = cross(nObj, tObj); vec3 tn = evalBakedTangentNormal(fuv, freq, depth); vec3 bakedN = normalize(transpose(rot) * (tObj * tn.x + bObj * tn.y + nObj * tn.z)); vec3 flatN = normalize(transpose(rot) * nObj); vec3 L = normalize(vec3(0.62, 0.74, 0.58)); vec3 v = -rd; if (!showBaked) { // Left: Tangent-space normal map RGB (purple/cyan/pink) baked directly onto the faceted low-poly cage vec3 nmRGB = tn * 0.5 + 0.5; float ndl = 0.55 + 0.45 * max(dot(flatN, L), 0.0); // Facet edge wireframe highlight vec3 ap = abs(op); float edge = smoothstep(0.025, 0.004, abs((ap.x + ap.y + ap.z - 0.82) * 0.57735 - (max(ap.x, max(ap.y, ap.z)) - 0.52))); col = nmRGB * ndl + vec3(0.95, 0.92, 0.45) * edge * 0.45; } else { // Right: Identical low-poly silhouette shaded with the baked tangent-space normal map vec3 H = normalize(L + v); float ndl = max(dot(bakedN, L), 0.0); float ndh = max(dot(bakedN, H), 0.0); float rim = pow(1.0 - max(dot(bakedN, v), 0.0), 3.0); vec3 alb = vec3(0.66, 0.54, 0.36); float spec = pow(ndh, 42.0) * 1.1; vec3 sky = mix(vec3(0.14, 0.18, 0.26), vec3(0.38, 0.48, 0.66), 0.5 + 0.5 * bakedN.y); col = alb * (vec3(1.25, 1.15, 0.98) * ndl + sky * 0.52) + vec3(1.0, 0.88, 0.68) * (spec + rim * 0.25); } } // Lower-left corner: inset 2D tangent-space normal map texture tile preview vec2 insetUv = (fragCoord / max(iResolution.y, 1.0)) - vec2(0.05, 0.06); if (!showBaked && insetUv.x > 0.0 && insetUv.x < 0.26 && insetUv.y > 0.0 && insetUv.y < 0.26) { vec2 tileUv = (insetUv / 0.26 - 0.5) * 0.95; vec3 tn = evalBakedTangentNormal(tileUv, freq, depth); col = tn * 0.5 + 0.5; vec2 b = abs(insetUv / 0.26 - 0.5); if (max(b.x, b.y) > 0.48) col = vec3(0.95, 0.96, 1.0); } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) ## Combines with - [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md): The baker writes tangent-space normals; MikkTSpace guarantees the shader decodes them with the same basis. - [xatlas](https://texelatlas.vercel.app/t/xatlas.md): Provides the non-overlapping UV layout that the bake needs on the low-poly mesh. ## Sources 1. [primary] Diogo Teixeira Chapter 22. Baking Normal Maps on the GPU. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-iv-image-effects/chapter-22-baking-normal-maps-gpu (verified via http on 2026-11-29) 2. [secondary] Jonathan Cohen, Marc Olano, Dinesh Manocha (1998) Appearance-preserving simplification. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280832 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "High-to-low-poly normal map baking." https://texelatlas.vercel.app/t/normal-map-baking/ (accessed 2026-12-01). --- id: "normal-mapping-mikktspace" title: "Normal mapping with MikkTSpace" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2008 inputs: [normals, texture, mesh, uv-atlas] outputs: [normals] style: "both" dynamic: "both" cost: "cheap" authority: "Mikkelsen" url: "https://texelatlas.vercel.app/t/normal-mapping-mikktspace/" sources_verified_at: "2026-11-29" --- # Normal mapping with MikkTSpace (Mikkelsen) > Normal mapping stores perturbed normals in a texture to fake fine detail; MikkTSpace is the standard tangent-basis definition that makes bakers and renderers agree. It is what glTF, Blender, Unity and Substance assume. ## Reach for it when - baked normal map looks wrong in another engine - lighting seams across uv islands - tangent space mismatch between baker and renderer - add surface detail to low poly without more triangles ## How it works A tangent-space normal map encodes a unit normal per texel in a frame (tangent, bitangent, normal). At render time the shader fetches the texel, decodes it (n = 2c - 1), rebuilds the frame from interpolated vertex tangent and normal, and transforms to world space. Baking and rendering must use the same frame or the shading shows seams, which is why Mikkelsen defined MikkTSpace: a per-vertex tangent computed from the triangle's UV gradients, with a specific rule for splitting vertices at UV mirrors and for orthogonalisation. The tangent's w component stores handedness. In the fragment shader the bitangent is rebuilt as the cross product of normal and tangent scaled by that sign, and the frame is not re-orthogonalised per pixel; this is what makes baker and renderer match. Normal textures are stored linearly (not sRGB) and often as two-channel BC5. ## When to use it Choose it as the default for authored detail on UV-mapped meshes. Prefer [Surface gradient based bump mapping framework](https://texelatlas.vercel.app/t/surface-gradient-bump-mapping.md) for layered or non-UV sources, and [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) or [Relief mapping](https://texelatlas.vercel.app/t/relief-mapping.md) when parallax and self-occlusion matter at grazing angles. Pair with [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) to stop minified normal maps shimmering. ## Cost cheap — One texture fetch and a 3x3 transform per pixel. Measured GPU Weight: 2.18× baseline (light) — 0.0716 ms median / 0.0752 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.77× baseline (feather) — 0.0281 ms median (2.55× faster on L4). Ampere A100 scaling: 1.25× baseline (feather) — 0.0359 ms median (1.99× faster on A100). ## Failure modes - Tangent mismatch between baker and renderer causes stretched or inverted lighting and visible seams along UV borders - Mirrored UVs without correct handedness flip lighting - Normal maps flatten under minification, making surfaces glossier unless filtered (toksvig-mipmapping) - Flat silhouettes: normal mapping adds no geometry, so edges and shadows stay smooth ## Engine support - babylonjs: builtin — `glTF 2.0 MikkTSpace vertex tangents + screen-space cotangent_frame fallback in bumpFragmentMainFunctions.fx` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/mesh.vertexData.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Vector > Normal Map, Space = Tangent Space` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/displacement/normal_map.html, checked 2026-12-01) — Tangent space follows MikkTSpace. - godot: builtin — `SurfaceTool.generate_tangents() and mesh importers compute MikkTSpace tangents (mikktspace.h)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/scene/resources/surface_tool.cpp, checked 2026-12-01) - threejs: official — `import { computeMikkTSpaceTangents } from 'three/addons/utils/BufferGeometryUtils.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/utils/BufferGeometryUtils.js, checked 2026-12-01) - unity: builtin — `Default tangent space for imported meshes and Lit/Shader Graph` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl, checked 2026-12-01) — Unity uses the MikkTSpace convention; HDRP shaders use the surface-gradient form. - unreal: builtin — `Interchange / Static Mesh Import > Use MikkTSpace (use_mikk_t_space = true by default)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/InterchangeGenericCommonMeshesProperties, checked 2026-12-01) ## Dataflow - Inputs: normals, texture, mesh, uv-atlas - Outputs: normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Tangent-space normal mapping on a sphere: geometric (left) vs mapped (right) (glsl-fragment; rendered 2026-11-29) ```json { "STRENGTH": 2.2 } ``` ```glsl // Tangent-space normal mapping with a per-pixel TBN frame built from the sphere's (longitude, latitude) // parametrisation. Left half: geometric normals. Right half: dimple normal map perturbs the shading normal. const float STRENGTH = 2.2; const vec2 CELLS = vec2(16.0, 8.0); void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -2.6)); vec3 col = vec3(0.05) + 0.05 * uv.y; float b = dot(ro, rd); float h = b * b - dot(ro, ro) + 0.81; if (h > 0.0) { vec3 p = ro + rd * (-b - sqrt(h)); vec3 n = normalize(p); float lon = atan(n.x, n.z), lat = asin(clamp(n.y, -1.0, 1.0)); if (fragCoord.x > 0.5 * iResolution.x) { vec2 g = vec2(lon / 6.2832, lat / 3.14159) * CELLS * 6.2832; // height = cos(u) * cos(v); analytic derivatives w.r.t. u and v vec2 dh = vec2(-sin(g.x) * cos(g.y), -cos(g.x) * sin(g.y)); vec3 nts = normalize(vec3(-dh * STRENGTH * 0.25, 1.0)); vec3 T = vec3(cos(lon), 0.0, -sin(lon)); vec3 B = cross(n, T); n = normalize(T * nts.x + B * nts.y + n * nts.z); } vec3 l = normalize(vec3(0.6, 0.5, 0.7)), v = -rd, hv = normalize(l + v); float nl = max(dot(n, l), 0.0); col = vec3(0.55, 0.38, 0.3) * (nl + 0.08) + vec3(0.8) * pow(max(dot(n, hv), 0.0), 40.0) * nl; } if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); col = col / (1.0 + col * 0.6); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [High-to-low-poly normal map baking](https://texelatlas.vercel.app/t/normal-map-baking.md) - extended by [Reoriented normal map blending (detail normals)](https://texelatlas.vercel.app/t/reoriented-normal-mapping.md) ## Sources 1. [primary] Morten S. Mikkelsen MikkTSpace. mikktspace.com. http://www.mikktspace.com/ (verified via http on 2026-11-29) 2. [implementation] mmikk (2020) mmikk/MikkTSpace. https://github.com/mmikk/MikkTSpace (verified via github on 2026-11-29) ## Cite this entry Texel. "Normal mapping with MikkTSpace." https://texelatlas.vercel.app/t/normal-mapping-mikktspace/ (accessed 2026-12-01). --- id: "ntsc-composite-vhs-crt-signal-emulation" title: "Physically Modeled NTSC Composite / VHS Tape & CRT Electron-Beam Emulation" aliases: [NTSC/VHS signal emulation, composite video shader, CRT electron-beam post-processing] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 2023 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "ntsc-rs, 2023" url: "https://texelatlas.vercel.app/t/ntsc-composite-vhs-crt-signal-emulation/" sources_verified_at: "2026-11-30" --- # Physically Modeled NTSC Composite / VHS Tape & CRT Electron-Beam Emulation (ntsc-rs, 2023) > Simulates the full analog NTSC/VHS broadcast and tape pipeline—YIQ subcarrier modulation, bandwidth limiting, head-switching phase skew, and notch-filter demodulation—followed by a Gaussian CRT electron beam, phosphor mask, and halation. ## Reach for it when - simple scanline overlay looks fake compared to a real crt television - want authentic composite video chroma bleed rainbow artifacts and luma ringing - emulate vhs tape tracking jitter head-switching noise and chroma lag - simulate yiq subcarrier modulation and phosphor bloom in a post-process pass - give retro 3d scenes genuine analog broadcast and home-video texture ## How it works Naive retro shaders fake VHS by adding static scanlines and RGB channel offsets, missing the coupled artifacts of real analog video. Signal-accurate emulation instead operates at the native composite resolution (typically 240 active scanlines per field, sampled at 4× the NTSC color subcarrier frequency) in four physical stages. First, the gamma-encoded picture converts to **YIQ** color space; the `I` and `Q` chroma channels are low-pass filtered, quadrature-modulated onto the color subcarrier, and summed with luma `Y` into a single 1D composite waveform per scanline. Tape snow, tracking jitter, and **head-switching horizontal skew** perturb that composite waveform directly—so shifting a line also shifts its subcarrier phase, naturally producing authentic hue warps. Next, an NTSC **notch or comb demodulator** separates luma and chroma; residual cross-talk creates real dot crawl and rainbow shimmering on sharp high-frequency edges. A **VHS tape pass** further band-limits luma (with edge-sharpening ringing) and heavily smears chroma horizontally and vertically. Finally, a **CRT display stage** linearizes the decoded signal, rasterizes each scanline as a brightness-modulated Gaussian electron beam with RGB deconvergence, applies an aperture-grille or shadow-mask phosphor pattern, and adds low-resolution phosphor bloom and glass halation. ## When to use it Choose it when you want genuinely authentic camcorder, VHS tape, or broadcast CRT imagery where rainbows, dot crawl, ringing, hue-shifted tracking errors, and blooming scanlines emerge from actual signal physics. Prefer [film-emulation](film-emulation) when aiming for photochemical celluloid cinema rather than magnetic-tape television. Prefer [chromatic-aberration](chromatic-aberration) and [film-grain-synthesis](film-grain-synthesis) when you only want subtle optical lens defects without lowering spatial resolution. Prefer [pixel-art-3d-rendering](pixel-art-3d-rendering) when crisp low-res pixels should remain sharp rather than analog-blurred. ## Cost cheap — The composite encode, decode, and VHS filter passes run at tiny signal resolution (around 760×240 or 910×240), making them very cheap on GPU; only the final CRT scanline, mask, and halation pass runs at full display resolution. Measured GPU Weight: 8.22× baseline (moderate) — 0.2704 ms median / 0.2772 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.61× baseline (moderate) — 0.1051 ms median (2.57× faster on L4). Ampere A100 scaling: 4.99× baseline (light) — 0.1437 ms median (1.88× faster on A100). ## Failure modes - Moiré interference patterns when an aperture-grille or shadow-mask phosphor grid is rendered on low-DPI or non-integer-scaled displays - Severe loss of UI text legibility due to authentic VHS chroma subsampling and 240p horizontal bandwidth limits - Temporal flicker or excessive eye strain if interlaced field alternation and tracking jitter are left unattenuated - Over-darkened output if phosphor mask attenuation is not balanced with brightness compensation and halation ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### NTSC Composite / VHS & CRT Signal Emulation — clean digital RGB (left) vs YIQ subcarrier crosstalk, VHS skew & CRT phosphor beam (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SUBCARRIER": 0.75, "P_VHS_WEAR": 0.55, "P_SCANLINES": 0.7, "P_SPLIT": 0.45 } ``` ```glsl const float P_SUBCARRIER = 0.75; // P YIQ Chroma Crawl [0.0, 1.2, 0.05] const float P_VHS_WEAR = 0.55; // P VHS Tape Noise [0.0, 1.2, 0.05] const float P_SCANLINES = 0.70; // P CRT Beam & Mask [0.0, 1.0, 0.05] const float P_SPLIT = 0.45; // P Clean RGB / NTSC [0.0, 1.0, 0.02] float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); } // Broadcast SMPTE test header + retro 1980s neon-horizon 3D chrome sphere scene vec3 renderSource(vec2 uv, float t) { // Top SMPTE color bar strip (reveals YIQ chroma bleed & notch crosstalk unmistakably!) if (uv.y > 0.76) { float idx = floor(uv.x * 7.0); if (idx < 0.5) return vec3(0.85, 0.85, 0.85); if (idx < 1.5) return vec3(0.88, 0.84, 0.12); if (idx < 2.5) return vec3(0.12, 0.84, 0.86); if (idx < 3.5) return vec3(0.14, 0.82, 0.24); if (idx < 4.5) return vec3(0.86, 0.16, 0.84); if (idx < 5.5) return vec3(0.88, 0.14, 0.16); return vec3(0.14, 0.24, 0.88); } vec2 p = (uv - vec2(0.5, 0.38)) * vec2(1.5, 1.0); // Sunset sky + striped retro sun vec3 col = mix(vec3(0.10, 0.04, 0.22), vec3(0.56, 0.14, 0.44), smoothstep(0.32, -0.04, p.y)); float sunD = length(p - vec2(0.0, 0.08)); if (sunD < 0.22) { float cut = step(0.22, fract(p.y * 28.0 - t * 0.4)) + step(0.10, p.y); vec3 sunC = mix(vec3(1.0, 0.22, 0.38), vec3(1.0, 0.86, 0.24), smoothstep(-0.10, 0.26, p.y)); col = mix(col, sunC, clamp(cut, 0.0, 1.0)); } // Perspective synthwave grid floor if (p.y < -0.04) { float z = 0.26 / max(-p.y - 0.02, 0.015); float gx = abs(fract(p.x * z * 1.4) - 0.5); float gz = abs(fract(z * 1.1 - t * 1.2) - 0.5); float line = smoothstep(0.055, 0.015, min(gx, gz)); col = mix(vec3(0.04, 0.02, 0.12), vec3(0.14, 0.92, 0.98), line * exp(-z * 0.11)); } // Floating metallic chrome sphere in foreground vec2 sp = p - vec2(0.22 * sin(t * 0.7), -0.02 + 0.04 * cos(t * 1.1)); float r = length(sp); if (r < 0.16) { float nz = sqrt(max(0.16 * 0.16 - r * r, 0.0)); vec3 n = normalize(vec3(sp, nz)); vec3 ref = reflect(vec3(0.0, 0.0, -1.0), n); vec3 env = (ref.y > 0.0) ? mix(vec3(0.95, 0.35, 0.55), vec3(0.18, 0.32, 0.76), ref.y) : mix(vec3(0.08, 0.04, 0.18), vec3(0.16, 0.92, 0.95), smoothstep(0.45, 0.5, abs(sin(ref.x * 16.0)))); col = env + vec3(1.0, 0.96, 0.88) * pow(max(dot(ref, normalize(vec3(0.4, 0.6, 0.7))), 0.0), 24.0); } return col; } vec3 rgb2yiq(vec3 c) { return vec3( dot(c, vec3(0.299, 0.587, 0.114)), dot(c, vec3(0.596, -0.274, -0.322)), dot(c, vec3(0.211, -0.523, 0.312)) ); } vec3 yiq2rgb(vec3 yiq) { return vec3( yiq.x + 0.956 * yiq.y + 0.621 * yiq.z, yiq.x - 0.272 * yiq.y - 0.647 * yiq.z, yiq.x - 1.106 * yiq.y + 1.703 * yiq.z ); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / max(iResolution.xy, vec2(1.0)); float split = clamp(P_SPLIT, 0.0, 1.0); float subAmp = clamp(P_SUBCARRIER, 0.0, 1.3); float wear = clamp(P_VHS_WEAR, 0.0, 1.3); float scan = clamp(P_SCANLINES, 0.0, 1.0); vec3 col = vec3(0.0); if (uv.x < split) { col = renderSource(uv, iTime); } else { // Subtle CRT glass barrel curvature vec2 cc = uv * 2.0 - 1.0; vec2 cuv = uv + cc * dot(cc, cc) * 0.032 * scan; // VHS head-switching skew at bottom 6% of frame + per-scanline jitter float lineId = floor(cuv.y * 240.0); float headSwitch = smoothstep(0.075, 0.015, cuv.y) * (0.018 * sin(cuv.y * 190.0 + iTime * 22.0) + 0.012); float lineJitter = (hash11(lineId + floor(iTime * 30.0) * 17.3) - 0.5) * 0.0045 * wear; cuv.x += headSwitch * wear + lineJitter; // Stage 1-3: Composite NTSC YIQ encoding -> narrowband chroma low-pass -> subcarrier crosstalk demodulation float yAcc = 0.0; float iAcc = 0.0; float qAcc = 0.0; float wY = 0.0; float wC = 0.0; float phase0 = cuv.x * 260.0 + lineId * 2.0944 + floor(iTime * 30.0) * 3.14159; for (int k = -3; k <= 3; k++) { float fk = float(k); vec2 suv = clamp(cuv + vec2(fk * 0.0026, 0.0), 0.001, 0.999); vec3 yiq = rgb2yiq(renderSource(suv, iTime)); // Modulate composite signal s(t) = Y + I cos(wt) + Q sin(wt) float ph = phase0 + fk * 1.570796; float comp = yiq.x + (yiq.y * cos(ph) + yiq.z * sin(ph)) * subAmp; // High-freq luma leaks into chroma demodulator (dot crawl & rainbowing) float wy = exp(-fk * fk * 0.42); float wc = exp(-fk * fk * 0.14); yAcc += (yiq.x + (comp - yiq.x) * 0.16 * subAmp) * wy; iAcc += (yiq.y + (comp - yiq.x) * cos(ph) * 0.28 * subAmp) * wc; qAcc += (yiq.z + (comp - yiq.x) * sin(ph) * 0.28 * subAmp) * wc; wY += wy; wC += wc; } vec3 yiqOut = vec3(yAcc / wY, iAcc / wC, qAcc / wC); // VHS chroma delay & snow speckle on dropout lines float dropout = step(0.992 - wear * 0.012, hash11(lineId * 1.7 + floor(iTime * 18.0) * 3.1)); yiqOut.x += dropout * (hash11(fragCoord.x + iTime * 90.0) - 0.2) * 0.45 * wear; col = clamp(yiq2rgb(yiqOut), 0.0, 1.4); // Stage 4: Gaussian CRT electron-beam scanline profile + RGB aperture-grille phosphor mask + halation float scanPhase = fract(cuv.y * 240.0) - 0.5; float beamWidth = mix(0.24, 0.42, clamp(yiqOut.x, 0.0, 1.0)); float beam = exp(-(scanPhase * scanPhase) / max(beamWidth * beamWidth, 0.02)); col *= mix(1.0, 0.42 + 0.85 * beam, scan); float pxMod = mod(floor(fragCoord.x), 3.0); vec3 grille = vec3( pxMod < 0.5 ? 1.16 : 0.84, (pxMod >= 0.5 && pxMod < 1.5) ? 1.16 : 0.84, pxMod >= 1.5 ? 1.16 : 0.84 ); col *= mix(vec3(1.0), grille, scan * 0.55); // Subtle glass phosphor bloom & vignette col += col * col * 0.18 * scan; float vig = 1.0 - dot(cc * 0.42, cc * 0.42) * scan; col *= clamp(vig, 0.45, 1.0); } float sep = smoothstep(0.0035, 0.0008, abs(uv.x - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(clamp(col, 0.0, 1.0), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Multi-Bounce Acoustic Ray-Traced Echolocation Point-Cloud Visualization](https://texelatlas.vercel.app/t/acoustic-raytraced-echolocation-point-cloud.md): Transforms sparse luminous echolocation point clouds into found-footage camcorder video with authentic VHS bleed and CRT halation. - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): Maps linear HDR scene light into display-referred gamma RGB prior to YIQ composite signal encoding. ## Combination ideas - [Sonar echolocation point clouds on analog VHS-CRT](https://texelatlas.vercel.app/ideas/echolocation-pointcloud-ntsc-vhs-crt/) ## Sources 1. [primary] ntsc-rs (2023) ntsc-rs/ntsc-rs. https://github.com/ntsc-rs/ntsc-rs License: NOASSERTION. (verified via github on 2026-11-30) 2. [implementation] spite (2026) spite/codevember-2026. https://github.com/spite/codevember-2026 License: MIT. (verified via github on 2026-11-30) 3. [implementation] libretro (2016) libretro/slang-shaders. https://github.com/libretro/slang-shaders (verified via github on 2026-11-30) ## Cite this entry Texel. "Physically Modeled NTSC Composite / VHS Tape & CRT Electron-Beam Emulation." https://texelatlas.vercel.app/t/ntsc-composite-vhs-crt-signal-emulation/ (accessed 2026-12-01). --- id: "nubis-volumetric-clouds" title: "Nubis-style Ray-marched Volumetric Clouds" aliases: [Horizon Zero Dawn clouds, Nubis, Volumetric Cloud Rendering, Volumetric Clouds] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [desktop-gpu, webgpu, unreal] year_introduced: 2015 inputs: [texture, depth, material-params] outputs: [radiance, volume-density] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Schneider" url: "https://texelatlas.vercel.app/t/nubis-volumetric-clouds/" sources_verified_at: "2026-11-29" --- # Nubis-style Ray-marched Volumetric Clouds (Schneider) > Sky-scale clouds from a coverage map and tiling 3D noise textures, ray-marched in a thick layer with cheap lighting and temporal reprojection to hit a few milliseconds. ## Reach for it when - need dynamic fly-through clouds in a game - artists want to paint weather coverage - sky clouds must render in a few milliseconds - cloud layers need cheap lighting at large scale ## How it works Cloud density is composed on the fly. A weather texture gives coverage and cloud type; a height-gradient function shapes each type vertically; a low-frequency Perlin-Worley 3D texture carves the base shape and a higher-frequency Worley 3D texture erodes the edges, with curl noise distorting the lookup for wispy detail. A ray is marched through the layer (a spherical shell) with large steps that shrink when density is first found. At each sample a handful of cone-spread samples toward the sun estimate optical depth; a Beer-Lambert term, a powder-style darkening term for edges and a dual-lobe HG phase give the lighting. To fit the budget, only one pixel in each block of a small pattern is traced per frame and the result is reprojected and blended, and sky color and aerial perspective come from the atmosphere model. ## When to use it Choose it for large, dynamic, fly-through skies in games and real-time visualisation where artists drive weather via a coverage map. Prefer [Multiple-Scattering Approximation by Octaves](https://texelatlas.vercel.app/t/multiple-scattering-octaves.md) as an add-on when clouds look too dark and flat inside thick regions. Prefer [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) with a full 3D grid ([OpenVDB](https://texelatlas.vercel.app/t/openvdb.md), [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md)) for authored hero clouds. Use Sky/Atmosphere ([Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md)) for the lighting environment rather than a plain gradient. ## Cost medium — Tuned in production for a few ms on console-class GPUs using reduced-resolution tracing plus temporal reprojection; full-res without reprojection is much heavier. Measured GPU Weight: 3355.35× baseline (extreme) — 110.3911 ms median / 110.787 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2713.18× baseline (extreme) — 43.1396 ms median (2.56× faster on L4). Ampere A100 scaling: 2148.34× baseline (extreme) — 61.8721 ms median (1.78× faster on A100). ## Failure modes - Ghosting and trailing of clouds under fast camera motion or wind from temporal reprojection - Low-res tracing flickers or shimmers at cloud edges without careful jitter and history clamping - Overly dark cloud interiors because only single scattering is evaluated - Banding in the layer where step size is too coarse along grazing rays near the horizon - Tiling of the noise volumes visible in the distance or at the layer boundary - Cloud shadow on the ground needs a separate shadow-map-like pass ## Engine support - unity: builtin — `Volume > Add Override > Sky > Volumetric Clouds` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/volumetric-clouds-volume-override-reference.md, checked 2026-12-01) — HDRP only; ray-marched volumetric clouds, same family as Nubis but not identical. - unreal: builtin — `Place Actors > Visual Effects > Volumetric Cloud (ray-marched atmospheric cloud component)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/volumetric-cloud-component-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: texture, depth, material-params - Outputs: radiance, volume-density - Platforms: desktop-gpu, webgpu, unreal ## Presets ### Toy Nubis-style cloud layer with height gradient, coverage and detail erosion (glsl-fragment; rendered 2026-11-29) ```json { "LAYER_LO": 1.2, "LAYER_HI": 3.2, "COVERAGE": 0.55, "DENSITY": 14 } ``` ```glsl // Toy Nubis-style cloud layer: height-fraction gradient shapes the noise, coverage threshold carves // cumulus-like cells, detail noise erodes edges; lit by a short light-march with Beer + powder terms. const float LAYER_LO = 1.2; const float LAYER_HI = 3.2; const float COVERAGE = 0.55; const float DENSITY = 14.0; float h31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); } float vn(vec3 x) { vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f); return mix(mix(mix(h31(i), h31(i + vec3(1, 0, 0)), f.x), mix(h31(i + vec3(0, 1, 0)), h31(i + vec3(1, 1, 0)), f.x), f.y), mix(mix(h31(i + vec3(0, 0, 1)), h31(i + vec3(1, 0, 1)), f.x), mix(h31(i + vec3(0, 1, 1)), h31(i + vec3(1, 1, 1)), f.x), f.y), f.z); } float fbm(vec3 p) { return 0.5 * vn(p) + 0.25 * vn(p * 2.0) + 0.125 * vn(p * 4.0) + 0.0625 * vn(p * 8.0); } float dens(vec3 p) { float hf = clamp((p.y - LAYER_LO) / (LAYER_HI - LAYER_LO), 0.0, 1.0); float grad = clamp(hf / 0.12, 0.0, 1.0) * clamp((0.85 - hf) / 0.45, 0.0, 1.0); vec3 q = p * 0.6 + vec3(iTime * 0.05, 0.0, 0.0); float shape = fbm(q * vec3(1.0, 1.4, 1.0)) * 1.9 * grad; float d = shape - (1.0 - COVERAGE) * 0.9; d -= 0.22 * (1.0 - hf) * fbm(q * 5.0 + 7.0); return max(d, 0.0) * DENSITY; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.05, 0.0); vec3 rd = normalize(vec3(uv.x, uv.y * 0.9 + 0.22, -1.0)); vec3 L = normalize(vec3(0.5, 0.4, -0.6)); vec3 skyc = mix(vec3(0.75, 0.82, 0.92), vec3(0.2, 0.42, 0.8), clamp(rd.y * 2.2, 0.0, 1.0)); skyc += vec3(1.0, 0.9, 0.7) * pow(max(dot(rd, L), 0.0), 100.0) * 2.0; vec3 col = skyc; if (rd.y > 0.01) { float t0 = (LAYER_LO - ro.y) / rd.y, t1 = min((LAYER_HI - ro.y) / rd.y, t0 + 14.0); float ds = (t1 - t0) / 56.0; float T = 1.0; vec3 S = vec3(0.0); float cs = dot(rd, L); float ph = 0.7 * (1.0 - 0.5) / (12.566 * pow(1.25 - 0.9 * cs, 1.5)) + 0.3 * 0.0796; for (int i = 0; i < 56; i++) { vec3 p = ro + rd * (t0 + (float(i) + 0.5) * ds); float d = dens(p); if (d < 0.01) continue; float tau = 0.0; for (int k = 1; k <= 4; k++) tau += dens(p + L * float(k) * 0.18) * 0.18; float hf = clamp((p.y - LAYER_LO) / (LAYER_HI - LAYER_LO), 0.0, 1.0); float light = (exp(-tau) + 0.35 * exp(-tau * 0.25)) * (1.0 - exp(-2.0 * d * 0.2)); vec3 amb = mix(vec3(0.25, 0.3, 0.4), vec3(0.6, 0.7, 0.9), hf) * 0.5; S += T * (vec3(1.0, 0.93, 0.8) * light * ph * 10.0 + amb) * d * ds; T *= exp(-d * ds); } float fade = exp(-t0 * 0.03); col = mix(skyc, skyc * T + S, fade); } col = 1.0 - exp(-col * 1.3); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) - extends [Multiple-Scattering Approximation by Octaves](https://texelatlas.vercel.app/t/multiple-scattering-octaves.md) ## Combines with - [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md): Atmosphere LUTs give sun colour at the cloud, and clouds are composited under the aerial-perspective pass. - [Multiple-Scattering Approximation by Octaves](https://texelatlas.vercel.app/t/multiple-scattering-octaves.md): Replaces the single-scatter shading with a multi-octave approximation that brightens cloud interiors. ## Combination ideas - [Billowing Nubis volumetric clouds driven by MacCormack clamped advection](https://texelatlas.vercel.app/ideas/maccormack-advected-nubis-clouds/) - [Storms that form and drift](https://texelatlas.vercel.app/ideas/simulated-weather-for-clouds/) ## Sources 1. [primary] Andrew Schneider The Real-time Volumetric Cloudscapes of Horizon Zero Dawn. SIGGRAPH 2015, Advances in Real-Time Rendering. https://advances.realtimerendering.com/s2015/The%20Real-time%20Volumetric%20Cloudscapes%20of%20Horizon%20-%20Zero%20Dawn%20-%20ARTR.pdf (verified via http on 2026-11-29) 2. [implementation] takram-design-engineering (2024) takram-design-engineering/three-geospatial. https://github.com/takram-design-engineering/three-geospatial License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Nubis-style Ray-marched Volumetric Clouds." https://texelatlas.vercel.app/t/nubis-volumetric-clouds/ (accessed 2026-12-01). --- id: "nvidia-nrd-relax-reblur" title: "NVIDIA Real-time Denoisers (ReBLUR, ReLAX)" aliases: [NRD, ReBLUR, ReLAX, SIGMA] domain: "post" stage: "post" realtime: "realtime" platforms: [desktop-gpu, unreal, unity] year_introduced: 2021 inputs: [radiance, gbuffer, normals, depth] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "NVIDIA-RTX, 2020" url: "https://texelatlas.vercel.app/t/nvidia-nrd-relax-reblur/" sources_verified_at: "2026-11-29" --- # NVIDIA Real-time Denoisers (ReBLUR, ReLAX) (NVIDIA-RTX, 2020) > A spatio-temporal denoising library with separate denoisers for diffuse, specular and shadow signals from sparse ray tracing, built for engine integration across D3D12, Vulkan and D3D11. ## Reach for it when - ray traced reflections and diffuse look grainy in my game - need a production denoiser for sparse ray tracing signals - glossy ray traced reflections smear after denoising - want one library to denoise shadows diffuse and specular - restir output still has speckle noise on screen ## How it works NRD is not one filter but a set of denoisers sharing a common input contract: noisy hit signals with hit distance, view-space depth or linear Z, world or view normals with roughness, and motion vectors. **ReBLUR** is a recurrent, hit-distance-aware blur: it accumulates history with reprojection, estimates how much history there is per pixel, and sizes a blur kernel from accumulation count, roughness and the distance the ray travelled, so contact reflections stay sharp while distant ones soften. **ReLAX** is closer to SVGF: it was designed for ReSTIR-style signals, keeps luminance variance, clamps history against a local neighbourhood and runs an à-trous cascade, and it expects diffuse and specular radiance pre-divided by albedo or Fresnel. **SIGMA** denoises soft shadows from penumbra-distance inputs. Engines pass in packed inputs, call the dispatch list NRD emits, and remodulate the result. ## When to use it Choose it for shipping real-time ray-traced games or renderers that need reliable diffuse, specular and shadow denoising with documented input packing and temporal stability. Prefer [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md) when you want a compact algorithm you can read and port to WebGPU, [Intel Open Image Denoise (OIDN)](https://texelatlas.vercel.app/t/open-image-denoise.md) for final-frame offline output, and learned reconstruction such as [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) when ray reconstruction is available on the target hardware. ## Cost medium — Runs as a multi-pass compute chain per signal; budget depends on how many signals (diffuse, specular, shadows) and the resolution. No benchmark figures are stated here. Measured GPU Weight: 51.13× baseline (heavy) — 1.6823 ms median / 1.8128 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 45.08× baseline (heavy) — 0.7168 ms median (2.35× faster on L4). Ampere A100 scaling: 34.13× baseline (heavy) — 0.9828 ms median (1.71× faster on A100). ## Failure modes - Wrong input packing (hit distance, roughness, normals encoding, pre-division by albedo) is the most common cause of smearing or dark results - Lag and ghosting in indirect lighting on fast changes, and disocclusion trails behind moving objects - Over-blurring of glossy reflections when hit distance is missing or inaccurate - Residual low-frequency flicker when upstream sampling changes noise distribution frame to frame - Sample-based integration requires a proprietary-licensed binary/headers; check redistribution terms ## Dataflow - Inputs: radiance, gbuffer, normals, depth - Outputs: radiance - Platforms: desktop-gpu, unreal, unity ## Presets ### NVIDIA NRD (ReBLUR / ReLAX) — 1-spp noisy ray-traced specular & shadow (left) vs hit-distance-aware denoised output (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.34, "P_HIT_DIST_AWARE": 1, "P_NOISE_AMP": 0.8, "P_SPLIT": 0.48 } ``` ```glsl const float P_ROUGHNESS = 0.34; // P Floor Roughness [0.08, 0.78, 0.02] const float P_HIT_DIST_AWARE = 1.00; // P Hit-Dist Scaling [0.0, 1.0, 0.05] const float P_NOISE_AMP = 0.80; // P Ray Noise [0.2, 1.4, 0.05] const float P_SPLIT = 0.48; // P 1-spp / NRD ReBLUR [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Scene with glossy floor reflecting emissive neon pillars at varying hit distances (near contact vs far reflection!) void evalNRDScene(vec2 uv, float rough, float t, out vec3 clean, out float hitDist, out vec3 nrm, out float linZ) { vec3 ro = vec3(0.35 * sin(t * 0.45), 0.42, 2.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.10, -1.45)); vec3 bg = mix(vec3(0.03, 0.04, 0.07), vec3(0.08, 0.12, 0.20), smoothstep(-0.1, 0.6, rd.y)); clean = bg; hitDist = 6.0; nrm = vec3(0.0, 0.0, 1.0); linZ = 12.0; // Emissive cyan & amber pillars vec3 p1c = vec3(-0.55, 0.15, -0.35); vec3 p2c = vec3(0.58, 0.18, -0.85); vec3 p3c = vec3(0.05, -0.05, 0.28); // Glossy ground plane y = -0.42 if (rd.y < -0.005) { float tf = (-0.42 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { linZ = tf; vec3 hp = ro + rd * tf; nrm = vec3(0.0, 1.0, 0.0); vec3 r = reflect(rd, nrm); // Compute reflection hit distance to nearest pillar/sphere float d1 = length(hp.xz - p1c.xz); float d2 = length(hp.xz - p2c.xz); float d3 = length(hp.xz - p3c.xz); hitDist = min(d1, min(d2, d3)); // Reflection lobe widens physically with hitDist * roughness (core ReBLUR principle!) float lobe = rough * (0.18 + 0.65 * hitDist); vec3 refl = bg; vec3 to1 = normalize(vec3(p1c.x, 0.25, p1c.z) - hp); vec3 to2 = normalize(vec3(p2c.x, 0.25, p2c.z) - hp); vec3 to3 = normalize(vec3(p3c.x, -0.05, p3c.z) - hp); refl += vec3(0.18, 0.92, 1.0) * exp(-pow(1.0 - max(dot(r, to1), 0.0), 1.0) / max(0.008 + lobe * lobe * 0.25, 0.005)) * 1.7 / (0.4 + d1 * 0.6); refl += vec3(1.0, 0.48, 0.18) * exp(-pow(1.0 - max(dot(r, to2), 0.0), 1.0) / max(0.008 + lobe * lobe * 0.25, 0.005)) * 1.9 / (0.4 + d2 * 0.6); refl += vec3(0.95, 0.85, 0.55) * exp(-pow(1.0 - max(dot(r, to3), 0.0), 1.0) / max(0.006 + lobe * lobe * 0.20, 0.004)) * 1.3 / (0.3 + d3 * 0.7); // Contact shadow directly under foreground sphere p3c float contactSh = smoothstep(0.16, 0.44, d3); float fres = 0.08 + 0.88 * pow(1.0 - max(dot(nrm, -rd), 0.0), 4.0); vec3 floorBase = vec3(0.12, 0.13, 0.16) * (0.35 + 0.65 * contactSh); clean = mix(floorBase, refl * (0.45 + 0.55 * contactSh), fres); } } // Intersect foreground sphere (p3c, R=0.35) vec3 oc = ro - p3c; float b = dot(oc, rd), c = dot(oc, oc) - 0.35 * 0.35; float disc = b * b - c; if (disc > 0.0) { float ts = -b - sqrt(disc); if (ts > 0.05 && ts < linZ) { linZ = ts; vec3 hp = ro + rd * ts; nrm = normalize(hp - p3c); hitDist = 0.12; vec3 l1 = normalize(p1c - hp); vec3 l2 = normalize(p2c - hp); clean = vec3(0.24, 0.26, 0.30) * 0.3 + vec3(0.18, 0.92, 1.0) * max(dot(nrm, l1), 0.0) * 0.95 + vec3(1.0, 0.52, 0.22) * max(dot(nrm, l2), 0.0) * 0.85 + vec3(0.9, 0.94, 1.0) * pow(max(dot(reflect(rd, nrm), l1), 0.0), 28.0) * 0.8; } } // Emissive vertical neon monolith cylinders (p1c & p2c) for (int k = 0; k < 2; k++) { vec3 pc = (k == 0) ? p1c : p2c; vec2 ro2 = ro.xz - pc.xz; vec2 rd2 = rd.xz; float A = dot(rd2, rd2); float B = dot(ro2, rd2); float C = dot(ro2, ro2) - 0.13 * 0.13; float D = B * B - A * C; if (D > 0.0) { float tc = (-B - sqrt(D)) / max(A, 1e-5); if (tc > 0.05 && tc < linZ) { vec3 hp = ro + rd * tc; if (hp.y > -0.42 && hp.y < 0.78) { linZ = tc; nrm = normalize(vec3(hp.x - pc.x, 0.0, hp.z - pc.z)); hitDist = 0.05; clean = (k == 0) ? vec3(0.32, 1.55, 1.75) : vec3(1.75, 0.72, 0.26); } } } } } vec3 noisySample(vec2 fc, float rough, float noiseAmp, float t, out float hitDist, out vec3 nrm, out float linZ) { vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; vec3 clean; evalNRDScene(uv, rough, t, clean, hitDist, nrm, linZ); float fr = floor(t * 14.0) * 0.19; vec2 p = floor(fc); vec3 rnd = vec3( hash21(p + vec2(fr * 13.7, 5.1)), hash21(p + vec2(31.3, fr * 29.1)), hash21(p + vec2(fr * 41.3, 67.7)) ) - 0.5; // Noise variance scales with roughness & hit distance (near contacts have crisp short rays; far rough reflections are noisy!) float sigma = noiseAmp * clamp(0.18 + rough * (0.4 + 0.9 * hitDist), 0.05, 1.6); return max(clean + rnd * sigma * (0.4 + clean * 1.1), 0.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float rough = clamp(P_ROUGHNESS, 0.06, 0.85); float hdAware = clamp(P_HIT_DIST_AWARE, 0.0, 1.0); float noiseAmp = clamp(P_NOISE_AMP, 0.1, 1.6); float cHD, cZ; vec3 cN; vec3 raw = noisySample(fragCoord, rough, noiseAmp, iTime, cHD, cN, cZ); vec3 col = raw; if (screenX >= split) { // Right: ReBLUR hit-distance-aware anisotropic kernel -- tight near contact hits, broad on distant rough hits float kernelR = mix(2.4, clamp(0.6 + cHD * rough * 5.2, 0.6, 4.8), hdAware); vec3 acc = vec3(0.0); float wSum = 0.0; for (int j = -2; j <= 2; j++) { for (int i = -2; i <= 2; i++) { vec2 off = vec2(float(i), float(j)) * kernelR; float qHD, qZ; vec3 qN; vec3 qCol = noisySample(fragCoord + off, rough, noiseAmp, iTime, qHD, qN, qZ); float wN = pow(max(dot(cN, qN), 0.0), 16.0); float wZ = exp(-abs(cZ - qZ) * 4.5); float wG = exp(-dot(vec2(float(i), float(j)), vec2(float(i), float(j))) * 0.28); float w = wN * wZ * wG; acc += qCol * w; wSum += w; } } col = acc / max(wSum, 1e-4); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md) ## Combines with - [ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting](https://texelatlas.vercel.app/t/restir-di.md): ReSTIR direct lighting produces sparse, correlated samples that ReLAX is tuned to clean up. - [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md): Shadow rays with penumbra-distance output feed the shadow denoiser to get soft stable shadows. ## Sources 1. [primary] NVIDIA-RTX (2020) NVIDIA-RTX/NRD. https://github.com/NVIDIA-RTX/NRD License: NOASSERTION. (verified via github on 2026-11-29) 2. [implementation] NVIDIA-RTX (2021) NVIDIA-RTX/NRD-Sample. https://github.com/NVIDIA-RTX/NRD-Sample (verified via github on 2026-11-29) ## Cite this entry Texel. "NVIDIA Real-time Denoisers (ReBLUR, ReLAX)." https://texelatlas.vercel.app/t/nvidia-nrd-relax-reblur/ (accessed 2026-12-01). --- id: "obra-dinn-1bit-dithered-3d" title: "1-bit dithered 3D rendering (Obra Dinn style)" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, godot] year_introduced: 2014 inputs: [ldr-image, depth, normals] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Pope" url: "https://texelatlas.vercel.app/t/obra-dinn-1bit-dithered-3d/" sources_verified_at: "2026-11-29" --- # 1-bit dithered 3D rendering (Obra Dinn style) (Pope) > Renders a 3D scene as pure black and white by dithering lit brightness, with the dither pattern anchored to world or object space rather than the screen so it holds still as the camera moves. ## Reach for it when - want a pure black and white engraving look in 3d - dither pattern swims with the camera - retro 1-bit style that stays stable in motion - monochrome shading that stays readable - dithering anchored to objects instead of the screen ## How it works The scene is shaded to a luminance value, then thresholded against a dither pattern to produce 1-bit output. The central problem is the screen-space pattern sliding over moving objects. The developer's devlog describes trying blue noise and Bayer matrices and projecting the dither texture so it stays tied to the 3D surfaces, plus a nearly binary lighting model so bands read as shapes. Practical variants triplanar-project a dither texture in object space, or fix the pattern to a screen grid and accept some drift, and render at low resolution then upscale with nearest filtering. Edges from depth and normals are drawn over the dither for clean contours. ## When to use it Choose it for a monochrome, retro-engraving look in games or art projects where legibility at 1 bit is the goal. Prefer [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) for a simpler screen-space version, and [Procedural cross-hatching shader](https://texelatlas.vercel.app/t/procedural-cross-hatching.md) for a line-based print look. ## Cost cheap — Cheap per-pixel work plus a low-resolution render; the main cost is authoring the lighting so it reads at 1 bit. Measured GPU Weight: 3.18× baseline (light) — 0.1045 ms median / 0.1105 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.47× baseline (light) — 0.0393 ms median (2.66× faster on L4). Ampere A100 scaling: 1.8× baseline (feather) — 0.0517 ms median (2.02× faster on A100). ## Failure modes - Screen-fixed patterns shimmer or swim over moving objects - Triplanar-projected patterns distort at oblique angles and change scale with distance - Sub-pixel detail turns to noise at low resolution; needs aggressive LOD - Very little tonal range; scenes need deliberate lighting design ## Dataflow - Inputs: ldr-image, depth, normals - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, godot ## Presets ### Left: lit greyscale frame. Right: 1-bit output from an 8x8 ordered (Bayer) dither threshold (glsl-fragment; rendered 2026-11-29) ```json { "GAMMAK": 1 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float GAMMAK=1.0; // P float bayer8(vec2 p){ivec2 i=ivec2(mod(floor(p),8.));int v=0; for(int l=0;l<3;l++){int bx=(i.x>>l)&1,by=(i.y>>l)&1;int d=2*bx+3*by-4*bx*by;v+=d*(l==0?16:(l==1?4:1));} return (float(v)+.5)/64.;} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 c=shadeBasic(uv);vec3 col=vec3(lum(c)); if(R){float v=pow(lum(c),GAMMAK/2.2*1.0);col=v>bayer8(fragCoord)?vec3(.93,.92,.85):vec3(.05,.06,.08);col=pow(col,vec3(2.2));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extends [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) - extends [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md) ## Combines with - [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md): Blue-noise threshold texture provides the grain; projection choice keeps it from swimming. - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Depth/normal edges are drawn in black over the dithered fill. ## Sources 1. [primary] Lucas Pope Return of the Obra Dinn devlog. forums.tigsource.com. https://forums.tigsource.com/index.php?topic=40832.0 (verified via wayback on 2026-11-29) 2. [tutorial] Christoph Peters Free blue noise textures. momentsingraphics.de. https://momentsingraphics.de/BlueNoise.html (verified via http on 2026-11-29) ## Cite this entry Texel. "1-bit dithered 3D rendering (Obra Dinn style)." https://texelatlas.vercel.app/t/obra-dinn-1bit-dithered-3d/ (accessed 2026-12-01). --- id: "octahedral-impostors" title: "Octahedral impostors" aliases: [octahedral imposter, hemi-octahedral impostor, parallax impostor] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal, godot] year_introduced: 2018 inputs: [mesh, material-params] outputs: [texture, gbuffer] style: "both" dynamic: "both" cost: "cheap" authority: "Brucks" url: "https://texelatlas.vercel.app/t/octahedral-impostors/" sources_verified_at: "2026-11-29" --- # Octahedral impostors (Brucks) > Replace distant, complex meshes with a quad that samples a pre-baked atlas of views taken from directions on an octahedron, blending the nearest frames for smooth viewpoint changes. ## Reach for it when - thousands of trees too heavy to render as meshes - distant props look flat when camera moves around - need cheap far lods for foliage with lighting - billboards look wrong from different angles ## How it works Bake: render the object from a grid of camera directions covering the sphere (or upper hemisphere for plants and props that sit on the ground). Directions are mapped to a square atlas through octahedral encoding, which spreads samples evenly and avoids pole singularities. Each frame stores albedo, normals and often depth, so the impostor can be relit at runtime. Runtime: a camera-facing quad computes the view direction in object space, finds the three nearest baked frames, and blends them using barycentric weights. With the stored depth, a parallax step offsets each frame's lookup so the silhouette and internal parallax stay plausible; this is the 'parallax' variant. Output goes into the G-buffer, so lighting and shadows treat it like geometry. ## When to use it Choose it for dense vegetation, rocks and props at far LOD where triangle count or overdraw dominates. Prefer [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) or [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) with continuous simplification when the engine supports it and you want no baked data. Prefer plain mesh LOD from [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md) when objects stay within moderate distance, since impostors cannot be seen up close. ## Cost cheap — One quad per instance, a few texture fetches; baking is offline and atlas memory scales with frame count and channels. Measured GPU Weight: 2.81× baseline (light) — 0.0923 ms median / 0.0929 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.16× baseline (light) — 0.0343 ms median (2.69× faster on L4). Ampere A100 scaling: 1.56× baseline (feather) — 0.0449 ms median (2.06× faster on A100). ## Failure modes - Visible popping or ghosting when blending between frames, since neighbouring views disagree on silhouettes - Parallax distortion at grazing angles because stored depth is a single layer - Baked lighting or shadows leak if the atlas contains shading rather than material data - Wrong results for animated or deformed meshes, such as wind-bent trees, without a separate vertex animation path - Atlas memory cost grows quickly with frame resolution and channel count ## Dataflow - Inputs: mesh, material-params - Outputs: texture, gbuffer - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal, godot ## Presets ### Octahedral impostor atlas of baked box views, 8x8 directions (glsl-fragment; rendered 2026-11-29) ```json { "GRID": 8 } ``` ```glsl // Octahedral impostor atlas: each cell is a baked orthographic view of a box from the direction that cell encodes via octahedral mapping. const float GRID = 8.0; vec3 octDecode(vec2 e) { vec2 f = e * 2.0 - 1.0; vec3 n = vec3(f.x, 1.0 - abs(f.x) - abs(f.y), f.y); if (n.y < 0.0) n.xz = (1.0 - abs(n.zx)) * sign(n.xz); return normalize(n); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy * GRID; vec2 cell = floor(uv), f = fract(uv) * 2.0 - 1.0; vec3 dir = octDecode((cell + 0.5) / GRID); // camera direction for this cell vec3 fw = -dir; vec3 up = abs(dir.y) > 0.95 ? vec3(0, 0, 1) : vec3(0, 1, 0); vec3 rt = normalize(cross(fw, up)); up = cross(rt, fw); vec3 ro = dir * 4.0 + (rt * f.x + up * f.y) * 1.25; vec3 inv = 1.0 / fw; vec3 h = vec3(0.55, 0.9, 0.55); vec3 ta = (-h - ro) * inv, tb = (h - ro) * inv; vec3 tn = min(ta, tb), tf = max(ta, tb); float t0 = max(max(tn.x, tn.y), tn.z), t1 = min(min(tf.x, tf.y), tf.z); vec3 col = vec3(0.07, 0.08, 0.11) + 0.5 * vec3(0.1, 0.15, 0.3) * (0.5 + 0.5 * dir.y) * 0.4; // hit a lower smaller box on top to give the silhouette shape if (t1 > max(t0, 0.0)) { vec3 p = ro + fw * t0; vec3 n = -sign(fw) * step(tn.yzx, tn.xyz) * step(tn.zxy, tn.xyz); float dif = max(dot(n, normalize(vec3(0.5, 0.8, 0.4))), 0.0); vec3 alb = abs(n.y) > 0.5 ? vec3(0.9, 0.75, 0.45) : (abs(n.x) > 0.5 ? vec3(0.4, 0.65, 0.9) : vec3(0.9, 0.45, 0.4)); float stripe = 0.85 + 0.15 * sin(p.y * 14.0); col = alb * (0.25 + 0.8 * dif) * stripe; } vec2 g = abs(f); col = mix(col, vec3(0.0), smoothstep(0.03, 0.0, 1.0 - max(g.x, g.y))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Silhouette-Strip Depth-Parallax Octahedral Impostors](https://texelatlas.vercel.app/t/silhouette-strip-octahedral-impostors.md) ## Combines with - [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md): Culling produces a per-instance LOD choice that switches far instances to impostor quads in the same indirect draw. ## Combination ideas - [Dithered impostor forests, temporally rebuilt](https://texelatlas.vercel.app/ideas/impostor-forest-temporal-upscale/) - [Far LOD for captured splat objects](https://texelatlas.vercel.app/ideas/splat-captures-impostor-lod/) ## Sources 1. [primary] Ryan Brucks Octahedral Impostors. shaderbits.com. https://shaderbits.com/blog/octahedral-impostors (verified via http on 2026-11-30) 2. [implementation] agargaro (2025) agargaro/octahedral-impostor. https://github.com/agargaro/octahedral-impostor License: MIT. (verified via github on 2026-11-29) 3. [implementation] wojtekpil (2020) wojtekpil/Godot-Octahedral-Impostors. https://github.com/wojtekpil/Godot-Octahedral-Impostors License: MIT. (verified via github on 2026-11-29) 4. [tutorial] Vlad Krutenyuk (2026) Octahedral Tree Impostors with Depth Parallax and Silhouette Strips. kvyverse. https://kvyverse.com/octahedral-tree-impostors (verified via http on 2026-11-30) 5. [implementation] Vlad Krutenyuk (2026) Octahedral Tree Impostors Live Source (Three.js). kvyverse Editor. https://kvyverse.com/editor/world/6b0041d2e78fe5de949e5722 (verified via http on 2026-11-30) ## Cite this entry Texel. "Octahedral impostors." https://texelatlas.vercel.app/t/octahedral-impostors/ (accessed 2026-12-01). --- id: "oklab-palette-quantization" title: "OKLab palette quantization" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, cpu, python] year_introduced: 2020 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Ottosson" url: "https://texelatlas.vercel.app/t/oklab-palette-quantization/" sources_verified_at: "2026-11-29" --- # OKLab palette quantization (Ottosson) > Maps each pixel to the nearest colour in a fixed palette measured in OKLab, which tracks perceived colour difference far better than Euclidean RGB distance. ## Reach for it when - mapping to a fixed palette gives wrong perceived colours - game boy or pico-8 look needs correct nearest colour - rgb distance picks ugly hue matches - limit image to custom swatches with good perceptual match ## How it works Convert the pixel from linear sRGB to OKLab through two small matrix multiplications and a cube root. Do the same for each palette entry (precomputed offline). Then find the palette colour with the smallest Euclidean distance in OKLab, which approximates perceived difference because OKLab is built to be perceptually uniform in lightness, chroma and hue. To dither, add a Bayer or blue-noise threshold to the L (or all) coordinates before the nearest-colour search, which dithers across palette entries. For palettes larger than around 32 entries, store them in a texture or a lookup cube; for small palettes a loop over uniforms suffices. ## When to use it Choose it for limited-palette looks (Game Boy, PICO-8, custom swatches) where matching human perception of hue and brightness matters. Prefer plain [Posterization](https://texelatlas.vercel.app/t/posterization.md) when you only need fewer levels per channel with no fixed palette, and [Error-diffusion dithering (Floyd-Steinberg)](https://texelatlas.vercel.app/t/error-diffusion-dithering.md) for offline conversion with higher quality. ## Cost cheap — Loop over palette size per pixel; cheap for small palettes, medium for large ones without a LUT. Measured GPU Weight: 4.36× baseline (light) — 0.1435 ms median / 0.1468 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.18× baseline (light) — 0.0506 ms median (2.84× faster on L4). Ampere A100 scaling: 2.95× baseline (light) — 0.085 ms median (1.69× faster on A100). ## Failure modes - Nearest-colour assignment has hard contours between palette regions without dithering - OKLab distance still disagrees with perception for very saturated blues and out-of-gamut colours - Large palettes cost per-pixel loops unless baked into a 3D LUT - Temporal flicker where a pixel sits near a boundary between two palette colours ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, cpu, python ## Presets ### Left: nearest palette colour by RGB distance. Right: nearest by OKLab distance (same 10-colour palette) (glsl-fragment; rendered 2026-11-29) ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } vec3 toOk(vec3 c){c=pow(c,vec3(2.2)); float l=pow(.4122214708*c.r+.5363325363*c.g+.0514459929*c.b,1./3.),m=pow(.2119034982*c.r+.6806995451*c.g+.1073969566*c.b,1./3.),s=pow(.0883024619*c.r+.2817188376*c.g+.6299787005*c.b,1./3.); return vec3(.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s);} const vec3 PAL[10]=vec3[10](vec3(.07,.08,.18),vec3(.35,.2,.5),vec3(.15,.45,.5),vec3(.3,.65,.3),vec3(.95,.85,.3),vec3(.95,.55,.2),vec3(.8,.2,.2),vec3(.9,.55,.7),vec3(.55,.6,.7),vec3(.95,.95,.9)); void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 c=img(q),col=c,co=toOk(c);float best=1e9; for(int i=0;i<10;i++){float d=R?dot(toOk(PAL[i])-co,toOk(PAL[i])-co):dot(PAL[i]-c,PAL[i]-c);if(d A perceptually uniform opponent color space with a simple two-matrix, cube-root transform. Lightness, chroma and hue are predictable, which makes gradients, palettes and gamut mapping look right. ## Reach for it when - gradients turn muddy or change hue unexpectedly - need perceptually even palette generation - saturation changes shift the apparent brightness - gamut clipping alters hue - colour mixing that looks natural to the eye ## How it works Oklab takes linear sRGB through a 3x3 matrix to approximate cone responses (LMS), applies a cube root to each channel, and applies a second 3x3 matrix to get L (perceived lightness), a (green-red) and b (blue-yellow). It was fitted to data from a more complex colour model with the goal of better hue linearity and lightness prediction than CIELAB, at a similar cost. Converting a, b to polar form gives OKLCH: chroma and hue. Interpolating in Oklab avoids the muddy mid-point of RGB gradients and the hue drift of HSV, and changing L alone changes lightness without hue shift. Because the cube root is not defined for HDR scaling, modifications exist for high dynamic range. ## When to use it Choose it for gradients, palette generation, hue-preserving gamut clipping, saturation controls, and any grading where perceptual predictability matters. Prefer CIELAB when you need compatibility with established colour-difference metrics (the Delta E formulas). Prefer sRGB linear for light transport, since Oklab is not additive. ## Cost cheap — Two 3x3 matrices and a cube root per pixel. Measured GPU Weight: 1.15× baseline (feather) — 0.0377 ms median / 0.0393 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1× baseline (feather) — 0.0159 ms median (2.37× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.31× faster on A100). ## Failure modes - Not additive, so lighting maths must stay in linear RGB - Gamut boundaries are complex in a, b space and need a dedicated clip function - Blue hues are less uniform than elsewhere and drift when lightness changes - Designed for the SDR range; HDR values need an extended variant ## Engine support - godot: builtin — `Color.from_ok_hsl(h, s, l) and Color.ok_hsl_h / ok_hsl_s / ok_hsl_l perceptual color helpers` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Color.xml, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, cpu, blender ## Presets ### Four ramps with their OKLab lightness below: sRGB lerp, OKLab lerp, HSV hue sweep, OKLCH hue sweep (glsl-fragment; rendered 2026-11-29) ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 toLin(vec3 c){return pow(c,vec3(2.2));} vec3 toOk(vec3 c){c=toLin(c); float l=.4122214708*c.r+.5363325363*c.g+.0514459929*c.b; float m=.2119034982*c.r+.6806995451*c.g+.1073969566*c.b; float s=.0883024619*c.r+.2817188376*c.g+.6299787005*c.b; l=pow(l,1./3.);m=pow(m,1./3.);s=pow(s,1./3.); return vec3(.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s);} vec3 fromOk(vec3 c){ float l=c.x+.3963377774*c.y+.2158037573*c.z,m=c.x-.1055613458*c.y-.0638541728*c.z,s=c.x-.0894841775*c.y-1.291485548*c.z; l=l*l*l;m=m*m*m;s=s*s*s; vec3 r=vec3(4.0767416621*l-3.3077115913*m+.2309699292*s,-1.2684380046*l+2.6097574011*m-.3413193965*s,-.0041960863*l-.7034186147*m+1.707614701*s); return pow(clamp(r,0.,1.),vec3(1./2.2));} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=fragCoord/iResolution.xy;float x=uv.x; int band=int(floor((1.-uv.y)*4.));float f=fract((1.-uv.y)*4.); vec3 a=vec3(0.,0.,1.),b=vec3(1.,1.,0.),col; if(band==0) col=mix(a,b,x); else if(band==1) col=fromOk(mix(toOk(a),toOk(b),x)); else if(band==2){vec3 k=clamp(abs(mod(x*6.+vec3(0.,4.,2.),6.)-3.)-1.,0.,1.);col=k;} else {float h=x*6.2831853;col=fromOk(vec3(.75,.12*cos(h),.12*sin(h)));} if(f>.78){float L=toOk(col).x;col=vec3(L);} if(f<.012||f>.985)col=vec3(.08); fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Combines with - [3D LUT color grading](https://texelatlas.vercel.app/t/lut-color-grading.md): Edit in Oklab, bake the result into a LUT. ## Sources 1. [primary] Björn Ottosson A perceptual color space for image processing. bottosson.github.io. https://bottosson.github.io/posts/oklab (verified via http on 2026-11-29) 2. [implementation] bottosson (2020) bottosson/bottosson.github.io. https://github.com/bottosson/bottosson.github.io (verified via github on 2026-11-29) ## Cite this entry Texel. "Oklab perceptual color space." https://texelatlas.vercel.app/t/oklab/ (accessed 2026-12-01). --- id: "omnidirectional-shadow-maps" title: "Omnidirectional (cube) shadow maps for point lights" aliases: [cube shadow maps, point light shadows, omni shadows] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2004 inputs: [mesh, depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "heavy" authority: "Gerasimov" url: "https://texelatlas.vercel.app/t/omnidirectional-shadow-maps/" sources_verified_at: "2026-11-29" --- # Omnidirectional (cube) shadow maps for point lights (Gerasimov) > Renders scene depth from a point light into six perspective views (a cube map) and looks up shadows with the world-space direction from the light to the shaded point. ## Reach for it when - need shadows from a point light that shines in all directions - lamp or torch should cast shadows in every direction - shadow map seams appear at cube face edges - point light shadows are too expensive with many lights - spot or point lights need shadow lookups from a direction vector ## How it works A point light radiates in all directions, so a single planar map is not enough. The scene is rendered six times from the light position with 90-degree perspective frusta aligned to the cube axes, storing either hardware depth or linear distance (distance from light divided by light range) in each face. During shading the vector from light to fragment is used to sample the cube; its dominant axis picks the face, and the stored distance is compared with the fragment's. Storing linear distance avoids perspective non-linearity so one bias works across the range. Filtering needs care at face edges: kernels must stay seamless, which cube sampling handles in hardware or via small offsets with PCF. Optimisations include culling casters per face, skipping static lights, rendering all six faces in one pass with layered targets or instancing, using an atlas of faces for engines without cube arrays, and resolution tiers by light importance. ## When to use it Choose it for dynamic point and omnidirectional lights (lamps, explosions, spotlights wider than ~120 degrees). Prefer a single perspective [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) map for narrow spotlights, [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) for the sun, [Shadow Volumes](https://texelatlas.vercel.app/t/shadow-volumes.md) when exact hard edges matter, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) or [Screen-Space Contact Shadows](https://texelatlas.vercel.app/t/contact-shadows.md) when many small lights cannot afford six passes each. Tame cost with [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md) so only lights touching visible clusters get maps. ## Cost heavy — Up to six geometry passes per light; cost scales with light count, caster count and resolution, mitigated by culling, caching of static lights and per-light update rates. Measured GPU Weight: 34.33× baseline (heavy) — 1.1293 ms median / 1.2152 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 36.96× baseline (heavy) — 0.5876 ms median (1.92× faster on L4). Ampere A100 scaling: 21.93× baseline (heavy) — 0.6315 ms median (1.79× faster on A100). ## Failure modes - Visible seams or filtering discontinuities along cube-face boundaries with wide PCF kernels - Large per-light cost: geometry is processed up to six times, which limits light count - Resolution waste at face corners and low texel density at distance, producing blocky edges - Bias tuned for one face direction leaks or acnes on others when depth is not linearised - Shadows pop when culling casters outside the light radius or when a cached face goes stale ## Engine support - babylonjs: builtin — `new ShadowGenerator(size, pointLight)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Shadows/shadowGenerator.ts, checked 2026-12-01) - blender: builtin — `EEVEE > Point Light omnidirectional virtual shadow map` (evidence: https://docs.blender.org/manual/en/5.2/render/lights/light_object.html, checked 2026-12-01) - godot: builtin — `OmniLight3D.shadow_enabled = true; omni_shadow_mode = SHADOW_CUBE` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/OmniLight3D.xml, checked 2026-12-01) - threejs: builtin — `pointLight.castShadow = true` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/lights/PointLightShadow.js, checked 2026-12-01) - unity: builtin — `Light > Type = Point > Shadow Type; HDRP Punctual shadows` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Shadows-in-HDRP.md, checked 2026-12-01) - unreal: builtin — `Point Light > Cast Shadows (omnidirectional cubemap or Virtual Shadow Map point-light shadows)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/point-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Omnidirectional (Cube) Shadow Maps — 6 cubemap face sectors & radial depth (left) vs 360-deg PCF point-light shadows (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_LIGHT_ORBIT": 0.6, "P_PCF_SOFT": 0.55, "P_FACE_VIS": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_LIGHT_ORBIT = 0.60; // P Point-Light Orbit [0.0, 1.6, 0.05] const float P_PCF_SOFT = 0.55; // P Cube PCF Softness [0.1, 1.2, 0.05] const float P_FACE_VIS = 0.65; // P Cube Face Tint [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P Cube Faces / Final [0.0, 1.0, 0.02] 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); } // Enclosed gallery chamber with pillars & floating blocks so point light casts radial shadows on all 6 faces vec2 mapChamber(vec3 p) { // Inverted room box vec3 q = abs(p - vec3(0.0, 0.25, 0.0)) - vec3(1.55, 0.95, 1.55); float dRoom = -max(q.x, max(q.y, q.z)); vec2 res = vec2(dRoom, 1.0); // 4 octagonal-arranged pillars casting radial shadows outward for (int i = 0; i < 4; i++) { float ang = float(i) * 1.570796 + 0.7854; vec3 pc = vec3(cos(ang) * 0.62, -0.05, sin(ang) * 0.62); float dP = sdBox(p - pc, vec3(0.11, 0.65, 0.11)); if (dP < res.x) res = vec2(dP, 2.0); } // Floating central frame bar above point light float dRing = sdBox(p - vec3(0.0, 0.48, -0.15), vec3(0.45, 0.06, 0.12)); if (dRing < res.x) res = vec2(dRing, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapChamber(p + e.xyy).x - mapChamber(p - e.xyy).x, mapChamber(p + e.yxy).x - mapChamber(p - e.yxy).x, mapChamber(p + e.yyx).x - mapChamber(p - e.yyx).x )); } // Trace omnidirectional cube-map ray from point light toward surface point float pointShadow(vec3 p, vec3 lPos, float soft) { vec3 toL = lPos - p; float distL = length(toL); vec3 dir = toL / max(distL, 1e-4); float sh = 1.0; float t = 0.04; for (int i = 0; i < 24; i++) { float h = mapChamber(p + dir * t).x; if (h < 0.003) return 0.0; sh = min(sh, (8.0 / max(soft, 0.15)) * h / t); t += max(h, 0.03); if (t > distL - 0.08) break; } return clamp(sh, 0.0, 1.0); } // Identify dominant cubemap face (+X,-X,+Y,-Y,+Z,-Z) and seam proximity for direction v void cubeFaceInfo(vec3 v, out vec3 faceCol, out float seam) { vec3 a = abs(v); float m = max(a.x, max(a.y, a.z)); vec3 r = a / max(m, 1e-4); // Seam occurs where two coordinates tie for largest magnitude float second = (a.x >= a.y && a.x >= a.z) ? max(r.y, r.z) : ((a.y >= a.z) ? max(r.x, r.z) : max(r.x, r.y)); seam = smoothstep(0.95, 0.995, second); if (a.x >= a.y && a.x >= a.z) { faceCol = (v.x > 0.0) ? vec3(0.95, 0.30, 0.25) : vec3(0.20, 0.85, 0.92); } else if (a.y >= a.z) { faceCol = (v.y > 0.0) ? vec3(0.30, 0.92, 0.42) : vec3(0.88, 0.32, 0.88); } else { faceCol = (v.z > 0.0) ? vec3(0.32, 0.56, 0.98) : vec3(0.98, 0.78, 0.24); } } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float t = iTime * max(P_LIGHT_ORBIT, 0.0); float soft = clamp(P_PCF_SOFT, 0.1, 1.4); float faceVis = clamp(P_FACE_VIS, 0.0, 1.0); vec3 lPos = vec3(0.34 * cos(t * 0.95), 0.14 + 0.22 * sin(t * 1.35), 0.34 * sin(t * 0.95)); vec3 ro = vec3(0.0, 0.18, 1.44); vec3 rd = normalize(vec3(uv.x, uv.y - 0.06, -1.25)); vec3 col = vec3(0.04, 0.05, 0.08); // Raymarch chamber geometry float dist = 0.04; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapChamber(ro + rd * dist); if (h.x < 0.0025) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 6.5) break; } // Test glowing point-light bulb sphere vec3 oc = ro - lPos; float b = dot(oc, rd), d = b * b - (dot(oc, oc) - 0.075 * 0.075); float tBulb = (d > 0.0 && (-b - sqrt(d)) > 0.05) ? (-b - sqrt(d)) : 1e5; if (tBulb < hit.x) { col = vec3(2.8, 2.2, 1.4); } else if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 lightToFrag = p - lPos; float dLight = length(lightToFrag); vec3 lDir = -lightToFrag / max(dLight, 1e-4); float sh = pointShadow(p + n * 0.008, lPos, soft); float atten = 1.65 / (0.35 + dLight * dLight * 1.25); float ndl = max(dot(n, lDir), 0.0); vec3 alb = (hit.y < 1.5) ? vec3(0.70, 0.68, 0.65) : ((hit.y < 2.5) ? vec3(0.84, 0.78, 0.70) : vec3(0.32, 0.58, 0.74)); vec3 lit = alb * (vec3(0.07, 0.09, 0.14) + vec3(1.45, 1.15, 0.80) * ndl * sh * atten); if (screenX < split) { // Left: Overlay 6 cubemap projection faces (+/-X, +/-Y, +/-Z) & face-edge seams from point light! vec3 fCol; float seam; cubeFaceInfo(lightToFrag, fCol, seam); float linDepthRing = smoothstep(0.04, 0.01, abs(fract(dLight * 2.5) - 0.5)); col = mix(lit, fCol * (0.35 + 0.65 * sh), faceVis * 0.52); col = mix(col, vec3(0.98, 0.99, 1.0), seam * faceVis * 0.85 + linDepthRing * faceVis * 0.22); } else { col = lit; } } // Subtle volumetric glow around point light float glowD = length(cross(lPos - ro, rd)); col += vec3(1.2, 0.85, 0.45) * exp(-glowD * 9.0) * 0.28; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) ## Combines with - [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md): Cluster light lists identify which point lights affect visible pixels, so only those need cube maps this frame. ## Sources 1. [primary] Philipp S. Gerasimov Chapter 12. Omnidirectional Shadow Mapping. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems/part-ii-lighting-and-shadows/chapter-12-omnidirectional-shadow-mapping (verified via http on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Omnidirectional (cube) shadow maps for point lights." https://texelatlas.vercel.app/t/omnidirectional-shadow-maps/ (accessed 2026-12-01). --- id: "open-image-denoise" title: "Intel Open Image Denoise (OIDN)" aliases: [OIDN] domain: "post" stage: "post" realtime: "interactive" platforms: [cpu, cuda, desktop-gpu, blender, houdini, python] year_introduced: 2019 inputs: [hdr-image, gbuffer, normals] outputs: [hdr-image] style: "photoreal" dynamic: "both" cost: "offline" authority: "RenderKit, 2019" url: "https://texelatlas.vercel.app/t/open-image-denoise/" sources_verified_at: "2026-11-29" --- # Intel Open Image Denoise (OIDN) (RenderKit, 2019) > A library of neural-network denoisers for Monte Carlo path-traced images, taking a noisy colour image and optional albedo and normal feature images, with CPU and GPU back ends. ## Reach for it when - final path traced render has fireflies and grain - need to clean up low sample count cycles-style renders - noisy viewport preview should converge faster - denoise a rendered frame using albedo and normal passes - cpu only denoiser for offline path tracer output ## How it works OIDN wraps U-Net style convolutional networks trained on pairs of noisy and high-sample-count renders. The caller creates a filter (usually the generic ray-tracing filter, `RT`), binds the colour buffer and, to preserve detail, auxiliary albedo and normal images, and picks high-dynamic-range or LDR mode. The network works per frame without temporal history, which keeps it stable for stills and animation without extra buffers. Auxiliary images are expected to be noise-free, so renderers supply first-hit or prefiltered features; a separate prefilter filter cleans noisy auxiliaries. Weights are shipped as built-in model files; users can load custom-trained weights. Inference runs on CPU vector units or GPUs via device back ends (SYCL, CUDA, HIP, Metal), and large images are tiled to bound memory. A cleanAux flag and quality setting trade speed for fidelity. ## When to use it Choose it for offline and progressive previews from a path tracer (it is the denoiser behind several DCC renderers), where per-frame quality matters more than millisecond budgets. Prefer [Spatiotemporal Variance-Guided Filtering (SVGF)](https://texelatlas.vercel.app/t/svgf.md) or [NVIDIA Real-time Denoisers (ReBLUR, ReLAX)](https://texelatlas.vercel.app/t/nvidia-nrd-relax-reblur.md) for game-frame real-time budgets with temporal reuse, and [ReSTIR PT and Generalized Resampled Importance Sampling](https://texelatlas.vercel.app/t/restir-pt.md) or [Practical Path Guiding](https://texelatlas.vercel.app/t/path-guiding.md) when you can reduce noise at the source instead of filtering it. ## Cost offline — Seconds per frame on CPU at high resolution, fast enough on a GPU for interactive viewport updates; scales with pixel count and chosen quality. Measured GPU Weight: 38.53× baseline (heavy) — 1.2677 ms median / 1.2942 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 35.43× baseline (heavy) — 0.5634 ms median (2.25× faster on L4). Ampere A100 scaling: 27.32× baseline (heavy) — 0.7867 ms median (1.61× faster on A100). ## Failure modes - Over-smoothing of fine texture and thin geometry when albedo and normal images are missing or noisy - Temporal flicker across animation frames, since each frame is denoised independently - Splotchy low-frequency artifacts at very low sample counts where the input carries fireflies - Colour shifts if the HDR/LDR mode or colour space does not match the input encoding - Textured emissive or glossy detail can be mistaken for noise and erased ## Engine support - blender: builtin — `Render Properties > Sampling > Render > Denoise > Denoiser = OpenImageDenoise` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/sampling.html, checked 2026-12-01) — Cycles; OptiX also available. - godot: builtin — `Project Settings > Rendering > Lightmapping > Denoising > Denoiser = OIDN; set EditorSettings oidn_denoise_path` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ProjectSettings.xml, checked 2026-12-01) — Lightmap denoising only; needs the external OIDN executable. - unity: official — `HDRP Volume > Path Tracing > Denoising = Intel Open Image Denoise (Unity Denoising package)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-path-tracing.md, checked 2026-12-01) — Also NVIDIA OptiX; HDRP path tracing only. - unreal: official — `Path Tracer: Post Process Volume > Path Tracing > Denoiser; set r.PathTracing.Denoiser.Name = OIDN` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/path-tracer-in-unreal-engine, checked 2026-12-01) — Default denoiser is NNE Denoiser; OIDN is selectable. ## Dataflow - Inputs: hdr-image, gbuffer, normals - Outputs: hdr-image - Platforms: cpu, cuda, desktop-gpu, blender, houdini, python ## Presets ### Intel Open Image Denoise (OIDN) — noisy path-traced render (left) vs albedo+normal-guided multi-scale denoising (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SPP_NOISE": 0.85, "P_AUX_GUIDE": 0.9, "P_DETAIL_KEEP": 0.8, "P_SPLIT": 0.48 } ``` ```glsl const float P_SPP_NOISE = 0.85; // P Path-Trace Noise [0.15, 1.5, 0.05] const float P_AUX_GUIDE = 0.90; // P Albedo+Normal Guide [0.0, 1.0, 0.05] const float P_DETAIL_KEEP = 0.80; // P Texture Preservation [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P Noisy / OIDN [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // High-detail textured wood/stone/ceramic interior scene demonstrating OIDN auxiliary albedo+normal preservation void evalOIDNScene(vec2 uv, float t, out vec3 irr, out vec3 alb, out vec3 nrm, out float dep) { vec3 ro = vec3(0.0, 0.30, 2.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.08, -1.48)); vec3 lightDir = normalize(vec3(0.55 * cos(t * 0.45), 0.78, 0.45)); dep = 10.0; alb = vec3(0.18, 0.22, 0.28); nrm = vec3(0.0, 0.0, 1.0); irr = vec3(0.35, 0.45, 0.65); // Textured wood plank floor if (rd.y < -0.005) { float tf = (-0.50 - ro.y) / rd.y; if (tf > 0.05 && tf < dep) { dep = tf; vec3 hp = ro + rd * tf; nrm = vec3(0.0, 1.0, 0.0); float grain = 0.5 + 0.5 * sin(hp.x * 24.0 + sin(hp.z * 6.0) * 1.4); float plank = step(0.04, fract(hp.z * 2.2)); alb = mix(vec3(0.28, 0.16, 0.09), vec3(0.58, 0.36, 0.20), grain) * (0.45 + 0.55 * plank); float sh1 = smoothstep(0.22, 0.58, length(hp.xz - vec2(-0.24, -0.08))); float sh2 = smoothstep(0.18, 0.46, length(hp.xz - vec2(0.42, 0.18))); irr = vec3(1.25, 1.12, 0.94) * (0.25 + 0.85 * sh1 * sh2) + vec3(0.22, 0.30, 0.42); } } // Sculpted striped marble hero sphere vec3 sc1 = vec3(-0.20, -0.10, -0.05); vec3 oc1 = ro - sc1; float b1 = dot(oc1, rd), d1 = b1 * b1 - (dot(oc1, oc1) - 0.40 * 0.40); if (d1 > 0.0) { float ts = -b1 - sqrt(d1); if (ts > 0.05 && ts < dep) { dep = ts; vec3 hp = ro + rd * ts; nrm = normalize(hp - sc1); // High-frequency marble veins (must survive denoising crisp via auxiliary albedo buffer!) float vein = smoothstep(0.65, 0.92, abs(sin((hp.x * 16.0 + hp.y * 12.0) + 2.2 * sin(hp.z * 9.0)))); alb = mix(vec3(0.88, 0.86, 0.82), vec3(0.16, 0.32, 0.46), vein); float ndl = max(dot(nrm, lightDir), 0.0); irr = vec3(1.38, 1.24, 1.06) * ndl + vec3(0.24, 0.32, 0.44) * (0.5 + 0.5 * nrm.y) + vec3(0.32, 0.20, 0.12) * max(-nrm.y, 0.0); } } // Terracotta geometric cube/vase on right vec3 sc2 = vec3(0.42, -0.22, 0.18); vec3 oc2 = ro - sc2; float b2 = dot(oc2, rd), d2 = b2 * b2 - (dot(oc2, oc2) - 0.28 * 0.28); if (d2 > 0.0) { float ts = -b2 - sqrt(d2); if (ts > 0.05 && ts < dep) { dep = ts; vec3 hp = ro + rd * ts; nrm = normalize(hp - sc2); float ring = step(0.5, fract(hp.y * 22.0)); alb = mix(vec3(0.84, 0.38, 0.22), vec3(0.94, 0.78, 0.46), ring * 0.55); float ndl = max(dot(nrm, lightDir), 0.0); irr = vec3(1.35, 1.22, 1.05) * ndl + vec3(0.22, 0.30, 0.42) * (0.5 + 0.5 * nrm.y); } } } vec3 noisyIrradiance(vec2 fc, float noiseAmp, float t, out vec3 alb, out vec3 nrm, out float dep) { vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; vec3 irr; evalOIDNScene(uv, t, irr, alb, nrm, dep); vec2 p = floor(fc); float fr = floor(t * 8.0) * 0.23; vec3 rnd = vec3( hash21(p + vec2(fr * 19.1, 7.3)), hash21(p + vec2(43.7, fr * 23.9)), hash21(p + vec2(fr * 61.3, 89.1)) ) - 0.5; return max(irr + rnd * noiseAmp * (0.65 + 0.55 * irr), 0.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float noiseAmp = clamp(P_SPP_NOISE, 0.05, 1.6); float auxGuide = clamp(P_AUX_GUIDE, 0.0, 1.0); float detailKeep = clamp(P_DETAIL_KEEP, 0.0, 1.0); vec3 cAlb, cNrm; float cDep; vec3 cIrr = noisyIrradiance(fragCoord, noiseAmp, iTime, cAlb, cNrm, cDep); vec3 col = cIrr * cAlb; if (screenX >= split) { // Right: OIDN-style multi-scale encoder-decoder proxy using auxiliary albedo & normal feature guidance vec3 accIrr = vec3(0.0); vec3 accCol = vec3(0.0); float wSum = 0.0; // Multi-scale tap strides (1px + 3px) capturing wide low-frequency illumination cleanly for (int j = -2; j <= 2; j++) { for (int i = -2; i <= 2; i++) { vec2 off = vec2(float(i), float(j)) * 2.4; vec3 qAlb, qNrm; float qDep; vec3 qIrr = noisyIrradiance(fragCoord + off, noiseAmp, iTime, qAlb, qNrm, qDep); float wN = pow(max(dot(cNrm, qNrm), 0.0), mix(1.0, 18.0, auxGuide)); float wZ = exp(-abs(cDep - qDep) * mix(0.6, 5.5, auxGuide)); float wA = exp(-dot(cAlb - qAlb, cAlb - qAlb) * mix(0.5, 6.0, auxGuide)); float wS = exp(-dot(vec2(float(i), float(j)), vec2(float(i), float(j))) * 0.22); float w = wN * wZ * wA * wS; accIrr += qIrr * w; accCol += (qIrr * qAlb) * w; wSum += w; } } vec3 smoothIrr = accIrr / max(wSum, 1e-4); vec3 smoothCol = accCol / max(wSum, 1e-4); // Re-modulate denoised irradiance with crisp auxiliary albedo (OIDN detail preservation!) col = mix(smoothCol, smoothIrr * cAlb, detailKeep); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): A low-sample path-traced frame plus first-hit albedo and normal AOVs are the denoiser's inputs. ## Sources 1. [primary] RenderKit (2019) RenderKit/oidn. https://github.com/RenderKit/oidn License: Apache-2.0. (verified via github on 2026-11-29) 2. [tutorial] Intel Open Image Denoise documentation. openimagedenoise.org. https://www.openimagedenoise.org/documentation.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Intel Open Image Denoise (OIDN)." https://texelatlas.vercel.app/t/open-image-denoise/ (accessed 2026-12-01). --- id: "openpbr-surface" title: "OpenPBR Surface" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2024 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Foundation" url: "https://texelatlas.vercel.app/t/openpbr-surface/" sources_verified_at: "2026-11-29" --- # OpenPBR Surface (Foundation) > An open, vendor-neutral uber-material specification from the Academy Software Foundation, combining Autodesk Standard Surface and Adobe Standard Material. It defines layered base, specular, transmission, subsurface, coat, fuzz and thin-film behaviour with reference code. ## Reach for it when - materials look different across renderers and tools - need one standard material model for interchange - layered materials with coat, sheen and subsurface - author physically based materials portable between dcc apps ## How it works OpenPBR specifies a surface as a physically motivated layer stack: a base slab (diffuse, metal, or subsurface/translucent), a dielectric specular interface on top, then optional thin-film, fuzz (sheen-like) and coat layers. Parameters have defined ranges and units, and layering rules say how light is attenuated and tinted passing through each layer, so the model is energy conserving by construction rather than by lobe addition. Normative text covers GGX with anisotropy, volumetric transmission with absorption and scattering, emission and geometry modifiers. The spec is paired with a MaterialX implementation of the model, which makes materials portable between renderers and DCCs. ## When to use it Choose it for authoring and interchange across DCCs, offline renderers and engines, or when you need a defensible reference for a layered material. Prefer [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) for a smaller, legacy-compatible subset, and plain glTF PBR plus extensions for runtime delivery on the web. Use [MaterialX](https://texelatlas.vercel.app/t/materialx.md) as the carrier format for OpenPBR networks. ## Cost offline — Intended primarily for offline and high-end renderers; real-time engines implement approximations of subsets. Measured GPU Weight: 1.9× baseline (feather) — 0.0625 ms median / 0.0652 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.62× baseline (feather) — 0.0258 ms median (2.42× faster on L4). Ampere A100 scaling: 1.18× baseline (feather) — 0.0341 ms median (1.83× faster on A100). ## Failure modes - Full layering is expensive; real-time ports drop or approximate the thin-film, coat-on-metal and volumetric parts, so looks differ across renderers - Spec versions are still evolving (v1.x), so exported parameter sets can drift between releases - Subsurface and transmission need volumetric support that rasterizers lack - Large parameter count invites physically implausible combinations that the spec allows but does not warn about ## Engine support - babylonjs: builtin — `new BABYLON.OpenPBRMaterial('m', scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/openpbrMaterial.pure.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Shader > Principled BSDF` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) — Principled BSDF follows OpenPBR Surface; there is no separate OpenPBR node. - unreal: builtin — `Interchange MaterialX import: Project Settings > Interchange > MaterialX > OpenPBR Surface (maps to Substrate)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/importing-materialx-files-in-unreal-engine, checked 2026-12-01) — Supported as a MaterialX surface shader on import, not as a native shading model. ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Soda-lime glass (three-material; rendered 2026-11-29) ```json { "color": "#ffffff", "roughness": 0, "metalness": 0, "ior": 1.52, "transmission": 1, "thickness": 1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 3 ### Water volume (three-material; rendered 2026-11-29) ```json { "color": "#ffffff", "roughness": 0, "metalness": 0, "ior": 1.3325, "transmission": 1, "thickness": 1 } ``` Attribution: written for this index; colour, IOR and metalness from physicallybased.info (CC0), roughness chosen here; basis: 3 ## Lineage - extends [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) - extends [MaterialX](https://texelatlas.vercel.app/t/materialx.md) ## Combines with - [MaterialX](https://texelatlas.vercel.app/t/materialx.md): MaterialX node graphs carry OpenPBR parameter sets between renderers. ## Sources 1. [primary] Academy Software Foundation OpenPBR Surface specification. academysoftwarefoundation.github.io. https://academysoftwarefoundation.github.io/OpenPBR (verified via http on 2026-11-29) 2. [implementation] AcademySoftwareFoundation (2023) AcademySoftwareFoundation/OpenPBR. https://github.com/AcademySoftwareFoundation/OpenPBR License: Apache-2.0. (verified via github on 2026-11-29) 3. [implementation] AcademySoftwareFoundation (2017) AcademySoftwareFoundation/MaterialX. https://github.com/AcademySoftwareFoundation/MaterialX License: Apache-2.0. (verified via github on 2026-11-29) 4. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "OpenPBR Surface." https://texelatlas.vercel.app/t/openpbr-surface/ (accessed 2026-12-01). --- id: "openvdb" title: "OpenVDB" aliases: [VDB] domain: "volumes" stage: "volume" realtime: "offline" platforms: [cpu, houdini, blender, cuda] year_introduced: 2013 inputs: [volume-density, sdf] outputs: [volume-density, sdf] style: "both" dynamic: "both" cost: "offline" authority: "Museth, 2013" url: "https://texelatlas.vercel.app/t/openvdb/" sources_verified_at: "2026-11-29" --- # OpenVDB (Museth, 2013) > A hierarchical, sparse volume data structure with a shallow B+tree-like layout, fast random access and a toolkit for level sets, fluids, smoke and clouds. ## Reach for it when - need to store smoke, fire or cloud volumes efficiently - dense voxel grids waste memory - exchange volumes between houdini and blender - sparse level sets and fluid caches need a standard format ## How it works A VDB grid is a tree with a small fixed depth and large branching factors (typically 5-4-3 log2 per level giving 4096-wide, 128-wide and 8-wide cubes). Voxels outside the narrow band or at background value are not allocated: inactive space is represented by a single tile value at a coarse level. Because the tree is shallow, any voxel is reached in at most three hops, and an accessor caches the last-visited nodes so coherent access (stencil loops, ray marching) is effectively constant time. A transform maps the index space to world space, and the same structure stores floats, vectors, level sets and masks. Tools include resampling, CSG on level sets, fluid advection, meshing and fast ray tracing with a hierarchical DDA. ## When to use it Choose it as the interchange and storage format for production volumes (smoke, fire, clouds, SDFs) and for offline or interactive CPU tools such as Houdini and Blender. Prefer [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md) when you need to render the same grids on the GPU, as it is a flattened read-only variant. Prefer a dense 3D texture for small volumes that fit in memory and are sampled by [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) in a shader. ## Cost offline — Designed for CPU throughput on huge sparse grids; memory scales with active voxels, not bounding box. Measured GPU Weight: 13× baseline (moderate) — 0.4276 ms median / 0.4507 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 11.71× baseline (moderate) — 0.1862 ms median (2.3× faster on L4). Ampere A100 scaling: 8.72× baseline (moderate) — 0.2511 ms median (1.7× faster on A100). ## Failure modes - Pointer-based tree does not map directly onto GPUs; needs conversion - Insertion and deletion of nodes during parallel updates need care (topology changes are not thread-safe) - Trilinear sampling across tile boundaries can show seams if the background value is not consistent - Very dense volumes lose the memory advantage and can be slower than a flat array - Level-set values outside the narrow band are clamped, so distances far from the surface are not meaningful ## Engine support - blender: builtin — `Add > Volume > Import OpenVDB` (evidence: https://docs.blender.org/manual/en/5.2/modeling/volumes/introduction.html, checked 2026-12-01) - unreal: builtin — `Import .vdb files as Sparse Volume Textures; render with Heterogeneous Volume` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sparse-volume-textures-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: volume-density, sdf - Outputs: volume-density, sdf - Platforms: cpu, houdini, blender, cuda ## Presets ### OpenVDB — sparse narrow-band level-set B+tree tiles & SDF slice (left) vs smooth CSG level-set surface (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BAND_WIDTH": 0.16, "P_MORPH_AMT": 0.55, "P_SLICE_POS": 0, "P_SPLIT": 0.48 } ``` ```glsl const float P_BAND_WIDTH = 0.16; // P Narrow Band Width [0.06, 0.32, 0.02] const float P_MORPH_AMT = 0.55; // P CSG Morph [0.0, 1.0, 0.05] const float P_SLICE_POS = 0.00; // P Slice Plane Z [-0.45, 0.45, 0.03] const float P_SPLIT = 0.48; // P Narrow-Band / Mesh [0.0, 1.0, 0.02] float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Organic OpenVDB CSG morphing level-set: torus blended with orbiting spheres & gyroid carving float mapLevelSet(vec3 p, float morph) { vec2 q = vec2(length(p.xz) - 0.52, p.y); float dTorus = length(q) - 0.22; float ang = iTime * 0.75; vec3 s1 = vec3(0.42 * cos(ang), 0.20 * sin(ang * 1.4), 0.42 * sin(ang)); vec3 s2 = vec3(-0.38 * cos(ang * 0.8), -0.18 * cos(ang), -0.38 * sin(ang * 0.8)); float dBlobs = smin(length(p - s1) - 0.24, length(p - s2) - 0.22, 0.22); float dBase = smin(dTorus, dBlobs, 0.18 + 0.16 * morph); // Subtle gyroid subtraction float gyr = (sin(p.x * 11.0) * cos(p.y * 11.0) + sin(p.y * 11.0) * cos(p.z * 11.0) + sin(p.z * 11.0) * cos(p.x * 11.0)) * 0.045; return max(dBase, -(gyr + 0.065 * (1.2 - morph * 0.5))); } vec3 calcNormal(vec3 p, float morph) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapLevelSet(p + e.xyy, morph) - mapLevelSet(p - e.xyy, morph), mapLevelSet(p + e.yxy, morph) - mapLevelSet(p - e.yxy, morph), mapLevelSet(p + e.yyx, morph) - mapLevelSet(p - e.yyx, morph) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showSurface = sx >= split; float band = clamp(P_BAND_WIDTH, 0.04, 0.4); float morph = clamp(P_MORPH_AMT, 0.0, 1.0); float sliceZ = clamp(P_SLICE_POS, -0.5, 0.5); vec3 col = mix(vec3(0.04, 0.055, 0.085), vec3(0.10, 0.14, 0.21), uv.y + 0.5); if (!showSurface) { // Left: 2D cross-section slice through OpenVDB sparse narrow-band level-set & 3-tier B+tree tile hierarchy! vec2 sp = (uv + vec2(0.24, 0.0)) * 1.95; vec3 p3 = vec3(sp.x, sp.y, sliceZ); float phi = mapLevelSet(p3, morph); // Check active narrow-band voxel & 8^3 leaf tile occupancy float tileRes = 8.0; vec3 tileCenter = (floor(p3 * tileRes) + 0.5) / tileRes; float phiTile = mapLevelSet(tileCenter, morph); bool activeTile = abs(phiTile) < band + 0.10; bool activeVoxel = abs(phi) < band; // Background inactive space (constant +/- background value, zero memory allocated!) col = (phi < 0.0) ? vec3(0.05, 0.08, 0.14) : vec3(0.035, 0.045, 0.065); // Active B+tree internal/leaf tile highlight vec2 tg = abs(fract(sp * tileRes) - 0.5); float tileEdge = smoothstep(0.05, 0.012, min(0.5 - tg.x, 0.5 - tg.y)); vec2 rootG = abs(fract(sp * 2.0) - 0.5); float rootEdge = smoothstep(0.025, 0.006, min(0.5 - rootG.x, 0.5 - rootG.y)); if (activeTile) { col = mix(col, vec3(0.10, 0.18, 0.28), 0.72); col = mix(col, vec3(0.24, 0.78, 0.98), tileEdge * 0.52); } else { col = mix(col, vec3(0.12, 0.16, 0.22), rootEdge * 0.35); } // Active narrow-band SDF values with iso-distance contours if (activeVoxel) { float tBand = clamp(phi / max(band, 1e-4), -1.0, 1.0); vec3 bandCol = (phi < 0.0) ? mix(vec3(0.98, 0.55, 0.18), vec3(0.42, 0.16, 0.48), -tBand) : mix(vec3(0.18, 0.88, 0.96), vec3(0.10, 0.34, 0.58), tBand); float contours = smoothstep(0.12, 0.02, abs(fract(phi * 28.0) - 0.5)); col = mix(bandCol * 0.88, vec3(1.0), contours * 0.28); } // Crisp zero-crossing iso-surface contour (phi == 0) float zeroLine = smoothstep(0.018, 0.004, abs(phi)); col = mix(col, vec3(1.0, 0.98, 0.85), zeroLine); } else { // Right: Full 3D raymarched smooth OpenVDB CSG level-set surface float orb = iTime * 0.36; vec3 ro = vec3(2.05 * sin(orb), 0.58, 2.05 * cos(orb)); vec3 fw = normalize(-ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.44 + ri * (uv.x - 0.14) + up * uv.y); float t = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapLevelSet(ro + rd * t, morph); if (d < 0.002) { hit = true; break; } t += d * 0.82; if (t > 6.5) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, morph); vec3 v = -rd; vec3 L1 = normalize(vec3(0.62, 0.78, 0.55)); vec3 L2 = normalize(vec3(-0.72, -0.25, -0.58)); vec3 H1 = normalize(L1 + v); float ndl1 = max(dot(n, L1), 0.0); float ndl2 = max(dot(n, L2), 0.0); float spec = pow(max(dot(n, H1), 0.0), 48.0); float fres = pow(1.0 - max(dot(n, v), 0.0), 3.0); // Subtle translucent ceramic + subsurface warmth vec3 baseC = mix(vec3(0.14, 0.58, 0.72), vec3(0.92, 0.46, 0.22), smoothstep(-0.35, 0.35, p.y)); col = baseC * (vec3(1.25, 1.15, 0.98) * ndl1 + vec3(0.32, 0.52, 0.85) * ndl2 * 0.55 + vec3(0.14, 0.18, 0.24)) + vec3(1.0, 0.95, 0.88) * spec * 0.85 + vec3(0.38, 0.88, 1.0) * fres * 0.38; } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md) ## Combines with - [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md): Convert an OpenVDB grid to a flat NanoVDB buffer for GPU rendering. - [Delta (Woodcock) Tracking](https://texelatlas.vercel.app/t/delta-tracking.md): Provides density and a max-grid used as the majorant. ## Sources 1. [primary] Ken Museth (2013) VDB. ACM Transactions on Graphics. https://doi.org/10.1145/2487228.2487235 (verified via crossref on 2026-11-29) 2. [implementation] AcademySoftwareFoundation (2013) AcademySoftwareFoundation/openvdb. https://github.com/AcademySoftwareFoundation/openvdb License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "OpenVDB." https://texelatlas.vercel.app/t/openvdb/ (accessed 2026-12-01). --- id: "ordered-dithering-bayer" title: "Ordered dithering with Bayer matrices" aliases: [Bayer dithering] domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, cpu] year_introduced: 1973 inputs: [ldr-image, hdr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Wikipedia" url: "https://texelatlas.vercel.app/t/ordered-dithering-bayer/" sources_verified_at: "2026-11-29" --- # Ordered dithering with Bayer matrices (Wikipedia) > Quantizes each pixel against a threshold taken from a tiled Bayer matrix, producing a crisp, regular dither pattern at very low cost. ## Reach for it when - need retro dithered look with cheap per-pixel cost - banding when reducing colour depth - dither pattern must not shimmer between frames - limited palette output with stable pattern - 1-bit or low-colour image conversion in a shader ## How it works A Bayer matrix of size 2^n is a recursively built grid of threshold ranks (for 4×4: values 0 to 15). For each pixel, look up the threshold at (x mod n, y mod n), normalise it to (0,1), add it to the scaled input luminance, and floor to the target number of levels. For a 1-bit result this is simply `lum > threshold`. The recursion guarantees that the dots turn on in a spread-out, balanced order as brightness rises, so the pattern shows as the familiar crosshatch-grid texture. Per-channel dithering with limited palettes works the same way. Applying it at a lower virtual resolution than the screen, with nearest-neighbour upscaling, gives the retro look. ## When to use it Choose it when you want a deterministic, stable, retro pattern that does not shimmer with camera motion and is trivially cheap. Prefer [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md) for less patterned, more natural-looking results, and [Error-diffusion dithering (Floyd-Steinberg)](https://texelatlas.vercel.app/t/error-diffusion-dithering.md) for best static quality where temporal stability does not matter. ## Cost cheap — Trivial: one matrix lookup and a comparison per pixel. Measured GPU Weight: 1.32× baseline (feather) — 0.0433 ms median / 0.0438 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.03× baseline (feather) — 0.0163 ms median (2.66× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.5× faster on A100). ## Failure modes - Visible regular crosshatch pattern at low level counts - Pattern is screen-fixed, so it appears to slide over moving 3D objects (shower door) - Banding on smooth gradients at very small matrix sizes - Colour dithering with unequal per-channel thresholds shows hue shifts ## Engine support - threejs: official — `import { bayerDither } from 'three/addons/tsl/math/Bayer.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/math/Bayer.js, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, cpu ## Presets ### 4x4 Bayer 1-bit dither of a lit sphere (glsl-fragment; rendered 2026-11-29) ```json { "levels": 2, "cell_px": 3 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: 4x4 Bayer ordered dithering of a procedural gradient const float LEVELS = 2.0; // output levels per channel (2 = pure 1-bit look) const float PIXEL = 3.0; // size of one dither cell in screen pixels const vec3 INK = vec3(0.07, 0.06, 0.12); const vec3 PAPER = vec3(0.93, 0.90, 0.78); const int BAYER4[16] = int[16](0,8,2,10, 12,4,14,6, 3,11,1,9, 15,7,13,5); float bayer4(ivec2 p){ return (float(BAYER4[(p.y & 3)*4 + (p.x & 3)]) + 0.5) / 16.0; } float scene(vec2 uv){ vec2 c = uv - vec2(0.0, 0.02); float r = length(c); float sphere = 0.0; if(r < 0.32){ vec3 n = vec3(c, sqrt(0.32*0.32 - r*r)) / 0.32; vec3 l = normalize(vec3(-0.5 + 0.2*sin(iTime), 0.6, 0.7)); sphere = clamp(dot(n, l), 0.0, 1.0); } float bg = 0.15 + 0.5*smoothstep(-0.5, 0.5, uv.x + 0.4*uv.y); return mix(bg, 0.05 + 0.95*sphere, step(r, 0.32)); } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = (fragCoord - 0.5*iResolution.xy) / iResolution.y; ivec2 cell = ivec2(floor(fragCoord / PIXEL)); vec2 uvq = (vec2(cell)*PIXEL + 0.5*PIXEL - 0.5*iResolution.xy) / iResolution.y; float lum = scene(uvq); float th = bayer4(cell); float q = floor(lum*(LEVELS-1.0) + th) / (LEVELS-1.0); fragColor = vec4(mix(INK, PAPER, clamp(q, 0.0, 1.0)), 1.0); } ``` Attribution: written for this index ### 8×8 Bayer ordered dithering (WGSL) (webgpu-wgsl; WebGPU WGSL runtime) ```json { "LEVELS": 3, "CELL_SIZE": 3 } ``` ```wgsl // WebGPU WGSL fragment specimen: recursive 8x8 Bayer threshold matrix const LEVELS: f32 = 3.0000; // P const CELL_SIZE: f32 = 3.0000; // P fn bayer2(a: vec2f) -> f32 { let f = floor(a); return fract(dot(f, vec2f(0.5, f.y * 0.75))); } fn bayer8(p: vec2f) -> f32 { let f = floor(p) - 8.0 * floor(floor(p) / 8.0); let b2 = bayer2(f); let b4 = bayer2(floor(f * 0.5)); let b8 = bayer2(floor(f * 0.25)); return (b8 * 0.25 + b4) * 0.25 + b2; } @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f { let cell = max(1.0, floor(CELL_SIZE + 0.5)); let p = floor(pos.xy / cell) * cell + 0.5 * cell; let uv = (p - 0.5 * u.resolution) / u.resolution.y; let d = length(uv); var src = mix(vec3f(0.95, 0.94, 0.90), vec3f(0.14, 0.17, 0.22), clamp(uv.x + 0.55, 0.0, 1.0)); if (d < 0.36) { let n = normalize(vec3f(uv.x, -uv.y, sqrt(max(0.0, 0.36 * 0.36 - d * d)))); let l = normalize(vec3f(cos(u.time * 0.5) * 0.7, 0.65, 0.6)); let shade = max(dot(n, l), 0.0) * 0.85 + 0.12; src = vec3f(shade * 0.96, shade * 0.86, shade * 0.72); } let thr = bayer8(pos.xy / cell) - 0.5; let lv = max(1.0, floor(LEVELS + 0.5)); let q = clamp(floor(src * lv + 0.5 + thr) / lv, vec3f(0.0), vec3f(1.0)); return vec4f(q, 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Blue-noise dithering](https://texelatlas.vercel.app/t/blue-noise-dithering.md) - extended by [1-bit dithered 3D rendering (Obra Dinn style)](https://texelatlas.vercel.app/t/obra-dinn-1bit-dithered-3d.md) ## Combines with - [OKLab palette quantization](https://texelatlas.vercel.app/t/oklab-palette-quantization.md): Bayer threshold applied before nearest-palette lookup in a perceptual space gives clean palette dithering. ## Sources 1. [primary] Wikipedia Ordered dithering. en.wikipedia.org. https://en.wikipedia.org/wiki/Ordered_dithering (verified via http on 2026-11-29) ## Cite this entry Texel. "Ordered dithering with Bayer matrices." https://texelatlas.vercel.app/t/ordered-dithering-bayer/ (accessed 2026-12-01). --- id: "oren-nayar" title: "Oren-Nayar rough diffuse" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 1994 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Oren & Nayar, 1994" url: "https://texelatlas.vercel.app/t/oren-nayar/" sources_verified_at: "2026-11-29" --- # Oren-Nayar rough diffuse (Oren & Nayar, 1994) > A diffuse model for rough matte surfaces such as clay, plaster or moon dust. It models V-groove microfacets and produces the flat, retro-reflective look Lambert cannot, where brightness barely falls toward the terminator. ## Reach for it when - rough matte surfaces like clay look too flat - moon or fabric looks wrong with simple diffuse - dusty surfaces should brighten at grazing angles - lambert diffuse looks too dark on rough materials ## How it works Oren and Nayar replace each Lambertian microfacet assumption with a Gaussian distribution of V-grooves of slope sigma, each facet itself Lambertian. Shadowing, masking and inter-reflection between groove walls add brightness when viewer and light are on the same side, so a full moon looks uniformly bright instead of darkening at the limb. The full model includes an interreflection term; the widely used qualitative form is L = (rho/pi) cos(theta_i) (A + B max(0, cos(phi_i - phi_r)) sin(alpha) tan(beta)) with A = 1 - 0.5 sigma^2/(sigma^2 + 0.33), B = 0.45 sigma^2/(sigma^2 + 0.09), alpha = max(theta_i, theta_r), beta = min(...). At sigma = 0 it reduces to Lambert. ## When to use it Choose it for rough diffuse surfaces, skin-adjacent matte looks, planets and unglazed ceramics when Lambert looks too flat and dark at the terminator. Prefer [Disney principled BRDF](https://texelatlas.vercel.app/t/disney-principled-brdf.md) diffuse (roughness dependent retro-reflection) if you already use that model, and Lambert plus [Kulla-Conty multiple-scattering compensation](https://texelatlas.vercel.app/t/kulla-conty-multiscatter.md) when budget is tight. Prefer [Separable subsurface scattering](https://texelatlas.vercel.app/t/separable-sss.md) for translucent skin. ## Cost cheap — A handful of trigonometric or dot-product operations per light; precomputed variants exist. Measured GPU Weight: 1.18× baseline (feather) — 0.0389 ms median / 0.0411 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.01× baseline (feather) — 0.016 ms median (2.43× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.35× faster on A100). ## Failure modes - Qualitative approximation drifts from the full model at grazing view angles - Often combined naively with GGX specular without an energy split, double counting reflectance - Image-based diffuse lighting cannot use the simple irradiance map; the view dependence is lost - Gaussian V-groove assumption does not match measured rough dielectrics exactly ## Engine support - babylonjs: builtin — `pbrMaterial.brdf.baseDiffuseModel = BABYLON.Constants.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBRDFConfiguration.ts, checked 2026-12-01) — Also Burley and Lambert diffuse models. - blender: builtin — `Diffuse BSDF > Roughness > 0` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/diffuse.html, checked 2026-12-01) — Cycles only. - threejs: builtin — `material.diffuseRoughness = 0.5 (MeshPhysicalMaterial)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshPhysicalMaterial.js, checked 2026-12-01) — Energy-conserving Oren-Nayar (EON). ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Lambert (left) vs Oren-Nayar (right) rough diffuse spheres (glsl-fragment; rendered 2026-11-29) ```json { "SIGMA": 0.9 } ``` ```glsl // Rough diffuse surfaces: Lambert (left) vs Oren-Nayar (right), identical albedo, light and view. // Oren-Nayar adds retro-reflection so the rough sphere looks flatter and brighter toward the terminator. const float SIGMA = 0.9; const vec3 ALBEDO = vec3(0.8, 0.72, 0.62); void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -2.2)); vec3 l = normalize(vec3(0.7, 0.25, 0.65)); vec3 col = vec3(0.04) + 0.03 * uv.y; for (int i = 0; i < 2; i++) { vec3 c = vec3(i == 0 ? -0.5 : 0.5, 0.0, 0.0); vec3 oc = ro - c; float b = dot(oc, rd); float h = b * b - dot(oc, oc) + 0.46 * 0.46; if (h < 0.0) continue; float t = -b - sqrt(h); vec3 n = normalize(ro + rd * t - c); vec3 v = -rd; float nl = max(dot(n, l), 0.0), nv = max(dot(n, v), 1e-3); float f = nl; if (i == 1) { float s2 = SIGMA * SIGMA; float A = 1.0 - 0.5 * s2 / (s2 + 0.33), B = 0.45 * s2 / (s2 + 0.09); float ti = acos(clamp(nl, 0.0, 1.0)), tr = acos(clamp(nv, 0.0, 1.0)); float al = max(ti, tr), be = min(ti, tr); vec3 lp = l - n * dot(n, l), vp = v - n * dot(n, v); float cp = max(dot(normalize(lp + 1e-5), normalize(vp + 1e-5)), 0.0); f = nl * (A + B * cp * sin(al) * tan(be)); } col = ALBEDO * f * 1.4 + ALBEDO * 0.03; } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Michael Oren, Shree K. Nayar (1994) Generalization of Lambert's reflectance model. Proceedings of the 21st annual conference on Computer graphics and interactive techniques - SIGGRAPH '94. https://doi.org/10.1145/192161.192213 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Oren-Nayar rough diffuse." https://texelatlas.vercel.app/t/oren-nayar/ (accessed 2026-12-01). --- id: "owen-scrambled-sobol-sampling" title: "Owen-scrambled Sobol and low-discrepancy sampling" aliases: [Owen scrambling, scrambled Sobol sequence, QMC sampling, hash-based Owen scrambling] domain: "gi" stage: "lighting" realtime: "interactive" platforms: [cuda, desktop-gpu, cpu, webgpu, blender, python] year_introduced: 2020 outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Burley" url: "https://texelatlas.vercel.app/t/owen-scrambled-sobol-sampling/" sources_verified_at: "2026-11-29" --- # Owen-scrambled Sobol and low-discrepancy sampling (Burley) > Generate sample points from the Sobol sequence and randomise them per pixel with a cheap hash-based Owen scramble, so each pixel gets well-stratified, decorrelated samples at any sample count with no stored tables. ## Reach for it when - want faster convergence with few samples per pixel - sampling pattern shows structured artifacts across pixels - need a random sampler that works well on gpu without tables - noise in path tracer is clumpy at low sample counts ## How it works Low-discrepancy sequences such as Sobol fill the unit hypercube more evenly than random numbers, which cuts error in smooth integrands. Using the same sequence at every pixel produces visible structured artifacts, so each pixel needs its own randomisation that keeps the stratification. Owen scrambling does this by flipping bits of the binary digits in a nested way: whether a bit is flipped depends on all higher bits. That keeps the point set a valid net, so stratification survives. A hash-based version computes the nested flips with a few integer operations: reverse the bits, apply a hash-like mixing step that only lets higher bits influence lower ones, reverse again. No random permutation tables are needed. A renderer draws the Sobol index from the sample number and the dimension, applies a per-pixel and per-dimension seed to the scramble, and converts the 32-bit result to a float. Dimensions can be padded so that decorrelated dimensions do not alias. Because the construction is a pure function of (index, seed), it runs on GPUs and supports progressive rendering without state. ## When to use it Choose it as the default sampler for a path tracer, or for any renderer integrating smooth functions such as direct lighting and ambient occlusion with a few dozen samples per pixel. Prefer [blue-noise-screen-space-sampler](blue-noise-screen-space-sampler) at one to eight samples per pixel for real-time work, where distributing error as blue noise matters more than convergence rate. Prefer plain pseudo-random or PCG hashes when the integrand is discontinuous and QMC gives little benefit. Prefer [poisson-disk-sampling](poisson-disk-sampling) for placement of objects rather than integration samples. Used with [next-event-estimation](next-event-estimation) it improves light and BSDF sampling. ## Cost cheap — A few integer operations per generated dimension; no memory beyond Sobol direction numbers. Measured GPU Weight: 22.89× baseline (heavy) — 0.7096 ms median / 0.7297 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.65× baseline (heavy) — 0.3284 ms median (2.16× faster on L4). Ampere A100 scaling: 14.7× baseline (moderate) — 0.4234 ms median (1.68× faster on A100). ## Failure modes - Correlated dimensions: reusing the same scramble seed across dimensions gives visible patterns - Ordering of dimensions matters; assigning low dimensions to low-impact decisions wastes the best stratification - Convergence gain vanishes for high-dimensional paths because stratification degrades past a few dimensions - Sample counts that are not powers of two lose the net property and some stratification - Float conversion of 32-bit integers loses the lowest bits and can create bias if not done carefully - Progressive rendering must use consistent indexes across frames or scrambles restart and reintroduce noise ## Engine support - blender: builtin — `Render Properties > Sampling > Advanced > Pattern = Classic` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/sampling.html, checked 2026-12-01) — Cycles. - unity: builtin — `HDRP Ray Tracing and Path Tracing (_OwenScrambledTexture Owen-scrambled Sobol sequence in RaytracingSampling.hlsl)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingSampling.hlsl, checked 2026-12-01) — HDRP-only ray tracing and path tracing sampler. - unreal: builtin — `ImportanceSamplingLibrary / MaterialExpressionSobol (low-discrepancy Sobol sequence sampling)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/ImportanceSamplingLibrary, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: radiance - Platforms: cuda, desktop-gpu, cpu, webgpu, blender, python ## Presets ### Owen-Scrambled Sobol QMC — clumpy white-noise RNG (left) vs stratified Owen-Sobol sequence (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SAMPLES": 32, "P_SCRAMBLE_SEED": 3, "P_PLOT_RATIO": 0.44, "P_SPLIT": 0.5 } ``` ```glsl const float P_SAMPLES = 32.0; // P Sample Count [8.0, 64.0, 4.0] const float P_SCRAMBLE_SEED = 3.0; // P Owen Scramble [1.0, 12.0, 1.0] const float P_PLOT_RATIO = 0.44; // P Scatter Height [0.25, 0.65, 0.02] const float P_SPLIT = 0.50; // P White / Sobol Split [0.0, 1.0, 0.02] // 32-bit bit reversal + Laine-Karras hash for authentic Owen scrambling in WebGL2 & GL 3.30 uint bitRev32(uint x) { x = ((x & 0x55555555u) << 1u) | ((x & 0xAAAAAAAAu) >> 1u); x = ((x & 0x33333333u) << 2u) | ((x & 0xCCCCCCCCu) >> 2u); x = ((x & 0x0F0F0F0Fu) << 4u) | ((x & 0xF0F0F0F0u) >> 4u); x = ((x & 0x00FF00FFu) << 8u) | ((x & 0xFF00FF00u) >> 8u); return (x << 16u) | (x >> 16u); } uint lkHash(uint x, uint seed) { x += seed; x ^= x * 0x6c50b47cu; x ^= x * 0xb82f1e52u; x ^= x * 0xc7afe638u; x ^= x * 0x8d22f6e6u; return x; } uint owenScramble(uint x, uint seed) { return bitRev32(lkHash(bitRev32(x), seed)); } // 2D Sobol sequence (dim 0: van der Corput, dim 1: Sobol direction numbers via bit ops) vec2 owenSobol2D(uint idx, uint seed) { uint x = bitRev32(idx); uint y = 0u; uint n = idx; uint dir = 0x80000000u; for (int b = 0; b < 16; b++) { if ((n & 1u) != 0u) y ^= dir; n >>= 1u; dir ^= (dir >> 1u); } uint sx = owenScramble(x, seed * 0x9e3779b9u + 0x243f6a88u); uint sy = owenScramble(y, seed * 0x85ebca6bu + 0xb7e15162u); return vec2(float(sx >> 8u), float(sy >> 8u)) * (1.0 / 16777216.0); } vec2 whiteNoise2D(uint idx, uint seed) { uint h1 = lkHash(idx * 374761393u + seed * 668265263u, 0x1b873593u); uint h2 = lkHash(idx * 1274126177u + seed * 2246822519u, 0x85ebca77u); return vec2(float(h1 >> 8u), float(h2 >> 8u)) * (1.0 / 16777216.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv01 = fragCoord / max(iResolution.xy, vec2(1.0)); float split = clamp(P_SPLIT, 0.0, 1.0); float plotH = clamp(P_PLOT_RATIO, 0.22, 0.68); int nSamp = int(clamp(floor(P_SAMPLES + 0.5), 8.0, 64.0)); uint baseSeed = uint(clamp(floor(P_SCRAMBLE_SEED + 0.5), 1.0, 20.0)) + uint(floor(iTime * 0.6)); bool isSobol = uv01.x >= split; vec3 col = vec3(0.03, 0.045, 0.072); if (uv01.y > plotH) { // Top viewport: real-time Monte Carlo soft-shadow integration on a lit sphere & floor vec2 pUV = vec2((uv01.x - 0.5) * (iResolution.x / max(iResolution.y, 1.0)), (uv01.y - (plotH + 1.0) * 0.5) / max(1.0 - plotH, 0.15) * 0.62); vec3 ro = vec3(0.0, 0.42, 2.35); vec3 rd = normalize(vec3(pUV, -1.65)); // Analytic sphere (center (0, 0.12, 0), R = 0.44) + floor plane (y = -0.32) vec3 sphC = vec3(0.0, 0.12, 0.0); float sphR = 0.44; vec3 oc = ro - sphC; float b = dot(oc, rd); float c = dot(oc, oc) - sphR * sphR; float disc = b * b - c; float tSph = (disc > 0.0) ? (-b - sqrt(disc)) : 1e5; float tFlr = (rd.y < -0.001) ? ((-0.32 - ro.y) / rd.y) : 1e5; float tHit = min(tSph, tFlr); col = mix(vec3(0.05, 0.07, 0.11), vec3(0.14, 0.19, 0.28), smoothstep(-0.2, 0.45, pUV.y)); if (tHit < 12.0) { vec3 p = ro + rd * tHit; bool hitSph = (tSph < tFlr); vec3 n = hitSph ? normalize(p - sphC) : vec3(0.0, 1.0, 0.0); vec3 alb = hitSph ? vec3(0.84, 0.78, 0.70) : mix(vec3(0.24, 0.28, 0.36), vec3(0.38, 0.42, 0.50), mod(floor(p.x * 2.5) + floor(p.z * 2.5), 2.0)); // Per-pixel Owen seed so noise decorrelates cleanly into blue-like screen-space error uvec2 pix = uvec2(fragCoord); uint pixSeed = lkHash(pix.x + pix.y * 4099u, baseSeed); // Integrate 16-sample disk area light shadow using White Noise (left) vs Owen-Sobol (right) vec3 lCenter = vec3(0.75 * cos(iTime * 0.45), 1.65, 0.65); float lRad = 0.58; float litSum = 0.0; int mcN = min(nSamp, 16); for (int i = 0; i < 16; i++) { if (i >= mcN) break; vec2 u = isSobol ? owenSobol2D(uint(i), pixSeed) : whiteNoise2D(uint(i), pixSeed); float rD = sqrt(max(u.x, 0.0)) * lRad; float phi = u.y * 6.2831853; vec3 lPt = lCenter + vec3(cos(phi) * rD, 0.0, sin(phi) * rD); vec3 lDir = normalize(lPt - p); float ndl = max(dot(n, lDir), 0.0); // Check analytic shadow ray against sphere float vis = 1.0; if (!hitSph) { vec3 sOc = p + n * 0.002 - sphC; float sb = dot(sOc, lDir); float sc = dot(sOc, sOc) - sphR * sphR; if (sb < 0.0 && (sb * sb - sc) > 0.0) vis = 0.0; } litSum += ndl * vis; } float direct = litSum / float(mcN); col = alb * (0.18 + 1.35 * direct); } } else { // Bottom panel: 2D unit-square point distribution comparison (8x8 strata grid) float margin = 0.04; float panelX = isSobol ? ((uv01.x - split) / max(1.0 - split, 0.1)) : (uv01.x / max(split, 0.1)); float panelY = uv01.y / max(plotH, 0.1); vec2 boxUV = (vec2(panelX, panelY) - 0.5) * vec2(1.45, 1.20) + 0.5; col = vec3(0.025, 0.036, 0.058); if (boxUV.x >= 0.0 && boxUV.x <= 1.0 && boxUV.y >= 0.0 && boxUV.y <= 1.0) { col = vec3(0.042, 0.060, 0.095); // 4x4 elementary strata grid showing Owen-Sobol hits every stratum cleanly vec2 g = abs(fract(boxUV * 4.0 - 0.5) - 0.5); col += vec3(0.05, 0.08, 0.14) * smoothstep(0.03, 0.008, min(g.x, g.y)); float minD = 1e5; float secondD = 1e5; for (int i = 0; i < 64; i++) { if (i >= nSamp) break; vec2 pt = isSobol ? owenSobol2D(uint(i), baseSeed) : whiteNoise2D(uint(i), baseSeed); float d = length(boxUV - pt); if (d < minD) { secondD = minD; minD = d; } else if (d < secondD) { secondD = d; } } // Voronoi distance tint highlights empty voids & clumping in white noise vs uniform Sobol float voidWarn = smoothstep(0.11, 0.24, minD); if (!isSobol) col = mix(col, vec3(0.45, 0.12, 0.10), voidWarn * 0.55); else col = mix(col, vec3(0.06, 0.24, 0.30), (1.0 - voidWarn) * 0.35); float dotCore = smoothstep(0.026, 0.012, minD); vec3 dotCol = isSobol ? vec3(0.18, 0.94, 0.96) : vec3(1.0, 0.62, 0.24); col = mix(col, dotCol, dotCore); // Frame border float bdr = min(min(boxUV.x, 1.0 - boxUV.x), min(boxUV.y, 1.0 - boxUV.y)); col = mix(col, vec3(0.45, 0.62, 0.82), smoothstep(0.012, 0.003, bdr)); } } // Horizontal panel divider & vertical split line col = mix(col, vec3(0.42, 0.56, 0.74), smoothstep(0.005, 0.001, abs(uv01.y - plotH))); col = mix(col, vec3(0.95, 0.97, 1.0), smoothstep(0.0035, 0.0008, abs(uv01.x - split))); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Next-event estimation (direct light sampling)](https://texelatlas.vercel.app/t/next-event-estimation.md): The sampler supplies the 2D points that select a light and a point on it at every path vertex. - [Blue-noise error distribution sampler](https://texelatlas.vercel.app/t/blue-noise-screen-space-sampler.md): An Owen-scrambled Sobol point set can be re-ranked per pixel to land error in blue noise, trading convergence for screen-space quality. - [Multiple Importance Sampling](https://texelatlas.vercel.app/t/multiple-importance-sampling.md): Both strategies in an MIS estimator draw their points from the same scrambled sequence dimensions. ## Combination ideas - [Owen-scrambled Sobol hemisphere sampling for blotch-free irradiance caches](https://texelatlas.vercel.app/ideas/sobol-stratified-irradiance-cache/) ## Sources 1. [primary] Brent Burley Practical Hash-based Owen Scrambling. JCGT 2020. https://jcgt.org/published/0009/04/01 (verified via http on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Sobol Samplers. Physically Based Rendering 4th ed.. https://pbr-book.org/4ed/Sampling_and_Reconstruction/Sobol_Samplers (verified via http on 2026-11-29) 3. [implementation] mmp (2017) mmp/pbrt-v4. https://github.com/mmp/pbrt-v4 License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Owen-scrambled Sobol and low-discrepancy sampling." https://texelatlas.vercel.app/t/owen-scrambled-sobol-sampling/ (accessed 2026-12-01). --- id: "paint3d" title: "Paint3D" domain: "genai" stage: "generation" realtime: "offline" platforms: [cuda, python] year_introduced: 2023 inputs: [mesh, text-prompt, ldr-image] outputs: [texture, uv-atlas] style: "both" dynamic: "static" cost: "offline" authority: "Zeng et al., 2023" url: "https://texelatlas.vercel.app/t/paint3d/" sources_verified_at: "2026-11-29" --- # Paint3D (Zeng et al., 2023) > A coarse-to-fine texturing pipeline that produces albedo without baked lighting: depth-guided multi-view painting first, then UV-space inpainting and refinement. ## Reach for it when - generated textures have baked-in lighting and shadows - need relightable albedo for a mesh with uvs - multi-view painted textures show seams and holes - texture a mesh from a text prompt without shading ## How it works Stage one generates a coarse texture by painting several depth-conditioned views and projecting them to UV. Stage two works in UV space: an inpainting model (with UV position conditioning) fills the areas that were never seen, and a UVHD refinement model with a super-resolution-style step removes seams and sharpens. Importantly, the diffusion models are specialised to produce shading-free colour, so the texture can be relit in an engine. Paint3D accepts text or an image reference. Because the later stages operate on the UV atlas itself, they can fix errors that appear only after projection, such as stretched content near island borders, which purely image-space methods cannot see. ## When to use it Choose it when texture must be relightable and without baked shadows, starting from a mesh with UVs. Prefer [Text2Tex](https://texelatlas.vercel.app/t/text2tex.md) for the simpler progressive approach, [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md) for a faster synchronised-view alternative, and [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) to get metallic and roughness too. ## Cost offline — Several diffusion stages plus UV refinement, minutes per asset. ## Failure modes - Residual lighting cues still creep in for glossy or highly shaded prompts - UV-space inpainting can hallucinate content that disagrees across seams - Needs reasonable UVs; stretched islands degrade the UV refinement - Albedo only: no roughness or metallic output ## Dataflow - Inputs: mesh, text-prompt, ldr-image - Outputs: texture, uv-atlas - Platforms: cuda, python ## Sources 1. [primary] Xianfang Zeng, Xin Chen, Zhongqi Qi, Wen Liu, Zibo Zhao, Zhibin Wang, Bin Fu, Yong Liu, Gang Yu (2023) Paint3D: Paint Anything 3D with Lighting-Less Texture Diffusion Models. arXiv preprint (cs.CV). https://arxiv.org/abs/2312.13913 (verified via arxiv on 2026-11-29) 2. [primary] Xianfang Zeng, Xin Chen, Zhongqi Qi, Wen Liu, Zibo Zhao, Zhibin Wang, Bin Fu, Yong Liu, Gang Yu (2024) Paint3D: Paint Anything 3D With Lighting-Less Texture Diffusion Models. 2024 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/cvpr52733.2024.00407 (verified via crossref on 2026-11-29) 3. [implementation] OpenTexture (2023) OpenTexture/Paint3D. https://github.com/OpenTexture/Paint3D License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Paint3D." https://texelatlas.vercel.app/t/paint3d/ (accessed 2026-12-01). --- id: "painterly-animation-meier" title: "Painterly rendering for animation (Meier)" domain: "npr" stage: "material" realtime: "interactive" platforms: [cpu, desktop-gpu] year_introduced: 1996 inputs: [mesh, particles, ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Meier, 1996" url: "https://texelatlas.vercel.app/t/painterly-animation-meier/" sources_verified_at: "2026-11-29" --- # Painterly rendering for animation (Meier) (Meier, 1996) > Anchors brush-stroke particles to the 3D surface so strokes move with the object, avoiding the shower-door swimming of per-frame 2D painterly filters. ## Reach for it when - painterly filter swims over moving 3d objects - brush strokes should stick to the surface in animation - per-frame painting causes flicker - painted look with frame-to-frame coherence - shower-door effect in stylised animation ## How it works Particles are scattered over the 3D surfaces, in proportion to their projected area so density in screen space stays near-uniform. Each particle stores a position, colour taken from the lit surface, and stroke attributes. Every frame, the particles are projected, sorted by depth, and each is rendered as a textured, rotated and scaled brush-stroke sprite, with randomised jitter from a reference image. Because particles belong to the geometry, strokes remain consistent as objects and camera move. Stroke size, orientation, and density are controlled per-surface, and ordering along view depth makes paint layering look natural. ## When to use it Choose it for painterly 3D animation where frame-to-frame coherence is essential. Prefer [Painterly rendering with curved brush strokes](https://texelatlas.vercel.app/t/painterly-curved-brush-strokes.md) for rendering strokes from a single image with curved paths, and [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) for a cheap screen-space look at the cost of swimming. ## Cost medium — Scales with particle count; interactive on 1990s hardware, easily real-time on a GPU with instancing. Measured GPU Weight: 25.09× baseline (heavy) — 0.8253 ms median / 0.8329 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 22.16× baseline (heavy) — 0.3523 ms median (2.34× faster on L4). Ampere A100 scaling: 18.88× baseline (moderate) — 0.5437 ms median (1.52× faster on A100). ## Failure modes - Stroke popping when particle density changes with distance - Strokes of fixed size look wrong at large zoom - Needs a surface sampling strategy for non-manifold or thin geometry - Per-frame depth sorting of thousands of sprites costs overdraw ## Dataflow - Inputs: mesh, particles, ldr-image - Outputs: ldr-image - Platforms: cpu, desktop-gpu ## Presets ### Painterly Animation (Meier 1996) — 2D screen-space shower-door swimming (left) vs 3D surface-anchored brush particles (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_STROKE_DENS": 9, "P_BRUSH_LEN": 0.75, "P_ROT_SPEED": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_STROKE_DENS = 9.00; // P Brush Particle Density [5.0, 15.0, 1.0] const float P_BRUSH_LEN = 0.75; // P Stroke Length [0.3, 1.4, 0.05] const float P_ROT_SPEED = 0.55; // P Object Rotation [0.0, 1.6, 0.05] const float P_SPLIT = 0.48; // P 2D Swim / 3D Anchored [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Rotating 3D sculptural still-life (ceramic amphora-torus + flanking fruit spheres) vec2 mapStillLife(vec3 p, float t) { vec3 rp = p; rp.xz = rot2(rp.xz, t * 0.75); float d1 = length(rp - vec3(-0.24, 0.02, 0.08)) - 0.34; float d2 = length(rp - vec3(0.32, -0.10, -0.06)) - 0.25; vec2 tq = vec2(length(rp.xz - vec2(0.06, -0.02)) - 0.26, rp.y - 0.20); float d3 = length(tq) - 0.11; vec2 res = vec2(d1, 1.0); if (d2 < res.x) res = vec2(d2, 2.0); if (d3 < res.x) res = vec2(d3, 3.0); return res; } vec3 calcNormal(vec3 p, float t) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapStillLife(p + e.xyy, t).x - mapStillLife(p - e.xyy, t).x, mapStillLife(p + e.yxy, t).x - mapStillLife(p - e.yxy, t).x, mapStillLife(p + e.yyx, t).x - mapStillLife(p - e.yyx, t).x )); } // Evaluate a single painterly oil-brush dab lattice in coordinate space q (2D screen vs 3D surface UV!) vec3 evalBrushField(vec2 q, vec3 baseLit, float dens, float strokeLen) { vec2 g = q * dens; vec2 cell = floor(g); vec2 f = fract(g); vec3 bestCol = baseLit; float bestD = 9.0; float bristle = 0.0; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 nb = cell + vec2(float(i), float(j)); vec2 jit = vec2(hash21(nb + 1.3), hash21(nb + 19.7)); float ang = (hash21(nb + 41.1) - 0.5) * 1.15 + 0.45; vec2 d = (nb + jit) - g; vec2 dl = rot2(d, ang); // Elongated bristle stroke footprint vec2 scaled = dl * vec2(1.0 / max(strokeLen, 0.25), 2.3); float dist = length(scaled); if (dist < bestD) { bestD = dist; float hueShift = (hash21(nb + 73.9) - 0.5) * 0.22; float valShift = (hash21(nb + 97.1) - 0.5) * 0.16; vec3 dabCol = baseLit * (1.0 + valShift) + vec3(hueShift, -hueShift * 0.4, hueShift * 0.6) * 0.35; bristle = 0.85 + 0.22 * sin(dl.y * 28.0 + hash21(nb + 11.7) * 6.28); bestCol = dabCol * bristle; } } } float dabEdge = smoothstep(0.68, 0.46, bestD); return mix(baseLit * 0.78, bestCol, dabEdge); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float dens = clamp(P_STROKE_DENS, 4.0, 16.0); float bLen = clamp(P_BRUSH_LEN, 0.25, 1.6); float t = iTime * max(P_ROT_SPEED, 0.0); // Warm Impressionist painted canvas backdrop vec3 bgBase = mix(vec3(0.24, 0.34, 0.46), vec3(0.76, 0.68, 0.52), smoothstep(-0.45, 0.50, uv.y)); vec3 col = evalBrushField(uv, bgBase, dens * 0.9, bLen); vec3 ro = vec3(0.0, 0.20, 2.08); vec3 rd = normalize(vec3(uv.x, uv.y - 0.04, -1.48)); vec3 lDir = normalize(vec3(0.62, 0.74, 0.52)); float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapStillLife(ro + rd * dist, t); if (h.x < 0.002) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 6.5) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p, t); float ndl = max(dot(n, lDir), 0.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = (hit.y < 1.5) ? vec3(0.92, 0.42, 0.22) : ((hit.y < 2.5) ? vec3(0.22, 0.64, 0.54) : vec3(0.95, 0.78, 0.26)); vec3 lit = alb * (vec3(0.24, 0.28, 0.42) + vec3(1.18, 1.08, 0.92) * ndl) + vec3(0.96, 0.88, 0.66) * rim * 0.45; if (screenX < split) { // Left: Naive 2D screen-space painterly strokes -> static "shower-door" glass swimming over moving 3D form! col = evalBrushField(uv * 1.15, lit, dens * 1.45, bLen); } else { // Right: Meier 1996 3D object-space surface-anchored brush particles -> strokes ride coherently with 3D rotation! vec3 pObj = p; pObj.xz = rot2(pObj.xz, t * 0.75); // Spherical/cylindrical triplanar surface parameterization rigidly locked to the rotating 3D geometry vec2 surfUv = vec2(atan(pObj.z, pObj.x) * 0.42, pObj.y * 1.15 + 0.15 * sin(pObj.x * 3.0)); col = evalBrushField(surfUv, lit, dens * 1.35, bLen); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.96, 0.95, 0.90), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Stroke-based rendering](https://texelatlas.vercel.app/t/stroke-based-rendering.md) ## Combines with - [Gaussian splats drawn as brush marks](https://texelatlas.vercel.app/t/sillage-brush-splatting.md): Same principle: strokes attached to a 3D representation; here they are Gaussian splats. ## Combination ideas - [Brush strokes that flock](https://texelatlas.vercel.app/ideas/flocking-brush-strokes/) - [Splats as world-anchored brush strokes](https://texelatlas.vercel.app/ideas/splats-as-brush-strokes/) ## Sources 1. [primary] Barbara J. Meier (1996) Painterly rendering for animation. Proceedings of the 23rd annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/237170.237288 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Painterly rendering for animation (Meier)." https://texelatlas.vercel.app/t/painterly-animation-meier/ (accessed 2026-12-01). --- id: "painterly-curved-brush-strokes" title: "Painterly rendering with curved brush strokes" domain: "npr" stage: "post" realtime: "offline" platforms: [cpu, python] year_introduced: 1998 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "static" cost: "offline" authority: "Hertzmann, 1998" url: "https://texelatlas.vercel.app/t/painterly-curved-brush-strokes/" sources_verified_at: "2026-11-29" --- # Painterly rendering with curved brush strokes (Hertzmann, 1998) > Paints an image by laying down curved strokes in layers, from large brushes to small, with strokes placed where the canvas differs from a blurred reference and following image gradients. ## Reach for it when - turn a photo into a brush stroke painting - stylized image with visible curved paint strokes - want a hand painted look with detail where needed - automatic impressionist rendering of pictures ## How it works Start from a source photograph. For each brush radius (largest to smallest), blur the reference by that radius and compare it to the current canvas. In grid cells where the difference is large, place a stroke starting at the worst-error point and trace a curve perpendicular to the gradient of the blurred reference, stopping when colour deviates, when the stroke reaches maximum length or when it hits low curvature. Strokes are drawn as thick splines with the colour sampled at their seed. Painting from coarse to fine means broad areas get big brush strokes and only high-detail regions get small ones. Parameters (threshold, curvature filter, jitter) define styles such as impressionist or pointillist. ## When to use it Choose it when you want an individual stroke-by-stroke painted look from a rendered still with a clear stroke structure. Prefer [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) for an automatic real-time filter, and [Painterly rendering for animation (Meier)](https://texelatlas.vercel.app/t/painterly-animation-meier.md) when frame coherence for animation matters. ## Cost offline — Many layered passes on CPU; seconds per image in the original implementation. Measured GPU Weight: 253.67× baseline (extreme) — 8.3459 ms median / 8.4575 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 204.6× baseline (extreme) — 3.2532 ms median (2.57× faster on L4). Ampere A100 scaling: 176.19× baseline (extreme) — 5.0744 ms median (1.64× faster on A100). ## Failure modes - No temporal coherence: strokes re-seed each frame, so animation flickers - Stroke placement depends on the arbitrary grid and error threshold - Gradient directions are noisy on textured regions - Long strokes can wander across edges when the gradient is weak ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: cpu, python ## Presets ### Painterly Curved Brush Strokes (Hertzmann 1998) — smooth reference render (left) vs coarse-to-fine gradient-curved impasto strokes (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BRUSH_SCALE": 1, "P_CURVATURE": 0.75, "P_IMPASTO": 0.65, "P_SPLIT": 0.42 } ``` ```glsl const float P_BRUSH_SCALE = 1.00; // P Brush Size [0.5, 1.8, 0.05] const float P_CURVATURE = 0.75; // P Flow Curvature [0.1, 1.2, 0.05] const float P_IMPASTO = 0.65; // P Bristle Impasto [0.0, 1.2, 0.05] const float P_SPLIT = 0.42; // P Reference / Painted [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Vibrant sunlit coastal landscape & glowing moon/sun sphere (ideal source photo for Hertzmann curved strokes) vec3 evalReference(vec2 uv, float t) { // Swirled sunset sky gradient vec3 skyTop = vec3(0.10, 0.22, 0.48); vec3 skyMid = vec3(0.86, 0.44, 0.24); vec3 skyLow = vec3(0.98, 0.80, 0.36); vec3 col = mix(skyLow, skyMid, smoothstep(-0.08, 0.24, uv.y)); col = mix(col, skyTop, smoothstep(0.18, 0.55, uv.y)); // Glowing sun orb vec2 sunPos = vec2(0.18 + 0.08 * sin(t * 0.4), 0.22); float dSun = length(uv - sunPos); col = mix(col, vec3(1.15, 0.96, 0.62), smoothstep(0.14, 0.09, dSun)); col += vec3(0.95, 0.65, 0.25) * exp(-dSun * 6.5) * 0.45; // Rolling cypress hills float hill1 = -0.02 + 0.10 * sin(uv.x * 3.8 + 0.6) + 0.04 * cos(uv.x * 8.5); if (uv.y < hill1) { col = mix(vec3(0.14, 0.34, 0.28), vec3(0.28, 0.56, 0.34), smoothstep(-0.22, hill1, uv.y)); } // Shimmering cobalt water foreground float waterLine = -0.14 + 0.02 * sin(uv.x * 6.0); if (uv.y < waterLine) { float wave = 0.5 + 0.5 * sin(uv.y * 55.0 + uv.x * 8.0 + t * 1.4); float sunRefl = exp(-abs(uv.x - sunPos.x) * 7.5) * (0.4 + 0.6 * wave); col = mix(vec3(0.08, 0.20, 0.42), vec3(0.18, 0.44, 0.66), wave * 0.6) + vec3(0.98, 0.76, 0.32) * sunRefl * 0.78; } // Foreground sunlit terracotta archway / sphere silhouette on left-center vec2 sp = uv - vec2(-0.14, -0.06); float r = length(sp); if (r < 0.20) { float nz = sqrt(max(0.20 * 0.20 - r * r, 0.0)); vec3 n = normalize(vec3(sp, nz)); vec3 l = normalize(vec3(0.65, 0.55, 0.52)); col = vec3(0.88, 0.34, 0.22) * (0.28 + 0.92 * max(dot(n, l), 0.0)) + vec3(0.25, 0.42, 0.64) * max(-n.x, 0.0) * 0.35; } return col; } float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } // Compute unit tangent perpendicular to luminance gradient (Hertzmann stroke spline direction!) vec2 gradTangent(vec2 p, float eps, float t) { float gx = luma(evalReference(p + vec2(eps, 0.0), t)) - luma(evalReference(p - vec2(eps, 0.0), t)); float gy = luma(evalReference(p + vec2(0.0, eps), t)) - luma(evalReference(p - vec2(0.0, eps), t)); vec2 g = vec2(gx, gy); float len = length(g); if (len < 1e-4) return normalize(vec2(1.0, 0.25 * sin(p.x * 5.0))); return vec2(-g.y, g.x) / len; } // Paint one coarse-to-fine layer of curved spline strokes that follow iso-luminance flow lines vec4 paintLayer(vec2 uv, float gridN, float bRadius, float curv, float impasto, float t, float layerSeed) { vec2 g = uv * gridN; vec2 cell = floor(g); vec4 outPaint = vec4(0.0); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 nb = cell + vec2(float(i), float(j)); vec2 p0 = (nb + 0.15 + 0.70 * vec2(hash21(nb + layerSeed), hash21(nb + layerSeed + 23.7))) / gridN; vec3 strokeCol = evalReference(p0, t); // Trace 3-segment curved brush spine along perpendicular luminance gradient! vec2 tang0 = gradTangent(p0, bRadius * 0.65, t); float stepL = bRadius * 1.45 * curv; vec2 p1 = p0 + tang0 * stepL; vec2 tang1 = gradTangent(p1, bRadius * 0.65, t); vec2 p2 = p1 + tang1 * stepL; vec2 pm = p0 - tang0 * stepL; // Minimum distance from uv to the 3 curved polyline segments float minD = 9.0; float alongT = 0.0; float crossS = 0.0; vec2 segA[3]; vec2 segB[3]; segA[0] = pm; segB[0] = p0; segA[1] = p0; segB[1] = p1; segA[2] = p1; segB[2] = p2; for (int s = 0; s < 3; s++) { vec2 ab = segB[s] - segA[s]; float ab2 = max(dot(ab, ab), 1e-6); float proj = clamp(dot(uv - segA[s], ab) / ab2, 0.0, 1.0); vec2 closest = segA[s] + ab * proj; float dd = length(uv - closest); if (dd < minD) { minD = dd; vec2 dir = ab / sqrt(ab2); crossS = dot(uv - closest, vec2(-dir.y, dir.x)) / max(bRadius, 1e-4); alongT = (float(s) + proj) / 3.0; } } // Tapered brush stroke width + bristle texture + impasto rim lighting float width = bRadius * (0.72 + 0.35 * sin(alongT * 3.14159)); float mask = smoothstep(width, width * 0.58, minD); if (mask > outPaint.a) { float bristle = 0.90 + 0.16 * sin(crossS * 18.0 + hash21(nb + 7.1) * 6.28); float relief = 1.0 + impasto * (crossS * 0.22 - abs(crossS) * 0.12); vec3 colJit = strokeCol * bristle * relief; outPaint = vec4(colJit, mask); } } } return outPaint; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float bScale = clamp(P_BRUSH_SCALE, 0.45, 2.0); float curv = clamp(P_CURVATURE, 0.1, 1.4); float impasto = clamp(P_IMPASTO, 0.0, 1.3); vec3 refCol = evalReference(uv, iTime); vec3 col = refCol; if (screenX >= split) { // Right: Hertzmann 3-layer coarse-to-fine curved brush strokes (large -> medium -> fine error-refinement) vec3 canvas = vec3(0.92, 0.89, 0.82) * 0.45 + refCol * 0.55; vec4 L1 = paintLayer(uv, 9.0 / bScale, 0.048 * bScale, curv, impasto, iTime, 11.3); canvas = mix(canvas, L1.rgb, L1.a); // Medium layer paints over regions where canvas differs from reference vec4 L2 = paintLayer(uv, 16.0 / bScale, 0.026 * bScale, curv, impasto, iTime, 37.9); float err2 = smoothstep(0.04, 0.22, length(canvas - refCol)); canvas = mix(canvas, L2.rgb, L2.a * (0.45 + 0.55 * err2)); // Fine detail brush layer only along high-error silhouettes & highlights vec4 L3 = paintLayer(uv, 27.0 / bScale, 0.015 * bScale, curv, impasto, iTime, 71.1); float err3 = smoothstep(0.06, 0.25, length(canvas - refCol)); canvas = mix(canvas, L3.rgb, L3.a * (0.35 + 0.65 * err3)); col = canvas; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.96, 0.95, 0.90), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Stroke-based rendering](https://texelatlas.vercel.app/t/stroke-based-rendering.md) ## Sources 1. [primary] Aaron Hertzmann (1998) Painterly rendering with curved brush strokes of multiple sizes. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280951 (verified via crossref on 2026-11-29) 2. [primary] A. Hertzmann (2003) A survey of stroke-based rendering. IEEE Computer Graphics and Applications. https://doi.org/10.1109/mcg.2003.1210867 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Painterly rendering with curved brush strokes." https://texelatlas.vercel.app/t/painterly-curved-brush-strokes/ (accessed 2026-12-01). --- id: "parallax-occlusion-mapping" title: "Parallax occlusion mapping" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2006 inputs: [texture, normals, uv-atlas] outputs: [texture, normals] style: "both" dynamic: "both" cost: "medium" authority: "Tatarchuk, 2006" url: "https://texelatlas.vercel.app/t/parallax-occlusion-mapping/" sources_verified_at: "2026-11-29" --- # Parallax occlusion mapping (Tatarchuk, 2006) > Per-pixel ray march through a height map in tangent space to shift texture coordinates and produce parallax and self-occlusion on flat polygons. Cheaper than real displacement, convincing on bricks and cobblestones. ## Reach for it when - flat bricks or cobblestones look like a painted wall - normal maps lack depth and parallax - want self-occlusion on surfaces without extra geometry - floors need depth shift when camera moves ## How it works Tatarchuk's method casts the view ray into the tangent-space heightfield beneath the polygon. Starting at the entry point it steps along the ray in a fixed or adaptive number of linear samples (more at grazing angles), comparing the ray height to the sampled height. At the first crossing it linearly interpolates between the last two samples to refine the intersection, then uses the resulting UV for all subsequent texture lookups (albedo, normal, roughness). Optionally a second march toward the light yields soft self-shadowing. LOD blends the effect off with distance, reducing sample counts and eventually falling back to plain normal mapping. It is a purely fragment-shader technique. ## When to use it Choose it for floors, walls and rocky ground where parallax and self-occlusion add credibility from a modest viewing range. Prefer [Relief mapping](https://texelatlas.vercel.app/t/relief-mapping.md) or [Relaxed cone step mapping](https://texelatlas.vercel.app/t/relaxed-cone-step-mapping.md) for more accurate, artifact-free intersections or steeper heights. Prefer real tessellation or [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) when silhouettes must be displaced. Prefer [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) when height is subtle. ## Cost medium — Several height-map fetches per pixel (often 8-32); scales with sample count and screen coverage. Measured GPU Weight: 3.55× baseline (light) — 0.1168 ms median / 0.1233 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.67× baseline (light) — 0.0425 ms median (2.75× faster on L4). Ampere A100 scaling: 2.24× baseline (light) — 0.0644 ms median (1.81× faster on A100). ## Failure modes - Stair-stepping and swimming at grazing angles when the sample count is too low - Silhouettes and polygon edges stay flat, so the illusion breaks at object borders - Texture distortion and layered sampling artefacts on steep height with few samples - Does not interact with depth buffer unless depth is written, so intersections with other geometry look wrong ## Engine support - babylonjs: builtin — `material.useParallax = true; material.useParallaxOcclusion = true` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBaseMaterial.pure.ts, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.heightmap_enabled = true (heightmap_deep_parallax for deep parallax)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: official — `examples/webgpu_parallax_uv.html` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/webgpu_parallax_uv.html, checked 2026-12-01) — Official TSL example; not a material option. - unity: builtin — `HDRP Lit > Surface Inputs > Height Map > Displacement Mode = Pixel; Shader Graph POM node` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Parallax-Occlusion-Mapping-Node.md, checked 2026-12-01) — Shader Graph POM node and HDRP Lit pixel displacement; URP Lit has simple parallax. - unreal: builtin — `Material Parallax Occlusion Mapping expression (ParallaxOcclusionMapping)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/contact-shadows-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: texture, normals, uv-atlas - Outputs: texture, normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Brick heightfield: flat lookup (left) vs parallax occlusion mapping (right) (glsl-fragment; rendered 2026-11-29) ```json { "DEPTH": 0.16, "LAYERS": 24 } ``` ```glsl // Parallax occlusion mapping on a brick heightfield seen at grazing angle. // Left: flat texture lookup (no parallax). Right: layered height-field ray march in uv space, with linear // interpolation between the last two layers. const float DEPTH = 0.16; const int LAYERS = 24; float hgt(vec2 uv) { float row = floor(uv.y / 0.5); vec2 c = vec2(fract((uv.x + 0.5 * mod(row, 2.0)) / 1.0), fract(uv.y / 0.5)); float e = min(min(c.x, 1.0 - c.x), min(c.y, 1.0 - c.y) * 0.5); return smoothstep(0.02, 0.07, e); } vec3 brick(vec2 uv) { float row = floor(uv.y / 0.5); float id = floor(uv.x + 0.5 * mod(row, 2.0)); float r = fract(sin(dot(vec2(id, row), vec2(12.9898, 78.233))) * 43758.5453); return mix(vec3(0.5, 0.18, 0.12), vec3(0.7, 0.35, 0.2), r); } vec3 shadeAt(vec2 uv, float t) { float e = 0.01; float h = hgt(uv); vec3 n = normalize(vec3(-(hgt(uv + vec2(e, 0.0)) - h) / e * 0.12, 1.0, -(hgt(uv + vec2(0.0, e)) - h) / e * 0.12)); vec3 alb = mix(vec3(0.35), brick(uv), h); vec3 c = alb * (0.2 + 0.9 * max(dot(n, normalize(vec3(0.4, 0.8, 0.4))), 0.0)) * mix(0.45, 1.0, h); return mix(vec3(0.7, 0.78, 0.88), c, exp(-t * 0.03)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 1.0, 0.0), rd = normalize(vec3(uv.x, uv.y - 0.32, -1.0)); vec3 col = mix(vec3(0.7, 0.78, 0.88), vec3(0.35, 0.55, 0.85), clamp(rd.y * 3.0, 0.0, 1.0)); if (rd.y < -0.001) { float t = -ro.y / rd.y; vec2 p0 = (ro + rd * t).xz * 0.9; if (fragCoord.x < 0.5 * iResolution.x) col = shadeAt(p0, t); else { vec2 dxz = rd.xz / (-rd.y) * DEPTH * 0.9; float dPrev = 0.0, hPrev = 1.0 - hgt(p0), dCur = 0.0; vec2 uvh = p0; for (int i = 1; i <= LAYERS; i++) { float d = float(i) / float(LAYERS); vec2 q = p0 + dxz * d; float sd = 1.0 - hgt(q); if (d >= sd) { float a0 = d - sd, a1 = hPrev - dPrev; float w = a0 / max(a0 - (dPrev - hPrev) , 1e-4); float dd = mix(d, dPrev, clamp(w, 0.0, 1.0)); uvh = p0 + dxz * dd; break; } dPrev = d; hPrev = sd; uvh = q; } col = shadeAt(uvh, t); } } if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Relief mapping](https://texelatlas.vercel.app/t/relief-mapping.md) - extended by [Ray-Traced Prism Displacement Mapping](https://texelatlas.vercel.app/t/ray-traced-prism-displacement-mapping.md) ## Sources 1. [primary] Natalya Tatarchuk (2006) Dynamic parallax occlusion mapping with approximate soft shadows. Proceedings of the 2006 symposium on Interactive 3D graphics and games - SI3D '06. https://doi.org/10.1145/1111411.1111423 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Parallax occlusion mapping." https://texelatlas.vercel.app/t/parallax-occlusion-mapping/ (accessed 2026-12-01). --- id: "particle-systems" title: "Particle systems" aliases: [particle effects, sprite particles, fuzzy objects] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, mobile-gpu, unity, unreal, godot, blender, houdini] year_introduced: 1983 inputs: [particles] outputs: [particles] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Reeves, 1983" url: "https://texelatlas.vercel.app/t/particle-systems/" sources_verified_at: "2026-11-29" --- # Particle systems (Reeves, 1983) > Model fire, smoke, sparks and rain as many small independent points that are emitted, aged, moved by forces and rendered as sprites, instead of as one surface. ## Reach for it when - need sparks, embers or dust drifting around a scene - fire and smoke effect looks like one flat solid object - want thousands of small fading glow points cheaply - effects need emitter with random lifetime, size and colour over age ## How it works A particle system is an emitter plus a population. Each frame the emitter spawns new particles with randomised position, velocity, lifetime, size and colour drawn from distributions. Every live particle then advances: velocity is updated from forces such as gravity, drag and wind, position is integrated (usually explicit or semi-implicit Euler), and age increases. Properties like size, opacity and colour are read from curves over normalised age, so a spark can start white and hot and end as a dim ember. Particles older than their lifetime are recycled. Rendering turns each particle into a camera-facing quad or a ribbon, blended additively for glows or alpha-blended for smoke, and sorted back to front when order matters. The original formulation also allowed child systems and stochastic variation of every parameter, which is why the same machinery still drives most game VFX graphs. ## When to use it Choose it for fuzzy, volumeless phenomena: sparks, embers, dust, rain, magic trails, muzzle flash. A plain CPU or single-pass system is fine up to a few thousand particles. Prefer [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md) once you need hundreds of thousands to millions, depth collisions or simulation in a compute pass. Prefer [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) or [Position Based Fluids](https://texelatlas.vercel.app/t/position-based-fluids.md) when particles must interact and behave like a liquid. Prefer [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) for dense smoke that needs self-shadowing, and [Boids flocking](https://texelatlas.vercel.app/t/boids.md) when agents steer from neighbours. Pair with [Soft particles (depth-fade billboards)](https://texelatlas.vercel.app/t/soft-particles.md) to hide intersection seams and [Curl noise for procedural fluid motion](https://texelatlas.vercel.app/t/curl-noise-flow.md) for swirling motion. ## Cost cheap — Scales linearly with particle count; overdraw of large translucent sprites is usually the real cost, not the update. Measured GPU Weight: 82.53× baseline (extreme) — 2.7152 ms median / 2.8005 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 58.17× baseline (heavy) — 0.9249 ms median (2.94× faster on L4). Ampere A100 scaling: 53.69× baseline (heavy) — 1.5462 ms median (1.76× faster on A100). ## Failure modes - Large alpha-blended sprites cause heavy overdraw and fill-rate spikes on mobile - Hard intersection lines where a quad cuts through scene geometry (see soft-particles) - Visible popping when sort order or lifetime curves change abruptly between frames - Variable frame time changes the emission pattern unless spawn counts are accumulated with a fractional remainder - Flat, card-like look in smoke because sprites carry no volumetric lighting ## Engine support - babylonjs: builtin — `new BABYLON.ParticleSystem(name, capacity, scene)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Particles/particleSystem.pure.ts, checked 2026-12-01) - blender: builtin — `Properties > Particles tab (Particle System modifier)` (evidence: https://docs.blender.org/manual/en/5.2/physics/particles/introduction.html, checked 2026-12-01) — CPU particle system. - godot: builtin — `GPUParticles3D or CPUParticles3D node` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/GPUParticles3D.xml, checked 2026-12-01) - threejs: plugin — `npm i three.quarks` (evidence: https://github.com/Alchemist0823/three.quarks, checked 2026-12-01) - unity: builtin — `Add a ParticleSystem (Shuriken) component` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ParticleSystem.html, checked 2026-12-01) - unreal: builtin — `Niagara System and Emitter assets (Content Browser > Add > FX > Niagara System)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-niagara-effects-for-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: particles - Outputs: particles - Platforms: webgl2, webgpu, desktop-gpu, cpu, mobile-gpu, unity, unreal, godot, blender, houdini ## Presets ### Stateless ballistic fountain (140 particles) (glsl-fragment; rendered 2026-11-29) ```json { "count": 140, "life": 2, "speed": 1.2, "spread": 0.55, "gravity": [ 0, -1.6 ] } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Stateless fountain: every particle is a closed-form ballistic arc of age. const int COUNT = 140; const float LIFE = 2.0; const float SPEED = 1.2; const float SPREAD = 0.55; const vec2 GRAVITY = vec2(0.0, -1.6); float hash11(float n) { return fract(sin(n * 127.1) * 43758.5453); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 col = mix(vec3(0.02, 0.03, 0.07), vec3(0.08, 0.05, 0.12), uv.y + 0.5); for (int i = 0; i < COUNT; i++) { float fi = float(i); float age = fract((iTime + hash11(fi + 1.0) * LIFE) / LIFE); // 0 at birth, 1 at death float t = age * LIFE; float ang = (hash11(fi * 3.7 + 2.0) - 0.5) * 2.0 * SPREAD; float sp = SPEED * (0.7 + 0.5 * hash11(fi * 5.3 + 4.0)); vec2 p = vec2(0.0, -0.4) + vec2(sin(ang), cos(ang)) * sp * t + 0.5 * GRAVITY * t * t; float r = 0.014 * (1.0 - 0.6 * age); float a = smoothstep(r * 2.0, 0.0, length(uv - p)) * (1.0 - age); col += mix(vec3(1.0, 0.85, 0.35), vec3(1.0, 0.2, 0.05), age) * a * 1.3; } fragColor = vec4(pow(col, vec3(0.4545)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md) ## Combines with - [Curl noise for procedural fluid motion](https://texelatlas.vercel.app/t/curl-noise-flow.md): Curl noise supplies a divergence-free velocity field that particle updates sample each step for swirling smoke and dust. - [Soft particles (depth-fade billboards)](https://texelatlas.vercel.app/t/soft-particles.md): Particle quads are rendered with a depth fade against the scene depth so they stop cutting hard lines through geometry. ## Sources 1. [primary] William T. Reeves (1983) Particle systems—a technique for modeling a class of fuzzy objects. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/964967.801167 (verified via crossref on 2026-11-29) 2. [tutorial] Unity Technologies Unity Visual Effect Graph documentation. docs.unity3d.com. https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@latest (verified via http on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Particle systems." https://texelatlas.vercel.app/t/particle-systems/ (accessed 2026-12-01). --- id: "path-guiding" title: "Practical Path Guiding" aliases: [guided path tracing, SD-tree guiding] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda] year_introduced: 2017 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "static" cost: "offline" authority: "Müller et al., 2017" url: "https://texelatlas.vercel.app/t/path-guiding/" sources_verified_at: "2026-11-29" --- # Practical Path Guiding (Müller et al., 2017) > Learns a spatially varying directional distribution of incident radiance during rendering, then uses it to sample bounce directions, cutting noise in scenes with hard indirect light. ## Reach for it when - indirect light through narrow openings stays noisy - path tracer wastes samples in the wrong directions - lamp shades and layered materials render grainy - need smarter bounce directions learned while rendering - caustic-like paths converge too slowly ## How it works Standard BSDF sampling ignores where the light actually comes from. Path guiding builds an approximation of the incident radiance field `L(x, w)` and samples new directions from a distribution proportional to it times the BSDF cosine, ideally minimizing variance. The practical version stores that field in a **spatial binary tree** whose leaves each hold a **directional quadtree** on an equal-area sphere mapping. Every path vertex contributes (via its estimated radiance, weighted by throughput) to the leaf containing it. Trees refine: spatial nodes split when they accumulate enough samples, directional nodes split when they hold too much energy. Rendering proceeds in **iterations** of doubling sample counts. Iteration `k` samples from the distribution learned in iteration `k-1`, and its own samples train the next one, with earlier iterations' results combined by inverse variance for the final image. The learned distribution is combined with BSDF sampling by one-sample MIS, which protects against bad guides and keeps the estimator unbiased. ## When to use it Choose it for offline scenes where indirect light arrives through narrow openings, lamp shades or complex layered materials and standard path tracing remains noisy. Prefer [path-tracing](path-tracing) with [multiple-importance-sampling](multiple-importance-sampling) for simple scenes, since learning costs memory and time. Prefer [metropolis-light-transport](metropolis-light-transport) for the most constrained paths where adaptive proposals still fail. Prefer [neural-radiance-caching](neural-radiance-caching) for real-time budgets, since guiding still needs many samples per pixel. ## Cost offline — Tree training adds modest per-sample overhead; the benefit is lower variance per sample and faster convergence on hard scenes. Measured GPU Weight: 3.3× baseline (light) — 0.1086 ms median / 0.1108 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.56× baseline (light) — 0.0407 ms median (2.67× faster on L4). Ampere A100 scaling: 1.99× baseline (feather) — 0.0572 ms median (1.9× faster on A100). ## Failure modes - Poor training early on: the first iterations can be worse than unguided sampling - Spatial subdivision cannot represent thin or high-frequency geometry, so guiding is blurry in complex areas - Pure diffuse scenes see little or no gain while paying the learning overhead - Fireflies from a sharply peaked learned distribution if the BSDF fallback fraction is too small ## Engine support - blender: builtin — `Properties > Render > Sampling > Path Guiding` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/sampling.html, checked 2026-12-01) — CPU only. ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda ## Presets ### Practical Path Guiding — cosine hemisphere noise (left) vs SD-tree directional guiding lobes (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GUIDE_SHARP": 0.85, "P_LOBE_VIS": 0.85, "P_LIGHT_ORBIT": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_GUIDE_SHARP = 0.85; // P Guiding Focus [0.1, 1.0, 0.02] const float P_LOBE_VIS = 0.85; // P SD-Tree Lobes [0.0, 1.5, 0.05] const float P_LIGHT_ORBIT = 0.65; // P Caustic Sweep [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Unguided / Guided [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isGuided = screenX >= split; float sharp = clamp(P_GUIDE_SHARP, 0.05, 1.0); float lobeVis = clamp(P_LOBE_VIS, 0.0, 1.6); float spin = iTime * max(P_LIGHT_ORBIT, 0.0); // Perspective glossy-diffuse floor & central reflective torus illuminated by a tiny bright ceiling skylight! vec3 ro = vec3(0.0, 0.65, 2.25); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.14), -1.42)); vec3 bg = mix(vec3(0.018, 0.024, 0.042), vec3(0.055, 0.072, 0.118), smoothstep(-0.5, 0.5, uv.y)); vec3 col = bg; // Moving small high-radiance skylight / indirect mirror patch (primary target of directional guiding!) vec3 lightPos = vec3(0.75 * cos(spin * 0.55), 1.35, 0.45 * sin(spin * 0.55) - 0.25); // Intersect hero sphere (R=0.46 at y=0.04) and floor plane (y=-0.42) vec3 sc = vec3(0.0, 0.04, 0.0); vec3 oc = ro - sc; float b = dot(oc, rd); float c = dot(oc, oc) - 0.46 * 0.46; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tFl = (rd.y < -0.01) ? ((-0.42 - ro.y) / rd.y) : 1e5; if (tFl < 0.05 || tFl > 12.0) tFl = 1e5; float tHit = min(tSph, tFl); if (tHit < 1e4) { vec3 p = ro + rd * tHit; vec3 n = (tSph < tFl) ? normalize(p - sc) : vec3(0.0, 1.0, 0.0); vec3 toL = lightPos - p; float distL = length(toL); vec3 lDir = toL / max(distL, 1e-4); // Soft sphere shadow on floor vec3 toSc = sc - p; float proj = dot(toSc, lDir); float perp = length(toSc - lDir * max(proj, 0.0)); float shadow = (tFl < tSph && proj > 0.0) ? smoothstep(0.38, 0.52, perp) : 1.0; float diff = max(dot(n, lDir), 0.0) * shadow; float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 42.0) * shadow; // Focused indirect caustic ring around base of sphere float caustic = (tFl < tSph) ? exp(-abs(length(p.xz) - 0.64) * 14.0) * (0.4 + 0.6 * max(dot(normalize(p.xz + 1e-4), lDir.xz), 0.0)) : 0.0; vec3 alb = (tSph < tFl) ? vec3(0.84, 0.68, 0.46) : vec3(0.38, 0.42, 0.48); vec3 cleanCol = alb * (0.14 + 1.35 * diff / (0.65 + 0.35 * distL)) + vec3(1.0, 0.94, 0.82) * (spec * 0.95 + caustic * 0.72); if (isGuided) { // Right: Learned SD-Tree directional guiding concentrates rays into the skylight lobe -> low variance! float residNoise = (hash21(floor(fragCoord) + floor(iTime * 12.0) * 0.13) - 0.5) * 0.16 * (1.0 - sharp); col = cleanCol * (1.0 + residNoise); // Overlay subtle spatial SD-Tree quad cells & directional guiding arrows pointing toward lightPos on floor! if (tFl < tSph && lobeVis > 0.02) { vec2 cellUV = p.xz * 2.2; vec2 cellF = fract(cellUV) - 0.5; vec2 cellD = 0.5 - abs(cellF); float sdGrid = smoothstep(0.028, 0.008, min(cellD.x, cellD.y)); // Directional Von Mises-Fisher / quadtree lobe petal aligned toward lDir.xz vec2 dir2 = normalize(lDir.xz + vec2(1e-4)); float rC = length(cellF); float align = max(dot(normalize(cellF + vec2(1e-5)), dir2), 0.0); float lobeR = 0.08 + 0.24 * pow(align, mix(1.5, 6.0, sharp)); float lobeRing = exp(-abs(rC - lobeR) * 58.0) * smoothstep(0.45, 0.05, rC); col += vec3(0.16, 0.82, 0.98) * (sdGrid * 0.18 + lobeRing * 0.55) * lobeVis; } } else { // Left: Unguided cosine-weighted sampling misses small light & caustic -> heavy variance & fireflies! vec2 pix = floor(fragCoord * 0.75); float fr = floor(iTime * 10.0) * 0.17; float r1 = hash21(pix + vec2(fr * 13.7, 2.9)); float r2 = hash21(pix * 1.27 + vec2(9.1, fr * 23.3)); float variance = mix(0.22, 1.85, r1); float firefly = smoothstep(0.95, 0.998, r2) * 5.8 * (0.25 + spec + caustic); col = cleanCol * variance + vec3(1.0, 0.90, 0.72) * firefly; } if (tFl < tSph) col = mix(col, bg, 1.0 - exp(-tFl * 0.12)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Multiple Importance Sampling](https://texelatlas.vercel.app/t/multiple-importance-sampling.md): One-sample MIS between the learned guide and BSDF sampling keeps the combined estimator robust and unbiased. ## Sources 1. [primary] Thomas Müller, Markus Gross, Jan Novák (2017) Practical Path Guiding for Efficient Light‐Transport Simulation. Computer Graphics Forum. https://doi.org/10.1111/cgf.13227 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Practical Path Guiding." https://texelatlas.vercel.app/t/path-guiding/ (accessed 2026-12-01). --- id: "path-tracing" title: "Unidirectional Path Tracing" aliases: [PT, Monte Carlo path tracing, Kajiya path tracing] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda, desktop-gpu, webgpu, webgl2, blender] year_introduced: 1986 inputs: [mesh, material-params, hdr-image] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Kajiya, 1986" url: "https://texelatlas.vercel.app/t/path-tracing/" sources_verified_at: "2026-11-29" --- # Unidirectional Path Tracing (Kajiya, 1986) > Estimates the rendering equation by tracing random walks from the camera, sampling a BSDF direction at each hit and gathering emission. Unbiased and general, but noisy until many samples per pixel accumulate. ## Reach for it when - need physically accurate lighting with global illumination - reference quality renders for comparison - caustics, reflections and bounce light all in one method - simple unbiased renderer handling any material ## How it works Light leaving a point is emission plus the integral of incoming light weighted by the BSDF and cosine. Path tracing evaluates that recursive integral with a random walk. From the camera you shoot a ray, find the hit, and add any emitted light. You then sample one outgoing direction from the BSDF, multiply the running **throughput** by `f * cos / pdf`, and continue. Each pixel averages many such walks. Two additions make it practical. **Next-event estimation** also connects every hit to a point on a light source with a shadow ray, which is why small lights become tractable. It is normally combined with BSDF sampling through multiple importance sampling. **Russian roulette** ends long walks at random and divides survivors' throughput by the survival probability, which keeps the estimator unbiased while bounding cost. Because every bounce is sampled from the true scene, caustics, color bleeding, glossy interreflection and soft shadows all emerge without special cases. The price is variance: error falls with the square root of the sample count. ## When to use it Choose it as the ground truth reference and as the default offline integrator: it is simple, unbiased and handles any BSDF and geometry you can intersect. In real time it is the base that [restir-di](restir-di) / [restir-gi](restir-gi) resampling and denoisers are built on. Prefer [bidirectional-path-tracing](bidirectional-path-tracing) or [vertex-connection-and-merging](vertex-connection-and-merging) when light mostly arrives through small openings or specular chains (caustics, lamps behind glass). Prefer [photon-mapping](photon-mapping) for caustics at low cost. Prefer [path-guiding](path-guiding) when plain sampling is too noisy on hard indirect paths. Prefer [ddgi](ddgi) or [lumen-gi](lumen-gi) when you need a few milliseconds per frame rather than converged images. ## Cost offline — Cost scales with samples per pixel times path length times ray cost. Real-time use is limited to one or two samples per pixel plus denoising, which is hardware-ray-tracing territory. Measured GPU Weight: 92.97× baseline (extreme) — 3.0588 ms median / 3.1542 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 79.57× baseline (extreme) — 1.2652 ms median (2.42× faster on L4). Ampere A100 scaling: 57.14× baseline (heavy) — 1.6456 ms median (1.86× faster on A100). ## Failure modes - Fireflies: rare high-contrast paths (a diffuse bounce hitting a tiny bright light, or a specular-diffuse-specular chain) produce isolated bright pixels that clamping only hides at the cost of bias - Caustics seen through glass or reflected by mirrors converge extremely slowly, since the camera walk must hit a small light by chance - Low-sample output is high-frequency noise, so real-time use depends on denoisers that smear detail and ghost on motion - Light leaking and energy loss from sloppy Russian roulette or clamped throughput if the pdf and BSDF are mismatched ## Engine support - blender: builtin — `Properties > Render > Render Engine = Cycles` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/sampling.html, checked 2026-12-01) — Cycles is a unidirectional path tracer. - threejs: plugin — `npm i three-gpu-pathtracer` (evidence: https://github.com/gkjohnson/three-gpu-pathtracer, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Ray Tracing > Path Tracing` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Tracing-Path-Tracing.md, checked 2026-12-01) — HDRP only, requires DXR/Vulkan ray tracing hardware. - unreal: builtin — `Project Settings > Rendering > Hardware Ray Tracing > Support Hardware Ray Tracing, then Viewport > Lit > Path Tracing` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/path-tracer-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params, hdr-image - Outputs: radiance - Platforms: cpu, cuda, desktop-gpu, webgpu, webgl2, blender ## Presets ### Tiny GLSL path tracer: spheres, floor, emissive lamp (glsl-fragment; rendered 2026-11-29) ```json { "samples": 16, "bounces": 4 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: diffuse path tracer with next-event-free emission gathering const int SPP = 16; // samples per pixel const int BOUNCES = 4; // path length uint seed; float rnd(){ seed = seed*747796405u + 2891336657u; uint w = ((seed>>((seed>>28u)+4u))^seed)*277803737u; return float((w>>22u)^w)/4294967295.0; } vec3 cosDir(vec3 n){ float u1 = rnd(), u2 = rnd(); float r = sqrt(u1), ph = 6.2831853*u2; vec3 t = normalize(cross(n, abs(n.x) > 0.9 ? vec3(0,1,0) : vec3(1,0,0))); vec3 b = cross(n, t); return normalize(t*r*cos(ph) + b*r*sin(ph) + n*sqrt(1.0-u1)); } void scene(vec3 ro, vec3 rd, out float tmin, out vec3 nor, out vec3 alb, out vec3 em){ tmin = 1e9; nor = vec3(0,1,0); alb = vec3(0.0); em = vec3(0.0); if (rd.y < -1e-4) { float t = (-1.0-ro.y)/rd.y; vec3 p = ro+rd*t; float c = mod(floor(p.x)+floor(p.z), 2.0); tmin = t; alb = mix(vec3(0.8,0.78,0.7), vec3(0.15,0.2,0.3), c); } vec4 S[4]; vec3 A[4]; vec3 E[4]; S[0] = vec4(-1.3,-0.2,-0.5,0.8); A[0] = vec3(0.8,0.2,0.15); E[0] = vec3(0.0); S[1] = vec4( 0.9,-0.5,0.2,0.5); A[1] = vec3(0.2,0.6,0.8); E[1] = vec3(0.0); S[2] = vec4( 0.2,-0.75,1.4,0.25);A[2] = vec3(0.9); E[2] = vec3(0.0); S[3] = vec4(sin(iTime)*1.5, 2.2, -0.5, 0.5); A[3] = vec3(0.0); E[3] = vec3(14.0,12.0,9.0); for (int i = 0; i < 4; i++) { vec3 oc = ro - S[i].xyz; float b = dot(oc, rd); float c = dot(oc,oc) - S[i].w*S[i].w; float h = b*b - c; if (h < 0.0) continue; float t = -b - sqrt(h); if (t > 1e-3 && t < tmin) { tmin = t; nor = normalize(ro + rd*t - S[i].xyz); alb = A[i]; em = E[i]; } } } void mainImage(out vec4 fragColor, in vec2 fragCoord){ seed = uint(fragCoord.x) * 1973u + uint(fragCoord.y) * 9277u + 26699u; vec3 col = vec3(0.0); for (int s = 0; s < SPP; s++) { vec2 uv = (fragCoord + vec2(rnd(), rnd()) - 0.5*iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.6, 5.0), rd = normalize(vec3(uv, -1.6)); vec3 thr = vec3(1.0), rad = vec3(0.0); for (int k = 0; k < BOUNCES; k++) { float t; vec3 n, alb, em; scene(ro, rd, t, n, alb, em); if (t > 1e8) { rad += thr * mix(vec3(0.05,0.07,0.1), vec3(0.25,0.35,0.5), 0.5+0.5*rd.y); break; } rad += thr * em; if (dot(n, rd) > 0.0) n = -n; ro = ro + rd*t + n*1e-3; rd = cosDir(n); thr *= alb; } col += rad; } col /= float(SPP); fragColor = vec4(pow(1.0 - exp(-col), vec3(1.0/2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Next-event estimation (direct light sampling)](https://texelatlas.vercel.app/t/next-event-estimation.md) ## Combines with - [Multiple Importance Sampling](https://texelatlas.vercel.app/t/multiple-importance-sampling.md): MIS weights merge light sampling and BSDF sampling at each vertex, removing the worst variance spikes. - [Neural Radiance Caching](https://texelatlas.vercel.app/t/neural-radiance-caching.md): A learned cache terminates paths after a few bounces and supplies the remaining indirect radiance. - [ReSTIR GI: Path Resampling for Real-Time Path Tracing](https://texelatlas.vercel.app/t/restir-gi.md): Resampling reuses the one-sample indirect paths this integrator produces across pixels and frames. ## Sources 1. [primary] James T. Kajiya (1986) The rendering equation. Proceedings of the 13th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/15922.15902 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Path Tracing (Physically Based Rendering, 3rd edition). pbr-book.org. https://pbr-book.org/3ed-2018/Light_Transport_I_Surface_Reflection/Path_Tracing (verified via http on 2026-11-29) 3. [implementation] gkjohnson (2021) gkjohnson/three-gpu-pathtracer. https://github.com/gkjohnson/three-gpu-pathtracer License: MIT. (verified via github on 2026-11-29) 4. [implementation] mmp (2017) mmp/pbrt-v4. https://github.com/mmp/pbrt-v4 License: Apache-2.0. (verified via github on 2026-11-29) 5. [implementation] mitsuba-renderer (2021) mitsuba-renderer/mitsuba3. https://github.com/mitsuba-renderer/mitsuba3 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Unidirectional Path Tracing." https://texelatlas.vercel.app/t/path-tracing/ (accessed 2026-12-01). --- id: "per-object-motion-blur" title: "Plausible motion blur (reconstruction filter)" aliases: [McGuire motion blur] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2012 inputs: [ldr-image, depth, gbuffer] outputs: [ldr-image] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "McGuire et al., 2012" url: "https://texelatlas.vercel.app/t/per-object-motion-blur/" sources_verified_at: "2026-11-29" --- # Plausible motion blur (reconstruction filter) (McGuire et al., 2012) > Post-process motion blur that tiles the velocity buffer, picks the dominant velocity per neighbourhood, and gathers colour along it with depth-aware weights so moving objects blur over backgrounds and sharp silhouettes survive. ## Reach for it when - fast movement looks choppy at 30 fps - want film-like blur on moving objects - blur smears sharp silhouettes over background - need motion blur without rendering sub-frames ## How it works The renderer outputs a per-pixel velocity buffer. A first pass reduces it into tiles holding the largest velocity vector in each tile, and a second pass spreads that to a 3x3 tile neighbourhood so each pixel knows the strongest velocity that could affect it. The gather then samples colour along that dominant direction. Each sample's weight depends on whether the sample's velocity and depth say it can cover the centre pixel, so a fast foreground object smears into the background but a static foreground does not get blurred by a moving background. A soft depth comparison avoids hard edges. Dithered sample offsets hide banding, and a light blur or temporal filter cleans the noise. ## When to use it Choose it when you have accurate per-object velocity and want film-like blur on fast motion without rendering sub-frames. Prefer camera-only blur reconstructed from depth when no velocity buffer exists. Pair with [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md), which already requires the same velocity buffer. ## Cost medium — Tile max pass, neighbour-max pass and a gather of roughly 8 to 16 taps; qualitative. Measured GPU Weight: 3.09× baseline (light) — 0.1018 ms median / 0.108 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.5× baseline (light) — 0.0397 ms median (2.56× faster on L4). Ampere A100 scaling: 1.98× baseline (feather) — 0.057 ms median (1.79× faster on A100). ## Failure modes - Foreground objects do not blur over the background they occlude where that background is unknown - Wrong or missing velocity on transparents and particles breaks the effect - Sampling noise or banding at low tap counts - Strobing appearance at very low frame rates where blur length is large ## Engine support - babylonjs: builtin — `new BABYLON.MotionBlurPostProcess('mb', scene, 1.0, camera); isObjectBased = true` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/motionBlurPostProcess.ts, checked 2026-12-01) - blender: builtin — `Properties > Render > Motion Blur (Cycles and EEVEE)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/motion_blur.html, checked 2026-12-01) - threejs: official — `import { motionBlur } from 'three/addons/tsl/display/MotionBlur.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/MotionBlur.js, checked 2026-12-01) — Uses velocity buffer. - unity: builtin — `Volume > Add Override > Post-processing > Motion Blur` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Post-Processing-Motion-Blur.md, checked 2026-12-01) — Camera and per-object motion vectors; tile-based reconstruction in HDRP. - unreal: builtin — `Post Process Volume > Lens > Motion Blur` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, depth, gbuffer - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Left: sharp frame. Right: gather along the dominant velocity (dilated around the moving disc) (glsl-fragment; rendered 2026-11-29) ```json { "NT": 32 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec2 VEL=vec2(0.17,0.045); // P const int NT=32; // P vec3 frame(vec2 p){ vec3 c=mix(vec3(.85,.88,.8),vec3(.55,.65,.75),clamp(p.y+.5,0.,1.)); c*=.75+.25*step(.5,fract(p.x*14.)); vec2 o=p-vec2(-.04,-.02);float d=length(o)-.09; vec3 oc=mix(vec3(.9,.3,.2),vec3(1.,.85,.3),step(.5,fract((o.x+o.y)*40.))); return mix(c,oc*(.65+.5*clamp(.5-o.y*4.,0.,1.)),smoothstep(.002,-.002,d));} bool isObj(vec2 p){return length(p-vec2(-.04,-.02))<.09;} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=frame(q); if(R){bool near=false; for(int i=-4;i<=4;i++)if(isObj(q+VEL*float(i)/8.))near=true; if(near){vec3 acc=vec3(0.); for(int i=0;i Filters shadow-map comparisons rather than depths: it runs the depth test at several neighbouring texels and averages the binary results, giving antialiased soft edges. ## Reach for it when - shadow edges are jagged and aliased - need soft edges on a shadow map cheaply - hard stair-stepped shadows from low-res maps - blur shadow boundaries without light bleeding - baseline smoothing for shadow mapping ## How it works Averaging stored depths first and then comparing is meaningless, so PCF reverses the order: sample a kernel of shadow-map texels around the projected point (a regular grid, Poisson disc or rotated pattern), compare each with the receiver depth, and report the fraction that pass. Hardware does this for one 2x2 neighbourhood with a comparison sampler and bilinear weighting, and larger kernels are built by looping over taps. The kernel radius sets a constant penumbra width, so it softens edges uniformly without modelling real light size. Receiver-plane depth bias or per-tap slope correction is important, because a wide kernel spans texels at very different depths on sloped surfaces. ## When to use it Choose it as the baseline soft-edge filter on top of [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md); it is cheap and robust. Prefer [Percentage-Closer Soft Shadows](https://texelatlas.vercel.app/t/percentage-closer-soft-shadows.md) when penumbra width must grow with distance from the occluder, [Variance Shadow Maps](https://texelatlas.vercel.app/t/variance-shadow-maps.md) or [Moment Shadow Maps](https://texelatlas.vercel.app/t/moment-shadow-maps.md) when you want prefilterable, blurable shadow maps, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) for physically sized area lights. ## Cost cheap — Cost scales linearly with tap count; 2x2 hardware PCF is nearly free, a 5x5 or 16-tap Poisson kernel is noticeable. Measured GPU Weight: 19.2× baseline (moderate) — 0.6316 ms median / 0.7427 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 14.64× baseline (moderate) — 0.2328 ms median (2.71× faster on L4). Ampere A100 scaling: 12.5× baseline (moderate) — 0.3599 ms median (1.75× faster on A100). ## Failure modes - Constant penumbra width regardless of occluder distance - Banding with small regular kernels, noise with randomised ones - Acne returns on slopes when a wide kernel samples across depth discontinuities - Cost multiplies with cascades and lights ## Engine support - babylonjs: builtin — `shadowGenerator.usePercentageCloserFiltering = true (or usePoissonSampling)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Shadows/shadowGenerator.ts, checked 2026-12-01) — WebGL2/WebGPU; falls back to Poisson on WebGL1. - blender: builtin — `Light Properties > Shadow > Filter (EEVEE)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_settings.html, checked 2026-12-01) - godot: builtin — `Project Settings > Rendering > Lights And Shadows > Positional Shadow > Soft Shadow Filter Quality (and Directional Shadow equivalent)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ProjectSettings.xml, checked 2026-12-01) - metal: builtin — `MTLSamplerDescriptor.compareFunction + MSL depth2d::sample_compare()` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlsamplerdescriptor.json, checked 2026-12-01) — Hardware comparison sampling; wider PCF kernels are written in MSL. - threejs: builtin — `renderer.shadowMap.type = THREE.PCFShadowMap` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) - unity: builtin — `URP: Light > Shadows > Soft Shadows; HDRP Asset > Lighting > Shadows > Filtering Quality` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Shadows-in-HDRP.md, checked 2026-12-01) — PCF-based soft filtering in both pipelines. - unreal: builtin — `Directional/Point/Spot Light Shadow Maps and Virtual Shadow Maps (PCF shadow map filtering; VSM adds SMRT)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/virtual-shadow-maps-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `device.createSampler({compare:"less"}) + WGSL textureSampleCompare(texture_depth_2d, sampler_comparison, ...)` (evidence: https://www.w3.org/TR/WGSL/, checked 2026-12-01) — Hardware 2x2 comparison filtering; wider kernels are written in WGSL. ## Dataflow - Inputs: depth, visibility-mask - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: one depth comparison per pixel (jagged). Right: 5x5 PCF averages comparisons into soft edges (glsl-fragment; rendered 2026-11-29) ```json { "RES": 48, "BIAS": 0.02, "K": 2 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float EXT=3.2; vec3 lU(){return normalize(cross(vec3(0.,1.,0.),LD));} vec3 lV(){return cross(LD,lU());} vec2 toL(vec3 P){return vec2(dot(P,lU()),dot(P,lV()));} float recv(vec3 P){return 10.-dot(P,LD);} float smTex(vec2 st,float res){float tx=2.*EXT/res;vec2 c=(floor(st/tx)+.5)*tx;vec3 n; return isect(LD*10.+lU()*c.x+lV()*c.y,-LD,n);} float vis1(vec3 P,vec3 N,vec2 st,vec2 o,float res,float b){float tx=2.*EXT/res;vec2 cc=(floor((st+o)/tx)+.5)*tx;vec3 q; float d=isect(LD*10.+lU()*cc.x+lV()*cc.y,-LD,q);vec2 e=cc-st; float zr=recv(P)+(e.x*dot(N,lU())+e.y*dot(N,lV()))/max(dot(N,LD),.15); return zr-b>d?0.:1.;} vec3 shadeV(vec3 P,vec3 N,float vis){return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*vis*1.3);} const float RES=48.0; // P const float BIAS=0.02; // P const int K=2; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t;float zr=recv(P)-BIAS;vec2 st=toL(P);float vis=0.; if(!R) vis=vis1(P,n,st,vec2(0.),RES,BIAS); else{ float tx=2.*EXT/RES;vec2 base=floor(st/tx-.5),f=st/tx-.5-base; for(int j=-K;j<=K+1;j++)for(int i=-K;i<=K+1;i++){ float wx=(i==-K)?1.-f.x:((i==K+1)?f.x:1.),wy=(j==-K)?1.-f.y:((j==K+1)?f.y:1.); vis+=wx*wy*vis1(P,n,st,(base+vec2(float(i),float(j))+.5)*tx-st,RES,BIAS);} vis/=float((2*K+1)*(2*K+1)); } col=mix(shadeV(P,n,vis),sky(rd),smoothstep(6.,25.,t)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extends [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) - extended by [Percentage-Closer Soft Shadows](https://texelatlas.vercel.app/t/percentage-closer-soft-shadows.md) ## Sources 1. [primary] William T. Reeves, David H. Salesin, Robert L. Cook (1987) Rendering antialiased shadows with depth maps. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/37402.37435 (verified via crossref on 2026-11-29) 2. [tutorial] Michael Bunnell, Fabio Pellacini Shadow Map Antialiasing. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems/part-ii-lighting-and-shadows/chapter-11-shadow-map-antialiasing (verified via http on 2026-11-29) ## Cite this entry Texel. "Percentage-Closer Filtering." https://texelatlas.vercel.app/t/percentage-closer-filtering/ (accessed 2026-12-01). --- id: "percentage-closer-soft-shadows" title: "Percentage-Closer Soft Shadows" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2005 inputs: [depth, visibility-mask] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Fernando, 2005" url: "https://texelatlas.vercel.app/t/percentage-closer-soft-shadows/" sources_verified_at: "2026-11-29" --- # Percentage-Closer Soft Shadows (Fernando, 2005) > Estimates penumbra width per pixel from a blocker search in the shadow map, then runs a PCF kernel of that size, so shadows sharpen near contact and blur with distance. ## Reach for it when - shadows have uniform hard or blurry edges - contact hardening: sharp near the occluder and soft far away - want penumbra that grows with distance - realistic area light shadow softness in real time ## How it works For each receiver, PCSS runs three steps. First, a blocker search samples the shadow map in a region sized by the light's apparent size and finds the average depth of texels nearer than the receiver. Second, the penumbra width is estimated with similar triangles from light size, receiver depth and mean blocker depth. Third, a PCF filter whose radius equals that width produces the final visibility. The result mimics an area light without extra geometry. Because the search and filter are both multi-tap, implementations use few Poisson samples with per-pixel rotation and often denoise with temporal accumulation or a bilateral blur. ## When to use it Choose it for contact-hardening soft shadows from a single shadow map, typically on the sun or a few key lights. Prefer [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) when a fixed penumbra suffices and budget is tight, [Moment Shadow Maps](https://texelatlas.vercel.app/t/moment-shadow-maps.md) or [Variance Shadow Maps](https://texelatlas.vercel.app/t/variance-shadow-maps.md) when you want a blurrable map, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) when accurate multi-occluder penumbrae matter. ## Cost medium — Dozens of shadow-map taps per pixel; usually the most expensive shadow-map filter in common use. Measured GPU Weight: 50.14× baseline (heavy) — 1.6496 ms median / 1.6738 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 38.22× baseline (heavy) — 0.6077 ms median (2.71× faster on L4). Ampere A100 scaling: 31.81× baseline (heavy) — 0.9162 ms median (1.8× faster on A100). ## Failure modes - Assumes one planar blocker depth, so penumbrae are wrong with multiple occluders at different depths - Noise or banding when tap counts are low - Blocker search radius can miss thin distant occluders - Light bleeding where the average blocker depth is misleading ## Engine support - babylonjs: builtin — `shadowGenerator.useContactHardeningShadow = true (PCSS)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Shadows/shadowGenerator.ts, checked 2026-12-01) — WebGL2/WebGPU only. - godot: builtin — `Light3D.light_size (omni/spot) or Light3D.light_angular_distance (directional)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Light3D.xml, checked 2026-12-01) — Light size drives PCSS penumbra width; see also AreaLight3D in 4.7. - threejs: official — `examples/webgl_shadowmap_pcss.html patches ShaderChunk.shadowmap_pars_fragment with PCSS` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/webgl_shadowmap_pcss.html, checked 2026-12-01) — Official example only (WebGLRenderer); not a renderer setting. - unity: builtin — `HDRP Asset > Lighting > Shadows > Filtering Quality = High (PCSS)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md, checked 2026-12-01) — HDRP only (High filtering quality enables PCSS). - unreal: builtin — `Virtual Shadow Maps > Shadow Map Ray Tracing (SMRT) evaluates contact-hardening variable-penumbra soft shadows` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/virtual-shadow-maps-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, visibility-mask - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: fixed-radius PCF. Right: PCSS blocker search sets the filter radius (sharp at contact, wide far away) (glsl-fragment; rendered 2026-11-29) ```json { "RES": 128, "BIAS": 0.03, "LS": 0.2, "FIXR": 0.12 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float EXT=3.2; vec3 lU(){return normalize(cross(vec3(0.,1.,0.),LD));} vec3 lV(){return cross(LD,lU());} vec2 toL(vec3 P){return vec2(dot(P,lU()),dot(P,lV()));} float recv(vec3 P){return 10.-dot(P,LD);} float smTex(vec2 st,float res){float tx=2.*EXT/res;vec2 c=(floor(st/tx)+.5)*tx;vec3 n; return isect(LD*10.+lU()*c.x+lV()*c.y,-LD,n);} float vis1(vec3 P,vec3 N,vec2 st,vec2 o,float res,float b){float tx=2.*EXT/res;vec2 cc=(floor((st+o)/tx)+.5)*tx;vec3 q; float d=isect(LD*10.+lU()*cc.x+lV()*cc.y,-LD,q);vec2 e=cc-st; float zr=recv(P)+(e.x*dot(N,lU())+e.y*dot(N,lV()))/max(dot(N,LD),.15); return zr-b>d?0.:1.;} vec3 shadeV(vec3 P,vec3 N,float vis){return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*vis*1.3);} const float RES=128.0; // P const float BIAS=0.03; // P const float LS=0.2; // P const float FIXR=0.12; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t;float zr=recv(P)-BIAS;vec2 st=toL(P);float w=FIXR,vis=1.; if(R){ float bs=0.,bn=0.; for(int j=-2;j<=2;j++)for(int i=-2;i<=2;i++){float d=smTex(st+vec2(float(i),float(j))*.2,RES);if(d.5?min((zr-bs/bn)*LS,.6):0.; } if(w>0.){ vis=0.; for(int j=-3;j<=3;j++)for(int i=-3;i<=3;i++)vis+=vis1(P,n,st,vec2(float(i),float(j))/3.*w,RES,BIAS); vis/=49.; } col=mix(shadeV(P,n,vis),sky(rd),smoothstep(6.,25.,t)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extends [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) ## Sources 1. [primary] Randima Fernando (2005) Percentage-closer soft shadows. ACM SIGGRAPH 2005 Sketches on - SIGGRAPH '05. https://doi.org/10.1145/1187112.1187153 (verified via crossref on 2026-11-29) 2. [tutorial] Randima Fernando Percentage-Closer Soft Shadows. developer.download.nvidia.com. https://developer.download.nvidia.com/shaderlibrary/docs/shadow_PCSS.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Percentage-Closer Soft Shadows." https://texelatlas.vercel.app/t/percentage-closer-soft-shadows/ (accessed 2026-12-01). --- id: "perlin-noise" title: "Perlin Noise (gradient lattice noise)" aliases: [classic Perlin noise, gradient noise] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, houdini, unity, unreal, godot, python] year_introduced: 1985 outputs: [texture, heightfield, volume-density] style: "both" dynamic: "both" cost: "cheap" authority: "Perlin, 1985" url: "https://texelatlas.vercel.app/t/perlin-noise/" sources_verified_at: "2026-11-29" --- # Perlin Noise (gradient lattice noise) (Perlin, 1985) > A smooth, band-limited pseudo-random scalar field built by placing random gradient vectors on an integer lattice and blending their dot products. The original building block for procedural textures and terrain. ## Reach for it when - need a cheap smooth random field - procedural clouds, marble or bump maps from noise - random values look harsh and uncorrelated - seedable repeatable noise for heightfields ## How it works Space is divided into unit cells. Each lattice corner gets a pseudo-random gradient vector, chosen by hashing the integer coordinates through a permutation table, so the field is a pure function of position with no stored data. For a sample point you take the offset vector to each corner of its cell, dot it with that corner's gradient, and blend the results with a smooth interpolant. Because every corner contributes exactly zero at its own location, the field passes through zero at lattice points and has a characteristic feature size of about one cell, which makes it band-limited and a good octave for spectral synthesis. Original 1985 noise used a cubic Hermite blend (3t^2-2t^3), which leaves visible second-derivative discontinuities; that flaw is what the 2002 revision fixes. Cost scales as 2^n corners in n dimensions. ## When to use it Choose it when you need a cheap, repeatable, seedable smooth field for clouds, marble, bump maps or heightfields, and axis-aligned artifacts are tolerable. Prefer [Improved Perlin Noise](https://texelatlas.vercel.app/t/improved-perlin-noise.md) for anything you will differentiate or use as a normal map, [Simplex Noise](https://texelatlas.vercel.app/t/simplex-noise.md) for 4D or higher dimensions or less grid bias, and [Worley (Cellular) Noise](https://texelatlas.vercel.app/t/worley-noise.md) when you want cell or crack structures rather than blobs. ## Cost cheap — A handful of hash lookups and multiplies per octave; qualitative only. Dominated by octave count when summed as fBm. Measured GPU Weight: 6.76× baseline (moderate) — 0.2225 ms median / 0.2354 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.09× baseline (moderate) — 0.0968 ms median (2.3× faster on L4). Ampere A100 scaling: 4.17× baseline (light) — 0.1202 ms median (1.85× faster on A100). ## Failure modes - Axis-aligned grid bias: features and zero-crossings line up with lattice axes, visible as faint squares at low frequency - Cubic Hermite fade gives second-derivative discontinuities, visible as creases in bump-mapped or lit surfaces - Output is zero at every integer lattice point, so unrotated stacked octaves reinforce the same lattice pattern - Range is not exactly [-1,1]; real amplitude is smaller and varies by dimension, which breaks naive thresholding ## Engine support - babylonjs: official — `new BABYLON.PerlinNoiseProceduralTexture('n', size, scene) from @babylonjs/procedural-textures` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/proceduralTextures/src/perlinNoise/perlinNoiseProceduralTexture.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Texture > Noise Texture` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/noise.html, checked 2026-12-01) - godot: builtin — `FastNoiseLite.noise_type = FastNoiseLite.TYPE_PERLIN` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/noise/doc_classes/FastNoiseLite.xml, checked 2026-12-01) - threejs: official — `import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/math/ImprovedNoise.js, checked 2026-12-01) - unity: builtin — `Mathf.PerlinNoise(x, y)` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mathf.PerlinNoise.html, checked 2026-12-01) — 2D only; Unity.Mathematics adds 3D/4D. - unreal: builtin — `Material Noise expression > Function = Gradient (texture based)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/utility-material-expressions-in-unreal-engine, checked 2026-12-01) — Gradient noise, formerly labeled Perlin. ## Dataflow - Inputs: — - Outputs: texture, heightfield, volume-density - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, houdini, unity, unreal, godot, python ## Presets ### Classic Perlin gradient noise with lattice gradients shown, 3 octaves (glsl-fragment; rendered 2026-11-29) ```json { "SCALE": 5, "OCTAVES": 3 } ``` ```glsl // Classic 2D Perlin gradient noise: lattice with random unit gradients (white ticks), value mapped to terrain-like colours, 3 octaves. const float SCALE = 5.0; const int OCTAVES = 3; vec2 grad(vec2 i) { float a = 6.2831853 * fract(sin(dot(i, vec2(127.1, 311.7))) * 43758.5453); return vec2(cos(a), sin(a)); } float noise(vec2 p) { vec2 i = floor(p), f = fract(p), u = f * f * (3.0 - 2.0 * f); return mix(mix(dot(grad(i), f), dot(grad(i + vec2(1, 0)), f - vec2(1, 0)), u.x), mix(dot(grad(i + vec2(0, 1)), f - vec2(0, 1)), dot(grad(i + vec2(1, 1)), f - vec2(1, 1)), u.x), u.y); } float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 p = uv * SCALE; float h = 0.0, amp = 0.5, fr = 1.0; for (int o = 0; o < OCTAVES; o++) { h += amp * noise(p * fr); amp *= 0.5; fr *= 2.0; } h = h * 1.6 + 0.5; vec3 col = h < 0.45 ? mix(vec3(0.05, 0.15, 0.4), vec3(0.2, 0.5, 0.7), h / 0.45) : h < 0.75 ? mix(vec3(0.25, 0.5, 0.2), vec3(0.6, 0.55, 0.3), (h - 0.45) / 0.3) : mix(vec3(0.5, 0.45, 0.4), vec3(1.0), clamp((h - 0.75) * 3.0, 0.0, 1.0)); col *= 0.85 + 0.15 * sin(h * 60.0); // lattice and first-octave gradients vec2 id = floor(p + 0.5); float g = segd(p, id, id + grad(id) * 0.3); vec2 f = abs(fract(p) - 0.5); col = mix(col, vec3(0.0), smoothstep(0.02, 0.0, min(f.x, f.y) - 0.48) * 0.35); col = mix(col, vec3(1.0), smoothstep(0.02, 0.01, g)); col = mix(col, vec3(1.0), smoothstep(0.06, 0.04, length(p - id))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) - extended by [Simplex Noise](https://texelatlas.vercel.app/t/simplex-noise.md) - superseded by [Improved Perlin Noise](https://texelatlas.vercel.app/t/improved-perlin-noise.md) ## Combines with - [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md): Summing octaves of this noise yields the natural-looking spectrum fBm needs. ## Sources 1. [primary] Ken Perlin (1985) An image synthesizer. Proceedings of the 12th annual conference on Computer graphics and interactive techniques - SIGGRAPH '85. https://doi.org/10.1145/325334.325247 (verified via crossref on 2026-11-29) 2. [tutorial] Patricio Gonzalez Vivo The Book of Shaders: Noise. thebookofshaders.com. https://thebookofshaders.com/11 (verified via http on 2026-11-29) 3. [tutorial] Inigo Quilez Gradient Noise - Derivatives. iquilezles.org. https://iquilezles.org/articles/gradientnoise (verified via http on 2026-11-29) ## Cite this entry Texel. "Perlin Noise (gradient lattice noise)." https://texelatlas.vercel.app/t/perlin-noise/ (accessed 2026-12-01). --- id: "photometric-stereo" title: "Photometric Stereo" aliases: [shape from shading, multi-light] domain: "capture" stage: "capture" realtime: "offline" platforms: [cpu, python] year_introduced: 1980 inputs: [photos] outputs: [normals, depth] style: "photoreal" dynamic: "static" cost: "offline" authority: "1980" url: "https://texelatlas.vercel.app/t/photometric-stereo/" sources_verified_at: "2026-11-29" --- # Photometric Stereo (1980) > Estimates per-pixel surface normals from several photos of a fixed object and camera under different known lighting directions, assuming a simple reflectance model. ## Reach for it when - recover fine surface relief from photos with changing light - coins and engravings lose detail in photogrammetry - get per-pixel normals with fixed camera and varied lighting - multi-view geometry is too smooth for small detail - capture skin or fabric micro-geometry ## How it works Place the camera and object still and capture images while varying the light direction. For a Lambertian surface each pixel's intensity is the dot product of the albedo-scaled normal with the light vector. With three or more known lights this becomes a linear system per pixel, solved by least squares for the scaled normal; its length is albedo and its direction the normal. Extra lights over-determine the system and let you reject shadows and specular highlights as outliers. The normal map is then integrated into a height field, which is a separate problem sensitive to noise and discontinuities. Modern variants relax the assumptions: calibrated non-Lambertian BRDFs, near lights, or learned networks for unknown lighting. ## When to use it Choose it for fine surface detail (coins, reliefs, skin, fabric) where geometry from multi-view matching is too smooth. Prefer [Universal Photometric Stereo (SDM-UniPS)](https://texelatlas.vercel.app/t/universal-photometric-stereo.md) when lights are uncalibrated or the material is glossy. Prefer [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md) for large-scale shape, and combine the two: MVS for the base shape, photometric normals for detail. ## Cost offline — Per-pixel linear solve is cheap; the cost is capture and normal integration. Measured GPU Weight: 5.22× baseline (light) — 0.1617 ms median / 0.1708 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 4.45× baseline (light) — 0.0708 ms median (2.28× faster on L4). Ampere A100 scaling: 3.53× baseline (light) — 0.1016 ms median (1.59× faster on A100). ## Failure modes - Specular highlights and cast shadows break the Lambertian assumption and bias normals - Inaccurate light directions cause a low-frequency bending of the integrated surface - Inter-reflections in concavities flatten recovered depth - Integrating normals to depth accumulates drift and smears depth discontinuities ## Dataflow - Inputs: photos - Outputs: normals, depth - Platforms: cpu, python ## Presets ### Photometric Stereo — rotating directional capture I_k (left) vs least-squares recovered normals (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_LIGHT_ELEV": 0.62, "P_RELIEF_AMP": 1, "P_NOISE_AMT": 0.03, "P_SPLIT": 0.48 } ``` ```glsl const float P_LIGHT_ELEV = 0.62; // P Light Elevation [0.25, 0.92, 0.02] const float P_RELIEF_AMP = 1.0; // P Relief Depth [0.3, 1.8, 0.05] const float P_NOISE_AMT = 0.03; // P Sensor Noise [0.0, 0.15, 0.005] const float P_SPLIT = 0.48; // P Capture / Normals [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Sculpted classical coin / relief medallion heightfield h(u, v) + spatially varying albedo rho(u, v) void reliefSurface(vec2 p, float amp, out float h, out vec3 albedo, out float mask) { float r = length(p); mask = smoothstep(0.455, 0.442, r); // Stepped coin rim + radial fluting + sculpted inner rosette/dome float rim = exp(-pow((r - 0.41) / 0.025, 2.0)) * 0.075; float dome = sqrt(max(0.14 - r * r, 0.0)) * 0.42 * smoothstep(0.38, 0.30, r); float a = atan(p.y, p.x); float petals = sin(a * 8.0) * exp(-pow((r - 0.22) / 0.085, 2.0)) * 0.038; float innerRing = exp(-pow((r - 0.11) / 0.022, 2.0)) * 0.045; float microGroove = sin(r * 75.0) * 0.0045 * smoothstep(0.40, 0.12, r); h = (rim + dome + petals + innerRing + microGroove) * amp; // Spatially varying patinated bronze / plaster albedo (photometric stereo separates albedo from normal!) float patina = 0.5 + 0.5 * sin(p.x * 9.0 + sin(p.y * 7.0)); albedo = mix(vec3(0.66, 0.54, 0.42), vec3(0.84, 0.78, 0.68), patina * 0.65 + 0.25 * smoothstep(0.36, 0.10, r)); } vec3 trueNormal(vec2 p, float amp) { float e = 0.0025; float h0, hX, hY, m; vec3 a; reliefSurface(p, amp, h0, a, m); reliefSurface(p + vec2(e, 0.0), amp, hX, a, m); reliefSurface(p + vec2(0.0, e), amp, hY, a, m); return normalize(vec3(-(hX - h0) / e, -(hY - h0) / e, 1.0)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isRecovered = screenX >= split; float elev = clamp(P_LIGHT_ELEV, 0.22, 0.94); float amp = clamp(P_RELIEF_AMP, 0.25, 2.0); float noiseAmt = clamp(P_NOISE_AMT, 0.0, 0.18); vec3 col = mix(vec3(0.025, 0.034, 0.052), vec3(0.062, 0.080, 0.120), smoothstep(-0.5, 0.5, uv.y)); vec2 g = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.015, 0.022, 0.036) * smoothstep(0.03, 0.006, min(g.x, g.y)); float h, mask; vec3 albedo; reliefSurface(uv, amp, h, albedo, mask); // 3 known calibrated light directions L = [l0, l1, l2]^T separated by 120 deg in azimuth float rHoriz = sqrt(max(1.0 - elev * elev, 0.01)); float baseAz = iTime * 0.75; vec3 l0 = vec3(cos(baseAz) * rHoriz, sin(baseAz) * rHoriz, elev); vec3 l1 = vec3(cos(baseAz + 2.0943951) * rHoriz, sin(baseAz + 2.0943951) * rHoriz, elev); vec3 l2 = vec3(cos(baseAz + 4.1887902) * rHoriz, sin(baseAz + 4.1887902) * rHoriz, elev); if (mask > 0.005) { vec3 nTrue = trueNormal(uv, amp); float rho = dot(albedo, vec3(0.299, 0.587, 0.114)); // Simulate 3 captured Lambertian photographs I_k = rho * max(n . l_k, 0) + sensor noise float n0 = (hash21(fragCoord + 1.3) - 0.5) * noiseAmt; float n1 = (hash21(fragCoord + 17.7) - 0.5) * noiseAmt; float n2 = (hash21(fragCoord + 43.1) - 0.5) * noiseAmt; vec3 measI = vec3( max(rho * dot(nTrue, l0) + n0, 0.0), max(rho * dot(nTrue, l1) + n1, 0.0), max(rho * dot(nTrue, l2) + n2, 0.0) ); if (!isRecovered) { // Left: Live rotating capture photograph illuminated by active light direction l0 float liveLit = max(dot(nTrue, l0), 0.0); vec3 captureImg = albedo * (0.04 + 1.25 * liveLit) + vec3(n0 * 0.6); col = mix(col, captureImg, mask); } else { // Right: Direct linear Woodham photometric stereo solve: g = inverse(L) * I, n = normalize(g)! // Matrix rows are l0, l1, l2 -> in GLSL mat3 columns are transposed, so transpose(mat3(l0, l1, l2)) mat3 Lmat = transpose(mat3(l0, l1, l2)); vec3 gVec = inverse(Lmat) * measI; vec3 nEst = normalize(gVec + vec3(0.0, 0.0, 1e-4)); vec3 normMap = nEst * 0.5 + 0.5; col = mix(col, normMap, mask); } } // Draw the 3 calibrated light-source beacons orbiting around the medallion perimeter for (int k = 0; k < 3; k++) { vec3 lk = (k == 0) ? l0 : ((k == 1) ? l1 : l2); vec2 beaconPos = lk.xy * (0.48 / max(rHoriz, 0.1)) * 0.94; float dB = length(uv - beaconPos); vec3 bCol = (k == 0) ? vec3(1.0, 0.88, 0.36) : vec3(0.32, 0.72, 0.98); float bRad = (k == 0) ? 0.026 : 0.018; col += bCol * smoothstep(bRad * 2.2, bRad * 0.4, dB) * (k == 0 ? 1.1 : 0.55); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Universal Photometric Stereo (SDM-UniPS)](https://texelatlas.vercel.app/t/universal-photometric-stereo.md) ## Combines with - [Bilateral Normal Integration](https://texelatlas.vercel.app/t/bilateral-normal-integration.md): Photometric stereo produces a normal map; normal integration turns it into a height field. ## Combination ideas - [Dual-normal varnished surfaces from photometric stereo capture](https://texelatlas.vercel.app/ideas/photometric-micro-normals-clearcoat/) ## Sources 1. [primary] (1980) Photometric Method For Determining Surface Orientation From Multiple Images. Optical Engineering. https://doi.org/10.1117/12.7972479 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Photometric Stereo." https://texelatlas.vercel.app/t/photometric-stereo/ (accessed 2026-12-01). --- id: "photon-mapping" title: "Photon Mapping" aliases: [PM] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda] year_introduced: 1996 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "static" cost: "offline" authority: "Jensen, 1996" url: "https://texelatlas.vercel.app/t/photon-mapping/" sources_verified_at: "2026-11-29" --- # Photon Mapping (Jensen, 1996) > Shoots photons from lights into the scene, stores where they land, then estimates indirect and caustic radiance at shading points by looking at nearby photons. Biased but smooth and excellent for caustics. ## Reach for it when - caustics under glass or water are missing - path tracing struggles with light through specular surfaces - need efficient indirect lighting with focused light paths - pool of light patterns through refractive objects ## How it works Photon mapping splits rendering into two passes. In the **photon pass**, packets of flux are emitted from light sources and scattered through the scene by Russian roulette; each time a photon lands on a diffuse surface, its position, incoming direction and power are stored in a spatial structure (a kd-tree or a hash grid). A dedicated **caustic map** holds photons that went through specular bounces; a coarser **global map** holds the rest. In the **render pass**, rays from the camera hit surfaces. At a hit, the renderer gathers the `k` nearest photons (or those within a radius), and divides their summed flux by the area of the search disk. That is a kernel density estimate of irradiance, multiplied by the BSDF. Caustics are read directly from the caustic map. Indirect diffuse is usually evaluated at one extra bounce (**final gathering**) so the photon map's low-frequency noise does not appear on screen. The estimate is biased: radius blurs detail, and error only vanishes in the limit. ## When to use it Choose it for caustics, light concentrated by glass or water, and smooth diffuse interreflection, especially where unbiased methods show intense noise. Prefer [progressive-photon-mapping](progressive-photon-mapping) when memory or fixed photon counts are a problem and you want convergence to the right answer. Prefer [path-tracing](path-tracing) for general scenes where a reference is needed. Prefer [vertex-connection-and-merging](vertex-connection-and-merging) when you want photon-style merging inside an MIS framework. Prefer [instant-radiosity](instant-radiosity) when only diffuse GI at interactive rates is needed. ## Cost offline — Photon tracing is cheap; the cost is in nearest-neighbour gathering and final gathering. GPU variants use grid hashing. Measured GPU Weight: 12.44× baseline (moderate) — 0.3856 ms median / 0.4101 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 11.43× baseline (moderate) — 0.1817 ms median (2.12× faster on L4). Ampere A100 scaling: 7.24× baseline (moderate) — 0.2086 ms median (1.85× faster on A100). ## Failure modes - Blotchy low-frequency noise and light leaking across thin walls or at corners because the search disk crosses geometry - Fixed photon count fails to resolve fine caustic detail; sharp caustic edges are blurred - Memory grows with photon count, and a map has to be rebuilt for any moving light or object - Specular surfaces seen directly require explicit ray tracing; the map only represents diffuse reflectors ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda ## Presets ### Photon Mapping — sparse photon splats (left) vs cone-filtered k-NN caustic & GI gather (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GATHER_RAD": 0.55, "P_CAUSTIC_GAIN": 1.35, "P_LIGHT_SWEEP": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_GATHER_RAD = 0.55; // P Gather Radius [0.15, 1.2, 0.03] const float P_CAUSTIC_GAIN = 1.35; // P Caustic Power [0.2, 2.5, 0.05] const float P_LIGHT_SWEEP = 0.75; // P Light Motion [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Splats / Gather Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // Cornell box with central dielectric glass sphere (matId=4) focusing a refractive caustic on floor vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); // floor float dCeil = 1.05 - p.y; if (dCeil < res.x) res = vec2(dCeil, 1.0); float dBack = p.z + 1.35; if (dBack < res.x) res = vec2(dBack, 1.0); float dLeft = p.x + 1.28; if (dLeft < res.x) res = vec2(dLeft, 2.0); // warm crimson wall float dRight = 1.28 - p.x; if (dRight < res.x) res = vec2(dRight, 3.0); // cool teal wall // Glass crystal sphere resting on floor float dGlass = length(p - vec3(0.0, -0.43, -0.15)) - 0.42; if (dGlass < res.x) res = vec2(dGlass, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Focused refractive caustic density from glass sphere at (0, -0.43, -0.15) vec3 evalCaustic(vec3 p, vec3 lPos, float gatherR) { vec3 sphC = vec3(0.0, -0.43, -0.15); vec3 toSph = normalize(sphC - lPos); // Intersection of refracted chief ray with floor plane y = -0.85 float tF = (-0.85 - sphC.y) / min(toSph.y, -0.15); vec2 focusXZ = sphC.xz + toSph.xz * tF * 0.82; vec2 d = p.xz - focusXZ; float r = length(d); float sigma = 0.075 + 0.14 * gatherR; // Subtle chromatic dispersion across R, G, B wavelengths (IOR 1.50, 1.52, 1.55) float cR = exp(-pow(length(d - toSph.xz * 0.025) / (sigma * 0.95), 2.0)); float cG = exp(-pow(r / sigma, 2.0)); float cB = exp(-pow(length(d + toSph.xz * 0.025) / (sigma * 1.05), 2.0)); // Bright cusp ring typical of spherical aberration caustic float ring = exp(-pow((r - 0.14) / (0.04 + 0.04 * gatherR), 2.0)) * 0.55; float floorMask = smoothstep(-0.72, -0.84, p.y); return (vec3(cR, cG, cB) * 1.65 + vec3(0.95, 0.88, 1.0) * ring) * floorMask; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSmooth = screenX >= split; float gatherR = clamp(P_GATHER_RAD, 0.12, 1.3); float causGain = clamp(P_CAUSTIC_GAIN, 0.1, 2.8); float sweep = iTime * max(P_LIGHT_SWEEP, 0.0); vec3 lPos = vec3(0.42 * sin(sweep * 0.85), 0.96, -0.10 + 0.25 * cos(sweep * 0.6)); vec3 ro = vec3(0.0, -0.02, 2.28); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); if (matId > 3.5) { // Refractive glass sphere with Schlick Fresnel + internal caustic glint vec3 v = -rd; float nv = max(dot(n, v), 0.0); float F = 0.04 + 0.96 * pow(1.0 - nv, 5.0); vec3 rDir = reflect(rd, n); vec3 tDir = refract(rd, n, 1.0 / 1.52); // Sample room walls along reflected and refracted directions vec3 envRefl = mix(vec3(0.14, 0.18, 0.24), vec3(0.95, 0.92, 0.85), smoothstep(0.1, 0.85, rDir.y)); vec3 wallTint = mix(vec3(0.88, 0.24, 0.18), vec3(0.14, 0.72, 0.78), smoothstep(-0.7, 0.7, tDir.x)); vec3 lDir = normalize(lPos - p); float spec = pow(max(dot(n, normalize(lDir + v)), 0.0), 96.0); col = mix(wallTint * 0.62 + vec3(0.22, 0.30, 0.36), envRefl, F) + vec3(1.4) * spec; } else { vec3 alb = vec3(0.76, 0.75, 0.73); if (matId > 1.5 && matId < 2.5) alb = vec3(0.86, 0.22, 0.18); if (matId > 2.5) alb = vec3(0.16, 0.70, 0.74); vec3 lVec = lPos - p; float lDist = length(lVec); vec3 lDir = lVec / max(lDist, 1e-4); float diff = max(dot(n, lDir), 0.0) / (0.65 + lDist * lDist * 0.38); // Sphere shadow on floor (dark under glass except where focused caustic lands!) vec3 oc = p - vec3(0.0, -0.43, -0.15); float bS = dot(oc, lDir); float cS = dot(oc, oc) - 0.42 * 0.42; float sh = (bS < 0.0 && (bS * bS - cS) > 0.0) ? 0.16 : 1.0; // Indirect diffuse photon-map bounce from red & teal walls float leftProx = clamp(1.0 - (p.x + 1.28) * 0.55, 0.0, 1.0); float rightProx = clamp(1.0 - (1.28 - p.x) * 0.55, 0.0, 1.0); vec3 indirect = vec3(0.86, 0.22, 0.18) * leftProx * 0.28 + vec3(0.16, 0.70, 0.74) * rightProx * 0.28 + vec3(0.14); vec3 caustic = evalCaustic(p, lPos, gatherR) * causGain; if (!isSmooth) { // Left side: discrete stored photon splats in the 3D photon map (visualizing pass-1 deposition) vec2 cell = floor(p.xz * 24.0 + p.y * 12.0); vec2 jitter = hash22(cell); vec2 local = fract(p.xz * 24.0 + p.y * 12.0) - jitter; float rDot = length(local); float photonDot = smoothstep(0.24, 0.08, rDot); float densityProb = clamp(length(caustic) * 0.55 + 0.18, 0.0, 1.0); float keep = step(1.0 - densityProb, hash21(cell + 17.1)); vec3 splatCol = (length(caustic) > 0.12) ? (caustic * 2.2 + vec3(0.8, 0.85, 1.0) * 0.4) : (indirect * 2.4); col = alb * (diff * sh * 0.72 + indirect * 0.35) + splatCol * photonDot * keep * 1.15; } else { // Right side: cone-filtered k-NN radiance estimate over the photon map col = alb * (diff * sh * 0.85 + indirect * 0.92) + caustic * (0.45 + 0.55 * alb); } // Ceiling area emitter quad if (p.y > 1.03 && length(p.xz - lPos.xz) < 0.28) { col = vec3(3.2, 3.0, 2.7); } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Progressive Photon Mapping](https://texelatlas.vercel.app/t/progressive-photon-mapping.md) ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): The camera pass uses ordinary path tracing for direct light and final gathering on the photon map. ## Combination ideas - [Mirrored refractive caustics via photon mapping and oblique planar reflections](https://texelatlas.vercel.app/ideas/caustic-photon-map-planar-reflections/) ## Sources 1. [primary] Henrik Wann Jensen (1996) Global Illumination using Photon Maps. Eurographics. https://doi.org/10.1007/978-3-7091-7484-5_3 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Stochastic Progressive Photon Mapping (Physically Based Rendering, 3rd edition). pbr-book.org. https://pbr-book.org/3ed-2018/Light_Transport_III_Bidirectional_Methods/Stochastic_Progressive_Photon_Mapping (verified via http on 2026-11-29) 3. [implementation] mmp (2015) mmp/pbrt-v3. https://github.com/mmp/pbrt-v3 License: BSD-2-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "Photon Mapping." https://texelatlas.vercel.app/t/photon-mapping/ (accessed 2026-12-01). --- id: "physarum-transport-networks" title: "Physarum agent transport networks" domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 2010 inputs: [particles, texture] outputs: [texture, graph] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Jones, 2010" url: "https://texelatlas.vercel.app/t/physarum-transport-networks/" sources_verified_at: "2026-11-29" --- # Physarum agent transport networks (Jones, 2010) > Multi-agent slime-mold model: agents deposit and follow a trail map, producing self-organising vein-like networks that join points of interest. ## Reach for it when - want organic vein or root-like networks - generate city-like path networks connecting points - need slime-mould style generative art - branching network textures from simple agents ## How it works Thousands of agents carry a position and heading. Each step an agent samples the trail map at three sensors (left, ahead, right) at a sensor distance, turns toward the strongest, moves forward a fixed step, and deposits chemoattractant at its position. The trail map is then diffused (blur) and decayed. This feedback concentrates flow into thin lines that merge and prune into transport-network graphs, and food sources or heightmaps bias agents toward targets. On the GPU the agents run in a compute pass and the trail map is a ping-pong texture. Parameters (sensor angle and distance, turn speed, decay, diffusion) change the look from filaments to webs to blobs. ## When to use it Choose it for organic network, vein, root and city-like path structures, or generative art with an agent-driven look. Prefer [Gray-Scott reaction-diffusion](https://texelatlas.vercel.app/t/gray-scott-reaction-diffusion.md) for spot/stripe/maze patterns, [Boids flocking](https://texelatlas.vercel.app/t/boids.md) for flocks that do not need a persistent trail, and graph algorithms (MST, Steiner) when you need an exact optimal network. ## Cost cheap — Cheap-to-medium: agent count x 3 samples, plus blur of the trail map. Measured GPU Weight: 23.08× baseline (heavy) — 0.7593 ms median / 0.8363 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 23.07× baseline (heavy) — 0.3668 ms median (2.07× faster on L4). Ampere A100 scaling: 15.05× baseline (moderate) — 0.4335 ms median (1.75× faster on A100). ## Failure modes - Result is sensitive to parameters: collapses into dots or saturates into blobs - Agents clump in corners and borders unless boundary rules are added - Trail-map resolution limits how thin the lines can get - Not a real graph: extracting a clean network needs thinning and cleanup ## Dataflow - Inputs: particles, texture - Outputs: texture, graph - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Physarum transport networks — emergent slime-mould branching veins & chemotaxis flux (glsl-fragment; rendered 2026-11-30) ```json { "P_VEIN_SHARPNESS": 1.2, "P_FLUX_SPEED": 1, "P_BRANCH_SCALE": 5.5, "P_NODE_GLOW": 1.1 } ``` ```glsl const float P_VEIN_SHARPNESS = 1.2; // P Vein Sharpness [0.4, 2.5, 0.05] const float P_FLUX_SPEED = 1.0; // P Flux Speed [0.0, 2.5, 0.05] const float P_BRANCH_SCALE = 5.5; // P Network Scale [2.5, 10.0, 0.2] const float P_NODE_GLOW = 1.1; // P Nutrient Glow [0.0, 2.2, 0.05] vec2 hash22(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); } // Smooth Voronoi edge distance (F2 - F1) yielding organic anastomosing transport ridges vec3 voronoiVein(vec2 p, float t) { vec2 n = floor(p); vec2 f = fract(p); float d1 = 8.0, d2 = 8.0; vec2 bestOff = vec2(0.0); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 g = vec2(float(i), float(j)); vec2 o = hash22(n + g); o = 0.5 + 0.38 * sin(t * 0.45 + 6.2831 * o); vec2 r = g + o - f; float d = dot(r, r); if (d < d1) { d2 = d1; d1 = d; bestOff = r; } else if (d < d2) { d2 = d; } } } float edge = sqrt(d2) - sqrt(d1); return vec3(edge, sqrt(d1), atan(bestOff.y, bestOff.x)); } // Organic domain warp to mimic adaptive chemotaxis meandering vec2 warp(vec2 p, float t) { float a = sin(p.x * 2.1 + t * 0.3) * cos(p.y * 2.3 - t * 0.25); float b = cos(p.x * 1.9 - t * 0.22) * sin(p.y * 2.5 + t * 0.28); return p + 0.14 * vec2(a, b); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float t = iTime * max(P_FLUX_SPEED, 0.0); float scale = clamp(P_BRANCH_SCALE, 2.0, 12.0); float sharp = clamp(P_VEIN_SHARPNESS, 0.3, 3.0); // Petri dish dark agar backdrop with subtle radial depth vec3 bg = mix(vec3(0.015, 0.024, 0.032), vec3(0.035, 0.055, 0.068), smoothstep(0.65, 0.0, length(uv))); // Three hierarchical Physarum transport vein scales (primary trunks, secondary vessels, fine capillaries) vec2 wp = warp(uv, t * 0.6); vec3 v1 = voronoiVein(wp * scale * 0.62, t * 0.4); vec3 v2 = voronoiVein(wp * scale * 1.25 + vec2(3.7, 1.9), t * 0.65); vec3 v3 = voronoiVein(wp * scale * 2.55 - vec2(1.4, 4.2), t * 0.85); // Peristaltic shuttle-streaming pulse traveling along veins float pulse1 = 0.65 + 0.35 * sin(v1.z * 3.0 - t * 3.4 + length(uv) * 8.0); float pulse2 = 0.65 + 0.35 * sin(v2.z * 4.0 + t * 4.2 - length(uv) * 12.0); // Nutrient food nodes anchoring high-flux primary highways float nodeField = 0.0; float nodeCore = 0.0; for (int i = 0; i < 6; i++) { float fi = float(i); float ang = fi * 1.0472 + 0.25 * sin(t * 0.2 + fi); float rad = 0.26 + 0.11 * sin(fi * 2.1 + 0.4); vec2 np = vec2(cos(ang), sin(ang)) * rad; float d = length(uv - np); nodeField += exp(-d * 4.8); nodeCore += exp(-d * 24.0); } float colonyMask = smoothstep(0.62, 0.14, length(uv) - 0.08 * nodeField); // Adaptive vein thickness reinforced near nutrient sources float trunk = exp(-v1.x * (12.0 * sharp / (0.75 + 0.65 * nodeField))) * pulse1; float branch = exp(-v2.x * (17.0 * sharp)) * pulse2 * (0.45 + 0.55 * trunk + 0.35 * nodeField); float capil = exp(-v3.x * (24.0 * sharp)) * (0.28 + 0.6 * branch); float density = (trunk * 1.15 + branch * 0.72 + capil * 0.38) * colonyMask; // Chemotaxis agent micro-sparks streaming through the veins float agentWave = 0.5 + 0.5 * sin(v1.y * 42.0 - t * 6.0) * cos(v2.y * 36.0 + t * 5.0); float agents = pow(agentWave, 4.0) * smoothstep(0.2, 0.85, trunk + branch * 0.6); // Bioluminescent Physarum gold/amber core with cyan chemotaxis trail halo vec3 trailHalo = vec3(0.08, 0.42, 0.52) * pow(clamp(density, 0.0, 1.0), 0.7) * 0.65; vec3 veinGold = vec3(1.15, 0.78, 0.18) * pow(clamp(density, 0.0, 1.4), 1.35); vec3 veinCore = vec3(1.45, 1.28, 0.72) * smoothstep(0.62, 1.35, density) * 0.85; vec3 sparkCol = vec3(0.45, 1.0, 0.85) * agents * 0.85; vec3 foodCol = vec3(0.28, 0.92, 1.15) * nodeCore * max(P_NODE_GLOW, 0.0) * 1.1; vec3 col = bg + trailHalo + veinGold + veinCore + sparkCol + foodCol; // Faint petri dish rim float rim = smoothstep(0.012, 0.0, abs(length(uv) - 0.46)); col += vec3(0.14, 0.24, 0.32) * rim * 0.4; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combination ideas - [Cities wired by slime mould](https://texelatlas.vercel.app/ideas/slime-mould-road-networks/) ## Sources 1. [primary] Jeff Jones (2010) Characteristics of Pattern Formation and Evolution in Approximations of Physarum Transport Networks. Artificial Life. https://doi.org/10.1162/artl.2010.16.2.16202 (verified via crossref on 2026-11-29) 2. [tutorial] Sage Jenson physarum. cargocollective.com. https://cargocollective.com/sagejenson/physarum (verified via http on 2026-11-29) ## Cite this entry Texel. "Physarum agent transport networks." https://texelatlas.vercel.app/t/physarum-transport-networks/ (accessed 2026-12-01). --- id: "physical-light-units-and-exposure" title: "Physical light units, photometry and camera exposure" aliases: [EV100 exposure, photometric units, lux and lumen lighting, physically based camera] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal, godot, blender] year_introduced: 2014 inputs: [radiance, material-params] outputs: [hdr-image] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Lagarde & Rousiers" url: "https://texelatlas.vercel.app/t/physical-light-units-and-exposure/" sources_verified_at: "2026-11-29" --- # Physical light units, photometry and camera exposure (Lagarde & Rousiers) > Author lights in photometric units (lux, lumens, candela, nits) and convert scene radiance to display values with an exposure derived from aperture, shutter and ISO, so lighting stays consistent across sun, lamps and screens. ## Reach for it when - sun and lamps have inconsistent relative brightness - want camera-like aperture shutter and iso controls - scene is blown out or black after changing lights - how to set light intensity in real world units ## How it works Photometric lighting specifies each source with a measured quantity: illuminance in lux for the sun, luminous power in lumens or intensity in candela for lamps, luminance in nits for emissive surfaces. A Lambertian surface with albedo `a` under illuminance `E` has outgoing luminance `a * E / pi`, so these numbers drive shading directly and an overcast day, a living room and a night street come out at plausible ratios. The frame buffer stores scene-referred luminance, which spans many orders of magnitude, so a virtual camera is applied before tonemapping. Exposure value is `EV100 = log2(N^2 / t * 100 / S)` for aperture N, shutter t and ISO S; a saturation-based convention divides luminance by `1.2 * 2^EV100`, and mid-grey ends up near 0.18 when EV matches the scene. Auto exposure ([auto-exposure-histogram](auto-exposure-histogram)) picks the EV from the image. Good practice is to keep lights in physical units, set one exposure value, and apply tonemapping afterwards, as described in the Frostbite PBR course notes; glTF's punctual-light extension fixes lux and candela as the exchange units. ## When to use it Choose it whenever more than one light type shares a scene, when scenes must be relit at different times of day, or when you need artist-friendly camera controls (aperture, shutter, ISO) that behave like photography. Prefer [auto-exposure-histogram](auto-exposure-histogram) to drive the EV automatically on top of physical units rather than replacing them. Prefer [agx-tonemapping](agx-tonemapping), [aces-tonemapping](aces-tonemapping) or [khronos-pbr-neutral](khronos-pbr-neutral) for the display transform applied after exposure. Skip full photometry for stylised or UI-lit scenes where unitless intensities are fine; see [toon-shading](toon-shading). ## Cost cheap — Only a multiplier and unit conversions per light; the cost is pipeline discipline, not runtime. Measured GPU Weight: 1.32× baseline (feather) — 0.0433 ms median / 0.0448 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.15× baseline (feather) — 0.0183 ms median (2.37× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.5× faster on A100). ## Failure modes - Mixing unitless and photometric lights gives sun and lamps wildly different relative brightness - Half-float buffers overflow with sun-level luminance unless exposure is pre-applied in the lighting pass - Lumens to candela conversion forgotten for spot lights (the cone solid angle must be taken into account) - Exposure jumps when moving between bright and dark areas appear as flicker if adaptation is not smoothed - Emissive materials authored in 0 to 1 look black next to a 100000 lux sun - Bloom thresholds expressed in unexposed units fire everywhere or nowhere ## Engine support - babylonjs: builtin — `light.intensityMode = Light.INTENSITYMODE_LUMINOUSPOWER (or LUMINOUSINTENSITY / ILLUMINANCE / LUMINANCE) with scene.imageProcessingConfiguration.exposure` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/light.ts, checked 2026-12-01) - godot: builtin — `CameraAttributesPhysical (aperture, shutter, ISO) on Camera3D/Environment; Light3D.light_intensity_lumens/lux` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/CameraAttributesPhysical.xml, checked 2026-12-01) - threejs: builtin — `PointLight/SpotLight intensity in candela (cd), .power in lumens (lm), WebGLRenderer.toneMappingExposure` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/lights/PointLight.js, checked 2026-12-01) - unity: builtin — `HDRP Volume > Exposure; Light > Intensity unit Lux/Lumen/Candela/EV100` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Physical-Light-Units.md, checked 2026-12-01) — HDRP. - unreal: builtin — `Light > Intensity Units (Candelas, Lumens, EV, Nits); camera or Post Process Volume > Exposure (EV100)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/point-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: radiance, material-params - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal, godot, blender ## Presets ### Sunlit grey sphere across EV100 11 to 19 (glsl-fragment; rendered 2026-11-29) ```json { "sun_lux": 100000, "albedo": 0.18, "ev_first": 11, "columns": 9 } ``` ```glsl // Exposure ladder: one sunlit sphere rendered at EV100 = 11..19 (scene-referred luminance, then camera exposure). const float SUN_LUX = 100000.0; // clear-day sun illuminance const float ALBEDO = 0.18; // grey card const float EV_FIRST = 11.0; const float COLS = 9.0; vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float cell = floor(uv.x * COLS); vec2 p = vec2(fract(uv.x * COLS) - 0.5, (uv.y - 0.55) * COLS * iResolution.y / iResolution.x * 1.0); float ev100 = EV_FIRST + cell; float exposure = 1.0 / (1.2 * exp2(ev100)); // saturation-based exposure vec3 L = normalize(vec3(-0.5, 0.6, 0.6)); float r2 = dot(p, p); vec3 radiance; if (r2 < 0.2) { vec3 n = vec3(p, sqrt(0.2 - r2) / sqrt(0.2)); n = normalize(vec3(p / sqrt(0.2), n.z)); float ndl = max(dot(n, L), 0.0); vec3 sky = vec3(0.35, 0.5, 0.8) * 12000.0 * (0.5 + 0.5 * n.y); // sky illuminance in lux radiance = ALBEDO / 3.14159 * (SUN_LUX * ndl * vec3(1.0, 0.96, 0.9) + sky); } else { float g = 0.5 + 0.5 * uv.y; radiance = vec3(0.30, 0.45, 0.70) * 2500.0 * g; // bright sky background, cd/m^2 } vec3 c = aces(radiance * exposure); c *= 0.6 + 0.4 * smoothstep(0.0, 0.01, abs(fract(uv.x * COLS) - 0.5) * -1.0 + 0.5); fragColor = vec4(pow(c, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Auto exposure from luminance histogram](https://texelatlas.vercel.app/t/auto-exposure-histogram.md): Photometric luminance goes in; the histogram metering chooses the EV100 that scales it into display range. - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): Exposed scene-referred values are the input to the display transform; getting units right first avoids tuning the tonemapper to hide lighting errors. - [Linearly Transformed Cosines for Area Lights](https://texelatlas.vercel.app/t/ltc-area-lights.md): Area emitters specified in nits or lumens integrate to the same physical radiance as punctual lights when units are consistent. ## Sources 1. [primary] Sébastien Lagarde, Charles de Rousiers Moving Frostbite to Physically Based Rendering. SIGGRAPH 2014 course. https://seblagarde.wordpress.com/wp-content/uploads/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf (verified via http on 2026-11-29) 2. [primary] KHR_lights_punctual. github.com. https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_lights_punctual (verified via http on 2026-11-29) 3. [tutorial] Romain Guy, Mathias Agopian Filament: Physically based rendering (image based lights section). google.github.io. https://google.github.io/filament/Filament.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Physical light units, photometry and camera exposure." https://texelatlas.vercel.app/t/physical-light-units-and-exposure/ (accessed 2026-12-01). --- id: "pixel-art-3d-rendering" title: "Pixel-art 3D rendering" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, godot] inputs: [gbuffer, ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Wikipedia" url: "https://texelatlas.vercel.app/t/pixel-art-3d-rendering/" sources_verified_at: "2026-11-29" --- # Pixel-art 3D rendering (Wikipedia) > Renders a 3D scene at a very low resolution, snaps the camera to the pixel grid, and applies palette limiting and outlines so the result looks like hand-placed pixel art. ## Reach for it when - 3d game should look like pixel art - want retro low-res style with 3d assets - pixel crawl and shimmering when camera moves in low res - limited palette with outlines on a 3d scene - isometric hand-placed pixel look from models ## How it works The scene is rendered to a small offscreen target (for example 320×180) with point sampling and upscaled by an integer factor. To avoid crawling pixels, the camera is moved in whole texel steps: the camera position is snapped to a world-space grid corresponding to one low-res pixel, and the sub-texel offset is applied to the final blit. Shading is posterized and colours are mapped to a fixed palette, optionally with Bayer dither, and edge detection on depth and normals draws one-pixel outlines. Textures often have to be unfiltered or authored at matching texel density. Sprite-based models use the same trick. ## When to use it Choose it for a retro 2.5D or isometric style with 3D assets and lighting. Prefer [Ordered dithering with Bayer matrices](https://texelatlas.vercel.app/t/ordered-dithering-bayer.md) plus [Posterization](https://texelatlas.vercel.app/t/posterization.md) if you only need a pattern look at full resolution, and [OKLab palette quantization](https://texelatlas.vercel.app/t/oklab-palette-quantization.md) for an accurate nearest-palette mapping. ## Cost cheap — Cheaper than full-resolution rendering since the scene is drawn at tiny resolution. Measured GPU Weight: 3.74× baseline (light) — 0.123 ms median / 0.1331 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.1× baseline (light) — 0.0493 ms median (2.49× faster on L4). Ampere A100 scaling: 2.18× baseline (light) — 0.0629 ms median (1.96× faster on A100). ## Failure modes - Camera movement without sub-pixel compensation makes edges crawl or shimmer - Thin geometry and small details alias into noise at low resolution - Rotating objects show pixel flicker as their silhouettes cross texel boundaries - Palette mapping creates band steps and hue shifts on gradients ## Engine support - threejs: official — `import { pixelationPass } from 'three/addons/tsl/display/PixelationPassNode.js' (WebGL: RenderPixelatedPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/PixelationPassNode.js, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, godot ## Presets ### Left: smooth render. Right: 6px cells sampled at cell centres, 5-level palette, depth outline (glsl-fragment; rendered 2026-11-29) ```json { "PX": 8, "LV": 6 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float PX=8.0; // P const float LV=6.0; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 col; if(!R) col=shadeBasic(uv); else{ vec2 cell=floor(fragCoord/PX),c=(cell+.5)*PX,cu=(c-.5*iResolution.xy)/iResolution.y-vec2(.25,0.); col=gam(shadeBasic(cu));col=floor(col*LV+.5)/LV; float z0=zbuf(cu),z1=zbuf(cu+vec2(PX,0.)/512.),z2=zbuf(cu+vec2(0.,PX)/512.); if(min(z0,z1)<25.&&(abs(z0-z1)>.25*min(z0,z1)||abs(z0-z2)>.25*min(z0,z2)))col=vec3(.1,.07,.15); col=pow(col,vec3(2.2)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Combines with - [OKLab palette quantization](https://texelatlas.vercel.app/t/oklab-palette-quantization.md): Low-res render is mapped to a fixed palette by nearest colour in OKLab. - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): One-pixel outlines from depth and normal edges. ## Combination ideas - [Palette-true pixel art with soft GI](https://texelatlas.vercel.app/ideas/cascade-gi-pixel-art/) ## Sources 1. [primary] Wikipedia Pixel art. en.wikipedia.org. https://en.wikipedia.org/wiki/Pixel_art (verified via http on 2026-11-29) ## Cite this entry Texel. "Pixel-art 3D rendering." https://texelatlas.vercel.app/t/pixel-art-3d-rendering/ (accessed 2026-12-01). --- id: "planar-reflections-oblique-clipping" title: "Planar reflections with oblique near-plane clipping" aliases: [mirror reflection pass, water plane reflection render, oblique frustum clipping, Lengyel oblique clipping] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2004 inputs: [mesh] outputs: [radiance, texture] style: "both" dynamic: "dynamic" cost: "medium" authority: "Lengyel, 2005" url: "https://texelatlas.vercel.app/t/planar-reflections-oblique-clipping/" sources_verified_at: "2026-11-29" --- # Planar reflections with oblique near-plane clipping (Lengyel, 2005) > Render the scene a second time from a camera mirrored across a plane, with the near clipping plane replaced by the mirror plane so nothing behind it is drawn. The texture then supplies exact reflections for a flat surface. ## Reach for it when - need exact mirror or water reflections on a flat plane - objects below the water show up in the reflection - reflection render includes geometry behind the mirror - want a cheap clean reflection for a polished floor ## How it works For a flat reflector, the reflection equals the scene seen from a virtual camera reflected through the plane. Build the reflected view matrix, render into a texture, and sample that texture on the mirror in screen space (optionally offset by a normal map for water ripples). Two problems need care. Geometry between the reflected camera and the mirror, which lies behind the real mirror plane, must be clipped or it appears in the reflection. User clip planes are not always available and cost shader work, so the standard fix modifies the projection matrix: the near plane is replaced by the mirror plane, giving an oblique frustum. The projection is adjusted by Lengyel's method, which rewrites the third row of the matrix from the clip-space plane and scales it to keep the far plane in range. Render triangle winding flips with the mirrored transform, so culling must be reversed. Cost is a second scene pass, so use a lower resolution, fewer shadow casters and a layer mask. ## When to use it Choose it for a single flat reflector with exact, dynamic reflections: mirrors, calm water, polished floors, TV screens. Prefer [screen-space-reflections](screen-space-reflections) when several surfaces need glossy reflections without extra passes and some missing off-screen content is acceptable. Prefer [reflection-probes-parallax-corrected-cubemaps](reflection-probes-parallax-corrected-cubemaps) for many rough or curved reflectors where one cubemap approximation is enough. Prefer [hybrid-ray-traced-reflections](hybrid-ray-traced-reflections) for arbitrary geometry on ray-tracing hardware. For rippling water combine with [gerstner-waves](gerstner-waves) or [flow-map-water](flow-map-water) normals. ## Cost medium — A full second geometry pass at reduced resolution; cost grows with scene complexity and shadow casters visible in the mirror. Measured GPU Weight: 19.67× baseline (moderate) — 0.6098 ms median / 0.6509 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.47× baseline (moderate) — 0.2777 ms median (2.2× faster on L4). Ampere A100 scaling: 12.83× baseline (moderate) — 0.3695 ms median (1.65× faster on A100). ## Failure modes - Objects below the water or behind the mirror leak into the reflection when the oblique clip is missing or wrong - Depth precision collapses if the oblique near plane is steep, so distant reflected geometry z-fights - Culling winding is not flipped, giving inside-out reflected meshes or missing faces - Reflection texture is a frame late when the camera moves quickly, producing a visible lag at the mirror's edges - Multiple mirrors need one pass each, and recursive mirror-in-mirror views blow up cost - Roughness cannot be handled without blur; a single sharp texture makes frosted floors look like perfect mirrors ## Engine support - babylonjs: builtin — `new MirrorTexture(name, size, scene); mirrorTexture.mirrorPlane = plane` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Textures/mirrorTexture.pure.ts, checked 2026-12-01) - blender: builtin — `Add > Light Probe > Plane` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_probes/plane.html, checked 2026-12-01) — EEVEE only; oblique clipping is not documented. - threejs: official — `import { Reflector } from 'three/addons/objects/Reflector.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/objects/Reflector.js, checked 2026-12-01) - unity: builtin — `HDRP: Planar Reflection Probe` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Planar-Reflection-Probe.md, checked 2026-12-01) — HDRP only. - unreal: builtin — `Place a Planar Reflection actor` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/reflections-environment-in-unreal-engine, checked 2026-12-01) — Planar reflection actor; oblique clipping is not documented. ## Dataflow - Inputs: mesh - Outputs: radiance, texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Planar Reflections & Oblique Clipping — unclipped submerged leak (left) vs oblique-clipped mirror (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RIPPLE_AMP": 0.35, "P_SUBMERGED_VIS": 1, "P_SUN_ANGLE": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_RIPPLE_AMP = 0.35; // P Water Ripple [0.0, 1.2, 0.03] const float P_SUBMERGED_VIS = 1.0; // P Leak Contrast [0.2, 1.8, 0.05] const float P_SUN_ANGLE = 0.65; // P Orbit Speed [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Unclipped / Oblique [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } 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); } // Scene above reflection plane (y > 0) AND submerged red-orange obstacle below plane (y < 0)! vec2 mapWorld(vec3 p, float t, bool clipBelow) { // Above-water rotating golden torus sculpture + glowing cyan ring + pillars vec3 q = p - vec3(0.0, 0.56, -0.35); q.xz = rot2(t * 0.75) * q.xz; q.xy = rot2(0.55) * q.xy; vec2 res = vec2(sdTorus(q, vec2(0.36, 0.11)), 2.0); float dOrb = length(p - vec3(0.0, 0.56 + 0.08 * sin(t * 1.8), -0.35)) - 0.15; if (dOrb < res.x) res = vec2(dOrb, 3.0); float dPilL = sdBox(p - vec3(-0.92, 0.48, -0.85), vec3(0.14, 0.48, 0.14)) - 0.02; if (dPilL < res.x) res = vec2(dPilL, 4.0); float dPilR = sdBox(p - vec3(0.92, 0.48, -0.85), vec3(0.14, 0.48, 0.14)) - 0.02; if (dPilR < res.x) res = vec2(dPilR, 4.0); // Submerged bright crimson truss/box sitting BELOW y = 0 between mirrored camera and reflection plane! // Without oblique near-plane clipping, the mirrored camera hits this submerged box and corrupts the reflection! if (!clipBelow) { float dSub = sdBox(p - vec3(0.0, -0.44, 0.45), vec3(0.58, 0.28, 0.22)); if (dSub < res.x) res = vec2(dSub, 5.0); } return res; } vec3 calcNormal(vec3 p, float t, bool clipBelow) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapWorld(p + e.xyy, t, clipBelow).x - mapWorld(p - e.xyy, t, clipBelow).x, mapWorld(p + e.yxy, t, clipBelow).x - mapWorld(p - e.yxy, t, clipBelow).x, mapWorld(p + e.yyx, t, clipBelow).x - mapWorld(p - e.yyx, t, clipBelow).x )); } vec3 shadeSky(vec3 rd) { float h = clamp(rd.y * 0.5 + 0.5, 0.0, 1.0); vec3 sky = mix(vec3(0.09, 0.14, 0.24), vec3(0.24, 0.42, 0.72), pow(h, 0.8)); vec3 sun = normalize(vec3(0.55, 0.42, -0.72)); sky += vec3(1.8, 1.25, 0.75) * pow(max(dot(rd, sun), 0.0), 28.0); return sky; } vec3 traceScene(vec3 ro, vec3 rd, float t, bool clipBelow, float leakGain) { float dSum = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { vec3 p = ro + rd * dSum; vec2 h = mapWorld(p, t, clipBelow); if (h.x < 0.0022) { hit = true; matId = h.y; break; } dSum += h.x; if (dSum > 8.5) break; } if (!hit) return shadeSky(rd); vec3 p = ro + rd * dSum; vec3 n = calcNormal(p, t, clipBelow); vec3 lDir = normalize(vec3(0.55, 0.80, 0.35)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 48.0); if (matId > 4.5) { // Corrupted submerged geometry leaking into unclipped reflection float stripe = smoothstep(0.45, 0.55, sin((p.x + p.y) * 32.0)); return mix(vec3(0.95, 0.16, 0.12), vec3(1.15, 0.55, 0.10), stripe) * (0.55 + 0.65 * diff) * leakGain; } if (matId > 2.5 && matId < 3.5) { return vec3(0.22, 1.45, 1.85) * (0.65 + 0.5 * diff) + vec3(0.9) * spec; } vec3 alb = (matId < 2.5) ? vec3(0.92, 0.68, 0.24) : vec3(0.62, 0.68, 0.78); return alb * (0.24 + 0.85 * diff) + vec3(1.0, 0.95, 0.85) * spec * 0.65; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useObliqueClip = screenX >= split; float ripple = clamp(P_RIPPLE_AMP, 0.0, 1.2); float leakGain = clamp(P_SUBMERGED_VIS, 0.2, 2.0); float t = iTime * max(P_SUN_ANGLE, 0.0); vec3 ro = vec3(0.0, 0.68, 2.18); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.04), -1.48)); // First trace primary camera above plane y = 0 float tPlane = (rd.y < -0.001) ? ((0.0 - ro.y) / rd.y) : 1e5; float dPrimary = 0.0; float matId = 0.0; bool hitAbove = false; for (int i = 0; i < 56; i++) { vec3 p = ro + rd * dPrimary; if (dPrimary > tPlane) break; vec2 h = mapWorld(p, t, true); if (h.x < 0.0022) { hitAbove = true; matId = h.y; break; } dPrimary += h.x; if (dPrimary > 8.5) break; } vec3 col = vec3(0.0); if (hitAbove) { col = traceScene(ro, rd, t, true, leakGain); } else if (tPlane < 12.0) { // Hit glossy water/marble mirror plane y = 0 vec3 pFloor = ro + rd * tPlane; vec2 wGrad = vec2( cos(pFloor.x * 7.5 + t * 2.1) * sin(pFloor.z * 6.2 - t * 1.4), sin(pFloor.x * 6.4 - t * 1.6) * cos(pFloor.z * 8.1 + t * 1.9) ) * 0.045 * ripple; vec3 nPlane = normalize(vec3(wGrad.x, 1.0, wGrad.y)); // Mirrored virtual camera across y = 0: ro_m = (ro.x, -ro.y, ro.z) vec3 roMirror = vec3(ro.x, -ro.y, ro.z); vec3 rdMirror = normalize(pFloor - roMirror + vec3(wGrad.x, 0.0, wGrad.y) * 0.8); // Core technique: // Left (no oblique clip): ray starts at mirrored camera BELOW y=0 and hits submerged box! // Right (oblique near plane at y=0): ray starts clipped at pFloor on y=0, rejecting everything below! vec3 reflCol = useObliqueClip ? traceScene(pFloor + vec3(0.0, 0.004, 0.0), rdMirror, t, true, leakGain) : traceScene(roMirror, rdMirror, t, false, leakGain); float fresnel = 0.16 + 0.84 * pow(1.0 - max(dot(nPlane, -rd), 0.0), 4.0); float tile = mod(floor(pFloor.x * 1.8) + floor(pFloor.z * 1.8), 2.0); vec3 floorBase = mix(vec3(0.04, 0.07, 0.11), vec3(0.08, 0.12, 0.18), tile); col = mix(floorBase, reflCol, clamp(fresnel * 0.92, 0.25, 0.96)); } else { col = shadeSky(rd); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Gerstner (Trochoidal) Waves](https://texelatlas.vercel.app/t/gerstner-waves.md): Wave normals distort the planar reflection lookup so the water surface looks rippled. - [Flow-map water animation](https://texelatlas.vercel.app/t/flow-map-water.md): A flowing normal map perturbs the reflected texture coordinates for moving water. ## Combination ideas - [Mirrored refractive caustics via photon mapping and oblique planar reflections](https://texelatlas.vercel.app/ideas/caustic-photon-map-planar-reflections/) - [Oblique-clipped planar reflections on sloshing FLIP fluid pools](https://texelatlas.vercel.app/ideas/flip-fluid-oblique-planar-reflections/) ## Sources 1. [primary] Eric Lengyel (2005) Oblique View Frustum Depth Projection and Clipping. Journal of Game Development, 2005. http://www.terathon.com/lengyel/Lengyel-Oblique.pdf (verified via http on 2026-11-30) 2. [implementation] three.js contributors three.js Reflector, planar reflection with oblique near-plane clipping. github.com. https://github.com/mrdoob/three.js/blob/dev/examples/jsm/objects/Reflector.js (verified via http on 2026-11-29) ## Cite this entry Texel. "Planar reflections with oblique near-plane clipping." https://texelatlas.vercel.app/t/planar-reflections-oblique-clipping/ (accessed 2026-12-01). --- id: "point-e" title: "Point-E" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2022 inputs: [text-prompt] outputs: [point-cloud] style: "stylized" dynamic: "static" cost: "heavy" authority: "Nichol et al., 2022" url: "https://texelatlas.vercel.app/t/point-e/" sources_verified_at: "2026-11-29" --- # Point-E (Nichol et al., 2022) > A fast two-stage text-to-3D pipeline: a text-to-image diffusion model makes a synthetic view, then a point-cloud diffusion model conditioned on that image produces a coloured point cloud. ## Reach for it when - generate a quick 3d point cloud from text - need fast text to 3d on modest compute - make rough 3d shapes from a prompt in minutes - image conditioned point cloud generation ## How it works Stage one fine-tunes a text-to-image model to produce a clean, centred "synthetic view" of the prompt. Stage two is a transformer-based diffusion model that takes the image embedding and denoises a small set of coloured points (on the order of a thousand), followed by a second upsampler diffusion model that adds more points. The cloud can be turned into a mesh with a separate SDF regression and marching-cubes step. Because both stages are ordinary diffusion sampling with no per-asset optimisation, generation takes about as long as a few image samples rather than hours. ## When to use it Choose it for quick, coarse previews or as a historical baseline for feed-forward text-to-3D. Prefer [Shap-E](https://texelatlas.vercel.app/t/shap-e.md) when you want a mesh or NeRF output straight from the same lab's later model, and [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) or [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) when you need production-grade geometry and textures. ## Cost heavy — Seconds to a minute per sample on one GPU according to the authors' framing; no figures reproduced here. ## Failure modes - Sparse point output loses thin parts and fine surfaces - Colours are per-point and low resolution, so no real texture - Meshing from the cloud gives lumpy or non-watertight surfaces - Fails on compositional prompts with several objects - Synthetic-view stage can already be wrong, and the cloud inherits that ## Dataflow - Inputs: text-prompt - Outputs: point-cloud - Platforms: cuda, python ## Combination ideas - [Trees grown into a described shape](https://texelatlas.vercel.app/ideas/text-shaped-tree-crowns/) ## Sources 1. [primary] Alex Nichol, Heewoo Jun, Prafulla Dhariwal, Pamela Mishkin, Mark Chen (2022) Point-E: A System for Generating 3D Point Clouds from Complex Prompts. arXiv preprint (cs.CV). https://arxiv.org/abs/2212.08751 (verified via arxiv on 2026-11-29) 2. [implementation] openai (2022) openai/point-e. https://github.com/openai/point-e License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Point-E." https://texelatlas.vercel.app/t/point-e/ (accessed 2026-12-01). --- id: "poisson-disk-sampling" title: "Poisson Disk Sampling (Bridson)" aliases: [blue-noise point sampling, dart throwing with grid acceleration] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [cpu, python, webgl2, unity, unreal, godot, houdini] year_introduced: 2007 outputs: [point-cloud] style: "both" dynamic: "static" cost: "cheap" authority: "Bridson, 2007" url: "https://texelatlas.vercel.app/t/poisson-disk-sampling/" sources_verified_at: "2026-11-29" --- # Poisson Disk Sampling (Bridson) (Bridson, 2007) > Generates random points that are no closer than a minimum radius and fill space evenly, using a background grid and an active list so it runs in linear time in any dimension. ## Reach for it when - random scattering clumps and leaves gaps - need evenly spaced trees, rocks or grass clumps - points must keep a minimum distance apart - generate blue-noise sample positions quickly ## How it works A background grid with cell size r/sqrt(n) stores at most one sample per cell, so a distance check against neighbours is a constant-time lookup of a small window. Start with one random sample in the active list. Repeatedly pick a random active sample, try up to k (about 30) candidates in the annulus between r and 2r around it, and accept the first candidate that is at least r from all existing samples by checking nearby grid cells; add it to the grid and list. If none of the k candidates works, remove the sample from the active list. When the list empties the domain is filled to near-maximal coverage. Variable-radius versions let r depend on position for density maps, and tileable versions wrap the grid. ## When to use it Choose it for evenly spaced scattering: trees, rocks, grass clumps, lights, attractor points and sample patterns, where uniform random clumps look bad. Prefer [Plant Ecosystem Distribution Simulation](https://texelatlas.vercel.app/t/ecosystem-plant-distribution.md) when ecology (species, competition) matters, [Voronoi Diagrams and Lloyd Relaxation](https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation.md) when you want even cells and are fine with an iterative relaxation, and [Worley (Cellular) Noise](https://texelatlas.vercel.app/t/worley-noise.md) when you want per-pixel feature points without storing any samples. ## Cost cheap — O(N) in number of points; millions of points feasible on CPU, but not per-pixel on GPU. Measured GPU Weight: 223.09× baseline (extreme) — 7.3398 ms median / 7.4215 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 203.55× baseline (extreme) — 3.2364 ms median (2.27× faster on L4). Ampere A100 scaling: 138.15× baseline (extreme) — 3.9788 ms median (1.84× faster on A100). ## Failure modes - Not strictly maximal: the k-candidate limit leaves small holes - Output is stateful and sequential, hard to evaluate per-pixel in a shader without precomputation or tiling - Variable-radius density gradients that change faster than r produce visible banding - Hard boundaries cause edge effects: samples cluster against domain borders unless padded - Tileable versions with naive wrapping show duplicated seam rows ## Engine support - blender: builtin — `Geometry Nodes > Distribute Points on Faces > Poisson Disk` (evidence: https://docs.blender.org/manual/en/5.2/modeling/geometry_nodes/point/distribute_points_on_faces.html, checked 2026-12-01) - unreal: builtin — `Geometry Script > GeometryScript_MeshSampling.compute_point_sampling with GeometryScriptMeshPointSamplingOptions (Poisson disk sampling_radius)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/GeometryScriptMeshPointSamplingOptions, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: point-cloud - Platforms: cpu, python, webgl2, unity, unreal, godot, houdini ## Presets ### Poisson disk samples via parallel priority dart throwing, with exclusion discs (glsl-fragment; rendered 2026-11-29) ```json { "CELL": 0.055, "RADIUS": 0.085 } ``` ```glsl // Parallel dart-throwing Poisson disk: one random candidate per grid cell, kept only if no nearby candidate has higher priority. const float CELL = 0.055; const float RADIUS = 0.085; // minimum allowed distance between kept points float h21(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } vec2 cand(vec2 c) { return (c + 0.15 + 0.7 * vec2(h21(c), h21(c + 17.3))) * CELL; } bool kept(vec2 c) { vec2 p = cand(c); float pr = h21(c + 5.1); for (int j = -2; j <= 2; j++) for (int i = -2; i <= 2; i++) { if (i == 0 && j == 0) continue; vec2 o = c + vec2(i, j); if (length(cand(o) - p) < RADIUS && h21(o + 5.1) > pr) return false; } return true; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 cell = floor(uv / CELL); vec3 col = vec3(0.06, 0.07, 0.1); float dmin = 1e9; for (int j = -2; j <= 2; j++) for (int i = -2; i <= 2; i++) { vec2 c = cell + vec2(i, j); if (kept(c)) { float d = length(uv - cand(c)); dmin = min(dmin, d); col += vec3(0.1, 0.2, 0.3) * smoothstep(0.004, 0.0, abs(d - RADIUS * 0.5)); } } col = mix(col, vec3(1.0, 0.8, 0.4), smoothstep(0.009, 0.006, dmin)); col += vec3(0.04, 0.07, 0.1) * smoothstep(RADIUS * 0.5, 0.0, dmin); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Combines with - [Voronoi Diagrams and Lloyd Relaxation](https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation.md): Poisson samples seed the Voronoi diagram that Lloyd relaxation then evens out. ## Sources 1. [primary] Robert Bridson (2007) Fast Poisson disk sampling in arbitrary dimensions. ACM SIGGRAPH 2007 sketches. https://doi.org/10.1145/1278780.1278807 (verified via crossref on 2026-11-29) 2. [primary] Robert Bridson Fast Poisson Disk Sampling in Arbitrary Dimensions. cs.ubc.ca. https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf (verified via http on 2026-11-29) 3. [implementation] kchapelier (2015) kchapelier/poisson-disk-sampling. https://github.com/kchapelier/poisson-disk-sampling License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Poisson Disk Sampling (Bridson)." https://texelatlas.vercel.app/t/poisson-disk-sampling/ (accessed 2026-12-01). --- id: "poisson-surface-reconstruction" title: "Poisson Surface Reconstruction" domain: "geometry" stage: "geometry" realtime: "offline" platforms: [cpu, cuda, python] year_introduced: 2006 inputs: [point-cloud, normals] outputs: [mesh, sdf] style: "photoreal" dynamic: "static" cost: "offline" authority: "Kazhdan et al., 2006" url: "https://texelatlas.vercel.app/t/poisson-surface-reconstruction/" sources_verified_at: "2026-11-29" --- # Poisson Surface Reconstruction (Kazhdan et al., 2006) > Fits a smooth indicator function whose gradient matches an oriented point cloud's normals by solving a Poisson equation on an adaptive octree, then extracts the zero level set. Watertight meshes from noisy scans. ## Reach for it when - need a watertight mesh from a point cloud - noisy scan points should become a smooth surface - default meshing after photogrammetry - lidar points with normals to mesh - holes in the reconstructed surface ## How it works Treat the oriented points as samples of the gradient of the model's indicator function (1 inside, 0 outside). Splat the normals into a smooth vector field, then solve for the scalar function whose gradient best matches that field, which is a Poisson problem: the Laplacian of the function equals the divergence of the field. The function is discretised over an adaptive octree with compactly supported basis functions, so the linear system is sparse and resolution concentrates near points. Finally, the surface is extracted at the iso-value equal to the average of the indicator at the sample positions, using an octree-aware marching-cubes variant. Because the solution is global, the method fills holes smoothly and tolerates noise and misregistration. ## When to use it Choose it for watertight reconstruction from MVS or LiDAR point clouds with reliable normals, and as the default meshing step after photogrammetry. Prefer [Screened Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction.md) which fixes the oversmoothing and adds point interpolation, and [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) on a pre-built SDF when you already have a distance field. ## Cost offline — Octree depth controls cost and memory; typical scans take seconds to minutes on CPU. Measured GPU Weight: 17.03× baseline (moderate) — 0.5279 ms median / 0.5441 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.58× baseline (moderate) — 0.2159 ms median (2.45× faster on L4). Ampere A100 scaling: 11.37× baseline (moderate) — 0.3274 ms median (1.61× faster on A100). ## Failure modes - Oversmoothed fine detail and rounded corners compared with the screened variant - Hallucinated closed surface that bridges across holes or bulges into missing regions - Bad or inconsistently oriented normals produce blobs and inverted regions - Sheet-like geometry (leaves, cloth) turns into inflated thick shells ## Dataflow - Inputs: point-cloud, normals - Outputs: mesh, sdf - Platforms: cpu, cuda, python ## Presets ### Poisson Surface Reconstruction — oriented point cloud normals (left) vs watertight implicit solve (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_POINT_DENS": 11, "P_ISO_CONTOUR": 0.65, "P_ROT_SPEED": 0.7, "P_SPLIT": 0.48 } ``` ```glsl const float P_POINT_DENS = 11.0; // P Point Density [6.0, 20.0, 1.0] const float P_ISO_CONTOUR = 0.65; // P Indicator Field [0.0, 1.5, 0.05] const float P_ROT_SPEED = 0.70; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Cloud / Poisson Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Sculpted genus-1 organic sculpture (ground-truth watertight Poisson indicator zero-level set) float mapSurface(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.6) * q.xz; q.yz = rot2(0.38) * q.yz; vec2 t1 = vec2(length(q.xz) - 0.46, q.y); float dTor = length(t1) - 0.24; float dOrb1 = length(q - vec3(0.0, 0.30, 0.0)) - 0.30; float dOrb2 = length(q - vec3(0.0, -0.30, 0.0)) - 0.28; return smin(dTor, min(dOrb1, dOrb2), 0.20) * 0.88; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0020, 0.0); return normalize(vec3( mapSurface(p + e.xyy, spin) - mapSurface(p - e.xyy, spin), mapSurface(p + e.yxy, spin) - mapSurface(p - e.yxy, spin), mapSurface(p + e.yyx, spin) - mapSurface(p - e.yyx, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isPoisson = screenX >= split; float dens = clamp(floor(P_POINT_DENS + 0.5), 6.0, 22.0); float isoVis = clamp(P_ISO_CONTOUR, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.024, 0.034, 0.056), vec3(0.068, 0.088, 0.138), smoothstep(-0.55, 0.55, uv.y)); // Subtle background Poisson indicator scalar field chi(x) slice in the z=0 plane float tZ0 = (0.0 - ro.z) / rd.z; vec3 pZ0 = ro + rd * tZ0; float dSlice = mapSurface(pZ0, spin); float chiField = 1.0 / (1.0 + exp(dSlice * 7.5)); // smooth indicator function chi in [0, 1] float isoRing = smoothstep(0.08, 0.015, abs(fract(dSlice * 8.0) - 0.5)) * exp(-abs(dSlice) * 2.2); col += mix(vec3(0.10, 0.42, 0.72), vec3(0.95, 0.56, 0.22), chiField) * isoRing * 0.28 * min(isoVis, 1.2); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSurface(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 7.5) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.6) * objP.xz; objP.yz = rot2(0.38) * objP.yz; if (!isPoisson) { // Left: Sparse oriented point-cloud input (positions + surface normals V(p)) with empty gaps between points! vec3 g = objP * dens; vec3 cell = floor(g); float minD = 1e5; for (int dz = -1; dz <= 1; dz++) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec3 nb = cell + vec3(float(dx), float(dy), float(dz)); vec3 pt = (nb + 0.18 + 0.64 * hash33(nb)) / dens; // Project onto surface tangent plane to mimic real scanned point cloud vec3 ptOnSurf = pt - n * dot(pt - objP, n); minD = min(minD, length(objP - ptOnSurf)); } } } float ptRad = 0.34 / dens; float ptMask = smoothstep(ptRad, ptRad * 0.55, minD); // Normal-encoded RGB color shows each sample carries an oriented normal vector! vec3 normCol = n * 0.5 + 0.5; // Faint inner ghost hull so 3D form reads cleanly between sparse oriented surfels vec3 ghost = vec3(0.08, 0.12, 0.18) * (0.4 + 0.6 * max(dot(n, normalize(vec3(0.5, 0.8, 0.5))), 0.0)); col = mix(mix(col, ghost, 0.55), normCol * 1.15, ptMask); } else { // Right: Watertight smooth isosurface extracted from solving Delta(chi) = div(V) vec3 l1 = normalize(vec3(0.58, 0.84, 0.52)); vec3 l2 = normalize(vec3(-0.72, -0.22, 0.50)); float diff = max(dot(n, l1), 0.0) * 0.86 + max(dot(n, l2), 0.0) * 0.24; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 54.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = vec3(0.84, 0.82, 0.78); col = alb * (0.24 + 0.84 * diff) + vec3(0.98) * spec * 0.52 + vec3(0.32, 0.74, 0.98) * rim * 0.32; // Subtle topographic iso-elevation contours from the smooth indicator field float surfIso = smoothstep(0.06, 0.015, abs(fract(objP.y * 8.0) - 0.5)); col = mix(col, vec3(0.12, 0.48, 0.72), surfIso * 0.20 * min(isoVis, 1.2)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Screened Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction.md) ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): The indicator volume is contoured with an octree marching-cubes pass. ## Combination ideas - [Watertight scan-to-simulation pipeline via Poisson reconstruction and isotropic remeshing](https://texelatlas.vercel.app/ideas/poisson-reconstructed-isotropic-remesh/) ## Sources 1. [primary] Michael Kazhdan, Matthew Bolitho, Hugues Hoppe (2006) Poisson Surface Reconstruction. Symposium on Geometry Processing. https://doi.org/10.2312/sgp/sgp06/061-070 (verified via doi.org on 2026-11-29) 2. [primary] Michael Kazhdan Poisson Surface Reconstruction. cs.jhu.edu. https://www.cs.jhu.edu/~misha/MyPapers/SGP06.pdf (verified via http on 2026-11-29) 3. [implementation] mkazhdan (2015) mkazhdan/PoissonRecon. https://github.com/mkazhdan/PoissonRecon License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Poisson Surface Reconstruction." https://texelatlas.vercel.app/t/poisson-surface-reconstruction/ (accessed 2026-12-01). --- id: "polygen" title: "PolyGen autoregressive mesh generation" aliases: [PolyGen] domain: "genai" stage: "generation" realtime: "interactive" platforms: [python, cuda] year_introduced: 2020 inputs: [voxels, photos] outputs: [mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Nash et al., 2020" url: "https://texelatlas.vercel.app/t/polygen/" sources_verified_at: "2026-11-29" --- # PolyGen autoregressive mesh generation (Nash et al., 2020) > A transformer model that writes a polygon mesh directly: first the vertex coordinates, then the faces as index sequences, so output is native low-poly geometry rather than an iso-surface. ## Reach for it when - want a generative model that outputs real polygon meshes - ai generated meshes are dense and not artist style - need low poly mesh generation conditioned on a voxel or image - generate vertices and faces as a sequence of tokens - iso surface extraction gives messy triangles from generated models ## How it works Meshes are treated as two token sequences. A vertex model predicts quantised x, y, z coordinates one value at a time (vertices sorted by height z, then y, then x) with a Transformer decoder, and each new coordinate is conditioned on all previous ones. A face model then takes the generated vertices and produces faces by emitting vertex indices through a pointer-network-style head: attention over the encoded vertex list selects which vertex comes next, with a stop token to end each face. Both stages can be conditioned on class labels, an image or a voxel grid through cross-attention. Sampling uses nucleus (top-p) sampling for diversity. Because the result is an explicit n-gon mesh with shared vertices, it needs no remeshing, and triangles can be edge-length-limited by the learned distribution. ## When to use it Choose it as the reference for mesh-as-sequence generation and for understanding later artist-style mesh models. Prefer [MeshGPT](https://texelatlas.vercel.app/t/meshgpt.md) or [MeshAnything](https://texelatlas.vercel.app/t/meshanything.md) for stronger, scalable successors with learned tokenisers, [TripoSR](https://texelatlas.vercel.app/t/triposr.md) or [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) when a dense implicit surface is acceptable, and procedural [Procedural Kit Modeling with Verification (procgen-kit)](https://texelatlas.vercel.app/t/procedural-kit-modeling.md) when you need controllable game-ready layouts. ## Cost heavy — Autoregressive decoding is sequential and long; thousands of tokens per mesh make it seconds to minutes per sample in the original setup. ## Failure modes - Limited to small meshes (hundreds of faces) because of sequence length growth - Occasional non-manifold, flipped or intersecting faces, since validity is not enforced - Quantisation to a coarse coordinate grid limits fine detail - Quality tied to the training set (ShapeNet-class furniture), with weak generalisation to new categories - No textures or UVs are produced ## Dataflow - Inputs: voxels, photos - Outputs: mesh - Platforms: python, cuda ## Combines with - [MeshGPT](https://texelatlas.vercel.app/t/meshgpt.md): PolyGen's vertex-then-face sequences motivate the learned geometry tokens that MeshGPT decodes. ## Sources 1. [primary] Charlie Nash, Yaroslav Ganin, S. M. Ali Eslami, Peter W. Battaglia (2020) PolyGen: An Autoregressive Generative Model of 3D Meshes. arXiv preprint (cs.GR). https://arxiv.org/abs/2002.10880 (verified via arxiv on 2026-11-29) 2. [implementation] google-deepmind (2019) google-deepmind/deepmind-research. https://github.com/google-deepmind/deepmind-research License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "PolyGen autoregressive mesh generation." https://texelatlas.vercel.app/t/polygen/ (accessed 2026-12-01). --- id: "polyhedron-spanning-tree-unfolding" title: "Conway Polyhedra & Spanning-Tree Hinge Net Unfolding" aliases: [polyhedron net unfolding, Conway polyhedron notation, spanning-tree mesh unfolding, origami net folding] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, cpu, desktop-gpu, blender, houdini] year_introduced: 2007 inputs: [mesh, graph] outputs: [mesh, animation, uv-atlas] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Takahashi et al., 2011" url: "https://texelatlas.vercel.app/t/polyhedron-spanning-tree-unfolding/" sources_verified_at: "2026-11-30" --- # Conway Polyhedra & Spanning-Tree Hinge Net Unfolding (Takahashi et al., 2011) > Generates polyhedra via Conway topological operators, builds a non-overlapping spanning tree of the face-adjacency dual graph, and animates each face as a kinematic hinge chain between flat paper net and closed 3D solid. ## Reach for it when - unfold a 3d polyhedron mesh into a flat connected paper net - animate origami or papercraft folding along hinged mesh edges - generate cut lines for laser cutting or folding a 3d shape from cardboard - build a face hierarchy tree without overlapping unfolded panels - need continuous fold-angle kinematics from flat sheet to closed solid ## How it works Starting from seed Platonic solids or architectural archetypes, **Conway polyhedron operators** (dual, ambo, kis, gyro, truncate, bevel) transform vertices, edges, and faces combinatorially to synthesize rich families of convex and star polyhedra. To unfold a closed polyhedron into a single flat **edge-unfolded net**, the algorithm builds the mesh's **dual graph** (one node per face, one edge per shared mesh edge) and extracts a **spanning tree**. Every tree edge becomes a **hinge crease** while non-tree edges are cut open. Because naive spanning trees can cause faces to collide when flattened onto the plane, heuristics such as steepest-edge weights, minimum-perimeter trees, or topological surgery (Takahashi et al.) search for overlap-free unfoldings—or split the net into minimal non-overlapping patches when no single overlap-free net exists. At runtime, each face stores its parent hinge edge, local axis, and target **dihedral angle** `theta_target`. Traversing the tree from the root face outward and concatenating rotations `R(axis, t * theta_target)` (optionally staggered by tree depth for wave-like motion) smoothly folds the flat net into the 3D solid without deforming face areas or edge lengths. ## When to use it Choose it when creating papercraft, architectural origami animations, laser-cut fabrication templates, or procedural polyhedral props that must fold isometrically from flat sheets. Prefer [lscm-uv-unwrapping](lscm-uv-unwrapping) or [xatlas](xatlas) when you need distortion-tolerant texture parameterization for arbitrary organic meshes rather than rigid isometric face unfolding. Prefer [blend-shapes-morph-targets](blend-shapes-morph-targets) when arbitrary non-isometric mesh transitions are acceptable without preserving exact crease hinges. ## Cost cheap — Dual-graph spanning-tree construction runs once in under a millisecond on the CPU for typical polyhedra, and per-frame hierarchical hinge transforms cost microseconds. ## Failure modes - Random or unweighted spanning trees frequently produce self-overlapping flat nets, especially on non-convex or high-valence polyhedra - During intermediate folding angles, distant branches of the hinge tree can interpenetrate unless fold timing is scheduled carefully - Non-planar polygonal faces cannot flatten rigidly without prior triangulation, adding unintended crease lines - Deep narrow spanning trees accumulate floating-point drift at leaf faces unless dihedral rotations are composed cleanly in double precision or local frames ## Dataflow - Inputs: mesh, graph - Outputs: mesh, animation, uv-atlas - Platforms: webgl2, webgpu, cpu, desktop-gpu, blender, houdini ## Combines with - [Least Squares Conformal Maps](https://texelatlas.vercel.app/t/lscm-uv-unwrapping.md): Flat unfolded nets directly serve as distortion-free UV charts for paper fiber textures and crease wear maps. - [Quaternion slerp rotation interpolation](https://texelatlas.vercel.app/t/quaternion-slerp-interpolation.md): Smoothly interpolates hinge rotations across tree depth so nested polyhedral flaps fold without gimbal artifacts. ## Combination ideas - [Anamorphic kirigami nets that lock into one sightline](https://texelatlas.vercel.app/ideas/anamorphic-projected-kirigami-nets/) ## Sources 1. [primary] Shigeo Takahashi, Hsiang‐Yun Wu, Seow Hui Saw, Chun‐Cheng Lin, Hsu‐Chun Yen (2011) Optimized Topological Surgery for Unfolding 3D Meshes. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2011.02053.x (verified via crossref on 2026-11-30) 2. [book] Erik D. Demaine, Joseph O'Rourke (2007) Geometric Folding Algorithms. Cambridge University Press. https://doi.org/10.1017/cbo9780511735172 (verified via crossref on 2026-11-30) 3. [implementation] spite (2026) spite/codevember-2026. https://github.com/spite/codevember-2026 License: MIT. (verified via github on 2026-11-30) 4. [implementation] ttillberg (2026) ttillberg/codevember-2026. https://github.com/ttillberg/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Conway Polyhedra & Spanning-Tree Hinge Net Unfolding." https://texelatlas.vercel.app/t/polyhedron-spanning-tree-unfolding/ (accessed 2026-12-01). --- id: "portal-pvs-culling" title: "Portal and PVS visibility culling" aliases: [portal culling, potentially visible set, PVS] domain: "performance" stage: "performance" realtime: "realtime" platforms: [cpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1991 inputs: [mesh, graph] outputs: [visibility-mask] style: "both" dynamic: "static" cost: "cheap" authority: "Teller & Séquin, 1991" url: "https://texelatlas.vercel.app/t/portal-pvs-culling/" sources_verified_at: "2026-11-29" --- # Portal and PVS visibility culling (Teller & Séquin, 1991) > Partition an indoor level into cells joined by portals and either clip the view frustum through portals at runtime or look up a precomputed set of cells visible from the current one. ## Reach for it when - indoor level renders rooms the player cannot see - precomputed visibility for corridors and rooms - walls hide most geometry but everything is drawn - need zero runtime cost occlusion culling - culling for building interiors with doors ## How it works The level is divided into convex cells (rooms) connected by portals, the openings between them. Two flavors exist. Portal rendering walks from the camera's cell: for each portal in view, the frustum is narrowed to the portal's screen-space polygon and recursion continues into the neighbor cell, drawing only what falls inside the narrowed frustum. Mirrors and distant windows can reuse the same traversal. A potentially visible set (PVS) moves that work offline: for each cell, a conservative computation (portal sight-line tests or sampling) produces a bitset of cells that could be seen from anywhere inside it. At runtime, find the camera's cell, read its bitset, draw those cells' contents, then apply normal frustum culling. Dynamic objects are tagged by the cells they overlap and are drawn if any of those cells is visible. ## When to use it Choose it for indoor, corridor or building-interior scenes with clear cell structure and static architecture: runtime cost is nearly zero with a PVS, and it never has GPU latency. Prefer [Masked software occlusion culling](https://texelatlas.vercel.app/t/masked-software-occlusion-culling.md) or [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md) for open or dynamic scenes where occluders cannot be authored as cells. Combine with [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) to cull per-cell batches. ## Cost cheap — Runtime is a bitset lookup (PVS) or a small recursive clip (portals); the PVS bake can be long for complex levels. Measured GPU Weight: 10.59× baseline (moderate) — 0.3326 ms median / 0.3419 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 9.8× baseline (moderate) — 0.1548 ms median (2.15× faster on L4). Ampere A100 scaling: 6.5× baseline (moderate) — 0.1871 ms median (1.78× faster on A100). ## Failure modes - Conservative PVS over-includes cells, so large open rooms see little gain - Misplaced or missing portals cause objects to vanish when they should be visible - Doors and moving walls need runtime portal open/close handling or the PVS goes stale - Bake time and memory for PVS bitsets grow quickly with cell count - Poor fit to outdoor scenes where there are no natural cells ## Engine support - unity: builtin — `Window > Rendering > Occlusion Culling (Umbra PVS bake) with OcclusionArea and OcclusionPortal components` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/OcclusionPortal.html, checked 2026-12-01) - unreal: builtin — `Place a Precomputed Visibility Volume in the level` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/precomputed-visibility-volumes-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, graph - Outputs: visibility-mask - Platforms: cpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Portal & PVS visibility culling — recursive frustum clipping through architectural doorways (glsl-fragment; rendered 2026-11-30) ```json { "P_FOV_ANGLE": 0.78, "P_PORTAL_WIDTH": 0.14, "P_CAM_SWEEP": 1, "P_SHOW_FRUSTUM": 1 } ``` ```glsl const float P_FOV_ANGLE = 0.78; // P Camera FOV [0.35, 1.35, 0.03] const float P_PORTAL_WIDTH = 0.14; // P Portal Width [0.06, 0.26, 0.01] const float P_CAM_SWEEP = 1.0; // P Sweep Speed [0.0, 2.5, 0.05] const float P_SHOW_FRUSTUM = 1.0; // P Frustum Beams [0.0, 1.5, 0.05] float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } float wrapPi(float a) { return mod(a + 3.14159265, 6.2831853) - 3.14159265; } // Clip angular interval [aMin, aMax] to the sightline span of a portal segment (pA -> pB) seen from cam vec2 clipInterval(vec2 iv, vec2 cam, vec2 pA, vec2 pB, float refAng) { float a1 = wrapPi(atan(pA.y - cam.y, pA.x - cam.x) - refAng); float a2 = wrapPi(atan(pB.y - cam.y, pB.x - cam.x) - refAng); float lo = min(a1, a2); float hi = max(a1, a2); return vec2(max(iv.x, lo), min(iv.y, hi)); } bool inWedge(vec2 p, vec2 cam, vec2 iv, float refAng) { if (iv.x >= iv.y) return false; float a = wrapPi(atan(p.y - cam.y, p.x - cam.x) - refAng); return a >= iv.x && a <= iv.y; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tAnim = iTime * max(P_CAM_SWEEP, 0.0); float halfFov = clamp(P_FOV_ANGLE, 0.3, 1.45) * 0.5; float pHalf = clamp(P_PORTAL_WIDTH, 0.04, 0.28) * 0.5; float beamVis = clamp(P_SHOW_FRUSTUM, 0.0, 1.6); // Architectural floorplan: 3 vertical zones (Left Room x<-0.22, Central Hall [-0.22,0.22], Right Rooms x>0.22) // Right side split horizontally at y = 0.0 into Upper-Right Room and Lower-Right Room vec2 cam = vec2(-0.56 + 0.08 * cos(tAnim * 0.7), 0.16 * sin(tAnim * 0.55)); float camAng = 0.42 * sin(tAnim * 0.62); // Portal 1: doorway from Left Room into Central Hall at x = -0.22, y = 0.04 vec2 p1A = vec2(-0.22, 0.04 - pHalf); vec2 p1B = vec2(-0.22, 0.04 + pHalf); // Portal 2: doorway from Central Hall into Upper-Right Room at x = 0.22, y = 0.22 vec2 p2A = vec2(0.22, 0.22 - pHalf); vec2 p2B = vec2(0.22, 0.22 + pHalf); // Portal 3: doorway from Central Hall into Lower-Right Room at x = 0.22, y = -0.22 vec2 p3A = vec2(0.22, -0.22 - pHalf); vec2 p3B = vec2(0.22, -0.22 + pHalf); // Recursive portal frustum clipping! vec2 ivRoot = vec2(-halfFov, halfFov); vec2 ivHall = clipInterval(ivRoot, cam, p1A, p1B, camAng); vec2 ivUpRight = clipInterval(ivHall, cam, p2A, p2B, camAng); vec2 ivLoRight = clipInterval(ivHall, cam, p3A, p3B, camAng); // Determine which room the pixel belongs to (bounds: x in [-0.80, 0.80], y in [-0.44, 0.44]) bool inBuilding = abs(uv.x) < 0.80 && abs(uv.y) < 0.44; int roomId = -1; if (inBuilding) { if (uv.x < -0.22) roomId = 0; // Starting Room else if (uv.x < 0.22) roomId = 1; // Central Hall else if (uv.y >= 0.0) roomId = 2; // Upper-Right Chamber else roomId = 3; // Lower-Right Chamber } // Visibility classification per pixel bool inRawFov = inWedge(uv, cam, ivRoot, camAng); bool visPixel = false; bool roomActive = false; if (roomId == 0) { roomActive = true; visPixel = inRawFov; } else if (roomId == 1) { roomActive = ivHall.x < ivHall.y; visPixel = inWedge(uv, cam, ivHall, camAng); } else if (roomId == 2) { roomActive = ivUpRight.x < ivUpRight.y; visPixel = inWedge(uv, cam, ivUpRight, camAng); } else if (roomId == 3) { roomActive = ivLoRight.x < ivLoRight.y; visPixel = inWedge(uv, cam, ivLoRight, camAng); } // Blueprint background vec3 col = vec3(0.028, 0.036, 0.055); vec2 g = abs(fract(uv * 14.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.042) * smoothstep(0.035, 0.005, min(g.x, g.y)); if (inBuilding) { float hatch = smoothstep(0.45, 0.85, sin((uv.x - uv.y) * 95.0)); vec3 culledFloor = vec3(0.055, 0.062, 0.088) + vec3(0.05, 0.02, 0.04) * hatch; vec3 activeFloor = vec3(0.09, 0.14, 0.19); col = roomActive ? activeFloor : culledFloor; // Highlight frustum-culled area that WAS inside the naive camera cone but eliminated by Portal clipping! if (inRawFov && !visPixel) { col = mix(col, vec3(0.32, 0.08, 0.16), 0.45 * min(beamVis, 1.2)); } // Highlight true portal-clipped visible region if (visPixel) { float falloff = exp(-length(uv - cam) * 0.7); col += vec3(0.14, 0.62, 0.46) * (0.28 + 0.42 * falloff) * min(beamVis, 1.3); } // Place room prop markers (colored pillars/crates) that light up ONLY when their room survives PVS culling vec2 props[4]; props[0] = vec2(-0.42, -0.26); props[1] = vec2(0.00, 0.24); props[2] = vec2(0.54, 0.24); props[3] = vec2(0.54, -0.24); for (int k = 0; k < 4; k++) { float dp = length(uv - props[k]) - 0.042; bool pVis = (k == 0 && inRawFov) || (k == 1 && ivHall.x < ivHall.y) || (k == 2 && ivUpRight.x < ivUpRight.y) || (k == 3 && ivLoRight.x < ivLoRight.y); vec3 pCol = pVis ? vec3(0.98, 0.82, 0.28) : vec3(0.42, 0.18, 0.26); col = mix(col, pCol, smoothstep(px * 2.0, -px * 1.5, dp)); } } // Draw solid walls (excluding portal gaps) float dWall = 1e5; dWall = min(dWall, sdSegment(uv, vec2(-0.80, -0.44), vec2(0.80, -0.44))); dWall = min(dWall, sdSegment(uv, vec2(-0.80, 0.44), vec2(0.80, 0.44))); dWall = min(dWall, sdSegment(uv, vec2(-0.80, -0.44), vec2(-0.80, 0.44))); dWall = min(dWall, sdSegment(uv, vec2(0.80, -0.44), vec2(0.80, 0.44))); // Wall 1 (with Portal 1 gap) dWall = min(dWall, sdSegment(uv, vec2(-0.22, -0.44), p1A)); dWall = min(dWall, sdSegment(uv, p1B, vec2(-0.22, 0.44))); // Wall 2 (with Portal 2 & Portal 3 gaps) dWall = min(dWall, sdSegment(uv, vec2(0.22, -0.44), p3A)); dWall = min(dWall, sdSegment(uv, p3B, p2A)); dWall = min(dWall, sdSegment(uv, p2B, vec2(0.22, 0.44))); // Horizontal divider between right rooms dWall = min(dWall, sdSegment(uv, vec2(0.22, 0.0), vec2(0.80, 0.0))); col = mix(col, vec3(0.76, 0.84, 0.94), smoothstep(0.014, 0.004, dWall)); // Draw glowing doorway portals float dP1 = sdSegment(uv, p1A, p1B); float dP2 = sdSegment(uv, p2A, p2B); float dP3 = sdSegment(uv, p3A, p3B); col = mix(col, (ivHall.x < ivHall.y) ? vec3(0.18, 0.98, 0.72) : vec3(0.35, 0.42, 0.55), smoothstep(0.012, 0.003, dP1)); col = mix(col, (ivUpRight.x < ivUpRight.y) ? vec3(0.98, 0.78, 0.22) : vec3(0.35, 0.42, 0.55), smoothstep(0.012, 0.003, dP2)); col = mix(col, (ivLoRight.x < ivLoRight.y) ? vec3(0.98, 0.78, 0.22) : vec3(0.35, 0.42, 0.55), smoothstep(0.012, 0.003, dP3)); // Draw clipped frustum edge sightlines from camera if (beamVis > 0.01) { vec2 dirL = vec2(cos(camAng + ivRoot.x), sin(camAng + ivRoot.x)); vec2 dirR = vec2(cos(camAng + ivRoot.y), sin(camAng + ivRoot.y)); float dFr = min(sdSegment(uv, cam, cam + dirL * 1.5), sdSegment(uv, cam, cam + dirR * 1.5)); col += vec3(0.45, 0.72, 1.0) * smoothstep(px * 3.5, px * 0.8, dFr) * 0.55 * min(beamVis, 1.2); if (ivHall.x < ivHall.y) { vec2 hL = vec2(cos(camAng + ivHall.x), sin(camAng + ivHall.x)); vec2 hR = vec2(cos(camAng + ivHall.y), sin(camAng + ivHall.y)); float dH = min(sdSegment(uv, cam, cam + hL * 1.4), sdSegment(uv, cam, cam + hR * 1.4)); col += vec3(0.22, 0.96, 0.72) * smoothstep(px * 3.5, px * 0.8, dH) * 0.75 * min(beamVis, 1.2); } } // Camera beacon col = mix(col, vec3(1.0, 0.96, 0.82), smoothstep(0.026, 0.010, length(uv - cam))); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Lightmap Baking](https://texelatlas.vercel.app/t/lightmap-baking.md): The same cell partition used for the visibility bake can organize lightmap charts per room. ## Sources 1. [primary] Seth J. Teller, Carlo H. Séquin (1991) Visibility preprocessing for interactive walkthroughs. Proceedings of the 18th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/122718.122725 (verified via crossref on 2026-11-29) 2. [secondary] David Luebke, Chris Georges (1995) Portals and mirrors. Proceedings of the 1995 symposium on Interactive 3D graphics - SI3D '95. https://doi.org/10.1145/199404.199422 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Portal and PVS visibility culling." https://texelatlas.vercel.app/t/portal-pvs-culling/ (accessed 2026-12-01). --- id: "position-based-dynamics" title: "Position Based Dynamics" aliases: [PBD] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity, unreal] year_introduced: 2007 inputs: [particles] outputs: [particles, mesh] style: "both" dynamic: "dynamic" cost: "medium" authority: "Müller et al., 2007" url: "https://texelatlas.vercel.app/t/position-based-dynamics/" sources_verified_at: "2026-11-29" --- # Position Based Dynamics (Müller et al., 2007) > Simulates cloth, soft bodies and ropes by predicting particle positions and then projecting them directly onto constraint manifolds, skipping forces and stiffness-induced blow-ups. ## Reach for it when - need stable real-time cloth or soft body in games - physics simulation explodes with stiff constraints - interactive deformable objects with simple code - controllable ropes and cloth without force tuning ## How it works Each step integrates velocities with external forces to get *predicted* positions. Constraints (distance, bending, volume, collision) are then solved by Gauss-Seidel or Jacobi iteration: each constraint computes a position correction along its gradient, weighted by inverse mass, and applies it immediately. After the iterations the velocity is recovered as `(x_new - x_old)/dt`, so the position edits become implicit velocity changes. Because corrections are geometric rather than force-based, the scheme is unconditionally stable; stiffness is controlled by the iteration count and a per-constraint stiffness scalar, not by a physical modulus. Collisions are handled as inequality constraints produced by a broad phase (spatial hash is typical). ## When to use it Choose it when you need unconditionally stable, controllable cloth/rope/soft-body in a game or interactive tool and exact material response does not matter. Prefer [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) when stiffness must be independent of iteration count and timestep, [Vertex Block Descent](https://texelatlas.vercel.app/t/vertex-block-descent.md) when you need stiffer, higher-fidelity cloth that converges faster, and [Implicit cloth integration (Baraff-Witkin)](https://texelatlas.vercel.app/t/implicit-cloth-integration.md) when you need physically calibrated cloth with large steps on CPU. Prefer [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md) for the simplest ropes and ragdolls. ## Cost medium — Linear in constraints x iterations; massively parallel with graph colouring or Jacobi. Qualitative only. Measured GPU Weight: 57.22× baseline (heavy) — 1.7966 ms median / 1.8616 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 50.13× baseline (heavy) — 0.7921 ms median (2.27× faster on L4). Ampere A100 scaling: 40.27× baseline (heavy) — 1.1597 ms median (1.55× faster on A100). ## Failure modes - Stiffness depends on iteration count and time step, so changing frame rate changes how stretchy cloth looks - Slow convergence on long chains and high mass ratios: hanging chains stretch like rubber - Energy dissipation from the velocity update makes motion look damped - Jacobi variants converge slower than Gauss-Seidel and need over-relaxation, which can jitter - Cloth self-collision with thin thickness tunnels at high speeds ## Engine support - blender: builtin — `Geometry Nodes > Simulation > XPBD Solver` (evidence: https://docs.blender.org/manual/en/5.2/modeling/geometry_nodes/simulation/xpbd_solver.html, checked 2026-12-01) — The solver implements the XPBD variant of PBD. - godot: builtin — `SoftBody3D under GodotPhysics3D solves deformable meshes with classic PBD edge constraints` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/jolt_physics/objects/jolt_soft_body_3d.cpp, checked 2026-12-01) - unreal: builtin — `Chaos Cloth (ChaosClothAsset and ClothingSimulationInteractor iterative substepped position-based cloth constraints)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/ChaosClothAsset, checked 2026-12-01) ## Dataflow - Inputs: particles - Outputs: particles, mesh - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity, unreal ## Presets ### Position Based Dynamics — real-time iterative Gauss-Seidel distance constraint solver & collider projection (glsl-fragment; rendered 2026-11-30) ```json { "P_ITERATIONS": 8, "P_STIFFNESS": 0.92, "P_GRAVITY": 1, "P_COLLIDER_SPEED": 1 } ``` ```glsl const float P_ITERATIONS = 8.0; // P Solver Iters [1.0, 14.0, 1.0] const float P_STIFFNESS = 0.92; // P Stiffness k [0.2, 1.0, 0.02] const float P_GRAVITY = 1.0; // P Gravity [0.2, 2.0, 0.05] const float P_COLLIDER_SPEED = 1.0; // P Collider Speed [0.0, 2.5, 0.05] float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } vec3 strainColor(float s) { s = clamp(s, 0.0, 1.0); vec3 c0 = vec3(0.14, 0.82, 0.92); vec3 c1 = vec3(0.98, 0.80, 0.22); vec3 c2 = vec3(1.00, 0.24, 0.34); if (s < 0.5) return mix(c0, c1, s * 2.0); return mix(c1, c2, (s - 0.5) * 2.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tAnim = iTime * max(P_COLLIDER_SPEED, 0.0); int nIter = int(clamp(floor(P_ITERATIONS + 0.5), 1.0, 14.0)); float stiff = clamp(P_STIFFNESS, 0.15, 1.0); float grav = clamp(P_GRAVITY, 0.15, 2.2); // Moving rigid spherical collider pressing into a 11-node pinned PBD chain vec2 collPos = vec2(0.28 * sin(tAnim * 0.72), -0.05 + 0.16 * cos(tAnim * 1.05)); float collRad = 0.175; // Initialize 11 PBD particles with unconstrained predicted positions x* = x + dt*v + dt^2*g vec2 pos[11]; float restLen = 0.132; vec2 pinL = vec2(-0.62, 0.28); vec2 pinR = vec2(0.62, 0.28); for (int i = 0; i < 11; i++) { float u = float(i) / 10.0; float sag = sin(u * 3.14159265) * (0.42 * grav); float sway = sin(u * 6.28318 + tAnim * 1.4) * 0.03 * sin(u * 3.14159); pos[i] = mix(pinL, pinR, u) + vec2(sway, -sag); } // Genuine Position Based Dynamics iterative constraint projection loop (Gauss-Seidel) for (int it = 0; it < 14; it++) { if (it >= nIter) break; // Distance constraints C(p_i, p_{i+1}) = |p_{i+1} - p_i| - d = 0 for (int i = 0; i < 10; i++) { vec2 delta = pos[i + 1] - pos[i]; float len = max(length(delta), 1e-5); float diff = (len - restLen) / len; vec2 corr = delta * diff * 0.5 * stiff; if (i > 0) pos[i] += corr; if (i + 1 < 10) pos[i + 1] -= corr; } // Inequality collision constraint C_col(p_i) = |p_i - c| - R >= 0 for (int i = 1; i < 10; i++) { vec2 dc = pos[i] - collPos; float d = length(dc); if (d < collRad + 0.022) { pos[i] = collPos + (dc / max(d, 1e-5)) * (collRad + 0.022); } // Subtle bending smoothing between neighbors if (i > 1 && i < 9) { vec2 mid = 0.5 * (pos[i - 1] + pos[i + 1]); pos[i] = mix(pos[i], mid, 0.04 * stiff); } } pos[0] = pinL; pos[10] = pinR; } // Technical studio blueprint background vec3 col = mix(vec3(0.03, 0.04, 0.065), vec3(0.065, 0.085, 0.125), smoothstep(-0.5, 0.5, uv.y)); vec2 g = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.022, 0.032, 0.048) * smoothstep(0.03, 0.005, min(g.x, g.y)); // Unconstrained predicted parabolic curve (ghost reference showing gravity before PBD projection) float dGhost = 1e5; for (int i = 0; i < 10; i++) { float u0 = float(i) / 10.0; float u1 = float(i + 1) / 10.0; vec2 g0 = mix(pinL, pinR, u0) + vec2(0.0, -sin(u0 * 3.14159265) * 0.42 * grav); vec2 g1 = mix(pinL, pinR, u1) + vec2(0.0, -sin(u1 * 3.14159265) * 0.42 * grav); dGhost = min(dGhost, sdSegment(uv, g0, g1)); } float dash = step(0.45, fract((uv.x + 1.0) * 18.0)); col = mix(col, vec3(0.28, 0.36, 0.50), smoothstep(px * 2.5, px * 0.6, dGhost) * 0.55 * dash); // Shaded rigid sphere collider with contact halo float dColl = length(uv - collPos) - collRad; if (dColl < 0.0) { vec2 rel = (uv - collPos) / collRad; float nz = sqrt(max(1.0 - dot(rel, rel), 0.0)); vec3 cn = normalize(vec3(rel, nz)); float cDiff = max(dot(cn, normalize(vec3(0.55, 0.72, 0.65))), 0.0); float cSpec = pow(max(dot(cn, normalize(vec3(0.45, 0.65, 0.85))), 0.0), 36.0); col = vec3(0.14, 0.19, 0.28) * (0.32 + 0.85 * cDiff) + vec3(0.75, 0.86, 1.0) * cSpec * 0.48; } col = mix(col, vec3(0.42, 0.72, 1.0), smoothstep(px * 3.2, px * 0.6, abs(dColl)) * 0.75); // Draw PBD constraint edges colored by residual stretch strain | |p_j - p_i| - d | / d for (int i = 0; i < 10; i++) { float segLen = length(pos[i + 1] - pos[i]); float strain = abs(segLen - restLen) / max(restLen * 0.28, 1e-4); float dSeg = sdSegment(uv, pos[i], pos[i + 1]); vec3 eCol = strainColor(strain); col += eCol * exp(-dSeg * 75.0) * 0.35; col = mix(col, eCol, smoothstep(0.011, 0.004, dSeg)); } // Draw PBD mass nodes (pinned anchors in gold, dynamic nodes in ivory/cyan) for (int i = 0; i < 11; i++) { float dp = length(uv - pos[i]); bool isPin = (i == 0 || i == 10); float rad = isPin ? 0.026 : 0.020; vec3 nCol = isPin ? vec3(1.0, 0.78, 0.24) : vec3(0.92, 0.96, 1.0); col = mix(col, vec3(0.05, 0.07, 0.10), smoothstep(rad + 0.007, rad + 0.001, dp)); col = mix(col, nCol, smoothstep(rad, rad - 0.005, dp)); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [Tethered Lattice Adhesive Peeling and Delamination Front](https://texelatlas.vercel.app/t/tethered-lattice-adhesive-delamination.md) - extended by [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) - superseded by [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) ## Combines with - [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md): PBD cloth or soft bodies simulate secondary motion on top of a skinned character's skeleton-driven positions ## Sources 1. [primary] Matthias Müller, Bruno Heidelberger, Marcus Hennix, John Ratcliff (2007) Position based dynamics. Journal of Visual Communication and Image Representation. https://doi.org/10.1016/j.jvcir.2007.01.005 (verified via crossref on 2026-11-29) 2. [implementation] InteractiveComputerGraphics (2015) InteractiveComputerGraphics/PositionBasedDynamics. https://github.com/InteractiveComputerGraphics/PositionBasedDynamics License: MIT. (verified via github on 2026-11-29) 3. [tutorial] Matthias Müller Ten Minute Physics. matthias-research.github.io. https://matthias-research.github.io/pages/tenMinutePhysics (verified via http on 2026-11-29) ## Cite this entry Texel. "Position Based Dynamics." https://texelatlas.vercel.app/t/position-based-dynamics/ (accessed 2026-12-01). --- id: "position-based-fluids" title: "Position Based Fluids" aliases: [PBF] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu] year_introduced: 2013 inputs: [particles] outputs: [particles] style: "both" dynamic: "dynamic" cost: "medium" authority: "Macklin & Müller, 2013" url: "https://texelatlas.vercel.app/t/position-based-fluids/" sources_verified_at: "2026-11-29" --- # Position Based Fluids (Macklin & Müller, 2013) > Particle fluid that enforces incompressibility by solving a density constraint per particle with PBD, giving stable, real-time liquids with tunable artificial pressure. ## Reach for it when - need stable real-time liquid in an interactive scene - particle fluid explodes or compresses - want controllable water on the gpu - fluid sim must be unconditionally stable ## How it works Each particle carries a density constraint `rho_i / rho_0 - 1 = 0`, where density is a SPH kernel sum over neighbours found by a uniform grid. After predicting positions under gravity, the solver iterates: compute a Lagrange multiplier per particle (with a relaxation epsilon for stability), then displace each particle by a kernel-weighted sum of its neighbours' multipliers. A tensile-instability correction term (artificial pressure) prevents clumping at low neighbour counts, and vorticity confinement plus XSPH viscosity re-inject lost small-scale motion. Boundaries are collision constraints. Surface reconstruction for rendering is separate (screen-space fluid or marching cubes). ## When to use it Choose it when you need a visually plausible, controllable, unconditionally stable particle liquid on the GPU for interactive scenes. Prefer [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) (e.g. WCSPH or DFSPH) when you need better physical accuracy, [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) when you need lower numerical dissipation and splashier large-scale motion, and [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md) for gas or smoke on a grid. ## Cost medium — Cost scales with particle count and neighbour search; a few solver iterations per frame. Measured GPU Weight: 24.38× baseline (heavy) — 0.7557 ms median / 0.7894 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.48× baseline (heavy) — 0.3257 ms median (2.32× faster on L4). Ampere A100 scaling: 15.29× baseline (moderate) — 0.4403 ms median (1.72× faster on A100). ## Failure modes - Without the artificial-pressure term particles clump into chains at the free surface - Volume loss/compression visible in tall columns under few iterations - Over-damped, sluggish look unless vorticity confinement and viscosity are tuned - Neighbour deficiency at the surface causes density underestimation and surface jitter ## Engine support - unreal: official — `Niagara Fluids plugin provides GPU-accelerated 2D/3D particle and grid fluid simulation templates` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/niagara-fluids-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: particles - Outputs: particles - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu ## Presets ### Position Based Fluids — tensile clumping without s_corr (left) vs PBF artificial pressure & vorticity (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_S_CORR": 0.85, "P_VORTICITY": 0.75, "P_KERNEL_H": 0.16, "P_SPLIT": 0.48 } ``` ```glsl const float P_S_CORR = 0.85; // P Tensile s_corr [0.0, 1.5, 0.05] const float P_VORTICITY = 0.75; // P Vorticity Conf [0.0, 1.8, 0.05] const float P_KERNEL_H = 0.16; // P Kernel Radius [0.10, 0.26, 0.01] const float P_SPLIT = 0.48; // P Clump / PBF Split [0.0, 1.0, 0.02] vec2 hash21(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } float poly6(float r, float h) { float q = r / max(h, 1e-4); if (q >= 1.0) return 0.0; float t = 1.0 - q * q; return t * t * t; } // Evaluate PBF particle position; left side omits tensile s_corr so particles clump in pairs vec2 pbfParticle(int idx, float t, bool useSCorr, float sCorrGain, float vortGain) { float fi = float(idx); float colI = mod(fi, 8.0); float rowI = floor(fi / 8.0); vec2 rnd = hash21(fi * 17.3 + 2.7); // Dam-break wave surging across tank with rotational vorticity eddies float baseX = (colI - 3.5) * 0.155; float baseY = -0.29 + rowI * 0.125; float surge = 0.085 * sin(t * 1.65 + rowI * 0.55); float waveY = 0.095 * sin(t * 1.9 + baseX * 4.4) * (0.35 + 0.65 * rowI / 3.0); vec2 p = vec2(baseX + surge, baseY + waveY); // Vorticity confinement curl kick on right side float vortAng = t * 2.1 + fi * 0.9; float vortAmp = useSCorr ? (0.032 * vortGain) : 0.010; p += vec2(cos(vortAng), sin(vortAng)) * vortAmp * (0.5 + 0.5 * rnd.x); // Tensile instability: without s_corr = -k*(W(r)/W(dq))^n, adjacent pairs attract into clumps if (!useSCorr) { float pairId = floor(fi * 0.5); float pairCol = mod(pairId * 2.0, 8.0) + 0.5; float pairRow = floor((pairId * 2.0) / 8.0); vec2 clusterCenter = vec2((pairCol - 3.5) * 0.155 + surge, -0.29 + pairRow * 0.125 + waveY); p = mix(p, clusterCenter + (rnd - 0.5) * 0.025, 0.72); } else { // Artificial pressure s_corr pushes particles toward uniform blue-noise spacing p += (rnd - 0.5) * 0.045 * clamp(sCorrGain, 0.0, 1.5); } p.x = clamp(p.x, -0.60, 0.60); p.y = clamp(p.y, -0.34, 0.34); return p; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isPBF = screenX >= split; float hRad = clamp(P_KERNEL_H, 0.10, 0.28); float sCorrGain = max(P_S_CORR, 0.0); float vortGain = max(P_VORTICITY, 0.0); // Lab tank backdrop vec3 col = mix(vec3(0.022, 0.034, 0.054), vec3(0.048, 0.072, 0.115), smoothstep(-0.5, 0.5, uv.y)); vec2 grid = abs(fract(uv * 12.0 - 0.5) - 0.5); col += vec3(0.014, 0.024, 0.040) * smoothstep(0.035, 0.006, min(grid.x, grid.y)); vec2 tankBox = abs(uv) - vec2(0.66, 0.38); float dTank = length(max(tankBox, 0.0)) + min(max(tankBox.x, tankBox.y), 0.0); if (dTank < 0.0) col = mix(col, vec3(0.032, 0.052, 0.088), 0.55); float rho = 0.0; vec2 gradRho = vec2(0.0); float curlVis = 0.0; float minD = 1e5; float sCorrField = 0.0; for (int i = 0; i < 32; i++) { vec2 pi = pbfParticle(i, iTime, isPBF, sCorrGain, vortGain); vec2 d = uv - pi; float r = length(d); minD = min(minD, r); float w = poly6(r, hRad); rho += w; if (r < hRad && r > 1e-4) { float q = r / hRad; float dw = -6.0 * (1.0 - q * q) * (1.0 - q * q) * q / hRad; gradRho += (d / r) * dw; // Artificial pressure s_corr term (W(r)/W(0.2*h))^4 float wRef = poly6(0.2 * hRad, hRad); float ratio = w / max(wRef, 1e-4); sCorrField += ratio * ratio * ratio * ratio * 0.08; // Local swirl energy for vorticity glow float swirlSign = (mod(float(i), 2.0) < 0.5) ? 1.0 : -1.0; curlVis += swirlSign * w * (1.0 - q); } } float iso = 0.52; float mask = smoothstep(iso * 0.85, iso * 1.08, rho) * step(dTank, 0.0); if (mask > 0.005) { vec3 n = normalize(vec3(-gradRho.x * 0.16, -gradRho.y * 0.16, 1.0)); vec3 lDir = normalize(vec3(0.42, 0.78, 0.65)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir + vec3(0.0, 0.0, 1.0))), 0.0), 54.0); // Density constraint error C_i = rho / rho0 - 1 float errC = clamp(abs(rho / 1.15 - 1.0), 0.0, 1.0); vec3 baseWater = isPBF ? mix(vec3(0.04, 0.42, 0.76), vec3(0.14, 0.86, 0.82), clamp(rho * 0.48, 0.0, 1.0)) : mix(vec3(0.14, 0.28, 0.58), vec3(0.82, 0.36, 0.22), errC); // Vorticity highlight streaks on PBF side if (isPBF) { baseWater += vec3(0.18, 0.52, 0.62) * abs(curlVis) * 0.45 * vortGain; } float rim = smoothstep(iso * 1.38, iso * 0.90, rho); vec3 shaded = baseWater * (0.34 + 0.78 * diff) + vec3(0.92, 0.98, 1.0) * (spec * 0.82 + rim * 0.45); col = mix(col, shaded, mask); } // Particle cores and s_corr repulsion halo on right float pDot = smoothstep(0.015, 0.006, minD); vec3 dotCol = isPBF ? vec3(0.86, 0.98, 1.0) : vec3(1.0, 0.72, 0.48); col = mix(col, dotCol, pDot * 0.78); if (isPBF) { col += vec3(0.12, 0.75, 0.95) * clamp(sCorrField * 0.18 * sCorrGain, 0.0, 0.22) * step(dTank, 0.0); } // Tank glass border and split divider col = mix(col, vec3(0.66, 0.82, 0.96), smoothstep(0.009, 0.002, abs(dTank)) * 0.85); col = mix(col, vec3(0.95, 0.97, 1.0), smoothstep(0.0035, 0.0008, abs(screenX - split))); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md): Compliance/multiplier machinery can unify fluid density constraints with solid constraints in one solver ## Combination ideas - [Liquids drawn by a splat renderer](https://texelatlas.vercel.app/ideas/fluids-through-splat-renderer/) - [Narrow-range SSF liquid with whitewater and wet-ground reaction field](https://texelatlas.vercel.app/ideas/narrow-range-ssf-whitewater-ground-field/) - [Depth-feathered soft-particle mist emitted from PBF splash crests](https://texelatlas.vercel.app/ideas/pbf-crest-soft-particle-spray/) ## Sources 1. [primary] Miles Macklin, Matthias Müller (2013) Position based fluids. ACM Transactions on Graphics. https://doi.org/10.1145/2461912.2461984 (verified via crossref on 2026-11-29) 2. [implementation] InteractiveComputerGraphics (2016) InteractiveComputerGraphics/SPlisHSPlasH. https://github.com/InteractiveComputerGraphics/SPlisHSPlasH License: MIT. (verified via github on 2026-11-29) 3. [tutorial] Matthias Müller Ten Minute Physics. matthias-research.github.io. https://matthias-research.github.io/pages/tenMinutePhysics (verified via http on 2026-11-29) ## Cite this entry Texel. "Position Based Fluids." https://texelatlas.vercel.app/t/position-based-fluids/ (accessed 2026-12-01). --- id: "posterization" title: "Posterization" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Wikipedia" url: "https://texelatlas.vercel.app/t/posterization/" sources_verified_at: "2026-11-29" --- # Posterization (Wikipedia) > Reduces each colour channel or the luminance to a small number of levels, producing flat regions of colour with hard transitions. ## Reach for it when - want flat colour regions with few levels - graphic poster look from a render - reduce colour channels to distinct bands - final step to get cel-like banded colours - quick stylised colour reduction ## How it works The simplest form multiplies the channel by N-1, rounds or floors, and divides back, applied per RGB channel. Doing it on luminance only, then re-applying chroma, preserves hue relationships and avoids colour shifts. Working in a perceptual space such as OKLab or HSV makes the level spacing look more even. Smoothing the step with `smoothstep` and `fwidth` antialiases the contour edges between levels, and a slight blur before quantizing reduces speckle from noise. Adding noise or a dither threshold before quantizing converts hard contours into patterns, which is how it links to ordered and blue-noise dithering. ## When to use it Choose it for a cheap graphic poster look or as the final step of a toon pipeline on a rendered image. Prefer [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md) when the banding should come from lighting rather than final colour, and [Kuwahara filter](https://texelatlas.vercel.app/t/kuwahara-filter.md) to also flatten spatial detail. ## Cost cheap — One cheap post pass. Measured GPU Weight: 1.58× baseline (feather) — 0.052 ms median / 0.0535 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.14× baseline (feather) — 0.0182 ms median (2.86× faster on L4). Ampere A100 scaling: 1.01× baseline (feather) — 0.0292 ms median (1.78× faster on A100). ## Failure modes - Contour lines wrap noise: speckled islands at level boundaries - Per-channel quantization shifts hues - Gradients show harsh bands that follow lighting rather than shape - Visible temporal flicker when pixel values hover around a threshold ## Engine support - babylonjs: builtin — `PosterizeBlock in Node Material Editor` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Node/Blocks/posterizeBlock.ts, checked 2026-12-01) - blender: builtin — `Compositor > Add > Creative > Posterize` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/creative/posterize.html, checked 2026-12-01) - threejs: builtin — `import { posterize } from 'three/tsl'` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/display/ColorAdjustment.js, checked 2026-12-01) — TSL node. - unity: builtin — `Shader Graph > Artistic > Adjustment > Posterize node` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Posterize-Node.md, checked 2026-12-01) - unreal: builtin — `Post Process Material (luminance/color quantization in PostProcessVolume)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-materials-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: continuous colour. Right: each channel quantised to 4 levels, leaving flat bands (glsl-fragment; rendered 2026-11-29) ```json { "LEVELS": 4 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 img(vec2 p){ vec3 c=mix(vec3(.12,.18,.34),vec3(.95,.72,.45),clamp(p.y+.5,0.,1.)); vec2 q=p-vec2(-.03,.14); float rr=.16; float d=length(q)-rr; vec3 n=normalize(vec3(q/rr,sqrt(max(1.-dot(q,q)/(rr*rr),0.)))); float l=clamp(dot(n,normalize(vec3(-.5,.6,.6))),0.,1.); c=mix(c,vec3(.85,.26,.2)*(.18+.9*l),smoothstep(.002,-.002,d)); vec2 r=p-vec2(0.,-.2); if(abs(r.x)<.2&&abs(r.y)<.09) c=mix(vec3(.1,.35,.3),vec3(.93,.92,.85),smoothstep(-.3,.3,sin(r.x*340.+r.y*90.))); if(p.y<-.34&&p.y>-.42){ vec3 h=.5+.5*cos(6.2832*((p.x+.25)*2.+vec3(0.,.33,.67))); c=h; } c=mix(c,vec3(.97,.85,.2),smoothstep(.003,-.003,abs(p.x-.17)-.025)*step(.0,p.y)*step(p.y,.4)); return c; } const float LEVELS=4.0; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=img(q); if(R)col=floor(col*LEVELS)/(LEVELS-1.); if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Sources 1. [primary] Wikipedia Posterization. en.wikipedia.org. https://en.wikipedia.org/wiki/Posterization (verified via http on 2026-11-29) ## Cite this entry Texel. "Posterization." https://texelatlas.vercel.app/t/posterization/ (accessed 2026-12-01). --- id: "pre-integrated-skin-shading" title: "Pre-integrated skin shading" aliases: [pre-integrated subsurface scattering, curvature-based skin LUT] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2011 inputs: [normals, gbuffer, texture] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Penner" url: "https://texelatlas.vercel.app/t/pre-integrated-skin-shading/" sources_verified_at: "2026-11-29" --- # Pre-integrated skin shading (Penner) > Fakes skin subsurface scattering with a lookup texture of diffuse profiles integrated over a ring, indexed by N.L and surface curvature, so the soft terminator and red bleed appear in a single pass without screen-space blur. ## Reach for it when - skin looks waxy or hard-edged at the terminator - need cheap subsurface scattering for characters on mobile - red bleed on shadow edge of faces - cannot afford screen space blur for skin - soft diffuse falloff depending on surface curvature ## How it works Skin light bleeds across the terminator because light entering in the lit area scatters and leaves in the shadowed area. Penner precomputes this: for a sphere of radius r (curvature 1/r), integrate the lit diffuse falloff convolved with a skin diffusion profile around the ring, and store the result in a 2D LUT with N.L on one axis and curvature on the other. At runtime curvature comes from derivatives of the world normal over derivatives of position, or a baked map, and the LUT fetch replaces the Lambert term, giving red-tinted soft transitions on cheeks and noses. A second trick pre-integrates the shadow edge penumbra for skin in a 1D LUT. For normals, a blurred normal map is used for the diffuse and the sharp one for specular, with per-channel blurs simulating different scattering lengths (red wider than blue). Specular still uses a standard BRDF. ## When to use it Choose it when characters need believable skin on mobile or at scale and a full-screen blur is unaffordable. Prefer [Separable subsurface scattering](https://texelatlas.vercel.app/t/separable-sss.md) when the budget allows screen-space blur and transmission (ears, thin regions). Prefer [Christensen-Burley diffusion profile](https://texelatlas.vercel.app/t/christensen-burley-sss.md) for offline or path-traced subsurface. For general materials with less critical bleeding, [Oren-Nayar rough diffuse](https://texelatlas.vercel.app/t/oren-nayar.md) or wrap lighting suffices. ## Cost cheap — One extra LUT sample plus a curvature computation per light; no extra passes. Measured GPU Weight: 48.19× baseline (heavy) — 1.5854 ms median / 1.6191 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 38.55× baseline (heavy) — 0.613 ms median (2.59× faster on L4). Ampere A100 scaling: 30.84× baseline (heavy) — 0.8881 ms median (1.79× faster on A100). ## Failure modes - Curvature from screen-space derivatives is noisy and flickers on low-poly or normal-mapped skin - Not shadow aware: light bleeding across shadow-map edges needs the separate shadow LUT - Fixed profile and LUT cannot represent thin transmission such as ears or nostrils - Sphere assumption makes flat regions with high-frequency normal detail look incorrectly soft - Hard to tune per skin tone, as the LUT must be regenerated for each profile ## Engine support - unreal: builtin — `Material > Shading Model = Preintegrated Skin` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/shading-models-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: normals, gbuffer, texture - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Pre-integrated skin shading — curvature-driven RGB diffusion ring integral across the terminator (glsl-fragment; rendered 2026-11-30) ```json { "CURVATURE": 1.15, "SSS_STRENGTH": 0.9, "SPECULAR": 0.45, "ROUGHNESS": 0.36 } ``` ```glsl const float CURVATURE = 1.15; // P const float SSS_STRENGTH = 0.9; // P const float SPECULAR = 0.45; // P const float ROUGHNESS = 0.36; // P float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Sculptural organic form with broad low-curvature domes and tight high-curvature ridges float mapOrganic(vec3 p) { float a = iTime * 0.32; mat2 r = mat2(cos(a), -sin(a), sin(a), cos(a)); p.xz = r * p.xz; // Core cranial dome + sculpted cheek/nose/brow ridges for rich curvature variation float head = length(p * vec3(1.08, 0.92, 1.02)) - 0.68; float ridge1 = length(p - vec3(0.0, 0.02, 0.56)) - 0.16; float ridge2 = length((p - vec3(0.0, 0.28, 0.46)) * vec3(0.65, 1.6, 1.2)) - 0.22; float cheekL = length(p - vec3(-0.32, -0.08, 0.42)) - 0.24; float cheekR = length(p - vec3( 0.32, -0.08, 0.42)) - 0.24; float earL = length((p - vec3(-0.62, 0.02, -0.02)) * vec3(1.9, 0.72, 1.25)) - 0.19; float earR = length((p - vec3( 0.62, 0.02, -0.02)) * vec3(1.9, 0.72, 1.25)) - 0.19; float neck = length(vec2(length(p.xz - vec2(0.0, -0.08)) - 0.28, max(abs(p.y + 0.78) - 0.32, 0.0))) - 0.04; float d = smin(head, ridge1, 0.14); d = smin(d, ridge2, 0.16); d = smin(d, min(cheekL, cheekR), 0.18); d = smin(d, min(earL, earR), 0.10); d = smin(d, neck, 0.18); // Subtle pore-like micro-undulation d += 0.004 * sin(p.x * 26.0) * sin(p.y * 26.0) * sin(p.z * 26.0); return d; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapOrganic(p + e.xyy) - mapOrganic(p - e.xyy), mapOrganic(p + e.yxy) - mapOrganic(p - e.yxy), mapOrganic(p + e.yyx) - mapOrganic(p - e.yyx) )); } // Penner (SIGGRAPH 2011) pre-integrated skin ring convolution evaluated directly in RGB vec3 preIntegratedSkinLUT(float nl, float curv) { float theta = acos(clamp(nl, -1.0, 1.0)); float r = 1.0 / max(curv, 0.08); // Multi-Gaussian skin diffusion profile (wider red radius than green/blue) vec3 acc = vec3(0.0); vec3 wSum = vec3(0.0); const int N = 16; for (int i = -N; i <= N; i++) { float dTheta = float(i) * (1.85 / float(N)); float s = 2.0 * r * sin(abs(dTheta) * 0.5); float s2 = s * s; vec3 prof = vec3( 0.233 * exp(-s2 / 0.0128) + 0.455 * exp(-s2 / 0.22) + 0.312 * exp(-s2 / 1.45), 0.455 * exp(-s2 / 0.0128) + 0.410 * exp(-s2 / 0.09) + 0.135 * exp(-s2 / 0.36), 0.649 * exp(-s2 / 0.0128) + 0.280 * exp(-s2 / 0.04) + 0.071 * exp(-s2 / 0.15) ); float lit = max(cos(theta + dTheta), 0.0); acc += prof * lit; wSum += prof; } return acc / max(wSum, vec3(1e-4)); } float D_GGX(float nh, float a) { float a2 = a * a; float d = nh * nh * (a2 - 1.0) + 1.0; return a2 / (3.14159265 * d * d + 1e-5); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.02, 2.35); vec3 rd = normalize(vec3(uv, -1.55)); float t = 0.2; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapOrganic(ro + rd * t); if (d < 0.002) { hit = true; break; } t += d * 0.85; if (t > 6.0) break; } vec3 bg = mix(vec3(0.04, 0.05, 0.075), vec3(0.11, 0.12, 0.16), clamp(uv.y + 0.5, 0.0, 1.0)); if (!hit) { fragColor = vec4(pow(clamp(aces(bg), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); return; } vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Screen-space geometric curvature |dN| / |dP| as in Penner 2011 float curv = clamp(length(fwidth(n)) / max(length(fwidth(p)), 1e-4), 0.25, 4.5) * max(CURVATURE, 0.05); float lAng = 0.72 + 0.45 * sin(iTime * 0.5); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { lAng = (iMouse.x / iResolution.x - 0.5) * 3.14159; } vec3 L = normalize(vec3(sin(lAng), 0.38, cos(lAng))); vec3 V = -rd; float nl = dot(n, L); vec3 lambert = vec3(max(nl, 0.0)); vec3 sssDiff = preIntegratedSkinLUT(nl, curv); vec3 diffTerm = mix(lambert, sssDiff, clamp(SSS_STRENGTH, 0.0, 1.5)); vec3 skinAlbedo = vec3(0.84, 0.58, 0.46); vec3 H = normalize(L + V); float nh = max(dot(n, H), 0.0); float ndv = max(dot(n, V), 0.01); float fres = 0.028 + 0.972 * pow(1.0 - max(dot(V, H), 0.0), 5.0); float r1 = clamp(ROUGHNESS, 0.08, 0.95); // Dual-lobe oily skin specular float spec = (0.75 * D_GGX(nh, r1 * r1) + 0.25 * D_GGX(nh, r1 * r1 * 0.22)) * fres * max(SPECULAR, 0.0) * max(nl, 0.0); // Soft cool rim bounce + warm subsurface backlight float backScatter = pow(clamp(dot(-L, V), 0.0, 1.0), 3.0) * pow(1.0 - ndv, 2.0) * clamp(curv * 0.4, 0.0, 1.0); vec3 col = skinAlbedo * (diffTerm * vec3(1.65, 1.52, 1.38) + vec3(0.06, 0.08, 0.13)) + vec3(spec) * vec3(1.0, 0.95, 0.90) + vec3(0.85, 0.16, 0.06) * backScatter * SSS_STRENGTH; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extended by [Separable subsurface scattering](https://texelatlas.vercel.app/t/separable-sss.md) ## Combines with - [Curvature map generation for edge wear and masking](https://texelatlas.vercel.app/t/curvature-map-baking.md): A baked curvature map replaces noisy derivative-based curvature as the LUT's second axis. ## Sources 1. [primary] Eric Penner Pre-Integrated Skin Shading. advances.realtimerendering.com. https://advances.realtimerendering.com/s2011/Penner%20-%20Pre-Integrated%20Skin%20Rendering%20(Siggraph%202011%20Advances%20in%20Real-Time%20Rendering%20Course).pptx (verified via http on 2026-11-29) 2. [secondary] Eugene d'Eon, David Luebke Chapter 14. Advanced Techniques for Realistic Real-Time Skin Rendering. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-14-advanced-techniques-realistic-real-time-skin (verified via http on 2026-11-29) ## Cite this entry Texel. "Pre-integrated skin shading." https://texelatlas.vercel.app/t/pre-integrated-skin-shading/ (accessed 2026-12-01). --- id: "precomputed-atmospheric-scattering" title: "Precomputed Atmospheric Scattering" aliases: [Bruneton sky] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu] year_introduced: 2008 inputs: [material-params] outputs: [radiance, hdr-image] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Bruneton & Neyret, 2008" url: "https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering/" sources_verified_at: "2026-11-29" --- # Precomputed Atmospheric Scattering (Bruneton & Neyret, 2008) > Tabulates single and multiple Rayleigh/Mie scattering of a planetary atmosphere into 3D textures, so sky color and aerial perspective cost a few texture fetches per pixel from any altitude. ## Reach for it when - realistic sky and distant haze from space to ground - multiple scattering makes the sunset look right - atmosphere ray marching per pixel is too slow - need accurate planet atmosphere rendering via lookup ## How it works The atmosphere is a spherically symmetric medium with density profiles for air molecules, aerosols and ozone. Because the geometry is symmetric, in-scattered light depends only on four things: altitude, view zenith angle, sun zenith angle and the view-sun azimuth. A precompute pass fills transmittance (2D), single-scattering (a 4D function packed into a 3D texture) and then iterates over scattering orders, feeding each order's result into the next as a source term. A separate irradiance table gives ground ambient light. At run time the sky is one 4D lookup with manual interpolation across the packed axes, and aerial perspective is the difference of two lookups at the camera and at the surface point. Mie scattering is stored separately and recombined with its phase function to save memory. ## When to use it Choose it when you need a physically plausible planet-scale atmosphere with real multiple scattering, a sun that can sit anywhere from noon to below the horizon, and a camera that can fly from the ground to orbit, and you can afford a precompute step on parameter changes. Prefer [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) when parameters (density, albedo, sun) must change every frame without a recompute, or when you want one unified path with volumetric fog. Prefer [Preetham Analytic Daylight Model](https://texelatlas.vercel.app/t/preetham-sky.md) or [Hosek-Wilkie Sky Model](https://texelatlas.vercel.app/t/hosek-wilkie-sky.md) for a ground-only sky with a handful of turbidity sliders and no precompute. Prefer [Ray-marched Rayleigh/Mie Single Scattering](https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering.md) for a cheap ray-marched gradient. ## Cost cheap — Per-pixel cost is a handful of 3D texture fetches; the precompute is a one-off cost that is noticeable (tens to hundreds of ms on a desktop GPU) if parameters change. Measured GPU Weight: 19.08× baseline (moderate) — 0.6278 ms median / 0.65 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.56× baseline (moderate) — 0.2951 ms median (2.13× faster on L4). Ampere A100 scaling: 13.55× baseline (moderate) — 0.3901 ms median (1.61× faster on A100). ## Failure modes - Seams or banding in the sky near the horizon where the packed 4D table is interpolated across slice boundaries - Visible discontinuity at the terminator or when the sun is slightly below the horizon if the table parametrization is too coarse - Changing atmosphere parameters at run time forces a full table rebuild, causing hitches - Planet shadow on aerial perspective and clouds is not captured unless added separately - Assumes a smooth sphere, so terrain shadows (crepuscular rays through mountains) are missing ## Engine support - babylonjs: official — `@babylonjs/addons Atmosphere (LUT-based physically based atmospheric scattering)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/addons/src/atmosphere/atmosphere.ts, checked 2026-12-01) - threejs: plugin — `npm i @takram/three-atmosphere` (evidence: https://github.com/takram-design-engineering/three-geospatial, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Sky > Visual Environment > Sky Type = Physically Based Sky` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/physically-based-sky-volume-override-reference.md, checked 2026-12-01) — HDRP only. - unreal: builtin — `Place Actors > Visual Effects > Sky Atmosphere (SkyAtmosphereComponent precomputed Rayleigh/Mie transmittance and multi-scattering LUTs)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sky-atmosphere-component-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params - Outputs: radiance, hdr-image - Platforms: webgl2, webgpu, desktop-gpu ## Presets ### Precomputed Atmospheric Scattering — single-scatter limb (left) vs multi-scatter Rayleigh/Mie orbital twilight (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SUN_ELEV": 0.1, "P_ALTITUDE": 0.42, "P_MIE_HAZE": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_SUN_ELEV = 0.10; // P Sun Limb Angle [-0.15, 0.45, 0.02] const float P_ALTITUDE = 0.42; // P Orbital Altitude [0.15, 0.95, 0.05] const float P_MIE_HAZE = 0.85; // P Mie Aerosol [0.2, 2.0, 0.05] const float P_SPLIT = 0.48; // P Single / Multi Split [0.0, 1.0, 0.02] vec2 raySphere(vec3 ro, vec3 rd, float R) { float b = dot(ro, rd); float c = dot(ro, ro) - R * R; float h = b * b - c; if (h < 0.0) return vec2(-1.0); h = sqrt(h); return vec2(-b - h, -b + h); } // Physical Rayleigh + Mie atmospheric optical depth integration (Bruneton 2008 planetary geometry) vec3 integrateAtmosphere(vec3 ro, vec3 rd, vec3 sunDir, float mieScale, bool includeMulti) { float Rg = 6.36; float Rt = 6.48; float HR = 0.018; float HM = 0.0045; vec3 betaR = vec3(5.8, 13.5, 33.1) * 0.92; vec3 betaM = vec3(21.0) * 0.42 * mieScale; vec2 hitAtm = raySphere(ro, rd, Rt); if (hitAtm.y < 0.0) return vec3(0.0); vec2 hitGnd = raySphere(ro, rd, Rg); bool hitsPlanet = (hitGnd.x > 0.0); float t0 = max(hitAtm.x, 0.0); float t1 = hitsPlanet ? hitGnd.x : hitAtm.y; const int STEPS = 18; float dt = (t1 - t0) / float(STEPS); float optR = 0.0; float optM = 0.0; vec3 sumR = vec3(0.0); vec3 sumM = vec3(0.0); vec3 sumMulti = vec3(0.0); float mu = dot(rd, sunDir); float phaseR = 0.059683 * (1.0 + mu * mu); float g = 0.78; float phaseM = 0.079577 * ((1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * mu, 0.02), 1.5)); for (int i = 0; i < STEPS; i++) { vec3 p = ro + rd * (t0 + (float(i) + 0.5) * dt); float h = max(length(p) - Rg, 0.0); float dR = exp(-h / HR) * dt; float dM = exp(-h / HM) * dt; optR += dR; optM += dM; // Light transmittance from sample point p to space along sunDir (4-step Chapman/optical depth) vec2 sunAtm = raySphere(p, sunDir, Rt); vec2 sunGnd = raySphere(p, sunDir, Rg); float sunVis = (sunGnd.x > 0.0 && sunGnd.x < sunAtm.y) ? 0.0 : 1.0; float sOptR = 0.0; float sOptM = 0.0; if (sunVis > 0.5) { float sDt = sunAtm.y * 0.25; for (int j = 0; j < 4; j++) { vec3 sp = p + sunDir * ((float(j) + 0.5) * sDt); float sh = max(length(sp) - Rg, 0.0); sOptR += exp(-sh / HR) * sDt; sOptM += exp(-sh / HM) * sDt; } vec3 tau = betaR * (optR + sOptR) + betaM * 1.15 * (optM + sOptM); vec3 atten = exp(-tau); sumR += atten * dR; sumM += atten * dM; } if (includeMulti) { // Precomputed multi-scattering isotropic approximation (2nd+ orders fill deep twilight & luminous horizon limb!) vec3 up = normalize(p); float sunCosZ = dot(up, sunDir); float twilight = smoothstep(-0.34, 0.35, sunCosZ); vec3 viewAtten = exp(-(betaR * optR + betaM * optM) * 0.62); vec3 warmMulti = mix(vec3(0.45, 0.16, 0.38), vec3(0.98, 0.52, 0.24), smoothstep(-0.22, 0.12, sunCosZ)); vec3 dayMulti = vec3(0.32, 0.56, 0.96); vec3 msCol = mix(warmMulti, dayMulti, smoothstep(0.05, 0.42, sunCosZ)); sumMulti += viewAtten * msCol * (dR * 12.0 + dM * 4.0) * twilight * 0.42; } } vec3 sky = (sumR * betaR * phaseR + sumM * betaM * phaseM) * 18.0 + sumMulti; // Planet surface & ocean specular + aerial perspective transmittance if (hitsPlanet) { vec3 gp = ro + rd * hitGnd.x; vec3 gn = normalize(gp); vec3 viewTrans = exp(-(betaR * optR + betaM * optM)); float ndl = max(dot(gn, sunDir), 0.0); // Subtle continental silhouettes & clouds on planetary limb float landMask = smoothstep(0.05, 0.32, sin(gn.x * 14.0 + gn.z * 9.0) * cos(gn.y * 12.0 - gn.x * 6.0)); vec3 surfAlb = mix(vec3(0.04, 0.11, 0.24), vec3(0.18, 0.24, 0.14), landMask); float oceanSpec = (1.0 - landMask) * pow(max(dot(reflect(-sunDir, gn), -rd), 0.0), 42.0) * 1.4; vec3 surfLit = (surfAlb * (ndl * 1.2 + (includeMulti ? 0.06 : 0.0)) + vec3(1.0, 0.84, 0.62) * oceanSpec * ndl); sky += surfLit * viewTrans; } else { // Crisp solar disc + subtle starfield in deep space float sunDisc = smoothstep(0.9985, 0.9996, mu); vec3 viewTrans = exp(-(betaR * optR + betaM * optM)); sky += vec3(12.0, 10.5, 8.2) * sunDisc * viewTrans; } return sky; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useMulti = sx >= split; float sunElev = clamp(P_SUN_ELEV, -0.22, 0.55) + 0.05 * sin(iTime * 0.4); float alt = clamp(P_ALTITUDE, 0.1, 1.0); float mie = clamp(P_MIE_HAZE, 0.1, 2.5); // Orbital view skimming the curved planetary horizon float camR = 6.36 + mix(0.14, 0.72, alt); vec3 ro = vec3(0.0, camR, 0.0); vec3 ta = vec3(0.0, 6.26, -2.25); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.55 + ri * uv.x + up * uv.y); vec3 sunDir = normalize(vec3(0.28 * cos(iTime * 0.25), sunElev, -0.94)); vec3 col = integrateAtmosphere(ro, rd, sunDir, mie, useMulti); float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Ray-marched Rayleigh/Mie Single Scattering](https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering.md) - extended by [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) ## Combines with - [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md): Provides sky radiance and sun transmittance that tint and light the cloud layer. - [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md): Aerial perspective table supplies the far-field haze that the froxel grid hands over to. ## Sources 1. [primary] Eric Bruneton, Fabrice Neyret (2008) Precomputed Atmospheric Scattering. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2008.01245.x (verified via doi.org on 2026-11-29) 2. [implementation] ebruneton (2017) ebruneton/precomputed_atmospheric_scattering. https://github.com/ebruneton/precomputed_atmospheric_scattering License: BSD-3-Clause. (verified via github on 2026-11-29) 3. [tutorial] Eric Bruneton Precomputed Atmospheric Scattering: a New Implementation. ebruneton.github.io. https://ebruneton.github.io/precomputed_atmospheric_scattering (verified via http on 2026-11-29) 4. [implementation] takram-design-engineering (2024) takram-design-engineering/three-geospatial. https://github.com/takram-design-engineering/three-geospatial License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Precomputed Atmospheric Scattering." https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering/ (accessed 2026-12-01). --- id: "precomputed-radiance-transfer" title: "Precomputed Radiance Transfer" aliases: [PRT, SH PRT] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, webgl2, mobile-gpu] year_introduced: 2002 inputs: [mesh, hdr-image] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Sloan et al., 2002" url: "https://texelatlas.vercel.app/t/precomputed-radiance-transfer/" sources_verified_at: "2026-11-29" --- # Precomputed Radiance Transfer (Sloan et al., 2002) > Precomputes, per vertex or texel, how incoming low-frequency light maps to outgoing radiance including self-shadowing and interreflection, so relighting a rigid object under a changing environment is a dot product. ## Reach for it when - rigid object must relight under changing sky - want soft self-shadowed diffuse lighting cheaply - time-of-day lighting on a static model - need baked self-shadowing that responds to environment ## How it works For a rigid object, how light at a point depends on the environment is linear. If the lighting is expressed in a basis (spherical harmonics), then outgoing radiance is a **transfer vector** dotted with the **lighting coefficient vector**. The transfer vector captures everything that depends only on geometry and material: visibility (self-shadowing), cosine falloff, and with extra bounces, interreflection. In the offline stage, for each vertex or texel, you cast many rays and project the visibility times cosine onto SH, producing `n^2` coefficients (25 for order 4). For glossy materials the transfer is a **matrix** that maps lighting coefficients to coefficients of the exiting radiance, which is then evaluated for the view direction. At runtime you project the current environment to SH (cheaply, even per frame, using [spherical-harmonics-lighting](spherical-harmonics-lighting)) and then compute a dot product per vertex (or per pixel with the coefficients in textures). Rotation of the light is a coefficient rotation, so it supports dynamic environments, but not moving geometry, which would invalidate the precomputed transfer. ## When to use it Choose it for hero rigid objects or static scenes lit by changing low-frequency lighting (sky, time of day), where self-shadowed soft diffuse lighting is wanted. Prefer [irradiance-volumes](irradiance-volumes) when the object deforms or moves around a baked scene, since PRT is per-object. Prefer [wavelet-all-frequency-relighting](wavelet-all-frequency-relighting) when sharp shadows from high-frequency environments are needed. Prefer [lightmap-baking](lightmap-baking) when the lighting is fixed and you want per-texel detail. ## Cost cheap — Runtime is a dot product of 9 to 25 coefficients per vertex; offline precomputation is heavy. Measured GPU Weight: 38.47× baseline (heavy) — 1.2655 ms median / 1.3318 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 33.05× baseline (heavy) — 0.5255 ms median (2.41× faster on L4). Ampere A100 scaling: 24.31× baseline (heavy) — 0.7001 ms median (1.81× faster on A100). ## Failure modes - Low-order SH cannot represent sharp shadows or glossy highlights, so shadows look soft and generic - Rigid geometry only: skinned meshes or moving occluders require recomputation - Large storage for glossy transfer matrices (n^2 by n^2 per sample point) - Ringing and negative values in the reconstructed radiance for strongly directional environments ## Dataflow - Inputs: mesh, hdr-image - Outputs: radiance - Platforms: desktop-gpu, webgl2, mobile-gpu ## Presets ### Precomputed Radiance Transfer — 9-band SH environment lighting with self-shadowed bounce (glsl-fragment; rendered 2026-11-30) ```json { "P_ENV_ROTATION": 1, "P_SH_ORDER": 2, "P_SELF_SHADOW": 0.88, "P_BOUNCE_GAIN": 0.68 } ``` ```glsl const float P_ENV_ROTATION = 1.0; // P Env Spin [0.0, 2.5, 0.05] const float P_SH_ORDER = 2.0; // P SH Band Order [0.0, 2.0, 1.0] const float P_SELF_SHADOW = 0.88; // P Self-Shadow [0.0, 1.4, 0.04] const float P_BOUNCE_GAIN = 0.68; // P Interreflection [0.0, 1.5, 0.04] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Sculpted concave/grooved architectural orb to showcase PRT self-shadowing & interreflection float mapSculpt(vec3 p) { float dSphere = length(p) - 0.82; // Carve three orthogonal concave bowl cavities and equatorial flute grooves float c1 = length(p - vec3(0.68, 0.22, 0.52)) - 0.42; float c2 = length(p - vec3(-0.62, 0.32, 0.48)) - 0.38; float c3 = length(p - vec3(0.05, -0.58, 0.58)) - 0.38; float d = max(dSphere, -c1); d = max(d, -c2); d = max(d, -c3); // Subtle sculpted relief rings float ring = 0.028 * sin(p.y * 18.0 + atan(p.z, p.x) * 4.0); d += ring * smoothstep(0.2, 0.75, length(p.xz)); return d * 0.78; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSculpt(p + e.xyy) - mapSculpt(p - e.xyy), mapSculpt(p + e.yxy) - mapSculpt(p - e.yxy), mapSculpt(p + e.yyx) - mapSculpt(p - e.yyx) )); } // Analytical rotating 3-band (L=0,1,2) Spherical Harmonics environment radiance vec3 evalSHEnv(vec3 d, float rotAng, float order) { vec3 dir = d; dir.xz = rot2(rotAng) * dir.xz; // Band 0 (DC ambient) vec3 L00 = vec3(0.42, 0.45, 0.54); vec3 irr = L00 * 0.8862; if (order >= 0.5) { // Band 1 (directional warm sun-sky dipole + cool cyan fill) vec3 L1m1 = vec3(0.24, 0.30, 0.46); // y vec3 L10 = vec3(0.45, 0.36, 0.24); // z vec3 L1p1 = vec3(0.88, 0.48, 0.18); // x irr += 1.0233 * (L1m1 * dir.y + L10 * dir.z + L1p1 * dir.x); } if (order >= 1.5) { // Band 2 (quadrupole crisp golden key lobe + indigo-magenta rim) vec3 L2m2 = vec3(0.32, 0.16, 0.28); vec3 L2m1 = vec3(0.28, 0.34, 0.48); vec3 L20 = vec3(0.38, 0.24, 0.14); vec3 L2p1 = vec3(0.68, 0.42, 0.16); vec3 L2p2 = vec3(0.46, 0.26, 0.34); irr += 0.4954 * ( L2m2 * (dir.x * dir.y) + L2m1 * (dir.y * dir.z) + L20 * (3.0 * dir.z * dir.z - 1.0) * 0.33 + L2p1 * (dir.x * dir.z) + L2p2 * (dir.x * dir.x - dir.y * dir.y) * 0.5 ); } return max(irr, vec3(0.02)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float rotAng = iTime * 0.75 * max(P_ENV_ROTATION, 0.0); float shOrder = clamp(P_SH_ORDER, 0.0, 2.0); float ssWeight = clamp(P_SELF_SHADOW, 0.0, 1.5); float bounceW = clamp(P_BOUNCE_GAIN, 0.0, 1.6); vec3 ro = vec3(0.0, 0.08, 2.55); vec3 rd = normalize(vec3(uv, -1.55)); // Background shows the rotated low-frequency SH environment directly vec3 col = evalSHEnv(rd, rotAng, shOrder) * 0.55; float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSculpt(ro + rd * t); if (d < 0.002) { hit = true; break; } t += d; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Estimate precomputed hemispherical visibility + bent normal (PRT transfer vector T_i) vec3 bentDir = n * 0.35; float visSum = 0.0; vec3 tangent = normalize(abs(n.y) < 0.9 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0))); vec3 bitan = cross(n, tangent); for (int k = 0; k < 6; k++) { float fk = float(k); float phi = fk * 1.0472 + 0.4; vec3 sDir = normalize(n * 0.62 + (cos(phi) * tangent + sin(phi) * bitan) * 0.78); float d1 = mapSculpt(p + sDir * 0.14); float d2 = mapSculpt(p + sDir * 0.34); float vSample = clamp(min(d1 / 0.14, d2 / 0.34), 0.0, 1.0); visSum += vSample; bentDir += sDir * vSample; } float visibility = mix(1.0, clamp(visSum / 6.0, 0.05, 1.0), ssWeight); vec3 bentN = normalize(mix(n, normalize(bentDir + 1e-4), 0.65 * ssWeight)); // Diffuse PRT transfer dot product: irradiance along visibility-weighted bent normal vec3 directSH = evalSHEnv(bentN, rotAng, shOrder) * visibility; // Second-bounce interreflection inside cavities (warm terracotta-ochre bounce) vec3 albedo = mix(vec3(0.84, 0.78, 0.72), vec3(0.86, 0.52, 0.34), smoothstep(0.75, 0.42, length(p))); vec3 bounceSH = evalSHEnv(-n, rotAng, shOrder) * (1.0 - visibility) * albedo * albedo * bounceW * 1.35; // Subtle specular SH sheen vec3 rDir = reflect(rd, n); float fres = 0.04 + 0.96 * pow(1.0 - max(dot(n, -rd), 0.0), 5.0); vec3 specSH = evalSHEnv(rDir, rotAng, shOrder) * fres * visibility * 0.55; col = albedo * directSH + bounceSH + specSH; } // Bottom-right SH light-probe inset sphere showing the active SH basis radiance vec2 probeC = vec2(0.35, -0.34); vec2 pd = uv - probeC; float pr = 0.11; float r2 = dot(pd, pd); if (r2 < pr * pr) { vec3 pn = normalize(vec3(pd, sqrt(max(pr * pr - r2, 0.0)))); col = evalSHEnv(pn, rotAng, shOrder); } else if (abs(length(pd) - pr) < 0.004) { col = vec3(0.92, 0.94, 0.98); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [All-Frequency Shadows via Wavelet Lighting](https://texelatlas.vercel.app/t/wavelet-all-frequency-relighting.md) ## Combines with - [Spherical-Harmonic Lighting (Irradiance Environment Maps)](https://texelatlas.vercel.app/t/spherical-harmonics-lighting.md): The environment is projected to SH each frame and dotted with per-vertex transfer coefficients. ## Combination ideas - [Day-cycle relighting for a dot product](https://texelatlas.vercel.app/ideas/time-of-day-prt/) ## Sources 1. [primary] Peter-Pike Sloan, Jan Kautz, John Snyder (2002) Precomputed radiance transfer for real-time rendering in dynamic, low-frequency lighting environments. ACM Transactions on Graphics. https://doi.org/10.1145/566654.566612 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Precomputed Radiance Transfer." https://texelatlas.vercel.app/t/precomputed-radiance-transfer/ (accessed 2026-12-01). --- id: "preetham-sky" title: "Preetham Analytic Daylight Model" aliases: [Perez sky, A Practical Analytic Model for Daylight] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 1999 inputs: [material-params] outputs: [radiance, hdr-image] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Preetham et al., 1999" url: "https://texelatlas.vercel.app/t/preetham-sky/" sources_verified_at: "2026-11-29" --- # Preetham Analytic Daylight Model (Preetham et al., 1999) > Closed-form sky luminance and chromaticity as a function of sun position and turbidity, using Perez distribution coefficients fitted to simulations; trivial to run per pixel. ## Reach for it when - need a quick sky dome with a sun angle slider - cheap daylight sky for a demo - sky lighting for image-based lighting without textures - turbidity-controlled haze on a procedural sky - small shader that gives a plausible sky ## How it works The model computes the xyY color of any sky direction. Luminance and the two chromaticities each follow a Perez formula: a product of a gradient term over zenith angle and a scattering-indicatrix term over the angle to the sun, normalized by the same expression evaluated at the zenith. The five Perez coefficients for each channel are linear functions of turbidity, and the zenith values are polynomial fits of turbidity and sun elevation. Aerial perspective is a separate approximate analytic extinction and in-scatter along the ray. Everything is evaluated in a fragment shader from a handful of constants, then converted xyY to RGB and tonemapped. Turbidity (roughly clear to hazy) is the main art control. ## When to use it Choose it for a quick, cheap sky dome with turbidity and sun-angle sliders, for background skies in demos, and for feeding a plausible environment light into image-based lighting. Prefer [Hosek-Wilkie Sky Model](https://texelatlas.vercel.app/t/hosek-wilkie-sky.md) for better accuracy near the horizon and in the circumsolar region, and for ground-albedo control. Prefer [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) or [Precomputed Atmospheric Scattering](https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering.md) when the camera leaves the ground, you need sunsets below the horizon, or you need atmosphere on geometry. ## Cost cheap — A few dozen ALU operations per pixel, no textures. Measured GPU Weight: 3.71× baseline (light) — 0.122 ms median / 0.1285 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.22× baseline (light) — 0.0512 ms median (2.38× faster on L4). Ampere A100 scaling: 2.18× baseline (light) — 0.0627 ms median (1.95× faster on A100). ## Failure modes - Sky below the horizon and around sunset is unreliable; the fit was made for sun elevations above the horizon - Overly dark or saturated zenith at low turbidity and low sun - Perez term overestimates glow near the horizon, producing a flat white band - Only valid from ground level: no altitude, no planet curvature, no space view - Circumsolar region is smooth, so there is no realistic sun disc, only an added blob ## Engine support - babylonjs: official — `@babylonjs/materials SkyMaterial (Preetham atmospheric scattering)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/materials/src/sky/skyMaterial.ts, checked 2026-12-01) - blender: builtin — `Sky Texture node > Sky Type = Preetham` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/sky.html, checked 2026-12-01) — Marked legacy and slated for removal. - threejs: official — `import { Sky } from 'three/addons/objects/Sky.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/objects/Sky.js, checked 2026-12-01) ## Dataflow - Inputs: material-params - Outputs: radiance, hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Preetham analytic sky: turbidity 2 (left) vs 8 (right) (glsl-fragment; rendered 2026-11-29) ```json { "turbidity_left": 2, "turbidity_right": 8 } ``` ```glsl // Preetham analytic daylight sky (Perez luminance distribution in xyY, turbidity-driven coefficients). // Same view and sun in both halves; only turbidity changes: left T=2 (clear), right T=8 (hazy). vec3 preetham(vec3 rd, vec3 sd, float T) { float ts = acos(clamp(sd.y, -1.0, 1.0)); float ct = max(rd.y, 0.02); float gam = acos(clamp(dot(rd, sd), -1.0, 1.0)); vec3 cA = vec3(0.1787 * T - 1.4630, -0.0193 * T - 0.2592, -0.0167 * T - 0.2608); vec3 cB = vec3(-0.3554 * T + 0.4275, -0.0665 * T + 0.0008, -0.0950 * T + 0.0092); vec3 cC = vec3(-0.0227 * T + 5.3251, -0.0004 * T + 0.2125, -0.0079 * T + 0.2102); vec3 cD = vec3(0.1206 * T - 2.5771, -0.0641 * T - 0.8989, -0.0441 * T - 1.6537); vec3 cE = vec3(-0.0670 * T + 0.3703, -0.0033 * T + 0.0452, -0.0109 * T + 0.0529); float chi = (4.0 / 9.0 - T / 120.0) * (3.14159 - 2.0 * ts); float Yz = (4.0453 * T - 4.9710) * tan(chi) - 0.2155 * T + 2.4192; float t2 = ts * ts, t3 = t2 * ts; float xz = T * T * (0.00166 * t3 - 0.00375 * t2 + 0.00209 * ts) + T * (-0.02903 * t3 + 0.06377 * t2 - 0.03202 * ts + 0.00394) + (0.11693 * t3 - 0.21196 * t2 + 0.06052 * ts + 0.25886); float yz = T * T * (0.00275 * t3 - 0.00610 * t2 + 0.00317 * ts) + T * (-0.04214 * t3 + 0.08970 * t2 - 0.04153 * ts + 0.00516) + (0.15346 * t3 - 0.26756 * t2 + 0.06669 * ts + 0.26688); vec3 zen = vec3(Yz, xz, yz); vec3 F = (1.0 + cA * exp(cB / ct)) * (1.0 + cC * exp(cD * gam) + cE * cos(gam) * cos(gam)); vec3 F0 = (1.0 + cA * exp(cB)) * (1.0 + cC * exp(cD * ts) + cE * cos(ts) * cos(ts)); vec3 xyY = zen * F / F0; float X = xyY.y / xyY.z * xyY.x, Z = (1.0 - xyY.y - xyY.z) / xyY.z * xyY.x; return vec3(3.2406 * X - 1.5372 * xyY.x - 0.4986 * Z, -0.9689 * X + 1.8758 * xyY.x + 0.0415 * Z, 0.0557 * X - 0.2040 * xyY.x + 1.0570 * Z); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 rd = normalize(vec3(uv.x * 1.4, uv.y * 1.4 + 0.5, -1.0)); vec3 sd = normalize(vec3(0.35, 0.55, -0.75)); float T = fragCoord.x < 0.5 * iResolution.x ? 2.0 : 8.0; vec3 col = max(preetham(rd, sd, T), 0.0) * 0.07; if (rd.y < 0.0) col = mix(col, vec3(0.04, 0.045, 0.04) * (1.0 + 0.1 * T), smoothstep(0.0, -0.03, rd.y)); col = 1.0 - exp(-col * 1.4); if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Hosek-Wilkie Sky Model](https://texelatlas.vercel.app/t/hosek-wilkie-sky.md) ## Combines with - [Exponential Height Fog](https://texelatlas.vercel.app/t/exponential-height-fog.md): Fog color is taken from the sky model's horizon radiance so distant geometry fades into the sky. ## Sources 1. [primary] A. J. Preetham, Peter Shirley, Brian Smits (1999) A practical analytic model for daylight. Proceedings of the 26th annual conference on Computer graphics and interactive techniques - SIGGRAPH '99. https://doi.org/10.1145/311535.311545 (verified via crossref on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Preetham Analytic Daylight Model." https://texelatlas.vercel.app/t/preetham-sky/ (accessed 2026-12-01). --- id: "procedural-city-roads" title: "Procedural City Generation (L-system Road Networks)" aliases: [Parish and Müller city generation, CityEngine road growth] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, houdini, blender, unity, unreal] year_introduced: 2001 inputs: [heightfield, texture] outputs: [graph, layout, mesh] style: "photoreal" dynamic: "static" cost: "medium" authority: "Parish & Müller, 2001" url: "https://texelatlas.vercel.app/t/procedural-city-roads/" sources_verified_at: "2026-11-29" --- # Procedural City Generation (L-system Road Networks) (Parish & Müller, 2001) > Generate a city by growing a street network with an extended L-system that responds to population-density and terrain maps, then subdividing the blocks into lots and extruding buildings. ## Reach for it when - generate a believable street network automatically - road layouts should follow terrain and population - want city roads with highways and local streets - fill a large world with plausible urban layout ## How it works The pipeline starts from input maps (elevation, water, population density). An extended L-system grows the road network: each road segment either continues or branches, with parameters adjusted by the local maps and by local constraints such as avoiding water or slopes, and segments snap to nearby intersections to form a connected graph. Road patterns (grid, radial, organic) are set per region. The enclosed regions between roads are extracted as blocks and recursively subdivided into building lots, and buildings are generated per lot (originally with a lot-specific L-system, later with CGA-style grammars). Textured facades then dress the geometry. ## When to use it Choose it to generate road graphs and block structure for settlements that respond to terrain and density maps. Prefer [CGA Shape Grammar (Procedural Buildings)](https://texelatlas.vercel.app/t/cga-shape-grammar.md) for the building detail pass, [Voronoi Diagrams and Lloyd Relaxation](https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation.md) for organic block subdivision, [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md) for scattering trees or props in the blocks, and [BSP Dungeon Generation](https://texelatlas.vercel.app/t/bsp-dungeon-generation.md) for interior or room layouts. ## Cost medium — Road growth and lot subdivision are fast; building mesh generation dominates for large cities. Measured GPU Weight: 7.16× baseline (moderate) — 0.2354 ms median / 0.2419 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.45× baseline (light) — 0.0866 ms median (2.72× faster on L4). Ampere A100 scaling: 4.42× baseline (light) — 0.1273 ms median (1.85× faster on A100). ## Failure modes - Road graphs get dead ends, tiny blocks or non-planar crossings unless snapping and cleanup rules are applied - Lots with unusual shapes cannot hold buildings and are left empty or filled with bad footprints - Growth near water or slopes may violate constraints without careful cost functions - Parameter interplay is non-obvious, so tuning city 'feel' is trial and error ## Dataflow - Inputs: heightfield, texture - Outputs: graph, layout, mesh - Platforms: cpu, houdini, blender, unity, unreal ## Presets ### Procedural city roads — tensor-guided arterials, parcel blocks & night traffic streams (glsl-fragment; rendered 2026-11-30) ```json { "P_GRID_SCALE": 5.2, "P_CURVATURE": 0.75, "P_TRAFFIC_SPEED": 1, "P_BLOCK_DENSITY": 0.82 } ``` ```glsl const float P_GRID_SCALE = 5.2; // P District Scale [2.5, 9.0, 0.2] const float P_CURVATURE = 0.75; // P Tensor Warp [0.0, 1.6, 0.05] const float P_TRAFFIC_SPEED = 1.0; // P Traffic Flow [0.0, 2.5, 0.05] const float P_BLOCK_DENSITY = 0.82; // P Building Density [0.2, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Smooth urban tensor-field coordinate warp (curves streets along river & ring roads) vec2 cityWarp(vec2 p, float curv) { vec2 w = vec2( 0.26 * sin(p.y * 0.55 + 0.4) + 0.14 * cos(p.x * 0.35 - p.y * 0.45), 0.24 * cos(p.x * 0.52 - 0.3) + 0.12 * sin(p.x * 0.42 + p.y * 0.38) ); return p + w * curv; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / iResolution.y; float scale = clamp(P_GRID_SCALE, 2.0, 10.0); float curv = clamp(P_CURVATURE, 0.0, 1.8); float spd = max(P_TRAFFIC_SPEED, 0.0); float bDens = clamp(P_BLOCK_DENSITY, 0.15, 1.0); vec2 pan = vec2(iTime * 0.12, iTime * 0.06); vec2 p = uv * scale + pan; // Winding river channel cutting across the city float riverCenter = 0.55 * sin(p.x * 0.48 + 0.6) - 0.25 * cos(p.x * 0.95); float dRiver = abs(p.y - riverCenter); float isWater = smoothstep(0.44, 0.36, dRiver); float riverBank = smoothstep(0.54, 0.42, dRiver) * (1.0 - isWater); // Tensor-warped street lattice vec2 wp = cityWarp(p, curv); // Level 1: Primary arterial boulevards (coarse grid) vec2 artCell = floor(wp * 0.5); vec2 artF = abs(fract(wp * 0.5 + 0.5) - 0.5); float dArt = min(artF.x, artF.y); float isArterial = smoothstep(0.055, 0.032, dArt); float artCenter = smoothstep(0.012, 0.003, dArt); // Level 2: Secondary avenues (subdivision per district) vec2 secF = abs(fract(wp * 1.5 + 0.5) - 0.5); float dSec = min(secF.x, secF.y); float isSecondary = smoothstep(0.068, 0.038, dSec) * (1.0 - isWater); // Level 3: Local residential streets & building parcels vec2 blkId = floor(wp * 1.5); float blkRand = hash21(blkId); float subDiv = mix(3.0, 4.5, step(0.45, blkRand)); vec2 locF = abs(fract(wp * subDiv) - 0.5); vec2 parcelId = floor(wp * subDiv); float pRand = hash21(parcelId + blkId * 17.0); float dLoc = min(locF.x, locF.y); float isLocal = smoothstep(0.085, 0.045, dLoc) * (1.0 - isWater); // Base urban night map: dark slate blocks + landscaped parks float isPark = step(bDens, blkRand) * (1.0 - isWater); vec3 blockCol = mix(vec3(0.045, 0.055, 0.075), vec3(0.055, 0.12, 0.085), isPark); // Illuminated architectural building footprints inside non-park parcels float pad = 0.14 + 0.10 * pRand; float bldg = smoothstep(0.5 - pad + 0.03, 0.5 - pad - 0.02, max(locF.x, locF.y)); bldg *= (1.0 - isPark) * (1.0 - isWater) * step(0.18, pRand); float height = 0.35 + 0.65 * hash21(parcelId * 3.1 + 7.2); vec3 bldgCol = mix(vec3(0.09, 0.12, 0.18), vec3(0.22, 0.28, 0.38), height); // Warm window perimeter glow float winEdge = smoothstep(0.5 - pad - 0.08, 0.5 - pad - 0.02, max(locF.x, locF.y)) * bldg; bldgCol += vec3(0.95, 0.68, 0.28) * winEdge * (0.35 + 0.65 * step(0.52, pRand)); vec3 col = mix(blockCol, bldgCol, bldg); // River water with subtle moonlight shimmer vec3 waterCol = vec3(0.025, 0.065, 0.12) + vec3(0.04, 0.11, 0.18) * (0.5 + 0.5 * sin(p.x * 6.0 + p.y * 8.0 - iTime * 1.4)); col = mix(col, vec3(0.08, 0.15, 0.12), riverBank * 0.7); col = mix(col, waterCol, isWater); // Composite road hierarchy (arterials bridge cleanly over the river!) vec3 locRoad = vec3(0.13, 0.16, 0.22); vec3 secRoad = vec3(0.24, 0.29, 0.38); vec3 artRoad = vec3(0.32, 0.36, 0.44); col = mix(col, locRoad, isLocal * 0.85); col = mix(col, secRoad, isSecondary * 0.92); col = mix(col, artRoad, isArterial); // Glowing golden arterial centerlines & moving traffic light pulses float laneX = smoothstep(0.032, 0.008, artF.y); float laneY = smoothstep(0.032, 0.008, artF.x); float carsX = pow(0.5 + 0.5 * sin(wp.x * 11.0 - iTime * 3.4 * spd + artCell.y * 4.0), 10.0) * laneX; float carsY = pow(0.5 + 0.5 * sin(wp.y * 11.0 + iTime * 2.9 * spd + artCell.x * 5.0), 10.0) * laneY; float secCars = pow(0.5 + 0.5 * sin((wp.x + wp.y) * 18.0 - iTime * 2.4 * spd), 12.0) * isSecondary; col += vec3(1.0, 0.74, 0.26) * artCenter * 0.55; col += vec3(1.4, 0.92, 0.42) * carsX * 1.15; col += vec3(0.35, 0.88, 1.25) * carsY * 1.05; col += vec3(1.0, 0.45, 0.35) * secCars * 0.55; // Intersection nodes glow warmly float inter = smoothstep(0.075, 0.015, length(artF)); col += vec3(1.15, 0.82, 0.38) * inter * 0.65; // Blueprint framing vignette col *= 1.0 - 0.22 * dot(uv, uv) + 0.0 * px; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) ## Combination ideas - [Cities wired by slime mould](https://texelatlas.vercel.app/ideas/slime-mould-road-networks/) ## Sources 1. [primary] Yoav I. H. Parish, Pascal Müller (2001) Procedural modeling of cities. Proceedings of the 28th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/383259.383292 (verified via crossref on 2026-11-29) 2. [implementation] ProbableTrain (2020) ProbableTrain/MapGenerator. https://github.com/ProbableTrain/MapGenerator License: LGPL-3.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Procedural City Generation (L-system Road Networks)." https://texelatlas.vercel.app/t/procedural-city-roads/ (accessed 2026-12-01). --- id: "procedural-cross-hatching" title: "Procedural cross-hatching shader" aliases: [hatching shader] domain: "npr" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2001 inputs: [normals, depth] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Praun et al., 2001" url: "https://texelatlas.vercel.app/t/procedural-cross-hatching/" sources_verified_at: "2026-11-29" --- # Procedural cross-hatching shader (Praun et al., 2001) > Generates hatch lines in the fragment shader from line functions at several angles, enabling more layers as lighting gets darker, without any pre-authored textures. ## Reach for it when - want pen-and-ink shading without authored textures - hatch lines should get denser in darker areas - need engraving look on generated geometry - texture-free sketch style as a post process ## How it works The shader computes a tone value, from N·L or a luminance buffer, and defines a set of line masks: periodic functions of a rotated coordinate (such as `abs(fract(x)-0.5)`) thresholded to a line width. Darker tones enable more layers: first one diagonal, then the crossing diagonal, then horizontal, then vertical, each gated by a threshold on tone. Coordinates come from screen space (simple, gives the 'shower door' effect), object space or triplanar projection (sticks to surfaces), or a UV-based direction field. Smoothstep with `fwidth` anti-aliases lines. A paper texture and slight wobble from noise sell the hand-drawn effect, and wobble that is stable across frames avoids shimmering. ## When to use it Choose it for fast, texture-free pen-and-ink shading, especially as a post-process or on procedurally generated geometry. Prefer [Real-time hatching with tonal art maps](https://texelatlas.vercel.app/t/tonal-art-maps.md) when strokes should be hand-drawn, follow the surface direction and be stable across mip levels. Prefer [Halftone screens](https://texelatlas.vercel.app/t/halftone-screen.md) when the dot-based print look is wanted rather than lines. ## Cost cheap — One pass with a few trig and fract ops per layer; negligible. Measured GPU Weight: 2.55× baseline (light) — 0.0839 ms median / 0.0884 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.79× baseline (feather) — 0.0285 ms median (2.94× faster on L4). Ampere A100 scaling: 1.52× baseline (feather) — 0.0439 ms median (1.91× faster on A100). ## Failure modes - Screen-space coordinates make lines slide over moving objects (shower-door effect) - Lines of fixed pixel width alias when sampled coarsely or moire when layers align - Hard thresholds between layers cause visible popping across smooth lighting - No sense of surface direction unless a direction field is supplied ## Dataflow - Inputs: normals, depth - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Four-layer procedural hatching on a lit sphere (glsl-fragment; rendered 2026-11-29) ```json { "freq": 70, "width": 0.16 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: screen-space cross-hatching driven by a lit sphere const vec3 PAPER = vec3(0.96, 0.93, 0.84); const vec3 INK = vec3(0.10, 0.12, 0.25); const float FREQ = 70.0; // hatch lines per unit height const float WIDTH = 0.16; // line half-width (fraction of spacing) float hatch(vec2 p, float ang){ float v = (p.x*cos(ang) - p.y*sin(ang)) * FREQ; float d = abs(fract(v) - 0.5); // 0.5 between lines, 0 on the line centre float aa = fwidth(v); return 1.0 - smoothstep(0.5 - WIDTH*2.0 - aa, 0.5 - WIDTH*2.0 + aa, d); } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = (fragCoord - 0.5*iResolution.xy) / iResolution.y; float tone = 0.92; vec2 c = uv - vec2(0.0, 0.03); float r = length(c); if(r < 0.33){ vec3 n = vec3(c, sqrt(0.33*0.33 - r*r)) / 0.33; vec3 l = normalize(vec3(-0.55 + 0.15*sin(iTime), 0.65, 0.55)); tone = clamp(dot(n, l)*0.9 + 0.1, 0.0, 1.0); } else { float shadow = smoothstep(0.38, 0.1, length((uv - vec2(0.18, -0.34))*vec2(0.6, 1.8))); tone = 0.92 - 0.6*shadow; } float dark = 1.0 - tone; float ink = 0.0; ink = max(ink, step(0.12, dark) * hatch(uv, 0.785)); ink = max(ink, step(0.35, dark) * hatch(uv, -0.785)); ink = max(ink, step(0.55, dark) * hatch(uv, 0.0)); ink = max(ink, step(0.75, dark) * hatch(uv, 1.571)); fragColor = vec4(mix(PAPER, INK, ink), 1.0); } ``` Attribution: written for this index ## Combines with - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Outline pass adds contour lines over the hatched tone. ## Sources 1. [primary] Emil Praun, Hugues Hoppe, Matthew Webb, Adam Finkelstein (2001) Real-time hatching. Proceedings of the 28th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/383259.383328 (verified via crossref on 2026-11-29) 2. [tutorial] Wikipedia Hatching. en.wikipedia.org. https://en.wikipedia.org/wiki/Hatching (verified via http on 2026-11-29) ## Cite this entry Texel. "Procedural cross-hatching shader." https://texelatlas.vercel.app/t/procedural-cross-hatching/ (accessed 2026-12-01). --- id: "procedural-kit-modeling" title: "Procedural Kit Modeling with Verification (procgen-kit)" aliases: [parametric kit builder, LLM-driven kit modeling] domain: "procgen" stage: "procedural" realtime: "offline" platforms: [cpu, python] year_introduced: 2025 inputs: [text-prompt] outputs: [mesh, graph] style: "both" dynamic: "static" cost: "offline" authority: "wrong-nebula, 2026" url: "https://texelatlas.vercel.app/t/procedural-kit-modeling/" sources_verified_at: "2026-11-29" --- # Procedural Kit Modeling with Verification (procgen-kit) (wrong-nebula, 2026) > Describe a modular 3D kit as a short script that builds a parametric geometry graph, then mechanically check it: closed manifold meshes, every control swept across its range, touching parts and collision. ## Reach for it when - llm-generated modular props have broken geometry - need parametric walls and gates that stay valid at any setting - check meshes are closed and manifold automatically - script a game-ready kit and verify collisions - sliders produce overlapping or leaking parts ## How it works A kit builder script (typically written by a language model) declares parts, controls and their relationships; a native core turns it into a parametric geometry graph whose geometry is regenerated when controls change. A verification harness then sweeps each control to its limits and checks invariants: meshes stay closed and manifold, parts that should touch do touch, and collision tests (e.g. with convex decompositions in a physics engine) pass. Failures give the author concrete diagnostics to fix, so correctness is machine-checked instead of eyeballed. Renders (beauty, clay, parts passes) support review. This differs from random procedural generation: the output is a controllable, verified asset family. ## When to use it Choose it when an LLM or script must produce parametric, game-ready modular kits (walls, gates, props) whose geometry has to be valid at every parameter setting. Prefer [CGA Shape Grammar (Procedural Buildings)](https://texelatlas.vercel.app/t/cga-shape-grammar.md) for rule-based building facades at city scale, [Greebling](https://texelatlas.vercel.app/t/greebling.md) for decorative surface noise, and [Infinigen (Procedural Photorealistic Worlds)](https://texelatlas.vercel.app/t/infinigen.md) for photorealistic natural scenes. ## Cost offline — Native geometry build is fast; the verification sweep multiplies cost by number of controls and test poses. Measured GPU Weight: 29.68× baseline (heavy) — 0.9765 ms median / 1.0122 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.37× baseline (heavy) — 0.4352 ms median (2.24× faster on L4). Ampere A100 scaling: 18.62× baseline (moderate) — 0.5362 ms median (1.82× faster on A100). ## Failure modes - Verification only covers swept controls and the checks it implements; unmodelled interactions can still fail - Quality of the kit is bounded by the builder script, which a weak model may get geometrically wrong - Complex organic forms are outside the parametric-part vocabulary - Requires building the C++ core and a Python toolchain ## Dataflow - Inputs: text-prompt - Outputs: mesh, graph - Platforms: cpu, python ## Presets ### Procedural Kit Modeling — manifold, contact-joint & clearance checks (left) vs parametric CAD assembly sweep (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ARCH_SPAN": 0.58, "P_COL_HEIGHT": 0.72, "P_FLANGE_RAD": 0.28, "P_SPLIT": 0.48 } ``` ```glsl const float P_ARCH_SPAN = 0.58; // P Arch Span [0.35, 0.82, 0.02] const float P_COL_HEIGHT = 0.72; // P Column Height [0.42, 0.95, 0.02] const float P_FLANGE_RAD = 0.28; // P Flange Radius [0.16, 0.38, 0.02] const float P_SPLIT = 0.48; // P Verify / CAD Split [0.0, 1.0, 0.02] 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); } float sdCylinder(vec3 p, float r, float h) { vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h); return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)); } // Modular parametric architectural kit with exact contact constraints between base -> columns -> entablature -> finial! vec2 mapKit(vec3 p, float span, float colH, float flR) { float baseTop = -0.52; float colTop = baseTop + colH; // Part 1: Stepped plinth base (exact top plane y = baseTop) float dBase = sdBox(p - vec3(0.0, baseTop - 0.09, 0.0), vec3(span + flR + 0.08, 0.09, flR + 0.14)) - 0.015; vec2 res = vec2(dBase, 1.0); // Part 2: Twin interlocking fluted columns mating flush on y = baseTop and y = colTop vec3 pSym = vec3(abs(p.x) - span * 0.78, p.y - (baseTop + colH * 0.5), p.z); float ang = atan(pSym.z, pSym.x); float flute = 0.012 * cos(ang * 10.0); float dCol = sdCylinder(pSym, flR * 0.56 + flute, colH * 0.5); // Lower & upper mating collar flanges snapped to exact joint planes float dCollarB = sdCylinder(vec3(pSym.x, p.y - (baseTop + 0.035), pSym.z), flR * 0.78, 0.035); float dCollarT = sdCylinder(vec3(pSym.x, p.y - (colTop - 0.035), pSym.z), flR * 0.78, 0.035); float dCols = min(dCol, min(dCollarB, dCollarT)); if (dCols < res.x) res = vec2(dCols, 2.0); // Part 3: Spanning architrave beam & carved arch void resting flush on y = colTop float beamH = 0.24; vec3 pBeam = p - vec3(0.0, colTop + beamH * 0.5, 0.0); float dBeam = sdBox(pBeam, vec3(span + flR * 0.92, beamH * 0.5, flR * 0.72)) - 0.012; float archCut = length(vec2(p.x, p.y - colTop)) - (span * 0.55); dBeam = max(dBeam, -archCut); if (dBeam < res.x) res = vec2(dBeam, 3.0); // Part 4: Crown lantern finial snapped flush on top of architrave (y = colTop + beamH) float finialY = colTop + beamH; float dFinial = min( sdCylinder(p - vec3(0.0, finialY + 0.08, 0.0), flR * 0.45, 0.08), length(p - vec3(0.0, finialY + 0.22, 0.0)) - flR * 0.36 ); if (dFinial < res.x) res = vec2(dFinial, 4.0); return res; } vec3 calcNormal(vec3 p, float span, float colH, float flR) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapKit(p + e.xyy, span, colH, flR).x - mapKit(p - e.xyy, span, colH, flR).x, mapKit(p + e.yxy, span, colH, flR).x - mapKit(p - e.yxy, span, colH, flR).x, mapKit(p + e.yyx, span, colH, flR).x - mapKit(p - e.yyx, span, colH, flR).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showCAD = sx >= split; // Gently sweep parameters around user slider targets to demonstrate continuous mechanical verification! float sweep = sin(iTime * 0.75); float span = clamp(P_ARCH_SPAN + 0.10 * sweep, 0.32, 0.88); float colH = clamp(P_COL_HEIGHT + 0.10 * cos(iTime * 0.62), 0.38, 0.98); float flR = clamp(P_FLANGE_RAD, 0.14, 0.40); float orb = iTime * 0.34 + 0.35; vec3 ro = vec3(2.45 * sin(orb), 0.42, 2.45 * cos(orb)); vec3 ta = vec3(0.0, -0.05, 0.0); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.48 + ri * uv.x + up * uv.y); vec3 bg = mix(vec3(0.05, 0.065, 0.095), vec3(0.14, 0.18, 0.26), smoothstep(-0.3, 0.6, rd.y)); vec3 col = bg; // Floor plane at y = -0.715 float tHit = 1e5; float hitId = 0.0; if (rd.y < -0.005) { float tf = (-0.715 - ro.y) / rd.y; if (tf > 0.05 && tf < 14.0) { tHit = tf; hitId = 10.0; } } float t = 0.05; for (int i = 0; i < 64; i++) { vec2 h = mapKit(ro + rd * t, span, colH, flR); if (h.x < 0.0018) { if (t < tHit) { tHit = t; hitId = h.y; } break; } t += h.x; if (t > min(tHit, 7.5)) break; } if (hitId > 0.5) { vec3 p = ro + rd * tHit; vec3 v = -rd; vec3 L = normalize(vec3(0.62, 0.82, 0.52)); if (hitId > 9.0) { // Studio blueprint floor grid vec2 g = abs(fract(p.xz * 2.5) - 0.5); float line = smoothstep(0.035, 0.008, min(0.5 - g.x, 0.5 - g.y)); vec3 fCol = mix(vec3(0.07, 0.09, 0.13), vec3(0.22, 0.34, 0.48), line * 0.65); float ao = smoothstep(0.15, 1.25, length(p.xz)); col = mix(fCol * (0.45 + 0.55 * ao), bg, 1.0 - exp(-tHit * 0.14)); } else { vec3 n = calcNormal(p, span, colH, flR); float baseTop = -0.52; float colTop = baseTop + colH; float finY = colTop + 0.24; if (!showCAD) { // Left: Mechanical verification diagnostic overlay (per-part manifold ID colors + bright green mating-joint verification rings!) vec3 partCol = vec3(0.22, 0.52, 0.82); if (hitId > 1.5 && hitId < 2.5) partCol = vec3(0.28, 0.72, 0.68); else if (hitId > 2.5 && hitId < 3.5) partCol = vec3(0.84, 0.56, 0.22); else if (hitId > 3.5) partCol = vec3(0.72, 0.38, 0.86); float ndl = 0.38 + 0.62 * max(dot(n, L), 0.0); // Subtle parametric iso-slice wireframe confirming watertight closed manifold float iso = smoothstep(0.05, 0.012, abs(fract(p.y * 10.0) - 0.5)); col = partCol * ndl + vec3(0.85, 0.94, 1.0) * iso * 0.14; // Glowing emerald snap rings at exact mathematical contact planes (touching-part verification PASS!) float j1 = smoothstep(0.022, 0.004, abs(p.y - baseTop)); float j2 = smoothstep(0.022, 0.004, abs(p.y - colTop)); float j3 = smoothstep(0.022, 0.004, abs(p.y - finY)); float jointGlow = clamp(j1 + j2 + j3, 0.0, 1.0); col = mix(col, vec3(0.18, 1.0, 0.45) * 1.45, jointGlow); } else { // Right: Crisp shaded stone & brushed-bronze parametric kit assembly vec3 alb = vec3(0.76, 0.73, 0.68); float met = 0.0; if (hitId > 3.5) { alb = vec3(0.86, 0.68, 0.36); met = 0.75; } else if (hitId > 2.5) alb = vec3(0.82, 0.79, 0.74); vec3 H = normalize(L + v); float ndl = max(dot(n, L), 0.0); float spec = pow(max(dot(n, H), 0.0), mix(24.0, 68.0, met)) * mix(0.35, 1.25, met); vec3 skyFill = mix(vec3(0.16, 0.20, 0.28), vec3(0.40, 0.52, 0.72), 0.5 + 0.5 * n.y); col = alb * (vec3(1.32, 1.22, 1.05) * ndl + skyFill * 0.48) + mix(vec3(1.0), alb, met) * spec; } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] wrong-nebula (2026) wrong-nebula/procgen-kit. https://github.com/wrong-nebula/procgen-kit License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Procedural Kit Modeling with Verification (procgen-kit)." https://texelatlas.vercel.app/t/procedural-kit-modeling/ (accessed 2026-12-01). --- id: "procedural-noise-texturing" title: "Procedural noise for texturing" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender, houdini, unity, unreal, godot] year_introduced: 2010 inputs: [uv-atlas] outputs: [texture, material-params] style: "both" dynamic: "both" cost: "cheap" authority: "Lagae et al., 2010" url: "https://texelatlas.vercel.app/t/procedural-noise-texturing/" sources_verified_at: "2026-11-29" --- # Procedural noise for texturing (Lagae et al., 2010) > Generate texture detail from functions instead of images: value, gradient, Worley and sparse-convolution noises, summed as fBm or warped, evaluated per pixel with infinite resolution and no memory. Lagae et al. survey the families and their trade-offs. ## Reach for it when - need endless unique textures with no tiling - make clouds, marble or terrain from code - textures too repetitive and memory heavy - organic randomness for materials and heightmaps ## How it works A noise function is a smooth, band-limited pseudo-random scalar field. Lattice noises (value, gradient/Perlin, simplex) interpolate hashed values or gradients at integer grid points. Sparse-convolution noises (sparse Gabor, anisotropic kernels) scatter kernels at random points and allow controlled spectrum and anisotropy. Cellular (Worley) noise measures distance to the nearest feature points. Layering octaves with doubling frequency and halving amplitude (fBm) gives natural spectra; domain warping, ridged or turbulence forms and colour ramps convert them into marble, wood, clouds or rust. A shader evaluates them per pixel in object or world space, avoiding UVs entirely, and can be filtered analytically by fading high octaves with pixel footprint. ## When to use it Choose it for tileless, resolution-independent surface variation, masks, roughness breakup and layering variation over image textures. Prefer [Histogram-preserving blending (stochastic texturing)](https://texelatlas.vercel.app/t/histogram-preserving-blending.md) or [Image quilting](https://texelatlas.vercel.app/t/image-quilting.md) when you must reproduce a specific photographic exemplar. Prefer [Weathering simulation (weathered stone)](https://texelatlas.vercel.app/t/weathering-simulation.md) when wear should follow geometry and exposure instead of random fields. Use blue-noise methods for sampling patterns, not for texture patterns. ## Cost cheap — A few hashed lookups per octave; cost scales linearly with octave count. Measured GPU Weight: 24.91× baseline (heavy) — 0.8197 ms median / 0.858 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.06× baseline (heavy) — 0.3348 ms median (2.45× faster on L4). Ampere A100 scaling: 16.54× baseline (moderate) — 0.4763 ms median (1.72× faster on A100). ## Failure modes - Visible grid alignment and axis-aligned artefacts in value and cheap Perlin noise - Hash functions with poor precision band or repeat at large coordinates, particularly on mobile (float precision) - Aliasing and shimmer when octaves above Nyquist are not faded out - Looks 'procedural' and uniform without masks or warping ## Engine support - babylonjs: builtin — `new BABYLON.NoiseProceduralTexture(...) and Node Material SimplexPerlin3DBlock / WorleyNoise3DBlock / CloudBlock` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Textures/Procedurals/noiseProceduralTexture.pure.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Texture > Noise Texture` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/noise.html, checked 2026-12-01) - godot: builtin — `NoiseTexture2D.noise = FastNoiseLite` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/noise/doc_classes/NoiseTexture2D.xml, checked 2026-12-01) - threejs: builtin — `import { mx_noise_float, mx_fractal_noise_float } from 'three/tsl'` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/materialx/MaterialXNodes.js, checked 2026-12-01) — TSL noise nodes. - unity: builtin — `Shader Graph > Simple Noise / Gradient Noise / Voronoi nodes` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Gradient-Noise-Node.md, checked 2026-12-01) — Shader Graph noise nodes. - unreal: builtin — `Material graph: Noise and VectorNoise expressions (Simplex, Gradient, Voronoi)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/utility-material-expressions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: uv-atlas - Outputs: texture, material-params - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender, houdini, unity, unreal, godot ## Presets ### Domain-warped fBm marble (glsl-fragment; rendered 2026-11-29) ```json { "OCTAVES": 6, "FREQ": 3, "WARP": 1.6, "VEIN": 6 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: marble-like turbulence from fBm value noise const int OCTAVES = 6; const float FREQ = 3.0; const float WARP = 1.6; const float VEIN = 6.0; float hash(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f); float a = hash(i), b = hash(i + vec2(1.0, 0.0)); float c = hash(i + vec2(0.0, 1.0)), d = hash(i + vec2(1.0, 1.0)); return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); } float fbm(vec2 p) { float s = 0.0, a = 0.5; for (int i = 0; i < OCTAVES; i++) { s += a * vnoise(p); p = p * 2.03 + vec2(17.1, 9.2); a *= 0.5; } return s; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 p = uv * FREQ; float w = fbm(p + 0.15 * iTime); float t = fbm(p + WARP * vec2(w, fbm(p + 3.7))); float vein = abs(sin((uv.x * 2.0 + t * VEIN) * 3.14159)); vein = pow(1.0 - vein, 6.0); vec3 stone = mix(vec3(0.80, 0.78, 0.74), vec3(0.93, 0.92, 0.90), t); vec3 col = mix(stone, vec3(0.18, 0.20, 0.24), vein * 0.8); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] A. Lagae, S. Lefebvre, R. Cook, T. DeRose, G. Drettakis, D.S. Ebert, J.P. Lewis, K. Perlin, M. Zwicker (2010) A Survey of Procedural Noise Functions. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2010.01827.x (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Procedural noise for texturing." https://texelatlas.vercel.app/t/procedural-noise-texturing/ (accessed 2026-12-01). --- id: "procgen-kit-llm-harness" title: "LLM-written procedural kits with verification gates" aliases: [procgen-kit] domain: "genai" stage: "generation" realtime: "offline" platforms: [python, cpu] year_introduced: 2026 inputs: [text-prompt] outputs: [mesh, graph] style: "both" dynamic: "static" cost: "offline" authority: "wrong-nebula, 2026" url: "https://texelatlas.vercel.app/t/procgen-kit-llm-harness/" sources_verified_at: "2026-11-29" --- # LLM-written procedural kits with verification gates (wrong-nebula, 2026) > A harness in which any LLM writes a short Python kit builder; a C++ core turns it into a parametric geometry graph and verifies it (manifold meshes, swept controls, touching parts, collision) before rendering. ## Reach for it when - llm-generated props are not watertight - need modular kit pieces that stay valid across parameters - generated walls and doors should pass collision checks - want verified parametric geometry from a language model ## How it works The model receives a builder API and examples, and writes a script that declares parts, parameters ("controls") and constraints. The C++ core compiles the script into a geometry graph, evaluates it at default and swept control values, and runs gates: closed-manifold output, part-contact checks, and collision tests with an external physics engine. Failure reports go back to the model to repair the script, and the loop ends when every gate passes and a render is produced. The point is to make the LLM responsible for design intent while a deterministic checker guards correctness, so output is a verified parametric asset set, not an unconstrained mesh. ## When to use it Choose it when you want LLM-generated modular kit pieces (walls, doors, props) that must be watertight and robust across their parameter range. Prefer [LL3M (Large Language 3D Modelers)](https://texelatlas.vercel.app/t/ll3m.md) for flexible Blender-centric authoring without hard gates, [ShapeLib](https://texelatlas.vercel.app/t/shapelib.md) for library learning from exemplars, and neural generators ([TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md), [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md)) for organic or textured one-off assets. ## Cost offline — LLM calls plus compile and verification rounds; local models are supported per the README. ## Failure modes - Gates guarantee validity, not aesthetics: a kit can pass and still look wrong - Limited to what the builder API can express - Model quality bounds how many repair rounds are needed - Needs a C++ build and extra dependencies for collision checking ## Dataflow - Inputs: text-prompt - Outputs: mesh, graph - Platforms: python, cpu ## Sources 1. [primary] wrong-nebula (2026) wrong-nebula/procgen-kit. https://github.com/wrong-nebula/procgen-kit License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "LLM-written procedural kits with verification gates." https://texelatlas.vercel.app/t/procgen-kit-llm-harness/ (accessed 2026-12-01). --- id: "progressive-meshes" title: "Progressive meshes" aliases: [PM, edge-collapse LOD streaming] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, desktop-gpu, unity, unreal] year_introduced: 1996 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "cheap" authority: "Hoppe, 1996" url: "https://texelatlas.vercel.app/t/progressive-meshes/" sources_verified_at: "2026-11-29" --- # Progressive meshes (Hoppe, 1996) > Stores a mesh as a coarse base plus an ordered list of vertex splits, so any level of detail can be reconstructed by replaying splits and the model can be streamed coarse-to-fine. ## Reach for it when - need smooth lod transitions without popping - stream a big mesh coarse to fine - switch between detail levels of a mesh continuously - view dependent refinement of a large static model ## How it works Simplify the mesh by repeatedly collapsing edges, picking each collapse by an energy that weighs geometric error plus attribute and discontinuity preservation. Every collapse is invertible: record it as a vertex split holding the new vertex position, the attributes and which wedge to open. The result is the coarsest base mesh plus the splits in reverse order. To get a mesh with N faces, apply splits until you reach N; apply or undo single splits at runtime to morph smoothly between levels with no popping, because vertices can be geomorphed from their parent position. The sequence is also a natural streaming format, since a partial prefix is already a valid, lower-quality model. Selective refinement variants split only where the view needs detail, giving view-dependent LOD for terrain and large static meshes. ## When to use it Choose it when you need continuous, streamable or view-dependent LOD on a single large static mesh, or want the history of an edge-collapse simplifier as a data structure. Prefer [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md) when you just want a few discrete LODs baked offline, [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) and [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) for modern GPU-driven pipelines with clustered hierarchies, and [meshoptimizer mesh optimization](https://texelatlas.vercel.app/t/meshoptimizer.md) for production-grade simplification and vertex cache work. ## Cost cheap — Runtime refinement is local pointer and index edits; the heavy part is the offline collapse ordering. Qualitative, no cited benchmark. ## Failure modes - Per-split index edits are awkward on GPUs and with static index buffers, which is why it fell out of favour for modern hardware - Collapsing across UV seams or hard normals without wedge handling tears textures or smooths creases - Topology changes are limited; genus and thin features are not preserved at coarse levels - Dynamic or skinned meshes need extra constraints because the collapse order is baked for the rest pose ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, desktop-gpu, unity, unreal ## Combines with - [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md): Quadric error metrics supply the collapse costs and optimal vertex positions that order the progressive sequence. ## Sources 1. [primary] Hugues Hoppe (1996) Progressive meshes. Proceedings of the 23rd annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/237170.237216 (verified via crossref on 2026-11-29) 2. [implementation] zeux (2016) zeux/meshoptimizer. https://github.com/zeux/meshoptimizer License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Progressive meshes." https://texelatlas.vercel.app/t/progressive-meshes/ (accessed 2026-12-01). --- id: "progressive-photon-mapping" title: "Progressive Photon Mapping" aliases: [PPM, SPPM] domain: "gi" stage: "lighting" realtime: "interactive" platforms: [cpu, cuda, desktop-gpu] year_introduced: 2008 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "static" cost: "offline" authority: "Hachisuka et al., 2008" url: "https://texelatlas.vercel.app/t/progressive-photon-mapping/" sources_verified_at: "2026-11-29" --- # Progressive Photon Mapping (Hachisuka et al., 2008) > Photon mapping reformulated so the gather radius shrinks over iterations. The result converges to the exact answer with bounded memory and handles extreme specular light transport. ## Reach for it when - caustics from glass or water stay noisy - lamp inside glass renders almost black - photon map eats memory and still looks blotchy - light through a pool surface needs long specular paths - want a render that keeps refining without bias ## How it works Classic photon mapping needs infinite memory to converge. Progressive photon mapping inverts the order. First, rays from the camera find **visible points** (diffuse hits seen after any specular chain) and store them with a small initial radius. Then, in repeated passes, a fresh batch of photons is traced and discarded; each photon that lands within a visible point's radius adds its flux to that point's running total. After every pass the radius of each visible point shrinks and its accumulated flux is rescaled by a fixed ratio governed by a parameter `alpha`, chosen so that variance falls while bias also falls. In the limit both vanish, so the estimate is consistent: unlimited photons effectively contribute, but only one batch exists in memory. **Stochastic PPM** extends this so that each pass also redraws the camera ray, which lets distributed effects like depth of field, motion blur and glossy surfaces work. Lookup uses a grid or hash over visible points rather than a tree of photons. ## When to use it Choose it for caustics and scenes with long specular chains (lamp inside glass, light through a pool surface) when you want an image that keeps refining without running out of memory. Prefer [vertex-connection-and-merging](vertex-connection-and-merging) when the scene also has plenty of non-specular paths where connections beat merging. Prefer [path-tracing](path-tracing) or [bidirectional-path-tracing](bidirectional-path-tracing) when you must stay unbiased. Prefer [photon-mapping](photon-mapping) when a one-shot photon map is acceptable and you only need a quick preview. ## Cost offline — One light-tracing pass per iteration plus a grid lookup per photon hit; memory is proportional to the number of visible points (pixels), not photons. Measured GPU Weight: 7.94× baseline (moderate) — 0.2611 ms median / 0.2697 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.52× baseline (moderate) — 0.1037 ms median (2.52× faster on L4). Ampere A100 scaling: 5.34× baseline (light) — 0.1539 ms median (1.7× faster on A100). ## Failure modes - Early iterations show large blur and low-frequency bias that fades slowly as the radius shrinks - The radius reduction rate trades noise against bias; a bad `alpha` leaves visible blur or persistent noise - Visible points are fixed per iteration, so view changes restart the render - Hash/grid lookup performance degrades when radii vary widely across the image ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda, desktop-gpu ## Presets ### Progressive Photon Mapping (PPM) — wide initial gather radius (left) vs shrinking caustic radius convergence (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PPM_PASSES": 0.85, "P_CAUSTIC_INT": 1.25, "P_RING_SPIN": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_PPM_PASSES = 0.85; // P PPM Pass Progress [0.05, 1.0, 0.02] const float P_CAUSTIC_INT = 1.25; // P Caustic Energy [0.3, 2.2, 0.05] const float P_RING_SPIN = 0.55; // P Light Spin [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Wide R / Shrunk R [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Analytical gold wedding-ring cardioid caustic intensity (classic Henrik Wann Jensen PPM showcase!) // Sharp cusp cardioid focused inside the ring on the tabletop, convolved by photon gather radius R_i float evalCardioidCaustic(vec2 xz, float gatherR) { // Parametric gold ring of radius 0.62 centered at origin, light coming from +X float energy = 0.0; // Accumulate 28 photon-hit clusters along the reflective inner ring cardioid cusp for (int i = 0; i < 28; i++) { float th = (float(i) / 27.0 - 0.5) * 2.55; // Exact cardioid caustic curve of a circular mirror under parallel light: // x = (R/4)*(3*cos(th) - cos(3*th)), z = (R/4)*(3*sin(th) - sin(3*th)) vec2 cPos = vec2( 0.165 * (3.0 * cos(th) - cos(3.0 * th)) - 0.14, 0.165 * (3.0 * sin(th) - sin(3.0 * th)) ); float d2 = dot(xz - cPos, xz - cPos); float r2 = max(gatherR * gatherR, 0.0005); // Normalized Epanechnikov/Gaussian photon density kernel K(d / R_i) / R_i^2 energy += exp(-d2 / r2) / (0.14 + gatherR * 12.0); } return energy * 0.24; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isConverged = screenX >= split; float prog = clamp(P_PPM_PASSES, 0.05, 1.0); float cGain = clamp(P_CAUSTIC_INT, 0.2, 2.4); float spin = iTime * max(P_RING_SPIN, 0.0) * 0.42; vec3 ro = vec3(0.0, 1.35, 1.85); vec3 rd = normalize(vec3(uv.x, uv.y - 0.46, -1.35)); vec3 bg = mix(vec3(0.022, 0.026, 0.042), vec3(0.062, 0.074, 0.112), smoothstep(-0.5, 0.5, uv.y)); vec3 col = bg; // Raymarch the polished gold ring (hollow cylinder wall at radius 0.62, height 0.24 resting on table y=0) float tRing = 1e5; float t = 0.2; for (int i = 0; i < 52; i++) { vec3 p = ro + rd * t; float r = length(p.xz); float dWall = abs(r - 0.62) - 0.042; float dY = abs(p.y - 0.14) - 0.14; float d = max(dWall, dY); if (d < 0.0025) { tRing = t; break; } t += max(d * 0.85, 0.006); if (t > 6.0) break; } float tTable = (rd.y < -0.01) ? (-ro.y / rd.y) : 1e5; if (tTable < 0.05 || tTable > 10.0) tTable = 1e5; vec3 lDir = normalize(vec3(cos(spin), 0.52, sin(spin))); if (tRing < tTable && tRing < 1e4) { vec3 p = ro + rd * tRing; vec3 n; if (abs(p.y - 0.28) < 0.01) n = vec3(0.0, 1.0, 0.0); else n = normalize(vec3(p.x, 0.0, p.z)) * ((length(p.xz) > 0.62) ? 1.0 : -1.0); vec3 refl = reflect(rd, n); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 64.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 gold = vec3(0.98, 0.78, 0.34); col = gold * (0.28 + 0.65 * max(dot(n, lDir), 0.0) + 0.35 * smoothstep(-0.3, 0.6, refl.y)) + vec3(1.0, 0.96, 0.86) * spec * 1.45 + gold * rim * 0.35; } else if (tTable < 1e4) { vec3 p = ro + rd * tTable; vec2 rotXZ = rot2(-spin) * p.xz; // Fine grained warm walnut studio tabletop float grain = 0.5 + 0.5 * sin(p.x * 26.0 + sin(p.z * 8.0) * 1.8); vec3 wood = mix(vec3(0.16, 0.12, 0.09), vec3(0.28, 0.21, 0.16), grain); // Soft shadow cast by gold ring onto table float rDist = abs(length(p.xz - lDir.xz * 0.22) - 0.62); float ringSh = smoothstep(0.04, 0.14, rDist); // PPM progressive radius shrinking: R_{i+1} = R_i * sqrt((N + alpha*M)/(N + M)) // Left: early pass 1 with wide biased gather radius R_0 (blurry caustic!) // Right: converged pass N with tight shrinking radius R_N (razor-sharp cusp caustic!) float gatherR = isConverged ? mix(0.12, 0.026, prog) : 0.16; float caustic = evalCardioidCaustic(rotXZ, gatherR) * cGain; // Subtle spectral gold-amber tint along caustic intensity vec3 causticCol = mix(vec3(0.98, 0.66, 0.20), vec3(1.0, 0.96, 0.80), clamp(caustic * 0.55, 0.0, 1.0)); col = wood * (0.25 + 0.75 * ringSh) + causticCol * caustic * 1.35; // Show sample gather-radius diagnostic circle on tabletop for visual clarity! vec2 probe = p.xz - vec2(isConverged ? 0.22 : -0.22, 0.16); float probeRing = exp(-abs(length(probe) - gatherR) * 110.0); col += (isConverged ? vec3(0.22, 0.96, 0.86) : vec3(0.98, 0.36, 0.28)) * probeRing * 0.75; col = mix(col, bg, 1.0 - exp(-tTable * 0.12)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Photon Mapping](https://texelatlas.vercel.app/t/photon-mapping.md) ## Combines with - [Vertex Connection and Merging](https://texelatlas.vercel.app/t/vertex-connection-and-merging.md): VCM reuses this radius-reduction schedule for its merging half. ## Sources 1. [primary] Toshiya Hachisuka, Shinji Ogaki, Henrik Wann Jensen (2008) Progressive photon mapping. ACM Transactions on Graphics. https://doi.org/10.1145/1409060.1409083 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Stochastic Progressive Photon Mapping (Physically Based Rendering, 3rd edition). pbr-book.org. https://pbr-book.org/3ed-2018/Light_Transport_III_Bidirectional_Methods/Stochastic_Progressive_Photon_Mapping (verified via http on 2026-11-29) 3. [implementation] mmp (2015) mmp/pbrt-v3. https://github.com/mmp/pbrt-v3 License: BSD-2-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "Progressive Photon Mapping." https://texelatlas.vercel.app/t/progressive-photon-mapping/ (accessed 2026-12-01). --- id: "qem-mesh-simplification" title: "Quadric Error Metric Simplification" aliases: [QEM, quadric simplification, Mesh Simplification, Mesh Decimation, Polygon Reduction] domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, desktop-gpu, blender, unity, unreal] year_introduced: 1997 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "offline" authority: "Garland & Heckbert, 1997" url: "https://texelatlas.vercel.app/t/qem-mesh-simplification/" sources_verified_at: "2026-11-29" --- # Quadric Error Metric Simplification (Garland & Heckbert, 1997) > Collapses mesh edges greedily, always choosing the cheapest collapse measured by a sum of squared distances to the planes of the original surrounding faces. A fast, general-purpose way to cut triangle counts while keeping shape. ## Reach for it when - mesh has too many polygons for realtime - decimate model while keeping its shape - generate lod chain from a high poly asset - reduce triangles but preserve silhouette and features ## How it works Attach to each vertex a 4x4 symmetric quadric: the sum of outer products of the plane equations of the faces around it. The error of placing a vertex at v is vᵀQv. For each candidate edge, merge the two quadrics, solve for the optimal position (or fall back to an endpoint or midpoint if the system is singular), and push the edge into a priority queue by cost. Repeatedly pop the cheapest edge, collapse it, update neighbouring costs and continue until the target triangle count is reached. Practical versions add rules to avoid triangle flips, preserve boundaries via extra penalty planes, weight by area and carry UVs or attributes in extended quadrics. ## When to use it Choose it for automatic LODs, cleaning dense scans or marching-cubes output and shrinking assets for the web. Prefer [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md) when you need uniform triangle sizes rather than minimal count, [Instant Field-Aligned Meshes](https://texelatlas.vercel.app/t/instant-meshes.md) or [QuadriFlow](https://texelatlas.vercel.app/t/quadriflow.md) for clean quad topology, and hand-authored LODs where silhouettes or animation deformation must be controlled. ## Cost offline — Near O(n log n) with a priority queue; millions of triangles take seconds on CPU. Not a per-frame operation. Measured GPU Weight: 25.84× baseline (heavy) — 0.8113 ms median / 0.8766 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.07× baseline (heavy) — 0.3329 ms median (2.44× faster on L4). Ampere A100 scaling: 15.44× baseline (moderate) — 0.4447 ms median (1.82× faster on A100). ## Failure modes - UV seams, skin weights and normals tear or distort unless attributes are included in the metric - Flipped or overlapping triangles when a collapse moves a vertex across its ring - Boundary and thin-shell collapse: open edges shrink or holes grow - Topology can change unexpectedly (non-manifold results) without explicit checks - Uneven triangle shapes: it optimises error, not triangle quality ## Engine support - babylonjs: builtin — `mesh.simplify([{distance, quality}]) (QuadraticErrorSimplification)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/meshSimplification.ts, checked 2026-12-01) - blender: builtin — `Add Modifier > Generate > Decimate > Collapse` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/generate/decimate.html, checked 2026-12-01) — Collapse mode; the manual does not name quadric error metrics. - godot: builtin — `ImporterMesh.generate_lods(); scene import option Meshes > Generate LODs` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ImporterMesh.xml, checked 2026-12-01) — Simplification via bundled meshoptimizer. - unity: plugin — `openupm add com.whinarn.unitymeshsimplifier` (evidence: https://github.com/Whinarn/UnityMeshSimplifier, checked 2026-12-01) — UnityMeshSimplifier (Fast Quadric Mesh Simplification in C#). - unreal: builtin — `Static Mesh Editor > LOD Settings > Reduction Settings (and GeometryScript_MeshSimplification)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/creating-and-using-lods-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, webgl2, webgpu, desktop-gpu, blender, unity, unreal ## Presets ### Quadric Error Metric Simplification — smooth high-poly reference (left) vs QEF edge-collapsed facets & error map (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DECIMATION": 0.62, "P_ERROR_HEAT": 0.55, "P_WIRE_ALPHA": 0.85, "P_SPLIT": 0.44 } ``` ```glsl const float P_DECIMATION = 0.62; // P Decimation Ratio [0.1, 1.0, 0.02] const float P_ERROR_HEAT = 0.55; // P Quadric Error Map [0.0, 1.0, 0.02] const float P_WIRE_ALPHA = 0.85; // P Mesh Wireframe [0.0, 1.5, 0.05] const float P_SPLIT = 0.44; // P Hi-Poly / QEM Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Sculpted multi-lobed organic polyhedron with both smooth basins and sharp ridges (ideal QEM test!) float mapSculpt(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.35) * q.xz; q.yz = rot2(0.28) * q.yz; float r = length(q); vec3 d = q / max(r, 1e-4); float lobes = 0.14 * sin(d.x * 5.0) * cos(d.y * 5.0) + 0.09 * cos(d.z * 6.0 + d.x * 3.0); float ridge = 0.045 * abs(sin(atan(d.z, d.x) * 4.0)); return (r - (0.78 + lobes + ridge)) * 0.78; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSculpt(p + e.xyy, spin) - mapSculpt(p - e.xyy, spin), mapSculpt(p + e.yxy, spin) - mapSculpt(p - e.yxy, spin), mapSculpt(p + e.yyx, spin) - mapSculpt(p - e.yyx, spin) )); } // Compute triangle-grid facet center, flat quantized normal, edge distance, and local quadric error void evalQemFacet(vec3 objP, vec3 smoothN, float freq, out vec3 flatN, out float edgeDist, out float qemErr) { // Spherical octahedral-like parameterization to form uniform triangle facets on the 3D surface vec3 d = normalize(objP + vec3(1e-5)); vec2 sp = vec2(atan(d.z, d.x) / 3.14159265, asin(clamp(d.y, -0.999, 0.999)) / 1.5707963); vec2 g = sp * vec2(freq * 1.8, freq); vec2 cell = floor(g); vec2 f = fract(g); float upper = step(f.x, f.y); vec3 bary = (upper > 0.5) ? vec3(1.0 - f.y, f.x, f.y - f.x) : vec3(1.0 - f.x, f.y, f.x - f.y); edgeDist = min(bary.x, min(bary.y, bary.z)); // Centroid of the collapsed QEM triangle on the unit sphere vec2 cUV = (cell + ((upper > 0.5) ? vec2(0.33, 0.67) : vec2(0.67, 0.33))) / vec2(freq * 1.8, freq); float lon = cUV.x * 3.14159265; float lat = clamp(cUV.y * 1.5707963, -1.55, 1.55); vec3 cDir = vec3(cos(lat) * cos(lon), sin(lat), cos(lat) * sin(lon)); // Approximate face normal & quadric error v^T Q v = (n_smooth . (v - v_plane))^2 flatN = normalize(mix(cDir, smoothN, 0.25)); qemErr = clamp((1.0 - dot(smoothN, flatN)) * 12.0, 0.0, 1.0); } vec3 errPalette(float x) { x = clamp(x, 0.0, 1.0); vec3 c0 = vec3(0.10, 0.32, 0.64); vec3 c1 = vec3(0.16, 0.84, 0.66); vec3 c2 = vec3(0.98, 0.72, 0.18); vec3 c3 = vec3(0.98, 0.22, 0.34); if (x < 0.35) return mix(c0, c1, x / 0.35); if (x < 0.72) return mix(c1, c2, (x - 0.35) / 0.37); return mix(c2, c3, (x - 0.72) / 0.28); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float decim = clamp(P_DECIMATION, 0.05, 1.0); float heatMix = clamp(P_ERROR_HEAT, 0.0, 1.0); float wireVis = clamp(P_WIRE_ALPHA, 0.0, 1.5); float spin = iTime; vec3 ro = vec3(0.0, 0.06, 2.45); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.032, 0.042, 0.068), vec3(0.092, 0.116, 0.168), smoothstep(-0.55, 0.55, uv.y)); vec2 bgG = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.018, 0.028, 0.045) * smoothstep(0.03, 0.0, min(bgG.x, bgG.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSculpt(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 nSmooth = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.35) * objP.xz; objP.yz = rot2(0.28) * objP.yz; vec3 objN = nSmooth; objN.xz = rot2(spin * 0.35) * objN.xz; objN.yz = rot2(0.28) * objN.yz; // Left: dense reference mesh (freq = 18); Right: QEM simplified mesh (freq drops with P_DECIMATION) bool isQem = screenX >= split; float triFreq = isQem ? mix(13.0, 3.8, decim) : 18.0; vec3 flatObjN; float edgeD; float qemErr; evalQemFacet(objP, objN, triFreq, flatObjN, edgeD, qemErr); // Transform faceted normal back to world space for authentic flat-shaded decimated lighting vec3 nFlat = flatObjN; nFlat.yz = rot2(-0.28) * nFlat.yz; nFlat.xz = rot2(-spin * 0.35) * nFlat.xz; vec3 nShade = isQem ? normalize(mix(nSmooth, nFlat, 0.82)) : nSmooth; vec3 l1 = normalize(vec3(0.62, 0.85, 0.55)); vec3 l2 = normalize(vec3(-0.72, -0.20, 0.52)); float diff1 = max(dot(nShade, l1), 0.0); float diff2 = max(dot(nShade, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(nShade, hVec), 0.0), 36.0) * 0.45; float rim = pow(1.0 - max(dot(nSmooth, -rd), 0.0), 3.0) * 0.28; vec3 clayAlb = vec3(0.76, 0.74, 0.72); vec3 qemAlb = mix(vec3(0.72, 0.75, 0.80), errPalette(qemErr * 1.45), heatMix); vec3 alb = isQem ? qemAlb : clayAlb; col = alb * (0.26 + 0.84 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.72, 1.0) * rim; float wire = smoothstep(0.065, 0.012, edgeD); vec3 wireCol = isQem ? vec3(0.06, 0.08, 0.12) : vec3(0.22, 0.30, 0.42); col = mix(col, wireCol, wire * (isQem ? 0.72 : 0.28) * min(wireVis, 1.2)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): Collapse the dense uniform mesh into an adaptive one. - [Geometry Images](https://texelatlas.vercel.app/t/geometry-images.md): Remesh/simplify before parametrization to keep atlas sizes sane. ## Sources 1. [primary] Michael Garland, Paul S. Heckbert (1997) Surface simplification using quadric error metrics. Proceedings of the 24th annual conference on Computer graphics and interactive techniques - SIGGRAPH '97. https://doi.org/10.1145/258734.258849 (verified via crossref on 2026-11-29) 2. [implementation] zeux (2016) zeux/meshoptimizer. https://github.com/zeux/meshoptimizer License: MIT. (verified via github on 2026-11-29) 3. [implementation] sp4cerat (2015) sp4cerat/Fast-Quadric-Mesh-Simplification. https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification License: MIT. (verified via github on 2026-11-29) 4. [tutorial] Michael Garland QSlim. cs.cmu.edu. https://www.cs.cmu.edu/~garland/quadrics/qslim.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Quadric Error Metric Simplification." https://texelatlas.vercel.app/t/qem-mesh-simplification/ (accessed 2026-12-01). --- id: "quadriflow" title: "QuadriFlow" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu] year_introduced: 2018 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "offline" authority: "Huang et al., 2018" url: "https://texelatlas.vercel.app/t/quadriflow/" sources_verified_at: "2026-11-29" --- # QuadriFlow (Huang et al., 2018) > Quad remeshing that formulates the integer-grid lattice as a minimum-cost flow, which guarantees a manifold, watertight quad mesh with a controllable number of faces and few irregular vertices. ## Reach for it when - need clean quad mesh with a fixed face count - sculpt or scan needs retopology to quads - want manifold watertight quad remesh with few irregular vertices - subdivision cage from a dense mesh ## How it works As in field-aligned meshers, it first smooths a 4-RoSy orientation field and a position field on the input. The key step is turning the extraction of the quad lattice into a network-flow problem: the integer offsets that must be resolved to align the position field across neighbouring faces are encoded as flows on a graph. Solving a minimum-cost flow makes singularities lie where the field wants them and guarantees the integer constraints are consistent. A subsequent optimisation extracts a quad mesh whose vertices follow the field and whose faces are all quads, with a user-specified target count. ## When to use it Choose it when you need a pure-quad, manifold result with a fixed face budget, for example subdivision cages or sculpt retopology of a clean scan. Prefer [Instant Field-Aligned Meshes](https://texelatlas.vercel.app/t/instant-meshes.md) for interactive guidance and strokes or when mixed quad/tri output is acceptable, and [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md) when quads do not matter. ## Cost offline — Seconds to minutes for 100k-1M faces on CPU; the flow solve is the bottleneck. ## Failure modes - Input must be (nearly) manifold; non-manifold or self-intersecting inputs fail or need preprocessing - Thin sheets and fine details get lost at low face counts - Cannot take artist guidance as readily as stroke-driven tools - Memory use grows quickly with input size ## Engine support - blender: builtin — `Object > Quad Remesh (Object Mode, 3D Viewport)` (evidence: https://docs.blender.org/manual/en/5.2/modeling/meshes/retopology.html, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu ## Combines with - [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md): Pure-quad output is a natural subdivision cage. ## Sources 1. [primary] Jingwei Huang, Yichao Zhou, Matthias Niessner, Jonathan Richard Shewchuk, Leonidas J. Guibas (2018) QuadriFlow: A Scalable and Robust Method for Quadrangulation. Computer Graphics Forum. https://doi.org/10.1111/cgf.13498 (verified via crossref on 2026-11-29) 2. [implementation] hjwdzh (2017) hjwdzh/QuadriFlow. https://github.com/hjwdzh/QuadriFlow License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "QuadriFlow." https://texelatlas.vercel.app/t/quadriflow/ (accessed 2026-12-01). --- id: "quaternion-slerp-interpolation" title: "Quaternion slerp rotation interpolation" aliases: [slerp, spherical linear interpolation, nlerp, squad] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender, python] year_introduced: 1985 inputs: [skeleton] outputs: [animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Shoemake, 1985" url: "https://texelatlas.vercel.app/t/quaternion-slerp-interpolation/" sources_verified_at: "2026-11-29" --- # Quaternion slerp rotation interpolation (Shoemake, 1985) > Interpolate between two unit quaternions along the great arc, giving constant angular velocity and no gimbal lock; nlerp and squad are the common cheaper or smoother cousins. ## Reach for it when - camera or bone spins the long way round when blending - rotation interpolation has uneven speed or gimbal lock - need constant angular velocity between two orientations - blending nearly equal rotations produces nan values ## How it works Unit quaternions live on the 3-sphere, and each rotation appears twice (q and -q). Spherical linear interpolation walks along the great circle joining two of them with parameter t: the result is sin((1-t)w)/sin(w) times the first plus sin(tw)/sin(w) times the second, where w is the angle between them. The path has constant angular speed and a fixed axis, so a camera or joint turns steadily. Two practical rules apply. First flip one quaternion's sign if their dot product is negative so the path takes the short arc. Second, when the angle is tiny, sin(w) approaches zero and the formula must fall back to normalised linear interpolation. Nlerp (lerp then normalise) has the same path but non-constant speed and is cheaper and common in skinning blends. Squad chains slerps to get C1 continuity across a keyframe sequence, and rotation-vector or log-space interpolation covers blending several poses. ## When to use it Choose slerp for two-keyframe rotation blends, camera orbits, aim smoothing and orientation render-interpolation. Prefer nlerp when the two quaternions are close and speed uniformity does not matter, as in per-vertex skinning blends. Prefer squad or spline-based interpolation for smooth multi-keyframe paths. For blending skinning transforms use [Dual quaternion skinning](https://texelatlas.vercel.app/t/dual-quaternion-skinning.md) or [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md), and for orienting along a curve without twist use [Rotation-Minimizing Frames](https://texelatlas.vercel.app/t/rotation-minimizing-frames.md). Pair with [Fixed timestep game loop and integration](https://texelatlas.vercel.app/t/fixed-timestep-integration.md) to interpolate physics orientation for display. ## Cost cheap — A few multiplies, one acos and two sin per interpolation; nlerp avoids the transcendentals. Measured GPU Weight: 9.07× baseline (moderate) — 0.2813 ms median / 0.2876 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.86× baseline (moderate) — 0.109 ms median (2.58× faster on L4). Ampere A100 scaling: 6.1× baseline (moderate) — 0.1756 ms median (1.6× faster on A100). ## Failure modes - Long-way-round spins when the sign flip for a negative dot product is skipped - Division by near-zero sin(w) producing NaNs for almost identical orientations - Not renormalising after repeated interpolation lets quaternions drift off the unit sphere - Slerp between consecutive keyframes has a velocity discontinuity at each key unless squad or a spline is used - Per-bone interpolation ignores the hierarchy, so end effectors can slip even though each joint turns smoothly ## Engine support - babylonjs: builtin — `Quaternion.Slerp(a, b, t)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Maths/math.vector.pure.ts, checked 2026-12-01) - blender: builtin — `Object/Pose Quaternion rotation interpolation and BLI_math_quaternion.hh shortest-arc spherical linear interpolation` (evidence: https://github.com/blender/blender/blob/main/source/blender/blenlib/BLI_math_quaternion.hh, checked 2026-12-01) - godot: builtin — `Quaternion.slerp(to, weight); Basis.slerp` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Quaternion.xml, checked 2026-12-01) - threejs: builtin — `quaternion.slerp(qb, t)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/math/Quaternion.js, checked 2026-12-01) - unity: builtin — `Quaternion.Slerp(a, b, t)` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.Slerp.html, checked 2026-12-01) - unreal: builtin — `FQuat::Slerp / unreal.Quat.slerp and Sequencer / Constraint Quaternion Slerp blending` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/Quat, checked 2026-12-01) ## Dataflow - Inputs: skeleton - Outputs: animation - Platforms: cpu, webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender, python ## Presets ### Quaternion SLERP — constant-speed geodesic arc on S^3 (cyan) vs uneven NLERP/Euler path (amber) (glsl-fragment; rendered 2026-11-30) ```json { "P_ROT_ANGLE": 2.35, "P_SPEED": 0.85, "P_TICKS": 12, "P_TRAIL_GLOW": 1 } ``` ```glsl const float P_ROT_ANGLE = 2.35; // P Sweep Angle Rad [0.8, 3.05, 0.05] const float P_SPEED = 0.85; // P Cycle Speed [0.0, 2.5, 0.05] const float P_TICKS = 12.0; // P Arc Sample Ticks [6.0, 20.0, 1.0] const float P_TRAIL_GLOW = 1.0; // P Arc Brightness [0.3, 1.8, 0.05] // Unit quaternion helpers: q = (x, y, z, w) vec4 qFromAxisAngle(vec3 axis, float ang) { float h = ang * 0.5; return vec4(normalize(axis) * sin(h), cos(h)); } vec4 qSlerp(vec4 q0, vec4 q1, float t) { float d = dot(q0, q1); if (d < 0.0) { q1 = -q1; d = -d; } d = clamp(d, -1.0, 1.0); if (d > 0.9995) return normalize(mix(q0, q1, t)); float theta = acos(d); float s = max(sin(theta), 1e-5); return (sin((1.0 - t) * theta) * q0 + sin(t * theta) * q1) / s; } vec4 qNlerp(vec4 q0, vec4 q1, float t) { if (dot(q0, q1) < 0.0) q1 = -q1; return normalize(mix(q0, q1, t)); } vec3 qRotate(vec4 q, vec3 v) { vec3 t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); } // Distance from 3D point p to segment a-b float sdSeg3(vec3 p, vec3 a, vec3 b) { vec3 pa = p - a; vec3 ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float ang = clamp(P_ROT_ANGLE, 0.6, 3.08); float tCyc = 0.5 - 0.5 * cos(iTime * max(P_SPEED, 0.0) * 1.4); float nTicks = clamp(floor(P_TICKS + 0.5), 6.0, 20.0); float glow = clamp(P_TRAIL_GLOW, 0.2, 2.0); // Start and end unit quaternions spanning a large rotation angle vec4 q0 = qFromAxisAngle(vec3(-0.35, 0.85, 0.25), -ang * 0.5); vec4 q1 = qFromAxisAngle(vec3(0.45, 0.72, -0.42), ang * 0.5); vec4 qCurSlerp = qSlerp(q0, q1, tCyc); vec4 qCurNlerp = qNlerp(q0, q1, tCyc); vec3 ro = vec3(0.0, 0.28, 2.85); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.04), -1.65)); vec3 col = mix(vec3(0.022, 0.030, 0.052), vec3(0.058, 0.075, 0.122), smoothstep(-0.55, 0.55, uv.y)); // Analytical unit reference sphere (radius R = 0.88) float R = 0.88; float b = dot(ro, rd); float c = dot(ro, ro) - R * R; float disc = b * b - c; float tSphere = 1e5; if (disc > 0.0) { tSphere = -b - sqrt(disc); vec3 p = ro + rd * tSphere; vec3 n = normalize(p); // Lat/lon spherical coordinate grid on S^2 float lat = abs(fract(asin(clamp(n.y, -1.0, 1.0)) * 6.0 / 3.1415926) - 0.5); float lon = abs(fract(atan(n.x, n.z) * 12.0 / 6.2831853) - 0.5); float wire = smoothstep(0.035, 0.008, min(lat, lon)); vec3 lDir = normalize(vec3(0.5, 0.78, 0.62)); float diff = max(dot(n, lDir), 0.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 sphCol = vec3(0.06, 0.10, 0.17) * (0.45 + 0.75 * diff) + vec3(0.14, 0.24, 0.40) * wire * 0.55; sphCol += vec3(0.24, 0.54, 0.88) * fres * 0.42; // Project SLERP (constant angular velocity) vs distorted Euler/NLERP curves onto the sphere surface vec3 baseAxis = normalize(vec3(0.0, 0.12, 1.0)); float dSlerpMin = 1e5; float dNlerpMin = 1e5; float tickSlerp = 0.0; float tickNlerp = 0.0; vec3 prevS = qRotate(q0, baseAxis) * R; vec3 prevN = prevS; for (int i = 1; i <= 20; i++) { if (float(i) > nTicks) break; float u = float(i) / nTicks; vec3 curS = qRotate(qSlerp(q0, q1, u), baseAxis) * R; // Emphasize non-uniform NLERP speed + Euler cross-axis detour for clear comparison float uWarp = u + 0.14 * sin(u * 6.2831853); vec3 curN = qRotate(qNlerp(q0, q1, clamp(uWarp, 0.0, 1.0)), baseAxis) * R; curN = normalize(curN + vec3(0.0, 0.24 * sin(u * 3.1415926), 0.0)) * R; dSlerpMin = min(dSlerpMin, sdSeg3(p, prevS, curS)); dNlerpMin = min(dNlerpMin, sdSeg3(p, prevN, curN)); tickSlerp = max(tickSlerp, smoothstep(0.036, 0.015, length(p - curS))); tickNlerp = max(tickNlerp, smoothstep(0.036, 0.015, length(p - curN))); prevS = curS; prevN = curN; } // Cyan SLERP geodesic arc with perfectly uniform tick marks sphCol += vec3(0.12, 0.92, 1.0) * smoothstep(0.022, 0.006, dSlerpMin) * 0.88 * glow; sphCol = mix(sphCol, vec3(0.75, 0.98, 1.0), tickSlerp * 0.92); // Amber Euler/NLERP detour arc with visibly bunched tick marks sphCol += vec3(1.0, 0.62, 0.16) * smoothstep(0.022, 0.006, dNlerpMin) * 0.78 * glow; sphCol = mix(sphCol, vec3(1.0, 0.84, 0.42), tickNlerp * 0.90); // Moving live triad heads on the sphere vec3 headS = qRotate(qCurSlerp, baseAxis) * R; float uW = clamp(tCyc + 0.14 * sin(tCyc * 6.2831853), 0.0, 1.0); vec3 headN = normalize(qRotate(qNlerp(q0, q1, uW), baseAxis) + vec3(0.0, 0.24 * sin(tCyc * 3.1415926), 0.0)) * R; sphCol += vec3(0.35, 1.0, 1.0) * smoothstep(0.085, 0.022, length(p - headS)) * 1.1; sphCol += vec3(1.0, 0.72, 0.24) * smoothstep(0.085, 0.022, length(p - headN)) * 1.1; col = sphCol; } // Bottom angular-velocity strip plot comparing SLERP (flat constant omega) vs NLERP (spiky omega) vec2 plotUV = vec2((uv.x + 0.68) / 1.36, (uv.y + 0.45) / 0.16); if (plotUV.x > 0.0 && plotUV.x < 1.0 && plotUV.y > 0.0 && plotUV.y < 1.0) { col = mix(col, vec3(0.03, 0.045, 0.075), 0.85); float omegaS = 0.55; float omegaN = 0.55 + 0.36 * cos(plotUV.x * 6.2831853); col = mix(col, vec3(0.16, 0.92, 1.0), smoothstep(0.06, 0.015, abs(plotUV.y - omegaS))); col = mix(col, vec3(1.0, 0.62, 0.16), smoothstep(0.06, 0.015, abs(plotUV.y - omegaN))); col = mix(col, vec3(0.95, 0.97, 1.0), smoothstep(0.012, 0.003, abs(plotUV.x - tCyc)) * 0.75); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Motion matching](https://texelatlas.vercel.app/t/motion-matching.md): Blending between matched animation clips interpolates each bone rotation with slerp or nlerp to avoid pops. - [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md): IK solves produce target orientations that are slerped from the animated pose for smooth blending in and out. ## Sources 1. [primary] Ken Shoemake (1985) Animating rotation with quaternion curves. Proceedings of the 12th annual conference on Computer graphics and interactive techniques - SIGGRAPH '85. https://doi.org/10.1145/325334.325242 (verified via crossref on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Quaternion slerp rotation interpolation." https://texelatlas.vercel.app/t/quaternion-slerp-interpolation/ (accessed 2026-12-01). --- id: "radiance-cascades" title: "Radiance Cascades" aliases: [RC, holographic radiance cascades] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu] year_introduced: 2023 inputs: [sdf, gbuffer, radiance] outputs: [radiance] style: "both" dynamic: "dynamic" cost: "medium" authority: "Freeman et al., 2025" url: "https://texelatlas.vercel.app/t/radiance-cascades/" sources_verified_at: "2026-11-29" --- # Radiance Cascades (Freeman et al., 2025) > A hierarchical set of probe grids where coarse probes have many angular samples but long ray intervals, and fine probes have few angles but short intervals. Merging them gives noise-free, penumbra-correct GI at fixed cost. ## Reach for it when - need dynamic global illumination without noise - 2d game lighting with soft penumbrae - fully dynamic indirect light at fixed cost - screen-space gi flickers and grains - sharp accurate shadows from large lights without baking ## How it works Radiance cascades exploit the way visual detail trades between space and angle. A small light source needs fine angular resolution but only coarse spatial resolution, because it is far away; a nearby occluder needs fine spatial resolution but little angular detail. Cascade 0 holds a dense grid of probes, each with few directions, tracing only a short **ray interval** (say, the first few pixels). Cascade 1 has a grid four times sparser, each probe with four times as many directions, tracing the *next* interval beyond cascade 0's range, and so on. The cascades are evaluated independently, then **merged from coarsest to finest**. A cascade `n` probe's interval radiance is combined with the already-merged radiance from cascade `n+1`: if the ray was blocked, its own result is used; if it reached the interval's end without hitting, the coarser cascade's interpolated radiance is continued. The finest cascade then holds the full radiance field at each pixel. The dimension of the work is constant per cascade, so cost is linear in pixels with a fixed angular budget, and penumbrae come out correct and noise-free instead of being sampled stochastically. 3D versions add a fourth dimension of directions and are active research. ## When to use it Choose it for 2D games and screen-space or SDF-based 3D GI where you want sharp, noise-free, fully dynamic indirect light with predictable cost. Prefer [ddgi](ddgi) when you have a hardware ray tracer and a 3D scene with probes on a world grid. Prefer [screen-space-gi](screen-space-gi) when you only need a cheap gather of nearby bounce light in a deferred pipeline. Prefer [lumen-gi](lumen-gi) when you need a production 3D solution. Prefer [light-propagation-volumes](light-propagation-volumes) when you can accept very coarse 3D propagation. ## Cost medium — Fixed per-pixel work for a given number of cascades; 2D implementations run comfortably in a few milliseconds at 1080p on desktop GPUs, 3D variants are much heavier. Measured GPU Weight: 234.65× baseline (extreme) — 7.72 ms median / 7.8575 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 228.5× baseline (extreme) — 3.6332 ms median (2.12× faster on L4). Ampere A100 scaling: 137.6× baseline (extreme) — 3.9629 ms median (1.95× faster on A100). ## Failure modes - Ringing or banding where probes in neighbouring cascades disagree, especially with visible seams between interval boundaries - Needs a scene representation that can be ray-marched quickly (SDF or screen depth), which limits where it works - Light leaking at thin occluders where an interval ends inside a wall - 3D extension is memory- and bandwidth-hungry because directions grow with the cascade level ## Dataflow - Inputs: sdf, gbuffer, radiance - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu ## Presets ### 2D Radiance Cascades — hierarchical interval probe GI with penumbra-correct colored shadows (glsl-fragment; rendered 2026-11-30) ```json { "CASCADES": 4, "RAYS": 24, "BASE_INTERVAL": 0.08, "FALLOFF": 1.6 } ``` ```glsl const int CASCADES = 4; // P const int RAYS = 24; // P const float BASE_INTERVAL = 0.08; // P const float FALLOFF = 1.6; // P float sdCircle(vec2 p, vec2 c, float r) { return length(p - c) - r; } 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); } float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0); return length(pa - ba * h); } vec4 sampleScene(vec2 p, vec2 orbPos) { float dObs = sdCircle(p, vec2(-0.08, 0.02), 0.11); dObs = min(dObs, sdBox(p - vec2(0.18, 0.18), vec2(0.025, 0.16))); dObs = min(dObs, sdBox(p - vec2(0.18, -0.22), vec2(0.025, 0.14))); vec2 q = p - vec2(-0.22, -0.26); mat2 rot = mat2(0.866, -0.5, 0.5, 0.866); dObs = min(dObs, sdBox(rot * q, vec2(0.14, 0.022))); float dE1 = sdCircle(p, orbPos, 0.055); float dE2 = sdSegment(p, vec2(-0.44, -0.18), vec2(-0.44, 0.24)) - 0.022; float dE3 = sdCircle(p, vec2(0.39, -0.02), 0.045); float d = min(dObs, min(dE1, min(dE2, dE3))); vec3 em = vec3(0.0); if (dE1 < 0.002) em = vec3(4.2, 2.0, 0.65); else if (dE2 < 0.002) em = vec3(0.45, 2.6, 3.8); else if (dE3 < 0.002) em = vec3(3.4, 0.55, 2.1); return vec4(em, d); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 orbPos = vec2(0.24 * cos(iTime * 0.65) - 0.06, 0.28 * sin(iTime * 0.52) + 0.05); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { orbPos = (iMouse.xy - 0.5 * iResolution.xy) / iResolution.y; } vec4 self = sampleScene(uv, orbPos); if (self.w < 0.0) { vec3 col = length(self.rgb) > 0.01 ? self.rgb : vec3(0.045, 0.05, 0.065); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); return; } int nCasc = clamp(CASCADES, 1, 6); int nRays = clamp(RAYS, 6, 48); float baseInt = max(BASE_INTERVAL, 0.015); float falloff = max(FALLOFF, 0.1); float jitter = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453); vec3 radiance = vec3(0.0); for (int r = 0; r < 48; r++) { if (r >= nRays) break; float ang = (float(r) + jitter * 0.35) * (6.2831853 / float(nRays)); vec2 dir = vec2(cos(ang), sin(ang)); float trans = 1.0; float tStart = 0.004; for (int c = 0; c < 6; c++) { if (c >= nCasc || trans < 0.01) break; float segLen = baseInt * pow(2.0, float(c)); float tEnd = tStart + segLen; float t = tStart; for (int s = 0; s < 6; s++) { vec4 hit = sampleScene(uv + dir * t, orbPos); if (hit.w < 0.0025) { float att = 1.0 / (1.0 + falloff * t * t * 6.0); radiance += trans * hit.rgb * att; trans = 0.0; break; } t += max(hit.w, segLen * 0.14); if (t > tEnd) break; } tStart = tEnd; } radiance += trans * vec3(0.015, 0.022, 0.04); } radiance /= float(nRays); vec2 grid = abs(fract(uv * 16.0 - 0.5) - 0.5) / fwidth(uv * 16.0); float probeDot = smoothstep(0.09, 0.03, length(fract(uv * 12.0) - 0.5)); vec3 floorAlbedo = vec3(0.76, 0.78, 0.82) * (1.0 - 0.06 * smoothstep(1.2, 0.0, min(grid.x, grid.y))); vec3 col = radiance * floorAlbedo + probeDot * radiance * 0.12; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ### 2D Radiance Cascades probe marcher (WGSL) (webgpu-wgsl; WebGPU WGSL runtime) ```json { "RAYS": 16, "STEP_SCALE": 0.018, "LIGHT_GAIN": 1.4 } ``` ```wgsl // WebGPU WGSL fragment specimen: 2D multi-interval Radiance Cascades approximation const RAYS: i32 = 16; // P const STEP_SCALE: f32 = 0.0180; // P const LIGHT_GAIN: f32 = 1.4000; // P fn rc_scene(p: vec2f, t: f32) -> vec4f { let e1 = length(p - vec2f(-0.34, 0.16 * sin(t * 0.7))) - 0.11; if (e1 < 0.0) { return vec4f(2.6, 1.35, 0.55, 1.0); } let e2 = length(p - vec2f(0.36, -0.14 * cos(t * 0.6))) - 0.095; if (e2 < 0.0) { return vec4f(0.55, 1.45, 2.7, 1.0); } let b = abs(p - vec2f(0.0, 0.02)) - vec2f(0.055, 0.24); if (max(b.x, b.y) < 0.0) { return vec4f(0.04, 0.045, 0.055, 1.0); } return vec4f(0.0, 0.0, 0.0, 0.0); } @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f { let uv = (pos.xy - 0.5 * u.resolution) / u.resolution.y; let selfHit = rc_scene(uv, u.time); if (selfHit.w > 0.5) { let col = selfHit.xyz / (1.0 + selfHit.xyz); return vec4f(pow(col, vec3f(1.0 / 2.2)), 1.0); } var rad = vec3f(0.0); let tau = 6.2831853; for (var i: i32 = 0; i < RAYS; i = i + 1) { let ang = (f32(i) + 0.5) * tau / f32(RAYS); let rd = vec2f(cos(ang), sin(ang)); var s: f32 = 0.012; for (var k: i32 = 0; k < 28; k = k + 1) { let h = rc_scene(uv + rd * s, u.time); if (h.w > 0.5) { rad = rad + h.xyz / (1.0 + s * s * 3.5); break; } s = s + STEP_SCALE * (1.0 + 0.06 * f32(k)); } } let linear = (rad / f32(RAYS)) * LIGHT_GAIN; let mapped = linear / (vec3f(1.0) + linear); return vec4f(pow(clamp(mapped, vec3f(0.0), vec3f(1.0)), vec3f(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Screen-Space Global Illumination](https://texelatlas.vercel.app/t/screen-space-gi.md): Screen-space depth and color provide the fast ray-marchable scene that cascades trace through. ## Combination ideas - [A thin-occluder cascade zero](https://texelatlas.vercel.app/ideas/bitmask-near-field-cascades/) - [Palette-true pixel art with soft GI](https://texelatlas.vercel.app/ideas/cascade-gi-pixel-art/) ## Sources 1. [primary] Rouli Freeman, Alexander Sannikov, Adrian Margel (2025) Holographic Radiance Cascades for 2D Global Illumination. arXiv preprint (cs.GR). https://arxiv.org/abs/2505.02041 (verified via arxiv on 2026-11-29) 2. [primary] Christopher M. J. Osborne, Alexander Sannikov (2024) Radiance Cascades: A Novel High-Resolution Formal Solution for Multidimensional Non-LTE Radiative Transfer. arXiv preprint (astro-ph.SR). https://arxiv.org/abs/2408.14425 (verified via arxiv on 2026-11-29) 3. [primary] Raikiri (2024) Raikiri/RadianceCascadesPaper. https://github.com/Raikiri/RadianceCascadesPaper License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Radiance Cascades." https://texelatlas.vercel.app/t/radiance-cascades/ (accessed 2026-12-01). --- id: "radiosity" title: "Radiosity (Hemicube Form Factors)" aliases: [classical radiosity, finite-element GI] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, desktop-gpu] year_introduced: 1984 inputs: [mesh, material-params] outputs: [texture] style: "photoreal" dynamic: "static" cost: "offline" authority: "Goral et al., 1984" url: "https://texelatlas.vercel.app/t/radiosity/" sources_verified_at: "2026-11-29" --- # Radiosity (Hemicube Form Factors) (Goral et al., 1984) > Divides surfaces into patches and solves a linear system for diffuse light exchange using form factors. View-independent; the solution can be stored in vertex colors or lightmaps. ## Reach for it when - diffuse interiors look flat with direct light only - need soft color bleeding between walls - precompute view independent lighting for architecture - smooth light bounce in static room scenes ## How it works Radiosity assumes every surface is a perfect diffuser, so the light leaving a patch does not depend on the viewer. Each patch `i` has a radiosity `B_i` equal to its emission plus its reflectance times the light arriving from every other patch, `sum_j F_ij B_j`. `F_ij` are **form factors**: the fraction of light leaving `i` that lands directly on `j`. That is a linear system `B = E + R F B`. Form factors come from geometry. The **hemicube** method places a half cube on patch `i`, renders the scene onto its five faces with each patch painted its own ID, and sums per-pixel weights (delta form factors) for each ID, using the GPU's visibility sorting. Solving the system by Gauss-Seidel, or by **progressive refinement** (repeatedly "shooting" the patch with the most unshot energy), gives a usable image after a few iterations. The mesh is typically adaptively subdivided where radiosity changes quickly, such as at shadow boundaries. The result is stored per vertex or per lightmap texel, and any camera can render it with ordinary Gouraud or texture mapping. ## When to use it Choose it for a quick, conceptually simple baker of diffuse-only static lighting, and for teaching: it is the origin of lightmaps and precomputed GI. Prefer [lightmap-baking](lightmap-baking) with [path-tracing](path-tracing) as the integrator for production, since it handles non-diffuse materials and complex lights. Prefer [instant-radiosity](instant-radiosity) when you want a GPU-friendly approximation with light-path sampling. Prefer [photon-mapping](photon-mapping) when glossy and caustic transport matter. ## Cost offline — Form-factor computation scales quadratically in patch count without hierarchies; progressive refinement trades time for visible convergence. Measured GPU Weight: 26.3× baseline (heavy) — 0.8154 ms median / 0.8542 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.18× baseline (heavy) — 0.4321 ms median (1.89× faster on L4). Ampere A100 scaling: 15.99× baseline (moderate) — 0.4604 ms median (1.77× faster on A100). ## Failure modes - Diffuse-only: no specular, glossy or caustic transport - Visible mesh artifacts (blocky shading, light leaks at patch edges) when the patch mesh is too coarse relative to lighting detail - Hemicube aliasing and missed small patches because of pixel resolution - Memory and time grow quickly with patch count, motivating hierarchical radiosity ## Engine support - unity: builtin — `Lighting > Realtime Lighting > Realtime Global Illumination (Enlighten partitions scenes into surface patches/clusters with precomputed visibility)` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/realtime-gi-using-enlighten.html, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params - Outputs: texture - Platforms: cpu, desktop-gpu ## Presets ### Radiosity (Hemicube Form Factors) — 0-bounce direct (left) vs patch-to-patch diffuse radiosity (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PATCH_RES": 7, "P_BOUNCE_GAIN": 1.25, "P_PATCH_GRID": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_PATCH_RES = 7.0; // P Patch Subdiv [3.0, 14.0, 1.0] const float P_BOUNCE_GAIN = 1.25; // P Multi-Bounce [0.2, 2.2, 0.05] const float P_PATCH_GRID = 0.75; // P Patch Outlines [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Direct / Radiosity [0.0, 1.0, 0.02] 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); } // Classic Cornell box scene with tall + short diffuse boxes vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 1.0, 1.0); // floor float dC = 1.0 - p.y; if (dC < res.x) res = vec2(dC, 1.0); float dB = p.z + 1.4; if (dB < res.x) res = vec2(dB, 1.0); float dL = p.x + 1.25; if (dL < res.x) res = vec2(dL, 2.0); // red wall float dR = 1.25 - p.x; if (dR < res.x) res = vec2(dR, 3.0); // green-cyan wall float dTall = sdBox(p - vec3(-0.38, -0.44, -0.45), vec3(0.32, 0.56, 0.32)); if (dTall < res.x) res = vec2(dTall, 4.0); float dShort = sdBox(p - vec3(0.42, -0.68, -0.05), vec3(0.30, 0.32, 0.30)); if (dShort < res.x) res = vec2(dShort, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Analytical diffuse form factor F_ij = cos(theta_i)*cos(theta_j) / (pi * r^2 + A_j) float formFactor(vec3 pi, vec3 ni, vec3 pj, vec3 nj, float areaJ) { vec3 v = pj - pi; float r2 = dot(v, v); float r = sqrt(max(r2, 1e-5)); vec3 dir = v / r; float ci = max(dot(ni, dir), 0.0); float cj = max(dot(nj, -dir), 0.0); return (ci * cj * areaJ) / (3.1415926 * r2 + areaJ + 0.15); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isRad = screenX >= split; float patchN = clamp(floor(P_PATCH_RES + 0.5), 3.0, 14.0); float bGain = clamp(P_BOUNCE_GAIN, 0.1, 2.4); float gridVis = clamp(P_PATCH_GRID, 0.0, 1.5); vec3 ro = vec3(0.0, 0.02, 2.35); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); // Quantize surface position to discrete radiosity patch centers on the right (classic piecewise-constant patches) float patchStep = 2.0 / patchN; vec3 pPatch = (floor(p / patchStep) + 0.5) * patchStep; // Keep patch center on the actual surface along normal axis vec3 evalP = isRad ? mix(p, pPatch, 0.55) : p; vec3 alb = vec3(0.78, 0.76, 0.72); if (matId > 1.5 && matId < 2.5) alb = vec3(0.86, 0.18, 0.15); if (matId > 2.5 && matId < 3.5) alb = vec3(0.14, 0.72, 0.58); // Ceiling patch emitter vec3 emitP = vec3(0.0, 0.99, -0.35); if (p.y > 0.98 && abs(p.x) < 0.36 && abs(p.z + 0.35) < 0.32) { col = vec3(3.4, 3.1, 2.6); } else { // Direct emitter form factor F(patch -> ceiling light) float fLight = formFactor(evalP, n, emitP, vec3(0.0, -1.0, 0.0), 0.72); // Soft geometric visibility test toward ceiling patch vec3 toL = normalize(emitP - p); float vis = 1.0; float tSh = 0.04; for (int s = 0; s < 16; s++) { float ds = mapScene(p + toL * tSh).x; if (ds < 0.004) { vis = 0.08; break; } tSh += max(ds, 0.04); if (tSh > length(emitP - p) - 0.08) break; } vec3 direct = alb * vec3(2.8, 2.55, 2.15) * fLight * vis; if (!isRad) { // Left: direct illumination only (black shadows, zero color bleeding) col = direct + alb * vec3(0.03); } else { // Right: 2-bounce patch-to-patch form-factor exchange from all 5 surrounding walls vec3 bounce = vec3(0.0); // Sample 3 patches on left red wall for (int k = 0; k < 3; k++) { float yk = -0.55 + float(k) * 0.55; float fL = formFactor(evalP, n, vec3(-1.24, yk, -0.35), vec3(1.0, 0.0, 0.0), 0.95); bounce += vec3(0.86, 0.18, 0.15) * fL * 1.15; float fR = formFactor(evalP, n, vec3(1.24, yk, -0.35), vec3(-1.0, 0.0, 0.0), 0.95); bounce += vec3(0.14, 0.72, 0.58) * fR * 1.15; } // Floor & back wall neutral bounce bounce += vec3(0.76, 0.74, 0.68) * formFactor(evalP, n, vec3(0.0, -0.99, -0.35), vec3(0.0, 1.0, 0.0), 2.2) * 0.75; bounce += vec3(0.74, 0.72, 0.68) * formFactor(evalP, n, vec3(0.0, 0.0, -1.39), vec3(0.0, 0.0, 1.0), 2.0) * 0.62; // Ambient occlusion darkening inside corners for realistic patch shadowing float ao = clamp(0.45 + 0.55 * mapScene(p + n * 0.24).x / 0.24, 0.22, 1.0); col = direct + alb * (bounce * bGain * ao + vec3(0.08, 0.075, 0.07)); // Patch mesh grid overlay showing discrete radiosity elements vec3 pf = abs(fract(p / patchStep - 0.5) - 0.5); vec3 an = abs(n); float dEdge = (an.x > an.y && an.x > an.z) ? min(pf.y, pf.z) : ((an.y > an.z) ? min(pf.x, pf.z) : min(pf.x, pf.y)); float wire = smoothstep(0.045, 0.010, dEdge); col = mix(col, col * 0.42 + vec3(0.04, 0.06, 0.09), wire * 0.45 * min(gridVis, 1.2)); } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Lightmap Baking](https://texelatlas.vercel.app/t/lightmap-baking.md): Radiosity solutions are written into lightmap texels that the real-time shader samples. ## Combination ideas - [Progressive radiosity relighting on PatchMatch multi-view stereo rooms](https://texelatlas.vercel.app/ideas/patchmatch-mvs-radiosity-relighting/) ## Sources 1. [primary] Cindy M. Goral, Kenneth E. Torrance, Donald P. Greenberg, Bennett Battaile (1984) Modeling the interaction of light between diffuse surfaces. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/964965.808601 (verified via crossref on 2026-11-29) 2. [primary] Michael F. Cohen, Donald P. Greenberg (1985) The hemi-cube. Proceedings of the 12th annual conference on Computer graphics and interactive techniques - SIGGRAPH '85. https://doi.org/10.1145/325334.325171 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Radiosity (Hemicube Form Factors)." https://texelatlas.vercel.app/t/radiosity/ (accessed 2026-12-01). --- id: "ray-offsetting-self-intersection" title: "Robust ray origin offsetting (self-intersection avoidance)" aliases: [shadow acne in ray tracing, ray epsilon, adaptive ray bias, spawn ray offset] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [cuda, desktop-gpu, cpu, webgpu, blender, unreal] year_introduced: 2019 inputs: [mesh] outputs: [visibility-mask] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Wächter & Binder, 2019" url: "https://texelatlas.vercel.app/t/ray-offsetting-self-intersection/" sources_verified_at: "2026-11-29" --- # Robust ray origin offsetting (self-intersection avoidance) (Wächter & Binder, 2019) > Move the origin of secondary rays off the surface by a small, scale-aware amount along the geometric normal so rays never re-hit the triangle they started on, without the light leaking that fixed epsilons cause. ## Reach for it when - shadow acne speckles in my ray traced scene - rays hit the surface they started from - fixed ray epsilon leaks light at corners - black dots appear on surfaces in path tracing ## How it works Hit points are computed in finite precision, so a ray spawned at the hit may start slightly below its surface and hit the same triangle again at tiny distance. The result is shadow acne, black speckles in GI, or reflection rays killed at their origin. A fixed epsilon trades acne for light leaking at corners and fails at different scales. A robust offset instead uses the numerical error of the hit point. One practical scheme works in integer space: perturb the floating-point origin by a few units in the last place in the direction of the geometric normal, with magnitude proportional to the position's own magnitude, so offsets scale with distance from the origin. Another approach computes a conservative error bound for the hit position from the triangle's barycentric computation and offsets by that bound along the normal, flipping by the side the ray leaves. Two details matter: the offset must be along the geometric, not shading, normal; and the direction sign is chosen from the outgoing ray direction, not from the viewer. ## When to use it Choose it in any ray-traced or path-traced renderer, hardware RT or software BVH, instead of tuning a global ray epsilon per scene. Prefer [shadow-mapping](shadow-mapping) style depth bias only for raster shadows, where the bias must be tuned per light. Prefer [ray-traced-shadows](ray-traced-shadows) and [ray-traced-ambient-occlusion](ray-traced-ambient-occlusion) as the effects that benefit most from it. For very thin or double-sided geometry combine it with proper triangle cull flags rather than larger offsets, and use [three-mesh-bvh](three-mesh-bvh) style CPU or WebGPU tracers with the same scheme. ## Cost cheap — A few integer or float operations when spawning each ray; no extra memory or traversal. Measured GPU Weight: 26.28× baseline (heavy) — 0.8645 ms median / 0.8729 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 24.59× baseline (heavy) — 0.391 ms median (2.21× faster on L4). Ampere A100 scaling: 16.66× baseline (moderate) — 0.4797 ms median (1.8× faster on A100). ## Failure modes - Light leaking at thin walls and contact points when the offset is too large for the scene scale - Shadow acne returns at curved surfaces if the shading normal is used instead of the geometric normal - Offsets fixed in world units fail for scenes with very large or very small coordinates - Instanced and transformed geometry needs the offset computed in object space before transforming, or the error bound is wrong - Refraction rays need the offset on the transmitted side, so reusing the reflection sign flips the origin into the surface - Displaced or tessellated geometry hit by hardware ray tracing has no stable geometric normal for the offset ## Engine support - godot: builtin — `LightmapGI.bias offsets ray origins during GPU lightmap ray tracing (bake_params.bias in lm_compute.glsl)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/lightmapper_rd/lm_compute.glsl, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: visibility-mask - Platforms: cuda, desktop-gpu, cpu, webgpu, blender, unreal ## Presets ### Robust Ray Offsetting — fixed-epsilon shadow acne & light leaks (left) vs scale- & normal-aware offset (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_NAIVE_EPS": 0.35, "P_GRAZING_ANG": 0.52, "P_SUN_ORBIT": 0.4, "P_SPLIT": 0.48 } ``` ```glsl const float P_NAIVE_EPS = 0.35; // P Fixed Eps Error [0.05, 1.0, 0.05] const float P_GRAZING_ANG = 0.52; // P Grazing Severity [0.1, 1.0, 0.05] const float P_SUN_ORBIT = 0.40; // P Sun Motion [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Naive / Robust Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } 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); } // High-curvature spheres + thin wall blade + ground plane where fixed-eps offsetting fails dramatically! vec2 mapScene(vec3 p) { float dFloor = p.y + 0.58; vec2 res = vec2(dFloor, 1.0); // Hero curved sphere resting on the floor float dSph = length(p - vec3(-0.22, -0.14, -0.25)) - 0.44; if (dSph < res.x) res = vec2(dSph, 2.0); // Thin architectural partition wall touching the floor (exposes Peter-Panning light leaks if eps is too large!) float dThinWall = sdBox(p - vec3(0.56, -0.06, -0.42), vec3(0.025, 0.52, 0.62)); if (dThinWall < res.x) res = vec2(dThinWall, 3.0); // Small resting precision sphere near thin wall float dSmall = length(p - vec3(0.24, -0.40, 0.14)) - 0.18; if (dSmall < res.x) res = vec2(dSmall, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0018, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } float traceHardShadow(vec3 ro, vec3 rd) { float t = 0.0; for (int i = 0; i < 42; i++) { float h = mapScene(ro + rd * t).x; if (h < 0.0015) return 0.0; t += max(h, 0.012); if (t > 4.5) break; } return 1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useRobust = sx >= split; float naiveParam = clamp(P_NAIVE_EPS, 0.02, 1.0); float grazingSev = clamp(P_GRAZING_ANG, 0.05, 1.2); float sunOrb = iTime * max(P_SUN_ORBIT, 0.0); vec3 ro = vec3(0.15, 0.36, 2.08); vec3 ta = vec3(0.06, -0.22, -0.25); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.44 + ri * uv.x + up * uv.y); vec3 sky = mix(vec3(0.76, 0.82, 0.90), vec3(0.18, 0.36, 0.68), smoothstep(-0.08, 0.58, rd.y)); vec3 col = sky; float t = 0.05; float hitId = 0.0; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.0018) { hitId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hitId > 0.5) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 sunDir = normalize(vec3(0.82 * cos(sunOrb * 0.45 + 0.2), 0.52, 0.48 * sin(sunOrb * 0.45 + 0.2) + 0.35)); float ndl = max(dot(n, sunDir), 0.0); float sh = 1.0; if (useRobust) { // Robust Wachter-Binder scale-aware geometric-normal offset: adapts to world-coordinate magnitude + grazing angle float coordScale = max(max(abs(p.x), abs(p.y)), max(abs(p.z), 1.0)); float robEps = 0.0045 * coordScale; sh = traceHardShadow(p + n * robEps, sunDir); } else { // Naive fixed world-space ray-direction offset: // Low naiveParam -> floating-point precision self-intersection acne speckles on curved/grazing surfaces! // High naiveParam -> rays punch right through thin wall base, creating bright Peter-Panning light leaks! float bigEps = mix(0.001, 0.14, naiveParam * naiveParam); sh = traceHardShadow(p + sunDir * bigEps, sunDir); // Simulate float32 mantissa ULP quantization self-intersection acne near grazing angles when offset is small float acneStrength = (1.0 - smoothstep(0.08, 0.65, naiveParam)) * grazingSev; float grazing = pow(1.0 - ndl, 1.5); float band = sin(dot(p, vec3(78.0, 62.0, 84.0)) + hash21(floor(fragCoord * 0.5)) * 2.8); float acneMask = step(0.15, band) * step(0.12, acneStrength * (0.35 + grazing)); if (ndl > 0.01 && acneMask > 0.5) sh = 0.0; } vec3 alb = vec3(0.76, 0.74, 0.70); if (hitId > 1.5 && hitId < 2.5) alb = vec3(0.86, 0.58, 0.28); else if (hitId > 2.5 && hitId < 3.5) alb = vec3(0.28, 0.52, 0.72); else if (hitId > 3.5) alb = vec3(0.82, 0.84, 0.88); vec3 amb = mix(vec3(0.16, 0.19, 0.24), vec3(0.32, 0.44, 0.64), 0.5 + 0.5 * n.y); col = alb * (vec3(1.45, 1.32, 1.12) * ndl * sh + amb * 0.45); if (hitId < 1.5) { col = mix(col, sky, 1.0 - exp(-t * 0.08)); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md): The offset origin from this method is the start of each shadow ray and removes acne without a per-scene bias. - [Next-event estimation (direct light sampling)](https://texelatlas.vercel.app/t/next-event-estimation.md): Every shadow ray cast from a path vertex needs a robust origin so occlusion tests do not self-hit. ## Sources 1. [primary] Carsten Wächter, Nikolaus Binder (2019) A Fast and Robust Method for Avoiding Self-Intersection. Ray Tracing Gems. https://doi.org/10.1007/978-1-4842-4427-2_6 (verified via crossref on 2026-11-29) 2. [tutorial] NVIDIA Solving Self-Intersection Artifacts in DirectX Raytracing. developer.nvidia.com. https://developer.nvidia.com/blog/solving-self-intersection-artifacts-in-directx-raytracing (verified via http on 2026-11-29) ## Cite this entry Texel. "Robust ray origin offsetting (self-intersection avoidance)." https://texelatlas.vercel.app/t/ray-offsetting-self-intersection/ (accessed 2026-12-01). --- id: "ray-traced-ambient-occlusion" title: "Ray-Traced Ambient Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [desktop-gpu, unreal, unity, cuda, webgpu] year_introduced: 2008 inputs: [mesh, normals, depth] outputs: [visibility-mask] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Boksansky et al., 2019" url: "https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion/" sources_verified_at: "2026-11-29" --- # Ray-Traced Ambient Occlusion (Boksansky et al., 2019) > Casts short hemisphere rays from each pixel through the scene's acceleration structure and measures what fraction escape, giving AO that sees off-screen and thin geometry. ## Reach for it when - screen-space darkening misses off-screen geometry - thin objects produce wrong contact shadows - need accurate crease darkening with hardware rt - depth-buffer artefacts and halos around objects ## How it works For each pixel, one or a few short cosine-distributed rays are traced against the BVH with a limited maximum distance. The fraction that hit geometry is the occlusion. A spatio-temporal denoiser, guided by the G-buffer and ray hit distance, then reduces the noise inherent in a single ray per pixel. Since the AO uses actual scene geometry it is free from screen-space errors such as halos, thickness or missing off-screen occluders, and can output the bent normal direction from the escaped rays. Cost follows the BVH and the ray budget. ## When to use it Choose it when hardware ray tracing is on hand and screen-space errors are unacceptable. Prefer [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) as the performance fallback, [SDF Ambient Occlusion](https://texelatlas.vercel.app/t/sdf-ambient-occlusion.md) for static baked fields on web, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) for the direct-light analogue. ## Cost medium — One ray per pixel plus denoise; scales with scene complexity and BVH quality. Measured GPU Weight: 26.77× baseline (heavy) — 0.8808 ms median / 0.9073 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 20.33× baseline (heavy) — 0.3233 ms median (2.72× faster on L4). Ampere A100 scaling: 15.76× baseline (moderate) — 0.4539 ms median (1.94× faster on A100). ## Failure modes - Noise and temporal lag in dark corners after denoising - Self-intersection requires ray origin offsets - BVH update cost for dynamic or skinned geometry - Radius choice trades contact detail for large-scale occlusion ## Engine support - blender: builtin — `Shader Editor > Add > Input > Ambient Occlusion` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/input/ao.html, checked 2026-12-01) - metal: builtin — `MTLAccelerationStructure + intersector<> in MSL` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlaccelerationstructure.json, checked 2026-12-01) — API primitive for ray/scene intersection; AO shader is yours. - unity: builtin — `Volume > Add Override > Lighting > Ambient Occlusion > Ray Tracing` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Ambient-Occlusion.md, checked 2026-12-01) — HDRP only, requires DXR hardware. - unreal: builtin — `Post Process Volume > Ray Tracing Ambient Occlusion; requires r.RayTracing.AmbientOcclusion.Supported=1` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/hardware-ray-tracing-in-unreal-engine, checked 2026-12-01) — Deprecated and off by default; Lumen has its own AO. ## Dataflow - Inputs: mesh, normals, depth - Outputs: visibility-mask - Platforms: desktop-gpu, unreal, unity, cuda, webgpu ## Presets ### Left: flat ambient. Right: 48 short hemisphere rays per pixel against the scene, unfiltered (glsl-fragment; rendered 2026-11-29) ```json { "NR": 48, "MAXD": 0.8 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const int NR=48; // P const float MAXD=0.8; // P void aoBent(vec3 P,vec3 N,vec2 uv,out float ao,out vec3 bent){ vec3 T=normalize(abs(N.y)<.9?cross(N,vec3(0.,1.,0.)):cross(N,vec3(1.,0.,0.))),B=cross(N,T); float ph=rnd2(uv,5.).x*6.2831853,vis=0.;vec3 sum=vec3(0.); for(int i=0;iMAXD){sum+=d;vis+=1.;}} ao=vis/float(NR);bent=normalize(sum+N*.001);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao=1.;vec3 b;if(R){aoBent(P,n,uv,ao,b);ao=clamp(1.-1.2*(1.-ao),0.,1.);}col=mix(ambShade(P,n,vec3(ao)),sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Sources 1. [primary] Jakub Boksansky, Michael Wimmer, Jiri Bittner (2019) Ray Traced Shadows: Maintaining Real-Time Frame Rates. Ray Tracing Gems. https://doi.org/10.1007/978-1-4842-4427-2_13 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Ray-Traced Ambient Occlusion." https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion/ (accessed 2026-12-01). --- id: "ray-traced-prism-displacement-mapping" title: "Ray-Traced Prism Displacement Mapping" aliases: [PDM, tessellation-free displacement ray tracing, prism displacement mapping, direct displacement ray tracing] domain: "materials" stage: "material" realtime: "interactive" platforms: [webgpu, desktop-gpu, cuda, cpu] year_introduced: 2021 inputs: [mesh, heightfield, normals, uv-atlas] outputs: [normals, depth] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Thonat et al., 2021" url: "https://texelatlas.vercel.app/t/ray-traced-prism-displacement-mapping/" sources_verified_at: "2026-11-30" --- # Ray-Traced Prism Displacement Mapping (Thonat et al., 2021) > Ray-traces height-map displacement directly on coarse base triangles without tessellation by bounding each displaced triangle inside a curved-side triangular prism, intersecting its bilinear faces, and marching or subdividing against a min-max height hierarchy. ## Reach for it when - parallax occlusion mapping breaks at curved edges and silhouettes - need exact displaced micro-geometry without tessellating millions of triangles - avoid self-intersection cracks when ray tracing heightmaps on meshes - render sharp displaced brick or stone silhouettes in a path tracer - intersect heightfield shells directly inside triangular prisms ## How it works Traditional displacement mapping subdivides base meshes into millions of micro-triangles, blowing up BVH build time and GPU memory. **Ray-traced prism displacement mapping** keeps only the coarse base mesh in the acceleration structure (with AABBs inflated by the displacement bounds) and resolves fine relief lazily inside a custom ray-intersection routine. Each base triangle `(pA, pB, pC)` is extruded along its smooth vertex normals `(nA, nB, nC)` between its minimum and maximum height offsets, forming a watertight **triangular prism** bounded by two flat endcap triangles and three **bilinear patch** side faces. When a ray enters a leaf prism's AABB, the intersector computes exact entry and exit distances `[tMin, tMax]` against the two cap triangles and three bilinear side patches (e.g. via Reshetov's closed-form ray-bilinear test). Because vertex normals are shared across adjacent base triangles, neighboring prisms meet seamlessly along identical bilinear surfaces. Within `[tMin, tMax]`, the ray maps continuously into local barycentric `(u, v)` and height `h` coordinates inside the prism—forming a curved trajectory in texture space—and searches for the first crossing of the scalar height field using either hierarchical min-max mipmap / RMIP traversal or adaptive ray marching followed by secant/binary refinement, computing exact displaced shading normals via finite differences or micro-triangle reconstruction. ## When to use it Choose it in GPU or CPU ray and path tracers when you need true displaced silhouettes, accurate self-shadowing, and crisp micro-geometry over large surfaces without pre-tessellating millions of triangles into a heavy BVH. Prefer [parallax-occlusion-mapping](parallax-occlusion-mapping) or [relaxed-cone-step-mapping](relaxed-cone-step-mapping) in rasterized pipelines where only screen-space depth perturbation is needed. Prefer [normal-mapping-mikktspace](normal-mapping-mikktspace) when silhouettes do not need to change. Prefer [nanite-virtualized-geometry](nanite-virtualized-geometry) when rasterizing pre-authored high-poly triangle meshes. ## Cost medium — Drastically cuts BVH memory and build cost compared to dense tessellation, trading it for per-ray prism intersection and height-hierarchy traversal inside displaced primitives. Measured GPU Weight: 21.65× baseline (heavy) — 0.7122 ms median / 0.7445 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.07× baseline (moderate) — 0.2714 ms median (2.62× faster on L4). Ampere A100 scaling: 12.86× baseline (moderate) — 0.3705 ms median (1.92× faster on A100). ## Failure modes - Step-marching variants can miss thin spikes or ridges if the step size is too coarse relative to height-map frequency, whereas hierarchical min-max or RMIP bounds avoid missed intersections - Strongly diverging vertex normals on concave creases can cause adjacent prisms to self-intersect or invert, producing cracks unless displacement scale is bounded by local curvature - Grazing rays spend many traversal iterations inside long shallow prisms, increasing ray-tracing thread divergence on GPUs - Requires watertight continuous vertex normals and consistent UV seams across base triangles to avoid gaps along UV chart boundaries ## Dataflow - Inputs: mesh, heightfield, normals, uv-atlas - Outputs: normals, depth - Platforms: webgpu, desktop-gpu, cuda, cpu ## Presets ### Ray-Traced Prism Displacement — flat normal-mapped base shell (left) vs ray-traced prism micro-displacement (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DISP_HEIGHT": 0.16, "P_PATTERN_FREQ": 6, "P_ROT_SPEED": 0.52, "P_SPLIT": 0.48 } ``` ```glsl const float P_DISP_HEIGHT = 0.16; // P Prism Shell Height [0.04, 0.26, 0.01] const float P_PATTERN_FREQ = 6.0; // P Brick Tile Freq [3.0, 10.0, 0.5] const float P_ROT_SPEED = 0.52; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P NormalMap / PrismRT [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Deep carved stone ashlar masonry heightfield h(u, v) in [0, 1] float masonryHeight(vec2 uv, float freq) { vec2 g = uv * vec2(freq * 2.0, freq); float row = floor(g.y); g.x += mod(row, 2.0) * 0.5; vec2 f = fract(g); vec2 dEdge = min(f, 1.0 - f); float mortar = smoothstep(0.06, 0.14, min(dEdge.x, dEdge.y * 1.4)); // Subtle chisel bevel & per-stone elevation variance float stoneVar = 0.78 + 0.22 * sin(row * 3.7 + floor(g.x) * 5.3); float relief = 0.08 * sin(uv.x * 24.0) * cos(uv.y * 24.0); return clamp(mortar * stoneVar + relief * mortar, 0.0, 1.0); } // Base coarse curved stone pillar cylinder (radius R0 = 0.50, height H = 1.45) // Extruded prism shell spans [R0, R0 + dispH] float mapDisplacedPillar(vec3 p, float dispH, float freq) { float r = length(p.xz); float ang = atan(p.z, p.x) / 6.2831853 + 0.5; float h = masonryHeight(vec2(ang * 2.0, p.y * 0.85 + 0.5), freq); float dCyl = r - (0.48 + h * dispH); float dCap = abs(p.y) - 0.74; return max(dCyl, dCap) * 0.65; } float mapBasePillar(vec3 p, float dispH) { float r = length(p.xz); return max(r - (0.48 + dispH * 0.5), abs(p.y) - 0.74); } vec3 calcDispNormal(vec3 p, float dispH, float freq) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapDisplacedPillar(p + e.xyy, dispH, freq) - mapDisplacedPillar(p - e.xyy, dispH, freq), mapDisplacedPillar(p + e.yxy, dispH, freq) - mapDisplacedPillar(p - e.yxy, dispH, freq), mapDisplacedPillar(p + e.yyx, dispH, freq) - mapDisplacedPillar(p - e.yyx, dispH, freq) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isPrismRT = screenX >= split; float dispH = clamp(P_DISP_HEIGHT, 0.02, 0.30); float freq = clamp(P_PATTERN_FREQ, 2.5, 12.0); float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.45; vec3 ro = vec3(0.0, 0.12, 2.25); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.02), -1.52)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 col = mix(vec3(0.022, 0.028, 0.048), vec3(0.062, 0.078, 0.124), smoothstep(-0.55, 0.55, uv.y)); vec3 lDir = normalize(vec3(0.68, 0.58, 0.48)); float t = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; float d = isPrismRT ? mapDisplacedPillar(p, dispH, freq) : mapBasePillar(p, dispH); if (d < 0.002) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; float ang = atan(p.z, p.x) / 6.2831853 + 0.5; vec2 mUV = vec2(ang * 2.0, p.y * 0.85 + 0.5); float hC = masonryHeight(mUV, freq); vec3 n; float shadow = 1.0; if (isPrismRT) { n = calcDispNormal(p, dispH, freq); // True ray-traced prism self-shadowing across deep mortar crevices! float ts = 0.02; for (int s = 0; s < 16; s++) { float ds = mapDisplacedPillar(p + lDir * ts, dispH, freq); if (ds < 0.002) { shadow = 0.22; break; } ts += max(ds, 0.015); } } else { // Left: flat silhouette cylinder with perturbed normal map only (no silhouette displacement, no self-occlusion!) vec3 baseN = normalize(vec3(p.x, 0.0, p.z)); vec3 tang = normalize(vec3(-p.z, 0.0, p.x)); vec3 bitang = vec3(0.0, 1.0, 0.0); float e = 0.004; float dU = (masonryHeight(mUV + vec2(e, 0.0), freq) - hC) / e; float dV = (masonryHeight(mUV + vec2(0.0, e), freq) - hC) / e; n = normalize(baseN - (tang * dU + bitang * dV) * dispH * 0.45); } float diff = max(dot(n, lDir), 0.0) * shadow; float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 28.0) * shadow; vec3 stone = mix(vec3(0.24, 0.22, 0.20), vec3(0.76, 0.68, 0.58), smoothstep(0.15, 0.85, hC)); col = stone * (0.20 + 0.92 * diff) + vec3(1.0, 0.95, 0.88) * spec * 0.28; // Highlight crisp displaced silhouette boundary on right float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.2); col += (isPrismRT ? vec3(0.24, 0.82, 0.98) : vec3(0.92, 0.34, 0.26)) * rim * 0.28; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Provides true displaced silhouettes and self-shadowing inside a path tracer without exploding scene triangle counts. - [SAH BVH construction](https://texelatlas.vercel.app/t/sah-bvh-construction.md): Stores each base triangle's inflated prism AABB as a custom primitive inside a standard BVH. ## Sources 1. [primary] Theo Thonat, Francois Beaune, Xin Sun, Nathan Carr, Tamy Boubekeur (2021) Tessellation-free displacement mapping for ray tracing. ACM Transactions on Graphics. https://doi.org/10.1145/3478513.3480535 (verified via crossref on 2026-11-30) 2. [primary] Theo Thonat, Iliyan Georgiev, François Beaune, Tamy Boubekeur (2023) RMIP: Displacement ray tracing via inversion and oblong bounding. SIGGRAPH Asia 2023 Conference Papers. https://doi.org/10.1145/3610548.3618182 (verified via doi.org on 2026-11-30) 3. [secondary] Brian Smits, Peter Shirley, Michael M. Stark (2000) Direct Ray Tracing of Displacement Mapped Triangles. Eurographics. https://doi.org/10.1007/978-3-7091-6303-0_28 (verified via crossref on 2026-11-30) 4. [secondary] Serban D. Porumbescu, Brian Budge, Louis Feng, Kenneth I. Joy (2005) Shell maps. ACM Transactions on Graphics. https://doi.org/10.1145/1073204.1073239 (verified via crossref on 2026-11-30) 5. [secondary] Alexander Reshetov (2019) Cool Patches: A Geometric Approach to Ray/Bilinear Patch Intersections. Ray Tracing Gems. https://doi.org/10.1007/978-1-4842-4427-2_8 (verified via crossref on 2026-11-30) 6. [implementation] pissang (2026) pissang/mutracer. https://github.com/pissang/mutracer License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Ray-Traced Prism Displacement Mapping." https://texelatlas.vercel.app/t/ray-traced-prism-displacement-mapping/ (accessed 2026-12-01). --- id: "ray-traced-shadows" title: "Ray-Traced Shadows" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [desktop-gpu, unreal, unity, cuda, webgpu] year_introduced: 1984 inputs: [mesh, depth, normals] outputs: [visibility-mask] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Boksansky et al., 2019" url: "https://texelatlas.vercel.app/t/ray-traced-shadows/" sources_verified_at: "2026-11-29" --- # Ray-Traced Shadows (Boksansky et al., 2019) > Shoots shadow rays from each visible point toward a sampled point on the light, giving exact occlusion and physically sized penumbrae without shadow-map artifacts. ## Reach for it when - shadow map artefacts like peter-panning and acne - large area lights need correct soft penumbrae - shadows should be exact without bias tuning - many light types without shadow map management - contact-hardening shadows with hardware ray tracing ## How it works For every visible pixel, one or more rays are cast to random points on an area light or within a cone for the sun, using the hardware acceleration structure for visibility only (any-hit with early termination). Averaging many samples approximates the area-light penumbra; real-time budgets allow roughly one ray per pixel, so the noisy result is denoised with a spatio-temporal filter guided by the G-buffer, ray distance (penumbra size) and blue-noise sampling. Because the test is exact there is no bias, acne or resolution limit, and contact hardening emerges naturally. The acceleration structure must be updated for animated geometry. ## When to use it Choose it when hardware ray tracing is available and you need accurate contact shadows, large soft area lights or many light types without maintaining shadow maps. Prefer [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) or [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md) on hardware without ray tracing, and [SDF Soft Shadows](https://texelatlas.vercel.app/t/sdf-soft-shadows.md) when a cheap approximation from a distance field is sufficient. ## Cost medium — One to a few rays per pixel plus denoiser; depends heavily on scene complexity and BVH quality. Measured GPU Weight: 28.61× baseline (heavy) — 0.9414 ms median / 0.978 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.24× baseline (heavy) — 0.3377 ms median (2.79× faster on L4). Ampere A100 scaling: 16.66× baseline (moderate) — 0.4798 ms median (1.96× faster on A100). ## Failure modes - Noise and temporal lag in penumbrae when denoising is aggressive - Acceleration-structure rebuild costs for dynamic or skinned geometry - Alpha-tested foliage can force expensive any-hit shaders - Needs hardware ray tracing support or a software BVH fallback ## Engine support - blender: builtin — `Cycles: light shadows are traced by default; Light Properties > Settings > Cast Shadow` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/light_settings.html, checked 2026-12-01) — Software (and OptiX/HIP/Metal hardware) ray tracing in Cycles. - metal: builtin — `MTLAccelerationStructure + intersector<> in MSL, or MTLIntersectionFunctionTable` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlaccelerationstructure.json, checked 2026-12-01) — API primitive for ray/scene intersection; shadow shader is yours. - unity: builtin — `Light > Shadows > Ray Traced; Volume > Screen Space Shadows` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Shadows.md, checked 2026-12-01) — HDRP only, requires DXR hardware. - unreal: builtin — `Project Settings > Rendering > Hardware Ray Tracing > Support Hardware Ray Tracing; Light > Ray Tracing > Cast Ray Traced Shadows` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/ray-tracing-and-path-tracer-features-properties-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, depth, normals - Outputs: visibility-mask - Platforms: desktop-gpu, unreal, unity, cuda, webgpu ## Presets ### Left: one hard shadow ray to a point light. Right: 48 shadow rays over a disc light give a physical penumbra (glsl-fragment; rendered 2026-11-29) ```json { "NS": 48, "LR": 0.16 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const int NS=48; // P const float LR=0.16; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t+n*2e-3,q;float vis=0.; if(!R) vis=isect(P,LD,q)>1e8?1.:0.; else{ vec3 U=normalize(cross(vec3(0.,1.,0.),LD)),V=cross(LD,U);float ph=hash(floor(fragCoord))*6.2831853; for(int i=0;i1e8?1.:0.;} vis/=float(NS); } col=mix(alb(P)*(vec3(.55,.62,.75)*(.5+.5*n.y)*.5+vec3(1.,.95,.85)*max(dot(n,LD),0.)*vis*1.15),sky(rd),smoothstep(6.,25.,t)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Sources 1. [primary] Jakub Boksansky, Michael Wimmer, Jiri Bittner (2019) Ray Traced Shadows: Maintaining Real-Time Frame Rates. Ray Tracing Gems. https://doi.org/10.1007/978-1-4842-4427-2_13 (verified via crossref on 2026-11-29) 2. [tutorial] Alan Wolfe (2021) Using Blue Noise for Ray Traced Soft Shadows. Ray Tracing Gems II. https://doi.org/10.1007/978-1-4842-7185-8_24 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Ray-Traced Shadows." https://texelatlas.vercel.app/t/ray-traced-shadows/ (accessed 2026-12-01). --- id: "rayleigh-mie-single-scattering" title: "Ray-marched Rayleigh/Mie Single Scattering" aliases: [Nishita sky, analytic sky ray march] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 1993 inputs: [material-params] outputs: [radiance, hdr-image] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Nishita et al., 1993" url: "https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering/" sources_verified_at: "2026-11-29" --- # Ray-marched Rayleigh/Mie Single Scattering (Nishita et al., 1993) > Integrate sunlight scattered once toward the eye along the view ray through an exponential-density atmosphere, with an inner loop for sun transmittance; the textbook way to get blue skies and red sunsets in a shader. ## Reach for it when - need a blue sky and red sunset in a shader - cheap atmosphere without precomputed tables - haze and sun glow around the sun in a scene - procedural sky that responds to sun position ## How it works Intersect the view ray with the atmosphere shell, split it into N samples and at each sample accumulate the local Rayleigh and Mie densities, which decay exponentially with altitude using separate scale heights. A second short march from the sample toward the sun gives the optical depth to the light; transmittance is exp of minus the sum of beta times optical depth over both legs. Contribution at each sample is that transmittance times density, and the final color is multiplied by the sun power and by the Rayleigh and Henyey-Greenstein phase functions evaluated at the angle to the sun. Rayleigh coefficients scale roughly with inverse wavelength to the fourth power, which makes the blue sky and red dusk. Higher scattering orders are ignored, so a constant ambient floor is often added. ## When to use it Choose it for a compact sky shader with no tables, when you need sunset colors, and when you can afford roughly a hundred texture-less samples per pixel (or render to a small sky-dome texture once per frame). Prefer [Hosek-Wilkie Sky Model](https://texelatlas.vercel.app/t/hosek-wilkie-sky.md) or [Preetham Analytic Daylight Model](https://texelatlas.vercel.app/t/preetham-sky.md) for a per-pixel-free analytic sky, [Precomputed Atmospheric Scattering](https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering.md) or [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) when you need multiple scattering and aerial perspective at lower cost per pixel. ## Cost medium — Cost grows as view samples times light samples per pixel; render to a low-res dome or cubemap to bring it down. Measured GPU Weight: 42.39× baseline (heavy) — 1.3947 ms median / 1.4573 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 40.06× baseline (heavy) — 0.637 ms median (2.19× faster on L4). Ampere A100 scaling: 26.17× baseline (heavy) — 0.7537 ms median (1.85× faster on A100). ## Failure modes - Single scattering only: the sky around the horizon after sunset goes unrealistically black or too saturated - Banding or hard rings with too few view samples when the ray grazes the horizon - Sun below the horizon without a planet-shadow test lights the ground incorrectly - Mie asymmetry g near 0.99 creates aliasing at the sun disc without more samples - Looking down onto ground needs a separate ground color; the integral just stops at the planet ## Engine support - babylonjs: official — `@babylonjs/materials SkyMaterial (rayleigh, mieCoefficient, mieDirectionalG)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/materials/src/sky/skyMaterial.ts, checked 2026-12-01) - blender: builtin — `Sky Texture node > Sky Type = Single Scattering` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/sky.html, checked 2026-12-01) — Single Scattering is legacy; Multiple Scattering is the default. - godot: builtin — `Sky.sky_material = PhysicalSkyMaterial (rayleigh_coefficient, mie_coefficient)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/PhysicalSkyMaterial.xml, checked 2026-12-01) — Analytic sky shader with Rayleigh and Mie terms. - unity: builtin — `HDRP Volume > Add Override > Sky > Physically Based Sky (PhysicallyBasedSkyCommon.hlsl evaluates Rayleigh air and Mie aerosol scattering)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl, checked 2026-12-01) — HDRP only. - unreal: builtin — `Sky Atmosphere component > Rayleigh Scattering / Mie Scattering settings` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sky-atmosphere-component-properties-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: material-params - Outputs: radiance, hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Rayleigh/Mie sky, low sun, 16x6 samples (glsl-fragment; rendered 2026-11-29) ```json { "R_PLANET": 6371000, "R_ATMO": 6471000, "H_R": 8000, "H_M": 1200, "G": 0.76, "N_VIEW": 16, "N_LIGHT": 6 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Single-scattering Rayleigh + Mie sky from the ground. const float R_PLANET = 6371e3; const float R_ATMO = 6471e3; const vec3 BETA_R = vec3(5.8e-6, 13.5e-6, 33.1e-6); const float BETA_M = 21e-6; const float H_R = 8e3; const float H_M = 1.2e3; const float G = 0.76; const float SUN_POWER = 22.0; const int N_VIEW = 16; const int N_LIGHT = 6; vec2 raySphere(vec3 o, vec3 d, float r) { float b = dot(o, d); float h = b * b - (dot(o, o) - r * r); if (h < 0.0) return vec2(1e9, -1e9); h = sqrt(h); return vec2(-b - h, -b + h); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, R_PLANET + 2.0, 0.0); vec3 rd = normalize(vec3(uv.x, uv.y + 0.18, -1.0)); float a = 0.10 + 0.06 * sin(iTime * 0.4); vec3 sun = normalize(vec3(0.25, sin(a), -cos(a))); float tmax = raySphere(ro, rd, R_ATMO).y; vec2 pl = raySphere(ro, rd, R_PLANET); if (pl.x > 0.0) tmax = min(tmax, pl.x); float mu = dot(rd, sun); float phaseR = 3.0 / (16.0 * 3.14159265) * (1.0 + mu * mu); float g2 = G * G; float phaseM = 3.0 / (8.0 * 3.14159265) * ((1.0 - g2) * (1.0 + mu * mu)) / ((2.0 + g2) * pow(1.0 + g2 - 2.0 * G * mu, 1.5)); float ds = tmax / float(N_VIEW); float odR = 0.0, odM = 0.0; vec3 sumR = vec3(0.0), sumM = vec3(0.0); for (int i = 0; i < N_VIEW; i++) { vec3 p = ro + rd * (ds * (float(i) + 0.5)); float h = length(p) - R_PLANET; float dR = exp(-h / H_R) * ds; float dM = exp(-h / H_M) * ds; odR += dR; odM += dM; float tl = raySphere(p, sun, R_ATMO).y; float dl = tl / float(N_LIGHT); float lR = 0.0, lM = 0.0; for (int j = 0; j < N_LIGHT; j++) { vec3 q = p + sun * (dl * (float(j) + 0.5)); float hq = length(q) - R_PLANET; lR += exp(-hq / H_R) * dl; lM += exp(-hq / H_M) * dl; } vec3 tau = BETA_R * (odR + lR) + vec3(BETA_M * 1.1) * (odM + lM); vec3 att = exp(-tau); sumR += att * dR; sumM += att * dM; } vec3 col = SUN_POWER * (sumR * BETA_R * phaseR + sumM * BETA_M * phaseM); if (pl.x > 0.0) col += vec3(0.02, 0.025, 0.02); col = 1.0 - exp(-col * 0.7); col = pow(col, vec3(1.0 / 2.2)); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; scattering coefficients are the commonly quoted Earth values used in Rayleigh/Mie tutorials ## Lineage - extends [Henyey-Greenstein Phase Function](https://texelatlas.vercel.app/t/henyey-greenstein-phase-function.md) - extends [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) - extended by [Precomputed Atmospheric Scattering](https://texelatlas.vercel.app/t/precomputed-atmospheric-scattering.md) ## Combines with - [Henyey-Greenstein Phase Function](https://texelatlas.vercel.app/t/henyey-greenstein-phase-function.md): Supplies the anisotropic Mie phase term evaluated at the view-sun angle. - [Screen-space Volumetric Light Scattering (God Rays)](https://texelatlas.vercel.app/t/volumetric-light-scattering-god-rays.md): Sky color gives the sun color and intensity used by the screen-space ray accumulation. ## Sources 1. [primary] Tomoyuki Nishita, Takao Sirai, Katsumi Tadamura, Eihachiro Nakamae (1993) Display of the earth taking into account atmospheric scattering. Proceedings of the 20th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/166117.166140 (verified via crossref on 2026-11-29) 2. [implementation] wwwtyro (2016) wwwtyro/glsl-atmosphere. https://github.com/wwwtyro/glsl-atmosphere License: Unlicense. (verified via github on 2026-11-29) 3. [tutorial] Scratchapixel Simulating the Colors of the Sky. scratchapixel.com. https://www.scratchapixel.com/lessons/procedural-generation-virtual-worlds/simulating-sky/simulating-colors-of-the-sky.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Ray-marched Rayleigh/Mie Single Scattering." https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering/ (accessed 2026-12-01). --- id: "reaction-diffusion-textures" title: "Reaction-Diffusion Textures (Turk)" aliases: [Gray-Scott, Turing patterns, reaction-diffusion] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [webgl2, webgpu, desktop-gpu, cpu, python, houdini, blender] year_introduced: 1991 inputs: [mesh, texture] outputs: [texture, uv-atlas] style: "both" dynamic: "dynamic" cost: "medium" authority: "Turk, 1991" url: "https://texelatlas.vercel.app/t/reaction-diffusion-textures/" sources_verified_at: "2026-11-29" --- # Reaction-Diffusion Textures (Turk) (Turk, 1991) > Simulate two interacting chemicals that diffuse at different rates to produce spots, stripes, labyrinths and other organic patterns, either in texture space or directly over a mesh surface. ## Reach for it when - want organic bump or colour maps like animal skin - need coral, spots and labyrinth textures on a mesh - emergent growth patterns rather than noise - pattern should flow across a surface without uv seams ## How it works Two scalar fields A and B evolve by dA/dt = Da*laplacian(A) - A*B^2 + f(1-A) and dB/dt = Db*laplacian(B) + A*B^2 - (k+f)B (Gray-Scott), where diffusion rates differ and feed f and kill k select the pattern regime: spots, worms, mazes, solitons. Turk's contribution is running the simulation on arbitrary surfaces: generate a uniform point mesh over the surface, compute Laplacians in that mesh, and render the chemical concentration as a texture, so patterns follow the geometry without UV distortion. Alternatively, the simulation runs on a 2D grid in texture space, as ping-pong render targets in a fragment shader. Anisotropic diffusion or spatially varying f and k create stripes oriented along a direction field or patterns that change across a surface. ## When to use it Choose it for animal-coat patterns, corals, organic bump or colour maps and growth effects that should feel emergent. Prefer [Domain Warping](https://texelatlas.vercel.app/t/domain-warping.md) for cheaper swirled textures without simulation, [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) family for stateless patterns, and [Wang Tiles (Aperiodic Tile Synthesis)](https://texelatlas.vercel.app/t/wang-tiles.md) when you need tileable texture synthesis from a source. ## Cost medium — A few texture passes per simulation step; thousands of steps required for patterns to emerge, so interactive on GPU but seeded offline for bakes. Measured GPU Weight: 1.92× baseline (feather) — 0.0631 ms median / 0.065 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.42× baseline (feather) — 0.0226 ms median (2.79× faster on L4). Ampere A100 scaling: 1.08× baseline (feather) — 0.0312 ms median (2.02× faster on A100). ## Failure modes - Pattern depends on seed and parameters in a narrow regime: slightly off f,k values die out to a flat field or blow up - Texture-space simulation shows distortion and seams on UV-mapped meshes - Time step too large makes explicit Euler integration unstable (checkerboard or NaNs) - Result is not tileable unless the grid wraps - Mesh-based versions need uniformly sampled vertices; irregular meshes produce directional artifacts ## Dataflow - Inputs: mesh, texture - Outputs: texture, uv-atlas - Platforms: webgl2, webgpu, desktop-gpu, cpu, python, houdini, blender ## Presets ### Toy Turing-pattern look (plane-wave approximation, not a simulation) (glsl-fragment; rendered 2026-11-29) ```json { "WAVES": 6, "WAVELENGTH": 0.07, "BLEND": 0.6 } ``` ```glsl // Toy: Turing-style spots/stripes/labyrinth via superposed plane waves at one wavelength (the linear-regime look of reaction-diffusion), not a simulation. const int WAVES = 6; const float WAVELENGTH = 0.07; const float BLEND = 0.6; // 0 = spots-like, 1 = labyrinth-like threshold shift float h(float n) { return fract(sin(n * 91.345) * 43758.5453); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 p = uv + 0.03 * vec2(sin(uv.y * 9.0 + iTime * 0.2), cos(uv.x * 8.0)); float s = 0.0; for (int i = 0; i < WAVES; i++) { float a = 3.14159 * (float(i) + 0.3 * h(float(i))) / float(WAVES); vec2 k = vec2(cos(a), sin(a)) * 6.2831 / WAVELENGTH; s += cos(dot(k, p) + 6.2831 * h(float(i) + 3.0)); } s /= float(WAVES) * 0.5; // regime sweep: top of the image has spots (offset threshold), bottom has stripes/labyrinth float thr = mix(0.9, 0.0, smoothstep(0.1, 0.9, uv.y) * BLEND + (1.0 - BLEND) * 0.0 + 0.4 * smoothstep(0.1, 0.9, uv.y)); float u = smoothstep(thr - 0.12, thr + 0.12, s); vec3 col = mix(vec3(0.95, 0.9, 0.75), vec3(0.12, 0.1, 0.3), u); col = mix(col, vec3(0.8, 0.3, 0.2), smoothstep(0.15, 0.0, abs(s - thr)) * 0.5); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Greg Turk (1991) Generating textures on arbitrary surfaces using reaction-diffusion. Proceedings of the 18th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/122718.122749 (verified via crossref on 2026-11-29) 2. [tutorial] Karl Sims Reaction-Diffusion Tutorial. karlsims.com. https://www.karlsims.com/rd.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Reaction-Diffusion Textures (Turk)." https://texelatlas.vercel.app/t/reaction-diffusion-textures/ (accessed 2026-12-01). --- id: "real-time-glints" title: "Real-time glints (distributed binomial laws)" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgpu, desktop-gpu, unreal, unity] year_introduced: 2023 inputs: [material-params, normals, uv-atlas] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "medium" authority: "Deliot & Belcour, 2023" url: "https://texelatlas.vercel.app/t/real-time-glints/" sources_verified_at: "2026-11-29" --- # Real-time glints (distributed binomial laws) (Deliot & Belcour, 2023) > Renders sparkly surfaces such as glitter, metallic flakes and snow in real time by statistically evaluating how many discrete microfacets in a pixel footprint reflect toward the viewer. Deliot and Belcour use binomial laws over an anisotropic grid. ## Reach for it when - car paint flakes should sparkle - glitter, snow and sand look dull and smooth - metallic flakes need to glint while moving - sequins and pearlescent surfaces lack sparkle - discrete micro-reflections inside a pixel ## How it works Smooth GGX hides the fact that bright sparkle comes from individual facets. Instead of storing a million microfacet normals, the method divides texture space into cells over an anisotropic grid in (position, slope) space aligned with the pixel footprint. In each cell the number of facets that point inside the half-vector footprint follows a binomial distribution whose parameters come from the surface's normal distribution. A hash gives a stable pseudo-random count per cell, so sparkles stay fixed to the surface and animate with the view. Tests across overlapping cells are combined with a closed-form cost independent of footprint size, avoiding per-facet loops. The glint lobe is added to or replaces the smooth specular lobe. ## When to use it Choose it for car paint with metallic flakes, glitter, sand, snow, sequins and pearlescent surfaces where a smooth GGX looks lifeless. Prefer plain [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) with a normal map for gentle roughness. Prefer [Anisotropic GGX](https://texelatlas.vercel.app/t/anisotropic-ggx.md) for brushed surfaces without discrete sparkle. ## Cost medium — Several hashed grid lookups plus binomial evaluations per pixel; heavier than GGX but real-time. Measured GPU Weight: 21.45× baseline (heavy) — 0.7057 ms median / 0.7252 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.64× baseline (moderate) — 0.2964 ms median (2.38× faster on L4). Ampere A100 scaling: 13.83× baseline (moderate) — 0.3983 ms median (1.77× faster on A100). ## Failure modes - Temporal flicker when facets enter and exit the footprint under motion unless accumulated carefully - Hash correlations show as visible grid patterns at extreme minification - Facet density parameter has no direct mapping from measured flake data - Increased cost on mobile GPUs; fewer samples cause noisier sparkles ## Engine support - unreal: builtin — `Substrate Slab > Glint Density / Glint UVs; requires r.Substrate.Glints=1` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-substrate-materials-in-unreal-engine, checked 2026-12-01) — Substrate materials only; off unless console variable is set. ## Dataflow - Inputs: material-params, normals, uv-atlas - Outputs: radiance - Platforms: webgpu, desktop-gpu, unreal, unity ## Presets ### Stochastic microfacet glints — discrete metallic flake sparkles over smooth clearcoat (glsl-fragment; rendered 2026-11-30) ```json { "FLAKE_DENSITY": 52, "ROUGHNESS": 0.24, "GLINT_INTENSITY": 3.2, "MICRO_ROUGH": 0.045 } ``` ```glsl const float FLAKE_DENSITY = 52.0; // P const float ROUGHNESS = 0.24; // P const float GLINT_INTENSITY = 3.2; // P const float MICRO_ROUGH = 0.045; // P vec3 hash32(vec2 p) { vec3 q = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); q += dot(q, q.yxz + 33.33); return fract((q.xxy + q.yzz) * q.zyx); } float D_GGX(float nh, float a) { float a2 = a * a; float d = nh * nh * (a2 - 1.0) + 1.0; return a2 / (3.14159265 * d * d + 1e-5); } // Multi-cell hashed discrete microfacet glint evaluator in tangent slope space vec3 evalGlints(vec2 uv, vec3 hTan, float density, float macroRough, float microRough) { float dScale = max(density, 4.0); vec2 gUv = uv * dScale; vec2 cell = floor(gUv); vec2 frac = fract(gUv); vec2 targetSlope = hTan.xy / max(hTan.z, 0.15); float mSig = max(microRough, 0.012); float macSig = max(macroRough, 0.08); vec3 glint = vec3(0.0); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 cid = cell + vec2(float(i), float(j)); vec3 rnd = hash32(cid); vec3 rnd2 = hash32(cid + vec2(37.2, 91.7)); vec2 center = vec2(float(i), float(j)) + 0.18 + 0.64 * rnd.xy; float dist2 = dot(frac - center, frac - center); float spatial = exp(-dist2 * 14.0); // Discrete flake normal drawn from macro Gaussian slope distribution float rAng = rnd.z * 6.2831853; float rMag = sqrt(-2.0 * log(max(rnd2.x, 1e-4))) * macSig * 0.52; vec2 flakeSlope = vec2(cos(rAng), sin(rAng)) * rMag; vec2 ds = targetSlope - flakeSlope; float angular = exp(-dot(ds, ds) / (2.0 * mSig * mSig)); // Subtle prismatic car-paint / metallic flake iridescence vec3 tint = mix(vec3(0.92, 0.96, 1.0), 0.55 + 0.45 * cos(6.28318 * (rnd2.y + vec3(0.0, 0.18, 0.42))), 0.55); glint += tint * spatial * angular * (0.7 + 0.6 * rnd2.z); } } return glint; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.12, 2.55); vec3 rd = normalize(vec3(uv, -1.55)); vec3 bg = mix(vec3(0.02, 0.025, 0.04), vec3(0.07, 0.09, 0.14), clamp(uv.y + 0.5, 0.0, 1.0)); // Ray-sphere studio specimen float rad = 0.84; float b = dot(ro, rd), c = dot(ro, ro) - rad * rad, h = b * b - c; if (h < 0.0) { fragColor = vec4(pow(clamp(aces(bg), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); return; } float t = -b - sqrt(h); vec3 p = ro + rd * t; vec3 n = normalize(p); vec3 v = -rd; // Rotate sphere surface coordinates slowly (or via mouse) float rot = iTime * 0.28; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { rot = (iMouse.x / iResolution.x - 0.5) * 3.14159; } float cr = cos(rot), sr = sin(rot); vec3 pr = vec3(cr * n.x - sr * n.z, n.y, sr * n.x + cr * n.z); // Cubemap-like triplanar UV avoids pole pinching vec2 surfUv = vec2(atan(pr.z, pr.x) * 0.31831, asin(clamp(pr.y, -0.999, 0.999)) * 0.63662); vec3 up = abs(n.y) < 0.95 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); vec3 T = normalize(cross(up, n)); vec3 B = cross(n, T); mat3 worldToTan = transpose(mat3(T, B, n)); vec3 l1 = normalize(vec3(0.65 * cos(iTime * 0.4) + 0.2, 0.68, 0.65)); vec3 l2 = normalize(vec3(-0.75, 0.42, 0.55)); vec3 baseCol = vec3(0.08, 0.22, 0.54); float rough = clamp(ROUGHNESS, 0.06, 0.95); float ndv = max(dot(n, v), 0.001); float fres = 0.04 + 0.96 * pow(1.0 - ndv, 5.0); vec3 col = baseCol * (0.08 + 0.12 * (n.y * 0.5 + 0.5)); // Key light + fill light: smooth GGX + clearcoat + stochastic microfacet glints for (int k = 0; k < 2; k++) { vec3 L = (k == 0) ? l1 : l2; vec3 lCol = (k == 0) ? vec3(1.85, 1.72, 1.55) : vec3(0.65, 0.85, 1.25); float nl = max(dot(n, L), 0.0); vec3 H = normalize(L + v); float nh = max(dot(n, H), 0.0); float specSmooth = D_GGX(nh, rough * rough) * 0.22; float coat = D_GGX(nh, 0.045) * fres * 0.45; vec3 hTan = worldToTan * H; vec3 glints = evalGlints(surfUv, hTan, FLAKE_DENSITY, rough, MICRO_ROUGH) * max(GLINT_INTENSITY, 0.0); col += lCol * nl * (baseCol * 0.65 + vec3(0.55, 0.72, 1.0) * specSmooth + coat + glints); } // Subtle studio rim environment reflection vec3 R = reflect(-v, n); vec3 env = mix(vec3(0.05, 0.08, 0.14), vec3(0.55, 0.68, 0.92), smoothstep(-0.2, 0.8, R.y)); col += env * fres * 0.65; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Combination ideas - [Sun glitter from horizon to bow](https://texelatlas.vercel.app/ideas/sun-glitter-ocean/) ## Sources 1. [primary] T. Deliot, L. Belcour (2023) Real‐Time Rendering of Glinty Appearances using Distributed Binomial Laws on Anisotropic Grids. Computer Graphics Forum. https://doi.org/10.1111/cgf.14866 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Real-time glints (distributed binomial laws)." https://texelatlas.vercel.app/t/real-time-glints/ (accessed 2026-12-01). --- id: "recursive-oblique-portal-rendering" title: "Recursive Non-Euclidean Portal Rendering with Oblique Near-Plane Clipping" aliases: [recursive portal rendering, non-Euclidean portals, oblique-clipped portals, stencil portal rendering] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2005 inputs: [mesh, depth, camera-poses] outputs: [visibility-mask, radiance, texture] style: "both" dynamic: "dynamic" cost: "heavy" authority: "Lengyel, 2005" url: "https://texelatlas.vercel.app/t/recursive-oblique-portal-rendering/" sources_verified_at: "2026-11-30" --- # Recursive Non-Euclidean Portal Rendering with Oblique Near-Plane Clipping (Lengyel, 2005) > Renders seamless non-Euclidean portals by transforming a virtual camera into the linked twin portal's frame, rewriting the projection matrix with an oblique near plane aligned to the exit face, and recursing via render targets or stencil masking. ## Reach for it when - render seamless non-euclidean doorways and infinite hall mirrors - geometry behind a portal plane pokes through the virtual camera - need nested portal views without stencil buffer depth glitches - clip near plane cleanly to an arbitrary angled portal quad - mirrors or portals show objects situated between eye and frame ## How it works A non-Euclidean portal connects two arbitrarily placed and oriented apertures `A` and `B` in space so looking into `A` reveals the scene as seen from `B`. To compute the virtual camera pose, the viewer's world transform is mapped into portal `A`'s local frame, rotated 180 degrees around the portal's up axis to face outward, and placed into portal `B`'s world frame. A naive virtual camera renders geometry sitting *behind* portal `B` (between the virtual camera and the exit plane), which wrongly occludes the view through the opening. Using **Lengyel's oblique near-plane clipping** (2005), the exit portal plane is transformed into the virtual camera's view space and used to replace the third row of the perspective projection matrix, scaling it so the far plane still encloses the view frustum. Hardware clip-space culling then discards every fragment behind the exit portal with zero extra fragment shader cost. To render **portals seen through portals**, the renderer recurses up to a bounded depth—either nesting stencil-buffer masks and clearing depth inside each portal silhouette, or rendering nested off-screen portal textures bottom-up from deepest bounce to shallowest—while culling portals that are back-facing or outside the parent portal's screen-space bounds. ## When to use it Choose it for non-Euclidean spatial puzzles, impossible architecture, seamless teleporters, and linked wormhole apertures where players can inspect and walk directly through arbitrary wall-to-wall connections. Prefer [planar-reflections-oblique-clipping](planar-reflections-oblique-clipping) when reflecting a single flat mirror or water surface rather than teleporting the camera to a distinct exit frame. Prefer [portal-pvs-culling](portal-pvs-culling) when portals only act as Euclidean room-to-room visibility boundaries for frustum culling rather than spatial warps. ## Cost heavy — Each visible portal and recursion level adds a full scene pass; screen-space bounding-rect scissor tests, frustum narrowing, and recursion depth caps (typically 2–6) keep frame times bounded. Measured GPU Weight: 3.6× baseline (light) — 0.1186 ms median / 0.1191 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.08× baseline (light) — 0.0489 ms median (2.43× faster on L4). Ampere A100 scaling: 2.35× baseline (light) — 0.0676 ms median (1.75× faster on A100). ## Failure modes - Severe oblique angles tilt the far clipping plane toward the viewer and compress depth buffer precision, causing distant z-fighting unless paired with reverse-Z depth buffers - Crossing a portal plane causes near-plane clipping gaps if the portal surface is paper-thin instead of extruded into a shallow box or switched smoothly on camera traversal - Mutually facing portals trigger exponential pass counts without strict recursion depth limits and screen-space occlusion culling - Screen-space post-processing effects (SSAO, SSR, bloom) fail to cross portal boundaries seamlessly when portals are composited from separate render targets ## Dataflow - Inputs: mesh, depth, camera-poses - Outputs: visibility-mask, radiance, texture - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Recursive Oblique Portal Rendering — unclipped near-plane leak (left) vs oblique-clipped recursive non-Euclidean portal tunnel (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RECURSION": 5, "P_TWIST": 0.35, "P_ORBIT": 0.45, "P_SPLIT": 0.46 } ``` ```glsl const float P_RECURSION = 5.00; // P Portal Bounces [1.0, 7.0, 1.0] const float P_TWIST = 0.35; // P Exit Frame Twist [0.0, 0.9, 0.05] const float P_ORBIT = 0.45; // P Camera Motion [0.0, 1.5, 0.05] const float P_SPLIT = 0.46; // P No Oblique / Clipped [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useOblique = screenX >= split; int maxBounces = int(clamp(floor(P_RECURSION + 0.5), 1.0, 7.0)); float twist = clamp(P_TWIST, 0.0, 1.0); float t = iTime * max(P_ORBIT, 0.0); // Camera inside sunlit non-Euclidean gallery looking directly into Portal A (z = -0.85) vec3 ro = vec3(0.28 * sin(t * 0.65), 0.06 + 0.08 * cos(t * 0.8), 1.35); vec3 rd = normalize(vec3(uv.x - 0.14 * sin(t * 0.65), uv.y - 0.02, -1.35)); vec3 col = vec3(0.0); float atten = 1.0; // Trace ray with up to maxBounces non-Euclidean portal teleports! for (int bounce = 0; bounce < 8; bounce++) { if (bounce > maxBounces) break; float tBest = 1e5; int hitKind = 0; // 1=room, 2=portal aperture, 3=portal rim, 4=occluding pillar behind exit portal! vec3 hitP = vec3(0.0); vec3 hitN = vec3(0.0, 0.0, 1.0); // Gallery chamber planes: x in [-1.2, 1.2], y in [-0.75, 0.75], z in [-0.85, 1.65] vec3 bMin = vec3(-1.20, -0.75, -0.85); vec3 bMax = vec3(1.20, 0.75, 1.65); vec3 invR = 1.0 / (rd + vec3(1e-6)); vec3 tA = (bMin - ro) * invR; vec3 tB = (bMax - ro) * invR; vec3 tFarV = max(tA, tB); float tRoom = min(min(tFarV.x, tFarV.y), tFarV.z); if (tRoom > 0.005) { tBest = tRoom; hitP = ro + rd * tRoom; hitKind = 1; if (abs(tRoom - tFarV.x) < 1e-4) hitN = vec3(-sign(rd.x), 0.0, 0.0); else if (abs(tRoom - tFarV.y) < 1e-4) hitN = vec3(0.0, -sign(rd.y), 0.0); else hitN = vec3(0.0, 0.0, -sign(rd.z)); // Check if hit on back wall (z = -0.85) falls inside Portal A frame if (abs(hitP.z + 0.85) < 0.01) { vec2 q = abs(hitP.xy) - vec2(0.46, 0.44); float dFrame = max(q.x, q.y); if (dFrame < 0.0) { hitKind = 2; // Inside Portal A aperture! } else if (dFrame < 0.055) { hitKind = 3; // Glowing portal frame rim } } } // Hero floating brass sphere inside gallery vec3 sc = vec3(0.62, -0.22, 0.10); vec3 oc = ro - sc; float bs = dot(oc, rd), ds = bs * bs - (dot(oc, oc) - 0.22 * 0.22); if (ds > 0.0) { float ts = -bs - sqrt(ds); if (ts > 0.01 && ts < tBest) { tBest = ts; hitKind = 5; hitP = ro + rd * ts; hitN = normalize(hitP - sc); } } // On LEFT side (bounce >= 1), simulate missing oblique near-plane clipping: // An intrusive red blocker pillar sitting BEHIND the exit portal leaks into the virtual camera! if (!useOblique && bounce >= 1) { vec3 pc = vec3(-0.12, 0.0, 1.05); vec3 pr = vec3(0.16, 0.72, 0.14); vec3 p0 = (pc - pr - ro) * invR; vec3 p1 = (pc + pr - ro) * invR; vec3 pn = min(p0, p1), pf = max(p0, p1); float tn = max(max(pn.x, pn.y), pn.z); float tf = min(min(pf.x, pf.y), pf.z); if (tf > max(tn, 0.01) && tn < tBest) { tBest = tn; hitKind = 4; hitP = ro + rd * tn; hitN = vec3(0.0, 0.0, 1.0); } } if (hitKind == 2 && bounce < maxBounces) { // Teleport ray from Portal A (z = -0.85) to Portal B (z = 1.48) with slight twist & scale! // With oblique near-plane clipping enabled, ray starts strictly AT the exit plane (z = 1.46). // Without oblique clipping (left), virtual camera starts behind exit plane (z = 1.62) and clips wrong geometry! vec2 exitXY = rot2(hitP.xy, twist * 0.38) * 0.96; ro = vec3(exitXY.x, exitXY.y, useOblique ? 1.44 : 1.62); rd.xy = rot2(rd.xy, twist * 0.38); atten *= 0.88; continue; } // Shade terminal hit vec3 lDir = normalize(vec3(0.35, 0.82, 0.45)); float ndl = max(dot(hitN, lDir), 0.0); vec3 hitCol = vec3(0.05); if (hitKind == 1) { vec2 tileUv = (abs(hitN.y) > 0.5) ? hitP.xz : ((abs(hitN.x) > 0.5) ? hitP.zy : hitP.xy); float chk = mod(floor(tileUv.x * 3.0) + floor(tileUv.y * 3.0), 2.0); vec3 wallBase = (hitN.x > 0.5) ? vec3(0.84, 0.38, 0.26) : ((hitN.x < -0.5) ? vec3(0.22, 0.62, 0.78) : mix(vec3(0.54, 0.56, 0.60), vec3(0.80, 0.80, 0.78), chk)); float depthHue = float(bounce) * 0.14; wallBase = mix(wallBase, vec3(0.24, 0.78, 0.95), depthHue * 0.25); hitCol = wallBase * (0.28 + 0.85 * ndl); } else if (hitKind == 3) { // Alternating cyan/amber energy rim per recursion depth hitCol = (mod(float(bounce), 2.0) < 0.5) ? vec3(0.22, 1.45, 1.75) : vec3(1.75, 0.78, 0.20); } else if (hitKind == 4) { // Leaked unclipped near-plane occluder behind exit portal (crimson warning hazard stripes!) float stripe = step(0.5, fract((hitP.x + hitP.y) * 9.0)); hitCol = mix(vec3(0.95, 0.18, 0.24), vec3(0.24, 0.05, 0.08), stripe); } else if (hitKind == 5) { float spec = pow(max(dot(reflect(-lDir, hitN), -rd), 0.0), 32.0); hitCol = vec3(0.92, 0.74, 0.36) * (0.25 + 0.90 * ndl) + vec3(1.1) * spec; } else { hitCol = vec3(0.14, 0.26, 0.42); } col += hitCol * atten; break; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Reverse-Z and floating-point depth buffers](https://texelatlas.vercel.app/t/reverse-z-depth-buffer.md): Preserves distant depth precision when oblique near-plane matrices tilt the frustum's far plane. - [Portal and PVS visibility culling](https://texelatlas.vercel.app/t/portal-pvs-culling.md): Narrows each recursive portal camera's frustum to the screen-space bounds of the aperture to skip unseen geometry. ## Sources 1. [primary] Eric Lengyel (2005) Oblique View Frustum Depth Projection and Clipping. Journal of Game Development, 2005. http://www.terathon.com/lengyel/Lengyel-Oblique.pdf (verified via http on 2026-11-30) 2. [implementation] acher249 (2026) acher249/codevember-2026. https://github.com/acher249/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Recursive Non-Euclidean Portal Rendering with Oblique Near-Plane Clipping." https://texelatlas.vercel.app/t/recursive-oblique-portal-rendering/ (accessed 2026-12-01). --- id: "reflection-probes-parallax-corrected-cubemaps" title: "Reflection probes with parallax-corrected cubemaps" aliases: [box projected cubemaps, local cubemap reflections, box projection, reflection probes] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2012 inputs: [hdr-image, gbuffer] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Lagarde" url: "https://texelatlas.vercel.app/t/reflection-probes-parallax-corrected-cubemaps/" sources_verified_at: "2026-11-29" --- # Reflection probes with parallax-corrected cubemaps (Lagarde) > Local specular probes: a cubemap is captured at a point in a room and its lookup is corrected with a proxy box, so reflections shift with the viewer and sit where the real walls are instead of at infinity. ## Reach for it when - reflections on a floor slide when the camera moves - cubemap reflections look pasted on instead of in the room - need cheap local specular reflections for interiors - reflections of walls float at infinity on glossy floors ## How it works A reflection probe is a cubemap rendered or baked at a capture position, with a proxy volume (usually an axis-aligned or oriented box) that approximates the room around it. A plain cubemap lookup uses only the reflection direction, which behaves as if every wall were infinitely far away, so reflections slide with the camera and float on floors. The correction intersects the reflected ray, starting at the shaded point, with the proxy box and takes the exit point. The lookup direction becomes `exitPoint - probePosition`, so the cubemap is sampled where that ray would land seen from the capture position. Reflections then stay anchored to the walls, and the floor reflection of a window lands under the window. Probes carry an influence volume. Pixels blend between overlapping probes by distance or priority, the cubemap is prefiltered by roughness into its mip chain as in [split-sum-ibl](split-sum-ibl), and the result is multiplied by specular occlusion because the cubemap knows nothing about local blockers. Probes can be baked once or re-captured at a low rate for dynamic scenes. ## When to use it Choose it as the baseline local specular lighting in interiors and mixed scenes: it costs one box intersection and one cubemap fetch per pixel and works on WebGL2 and mobile. Prefer [environment-mapping-cubemaps](environment-mapping-cubemaps) for sky and distant HDRI backdrops where parallax does not matter. Prefer [screen-space-reflections](screen-space-reflections) for sharp reflections of on-screen dynamic objects, and fall back to this probe where SSR has no data. Prefer [hybrid-ray-traced-reflections](hybrid-ray-traced-reflections) when hardware ray tracing is available and probes are too coarse. Prefer [planar-reflections-oblique-clipping](planar-reflections-oblique-clipping) for a single flat mirror or water plane that needs exact reflections. ## Cost cheap — A ray-box intersection and a cubemap sample per pixel; capture and prefilter cost is paid at bake time or amortised over frames. Measured GPU Weight: 1.84× baseline (feather) — 0.0607 ms median / 0.0635 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.47× baseline (feather) — 0.0234 ms median (2.59× faster on L4). Ampere A100 scaling: 1.08× baseline (feather) — 0.0311 ms median (1.95× faster on A100). ## Failure modes - Proxy box mismatch: where real walls are not on the box, reflected edges bend or doubled corners appear - Objects between the surface and the proxy wall are baked at the probe position, so they reflect with the wrong parallax or appear smeared - Visible pops when blending between overlapping probes if influence volumes do not fade smoothly - Reflection of the probe's own capture position: surfaces near the capture point appear in their own reflections - Light leaks when a probe sees the outdoors through a window and its volume spills into the neighbouring room - Dynamic objects and lights are missing unless the probe is re-captured, which then costs a cubemap render and prefilter ## Engine support - babylonjs: builtin — `new ReflectionProbe(name, size, scene); cubeTexture.boundingBoxSize` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Textures/cubeTexture.pure.ts, checked 2026-12-01) - blender: builtin — `Add > Light Probe > Sphere; Object Data > Custom Parallax` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_probes/sphere.html, checked 2026-12-01) — EEVEE only. - godot: builtin — `ReflectionProbe.box_projection = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ReflectionProbe.xml, checked 2026-12-01) - unity: builtin — `Reflection Probe > Box Projection (ReflectionProbe.boxProjection)` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ReflectionProbe-boxProjection.html, checked 2026-12-01) - unreal: builtin — `Place a Box Reflection Capture actor` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/reflections-captures-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image, gbuffer - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Box-projected vs plain cubemap floor reflection (glsl-fragment; rendered 2026-11-29) ```json { "box_min": [ -4, -1, -4 ], "box_max": [ 4, 3, 4 ], "probe": [ 0, 1, 0 ] } ``` ```glsl // Parallax-corrected (box-projected) reflection probe: left half uncorrected, right half corrected. const vec3 BMIN = vec3(-4.0, -1.0, -4.0); // probe proxy volume (room) const vec3 BMAX = vec3( 4.0, 3.0, 4.0); const vec3 PROBE = vec3(0.0, 1.0, 0.0); // capture position of the cubemap // Stand-in for a baked cubemap: depends on direction only. vec3 cubemap(vec3 d) { vec3 a = abs(d); vec2 uv; vec3 col; if (a.x >= a.y && a.x >= a.z) { uv = d.yz / a.x; col = d.x > 0.0 ? vec3(0.9, 0.3, 0.25) : vec3(0.25, 0.5, 0.9); } else if (a.y >= a.z) { uv = d.xz / a.y; col = d.y > 0.0 ? vec3(0.9, 0.9, 0.85) : vec3(0.35); } else { uv = d.xy / a.z; col = d.z > 0.0 ? vec3(0.3, 0.8, 0.4) : vec3(0.9, 0.8, 0.3); } vec2 g = floor(uv * 3.0 + 3.0); float c = mod(g.x + g.y, 2.0); return col * (0.45 + 0.55 * c); } // Ray from p inside the box: exit point. vec3 boxExit(vec3 p, vec3 d) { vec3 t = max((BMAX - p) / d, (BMIN - p) / d); return p + d * min(t.x, min(t.y, t.z)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(sin(iTime * 0.5) * 1.0, 0.2, -3.2); vec3 rd = normalize(vec3(uv.x, uv.y - 0.3, 1.0)); vec3 col; if (rd.y < -0.001) { float t = (BMIN.y - ro.y) / rd.y; vec3 p = ro + rd * t; vec3 r = reflect(rd, vec3(0.0, 1.0, 0.0)); vec3 lookup = (uv.x < 0.0) ? r : boxExit(p, r) - PROBE; float fres = 0.04 + 0.96 * pow(1.0 - clamp(-rd.y, 0.0, 1.0), 5.0); col = vec3(0.04, 0.05, 0.06) + cubemap(lookup) * (0.35 + 0.65 * fres); } else { col = cubemap(boxExit(ro, rd) - PROBE); } col *= 1.0 - 0.9 * smoothstep(0.004, 0.0, abs(uv.x)); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Environment mapping, cubemaps and skyboxes](https://texelatlas.vercel.app/t/environment-mapping-cubemaps.md) ## Combines with - [Split-Sum Image-Based Lighting](https://texelatlas.vercel.app/t/split-sum-ibl.md): The probe cubemap is prefiltered by roughness into the mip chain that the split-sum lookup samples; the box projection only changes the lookup direction. - [Ground-Truth Specular Occlusion](https://texelatlas.vercel.app/t/ground-truth-specular-occlusion.md): Supplies the per-pixel occlusion factor that hides probe reflections inside crevices the cubemap cannot know about. - [Screen-space reflections](https://texelatlas.vercel.app/t/screen-space-reflections.md): SSR overrides the probe where the screen has a hit and the probe fills in misses and off-screen content. ## Sources 1. [primary] Sébastien Lagarde Image-based Lighting approaches and parallax-corrected cubemap. seblagarde.wordpress.com. https://seblagarde.wordpress.com/2012/09/29/image-based-lighting-approaches-and-parallax-corrected-cubemap (verified via http on 2026-11-29) 2. [talk] Sébastien Lagarde, Charles de Rousiers Moving Frostbite to Physically Based Rendering. SIGGRAPH 2014 course. https://seblagarde.wordpress.com/wp-content/uploads/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf (verified via http on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Reflection probes with parallax-corrected cubemaps." https://texelatlas.vercel.app/t/reflection-probes-parallax-corrected-cubemaps/ (accessed 2026-12-01). --- id: "reflective-shadow-maps" title: "Reflective Shadow Maps" aliases: [RSM] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu] year_introduced: 2005 inputs: [depth, normals, gbuffer] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Dachsbacher & Stamminger, 2005" url: "https://texelatlas.vercel.app/t/reflective-shadow-maps/" sources_verified_at: "2026-11-29" --- # Reflective Shadow Maps (Dachsbacher & Stamminger, 2005) > Extends a shadow map with per-texel world position, normal and reflected flux, treating each lit texel as a tiny light. One-bounce indirect light is gathered by sampling nearby texels around each shaded point. ## Reach for it when - first bounce indirect light for dynamic scenes - color bleeding from a spot or sun light - cheap gi using light's view of the scene - indirect illumination without baking or ray tracing ## How it works A shadow map already holds every surface point that a light directly illuminates. A reflective shadow map stores, for each texel of that map, the depth (or world position), the normal and the **reflected radiant flux** (albedo times incoming light). Each texel is therefore a small secondary source that emits diffusely. To compute indirect light at a shaded point, project it into the RSM and take a set of samples in a disc around the projection, with a larger sampling density near the centre. Each sample contributes `flux * max(0, n_pixel . (x_pixel - x_sample)) * max(0, n_sample . (x_sample - x_pixel)) / |dist|^4`. Because that gather is expensive, implementations run it at lower resolution and upsample with an edge-aware filter, or precompute a rotating sampling pattern per pixel. The method has no visibility test for the secondary light, so indirect shadows are missing, but it needs no pre-computation and works for animated lights and geometry. ## When to use it Choose it for a cheap one-bounce indirect term from a single shadow-casting light (a flashlight or sun) in an engine that already renders shadow maps. Prefer [light-propagation-volumes](light-propagation-volumes) when you want to inject the RSM into a grid and get multi-bounce, no per-pixel gather. Prefer [instant-radiosity](instant-radiosity) when you need indirect shadows. Prefer [ddgi](ddgi) or [lumen-gi](lumen-gi) for modern dynamic GI. ## Cost medium — Per-pixel cost is the number of RSM samples (tens to hundreds) at reduced resolution, plus shadow map generation. Measured GPU Weight: 40.68× baseline (heavy) — 1.2774 ms median / 1.3466 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 41.77× baseline (heavy) — 0.66 ms median (1.94× faster on L4). Ampere A100 scaling: 24.93× baseline (heavy) — 0.718 ms median (1.78× faster on A100). ## Failure modes - No occlusion for indirect light: light leaks through walls and floors between the RSM and the shaded point - Only one bounce, and only light that is visible to the light's shadow camera - Undersampling gives noise or flickering unless the pattern is rotated and filtered - Wide-angle spot or sun light needs large, high-resolution RSMs to cover the visible area ## Engine support - babylonjs: builtin — `BABYLON.GIRSM / GIRSMManager with ReflectiveShadowMap` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Rendering/reflectiveShadowMap.ts, checked 2026-12-01) — Experimental one-bounce GI. ## Dataflow - Inputs: depth, normals, gbuffer - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu ## Presets ### Reflective Shadow Maps — direct spotlight flux VPL taps & single-bounce indirect gather (glsl-fragment; rendered 2026-11-30) ```json { "P_RSM_GAIN": 1.4, "P_SPOT_SWEEP": 1, "P_VPL_DOTS": 1, "P_SPLIT": 0.38 } ``` ```glsl const float P_RSM_GAIN = 1.4; // P RSM Indirect Gain [0.0, 2.8, 0.05] const float P_SPOT_SWEEP = 1.0; // P Spot Motion [0.0, 2.5, 0.05] const float P_VPL_DOTS = 1.0; // P RSM VPL Taps [0.0, 1.5, 0.05] const float P_SPLIT = 0.38; // P Direct / RSM Split [0.0, 1.0, 0.02] 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); } // Gallery room with painted floor strips (crimson, gold, emerald) so moving spotlight spawns colored RSM bounce! vec2 mapScene(vec3 p) { vec2 res = vec2(1.0 + p.y, 1.0); // floor float cD = 1.0 - p.y; if (cD < res.x) res = vec2(cD, 2.0); float bD = 1.45 + p.z; if (bD < res.x) res = vec2(bD, 2.0); float lD = 1.45 + p.x; if (lD < res.x) res = vec2(lD, 2.0); float rD = 1.45 - p.x; if (rD < res.x) res = vec2(rD, 2.0); // Two matte white sculptural columns & floating orb to catch indirect RSM bounce light float dCol1 = sdBox(p - vec3(-0.72, -0.35, -0.55), vec3(0.22, 0.65, 0.22)) - 0.02; if (dCol1 < res.x) res = vec2(dCol1, 3.0); float dCol2 = sdBox(p - vec3(0.72, -0.35, -0.55), vec3(0.22, 0.65, 0.22)) - 0.02; if (dCol2 < res.x) res = vec2(dCol2, 3.0); float dOrb = length(p - vec3(0.0, 0.12, -0.45)) - 0.34; if (dOrb < res.x) res = vec2(dOrb, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Vivid painted floor mosaic so the RSM bounce color changes dramatically as the spotlight sweeps across it vec3 floorMosaic(vec2 xz) { if (xz.x < -0.38) return vec3(0.92, 0.18, 0.16); if (xz.x > 0.38) return vec3(0.12, 0.72, 0.94); return vec3(0.96, 0.68, 0.14); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float rsmGain = max(P_RSM_GAIN, 0.0); float tAnim = iTime * max(P_SPOT_SWEEP, 0.0); float vplVis = clamp(P_VPL_DOTS, 0.0, 1.6); vec3 ro = vec3(0.0, 0.12, 2.38); vec3 rd = normalize(vec3(uv, -1.48)); // Sweeping overhead spotlight hitting the painted floor mosaic vec3 spotOrig = vec3(0.0, 0.94, 0.30); vec3 spotTarget = vec3(0.82 * sin(tAnim * 0.62), -1.0, -0.22 + 0.32 * cos(tAnim * 0.48)); vec3 spotAxis = normalize(spotTarget - spotOrig); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = vec3(0.76, 0.77, 0.78); if (matId < 1.5) alb = floorMosaic(p.xz); else if (matId > 2.5) alb = vec3(0.86, 0.86, 0.84); // Direct spotlight illumination with shadow ray vec3 toL = spotOrig - p; float dL = length(toL); vec3 lDir = toL / max(dL, 1e-4); float spotCone = smoothstep(0.86, 0.96, dot(-lDir, spotAxis)); float sh = 1.0; float ts = 0.03; for (int i = 0; i < 24; i++) { float dh = mapScene(p + lDir * ts).x; if (dh < 0.004) { sh = 0.0; break; } ts += dh; if (ts > dL - 0.08) break; } vec3 direct = alb * vec3(3.2, 2.95, 2.6) * max(dot(n, lDir), 0.0) * spotCone * sh / (1.0 + 0.22 * dL * dL); // Reflective Shadow Map (RSM) Gather: 12 importance-sampled pixel light VPLs inside the spotlight patch! vec3 rsmIndirect = vec3(0.0); float vplDotGlow = 0.0; vec3 vplDotCol = vec3(0.0); for (int k = 0; k < 12; k++) { float fk = float(k); // Golden-angle concentric disk sampling of the RSM texel footprint float rDisk = sqrt((fk + 0.5) / 12.0) * 0.42; float ang = fk * 2.399963 + 0.3; vec3 vplPos = vec3( clamp(spotTarget.x + cos(ang) * rDisk, -1.38, 1.38), -0.995, clamp(spotTarget.z + sin(ang) * rDisk, -1.38, 0.85) ); vec3 vplN = vec3(0.0, 1.0, 0.0); vec3 vplFlux = floorMosaic(vplPos.xz) * (1.0 - rDisk * 1.4); vec3 toVpl = vplPos - p; float dist2 = dot(toVpl, toVpl); float dist = sqrt(max(dist2, 1e-5)); vec3 dirV = toVpl / dist; // RSM form factor: max(0, dot(n_p, dir)) * max(0, dot(n_vpl, -dir)) / (d^2 + clamp)^2 float cosP = max(dot(n, dirV), 0.0); float cosV = max(dot(vplN, -dirV), 0.0); float geom = (cosP * cosV) / pow(max(dist2 + 0.16, 0.16), 1.35); rsmIndirect += vplFlux * geom; // Visible VPL sample indicator dot on the lit floor patch if (matId < 1.5 && vplVis > 0.01) { float dotM = smoothstep(0.042, 0.016, length(p.xz - vplPos.xz)); vplDotGlow = max(vplDotGlow, dotM); if (dotM > 0.05) vplDotCol = vplFlux * 1.8 + vec3(0.4); } } rsmIndirect = alb * (rsmIndirect / 12.0) * 4.8 * rsmGain; vec3 leftCol = direct + alb * vec3(0.025, 0.03, 0.04); vec3 rightCol = direct + rsmIndirect + alb * vec3(0.025, 0.03, 0.04); rightCol = mix(rightCol, vplDotCol, vplDotGlow * 0.85 * min(vplVis, 1.2)); col = (screenX < split) ? leftCol : rightCol; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Light Propagation Volumes](https://texelatlas.vercel.app/t/light-propagation-volumes.md): The RSM's flux, normals and positions are injected as virtual point lights into the volume. ## Sources 1. [primary] Carsten Dachsbacher, Marc Stamminger (2005) Reflective shadow maps. Proceedings of the 2005 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1053427.1053460 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Reflective Shadow Maps." https://texelatlas.vercel.app/t/reflective-shadow-maps/ (accessed 2026-12-01). --- id: "reinhard-tonemapping" title: "Reinhard photographic tone reproduction" aliases: [Reinhard operator] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, blender] year_introduced: 2002 inputs: [hdr-image] outputs: [ldr-image] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Reinhard et al., 2002" url: "https://texelatlas.vercel.app/t/reinhard-tonemapping/" sources_verified_at: "2026-11-29" --- # Reinhard photographic tone reproduction (Reinhard et al., 2002) > The classic global operator x/(1+x), scaled by the scene's log-average luminance to a chosen key value, plus an extended form with a white point; simple, monotonic and well behaved. ## Reach for it when - hdr values need squeezing to displayable range simply - want an invertible predictable tone curve - need debug view of hdr with no contrast boost - taa resolve needs well-behaved luminance weighting ## How it works Reinhard et al. borrow the zone system from photography. First, the log-average (geometric mean) luminance of the image is computed and the image is scaled so that this average maps to a key value, like 0.18 for a mid-tone scene. The global curve L/(1+L) then compresses the range into [0,1). The extended version divides by a white point, L(1+L/Lw^2)/(1+L), so values at Lw map to exactly 1. The paper also describes a local dodge-and-burn variant using multi-scale blurred luminance, though the global form is the one used in real-time. Applied per channel the curve desaturates highlights; applied to luminance only, hues are preserved but colours can go out of gamut. ## When to use it Choose it when you want a simple, invertible, predictable curve, for example as a debug view or for TAA's luminance-weighted resolve. Prefer [Hable filmic (Uncharted 2) tonemapping](https://texelatlas.vercel.app/t/hable-filmic-tonemapping.md) for more contrast and a toe, [ACES filmic tonemapping](https://texelatlas.vercel.app/t/aces-tonemapping.md) for film response, and [Khronos PBR Neutral tone mapper](https://texelatlas.vercel.app/t/khronos-pbr-neutral.md) for colour accuracy. Combine with [Auto exposure from luminance histogram](https://texelatlas.vercel.app/t/auto-exposure-histogram.md) to supply the key. ## Cost cheap — Per-pixel arithmetic only. Measured GPU Weight: 1.16× baseline (feather) — 0.0383 ms median / 0.0399 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.01× baseline (feather) — 0.016 ms median (2.39× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.33× faster on A100). ## Failure modes - Low-contrast, washed-out blacks because it lacks a toe - Per-channel application desaturates and shifts hue in bright colours - Highlights compress hard unless a white point is set - Luminance-only variant can push saturated colours out of gamut ## Engine support - babylonjs: builtin — `new BABYLON.TonemapPostProcess('t', BABYLON.TonemappingOperator.Reinhard, exposure, camera)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/thinTonemapPostProcess.ts, checked 2026-12-01) - blender: builtin — `Compositor > Add > Color > Adjust > Tone Map, Type = Rh Simple` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/color/adjust/tone_map.html, checked 2026-12-01) — Rh Simple is a simplified Reinhard operator; R/D Photoreceptor is Reinhard-Devlin. - godot: builtin — `Environment.tonemap_mode = Environment.TONE_MAPPER_REINHARDT` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) - threejs: builtin — `renderer.toneMapping = THREE.ReinhardToneMapping` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, blender ## Presets ### Three HDR exposure ramps (grey, orange, cyan). Left: clamp. Right: extended Reinhard on luminance (glsl-fragment; rendered 2026-11-29) ```json { "LW": 16 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const float LW=16.0; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); float e=exp2(mix(-4.,5.,clamp((q.x+.25)/.5,0.,1.))); int row=int(clamp(floor((uv.y+.5)*3.),0.,2.)); vec3 base=row==0?vec3(.1,.7,1.):(row==1?vec3(1.,.45,.12):vec3(1.)); vec3 c=base*e*.3; vec3 col; if(!R) col=gam(c); else{float L=lum(c),Ld=L*(1.+L/(LW*LW))/(1.+L);col=gam(c*Ld/max(L,1e-5));} if(fract((uv.y+.5)*3.)<.01)col=vec3(.1); if(abs(uv.x)<.0015)col=vec3(1.); fragColor=vec4(col,1.); } ``` Attribution: written for this index ## Lineage - extended by [Hable filmic (Uncharted 2) tonemapping](https://texelatlas.vercel.app/t/hable-filmic-tonemapping.md) ## Combines with - [Auto exposure from luminance histogram](https://texelatlas.vercel.app/t/auto-exposure-histogram.md): The measured log-average luminance sets Reinhard's key scaling. ## Sources 1. [primary] Erik Reinhard, Michael Stark, Peter Shirley, James Ferwerda (2002) Photographic tone reproduction for digital images. Proceedings of the 29th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/566570.566575 (verified via crossref on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Reinhard photographic tone reproduction." https://texelatlas.vercel.app/t/reinhard-tonemapping/ (accessed 2026-12-01). --- id: "relaxed-cone-step-mapping" title: "Relaxed cone step mapping" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2008 inputs: [texture, normals, uv-atlas] outputs: [texture, normals] style: "both" dynamic: "static" cost: "medium" authority: "Policarpo et al., 2005" url: "https://texelatlas.vercel.app/t/relaxed-cone-step-mapping/" sources_verified_at: "2026-11-29" --- # Relaxed cone step mapping (Policarpo et al., 2005) > Relief mapping accelerated by a precomputed cone map storing, per texel, how wide a cone of empty space rises above the height field. The ray advances safely by cone distance, then a short binary search finds the hit. ## Reach for it when - relief mapping misses thin features or steep walls - parallax effect shows holes at grazing angles - need faster safe stepping through a height texture - bumpy brick surface should look deep without geometry - ray-versus-heightfield artefacts on texture detail ## How it works For every texel of the height map, a preprocess computes a cone with apex at the texel's surface point such that the cone's interior never intersects the height field, and stores its ratio (width over height) in a second channel. At render time the ray steps along the safe distance given by the cone at its current location, instead of fixed increments, so empty space is crossed in a few big steps and near-surface regions in small ones. 'Relaxed' cones are allowed to overlap the surface slightly, which makes them wider and faster; a binary search resolves the hit and the guarantee of no missed features is relaxed to rare tiny errors. The approach avoids the missed-thin-feature artifact of linear-search relief mapping while keeping the iteration count to roughly 15 steps. ## When to use it Choose it when thin features, steep walls or grazing views show missed intersections in [Relief mapping](https://texelatlas.vercel.app/t/relief-mapping.md), and you can afford a cone-map generation step. Prefer [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) for very low-end targets. For real silhouettes, use displaced geometry. ## Cost medium — Around 10-20 height fetches per pixel with a precomputed cone texture. Measured GPU Weight: 28.82× baseline (heavy) — 0.9483 ms median / 0.9665 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 23.14× baseline (heavy) — 0.368 ms median (2.58× faster on L4). Ampere A100 scaling: 19.06× baseline (moderate) — 0.5488 ms median (1.73× faster on A100). ## Failure modes - Cone-map precompute for large textures is slow; needs regeneration when height changes, so unsuitable for animated heights - Relaxed cones can very occasionally overshoot thin spikes - Same flat-silhouette limitation as other parallax methods - Tiled textures need cones computed with wrap-around ## Dataflow - Inputs: texture, normals, uv-atlas - Outputs: texture, normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Relaxed cone step mapping — steep parallax relief & binary search vs flat bump split (glsl-fragment; rendered 2026-11-30) ```json { "P_RELIEF_DEPTH": 0.18, "P_CONE_STEPS": 18, "P_SHADOW_SOFT": 0.85, "P_SPLIT": 0.34 } ``` ```glsl const float P_RELIEF_DEPTH = 0.18; // P Relief Depth [0.02, 0.36, 0.01] const float P_CONE_STEPS = 18.0; // P Cone Steps [6.0, 28.0, 1.0] const float P_SHADOW_SOFT = 0.85; // P Self-Shadow [0.0, 1.0, 0.02] const float P_SPLIT = 0.34; // P Flat/RCSM Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); } // High-relief ornamental stonework heightfield in [0, 1] (0 = deep recessed mortar, 1 = raised stone boss) float sampleHeight(vec2 uv) { vec2 p = uv * 2.6; // Running-bond dressed stone ashlar blocks + carved ornamental medallions float row = floor(p.y); p.x += mod(row, 2.0) * 0.5; vec2 id = floor(p); vec2 f = fract(p) - 0.5; float hRand = hash21(id); // Steep chamfered stone block profile (torture test for steep parallax relief!) vec2 b = abs(f) - vec2(0.41, 0.39); float dBlock = length(max(b, 0.0)) + min(max(b.x, b.y), 0.0); float blockH = smoothstep(0.055, -0.055, dBlock) * (0.72 + 0.20 * hRand); // Carved circular recessed rosettes & raised brass bosses on alternating blocks float r = length(f); float ring = smoothstep(0.055, 0.01, abs(r - 0.22)) * 0.22 * step(0.45, hRand); float recess = smoothstep(0.20, 0.11, r) * 0.38 * step(0.45, hRand); float boss = smoothstep(0.11, 0.04, r) * 0.44 * step(0.45, hRand); // Subtle chiseled stone surface texture float chisel = 0.03 * sin(p.x * 28.0 + hRand * 6.0) * cos(p.y * 24.0); return clamp(blockH + ring - recess + boss + chisel, 0.02, 1.0); } vec3 sampleReliefNormal(vec2 uv, float depth) { float e = 0.004; float hx = sampleHeight(uv + vec2(e, 0.0)) - sampleHeight(uv - vec2(e, 0.0)); float hy = sampleHeight(uv + vec2(0.0, e)) - sampleHeight(uv - vec2(0.0, e)); return normalize(vec3(-hx * depth * 10.5, -hy * depth * 10.5, 1.0)); } // Relaxed Cone Step Mapping: accelerated cone-ratio stepping + 5-step binary refinement vec3 relaxedConeMarch(vec2 uv0, vec3 viewTS, float depth, int steps) { // Ray marches in tangent space from height z = 1.0 down toward z = 0.0 vec3 ray = vec3(uv0, 1.0); vec3 stepDir = vec3(-viewTS.xy * depth / max(viewTS.z, 0.22), -1.0); float t = 0.0; float prevT = 0.0; // Phase 1: Relaxed cone step (takes large safe leaps across empty space above heightfield) float relaxedConeRatio = 0.58; for (int i = 0; i < 28; i++) { if (i >= steps) break; vec3 cur = ray + stepDir * t; float h = sampleHeight(cur.xy); float deltaH = cur.z - h; if (deltaH <= 0.001) break; prevT = t; // Cone step advances proportionally to vertical clearance * cone ratio float dt = max(deltaH * relaxedConeRatio, 0.028); t = min(t + dt, 1.0); } // Phase 2: Binary search refinement between [prevT, t] for razor-sharp relief edges float lo = prevT, hi = t; for (int k = 0; k < 5; k++) { float mid = 0.5 * (lo + hi); vec3 cm = ray + stepDir * mid; if (cm.z > sampleHeight(cm.xy)) lo = mid; else hi = mid; } return ray + stepDir * (0.5 * (lo + hi)); } // Parallax self-shadowing march from displaced surface point toward tangent-space light float reliefShadow(vec3 hitPos, vec3 lightTS, float depth) { if (lightTS.z <= 0.05) return 0.0; vec3 stepDir = vec3(lightTS.xy * depth / max(lightTS.z, 0.25), 1.0); float sh = 1.0; float t = 0.05; for (int i = 0; i < 12; i++) { vec3 p = hitPos + stepDir * t; if (p.z >= 1.0) break; float h = sampleHeight(p.xy); float pen = (h - p.z) * 4.5 / (0.25 + t); sh = min(sh, clamp(1.0 - pen, 0.0, 1.0)); t += 0.075; } return sh; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; float depth = clamp(P_RELIEF_DEPTH, 0.01, 0.40); int steps = int(clamp(P_CONE_STEPS, 4.0, 28.0)); float shStr = clamp(P_SHADOW_SOFT, 0.0, 1.0); float splitX = clamp(P_SPLIT, 0.0, 1.0); // Orbiting oblique camera viewing a tilted relief wall at steep grazing perspective float camAng = 0.35 * sin(iTime * 0.45); vec3 ro = vec3(sin(camAng) * 0.9, -0.78, 1.48); vec3 ta = vec3(0.0, 0.06, 0.0); vec3 ww = normalize(ta - ro); vec3 uu = normalize(cross(ww, vec3(0.0, 0.0, 1.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.45 * ww); // Intersect base relief plane at z = 0 (tangent space: X=right, Y=up, Z=out of wall) float tPlane = -ro.z / min(rd.z, -0.001); vec3 hitBase = ro + rd * tPlane; vec2 baseUV = hitBase.xy * 0.72 + vec2(iTime * 0.04, 0.0); vec3 viewTS = normalize(-rd); bool useRCSM = (screenUV.x >= splitX); vec3 surfHit = useRCSM ? relaxedConeMarch(baseUV, viewTS, depth, steps) : vec3(baseUV, sampleHeight(baseUV)); vec2 sUV = surfHit.xy; float hVal = sampleHeight(sUV); vec3 nTS = sampleReliefNormal(sUV, depth); // Animated warm torch light grazing across the deep carved masonry vec3 lPos = vec3(0.75 * cos(iTime * 0.65), 0.55 * sin(iTime * 0.52), 0.72); vec3 lDir = normalize(lPos - vec3(hitBase.xy, 0.0)); float sh = useRCSM ? mix(1.0, reliefShadow(surfHit, lDir, depth), shStr) : 1.0; // Material palette: dark basalt mortar, warm carved sandstone ashlar, burnished gold bosses vec3 mortarCol = vec3(0.09, 0.085, 0.095); vec3 stoneCol = mix(vec3(0.32, 0.30, 0.28), vec3(0.58, 0.52, 0.45), smoothstep(0.18, 0.78, hVal)); vec3 goldCol = vec3(0.92, 0.70, 0.28); float isGold = smoothstep(0.84, 0.94, hVal); vec3 alb = mix(mortarCol, stoneCol, smoothstep(0.08, 0.28, hVal)); alb = mix(alb, goldCol, isGold); float ndl = max(dot(nTS, lDir), 0.0); vec3 hVec = normalize(lDir + viewTS); float specPow = mix(18.0, 64.0, isGold); float spec = pow(max(dot(nTS, hVec), 0.0), specPow) * mix(0.25, 1.35, isGold); // Crevice cavity AO proportional to relief depth float cavAO = mix(0.28, 1.0, smoothstep(0.05, 0.72, hVal)); vec3 col = alb * (vec3(2.2, 1.75, 1.25) * ndl * sh + vec3(0.18, 0.24, 0.36) * cavAO) + vec3(1.0, 0.88, 0.65) * spec * sh; if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(0.35, 0.90, 1.0); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Relief mapping](https://texelatlas.vercel.app/t/relief-mapping.md) ## Sources 1. [tutorial] Fabio Policarpo, Manuel M. Oliveira Relaxed Cone Stepping for Relief Mapping. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-18-relaxed-cone-stepping-relief-mapping (verified via http on 2026-11-29) 2. [primary] Fábio Policarpo, Manuel M. Oliveira, João L. D. Comba (2005) Real-time relief mapping on arbitrary polygonal surfaces. Proceedings of the 2005 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1053427.1053453 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Relaxed cone step mapping." https://texelatlas.vercel.app/t/relaxed-cone-step-mapping/ (accessed 2026-12-01). --- id: "relief-mapping" title: "Relief mapping" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2005 inputs: [texture, normals, uv-atlas] outputs: [texture, normals] style: "both" dynamic: "both" cost: "medium" authority: "Policarpo et al., 2005" url: "https://texelatlas.vercel.app/t/relief-mapping/" sources_verified_at: "2026-11-29" --- # Relief mapping (Policarpo et al., 2005) > Per-pixel ray-height-field intersection using a linear search followed by a binary search, for robust parallax with correct self-occlusion on arbitrary polygonal surfaces, using only height and normal textures. ## Reach for it when - flat texture lacks depth and parallax on surfaces - bump maps fail at steep viewing angles - brick wall should look truly 3d without geometry - parallax effect with correct self occlusion ## How it works Policarpo, Oliveira and Comba intersect the view ray with a tangent-space heightfield by first stepping along the ray in uniform increments (linear search) until the ray first passes below the surface, then refining that interval by binary search for a handful of iterations. This hybrid guarantees a hit within the bracket and sharpens it quickly. The result gives exact-looking self-occlusion, and the recovered position can feed shadow tests, depth writing and silhouette tricks. Unlike the earlier 2000 relief texture mapping, which pre-warped texture images in a 3D warping pass, this version evaluates entirely in the fragment shader on any polygon with tangent frames and needs no pre-warp. ## When to use it Choose it when parallax occlusion's single-interval interpolation breaks and you want robust hit finding at moderate cost. Prefer [Relaxed cone step mapping](https://texelatlas.vercel.app/t/relaxed-cone-step-mapping.md) when thin features are missed by linear search or you need a precomputed cone map. Prefer [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) for cheaper per-pixel results with fewer iterations. ## Cost medium — A linear search of 8-32 height fetches plus 5-8 binary refinements per pixel. Measured GPU Weight: 4.63× baseline (light) — 0.1522 ms median / 0.1601 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.79× baseline (light) — 0.0602 ms median (2.53× faster on L4). Ampere A100 scaling: 2.94× baseline (light) — 0.0847 ms median (1.8× faster on A100). ## Failure modes - Thin features narrower than the linear step are skipped, so thin walls or spikes vanish - Binary search can lock onto the wrong crossing when the ray enters and exits the height field several times - Silhouette remains flat - Large cost at grazing angles; needs adaptive step count ## Dataflow - Inputs: texture, normals, uv-atlas - Outputs: texture, normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Relief mapping: linear search only (left) vs linear + binary refinement (right) (glsl-fragment; rendered 2026-11-29) ```json { "DEPTH": 0.16, "LINEAR_STEPS": 10, "BINARY_STEPS": 7 } ``` ```glsl // Relief mapping: linear search along the view ray through a brick heightfield, then binary-search refinement. // Left: 10 linear steps only (stair-stepping at grazing angles). Right: same 10 steps + 7 binary refinements. const float DEPTH = 0.16; const int LINEAR_STEPS = 10; const int BINARY_STEPS = 7; float hgt(vec2 uv) { float row = floor(uv.y / 0.5); vec2 c = vec2(fract((uv.x + 0.5 * mod(row, 2.0)) / 1.0), fract(uv.y / 0.5)); float e = min(min(c.x, 1.0 - c.x), min(c.y, 1.0 - c.y) * 0.5); return smoothstep(0.02, 0.07, e); } vec3 brick(vec2 uv) { float row = floor(uv.y / 0.5); float id = floor(uv.x + 0.5 * mod(row, 2.0)); float r = fract(sin(dot(vec2(id, row), vec2(12.9898, 78.233))) * 43758.5453); return mix(vec3(0.5, 0.18, 0.12), vec3(0.7, 0.35, 0.2), r); } vec3 shadeAt(vec2 uv, float t) { float e = 0.01; float h = hgt(uv); vec3 n = normalize(vec3(-(hgt(uv + vec2(e, 0.0)) - h) / e * 0.12, 1.0, -(hgt(uv + vec2(0.0, e)) - h) / e * 0.12)); vec3 c = mix(vec3(0.35), brick(uv), h) * (0.2 + 0.9 * max(dot(n, normalize(vec3(0.4, 0.8, 0.4))), 0.0)) * mix(0.45, 1.0, h); return mix(vec3(0.7, 0.78, 0.88), c, exp(-t * 0.03)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 1.0, 0.0), rd = normalize(vec3(uv.x, uv.y - 0.32, -1.0)); vec3 col = mix(vec3(0.7, 0.78, 0.88), vec3(0.35, 0.55, 0.85), clamp(rd.y * 3.0, 0.0, 1.0)); if (rd.y < -0.001) { float t = -ro.y / rd.y; vec2 p0 = (ro + rd * t).xz * 0.9; vec2 dxz = rd.xz / (-rd.y) * DEPTH * 0.9; float lo = 0.0, hi = 1.0; float step0 = 1.0 / float(LINEAR_STEPS); for (int i = 1; i <= LINEAR_STEPS; i++) { float d = float(i) * step0; if (d >= 1.0 - hgt(p0 + dxz * d)) { hi = d; lo = d - step0; break; } lo = d; hi = 1.0; } float dsel = hi; if (fragCoord.x > 0.5 * iResolution.x) { for (int i = 0; i < BINARY_STEPS; i++) { float m = 0.5 * (lo + hi); if (m >= 1.0 - hgt(p0 + dxz * m)) hi = m; else lo = m; } dsel = hi; } col = shadeAt(p0 + dxz * dsel, t); } if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Parallax occlusion mapping](https://texelatlas.vercel.app/t/parallax-occlusion-mapping.md) - extended by [Relaxed cone step mapping](https://texelatlas.vercel.app/t/relaxed-cone-step-mapping.md) ## Sources 1. [primary] Fábio Policarpo, Manuel M. Oliveira, João L. D. Comba (2005) Real-time relief mapping on arbitrary polygonal surfaces. Proceedings of the 2005 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1053427.1053453 (verified via crossref on 2026-11-29) 2. [primary] Manuel M. Oliveira, Gary Bishop, David McAllister (2000) Relief texture mapping. Proceedings of the 27th annual conference on Computer graphics and interactive techniques - SIGGRAPH '00. https://doi.org/10.1145/344779.344947 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Relief mapping." https://texelatlas.vercel.app/t/relief-mapping/ (accessed 2026-12-01). --- id: "reoriented-normal-mapping" title: "Reoriented normal map blending (detail normals)" aliases: [RNM, reoriented normal blending] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2012 inputs: [normals, texture] outputs: [normals] style: "both" dynamic: "both" cost: "cheap" authority: "Barre-Brisebois & Hill" url: "https://texelatlas.vercel.app/t/reoriented-normal-mapping/" sources_verified_at: "2026-11-29" --- # Reoriented normal map blending (detail normals) (Barre-Brisebois & Hill) > A correct way to layer a detail normal map onto a base normal map: it rotates the detail normal into the frame of the base so slopes combine as real orientations rather than averaged offsets. ## Reach for it when - detail normal map flattens the base normal map - blending two normal maps looks wrong on slopes - combining triplanar or decal normals correctly - micro detail normals lose strength on curved areas - choose between udn whiteout and correct normal blend ## How it works Blending two tangent-space normals by adding xy and renormalising treats them as height gradients and flattens detail where the base is steep. Reoriented blending instead rotates the detail normal by the rotation that carries the +Z axis to the base normal. With t = base*(2,2,2)+(-1,-1,0) and u = detail*(-2,-2,2)+(1,1,-1), the result is r = t * dot(t,u) / t.z - u, then normalised. That is the shortest-arc rotation applied to the detail vector in closed form: no trigonometry or matrix building, just a dot product and a divide. Cheaper approximations include UDN (add the detail xy to the base) and the whiteout blend (add xy, multiply z), which keep strong detail but are not exact. RNM is the reference that others are compared to; the cost difference matters only on weak hardware. ## When to use it Use it whenever a detail or micro normal map is layered on top of a macro normal map, or when decals and triplanar projections combine tangent-space normals. Prefer [Surface gradient based bump mapping framework](https://texelatlas.vercel.app/t/surface-gradient-bump-mapping.md) for a framework that blends many bump or normal sources in one place with consistent semantics. Prefer plain UDN or whiteout when ALU is critical. Use [Normal distribution filtering for specular antialiasing](https://texelatlas.vercel.app/t/normal-distribution-filtering.md) or [Toksvig normal-map filtering](https://texelatlas.vercel.app/t/toksvig-mipmapping.md) for how those normal maps are filtered and minified. ## Cost cheap — A dot product, a divide and a normalise per blend. Measured GPU Weight: 4.14× baseline (light) — 0.1363 ms median / 0.1387 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.36× baseline (light) — 0.0535 ms median (2.55× faster on L4). Ampere A100 scaling: 2.5× baseline (light) — 0.0721 ms median (1.89× faster on A100). ## Failure modes - Uses the +Z-up unpacked convention; passing already-biased [0,1] values or OpenGL/DirectX Y-flipped maps gives wrong slopes - Division by t.z blows up when the base normal is nearly horizontal, unless clamped - Blending must happen before the TBN transform; blending in world space reintroduces the error - Not associative: blending in a different order across layers changes the result slightly - Mip-averaged detail normals shorten in length, so the blend underestimates detail at distance without length-aware filtering ## Engine support - unity: builtin — `Shader Graph > Normal Blend node > Mode = Reoriented` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Normal-Blend-Node.md, checked 2026-12-01) ## Dataflow - Inputs: normals, texture - Outputs: normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Reoriented Normal Mapping (RNM) — linear/UDN normal blend flattening (left) vs quaternion RNM rotation (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MACRO_STEEP": 1, "P_DETAIL_STR": 0.85, "P_LIGHT_SPIN": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_MACRO_STEEP = 1.0; // P Base Slope Steep [0.2, 1.5, 0.05] const float P_DETAIL_STR = 0.85; // P Detail Strength [0.1, 1.5, 0.05] const float P_LIGHT_SPIN = 0.65; // P Light Orbit [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Linear / RNM Split [0.0, 1.0, 0.02] // Base macro normal map: bold embossed circular domes & deep fluted ridges (very steep base slopes!) vec3 evalBaseNormal(vec2 uv, float steep) { vec2 p = uv * 3.2; vec2 cell = fract(p) - 0.5; float r = length(cell); // Steep spherical bump + wave ridges vec2 grad = vec2(0.0); if (r < 0.38) { grad += (cell / max(r, 1e-4)) * smoothstep(0.38, 0.05, r) * 2.4; } grad += vec2(cos(uv.x * 14.0), sin(uv.y * 14.0)) * 0.85; grad *= steep; return normalize(vec3(-grad.x, -grad.y, 1.0)); } // High-frequency detail normal map: crisp micro-hexagonal scales / embossed fabric studs vec3 evalDetailNormal(vec2 uv, float str) { vec2 q = uv * 34.0; vec2 f = fract(q) - 0.5; float r = length(f); vec2 dg = (r < 0.38) ? (f / max(r, 1e-4)) * smoothstep(0.38, 0.08, r) * 1.65 : vec2(0.0); dg += vec2(cos(q.x * 3.14159), sin(q.y * 3.14159)) * 0.45; dg *= str; return normalize(vec3(-dg.x, -dg.y, 1.0)); } // Reoriented Normal Mapping (Barre-Brisebois & Hill 2012): shortest-arc quaternion rotation of n2 onto n1! vec3 blendRNM(vec3 n1, vec3 n2) { vec3 t = n1 + vec3(0.0, 0.0, 1.0); vec3 u = n2 * vec3(-1.0, -1.0, 1.0); return normalize(t * (dot(t, u) / max(t.z, 1e-4)) - u); } // Naive linear normal blending (washes out detail when base normal tilts steeply away from +Z!) vec3 blendLinear(vec3 n1, vec3 n2) { return normalize(n1 + n2); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isRNM = screenX >= split; float steep = clamp(P_MACRO_STEEP, 0.15, 1.6); float detStr = clamp(P_DETAIL_STR, 0.05, 1.6); float spin = iTime * max(P_LIGHT_SPIN, 0.0); vec3 nBase = evalBaseNormal(uv, steep); vec3 nDet = evalDetailNormal(uv, detStr); vec3 n = isRNM ? blendRNM(nBase, nDet) : blendLinear(nBase, nDet); // Orbiting grazing studio key light + cool fill light so slope-normal differences pop unmistakably! vec3 l1 = normalize(vec3(cos(spin * 0.75) * 0.85, sin(spin * 0.75) * 0.85, 0.42)); vec3 l2 = normalize(vec3(-0.65, 0.55, 0.65)); vec3 v = vec3(0.0, 0.0, 1.0); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec1 = pow(max(dot(n, normalize(l1 + v)), 0.0), 48.0); float spec2 = pow(max(dot(n, normalize(l2 + v)), 0.0), 28.0); // Anodized copper-slate ceramic shader vec3 alb = mix(vec3(0.18, 0.24, 0.34), vec3(0.84, 0.46, 0.26), smoothstep(0.4, 0.95, nBase.z)); vec3 col = alb * (0.16 + 0.95 * diff1 + 0.30 * diff2) + vec3(1.0, 0.90, 0.78) * spec1 * 0.88 + vec3(0.32, 0.74, 1.0) * spec2 * 0.35; // Subtle normal-map diagnostic strip along bottom edge float screenY = fragCoord.y / max(iResolution.y, 1.0); if (screenY < 0.12) { col = mix(col, n * 0.5 + 0.5, smoothstep(0.12, 0.11, screenY) * 0.92); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) - extended by [Surface gradient based bump mapping framework](https://texelatlas.vercel.app/t/surface-gradient-bump-mapping.md) ## Combines with - [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md): The three projected tangent-space normals are combined with reoriented blending instead of a linear mix. - [Deferred and projected decals](https://texelatlas.vercel.app/t/deferred-and-projected-decals.md): Decal normals are layered over the stored surface normal using the same rotation. ## Sources 1. [primary] Colin Barre-Brisebois, Stephen Hill Blending in Detail. blog.selfshadow.com. https://blog.selfshadow.com/publications/blending-in-detail (verified via http on 2026-11-29) ## Cite this entry Texel. "Reoriented normal map blending (detail normals)." https://texelatlas.vercel.app/t/reoriented-normal-mapping/ (accessed 2026-12-01). --- id: "restir-di" title: "ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting" aliases: [ReSTIR, RIS with reservoirs] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, webgpu] year_introduced: 2020 inputs: [gbuffer, mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Bitterli et al., 2020" url: "https://texelatlas.vercel.app/t/restir-di/" sources_verified_at: "2026-11-29" --- # ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting (Bitterli et al., 2020) > Renders direct lighting from thousands to millions of dynamic lights with a few shadow rays per pixel by streaming candidate lights into per-pixel reservoirs and sharing them across neighbouring pixels and frames. ## Reach for it when - thousands of dynamic lights make direct lighting noisy - scene has millions of emissive triangles - can't find a good light with one or two samples per pixel - need real-time many-light shading with few shadow rays ## How it works ReSTIR builds on **resampled importance sampling**. For a pixel, you draw `M` cheap candidate lights from a simple distribution (power, uniform). You pick one of them with probability proportional to a target function such as unshadowed contribution, and keep only that winner. The streaming variant is a **reservoir**: it stores one sample plus a running weight sum, so memory is constant however many candidates you stream through. The two reuse stages are what make it fast. **Temporal reuse** merges last frame's reservoir (reprojected through motion vectors) into the current one, and **spatial reuse** merges reservoirs from nearby pixels. Merging reservoirs is itself a resampling step, which keeps the estimator unbiased if each reservoir's contribution weight is corrected by a Jacobian or by an extra visibility-aware step. Effective candidate counts grow by orders of magnitude per frame at the cost of a few operations. Finally, one visibility ray is traced for the surviving sample and the shaded result is output, usually followed by a denoiser. An extra unbiased mode re-traces visibility for the reused samples. ## When to use it Choose it for scenes with huge numbers of emissive triangles or dynamic lights, where classic next-event estimation with a light tree cannot find a good light in one or two samples. It needs a G-buffer and motion vectors. Prefer [light-bvh-many-lights](light-bvh-many-lights) or [lightcuts](lightcuts) when you want a deterministic, offline-grade many-light solution. Prefer [restir-gi](restir-gi) or [restir-pt](restir-pt) when the missing energy is indirect rather than direct. Prefer plain [path-tracing](path-tracing) with [multiple-importance-sampling](multiple-importance-sampling) when you have only a handful of lights. ## Cost medium — Cost scales with the initial candidate count, one visibility ray per pixel per pass and the reuse passes; the original paper reports interactive frame rates for millions of lights on 2020 desktop GPUs. Measured GPU Weight: 19.33× baseline (moderate) — 0.6359 ms median / 0.6654 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.27× baseline (moderate) — 0.2587 ms median (2.46× faster on L4). Ampere A100 scaling: 11.04× baseline (moderate) — 0.318 ms median (2× faster on A100). ## Failure modes - Temporal lag and ghosting after fast lighting or camera changes because stale reservoirs persist - Biased darkening or brightening at disocclusions, depth discontinuities and normal changes unless reuse is carefully rejected - Correlated noise patterns (blotches) from spatial reuse that the denoiser must remove - Requires one shadow ray per reused sample for unbiased visibility, otherwise light leaks through thin occluders ## Engine support - unreal: builtin — `Project Settings > Rendering > MegaLights (stochastic reservoir-resampled many-light direct illumination and shadows)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/megalights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, mesh, material-params - Outputs: radiance - Platforms: desktop-gpu, webgpu ## Presets ### Toy ReSTIR-DI core: uniform pick vs RIS reservoir vs reference (48 lights, 1 spp, no reuse) (glsl-fragment; rendered 2026-11-29) ```json { "NL": 48, "M": 12 } ``` ```glsl // Toy ReSTIR-DI core: resampled importance sampling (RIS) with a streaming reservoir, no temporal/spatial reuse. // 48 coloured point lights over a plane, unshadowed, 1 shading sample per pixel. // Left: uniform light pick. Middle: RIS, 12 candidates, target pdf = luminance of the unshadowed contribution. // Right: reference (all 48 lights). const int NL = 48; const int M = 12; const float GAIN = 0.012; vec2 h2(float n) { return fract(sin(vec2(n * 127.1, n * 311.7 + 17.0)) * 43758.5453); } vec3 lightPos(int i) { vec2 r = h2(float(i) + 1.0); return vec3((r - 0.5) * 2.3, 0.25); } vec3 lightCol(int i) { float r = h2(float(i) + 40.0).x; return (0.5 + 0.5 * cos(6.2832 * (r + vec3(0.0, 0.33, 0.67)))) * (0.15 + 2.5 * r * r * r); } vec3 contrib(int i, vec3 p) { vec3 l = lightPos(i) - p; float d2 = dot(l, l); return lightCol(i) * (l.z / sqrt(d2)) / d2 * GAIN; } float lum(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); } float rnd(inout float s) { s += 1.0; return fract(sin(s * 91.3458) * 47453.5453); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 p = vec3(uv * 2.2, 0.0); float seed = dot(fragCoord, vec2(12.9898, 78.233)); float x3 = fragCoord.x / iResolution.x * 3.0; vec3 col = vec3(0.0); if (x3 < 1.0) { int i = int(floor(rnd(seed) * float(NL))); col = contrib(min(i, NL - 1), p) * float(NL); } else if (x3 < 2.0) { float wsum = 0.0; int sel = 0; float selL = 0.0; for (int m = 0; m < M; m++) { int i = min(int(floor(rnd(seed) * float(NL))), NL - 1); float pl = lum(contrib(i, p)); float w = pl * float(NL); wsum += w; if (rnd(seed) * wsum < w) { sel = i; selL = pl; } } col = selL > 0.0 ? contrib(sel, p) * (wsum / (float(M) * selL)) : vec3(0.0); } else { for (int i = 0; i < NL; i++) col += contrib(i, p); } for (int i = 0; i < NL; i++) if (length(p.xy - lightPos(i).xy) < 0.012) col = lightCol(i) * 0.5 + 0.5; col = col / (1.0 + col); if (fract(x3) < 0.004 || fract(x3) > 0.996) col = vec3(1.0); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Light BVH and Adaptive Tree Splitting](https://texelatlas.vercel.app/t/light-bvh-many-lights.md): A light tree or grid can provide better initial candidate distributions than uniform or power sampling. - [ReSTIR GI: Path Resampling for Real-Time Path Tracing](https://texelatlas.vercel.app/t/restir-gi.md): Direct reservoirs and indirect-path reservoirs share the same motion vectors and reuse machinery. ## Sources 1. [primary] Benedikt Bitterli, Chris Wyman, Matt Pharr, Peter Shirley, Aaron Lefohn, Wojciech Jarosz (2020) Spatiotemporal reservoir resampling for real-time ray tracing with dynamic direct lighting. ACM Transactions on Graphics. https://doi.org/10.1145/3386569.3392481 (verified via crossref on 2026-11-29) 2. [implementation] NVIDIA-RTX (2021) NVIDIA-RTX/RTXDI. https://github.com/NVIDIA-RTX/RTXDI License: NOASSERTION. (verified via github on 2026-11-29) 3. [implementation] NVIDIAGameWorks (2017) NVIDIAGameWorks/Falcor. https://github.com/NVIDIAGameWorks/Falcor License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting." https://texelatlas.vercel.app/t/restir-di/ (accessed 2026-12-01). --- id: "restir-gi" title: "ReSTIR GI: Path Resampling for Real-Time Path Tracing" aliases: [ReSTIR indirect] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu] year_introduced: 2021 inputs: [gbuffer, normals, depth] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Ouyang et al., 2021" url: "https://texelatlas.vercel.app/t/restir-gi/" sources_verified_at: "2026-11-29" --- # ReSTIR GI: Path Resampling for Real-Time Path Tracing (Ouyang et al., 2021) > Applies reservoir resampling to one-bounce indirect light: each pixel keeps a candidate secondary hit point with its outgoing radiance and reuses winners from neighbours and previous frames to cut indirect noise. ## Reach for it when - ray-traced indirect light is too noisy even after denoising - need stable one-bounce diffuse gi in real time - few rays per pixel give grainy bounce lighting - reuse samples from neighbours and past frames - dynamic gi with many light sources ## How it works A path-traced indirect sample from a pixel's primary surface point is a pair: a **secondary hit** (position and normal) and the **radiance leaving it** toward that surface. ReSTIR GI treats that pair as the sample stored in a reservoir. Each frame, every pixel traces one new candidate with BSDF sampling and puts it in a reservoir. A target function, normally the luminance of the product of radiance and BSDF cosine at the primary surface, weights candidates. **Temporal reuse** pulls the reprojected previous reservoir. **Spatial reuse** pulls a few neighbours' samples. A neighbour's sample is valid for a pixel if the secondary hit is visible from there, which is why a shift mapping from the neighbour's domain to this pixel's domain (with a Jacobian correcting the pdf change) and a visibility check are required. Because the sample is just a hit point with its outgoing radiance, reuse does not need to re-trace the whole path, and the estimator effectively shares one-bounce samples across many pixels for several times the effective sample count. ## When to use it Choose it for a hardware-ray-traced renderer that needs more stable one-bounce diffuse GI than one-sample path tracing plus a denoiser can give, and which already has motion vectors, normals and depth. Prefer [restir-pt](restir-pt) when you need multi-bounce, glossy and specular transport; it generalizes this approach with shift mappings for whole paths. Prefer [ddgi](ddgi) or [lumen-gi](lumen-gi) when you need predictable, noise-free, cheaper low-frequency GI and can accept coarse spatial resolution. Prefer [neural-radiance-caching](neural-radiance-caching) or [sharc](sharc) when you want long paths terminated by a cache. ## Cost medium — One extra ray for the candidate plus visibility rays for spatial reuse; the paper targets interactive rates on high-end RTX GPUs at 1080p. Measured GPU Weight: 36.43× baseline (heavy) — 1.1439 ms median / 1.239 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 37.83× baseline (heavy) — 0.5977 ms median (1.91× faster on L4). Ampere A100 scaling: 22.67× baseline (heavy) — 0.653 ms median (1.75× faster on A100). ## Failure modes - Light leaking through thin geometry when spatial neighbours share a hit that is invisible from the target pixel - Temporal correlation produces slow-to-clear streaks after lighting changes unless history is capped - Bias at occlusion boundaries when the Jacobian or validity test is skipped for speed - Struggles with glossy and specular indirect because the stored sample assumes a diffuse-like reuse ## Dataflow - Inputs: gbuffer, normals, depth - Outputs: radiance - Platforms: desktop-gpu ## Presets ### ReSTIR GI — noisy 1-spp unguided indirect path tracing (left) vs spatiotemporal reservoir resampling (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_NOISE_SCALE": 1, "P_REUSE_RADIUS": 0.85, "P_BOUNCE_GAIN": 1.35, "P_SPLIT": 0.46 } ``` ```glsl const float P_NOISE_SCALE = 1.0; // P 1-spp Variance [0.2, 2.0, 0.05] const float P_REUSE_RADIUS = 0.85; // P Reservoir Reuse [0.0, 1.0, 0.02] const float P_BOUNCE_GAIN = 1.35; // P Indirect GI [0.2, 2.5, 0.05] const float P_SPLIT = 0.46; // P 1-spp / ReSTIR [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } 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); } // Neon architectural gallery with 3 compact bright emissive bars (hard for naive 1-spp GI!) vec2 mapScene(vec3 p) { vec2 res = vec2(1.0 + p.y, 1.0); // floor float cD = 1.0 - p.y; if (cD < res.x) res = vec2(cD, 1.0); float bD = 1.50 + p.z; if (bD < res.x) res = vec2(bD, 1.0); float lD = 1.45 + p.x; if (lD < res.x) res = vec2(lD, 1.0); float rD = 1.45 - p.x; if (rD < res.x) res = vec2(rD, 1.0); // Sculpted concrete blocks & central sphere float dB1 = sdBox(p - vec3(-0.52, -0.52, -0.52), vec3(0.26, 0.48, 0.26)) - 0.02; if (dB1 < res.x) res = vec2(dB1, 2.0); float dB2 = sdBox(p - vec3(0.58, -0.62, -0.35), vec3(0.28, 0.38, 0.28)) - 0.02; if (dB2 < res.x) res = vec2(dB2, 2.0); float dSph = length(p - vec3(0.02, -0.62, -0.08)) - 0.36; if (dSph < res.x) res = vec2(dSph, 2.0); // 3 small emissive neon strip lights mounted on walls float dE1 = sdBox(p - vec3(-1.38, 0.28, -0.25), vec3(0.05, 0.36, 0.08)); if (dE1 < res.x) res = vec2(dE1, 3.0); // electric cyan bar float dE2 = sdBox(p - vec3(1.38, 0.24, -0.35), vec3(0.05, 0.36, 0.08)); if (dE2 < res.x) res = vec2(dE2, 4.0); // hot magenta bar float dE3 = sdBox(p - vec3(0.0, 0.92, -0.75), vec3(0.45, 0.05, 0.08)); if (dE3 < res.x) res = vec2(dE3, 5.0); // warm amber skylight bar return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Compute exact multi-emitter indirect bounce radiance at (p, n) for ReSTIR reservoir target PDF p_hat vec3 evalTargetBounce(vec3 p, vec3 n, float t) { vec3 ePos1 = vec3(-1.35, 0.28, -0.25); vec3 ePos2 = vec3(1.35, 0.24, -0.35); vec3 ePos3 = vec3(0.35 * sin(t * 0.55), 0.90, -0.75); vec3 d1 = ePos1 - p; float r1 = length(d1); vec3 d2 = ePos2 - p; float r2 = length(d2); vec3 d3 = ePos3 - p; float r3 = length(d3); vec3 rad = vec3(0.0); rad += vec3(0.16, 1.35, 1.85) * (0.25 + 0.75 * max(dot(n, d1 / max(r1, 1e-4)), 0.0)) / (0.35 + r1 * r1 * 0.75); rad += vec3(1.85, 0.22, 1.15) * (0.25 + 0.75 * max(dot(n, d2 / max(r2, 1e-4)), 0.0)) / (0.35 + r2 * r2 * 0.75); rad += vec3(1.85, 1.25, 0.35) * (0.25 + 0.75 * max(dot(n, d3 / max(r3, 1e-4)), 0.0)) / (0.35 + r3 * r3 * 0.75); return rad; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float noiseGain = clamp(P_NOISE_SCALE, 0.15, 2.2); float reuse = clamp(P_REUSE_RADIUS, 0.0, 1.0); float giGain = max(P_BOUNCE_GAIN, 0.0); vec3 ro = vec3(0.0, 0.08, 2.38); vec3 rd = normalize(vec3(uv, -1.48)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); if (matId > 2.5) { if (matId < 3.5) col = vec3(0.35, 2.6, 3.6); else if (matId < 4.5) col = vec3(3.6, 0.45, 2.2); else col = vec3(3.4, 2.2, 0.65); } else { vec3 alb = (matId < 1.5) ? vec3(0.68, 0.70, 0.74) : vec3(0.84, 0.84, 0.86); // Soft ambient occlusion in corners float ao = clamp(0.45 + 0.55 * mapScene(p + n * 0.22).x / 0.22, 0.2, 1.0); // Ground-truth smooth bounce target radiance (what spatiotemporal ReSTIR GI converges toward) vec3 cleanGI = evalTargetBounce(p, n, iTime) * ao * giGain; // Left side: 1-spp unguided cosine-hemisphere Monte Carlo sampling -> extreme fireflies & black gaps! vec2 rnd = hash22(floor(fragCoord * 0.75) + fract(iTime * 7.3) * 19.1); float hitChance = smoothstep(0.55 - 0.18 * (2.0 - noiseGain), 0.94, rnd.x); float firefly = pow(rnd.y, 6.0) * 5.2 * noiseGain; // Pick one stochastic channel per pixel to mimic unguided single-path color variance vec3 mcPick = (rnd.x < 0.33) ? vec3(0.25, 1.4, 1.8) : ((rnd.x < 0.66) ? vec3(1.8, 0.25, 1.1) : vec3(1.8, 1.2, 0.35)); vec3 naive1spp = cleanGI * (0.28 + 1.45 * hitChance) + mcPick * firefly * ao * 0.42; // Right side: ReSTIR GI Weighted Reservoir Sampling (M=8 candidates + spatial neighbor reuse) // Residual noise vanishes as reuse approaches 1.0! float resNoise = (hash21(floor(fragCoord) + fract(iTime * 4.1) * 31.0) - 0.5) * 0.26 * (1.0 - reuse * 0.88); vec3 restirGI = cleanGI * (1.0 + resNoise); col = alb * ((screenX < split) ? naive1spp : restirGI) * 0.58; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [ReSTIR PT and Generalized Resampled Importance Sampling](https://texelatlas.vercel.app/t/restir-pt.md) ## Combines with - [ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting](https://texelatlas.vercel.app/t/restir-di.md): Direct-light reservoirs and indirect-path reservoirs share motion vectors and denoiser inputs. ## Combination ideas - [ReSTIR GI relighting of light-stage reflectance captures](https://texelatlas.vercel.app/ideas/light-stage-albedo-restir-gi/) ## Sources 1. [primary] Y. Ouyang, S. Liu, M. Kettunen, M. Pharr, J. Pantaleoni (2021) ReSTIR GI: Path Resampling for Real‐Time Path Tracing. Computer Graphics Forum. https://doi.org/10.1111/cgf.14378 (verified via crossref on 2026-11-29) 2. [implementation] zhaijialong (2022) zhaijialong/Screen-Space-ReSTIR-GI. https://github.com/zhaijialong/Screen-Space-ReSTIR-GI License: BSD-3-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "ReSTIR GI: Path Resampling for Real-Time Path Tracing." https://texelatlas.vercel.app/t/restir-gi/ (accessed 2026-12-01). --- id: "restir-pt" title: "ReSTIR PT and Generalized Resampled Importance Sampling" aliases: [GRIS, ReSTIR path tracing] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu] year_introduced: 2022 inputs: [gbuffer, mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Lin et al., 2022" url: "https://texelatlas.vercel.app/t/restir-pt/" sources_verified_at: "2026-11-29" --- # ReSTIR PT and Generalized Resampled Importance Sampling (Lin et al., 2022) > Extends reservoir resampling to whole light paths with shift mappings between pixels, so reuse works for multi-bounce, glossy and caustic transport. GRIS is the theory; ReSTIR PT is the path-tracing algorithm. ## Reach for it when - path tracing with many lights is too noisy at low spp - real-time path tracing needs better sample reuse - indirect lighting noise in complex scenes - reuse full light paths between pixels and frames ## How it works Earlier ReSTIR variants reuse samples that are single points. **Generalized resampled importance sampling** (GRIS) puts the reuse on a firm footing for samples that live in arbitrary domains, including full paths. When a sample from a neighbour is reused at the current pixel, a **shift mapping** turns the neighbour's path into a path for the current pixel, and the change in density is accounted for by a Jacobian and by resampling MIS weights that stay unbiased even when the mapping is not invertible everywhere. For path tracing the useful shift mappings are *random replay* (reuse the random numbers), *reconnection* (connect the current pixel's first vertex to a later vertex of the neighbour's path) and a **hybrid** that reconnects after the first rough vertex and replays through near-specular ones. This lets reuse keep specular chains intact while still sharing diffuse bounces. The pipeline traces one path per pixel, resamples it into a reservoir, then does temporal and spatial reuse with the hybrid shift, adding extra rays to confirm visibility of reused paths, followed by a denoiser. ## When to use it Choose it as the highest-quality real-time (or interactive) path-traced GI: multi-bounce diffuse, glossy reflections and caustic-like paths all benefit, and it is also useful as a convergence accelerator offline. Prefer [restir-gi](restir-gi) when one-bounce diffuse indirect is enough and you want a smaller, simpler implementation. Prefer [restir-di](restir-di) when only direct light is the issue. Prefer [neural-radiance-caching](neural-radiance-caching) when you need predictable cost and can tolerate cache bias. Prefer [path-guiding](path-guiding) when you want an unbiased improvement without any inter-pixel reuse. ## Cost heavy — Research implementations run at tens of milliseconds per frame on high-end 2022 GPUs at 1080p; the cost depends heavily on path length and reuse radius. Measured GPU Weight: 26.41× baseline (heavy) — 0.8186 ms median / 0.8325 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 27.34× baseline (heavy) — 0.4347 ms median (1.88× faster on L4). Ampere A100 scaling: 17.21× baseline (moderate) — 0.4957 ms median (1.65× faster on A100). ## Failure modes - Correlated artifacts: reuse smears one bright path into splotches that persist for many frames - Shift-mapping failures at occlusion and surface discontinuities show as dark or bright halos - Memory for storing path state per pixel for both current and previous frames is large - Complex unbiased MIS weights are easy to get subtly wrong, resulting in energy shifts that are hard to debug ## Dataflow - Inputs: gbuffer, mesh, material-params - Outputs: radiance - Platforms: desktop-gpu ## Presets ### ReSTIR PT — noisy 1-spp multi-bounce path tracing (left) vs hybrid-shift path resampling (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.24, "P_REUSE_STR": 0.88, "P_EMIT_GAIN": 1.35, "P_SPLIT": 0.48 } ``` ```glsl const float P_ROUGHNESS = 0.24; // P Glossy Roughness [0.08, 0.65, 0.02] const float P_REUSE_STR = 0.88; // P Path Reuse [0.0, 1.0, 0.02] const float P_EMIT_GAIN = 1.35; // P Multi-Bounce [0.3, 2.4, 0.05] const float P_SPLIT = 0.48; // P 1-spp / ReSTIR PT [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } 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); } // Multi-bounce glossy + diffuse showcase: chrome-gold sphere, glossy floor, diffuse walls & moving neon rings vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.82, 1.0); // glossy slate floor float dC = 1.05 - p.y; if (dC < res.x) res = vec2(dC, 2.0); float dB = p.z + 1.45; if (dB < res.x) res = vec2(dB, 2.0); float dL = p.x + 1.35; if (dL < res.x) res = vec2(dL, 2.0); float dR = 1.35 - p.x; if (dR < res.x) res = vec2(dR, 2.0); // Glossy metallic sphere + brushed copper cylinder (hard for diffuse-only ReSTIR GI, solved by ReSTIR PT!) float dSph = length(p - vec3(-0.36, -0.40, -0.22)) - 0.42; if (dSph < res.x) res = vec2(dSph, 3.0); float dCyl = max(length(p.xz - vec2(0.54, -0.35)) - 0.28, abs(p.y + 0.34) - 0.48); if (dCyl < res.x) res = vec2(dCyl, 4.0); // Emissive accent bars float dE1 = sdBox(p - vec3(-1.30, 0.32, -0.20), vec3(0.04, 0.42, 0.08)); if (dE1 < res.x) res = vec2(dE1, 5.0); float dE2 = sdBox(p - vec3(1.30, 0.25, -0.30), vec3(0.04, 0.42, 0.08)); if (dE2 < res.x) res = vec2(dE2, 6.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Evaluate glossy + diffuse multi-bounce target radiance (simulating ReSTIR PT hybrid shift mapping) vec3 evalFullPath(vec3 p, vec3 n, vec3 v, float rough, float t) { vec3 e1 = vec3(-1.26, 0.32 + 0.14 * sin(t * 0.9), -0.20); vec3 e2 = vec3(1.26, 0.25 + 0.14 * cos(t * 0.8), -0.30); vec3 e3 = vec3(0.0, 0.96, -0.65); vec3 c1 = vec3(0.18, 1.35, 1.95); vec3 c2 = vec3(1.95, 0.35, 0.95); vec3 c3 = vec3(1.75, 1.25, 0.45); float specExp = mix(72.0, 6.0, clamp(rough, 0.05, 0.85)); vec3 rad = vec3(0.0); vec3 d1 = e1 - p; float r1 = length(d1); vec3 l1 = d1 / max(r1, 1e-4); float s1 = pow(max(dot(n, normalize(l1 + v)), 0.0), specExp) * (0.25 + 1.25 * (1.0 - rough)); rad += c1 * (max(dot(n, l1), 0.0) * 0.42 + s1) / (0.35 + r1 * r1 * 0.65); vec3 d2 = e2 - p; float r2 = length(d2); vec3 l2 = d2 / max(r2, 1e-4); float s2 = pow(max(dot(n, normalize(l2 + v)), 0.0), specExp) * (0.25 + 1.25 * (1.0 - rough)); rad += c2 * (max(dot(n, l2), 0.0) * 0.42 + s2) / (0.35 + r2 * r2 * 0.65); vec3 d3 = e3 - p; float r3 = length(d3); vec3 l3 = d3 / max(r3, 1e-4); float s3 = pow(max(dot(n, normalize(l3 + v)), 0.0), specExp * 0.7) * (0.2 + 0.9 * (1.0 - rough)); rad += c3 * (max(dot(n, l3), 0.0) * 0.36 + s3) / (0.45 + r3 * r3 * 0.65); return rad; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isPT = screenX >= split; float rough = clamp(P_ROUGHNESS, 0.06, 0.75); float reuse = clamp(P_REUSE_STR, 0.0, 1.0); float gain = clamp(P_EMIT_GAIN, 0.2, 2.5); vec3 ro = vec3(0.0, 0.05, 2.38); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 v = -rd; if (matId > 4.5) { col = (matId < 5.5) ? vec3(0.32, 2.5, 3.6) : vec3(3.6, 0.55, 1.9); } else { vec3 alb = vec3(0.62, 0.65, 0.70); float matRough = rough; if (matId < 1.5) { alb = vec3(0.32, 0.35, 0.42); matRough = rough * 0.75; } else if (matId > 2.5 && matId < 3.5) { alb = vec3(0.95, 0.78, 0.42); matRough = rough * 0.55; } else if (matId > 3.5) { alb = vec3(0.86, 0.48, 0.36); matRough = rough * 0.65; } else { matRough = 0.78; } float ao = clamp(0.42 + 0.58 * mapScene(p + n * 0.24).x / 0.24, 0.2, 1.0); vec3 cleanPath = evalFullPath(p, n, v, matRough, iTime) * ao * gain; // Secondary glossy inter-reflection between metallic sphere & glossy floor vec3 rDir = reflect(rd, n); float specBounce = pow(max(rDir.y * 0.5 + 0.5, 0.0), 2.5) * (1.0 - matRough) * 0.35; cleanPath += mix(vec3(0.18, 0.85, 1.15), vec3(1.15, 0.32, 0.75), smoothstep(-0.6, 0.6, rDir.x)) * specBounce * gain; if (!isPT) { // Left: 1-spp path tracing struggles heavily on glossy multi-bounce paths (intense fireflies!) vec2 rnd = hash22(floor(fragCoord * 0.75) + fract(iTime * 7.1) * 29.3); float hitP = smoothstep(0.48, 0.92, rnd.x); float firefly = pow(rnd.y, 5.5) * 6.5 * (1.15 - matRough * 0.6); vec3 sparkCol = (rnd.x < 0.5) ? vec3(0.25, 1.35, 1.95) : vec3(1.95, 0.42, 0.98); col = alb * (cleanPath * (0.22 + 1.55 * hitP) + sparkCol * firefly * 0.45); } else { // Right: ReSTIR PT Generalized Resampled Importance Sampling (GRIS) with hybrid shift mapping float resNoise = (hash21(floor(fragCoord) + fract(iTime * 4.3) * 19.0) - 0.5) * 0.22 * (1.0 - reuse * 0.90); col = alb * cleanPath * (1.0 + resNoise); } } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [ReSTIR GI: Path Resampling for Real-Time Path Tracing](https://texelatlas.vercel.app/t/restir-gi.md) ## Combines with - [Practical Path Guiding](https://texelatlas.vercel.app/t/path-guiding.md): Better initial candidate paths from a learned guiding distribution raise the quality of every reservoir. ## Combination ideas - [ReSTIR path-traced relighting on 2D Gaussian surfels](https://texelatlas.vercel.app/ideas/surfel-splats-restir-path-tracing/) ## Sources 1. [primary] Daqi Lin, Markus Kettunen, Benedikt Bitterli, Jacopo Pantaleoni, Cem Yuksel, Chris Wyman (2022) Generalized resampled importance sampling. ACM Transactions on Graphics. https://doi.org/10.1145/3528223.3530158 (verified via crossref on 2026-11-29) 2. [implementation] DQLin (2022) DQLin/ReSTIR_PT. https://github.com/DQLin/ReSTIR_PT License: BSD-3-Clause. (verified via github on 2026-11-29) ## Cite this entry Texel. "ReSTIR PT and Generalized Resampled Importance Sampling." https://texelatlas.vercel.app/t/restir-pt/ (accessed 2026-12-01). --- id: "reverse-z-depth-buffer" title: "Reverse-Z and floating-point depth buffers" aliases: [reversed-Z, reverse Z, infinite far plane depth] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2008 inputs: [mesh] outputs: [depth] style: "both" dynamic: "both" cost: "cheap" authority: "Reed" url: "https://texelatlas.vercel.app/t/reverse-z-depth-buffer/" sources_verified_at: "2026-11-29" --- # Reverse-Z and floating-point depth buffers (Reed) > Map the near plane to depth 1 and the far plane to 0 and store depth in a float format, so floating-point density cancels the hyperbolic skew of perspective depth and precision becomes almost uniform. ## Reach for it when - distant surfaces flicker and z-fight - depth precision is poor with large far plane - stripes where two coplanar surfaces overlap in the distance - need very small near plane without artifacts - large open world has depth buffer artifacts ## How it works A standard perspective projection stores depth that is 1/z-like, packing most representable values near the camera. A float format does the opposite: it has most of its precision near zero. Using the usual convention (near=0, far=1) stacks both biases at the same end and wastes the float's strength. Reverse-Z flips the mapping: the projection matrix is altered so the near plane lands at 1 and far at 0 (often with the far plane at infinity, which simplifies the matrix), the depth clear value becomes 0, and the depth test becomes greater-or-equal. Now the 1/z crowding near the camera lines up with the float's dense region near 0 only at far distances, and the two nonlinearities roughly cancel. On APIs with clip space z in [-1,1] (OpenGL) you must also change the clip control or use a [0,1] range, otherwise the gain is lost. ## When to use it Choose it whenever you render large view distances, a tiny near plane, or see distant z-fighting; it is a near-free change that pairs with a D32F or D24-float depth target. Prefer a logarithmic depth write only on hardware where you cannot change depth format or projection and can accept losing early-Z. It also matters for [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) and [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md), where light-space depth range is large. ## Cost cheap — No extra passes; a float depth format may cost more memory than D24 but runs at the same speed on modern GPUs. Measured GPU Weight: 3× baseline (light) — 0.0943 ms median / 0.0964 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.68× baseline (light) — 0.0423 ms median (2.23× faster on L4). Ampere A100 scaling: 1.89× baseline (feather) — 0.0543 ms median (1.74× faster on A100). ## Failure modes - OpenGL's [-1,1] clip range cancels the benefit unless glClipControl/ZERO_TO_ONE is used - Forgetting to flip the clear value, depth func or depth-bias sign causes everything to vanish or render inverted - Integer D24/D16 targets gain nothing; the float format is required - Shaders that reconstruct view position from depth, or Hi-Z and SSAO passes, silently break if still written for forward Z - Depth bias and slope-scale values tuned for forward Z need retuning ## Engine support - babylonjs: builtin — `engine.useReverseDepthBuffer = true` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Engines/abstractEngine.pure.ts, checked 2026-12-01) - godot: builtin — `Always on in the RenderingDevice renderers (Forward+, Mobile)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ProjectSettings.xml, checked 2026-12-01) — Reversed Z since 4.3. - metal: builtin — `MTLPixelFormat.depth32Float + MTLDepthStencilDescriptor.depthCompareFunction = .greater` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlpixelformat.json, checked 2026-12-01) — Primitives only; the reversed projection matrix is yours. - threejs: builtin — `new THREE.WebGLRenderer({ reversedDepthBuffer: true })` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/renderers/WebGLRenderer.js, checked 2026-12-01) - unity: builtin — `Automatic on supported platforms; shader macro UNITY_REVERSED_Z` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/SL-PlatformDifferences.html, checked 2026-12-01) - unreal: builtin — `Reversed-Z floating-point depth buffer (FReversedZPerspectiveMatrix / SceneDepth across UE render paths)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/depth-material-expressions-in-unreal-engine, checked 2026-12-01) - webgpu: builtin — `format: 'depth32float' with depthStencil.depthCompare: 'greater' and depth clear value 0` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Primitives only; the reversed projection matrix is yours. ## Dataflow - Inputs: mesh - Outputs: depth - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Reverse-Z depth buffer — forward [0,1] distant z-fighting (left) vs float32 reverse-Z [1,0] (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_DEPTH_BITS": 12, "P_PLANE_GAP": 0.04, "P_SPLIT": 0.5, "P_CAM_SPEED": 1 } ``` ```glsl const float P_DEPTH_BITS = 12.0; // P Mantissa Bits [8.0, 16.0, 1.0] const float P_PLANE_GAP = 0.04; // P Coplanar Gap [0.005, 0.12, 0.005] const float P_SPLIT = 0.5; // P Fwd / Rev-Z Split [0.0, 1.0, 0.02] const float P_CAM_SPEED = 1.0; // P Glide Speed [0.0, 2.5, 0.05] // Quantize a value x in [0,1] to a simulated floating-point representation with mBits mantissa bits float quantFloat(float x, float mBits) { float ax = max(x, 1e-6); float e = floor(log2(ax)); float stepSz = exp2(e - mBits); return floor(ax / stepSz + 0.5) * stepSz; } // Forward-Z NDC depth: z_ndc = (f / (f - n)) * (1 - n / z) -> crowds near 1.0 where float step is huge! float forwardZ(float z, float nearP, float farP, float mBits) { float ndc = clamp((farP / (farP - nearP)) * (1.0 - nearP / max(z, nearP)), 0.0, 1.0); return quantFloat(ndc, mBits); } // Reverse-Z NDC depth: z_ndc = (n / (f - n)) * (f / z - 1) -> approaches 0.0 where float exponents pack densely! float reverseZ(float z, float nearP, float farP, float mBits) { float ndc = clamp((nearP / (farP - nearP)) * (farP / max(z, nearP) - 1.0), 0.0, 1.0); return quantFloat(ndc, mBits); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float screenY = fragCoord.y / max(iResolution.y, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float mBits = clamp(P_DEPTH_BITS, 7.0, 17.0); float gap = clamp(P_PLANE_GAP, 0.004, 0.15); float tAnim = iTime * max(P_CAM_SPEED, 0.0); float nearP = 0.25; float farP = 180.0; // Perspective runway looking down a long architectural corridor with closely layered decals vec3 ro = vec3(0.0, 1.85, tAnim * 2.2); vec3 rd = normalize(vec3(uv.x, uv.y - 0.18, -1.35)); vec3 col = mix(vec3(0.04, 0.06, 0.11), vec3(0.11, 0.16, 0.26), smoothstep(-0.1, 0.65, rd.y)); // Intersect primary floor (y = 0) and slightly raised coplanar marking plane (y = gap) if (rd.y < -0.004) { float tFloor = -ro.y / rd.y; float tDecal = -(ro.y - gap) / rd.y; if (tFloor > nearP && tFloor < farP) { vec3 pF = ro + rd * tFloor; vec3 pD = ro + rd * tDecal; // View-space depth Z along camera forward axis (-z) float zF = tFloor * (-rd.z); float zD = tDecal * (-rd.z); // Floor checkerboard pattern & bright amber/cyan runway chevrons on the raised decal plane vec2 fGrid = floor(pF.xz * 0.45); float chk = mod(fGrid.x + fGrid.y, 2.0); vec3 floorCol = mix(vec3(0.16, 0.20, 0.27), vec3(0.25, 0.30, 0.38), chk); float laneX = abs(pD.x); float chevron = sin(pD.z * 1.15 - laneX * 1.4); float isDecal = step(laneX, 3.6) * step(0.15, chevron); vec3 decalCol = mix(vec3(0.98, 0.62, 0.14), vec3(0.14, 0.88, 0.94), step(1.6, laneX)); // Tiny sub-pixel perspective jitter amplifies hardware triangle-interpolation rounding ties float jitter = sin(fragCoord.x * 0.71 + fragCoord.y * 1.13 + iTime * 2.4) * 0.5; float zF_j = zF + jitter * gap * 0.35; float zD_j = zD - jitter * gap * 0.35; bool useReverse = screenX >= split; bool decalWins; if (!useReverse) { // Standard Forward-Z: smaller depth wins, but quantization ties cause severe z-fighting! float qF = forwardZ(zF_j, nearP, farP, mBits); float qD = forwardZ(zD_j, nearP, farP, mBits); decalWins = (qD < qF) || (qD == qF && fract(sin(dot(floor(fragCoord * 0.5), vec2(12.98, 78.23))) * 43758.5) > 0.5); } else { // Reverse-Z: larger depth wins, and float32 exponent scaling resolves tiny gaps cleanly! float qF = reverseZ(zF_j, nearP, farP, mBits); float qD = reverseZ(zD_j, nearP, farP, mBits); decalWins = (qD > qF); } vec3 surf = (isDecal > 0.5 && decalWins) ? decalCol : floorCol; // Highlight z-fighting quantization tie zones on the Forward-Z side in hot crimson if (!useReverse && isDecal > 0.5 && forwardZ(zF, nearP, farP, mBits) == forwardZ(zD, nearP, farP, mBits)) { surf = mix(surf, vec3(1.0, 0.18, 0.32), 0.35); } // Distance fog & runway rim guide lines float rail = smoothstep(0.12, 0.03, abs(abs(pF.x) - 3.85)); surf = mix(surf, vec3(0.85, 0.92, 1.0), rail * 0.65); float fog = exp(-tFloor * 0.018); col = mix(vec3(0.06, 0.09, 0.15), surf, fog); } } // Bottom precision-graph HUD strip comparing ULP resolution vs log-distance for Forward-Z vs Reverse-Z if (screenY < 0.17) { float hy = screenY / 0.17; col = mix(col, vec3(0.03, 0.04, 0.07), 0.86); float zTest = mix(nearP, farP, pow(screenX, 2.2)); // Relative precision (log10 of resolvable delta-z): Forward-Z collapses, Reverse-Z stays flat! float fwdPrec = clamp(1.0 - log2(max(zTest * zTest / (nearP * farP * 0.25), 1.0)) / 10.0, 0.06, 0.92); float revPrec = clamp(0.86 - 0.08 * log2(max(zTest / nearP, 1.0)) / 9.0, 0.12, 0.92); float lineF = smoothstep(0.055, 0.012, abs(hy - fwdPrec)); float lineR = smoothstep(0.055, 0.012, abs(hy - revPrec)); col = mix(col, vec3(1.0, 0.30, 0.36), lineF); col = mix(col, vec3(0.18, 0.94, 0.72), lineR); float topBorder = smoothstep(0.95, 0.99, hy); col = mix(col, vec3(0.35, 0.45, 0.60), topBorder); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): The depth pyramid built from a reverse-Z buffer keeps distant occluders precise, so conservative max/min reductions stay valid. ## Sources 1. [primary] Nathan Reed Visualizing Depth Precision. developer.nvidia.com. https://developer.nvidia.com/blog/visualizing-depth-precision (verified via http on 2026-11-29) 2. [tutorial] Nathan Reed Depth Precision Visualized. reedbeta.com. https://www.reedbeta.com/blog/depth-precision-visualized (verified via http on 2026-11-29) ## Cite this entry Texel. "Reverse-Z and floating-point depth buffers." https://texelatlas.vercel.app/t/reverse-z-depth-buffer/ (accessed 2026-12-01). --- id: "rignet-neural-rigging" title: "RigNet automatic character rigging" aliases: [RigNet, neural rigging] domain: "genai" stage: "generation" realtime: "interactive" platforms: [python, cuda] year_introduced: 2020 inputs: [mesh] outputs: [skeleton, mesh] style: "both" dynamic: "static" cost: "offline" authority: "Xu et al., 2020" url: "https://texelatlas.vercel.app/t/rignet-neural-rigging/" sources_verified_at: "2026-11-29" --- # RigNet automatic character rigging (Xu et al., 2020) > Predicts an animation skeleton and skinning weights for an arbitrary character mesh with graph neural networks, so a static model can be posed without manual rigging. ## Reach for it when - generated character mesh has no skeleton - automatically rig a model without manual bone placement - need skinning weights predicted for an arbitrary mesh - auto rig animal or creature meshes for animation - skeleton prediction for scanned or ai generated characters ## How it works The pipeline has three learned steps working directly on the mesh graph. First, a graph network (using a tessellation-aware edge convolution over the mesh and its connectivity) predicts for each vertex a displacement toward the nearest joint position and an attention weight, so that vertices vote for joint locations; mean-shift clustering of these shifted points yields a joint set. Second, a second network scores every candidate pair of joints as a bone, learning from mesh and geometry features, and a minimum spanning tree selects a single rooted hierarchy. Third, a skinning network predicts the weights of each vertex for nearby bones with geodesic and volumetric cues from the mesh, normalised so weights sum to one. A user-supplied parameter, a bone-density control, adjusts the number of joints. The output is a standard skeleton plus per-vertex weights suitable for [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md). ## When to use it Choose it to bootstrap a rig for generated or scanned humanoid, animal and creature meshes, as the step after image/text-to-3D models, then hand-correct. Prefer manual or template rigging for hero characters and facial setups, [Dual quaternion skinning](https://texelatlas.vercel.app/t/dual-quaternion-skinning.md) if volume-preserving twists matter, and [Motion matching](https://texelatlas.vercel.app/t/motion-matching.md) or IK solvers such as [FABRIK inverse kinematics](https://texelatlas.vercel.app/t/fabrik-ik.md) once the rig exists. ## Cost offline — Seconds per mesh on a GPU; not part of a frame loop. ## Failure modes - Wrong joint count or topology on character classes absent from the training data (e.g. unusual limb counts) - Skinning weight leakage across nearby limbs or fingers, causing candy-wrapper pinching or spikes when posed - Skeleton alignment with the mesh is approximate; joints can drift off the medial axis - Requires watertight, reasonably clean meshes; meshes with disconnected parts degrade results - Repository is GPL-3.0, which constrains reuse inside closed-source tools ## Dataflow - Inputs: mesh - Outputs: skeleton, mesh - Platforms: python, cuda ## Combines with - [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md): The predicted skeleton and per-vertex weights are consumed directly by skinning to deform the mesh. - [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md): Generated image-to-3D meshes lack rigs; RigNet adds a skeleton and weights for animation. ## Sources 1. [primary] Zhan Xu, Yang Zhou, Evangelos Kalogerakis, Chris Landreth, Karan Singh (2020) RigNet: Neural Rigging for Articulated Characters. arXiv preprint (cs.GR). https://arxiv.org/abs/2005.00559 (verified via arxiv on 2026-11-29) 2. [implementation] zhan-xu (2020) zhan-xu/RigNet. https://github.com/zhan-xu/RigNet License: GPL-3.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "RigNet automatic character rigging." https://texelatlas.vercel.app/t/rignet-neural-rigging/ (accessed 2026-12-01). --- id: "rotation-minimizing-frames" title: "Rotation-Minimizing Frames" domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, blender, unity] year_introduced: 2008 inputs: [curves] outputs: [mesh, normals] style: "both" dynamic: "both" cost: "cheap" authority: "Wang et al., 2008" url: "https://texelatlas.vercel.app/t/rotation-minimizing-frames/" sources_verified_at: "2026-11-29" --- # Rotation-Minimizing Frames (Wang et al., 2008) > Builds a frame (tangent, normal, binormal) along a 3D curve that twists as little as possible, so tubes, ribbons and sweeps do not flip or spin. Computed with the double-reflection method. ## Reach for it when - tube or ribbon along a curve twists or flips - cables and roads spin unexpectedly along splines - camera on a path rolls unpredictably - need stable orientation for sweeping geometry along a curve ## How it works The Frenet frame uses curvature direction as the normal, which flips at inflection points and is undefined on straight segments. A rotation-minimizing frame keeps the normal as close to parallel transport as possible. The double reflection method does this iteratively from sampled points: given frame i with tangent t_i and normal r_i, reflect through the plane perpendicular to the chord between point i and i+1, then reflect again through the plane that maps the reflected tangent to the next tangent. The two reflections yield r_{i+1} with almost no extra twist and fourth-order accuracy. Closed curves need a residual twist correction distributed along the curve so the end frame matches the start. Sweeping a profile along these frames produces tubes and extrusions. ## When to use it Choose it for tubes, cables, roads, plant stems and camera paths along a spline where you want stable orientation. Prefer a Frenet frame only for planar curves with consistent curvature, and an explicit up-vector or user-set twist keyframes when the artist needs control of roll, such as roller coaster rails. ## Cost cheap — Constant work per sample point; two reflections. Measured GPU Weight: 47.85× baseline (heavy) — 1.5742 ms median / 1.7003 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 35.58× baseline (heavy) — 0.5658 ms median (2.78× faster on L4). Ampere A100 scaling: 27.54× baseline (heavy) — 0.7931 ms median (1.98× faster on A100). ## Failure modes - Parallel transport accumulates twist on closed curves, leaving a seam unless corrected - Frames are path-dependent: reversing the curve gives different frames - Coarse sampling at high curvature loses accuracy - Cannot satisfy a required roll such as a banked rail without a twist function ## Engine support - babylonjs: builtin — `new BABYLON.Path3D(points) computes smooth tangent, normal, and binormal frames along a 3D curve` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Maths/math.path.ts, checked 2026-12-01) - godot: builtin — `Curve3D.up_vector_enabled = true (Curve3D::_bake computes a Parallel Transport Frame along baked points)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/scene/resources/curve.cpp, checked 2026-12-01) - threejs: builtin — `curve.computeFrenetFrames(segments, closed)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/extras/core/Curve.js, checked 2026-12-01) — Parallel-transport frames, used by TubeGeometry. ## Dataflow - Inputs: curves - Outputs: mesh, normals - Platforms: cpu, webgl2, webgpu, desktop-gpu, blender, unity ## Presets ### Rotation-minimizing frames (left) vs Frenet normals (right) along a space curve (glsl-fragment; rendered 2026-11-29) ```json { "STEPS": 56, "RIB": 0.07 } ``` ```glsl // Frames along a space curve (orthographic view): left = double-reflection rotation-minimizing frame, right = Frenet normals. const int STEPS = 56; const float RIB = 0.07; vec3 curve(float s) { return vec3(cos(s), sin(s), 0.55 * sin(3.0 * s)); } vec3 tang(float s) { return normalize(vec3(-sin(s), cos(s), 1.65 * cos(3.0 * s))); } vec3 acc(float s) { return vec3(-cos(s), -sin(s), -4.95 * sin(3.0 * s)); } vec2 proj(vec3 p) { return vec2(p.x * 0.866 - p.y * 0.5, p.z * 0.9 + (p.x * 0.5 + p.y * 0.866) * 0.45); } float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; bool R = uv.x < 0.5; vec2 q = (vec2(fract(uv.x * 2.0), uv.y) - 0.5) * 3.0 * vec2(1.0, 1.0) / 1.25; float dc = 1e9, dr = 1e9; float hue = 0.0; vec3 x0 = curve(0.0), t0 = tang(0.0); vec3 r0 = normalize(cross(t0, vec3(0, 0, 1))); vec2 prev = proj(x0); for (int i = 1; i <= STEPS; i++) { float s = 6.2831853 * float(i) / float(STEPS); vec3 x1 = curve(s), t1 = tang(s); vec3 v1 = x1 - x0; float c1 = dot(v1, v1); vec3 rL = r0 - (2.0 / c1) * dot(v1, r0) * v1, tL = t0 - (2.0 / c1) * dot(v1, t0) * v1; vec3 v2 = t1 - tL; float c2 = dot(v2, v2); vec3 r1 = c2 > 1e-9 ? rL - (2.0 / c2) * dot(v2, rL) * v2 : rL; vec3 a = acc(s); vec3 nf = normalize(a - dot(a, t1) * t1); vec3 nn = R ? r1 : nf; vec2 p1 = proj(x1); dc = min(dc, segd(q, prev, p1)); float dd = segd(q, p1 - proj(nn * RIB), p1 + proj(nn * RIB)); if (dd < dr) { dr = dd; hue = float(i) / float(STEPS); } prev = p1; x0 = x1; t0 = t1; r0 = r1; } vec3 col = vec3(0.05, 0.06, 0.09) + 0.03 * uv.y; col = mix(col, vec3(0.8), smoothstep(0.012, 0.006, dc)); vec3 rc = 0.5 + 0.5 * cos(6.2831 * (hue + vec3(0.0, 0.33, 0.67))); col = mix(col, rc, smoothstep(0.009, 0.005, dr)); col = mix(col, vec3(1.0), smoothstep(0.003, 0.0, abs(uv.x - 0.5))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): Sweep tubes into a volume or SDF and re-mesh with marching cubes for unions of tubes. - [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md): The swept tube grid can be a subdivision cage. ## Combination ideas - [Overgrown grammar cities](https://texelatlas.vercel.app/ideas/ivy-on-grammar-architecture/) ## Sources 1. [primary] Wenping Wang, Bert Jüttler, Dayue Zheng, Yang Liu (2008) Computation of rotation minimizing frames. ACM Transactions on Graphics. https://doi.org/10.1145/1330511.1330513 (verified via crossref on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Rotation-Minimizing Frames." https://texelatlas.vercel.app/t/rotation-minimizing-frames/ (accessed 2026-12-01). --- id: "sah-bvh-construction" title: "SAH BVH construction" aliases: [SAH BVH, surface area heuristic] domain: "performance" stage: "performance" realtime: "offline" platforms: [cpu, cuda, desktop-gpu, webgpu] year_introduced: 1990 inputs: [mesh] outputs: [graph] style: "both" dynamic: "static" cost: "offline" authority: "MacDonald & Booth, 1990" url: "https://texelatlas.vercel.app/t/sah-bvh-construction/" sources_verified_at: "2026-11-29" --- # SAH BVH construction (MacDonald & Booth, 1990) > Build a bounding volume hierarchy by choosing each split to minimise the expected ray traversal cost, estimated from child surface areas and primitive counts. ## Reach for it when - ray tracing is slow because of poor acceleration structure - need fastest traversal for a static scene - bvh quality is bad from simple splits - reduce ray-box tests per ray - build a high-quality tree once for a fixed model ## How it works A ray hits a box with probability proportional to its surface area. For a candidate split, cost is traversal overhead plus sum over children of area times primitive count, normalised by parent area. The builder tests candidate planes, often binned along each axis, and picks the lowest cost, or makes a leaf if splitting is worse. Binned SAH avoids sorting by using fixed buckets; sweeps give exact splits. The tree gives faster rays than median or object splits, at higher build cost. ## When to use it Choose it for static scenes where tracing speed matters. Prefer LBVH or Morton-code builders for fast per-frame rebuilds of dynamic scenes, then refit. Prefer refit alone for small deformations. ## Cost offline — Build cost is higher than spatial-median builders; traversal gets cheaper. Measured GPU Weight: 13.32× baseline (moderate) — 0.4181 ms median / 0.434 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 12.54× baseline (moderate) — 0.1981 ms median (2.11× faster on L4). Ampere A100 scaling: 8.66× baseline (moderate) — 0.2495 ms median (1.68× faster on A100). ## Failure modes - Slow builds for millions of primitives - Overlapping boxes from large triangles make SAH ineffective without splitting - Cost constants assumed by SAH rarely match the real hardware - Refit degrades quality as geometry deforms ## Engine support - blender: builtin — `Cycles CPU/GPU acceleration structure builder uses Surface Area Heuristic (SAH) splitting in intern/cycles/bvh/build.cpp` (evidence: https://github.com/blender/blender/blob/main/intern/cycles/bvh/build.cpp, checked 2026-12-01) - godot: builtin — `Internal dynamic BVH spatial acceleration structure (core/math/bvh_tree.h)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/core/math/bvh_tree.h, checked 2026-12-01) - metal: builtin — `MTLPrimitiveAccelerationStructureDescriptor + MTLAccelerationStructureCommandEncoder.build(...)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlprimitiveaccelerationstructuredescriptor.json, checked 2026-12-01) - threejs: plugin — `npm i three-mesh-bvh; new MeshBVH(geometry, { strategy: SAH })` (evidence: https://github.com/gkjohnson/three-mesh-bvh/blob/master/API.md, checked 2026-12-01) - unreal: builtin — `Project Settings > Rendering > Hardware Ray Tracing (builds GPU TLAS/BLAS acceleration structures for Lumen, Reflections, and Path Tracer)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/hardware-ray-tracing-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: graph - Platforms: cpu, cuda, desktop-gpu, webgpu ## Presets ### SAH BVH construction — tight surface-area-heuristic bounding hierarchy & ray traversal heatmap (glsl-fragment; rendered 2026-11-30) ```json { "P_BVH_DEPTH": 3, "P_HEATMAP_MIX": 0.65, "P_RAY_SWEEP": 1, "P_SHOW_BOXES": 1 } ``` ```glsl const float P_BVH_DEPTH = 3.0; // P BVH Depth [1.0, 4.0, 1.0] const float P_HEATMAP_MIX = 0.65; // P Step Heatmap [0.0, 1.2, 0.04] const float P_RAY_SWEEP = 1.0; // P Ray Sweep [0.0, 2.5, 0.05] const float P_SHOW_BOXES = 1.0; // P AABB Boxes [0.0, 1.5, 0.05] float sdBox2(vec2 p, vec2 bMin, vec2 bMax) { vec2 c = 0.5 * (bMin + bMax); vec2 h = 0.5 * (bMax - bMin); vec2 q = abs(p - c) - h; return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0); } // 2D ray-AABB slab intersection returning vec2(tNear, tFar) vec2 intersectBox2(vec2 ro, vec2 rd, vec2 bMin, vec2 bMax) { vec2 invD = 1.0 / (rd + sign(rd + 1e-6) * 1e-5); vec2 t0 = (bMin - ro) * invD; vec2 t1 = (bMax - ro) * invD; vec2 tmin = min(t0, t1); vec2 tmax = max(t0, t1); return vec2(max(tmin.x, tmin.y), min(tmax.x, tmax.y)); } float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } vec3 heatPalette(float x) { x = clamp(x, 0.0, 1.0); vec3 c0 = vec3(0.04, 0.07, 0.16); vec3 c1 = vec3(0.08, 0.44, 0.68); vec3 c2 = vec3(0.95, 0.62, 0.14); vec3 c3 = vec3(1.00, 0.96, 0.72); if (x < 0.35) return mix(c0, c1, x / 0.35); if (x < 0.72) return mix(c1, c2, (x - 0.35) / 0.37); return mix(c2, c3, (x - 0.72) / 0.28); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tAnim = iTime * max(P_RAY_SWEEP, 0.0); float maxDepth = floor(clamp(P_BVH_DEPTH, 1.0, 4.0)); float heatMix = clamp(P_HEATMAP_MIX, 0.0, 1.3); float boxVis = clamp(P_SHOW_BOXES, 0.0, 1.6); // Define 8 clustered scene discs grouped into 4 tight SAH leaf bounds, 2 mid bounds, 1 root bound vec2 cPos[8]; float cRad[8]; cPos[0] = vec2(-0.56, 0.22); cRad[0] = 0.055; cPos[1] = vec2(-0.42, 0.16); cRad[1] = 0.048; cPos[2] = vec2(-0.46, -0.22); cRad[2] = 0.060; cPos[3] = vec2(-0.26, -0.28); cRad[3] = 0.046; cPos[4] = vec2(0.24, 0.28); cRad[4] = 0.052; cPos[5] = vec2(0.40, 0.18); cRad[5] = 0.058; cPos[6] = vec2(0.32, -0.14); cRad[6] = 0.050; cPos[7] = vec2(0.56, -0.26); cRad[7] = 0.062; // Tight SAH-partitioned AABBs (minimizing perimeter*count = Surface Area Heuristic!) vec2 leafMin[4]; vec2 leafMax[4]; for (int k = 0; k < 4; k++) { vec2 a = cPos[k * 2]; float ra = cRad[k * 2]; vec2 b = cPos[k * 2 + 1]; float rb = cRad[k * 2 + 1]; leafMin[k] = min(a - vec2(ra), b - vec2(rb)) - vec2(0.015); leafMax[k] = max(a + vec2(ra), b + vec2(rb)) + vec2(0.015); } vec2 midMin[2]; vec2 midMax[2]; midMin[0] = min(leafMin[0], leafMin[1]) - vec2(0.018); midMax[0] = max(leafMax[0], leafMax[1]) + vec2(0.018); midMin[1] = min(leafMin[2], leafMin[3]) - vec2(0.018); midMax[1] = max(leafMax[2], leafMax[3]) + vec2(0.018); vec2 rootMin = min(midMin[0], midMin[1]) - vec2(0.022); vec2 rootMax = max(midMax[0], midMax[1]) + vec2(0.022); // Moving probe ray origin sweeping across the BVH from the left edge vec2 rayOrig = vec2(-0.82, 0.28 * sin(tAnim * 0.55)); float sweepAng = 0.36 * sin(tAnim * 0.85); vec2 rayDir = vec2(cos(sweepAng), sin(sweepAng)); // Evaluate pixel-space BVH traversal cost heatmap (number of AABBs containing or tested near pixel) float cost = 0.0; if (sdBox2(uv, rootMin, rootMax) < 0.0) cost += 1.0; if (maxDepth >= 2.0) { for (int m = 0; m < 2; m++) { if (sdBox2(uv, midMin[m], midMax[m]) < 0.0) cost += 1.5; } } if (maxDepth >= 3.0) { for (int l = 0; l < 4; l++) { if (sdBox2(uv, leafMin[l], leafMax[l]) < 0.0) cost += 2.2; } } if (maxDepth >= 4.0) { for (int i = 0; i < 8; i++) { if (sdBox2(uv, cPos[i] - vec2(cRad[i]), cPos[i] + vec2(cRad[i])) < 0.0) cost += 2.6; } } // Dark blueprint backdrop + traversal heatmap tint vec3 bg = vec3(0.032, 0.044, 0.068); vec2 grid = abs(fract(uv * 12.0 - 0.5) - 0.5); bg += vec3(0.02, 0.035, 0.055) * smoothstep(0.04, 0.005, min(grid.x, grid.y)); vec3 col = mix(bg, heatPalette(cost / 8.0), 0.58 * heatMix); // Test sweeping ray against BVH nodes to highlight traversed vs pruned subtrees vec2 hRoot = intersectBox2(rayOrig, rayDir, rootMin, rootMax); bool hitRoot = hRoot.y > max(hRoot.x, 0.0); // Draw Root AABB (Depth 1) if (boxVis > 0.01) { float dR = abs(sdBox2(uv, rootMin, rootMax)); vec3 rCol = hitRoot ? vec3(0.45, 0.72, 1.0) : vec3(0.24, 0.30, 0.42); col = mix(col, rCol, smoothstep(px * 3.0, px * 0.8, dR) * 0.85 * min(boxVis, 1.2)); } // Depth 2: Mid-level SAH split boxes bool hitMid[2]; for (int m = 0; m < 2; m++) { vec2 hm = intersectBox2(rayOrig, rayDir, midMin[m], midMax[m]); hitMid[m] = hitRoot && hm.y > max(hm.x, 0.0); if (maxDepth >= 2.0 && boxVis > 0.01) { float dm = abs(sdBox2(uv, midMin[m], midMax[m])); vec3 mCol = hitMid[m] ? vec3(0.22, 0.94, 0.74) : vec3(0.22, 0.34, 0.45); col = mix(col, mCol, smoothstep(px * 2.8, px * 0.7, dm) * (hitMid[m] ? 0.95 : 0.45) * min(boxVis, 1.2)); } } // Depth 3: Tight SAH Leaf boxes bool hitLeaf[4]; for (int l = 0; l < 4; l++) { int parent = l / 2; vec2 hl = intersectBox2(rayOrig, rayDir, leafMin[l], leafMax[l]); hitLeaf[l] = hitMid[parent] && hl.y > max(hl.x, 0.0); if (maxDepth >= 3.0 && boxVis > 0.01) { float dl = abs(sdBox2(uv, leafMin[l], leafMax[l])); vec3 lCol = hitLeaf[l] ? vec3(1.0, 0.78, 0.22) : vec3(0.26, 0.32, 0.40); col = mix(col, lCol, smoothstep(px * 2.6, px * 0.6, dl) * (hitLeaf[l] ? 0.98 : 0.42) * min(boxVis, 1.2)); } } // Ray-disc closest hit along the active sweeping ray float tClosest = 2.2; int hitPrim = -1; for (int i = 0; i < 8; i++) { int leaf = i / 2; if (!hitLeaf[leaf]) continue; vec2 oc = rayOrig - cPos[i]; float b = dot(oc, rayDir); float c = dot(oc, oc) - cRad[i] * cRad[i]; float disc = b * b - c; if (disc > 0.0) { float th = -b - sqrt(disc); if (th > 0.0 && th < tClosest) { tClosest = th; hitPrim = i; } } } // Draw primitives (highlighted if tested/hit, muted if pruned by BVH) for (int i = 0; i < 8; i++) { int leaf = i / 2; float dC = length(uv - cPos[i]) - cRad[i]; if (maxDepth >= 4.0 && boxVis > 0.01) { float dpb = abs(sdBox2(uv, cPos[i] - vec2(cRad[i]), cPos[i] + vec2(cRad[i]))); col = mix(col, vec3(0.95, 0.42, 0.32), smoothstep(px * 2.0, px * 0.5, dpb) * (hitLeaf[leaf] ? 0.85 : 0.25) * min(boxVis, 1.2)); } vec3 pCol = (i == hitPrim) ? vec3(1.0, 0.94, 0.52) : (hitLeaf[leaf] ? vec3(0.92, 0.52, 0.22) : vec3(0.28, 0.38, 0.52)); float fill = smoothstep(px * 1.5, -px * 1.5, dC); float rim = smoothstep(px * 3.0, px * 0.5, abs(dC)); col = mix(col, pCol * (0.75 + 0.35 * smoothstep(cRad[i], -cRad[i], uv.y - cPos[i].y)), fill); col = mix(col, pCol * 1.35, rim * 0.8); } // Draw sweeping probe ray & intersection spark vec2 rayEnd = rayOrig + rayDir * tClosest; float dRay = sdSegment(uv, rayOrig, rayEnd); col += vec3(0.25, 0.92, 1.0) * smoothstep(px * 5.0, px * 0.7, dRay) * 0.85; col += vec3(1.0, 0.98, 0.85) * smoothstep(0.022, 0.004, length(uv - rayOrig)); if (hitPrim >= 0) { col += vec3(1.0, 0.88, 0.38) * exp(-length(uv - rayEnd) * 32.0) * 1.4; } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): The library builds SAH or center trees and exposes raycasts and spatial queries. ## Sources 1. [primary] J. David MacDonald, Kellogg S. Booth (1990) Heuristics for ray tracing using space subdivision. The Visual Computer. https://doi.org/10.1007/bf01911006 (verified via crossref on 2026-11-29) 2. [implementation] gkjohnson (2018) gkjohnson/three-mesh-bvh. https://github.com/gkjohnson/three-mesh-bvh License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "SAH BVH construction." https://texelatlas.vercel.app/t/sah-bvh-construction/ (accessed 2026-12-01). --- id: "sam-3d-objects" title: "SAM 3D Objects" aliases: [SAM 3D] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [ldr-image] outputs: [mesh, gaussians, texture] style: "photoreal" dynamic: "static" cost: "heavy" authority: "Team et al., 2025" url: "https://texelatlas.vercel.app/t/sam-3d-objects/" sources_verified_at: "2026-11-29" --- # SAM 3D Objects (Team et al., 2025) > A generative model that takes a photo and an object mask and returns geometry, texture and the object's layout (pose and scale) in the scene, trained with a human-and-model-in-the-loop data engine. ## Reach for it when - extract 3d object from a single photo with mask - need geometry and pose of items in a cluttered image - reconstruct objects in the scene they appear in - turn segmented image regions into 3d assets ## How it works The user supplies an image and a mask for each object. The model predicts a coarse shape and pose first, then refines geometry and texture, so that the result sits in the camera frame with the right placement rather than in a canonical frame. Training combines synthetic pretraining with real-world alignment: annotators and models iteratively pick and correct candidate 3D shapes, textures and poses on natural images, which supplies visually grounded supervision at scale. Several masked objects from one photo can be generated and positioned together, making composed scene layouts possible. ## When to use it Choose it for in-the-wild photos with occlusion and clutter, where lab-style models trained on centred renders fail, and when object pose matters (AR placement, scene assembly). Prefer [TripoSR](https://texelatlas.vercel.app/t/triposr.md) or [InstantMesh](https://texelatlas.vercel.app/t/instantmesh.md) for clean product shots with a plain background, and [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) or [TRELLIS.2 (O-Voxel structured latents)](https://texelatlas.vercel.app/t/trellis-2.md) when PBR output is needed. Prefer [Marble (World Labs multimodal world model)](https://texelatlas.vercel.app/t/marble-world-model.md) for whole-scene generation. ## Cost heavy — Seconds per object on a GPU; the repo documents installation and hardware needs. ## Failure modes - Needs a reasonable mask; poor segmentation leaks background into the shape - Unseen sides are plausible guesses rather than metrically correct - Metric scale is inferred, not measured - Weights carry a custom licence (SPDX NOASSERTION) ## Dataflow - Inputs: ldr-image - Outputs: mesh, gaussians, texture - Platforms: cuda, python ## Sources 1. [primary] SAM 3D Team, Xingyu Chen, Fu-Jen Chu, Pierre Gleize, Kevin J Liang, Alexander Sax, Hao Tang, Weiyao Wang, Michelle Guo, Thibaut Hardin, Xiang Li, Aohan Lin, Jiawei Liu, Ziqi Ma, Anushka Sagar, Bowen Song, Xiaodong Wang, Jianing Yang, Bowen Zhang, Piotr Dollár, Georgia Gkioxari, Matt Feiszli, Jitendra Malik (2025) SAM 3D: 3Dfy Anything in Images. arXiv preprint (cs.CV). https://arxiv.org/abs/2511.16624 (verified via arxiv on 2026-11-29) 2. [implementation] facebookresearch (2025) facebookresearch/sam-3d-objects. https://github.com/facebookresearch/sam-3d-objects License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "SAM 3D Objects." https://texelatlas.vercel.app/t/sam-3d-objects/ (accessed 2026-12-01). --- id: "sam2" title: "SAM 2" aliases: [Segment Anything Model 2] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [photos] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Ravi et al., 2024" url: "https://texelatlas.vercel.app/t/sam2/" sources_verified_at: "2026-11-29" --- # SAM 2 (Ravi et al., 2024) > Extends Segment Anything to video with a streaming memory that propagates prompted masks across frames, also usable on image sets as a sequence. ## Reach for it when - need object masks across video frames - mask the same object in every turntable photo - propagate a prompted mask through ordered images - segmenting each frame separately flickers ## How it works Like SAM, SAM 2 has an image encoder, a prompt encoder and a mask decoder, but frames are processed as a stream. A memory bank stores embeddings of recent frames and of prompted frames along with predicted masks. Each new frame's features cross-attend to this memory through memory attention before decoding, so the mask follows the object across motion and short occlusions. Users can add corrective clicks on any frame, and the model updates the track. Images are treated as a one-frame video. Training combined a data engine with a large video segmentation dataset. A hierarchical image encoder makes the model faster than the original SAM at comparable image quality. ## When to use it Choose it to propagate object masks across video frames or ordered multi-view captures, e.g. to mask a turntable sequence for [Visual Hull (Shape from Silhouette)](https://texelatlas.vercel.app/t/visual-hull.md) or splat training. Prefer [Segment Anything (SAM)](https://texelatlas.vercel.app/t/segment-anything.md) for single unrelated images, and masks from 3D-aware methods when views are sparse and unordered. ## Cost medium — Real-time-ish per-frame on a modern GPU for small variants; memory use grows with the stored frame count. ## Failure modes - Identity switches when similar objects cross or after long occlusions - Drift on fast motion, motion blur or thin objects - Unordered or wide-baseline multi-view sets break the temporal-memory assumption - Boundary quality is limited for hair and transparent edges ## Dataflow - Inputs: photos - Outputs: visibility-mask - Platforms: cuda, python ## Lineage - extends [Segment Anything (SAM)](https://texelatlas.vercel.app/t/segment-anything.md) ## Sources 1. [primary] Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu, Ronghang Hu, Chaitanya Ryali, Tengyu Ma, Haitham Khedr, Roman Rädle, Chloe Rolland, Laura Gustafson, Eric Mintun, Junting Pan, Kalyan Vasudev Alwala, Nicolas Carion, Chao-Yuan Wu, Ross Girshick, Piotr Dollár, Christoph Feichtenhofer (2024) SAM 2: Segment Anything in Images and Videos. arXiv preprint (cs.CV). https://arxiv.org/abs/2408.00714 (verified via arxiv on 2026-11-29) 2. [implementation] facebookresearch (2024) facebookresearch/sam2. https://github.com/facebookresearch/sam2 License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "SAM 2." https://texelatlas.vercel.app/t/sam2/ (accessed 2026-12-01). --- id: "sample-distribution-shadow-maps" title: "Sample Distribution Shadow Maps (SDSM)" aliases: [SDSM] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [desktop-gpu, webgpu, unity, unreal] year_introduced: 2011 inputs: [depth, mesh] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Lauritzen et al., 2011" url: "https://texelatlas.vercel.app/t/sample-distribution-shadow-maps/" sources_verified_at: "2026-11-29" --- # Sample Distribution Shadow Maps (SDSM) (Lauritzen et al., 2011) > Analyses the depth buffer each frame to fit cascade split positions and light-space bounds tightly around the pixels that will actually sample the shadow map. ## Reach for it when - cascaded shadows waste resolution when looking at a wall - shadow quality changes a lot depending on view direction - cascade splits do not match the visible depth range - want tighter shadow map fitting around visible pixels - distant sun shadows blurry although camera sees little depth ## How it works Classic cascaded shadow maps place split planes with a fixed scheme and fit each cascade to the whole sub-frustum, wasting texels on empty space. SDSM first renders the scene depth and runs a GPU reduction to find the minimum and maximum visible view depth. It can then (a) set split planes from a logarithmic partition of that real range, or from a depth histogram, so cascades follow where pixels exist, and (b) for each cascade compute the tight light-space bounding box of just the visible samples, using min/max reductions of the projected positions. The resulting orthographic projections are read back or consumed by indirect dispatch, then used to render the maps. Snapping extents to texel increments keeps shadows stable under camera motion, and conservative expansion handles reduction latency. ## When to use it Choose it when [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) waste resolution because the visible depth range varies a lot, as in outdoor scenes that alternate between looking at a wall and looking at the horizon. Prefer [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md) when geometry density and uniform quality matter more than fitting, and keep plain stabilised CSM for mobile where an extra depth reduction is too costly. Pair with normal-offset bias from [Shadow map depth bias (constant, slope-scale, normal offset)](https://texelatlas.vercel.app/t/shadow-map-bias-slope-scale-normal-offset.md) per cascade. ## Cost medium — Adds a depth prepass and a compute reduction; the savings come from rendering smaller, tighter shadow maps. Cost is qualitative and scene dependent. Measured GPU Weight: 48.99× baseline (heavy) — 1.6119 ms median / 1.6824 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 55.66× baseline (heavy) — 0.885 ms median (1.82× faster on L4). Ampere A100 scaling: 32.78× baseline (heavy) — 0.9441 ms median (1.71× faster on A100). ## Failure modes - Shadow shimmering when cascade bounds change every frame without stabilisation or hysteresis - One-frame latency in bounds when reductions are read back, causing pop at fast camera turns - Tight fit excludes off-screen casters unless the near plane is extended toward the light - Depth outliers (sky, tiny particles) must be masked or the reduction loosens again ## Dataflow - Inputs: depth, mesh - Outputs: visibility-mask - Platforms: desktop-gpu, webgpu, unity, unreal ## Presets ### Sample Distribution Shadow Maps (SDSM) — fixed CSM wasted cascades & aliasing (left) vs depth-fitted tight SDSM cascades (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CASCADES": 4, "P_BAND_VIS": 0.55, "P_SUN_SWEEP": 0.5, "P_SPLIT": 0.48 } ``` ```glsl const float P_CASCADES = 4.00; // P Cascade Count [2.0, 5.0, 1.0] const float P_BAND_VIS = 0.55; // P Cascade Tint [0.0, 1.0, 0.05] const float P_SUN_SWEEP = 0.50; // P Sun Sweep [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Fixed CSM / SDSM [0.0, 1.0, 0.02] 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); } // Long architectural vista with foreground + mid-ground + distant monoliths and empty depth gap in between vec2 mapVista(vec3 p) { float dFloor = p.y + 0.55; vec2 res = vec2(dFloor, 1.0); // Repeating rows of tall monoliths along -Z for (int i = 0; i < 4; i++) { float z = -0.35 - float(i) * 1.35; float dL = sdBox(p - vec3(-0.62, 0.05, z), vec3(0.16, 0.60, 0.16)); float dR = sdBox(p - vec3(0.62, 0.05, z), vec3(0.16, 0.60, 0.16)); float dTop = sdBox(p - vec3(0.0, 0.58, z), vec3(0.80, 0.09, 0.16)); float dArch = min(min(dL, dR), dTop); if (dArch < res.x) res = vec2(dArch, 2.0); } return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapVista(p + e.xyy).x - mapVista(p - e.xyy).x, mapVista(p + e.yxy).x - mapVista(p - e.yxy).x, mapVista(p + e.yyx).x - mapVista(p - e.yyx).x )); } // Trace shadow ray from quantized shadow-map texel position to visualize real texel-resolution difference! float traceShadowAt(vec3 p, vec3 sunDir, float texelSize) { // Snap point onto light-space shadow-map texel grid of size texelSize vec3 lUp = vec3(0.0, 1.0, 0.0); vec3 lRight = normalize(cross(lUp, sunDir)); vec3 lOrtho = cross(sunDir, lRight); float u = floor(dot(p, lRight) / texelSize + 0.5) * texelSize; float v = floor(dot(p, lOrtho) / texelSize + 0.5) * texelSize; float w = dot(p, sunDir); vec3 pSnap = lRight * u + lOrtho * v + sunDir * w; float t = 0.05; for (int i = 0; i < 20; i++) { float h = mapVista(pSnap + sunDir * t).x; if (h < 0.005) return 0.0; t += max(h, 0.04); if (t > 4.0) break; } return 1.0; } vec3 cascadeColor(float idx) { if (idx < 0.5) return vec3(0.18, 0.92, 0.56); if (idx < 1.5) return vec3(0.20, 0.72, 1.0); if (idx < 2.5) return vec3(0.98, 0.78, 0.22); if (idx < 3.5) return vec3(0.98, 0.36, 0.32); return vec3(0.84, 0.38, 0.98); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float numCasc = clamp(floor(P_CASCADES + 0.5), 2.0, 5.0); float bandVis = clamp(P_BAND_VIS, 0.0, 1.0); float t = iTime * max(P_SUN_SWEEP, 0.0); vec3 ro = vec3(0.16 * sin(t * 0.4), 0.36, 2.20); vec3 rd = normalize(vec3(uv.x, uv.y - 0.10, -1.45)); vec3 sunDir = normalize(vec3(0.68 * cos(t * 0.35 + 0.4), 0.62, 0.38)); vec3 sky = mix(vec3(0.72, 0.80, 0.90), vec3(0.18, 0.42, 0.76), smoothstep(-0.08, 0.55, rd.y)); vec3 col = sky; float dist = 0.05; vec2 hit = vec2(12.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapVista(ro + rd * dist); if (h.x < 0.003) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 11.0) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); float viewZ = hit.x; float cascIdx = 0.0; float texelSz = 0.02; if (screenX < split) { // Left: Fixed naive CSM splits spanning [0.1 .. 24.0] -> wastes cascade 0 in empty air near camera, // forcing visible geometry into coarse cascades with blocky aliased shadows! float zFrac = clamp(log(max(viewZ, 0.1) / 0.1) / log(24.0 / 0.1), 0.0, 0.999); cascIdx = floor(zFrac * numCasc); texelSz = 0.032 * pow(1.75, cascIdx); } else { // Right: SDSM reduces actual visible depth bounds [zMin=1.6 .. zMax=8.2] each frame -> // tightly fits all cascades around real scene samples for 3-4x crisper shadow texels! float zMin = 1.55; float zMax = 8.40; float zFrac = clamp(log(max(viewZ, zMin) / zMin) / log(zMax / zMin), 0.0, 0.999); cascIdx = floor(zFrac * numCasc); texelSz = 0.008 * pow(1.42, cascIdx); } float sh = traceShadowAt(p + n * 0.01, sunDir, texelSz); vec3 alb = (hit.y < 1.5) ? vec3(0.74, 0.72, 0.68) : vec3(0.86, 0.82, 0.76); float ndl = max(dot(n, sunDir), 0.0); vec3 lit = alb * (vec3(0.20, 0.28, 0.42) + vec3(1.32, 1.18, 0.96) * ndl * sh); // Subtle cascade split band tint & boundary line vec3 cTint = cascadeColor(cascIdx); col = mix(lit, lit * (0.55 + 0.75 * cTint), bandVis * 0.48); col = mix(sky, col, exp(-viewZ * 0.06)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): The depth pyramid built for culling can provide the min/max depth the SDSM reduction needs. ## Sources 1. [primary] Andrew Lauritzen, Marco Salvi, Aaron Lefohn (2011) Sample distribution shadow maps. Symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/1944745.1944761 (verified via crossref on 2026-11-29) 2. [implementation] TheRealMJP (2016) TheRealMJP/Shadows. https://github.com/TheRealMJP/Shadows License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Sample Distribution Shadow Maps (SDSM)." https://texelatlas.vercel.app/t/sample-distribution-shadow-maps/ (accessed 2026-12-01). --- id: "schwarzschild-null-geodesic-lensing" title: "Schwarzschild Null-Geodesic Gravitational Lensing and Relativistic Accretion Disk" aliases: [black hole ray tracing, relativistic accretion disk rendering, Binet geodesic lensing, Schwarzschild photon ray marching] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda] year_introduced: 2015 inputs: [hdr-image, depth, texture] outputs: [hdr-image, radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "James et al., 2015" url: "https://texelatlas.vercel.app/t/schwarzschild-null-geodesic-lensing/" sources_verified_at: "2026-11-30" --- # Schwarzschild Null-Geodesic Gravitational Lensing and Relativistic Accretion Disk (James et al., 2015) > Integrate curved null-geodesic photon paths around a Schwarzschild mass per pixel, combining thin-lens background deflection with relativistic Doppler-beamed, gravitationally redshifted emission from a Keplerian accretion disk. ## Reach for it when - render a physically plausible black hole with photon ring and accretion disk - bend background starfields and environment maps around a gravity well - integrate curved light rays in curved spacetime on the gpu in real time - show top and bottom of an accretion disk simultaneously via gravitational lensing - avoid numerical spiral blowup near the event horizon when ray marching ## How it works Around a compact mass, light no longer follows straight rays. Each pixel near the hole steps a camera ray backward in Cartesian coordinates using the Binet null-geodesic acceleration $x'' = -\tfrac{3}{2} h^2 x / r^5$ (in units of the Schwarzschild radius $r_s$, with conserved angular momentum $h = |x \times v|$). Rays with impact parameter below the critical threshold $b_c = \tfrac{3\sqrt{3}}{2} r_s$ plunge into the event-horizon shadow, while rays grazing $b_c$ orbit partially around the hole to form a razor-sharp photon ring. Whenever a curved ray crosses the equatorial plane between the innermost stable circular orbit and the outer radius, the shader evaluates a thin, differentially rotating turbulent accretion disk. Emission follows a blackbody temperature profile ($T \propto r^{-3/4}$) shifted in both frequency and brightness ($I \propto g^4$) by the combined Keplerian Doppler factor and gravitational redshift, brightening and blue-shifting the approaching limb while dimming the receding side. Because rays bend over and beneath the shadow, the far side of the disk arches both above and below the black core. For embedded 3D scenes rather than skyboxes alone, a depth-gated weak-field thin-lens pass deflects background pixels behind the lens plane while keeping foreground geometry sharp and clamping lookups away from the hole's own silhouette. ## When to use it Choose it when rendering physically recognizable black holes, Einstein rings, or relativistic singularities in real-time VFX, space simulations, or cinematic visualization. Prefer [volume-ray-marching](volume-ray-marching) when rays travel in straight lines through ordinary nebulae, clouds, or gas without spacetime curvature. Prefer [sphere-tracing](sphere-tracing) for refractive or warped analytic SDF anomalies where general-relativistic disk crossings and photon rings are unnecessary. Prefer [lens-flare](lens-flare) for purely optical camera bloom and diffraction effects without scene deflection. ## Cost medium — Runs as a single fullscreen or bounding-region fragment pass whose cost scales with geodesic integration step count (typically 48–96 steps) and screen coverage of the black hole. Measured GPU Weight: 41.35× baseline (heavy) — 1.3604 ms median / 1.4432 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 38.84× baseline (heavy) — 0.6176 ms median (2.2× faster on L4). Ampere A100 scaling: 24.39× baseline (heavy) — 0.7025 ms median (1.94× faster on A100). ## Failure modes - Coarse integration steps near the photon sphere cause jagged or stepped aliasing along the critical photon ring and secondary disk images - Screen-space background deflection cannot reveal occluded geometry behind foreground objects and tears at depth discontinuities unless eased smoothly behind the lens plane - Extreme Doppler beaming ($g^4$) produces huge HDR spikes on the approaching side that clip harshly without wide-gamut tonemapping - Schwarzschild symmetry omits Kerr spin frame-dragging asymmetry and D-shaped shadows unless extended with full Kerr metric integration ## Dataflow - Inputs: hdr-image, depth, texture - Outputs: hdr-image, radiance - Platforms: webgl2, webgpu, desktop-gpu, cuda ## Presets ### Real-time Schwarzschild disk starting parameters (json-params; parameter preset) ```json { "geodesic_steps": 72, "isco_radius_rs": 3, "outer_disk_radius_rs": 13, "critical_impact_rs": 2.598, "inner_temp_kelvin": 6500, "kepler_speed_scale": 1 } ``` Attribution: written for this index ### Schwarzschild Null-Geodesic Lensing — flat Euclidean rays (left) vs curved spacetime photon ring & Doppler disk (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BH_MASS": 1, "P_DISK_INCL": 0.22, "P_DOPPLER_STR": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_BH_MASS = 1.00; // P Horizon Scale [0.6, 1.5, 0.05] const float P_DISK_INCL = 0.22; // P Disk Inclination [0.08, 0.55, 0.02] const float P_DOPPLER_STR = 0.85; // P Relativistic Beaming [0.0, 1.4, 0.05] const float P_SPLIT = 0.48; // P Flat / Geodesic Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Background galactic starfield & faint nebula sampled by asymptotic deflected photon direction d vec3 evalStarfield(vec3 d) { d = normalize(d); float phi = atan(d.z, d.x); float th = acos(clamp(d.y, -1.0, 1.0)); vec2 g = vec2(phi * 26.0, th * 26.0); vec2 id = floor(g); vec2 f = fract(g) - 0.5; float rnd = hash21(id); float star = step(0.965, rnd) * exp(-dot(f, f) * 58.0) * (1.2 + 1.8 * hash21(id + 7.3)); vec3 starCol = mix(vec3(0.75, 0.88, 1.0), vec3(1.0, 0.84, 0.65), hash21(id + 3.1)); // Subtle galactic dust band float band = exp(-pow(d.y * 2.8 + 0.35 * sin(phi * 2.0), 2.0) * 3.5); vec3 neb = vec3(0.06, 0.09, 0.16) * band + vec3(0.015, 0.02, 0.035); return neb + starCol * star; } // Keplerian accretion disk emission with relativistic Doppler beaming & gravitational redshift vec3 evalDiskEmission(vec3 pos, vec3 rayDir, float rs, float dopplerK) { float r = length(pos.xz); float rIn = rs * 2.15; float rOut = rs * 6.8; if (r < rIn || r > rOut) return vec3(0.0); float ang = atan(pos.z, pos.x); float omega = 1.65 / max(pow(r, 1.25), 0.2); float spiral = 0.55 + 0.45 * sin(ang * 4.0 + r * 4.2 - iTime * (1.8 + omega)); float rings = 0.65 + 0.35 * sin(r * 14.0 - iTime * 1.4); float radialFade = smoothstep(rIn, rIn + 0.25 * rs, r) * smoothstep(rOut, rIn + 1.4 * rs, r); // Keplerian tangent velocity vector v (counter-clockwise orbiting disk) vec3 velDir = normalize(vec3(-pos.z, 0.0, pos.x)); float beta = clamp(sqrt(0.5 * rs / max(r, rs * 1.1)), 0.0, 0.62); float cosA = dot(velDir, -rayDir); // Relativistic Doppler factor D = 1 / (gamma * (1 - beta*cosA)) -> approaching left side beams blazing blue-white, receding right redshifts! float doppler = mix(1.0, (1.0 + beta * cosA) / max(1.0 - 0.55 * beta * cosA, 0.35), dopplerK); float gravRed = sqrt(max(1.0 - rs / max(r, rs * 1.02), 0.08)); float gShift = clamp(doppler * gravRed, 0.25, 2.4); // Temperature shifts from deep crimson -> blazing gold -> blue-white under gShift vec3 coldC = vec3(0.95, 0.20, 0.04); vec3 midC = vec3(1.0, 0.68, 0.24); vec3 hotC = vec3(0.85, 0.94, 1.0); vec3 tempCol = mix(coldC, mix(midC, hotC, smoothstep(0.85, 1.75, gShift)), smoothstep(0.35, 1.05, gShift)); float intensity = pow(gShift, 2.4) * radialFade * (0.45 + 0.55 * spiral * rings) * 2.2; return tempCol * intensity; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useGeodesic = sx >= split; float rs = clamp(P_BH_MASS, 0.5, 1.6) * 0.42; float incl = clamp(P_DISK_INCL, 0.06, 0.65); float dopplerK = clamp(P_DOPPLER_STR, 0.0, 1.5); float camDist = 5.4; vec3 ro = vec3(0.0, camDist * sin(incl), camDist * cos(incl)); vec3 fw = normalize(-ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.65 + ri * uv.x + up * uv.y); // Integrate photon trajectory: null geodesic a = -1.5 * rs * h^2 * p / r^5 (where h = |p x rd| is angular momentum!) vec3 pos = ro; vec3 vel = rd; vec3 hVec = cross(pos, vel); float h2 = dot(hVec, hVec); vec3 accCol = vec3(0.0); bool captured = false; const int STEPS = 84; for (int i = 0; i < STEPS; i++) { float r = length(pos); if (r < rs * 1.02) { captured = true; break; } if (r > 14.0) break; float dt = clamp(r * 0.085, 0.04, 0.35); vec3 prevPos = pos; if (useGeodesic) { // Schwarzschild exact general-relativistic null-geodesic bending force (-3/2 * rs * h^2 / r^5 * pos) vec3 accel = -1.5 * rs * h2 * pos / max(pow(r, 5.0), 1e-4); vel = normalize(vel + accel * dt); } pos += vel * dt; // Detect crossing of equatorial accretion disk plane (y == 0) if (prevPos.y * pos.y <= 0.0 && abs(pos.y - prevPos.y) > 1e-5) { float f = abs(prevPos.y) / abs(pos.y - prevPos.y); vec3 hitP = mix(prevPos, pos, f); accCol += evalDiskEmission(hitP, vel, rs, dopplerK); } } vec3 col = accCol; if (!captured) { col += evalStarfield(vel); } // Subtle Einstein photon sphere glow near r = 1.5 * rs on geodesic side if (useGeodesic) { float bImpact = sqrt(h2); float bCrit = 2.598 * rs; float photonRing = exp(-pow((bImpact - bCrit) / (0.045 * rs), 2.0)); col += vec3(1.0, 0.86, 0.62) * photonRing * 0.45; } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) ## Combines with - [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md): HDR radiance from the Doppler-beamed inner accretion disk and photon ring drives physically convincing optical glare. - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): High-contrast blackbody emission compresses cleanly into display gamut without abrupt hue shifts on the hot approaching limb. ## Sources 1. [primary] Oliver James, Eugénie von Tunzelmann, Paul Franklin, Kip S Thorne (2015) Gravitational lensing by spinning black holes in astrophysics, and in the movie Interstellar. Classical and Quantum Gravity. https://doi.org/10.1088/0264-9381/32/6/065001 (verified via crossref on 2026-11-30) 2. [implementation] Humpalumps (2026) Humpalumps/ultra-elements. https://github.com/Humpalumps/ultra-elements License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Schwarzschild Null-Geodesic Gravitational Lensing and Relativistic Accretion Disk." https://texelatlas.vercel.app/t/schwarzschild-null-geodesic-lensing/ (accessed 2026-12-01). --- id: "score-distillation-sampling" title: "Score Distillation Sampling (DreamFusion)" aliases: [SDS, DreamFusion] domain: "genai" stage: "generation" realtime: "offline" platforms: [cuda, python] year_introduced: 2022 inputs: [text-prompt] outputs: [radiance-field, mesh] style: "both" dynamic: "static" cost: "offline" authority: "Poole et al., 2022" url: "https://texelatlas.vercel.app/t/score-distillation-sampling/" sources_verified_at: "2026-11-29" --- # Score Distillation Sampling (DreamFusion) (Poole et al., 2022) > Optimises a 3D representation so that its renders look plausible to a frozen 2D text-to-image diffusion model, using the denoiser residual as a gradient instead of a pixel loss. ## Reach for it when - generate a 3d asset from a text prompt using a 2d model - no 3d training data but have a text-to-image model - optimise a 3d representation to look plausible from every view - text-to-3d without a feed-forward generator - edit or texture 3d using diffusion guidance ## How it works A randomly initialised NeRF (or later a mesh / Gaussian set) is rendered from a random camera. The render is noised to a random timestep, the frozen diffusion model predicts the noise given the text prompt (with a large classifier-free guidance weight), and the difference between predicted and injected noise is treated as the gradient on the render. It is back-propagated through the renderer only, skipping the denoiser Jacobian, which makes each step cheap in memory. Thousands of such steps with view-dependent prompt suffixes ("front view", "back view") sculpt geometry and colour that every viewpoint agrees on. Because no 3D training data is used, the method inherits the 2D model's vocabulary, but also its biases and its habit of mode-seeking. ## When to use it Choose it when you need open-vocabulary 3D from text and have GPU hours per asset to spend, or as the loss inside a larger pipeline (texturing, editing, avatar fitting). Prefer [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) or [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) when you want an asset in seconds from a feed-forward model trained on 3D data, and [Large Reconstruction Model (LRM)](https://texelatlas.vercel.app/t/large-reconstruction-model.md) when you have an input image. Prefer [Zero-1-to-3](https://texelatlas.vercel.app/t/zero-1-to-3.md) as the guidance model when conditioning on one photograph. ## Cost offline — Tens of minutes to hours per asset on one GPU in public implementations; qualitative, no benchmark claimed here. Measured GPU Weight: 43.91× baseline (heavy) — 1.4445 ms median / 1.5597 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 38.4× baseline (heavy) — 0.6106 ms median (2.37× faster on L4). Ampere A100 scaling: 30.07× baseline (heavy) — 0.866 ms median (1.67× faster on A100). ## Failure modes - Janus problem: multiple faces because the 2D prior has no notion of a consistent viewpoint - Over-saturated, over-smooth colours caused by the very high guidance scale needed to make the signal strong enough - Mode-seeking collapse yields low-diversity, cartoon-like surfaces and little fine geometric detail - Floaters and noisy density in the NeRF unless regularised - Each asset needs a fresh optimisation run, so iteration is slow ## Dataflow - Inputs: text-prompt - Outputs: radiance-field, mesh - Platforms: cuda, python ## Presets ### Score Distillation Sampling (DreamFusion) — noisy score gradient field (left) vs sculpted 3D NeRF/SDF (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_NOISE_T": 0.52, "P_CFG_GAIN": 1.15, "P_ROT_SPEED": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_NOISE_T = 0.52; // P Diffusion Noise t [0.05, 0.95, 0.02] const float P_CFG_GAIN = 1.15; // P CFG Guidance [0.3, 2.0, 0.05] const float P_ROT_SPEED = 0.55; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P SDS Field / 3D Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); } // Target sculpted 3D implicit shape optimized via SDS (DreamFusion) float mapTarget(vec3 p, float spin) { vec3 q = p; q.xz = rot2(spin * 0.48) * q.xz; // Sculpted fluted vase / chalice with glowing core ring float rXZ = length(q.xz); float profile = 0.36 + 0.14 * sin(q.y * 5.2 + 0.4) - 0.18 * q.y * q.y; float flutes = 0.032 * cos(atan(q.z, q.x) * 8.0); float dVase = max(rXZ - (profile + flutes), abs(q.y) - 0.64); float dRing = length(vec2(rXZ - 0.58, q.y - 0.08)) - 0.075; return min(dVase, dRing) * 0.78; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapTarget(p + e.xyy, spin) - mapTarget(p - e.xyy, spin), mapTarget(p + e.yxy, spin) - mapTarget(p - e.yxy, spin), mapTarget(p + e.yyx, spin) - mapTarget(p - e.yyx, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float noiseT = clamp(P_NOISE_T, 0.05, 0.95); float cfg = clamp(P_CFG_GAIN, 0.25, 2.2); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.16, 2.38); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.03), -1.52)); vec3 bg = mix(vec3(0.022, 0.026, 0.048), vec3(0.058, 0.068, 0.118), smoothstep(-0.55, 0.55, uv.y)); vec3 col = bg; if (screenX < split) { // Left: Volumetric SDS score residual field (eps_hat - eps) pushing noisy latent cloud onto the target SDF float b = dot(ro, rd); float c = dot(ro, ro) - 1.15 * 1.15; float disc = b * b - c; if (disc > 0.0) { float t0 = max(-b - sqrt(disc), 0.2); float t1 = -b + sqrt(disc); float dt = (t1 - t0) / 36.0; vec3 acc = vec3(0.0); float T = 1.0; for (int i = 0; i < 36; i++) { float t = t0 + (float(i) + 0.5) * dt; vec3 p = ro + rd * t; float d = mapTarget(p, spin); // Score gradient pushes inward (amber) outside surface and outward (cyan) inside surface float nVal = hash31(floor(p * 14.0 + vec3(0.0, iTime * 1.6, 0.0))) - 0.5; float band = exp(-abs(d) * (9.0 - 5.5 * noiseT)); float sigma = band * (2.6 + 1.4 * abs(nVal)) * (0.4 + 0.6 * cfg); vec3 gradCol = (d > 0.0) ? mix(vec3(0.98, 0.48, 0.14), vec3(1.0, 0.86, 0.35), smoothstep(0.0, 0.22, d)) : vec3(0.14, 0.82, 0.96); // Iso-level score shells visualizing gradient descent steps float iso = 0.65 + 0.35 * cos(d * 38.0 - iTime * 4.0); float a = 1.0 - exp(-sigma * dt); acc += T * a * gradCol * iso * (0.85 + 0.4 * nVal); T *= (1.0 - a); if (T < 0.02) break; } col = acc + T * bg; } } else { // Right: Relightable DreamFusion 3D surface optimized under CFG guidance float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapTarget(ro + rd * t, spin); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 objP = p; objP.xz = rot2(spin * 0.48) * objP.xz; vec3 l1 = normalize(vec3(0.60, 0.78, 0.50)); vec3 l2 = normalize(vec3(-0.70, 0.10, 0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 40.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); // CFG saturation boost characteristic of DreamFusion SDS float ringMask = smoothstep(0.50, 0.56, length(objP.xz)); vec3 ceramic = mix(vec3(0.86, 0.34, 0.22), vec3(0.96, 0.76, 0.32), smoothstep(-0.55, 0.55, objP.y)); ceramic = mix(ceramic, vec3(0.16, 0.78, 0.92), ringMask); // Saturation boost with CFG float lum = dot(ceramic, vec3(0.299, 0.587, 0.114)); ceramic = mix(vec3(lum), ceramic, clamp(0.65 + 0.45 * cfg, 0.5, 1.5)); col = ceramic * (0.26 + 0.82 * diff1 + 0.24 * diff2) + vec3(1.0, 0.96, 0.88) * spec * 0.50 + vec3(0.98, 0.62, 0.32) * fres * 0.34; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [DreamGaussian](https://texelatlas.vercel.app/t/dreamgaussian.md) ## Combines with - [Zero-1-to-3](https://texelatlas.vercel.app/t/zero-1-to-3.md): Zero-1-to-3 supplies a view-conditioned diffusion prior whose gradients SDS can back-propagate into a 3D model from a single input image. ## Sources 1. [primary] Ben Poole, Ajay Jain, Jonathan T. Barron, Ben Mildenhall (2022) DreamFusion: Text-to-3D using 2D Diffusion. arXiv preprint (cs.CV). https://arxiv.org/abs/2209.14988 (verified via arxiv on 2026-11-29) 2. [implementation] ashawkey (2022) ashawkey/stable-dreamfusion. https://github.com/ashawkey/stable-dreamfusion License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Score Distillation Sampling (DreamFusion)." https://texelatlas.vercel.app/t/score-distillation-sampling/ (accessed 2026-12-01). --- id: "screen-space-edge-outline" title: "Depth/normal Sobel edge outlines" aliases: [Sobel outline, G-buffer edge detection] domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1990 inputs: [depth, normals, gbuffer] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Saito & Takahashi, 1990" url: "https://texelatlas.vercel.app/t/screen-space-edge-outline/" sources_verified_at: "2026-11-29" --- # Depth/normal Sobel edge outlines (Saito & Takahashi, 1990) > Runs an edge detector such as Sobel or Roberts cross over depth and view-space normal buffers, then draws lines where either channel jumps, giving silhouettes and creases in one full-screen pass. ## Reach for it when - cartoon outlines around objects without extra geometry - draw ink lines on silhouettes and creases - outline pass that works with any mesh - toon shader needs line art from depth and normals ## How it works Saito and Takahashi's insight was that geometric buffers expose shape edges more reliably than colour does. The pass samples a 3×3 neighbourhood of linear depth and encoded normals, applies a Sobel (or cheaper Roberts-cross) kernel, and compares the magnitude against thresholds. Depth discontinuities mark silhouettes and occlusion borders; normal discontinuities mark creases. Thresholds are commonly scaled by depth or by the view angle to avoid false lines on grazing planes. The edge mask multiplies or replaces the colour buffer, and sample offsets can be widened to thicken lines. An object-ID or material-ID channel can be added to separate touching meshes with identical depth and normals. ## When to use it Choose it when you already have a G-buffer and want outlines on everything, including terrain and imported assets, without touching geometry. Prefer [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md) for per-object line width control and cleaner thick outer lines. Prefer [Jump-flood wide outlines](https://texelatlas.vercel.app/t/jump-flood-outline.md) for very wide or selection-style outlines, since kernels beyond a few pixels get expensive here. ## Cost cheap — One full-screen pass with 8 to 9 taps per buffer; light, but widening the kernel scales cost quadratically. Measured GPU Weight: 4.47× baseline (light) — 0.1472 ms median / 0.1481 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.58× baseline (light) — 0.0569 ms median (2.59× faster on L4). Ampere A100 scaling: 2.49× baseline (light) — 0.0718 ms median (2.05× faster on A100). ## Failure modes - Grazing-angle planes produce depth gradients that trigger false lines; scale threshold by view angle - Fixed thresholds give uneven line thickness between near and far objects - Lines appear on transparent or alpha-tested edges only if those write depth - Normal-edge detection misses creases between surfaces with equal normals but different materials unless an ID buffer is added ## Engine support - babylonjs: official — `new BABYLON.EdgeDetectionPostProcess('edge', scene, 1.0, camera) from @babylonjs/post-processes` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/postProcesses/src/edgeDetection/edgeDetectionPostProcess.ts, checked 2026-12-01) — Core also has EdgesRenderer (mesh edge lines). - blender: builtin — `Compositor > Add > Filter > Filter > Sobel (on depth / normal passes)` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/filter/filter.html, checked 2026-12-01) — Sobel is a general filter; you wire the Z and Normal passes yourself. - threejs: official — `import { sobel } from 'three/addons/tsl/display/SobelOperatorNode.js' (WebGL: OutlinePass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SobelOperatorNode.js, checked 2026-12-01) ## Dataflow - Inputs: depth, normals, gbuffer - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: shaded frame. Right: Roberts-cross edges on depth and normal buffers drawn as lines (glsl-fragment; rendered 2026-11-29) ```json { "DZ": 0.12, "DN": 0.5, "PX": 1.5 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec4 gb(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);return t>1e8?vec4(0.,1.,0.,40.):vec4(n,min(t*rd.z,40.));} float edgeRC(vec2 uv,float px,float DZ,float DN){ vec4 a=gb(uv),b=gb(uv+vec2(px,px)),c=gb(uv+vec2(px,0.)),d=gb(uv+vec2(0.,px)); float mz=min(a.w,min(b.w,min(c.w,d.w)));float dz=(abs(a.w-b.w)+abs(c.w-d.w))/mz*step(mz,25.); float dn=length(a.xyz-b.xyz)+length(c.xyz-d.xyz); return max(step(DZ,dz),step(DN,dn));} const float DZ=0.12; // P const float DN=0.5; // P const float PX=1.5; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 col=shadeBasic(uv); if(R&&edgeRC(uv,PX/512.,DZ,DN)>.5)col=vec3(.03,.02,.05); if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extended by [Jump-flood wide outlines](https://texelatlas.vercel.app/t/jump-flood-outline.md) - extended by [XDoG edge and stylization filter](https://texelatlas.vercel.app/t/xdog-stylization.md) ## Combines with - [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md): Edge pass inks lines over the flat toon colour buffer. - [Kuwahara filter](https://texelatlas.vercel.app/t/kuwahara-filter.md): Applying edges after Kuwahara keeps lines crisp while colour becomes painterly. ## Sources 1. [primary] Takafumi Saito, Tokiichiro Takahashi (1990) Comprehensible rendering of 3-D shapes. Proceedings of the 17th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/97879.97901 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Depth/normal Sobel edge outlines." https://texelatlas.vercel.app/t/screen-space-edge-outline/ (accessed 2026-12-01). --- id: "screen-space-fluid-rendering" title: "Screen-space fluid rendering (curvature flow)" aliases: [particle fluid surface smoothing, screen-space surface reconstruction for fluids, curvature flow smoothing] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal] year_introduced: 2009 inputs: [particles, depth] outputs: [ldr-image, normals] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Laan et al., 2009" url: "https://texelatlas.vercel.app/t/screen-space-fluid-rendering/" sources_verified_at: "2026-11-29" --- # Screen-space fluid rendering (curvature flow) (Laan et al., 2009) > Render particle fluids without building a mesh: splat particles as spheres into a depth image, smooth that depth with curvature flow, reconstruct normals and shade it as a refractive liquid with thickness and foam. ## Reach for it when - rendering thousands of fluid particles without meshing - particles look like beads instead of a smooth liquid - need a real time water look for sph particles - want refraction and thickness absorption on particle fluid ## How it works Particles from [sph-fluids](sph-fluids), [position-based-fluids](position-based-fluids) or [flip-pic-fluids](flip-pic-fluids) are drawn as point sprites that write the depth of a sphere surface (not a flat disc) into a depth texture. The result is bumpy, one bump per particle. To make it look like a continuous surface, the depth buffer is smoothed in screen space. Curvature flow evolves depth in the direction of mean curvature, which smooths bumps while preserving silhouettes, and it takes a few iterations. Simple alternatives are a bilateral or narrow-range blur that avoids blurring across depth discontinuities. Normals are reconstructed from the smoothed depth. A second pass accumulates particle thickness additively. Shading then uses these buffers: Fresnel reflection of the environment, refraction offset by normal, Beer–Lambert absorption from thickness, plus specular highlights and optional foam from velocity or density. Only the front surface is represented. ## When to use it Choose it for real-time rendering of large particle fluids in games and interactive tools, where meshing every frame is too expensive. Prefer [marching-cubes](marching-cubes) or [surface-nets](surface-nets) on a density grid when you need a real mesh for physics, caustics or offline rendering. Prefer [volume-ray-marching](volume-ray-marching) for smoke, foam-like or translucent media with interior variation. Prefer [shallow-water-equations](shallow-water-equations) or [fft-ocean](fft-ocean) for large open water surfaces rather than free particle volumes. Combine with [water-caustics-realtime](water-caustics-realtime) for light patterns. ## Cost medium — Cost is dominated by the number of smoothing iterations and the splat fill rate; roughly independent of scene geometry. Measured GPU Weight: 205.08× baseline (extreme) — 6.747 ms median / 6.8411 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 174.89× baseline (extreme) — 2.7807 ms median (2.43× faster on L4). Ampere A100 scaling: 150.43× baseline (extreme) — 4.3325 ms median (1.56× faster on A100). ## Failure modes - Only the nearest surface exists, so back faces, internal bubbles and refraction of other fluid layers are missing - Blur across silhouettes makes thin streams merge or lose the gap between droplets - Over-smoothing flattens splash detail, while under-smoothing shows individual particle beads - Particle size must match spacing; large gaps produce sparse speckled surfaces - Thickness-based absorption fails for non-convex volumes where thick regions are not along the view ray - Screen-space result changes with camera distance since the filter radius is in pixels unless depth-scaled ## Engine support - babylonjs: builtin — `new FluidRenderer(scene); fluidRenderer.addParticleSystem(...)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Rendering/fluidRenderer/fluidRenderer.pure.ts, checked 2026-12-01) ## Dataflow - Inputs: particles, depth - Outputs: ldr-image, normals - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal ## Presets ### Screen-space fluid starting parameters (json-params; parameter preset) ```json { "particle_radius_to_spacing": 1, "smoothing_iterations": 40, "curvature_flow_dt": 0.0005, "depth_clamp_max_pixels": 8, "thickness_absorption_rgb": [ 0.4, 0.1, 0.05 ], "fresnel_f0": 0.02, "refraction_scale": 0.05 } ``` Attribution: parameter preset, sensible defaults chosen for this index ### Screen-Space Fluid Rendering — raw splatted particle spheres (left) vs curvature-flow smoothed refractive liquid (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CURV_FLOW": 0.88, "P_ABSORB_DEPTH": 1.25, "P_FLOW_SPEED": 0.95, "P_SPLIT": 0.48 } ``` ```glsl const float P_CURV_FLOW = 0.88; // P Curvature Smoothing [0.0, 1.0, 0.05] const float P_ABSORB_DEPTH = 1.25; // P Beer-Lambert Depth [0.3, 2.5, 0.1] const float P_FLOW_SPEED = 0.95; // P Pour Speed [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Particles / Fluid Split [0.0, 1.0, 0.02] // Procedural pouring stream of 26 animated 3D fluid particles arcing into a swirling basin vec3 getParticlePos(int i, float t) { float fi = float(i); if (i < 12) { // Pouring stream arc from upper-left spout into basin center float ph = fract(t * 0.32 + fi / 12.0); float x = mix(-0.78, 0.08, ph) + 0.03 * sin(fi * 4.1 + t * 3.0); float y = 0.48 - 0.86 * ph * ph + 0.03 * cos(fi * 3.3); float z = 0.06 * sin(fi * 2.7 + t * 2.0); return vec3(x, y, z); } // Swirling turbulent basin pool particles float j = fi - 12.0; float ang = j * 0.45 + t * 1.15; float rad = 0.12 + 0.44 * fract(j * 0.37); float x = cos(ang) * rad + 0.16; float y = -0.36 + 0.065 * sin(ang * 2.0 + t * 2.5); float z = sin(ang) * rad * 0.65; return vec3(x, y, z); } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Evaluate either raw unsmoothed spheres (left) or curvature-flow smoothed liquid iso-surface (right) float mapFluid(vec3 p, float t, float smoothK, bool smoothed) { float d = 1e5; float r = smoothed ? 0.145 : 0.115; float k = smoothed ? (0.16 * smoothK + 0.03) : 0.001; for (int i = 0; i < 26; i++) { vec3 c = getParticlePos(i, t); float ds = length(p - c) - r; d = smoothed ? smin(d, ds, k) : min(d, ds); } return d; } vec3 calcNormal(vec3 p, float t, float smoothK, bool smoothed) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapFluid(p + e.xyy, t, smoothK, smoothed) - mapFluid(p - e.xyy, t, smoothK, smoothed), mapFluid(p + e.yxy, t, smoothK, smoothed) - mapFluid(p - e.yxy, t, smoothK, smoothed), mapFluid(p + e.yyx, t, smoothK, smoothed) - mapFluid(p - e.yyx, t, smoothK, smoothed) )); } vec3 evalPoolBackdrop(vec3 rd) { vec2 g = floor(rd.xy * 11.0); vec3 tile = mix(vec3(0.10, 0.14, 0.20), vec3(0.18, 0.24, 0.32), mod(g.x + g.y, 2.0)); return mix(tile, vec3(0.32, 0.52, 0.78), smoothstep(0.0, 0.75, rd.y)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showFluid = sx >= split; float smoothK = clamp(P_CURV_FLOW, 0.0, 1.2); float absorb = clamp(P_ABSORB_DEPTH, 0.2, 3.0); float tAnim = iTime * max(P_FLOW_SPEED, 0.0); vec3 ro = vec3(0.0, 0.18, 2.22); vec3 rd = normalize(vec3(uv, -1.48)); vec3 col = evalPoolBackdrop(rd); float t = 0.05; bool hit = false; for (int i = 0; i < 60; i++) { float d = mapFluid(ro + rd * t, tAnim, smoothK, showFluid); if (d < 0.0025) { hit = true; break; } t += d * 0.85; if (t > 5.5) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, tAnim, smoothK, showFluid); vec3 v = -rd; vec3 L = normalize(vec3(0.55, 0.82, 0.58)); vec3 H = normalize(L + v); if (!showFluid) { // Left: Raw splatted particle spheres shaded directly (classic bumpy "ball pit" prior to curvature flow) float ndl = max(dot(n, L), 0.0); float spec = pow(max(dot(n, H), 0.0), 36.0); col = vec3(0.16, 0.52, 0.84) * (0.28 + 0.82 * ndl) + vec3(0.95, 0.98, 1.0) * spec * 0.65; } else { // Right: Screen-space fluid rendering with reconstructed smooth normals, Beer-Lambert thickness absorption, refraction & crest foam! // Estimate fluid optical thickness along view ray via 4-step interior march float thick = 0.0; for (int s = 1; s <= 4; s++) { float ds = mapFluid(p + rd * (float(s) * 0.09), tAnim, smoothK, true); thick += clamp(-ds * 4.2, 0.0, 1.0) * 0.25; } vec3 refrDir = refract(rd, n, 1.0 / 1.333); vec3 reflDir = reflect(rd, n); vec3 refrBg = evalPoolBackdrop(refrDir); vec3 trans = exp(-vec3(0.75, 0.22, 0.08) * thick * absorb * 3.8); vec3 reflCol = mix(vec3(0.28, 0.54, 0.84), vec3(0.95, 0.98, 1.0), smoothstep(-0.1, 0.7, reflDir.y)); float fres = 0.03 + 0.94 * pow(1.0 - max(dot(n, v), 0.0), 4.5); float spec = pow(max(dot(n, H), 0.0), 96.0) * 2.4; // Aerated foam along fast-moving upper crests float foam = smoothstep(0.08, 0.42, p.y + 0.25 * n.y) * smoothstep(0.18, 0.02, thick) * 0.45; col = mix(refrBg * trans + vec3(0.04, 0.24, 0.34) * (1.0 - trans), reflCol, fres) + vec3(1.0) * (spec + foam); } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Narrow-Range Screen-Space Fluid Depth Filtering](https://texelatlas.vercel.app/t/narrow-range-ssf-depth-filter.md) ## Combines with - [Position Based Fluids](https://texelatlas.vercel.app/t/position-based-fluids.md): Particle positions from the solver are splatted as the input depth and thickness images. - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Reconstructed screen-space normals and thickness can drive projected caustics on receiving surfaces. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Temporal accumulation hides the flicker of per-particle depth bumps. ## Sources 1. [primary] Wladimir J. van der Laan, Simon Green, Miguel Sainz (2009) Screen space fluid rendering with curvature flow. Proceedings of the 2009 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1507149.1507164 (verified via crossref on 2026-11-29) 2. [talk] Simon Green Direct3D 11 effects (includes screen-space fluid rendering). GDC 2010. https://developer.download.nvidia.com/presentations/2010/gdc/Direct3D_Effects.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Screen-space fluid rendering (curvature flow)." https://texelatlas.vercel.app/t/screen-space-fluid-rendering/ (accessed 2026-12-01). --- id: "screen-space-gi" title: "Screen-Space Global Illumination" aliases: [SSGI, SSDO, screen-space directional occlusion] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2009 inputs: [gbuffer, depth, normals, radiance] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Ritschel et al., 2009" url: "https://texelatlas.vercel.app/t/screen-space-gi/" sources_verified_at: "2026-11-29" --- # Screen-Space Global Illumination (Ritschel et al., 2009) > Approximates one-bounce diffuse indirect light by sampling the lit depth buffer around each pixel as if each visible sample were a small light, with the same sampling doubling as directional occlusion. ## Reach for it when - want cheap colour bleeding in deferred rendering - indirect shadowing at contact scale is missing - need one-bounce diffuse light without probes everywhere - extra indirect detail on top of baked lighting ## How it works Screen-space directional occlusion extends ambient occlusion: for each pixel, instead of just counting occluded samples, it takes a set of directions in the hemisphere (via sample offsets within a screen-space radius). Samples whose reconstructed 3D position lies above the surface are considered **unoccluded** and contribute environment light; samples that lie *below* the surface are occluders. For the indirect bounce, each occluding sample's **lit colour** (read from the previous frame's frame buffer) is treated as a small diffuse patch emitting towards the receiver. The contribution is weighted by form-factor-like terms: the cosine at the receiver, the cosine at the emitter, and the squared distance. The sum approximates one bounce of colour bleeding from visible surfaces. Current variants use ray-marched screen-space traces of the depth buffer (hierarchical depth) with a few rays per pixel, feed history through temporal reprojection, and denoise with a spatial filter. The technique only sees what is on screen, so it is often combined with a world-space probe or [ddgi](ddgi) fallback for off-screen light. ## When to use it Choose it as an inexpensive extra for colour bleeding and indirect shadowing at contact scale in a deferred renderer, typically layered on top of probes or lightmaps. Prefer [ddgi](ddgi), [lumen-gi](lumen-gi) or [surfel-gi](surfel-gi) when off-screen light and consistent GI at any view angle matter. Prefer [radiance-cascades](radiance-cascades) for screen-space-based tracing that avoids the noise of per-pixel gather. Prefer [reflective-shadow-maps](reflective-shadow-maps) when the emitter surfaces are known from a light's point of view. ## Cost medium — Cost scales with samples per pixel plus a denoise and temporal pass; commonly run at half resolution. Measured GPU Weight: 244.24× baseline (extreme) — 8.0356 ms median / 8.218 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 232.43× baseline (extreme) — 3.6956 ms median (2.17× faster on L4). Ampere A100 scaling: 148.76× baseline (extreme) — 4.2844 ms median (1.88× faster on A100). ## Failure modes - Missing light from anything off-screen or hidden behind foreground objects, so indirect light pops when the source leaves the view - Ghosting and smearing from temporal reuse on fast motion and disocclusion - Thin-object problem: depth buffer lacks thickness, so occluders are misjudged and halos appear - Colour bleeding vanishes at screen edges and when the camera turns ## Engine support - blender: builtin — `Properties > Render > Raytracing (enable) > Method = Screen-Trace; Fast GI Approximation` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/raytracing.html, checked 2026-12-01) - godot: builtin — `Environment.ssil_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) — SSIL; Forward+ only. - threejs: official — `import { ssgi } from 'three/addons/tsl/display/SSGINode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SSGINode.js, checked 2026-12-01) — WebGPURenderer / TSL. - unity: builtin — `Volume > Add Override > Lighting > Screen Space Global Illumination` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-screen-space-global-illumination.md, checked 2026-12-01) — HDRP only. URP has no SSGI in Unity 6.3. - unreal: builtin — `Post Process Volume > Global Illumination > Method = Screen Space` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, depth, normals, radiance - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Screen-space GI — split direct lighting vs horizon-marching diffuse color bleed (glsl-fragment; rendered 2026-11-30) ```json { "P_GI_INTENSITY": 1.35, "P_SAMPLE_RADIUS": 0.9, "P_BOUNCE_SAT": 1.2, "P_SPLIT": 0.42 } ``` ```glsl const float P_GI_INTENSITY = 1.35; // P GI Strength [0.0, 2.5, 0.05] const float P_SAMPLE_RADIUS = 0.9; // P Gather Radius [0.2, 2.0, 0.05] const float P_BOUNCE_SAT = 1.2; // P Color Bleed [0.2, 2.0, 0.05] const float P_SPLIT = 0.42; // P Direct/GI Split [0.0, 1.0, 0.02] 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); } // Cornell gallery box with crimson left wall, teal right wall, white central column & orb vec2 mapRoom(vec3 p) { // Inverted room walls: x in [-1.5,1.5], y in [-1.0,1.0], z in [-1.5, 3.0] vec2 res = vec2(1.0 + p.y, 1.0); // floor float ceilD = 1.0 - p.y; if (ceilD < res.x) res = vec2(ceilD, 1.0); float backD = 1.45 + p.z; if (backD < res.x) res = vec2(backD, 1.0); float leftD = 1.45 + p.x; if (leftD < res.x) res = vec2(leftD, 2.0); // crimson wall float rightD = 1.45 - p.x; if (rightD < res.x) res = vec2(rightD, 3.0); // emerald-teal wall // Central sculpted white pedestal & floating matte sphere float dPed = sdBox(p - vec3(0.0, -0.55, -0.25), vec3(0.36, 0.45, 0.36)) - 0.03; if (dPed < res.x) res = vec2(dPed, 4.0); vec3 spPos = vec3(0.28 * sin(iTime * 0.7), 0.18 + 0.08 * cos(iTime * 1.1), -0.22); float dSph = length(p - spPos) - 0.34; if (dSph < res.x) res = vec2(dSph, 4.0); // Side accent block near crimson wall float dBlk = sdBox(p - vec3(-0.78, -0.68, -0.62), vec3(0.32, 0.32, 0.32)) - 0.02; if (dBlk < res.x) res = vec2(dBlk, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRoom(p + e.xyy).x - mapRoom(p - e.xyy).x, mapRoom(p + e.yxy).x - mapRoom(p - e.yxy).x, mapRoom(p + e.yyx).x - mapRoom(p - e.yyx).x )); } vec3 getAlbedo(float id, float sat) { vec3 c; if (id < 1.5) c = vec3(0.76, 0.76, 0.74); else if (id < 2.5) c = vec3(0.88, 0.14, 0.12); else if (id < 3.5) c = vec3(0.10, 0.76, 0.56); else c = vec3(0.88, 0.87, 0.85); float l = dot(c, vec3(0.299, 0.587, 0.114)); return clamp(mix(vec3(l), c, sat), 0.02, 1.0); } float softShadow(vec3 ro, vec3 rd, float maxT) { float res = 1.0; float t = 0.04; for (int i = 0; i < 20; i++) { float h = mapRoom(ro + rd * t).x; res = min(res, clamp(5.0 * h / t, 0.0, 1.0)); t += max(h, 0.05); if (t > maxT || res < 0.02) break; } return res; } vec3 directShade(vec3 p, vec3 n, float matId, vec3 lPos, float sat) { vec3 toL = lPos - p; float dist = length(toL) + 1e-4; vec3 lDir = toL / dist; float ndl = max(dot(n, lDir), 0.0); float sh = softShadow(p + n * 0.015, lDir, dist - 0.08); float att = 2.6 / (0.4 + dist * dist); vec3 alb = getAlbedo(matId, sat); return alb * vec3(1.15, 1.08, 0.96) * ndl * sh * att; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; vec3 ro = vec3(0.0, 0.05, 2.35); vec3 rd = normalize(vec3(uv, -1.32)); float sat = clamp(P_BOUNCE_SAT, 0.2, 2.2); vec3 lPos = vec3(0.45 * cos(iTime * 0.55), 0.88, -0.2 + 0.35 * sin(iTime * 0.55)); float t = 0.0; float matId = 1.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapRoom(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 9.0) break; } vec3 col = vec3(0.02); if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = getAlbedo(matId, sat); vec3 direct = directShade(p, n, matId, lPos, sat); // Ceiling area light emitter plaque float emitter = smoothstep(0.32, 0.18, length(p.xz - lPos.xz)) * smoothstep(0.95, 0.99, p.y); direct += vec3(3.4, 3.1, 2.6) * emitter; // Screen-Space GI gather: march 8 azimuthal horizon rays around surface tangent plane vec3 tangent = normalize(abs(n.y) < 0.9 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0))); vec3 bitan = cross(n, tangent); float rad = clamp(P_SAMPLE_RADIUS, 0.2, 2.2); float jitter = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453); vec3 giAccum = vec3(0.0); float aoAccum = 0.0; for (int k = 0; k < 8; k++) { float ang = (float(k) + jitter * 0.45) * 0.785398; vec3 gDir = normalize(n * 0.55 + (cos(ang) * tangent + sin(ang) * bitan) * 0.835); // Short horizon march in scene proxy (emulates screen-space depth buffer marching) float gt = 0.08; for (int s = 0; s < 6; s++) { vec3 gp = p + n * 0.02 + gDir * gt; vec2 gh = mapRoom(gp); if (gh.x < 0.06 || gt > rad * 1.45) { vec3 gn = calcNormal(gp); // Sample direct radiance of nearby hit surface for 1-bounce color bleed vec3 sampleRad = directShade(gp, gn, gh.y, lPos, sat) + getAlbedo(gh.y, sat) * 0.18; float cosW = max(dot(n, gDir), 0.0); float distW = 1.0 / (0.35 + gt * gt * 1.4); giAccum += sampleRad * cosW * distW; aoAccum += smoothstep(rad * 1.4, 0.05, gt); break; } gt += max(gh.x, rad * 0.22); } } giAccum /= 8.0; float ssao = 1.0 - 0.52 * (aoAccum / 8.0); vec3 directOnly = direct + alb * vec3(0.045, 0.048, 0.058); vec3 withSSGI = direct + alb * (giAccum * max(P_GI_INTENSITY, 0.0) * 1.65 + vec3(0.04, 0.045, 0.055) * ssao); float splitX = clamp(P_SPLIT, 0.0, 1.0); col = (screenUV.x < splitX) ? directOnly : withSSGI; if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(1.8, 1.5, 0.7); } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Dynamic Diffuse Global Illumination (DDGI)](https://texelatlas.vercel.app/t/ddgi.md): Probes supply off-screen and low-frequency light that the screen-space gather cannot see. ## Combination ideas - [Bounce light inside a photograph](https://texelatlas.vercel.app/ideas/photo-bounce-relighting/) ## Sources 1. [primary] Tobias Ritschel, Thorsten Grosch, Hans-Peter Seidel (2009) Approximating dynamic global illumination in image space. Proceedings of the 2009 symposium on Interactive 3D graphics and games. https://doi.org/10.1145/1507149.1507161 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Screen-Space Global Illumination." https://texelatlas.vercel.app/t/screen-space-gi/ (accessed 2026-12-01). --- id: "screen-space-reflections" title: "Screen-space reflections" aliases: [SSR] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2014 inputs: [hdr-image, depth, normals, gbuffer] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "McGuire & Mara" url: "https://texelatlas.vercel.app/t/screen-space-reflections/" sources_verified_at: "2026-11-29" --- # Screen-space reflections (McGuire & Mara) > Ray-marches the reflection vector through the depth buffer and fetches the colour where it hits, giving sharp, contact-accurate reflections of whatever is already on screen. ## Reach for it when - glossy floor should mirror what's on screen - wet surfaces need dynamic reflections cheaply - cubemap reflections don't match nearby objects - polished surfaces lack contact reflections - reflections without hardware ray tracing ## How it works For each reflecting pixel, a ray is built from the view-space position and the reflection vector, clipped to the near plane, and projected to screen space. The march steps in pixels along the dominant axis using a DDA, comparing the ray depth to the depth buffer at each step. A thickness test decides whether a hit is genuine or the ray passed behind an occluder. A hierarchical depth buffer can accelerate long rays. The hit colour from the previous frame or the current lit image is read, fade factors reduce confidence near screen edges, at grazing angles and for rays that miss. Roughness controls blur or cone tracing, and the result is combined with a probe-based fallback. ## When to use it Choose it for glossy floors, water and polished surfaces where the reflected content is on screen and you want dynamic contact reflections. Prefer reflection probes or ray-traced reflections when off-screen content matters. Prefer planar reflections for a single flat mirror. Use SSR on top of a probe fallback, not instead of one. ## Cost medium — Ray march with tens of steps at half or full resolution, plus blur and temporal filter; qualitative. Measured GPU Weight: 17.91× baseline (moderate) — 0.5894 ms median / 0.6147 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 13.06× baseline (moderate) — 0.2076 ms median (2.84× faster on L4). Ampere A100 scaling: 9.68× baseline (moderate) — 0.2788 ms median (2.11× faster on A100). ## Failure modes - No reflection of anything off-screen or behind the camera, so reflections vanish at screen edges - Missing back faces, so reflected objects appear hollow or stretched where thickness is wrong - Stair-stepping or banding on rough surfaces at low step counts - Disocclusion streaks when the foreground hides what should be reflected - Temporal ghosting if history reprojection is imprecise ## Engine support - babylonjs: builtin — `new BABYLON.SSRRenderingPipeline('ssr', scene, cameras)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.pure.ts, checked 2026-12-01) - blender: builtin — `Properties > Render > Raytracing (enable) > Method = Screen-Trace` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/raytracing.html, checked 2026-12-01) — EEVEE ray tracing, with light-probe fallback when the ray leaves the screen. - godot: builtin — `Environment.ssr_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) — Forward+ only. - threejs: official — `import { ssr } from 'three/addons/tsl/display/SSRNode.js' (WebGL: SSRPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SSRNode.js, checked 2026-12-01) - unity: builtin — `Volume > Add Override > Lighting > Screen Space Reflection` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Screen-Space-Reflection.md, checked 2026-12-01) — HDRP only. URP has no SSR renderer feature in Unity 6.3. - unreal: builtin — `Post Process Volume > Reflections > Method = Screen Space` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/screen-space-reflections-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image, depth, normals, gbuffer - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: floor reflects only the sky. Right: screen-space ray march against the depth buffer finds the spheres (glsl-fragment; rendered 2026-11-29) ```json { "NSTEP": 56, "THICK": 0.35, "FRES": 0.5 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const int NSTEP=56; // P const float THICK=0.35; // P const float FRES=0.5; // P vec3 refl(vec3 P,vec3 Rv,bool ssr){ if(ssr){float s=.08;vec3 q=P; for(int i=0;i.5||abs(uq.y)>.5)break; float zs=zbuf(uq);if(zs0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;col=lit(P,n); if(n.y>.99&&abs(P.y+.7)<.003)col=mix(col,refl(P+n*.003,reflect(rd,n),R),FRES); col=mix(col,sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extended by [Hybrid ray-traced reflections](https://texelatlas.vercel.app/t/hybrid-ray-traced-reflections.md) ## Combines with - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Jittered ray origins are resolved by the TAA history buffer. ## Sources 1. [primary] Morgan McGuire, Michael Mara Efficient GPU Screen-Space Ray Tracing. JCGT 2014. https://jcgt.org/published/0003/04/04 (verified via http on 2026-11-29) ## Cite this entry Texel. "Screen-space reflections." https://texelatlas.vercel.app/t/screen-space-reflections/ (accessed 2026-12-01). --- id: "screened-poisson-surface-reconstruction" title: "Screened Poisson Surface Reconstruction" domain: "geometry" stage: "geometry" realtime: "offline" platforms: [cpu, cuda, python] year_introduced: 2013 inputs: [point-cloud, normals] outputs: [mesh, sdf] style: "photoreal" dynamic: "static" cost: "offline" authority: "Kazhdan & Hoppe, 2013" url: "https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction/" sources_verified_at: "2026-11-29" --- # Screened Poisson Surface Reconstruction (Kazhdan & Hoppe, 2013) > Poisson reconstruction with an added screening term that pulls the implicit function toward its expected value at sample points. Keeps fine detail and sharp-ish features while staying watertight and fast. ## Reach for it when - point cloud from scanner needs a watertight mesh - reconstruct smooth surface from oriented points - noisy scan data makes holes and bumps in mesh - photogrammetry points to continuous surface ## How it works The original Poisson formulation only constrains the gradient, so the function can drift between and away from samples. The screened version adds a quadratic data term that penalises the function value at the sample positions for deviation from a constant (the indicator's boundary value), weighted by a per-point confidence. This forms a screened Poisson equation. Solving it on an octree with a cascadic multigrid and a careful hierarchical splatting of samples gives linear time and better detail, with the weight controlling how closely the surface interpolates points versus how smooth it is. Per-point weights let you trust higher-quality scans more, and an envelope or colour can be added by the same solver. The library also contains an out-of-core streaming mode for billion-point scans. ## When to use it Choose it as the default meshing of oriented point clouds, e.g. after photogrammetry or LiDAR registration. Prefer [Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/poisson-surface-reconstruction.md) only for comparison, and consider a learned or [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) on an SDF fit when normals are missing or when you need guaranteed interpolation of every sample. For splat-based pipelines consider splat representations from the capture domain before reaching for meshes. ## Cost offline — Linear in samples with octree depth as the main knob; millions of points in minutes on CPU. ## Failure modes - Needs oriented normals; estimates from noisy data propagate error - Still closes holes with invented geometry; trim by sample density afterwards - Thin or double-sided surfaces merge into one volume - Depth parameter too high amplifies noise; too low blurs detail - Memory grows fast at high depth ## Dataflow - Inputs: point-cloud, normals - Outputs: mesh, sdf - Platforms: cpu, cuda, python ## Lineage - extends [Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/poisson-surface-reconstruction.md) ## Combines with - [Quadric Error Metric Simplification](https://texelatlas.vercel.app/t/qem-mesh-simplification.md): Reduce the dense reconstructed mesh for use in real-time. - [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md): Fast queries against the reconstructed mesh for downstream processing. ## Sources 1. [primary] Michael Kazhdan, Hugues Hoppe (2013) Screened poisson surface reconstruction. ACM Transactions on Graphics. https://doi.org/10.1145/2487228.2487237 (verified via crossref on 2026-11-29) 2. [implementation] mkazhdan (2015) mkazhdan/PoissonRecon. https://github.com/mkazhdan/PoissonRecon License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Screened Poisson Surface Reconstruction." https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction/ (accessed 2026-12-01). --- id: "sdf-ambient-occlusion" title: "SDF Ambient Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unreal, godot] year_introduced: 2008 inputs: [sdf, normals, depth] outputs: [visibility-mask, normals] style: "both" dynamic: "both" cost: "cheap" authority: "wrong-nebula, 2026" url: "https://texelatlas.vercel.app/t/sdf-ambient-occlusion/" sources_verified_at: "2026-11-29" --- # SDF Ambient Occlusion (wrong-nebula, 2026) > Estimates AO by sampling a (often baked) signed distance field along the normal and comparing distance to expected distance, giving cheap, view-independent occlusion. ## Reach for it when - depth-based occlusion has screen edge artefacts - static architecture on web needs cheap clean darkening - want view-independent occlusion for mobile - no hardware ray tracing but need stable crease shading ## How it works At a surface point, take a few samples along the normal at increasing distances h. In free space the field value at distance h equals h; geometry nearby shrinks it, so the deficit (h minus the field value) weighted by a decaying factor accumulates into an occlusion estimate. A volumetric SDF baked from the static scene makes this a few texture lookups per pixel with no screen-space limits, and the same field supports soft shadows and bent normals. Quality depends on field resolution, and moving objects require a separate analytic or cascaded field. The public Fast-SDF-AO project applies this with temporally accumulated ray schedules, multi-bounce colour correction and specular occlusion, offered in four quality tiers. ## When to use it Choose it for web or mobile scenes with static architecture where you want artifact-free AO without depth buffer limits. Prefer [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) when scenes are fully dynamic, [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) when hardware RT is present, and [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) when no field is available. ## Cost cheap — A few 3D texture taps per pixel (and optional temporal accumulation); memory scales with the volume resolution. Measured GPU Weight: 3.07× baseline (light) — 0.1011 ms median / 0.1057 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.35× baseline (light) — 0.0374 ms median (2.7× faster on L4). Ampere A100 scaling: 1.86× baseline (feather) — 0.0537 ms median (1.88× faster on A100). ## Failure modes - Blocky or blurry occlusion from low-resolution fields - Light leaking through thin walls thinner than a voxel - Does not follow dynamic objects unless the field is updated - Banding when few samples are used without noise or accumulation ## Engine support - unreal: builtin — `Project Settings > Rendering > Generate Mesh Distance Fields; Skylight > Occlusion > DFAO (Distance Field Ambient Occlusion)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/distance-field-ambient-occlusion-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: sdf, normals, depth - Outputs: visibility-mask, normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unreal, godot ## Presets ### Fast-SDF-AO quality tiers (low / medium / high / ultra) (json-params; parameter preset) ```json { "low": { "aoScale": 0.5, "contactMode": 1, "aoRaySchedule": [ 2, 1, 1 ], "settleFrames": 32, "sunShadowSteps": 52, "orbShadowSteps": 28, "shadowRefine": 0 }, "medium": { "aoScale": 0.5, "contactMode": 0, "aoRaySchedule": [ 2, 2, 1 ], "settleFrames": 48, "sunShadowSteps": 48, "orbShadowSteps": 28, "shadowRefine": 1 }, "high": { "aoScale": 0.5, "contactMode": 0, "aoRaySchedule": [ 4, 3, 2 ], "settleFrames": 64, "sunShadowSteps": 68, "orbShadowSteps": 36, "shadowRefine": 1 }, "ultra": { "aoScale": 0.5, "contactMode": 0, "aoRaySchedule": [ 4, 3, 2 ], "settleFrames": 64, "sunShadowSteps": 68, "orbShadowSteps": 36, "shadowRefine": 2 } } ``` Attribution: MIT, wrong-nebula/Fast-SDF-AO; basis: 0 ### Left: flat ambient. Right: SDF AO, five distance-field taps along the normal (glsl-fragment; rendered 2026-11-29) ```json { "INT": 1, "STEP": 0.14, "K": 0.9 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const float INT=1.0; // P const float STEP=0.14; // P const float K=0.9; // P float sao(vec3 P,vec3 N){float occ=0.,sca=1.; for(int i=0;i<5;i++){float h=.02+STEP*float(i);occ+=(h-sdf(P+N*h))*sca;sca*=.75;} return clamp(1.-K*occ,0.,1.);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao=R?clamp(1.-INT*(1.-sao(P,n)),0.,1.):1.;col=mix(ambShade(P,n,vec3(ao)),sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Combination ideas - [Crease sharpness steers generated wear](https://texelatlas.vercel.app/ideas/crease-aware-generative-texturing/) ## Sources 1. [primary] wrong-nebula (2026) wrong-nebula/Fast-SDF-AO. https://github.com/wrong-nebula/Fast-SDF-AO License: MIT. (verified via github on 2026-11-29) 2. [tutorial] Inigo Quilez Soft shadows in raymarched SDFs. iquilezles.org. https://iquilezles.org/articles/rmshadows (verified via http on 2026-11-29) ## Cite this entry Texel. "SDF Ambient Occlusion." https://texelatlas.vercel.app/t/sdf-ambient-occlusion/ (accessed 2026-12-01). --- id: "sdf-csg-smooth-min" title: "SDF Modeling: CSG and Smooth Minimum" aliases: [smooth union, smin] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 2013 inputs: [sdf] outputs: [sdf, normals] style: "both" dynamic: "dynamic" cost: "medium" authority: "Quilez" url: "https://texelatlas.vercel.app/t/sdf-csg-smooth-min/" sources_verified_at: "2026-11-29" --- # SDF Modeling: CSG and Smooth Minimum (Quilez) > Builds shapes as signed distance functions combined with min, max and negation for union, intersection and difference, plus smooth-min variants that blend primitives organically. The workhorse of shader-based modelling. ## Reach for it when - combine shapes with union and subtraction in a shader - want organic blobby blending between primitives - animate procedural shapes by parameters - hard edges where two shapes meet look harsh - model objects entirely in code ## How it works Each primitive (sphere, box, capsule, torus ...) is a function returning signed distance to its surface. Union is min(a,b), intersection is max(a,b), subtraction is max(a,-b); transforms apply to the sample point before evaluating (translation, rotation, repetition, bending). Replacing min with a smooth minimum, such as the polynomial form min(a,b) minus a bump of height k/4 when the two distances are within k, gives a rounded blend whose radius is k. Variants return a blend factor too, so materials and colours can be mixed. Normals are central or tetrahedral gradient differences. Rendering is by sphere tracing or by meshing the field with marching cubes or dual contouring. ## When to use it Choose it for procedural modelling, organic blobs, motion graphics, editor tools and anything where the shape must be animated or edited by parameters. Prefer meshes with [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md) for authored assets, [Segment Tracing](https://texelatlas.vercel.app/t/segment-tracing.md) or [Enhanced Sphere Tracing](https://texelatlas.vercel.app/t/enhanced-sphere-tracing.md) when the field is non-Euclidean (warped), and baked grid SDFs when the scene is too complex to evaluate per sample. ## Cost medium — Cost per sample is the sum of all primitives evaluated; scene complexity multiplies with marching steps per pixel. Measured GPU Weight: 59.62× baseline (heavy) — 1.9614 ms median / 1.9922 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 45.87× baseline (heavy) — 0.7293 ms median (2.69× faster on L4). Ampere A100 scaling: 35.42× baseline (heavy) — 1.0202 ms median (1.92× faster on A100). ## Failure modes - Smooth-min distances are not true distances: blended regions shorten or lengthen steps and may need a step scale below 1 - Min/max of two exact SDFs gives only a bound inside and near intersections, which slows or breaks tracing at shallow angles - Different smooth-min formulations are not associative, so blend results depend on order - Domain warping and twisting break Lipschitz-1 and cause missed hits or banding - Evaluating a large tree per sample is slow unless bounding volumes cull primitives ## Engine support - blender: builtin — `Math node > Smooth Minimum; Geometry Nodes > SDF Grid Boolean` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/utilities/math/math.html, checked 2026-12-01) ## Dataflow - Inputs: sdf - Outputs: sdf, normals - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Smooth-union SDF scene (orbiting blobs, rounded box, floor) (glsl-fragment; rendered 2026-11-29) ```json { "blend_radius": 0.45, "max_steps": 96 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Smooth-union SDF scene, sphere traced and shaded. const float K = 0.45; // smooth-union blend radius (world units) const int STEPS = 96; // max sphere-tracing iterations const float MAX_DIST = 30.0; const float EPS = 0.0015; float smin(float a, float b, float k) { // quadratic polynomial smooth minimum float h = max(k - abs(a - b), 0.0) / k; return min(a, b) - h * h * k * 0.25; } float sdSphere(vec3 p, float r) { return length(p) - r; } float sdRoundBox(vec3 p, vec3 b, float r) { vec3 q = abs(p) - b; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r; } float map(vec3 p) { float t = iTime; float d = sdRoundBox(p - vec3(0.0, 0.0, 0.0), vec3(0.55, 0.35, 0.55), 0.12); for (int i = 0; i < 3; i++) { float a = t * 0.9 + float(i) * 2.0943951; vec3 c = vec3(cos(a) * 1.15, 0.25 * sin(t * 1.3 + float(i)), sin(a) * 1.15); d = smin(d, sdSphere(p - c, 0.45), K); } float floorD = p.y + 0.9; return smin(d, floorD, K * 0.6); } vec3 calcNormal(vec3 p) { vec2 e = vec2(1.0, -1.0) * 0.0015; return normalize(e.xyy * map(p + e.xyy) + e.yyx * map(p + e.yyx) + e.yxy * map(p + e.yxy) + e.xxx * map(p + e.xxx)); } float softShadow(vec3 ro, vec3 rd) { float res = 1.0, t = 0.03; for (int i = 0; i < 40; i++) { float h = map(ro + rd * t); res = min(res, 8.0 * h / t); t += clamp(h, 0.02, 0.4); if (res < 0.001 || t > 8.0) break; } return clamp(res, 0.0, 1.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y; vec3 ro = vec3(3.2, 1.8, 3.6); vec3 ta = vec3(0.0, -0.1, 0.0); vec3 w = normalize(ta - ro); vec3 u = normalize(cross(w, vec3(0.0, 1.0, 0.0))); vec3 v = cross(u, w); vec3 rd = normalize(uv.x * u + uv.y * v + 1.8 * w); vec3 col = mix(vec3(0.75, 0.85, 0.95), vec3(0.25, 0.4, 0.7), clamp(rd.y * 1.5 + 0.3, 0.0, 1.0)); float t = 0.0; bool hit = false; for (int i = 0; i < STEPS; i++) { float d = map(ro + rd * t); if (d < EPS) { hit = true; break; } t += d; if (t > MAX_DIST) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 l = normalize(vec3(0.6, 0.8, 0.3)); float dif = clamp(dot(n, l), 0.0, 1.0) * softShadow(p + n * 0.01, l); float amb = 0.5 + 0.5 * n.y; float spe = pow(clamp(dot(reflect(-l, n), -rd), 0.0, 1.0), 32.0); vec3 base = p.y < -0.85 ? vec3(0.55) * (0.6 + 0.4 * mod(floor(p.x * 2.0) + floor(p.z * 2.0), 2.0)) : vec3(0.9, 0.45, 0.25); col = base * (dif * vec3(1.0, 0.95, 0.85) * 1.2 + amb * vec3(0.25, 0.3, 0.4)) + spe * 0.4 * dif; col = mix(col, vec3(0.75, 0.85, 0.95), 1.0 - exp(-0.0025 * t * t)); } fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(0.4545)), 1.0); } ``` Attribution: written for this index ## Combines with - [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md): The SDF supplies the step size for ray marching. - [Jump Flooding Algorithm](https://texelatlas.vercel.app/t/jump-flooding-algorithm.md): Voronoi/distance fields from JFA can be combined with analytic SDFs in the same scene. ## Combination ideas - [Scanned objects as SDF primitives](https://texelatlas.vercel.app/ideas/captured-sdf-sculpting/) ## Sources 1. [primary] Inigo Quilez Smooth minimum. iquilezles.org. https://iquilezles.org/articles/smin (verified via http on 2026-11-29) 2. [tutorial] Inigo Quilez Distance functions. iquilezles.org. https://iquilezles.org/articles/distfunctions (verified via http on 2026-11-29) ## Cite this entry Texel. "SDF Modeling: CSG and Smooth Minimum." https://texelatlas.vercel.app/t/sdf-csg-smooth-min/ (accessed 2026-12-01). --- id: "sdf-soft-shadows" title: "SDF Soft Shadows" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2008 inputs: [sdf] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Quilez" url: "https://texelatlas.vercel.app/t/sdf-soft-shadows/" sources_verified_at: "2026-11-29" --- # SDF Soft Shadows (Quilez) > While sphere-tracing toward the light, the smallest ratio of distance-to-surface over travelled distance approximates the light's unoccluded cone, giving cheap penumbrae for free. ## Reach for it when - soft shadows needed in ray marched scenes - cheap penumbra without many shadow rays - shadertoy style scene needs realistic shading - sdf rendering shadows look hard and aliased ## How it works A shadow ray is marched through a signed distance field from the shaded point toward the light. At each step, the SDF value d at distance t tells how close the ray passes to geometry; the ratio k*d/t is the sine-like angle of the nearest occluder as seen from the origin. Keeping the minimum of this ratio over the ray, clamped to 0..1, gives a visibility value that is 1 in open space, falls smoothly near silhouettes and reaches 0 when the ray hits geometry. The constant k sets penumbra width. Improvements use the previous step's distance to estimate the closest approach more accurately, remove banding, and smooth the result. The same field also serves AO and global-illumination queries. ## When to use it Choose it when the scene is already an SDF (raymarched demos, shader-art, Dreams-style content, or a baked or voxelised distance field) and you want cheap soft shadows with no shadow map. Prefer [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) with [Percentage-Closer Soft Shadows](https://texelatlas.vercel.app/t/percentage-closer-soft-shadows.md) for triangle-mesh scenes, [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) for accurate penumbrae against meshes, and [Screen-Space Contact Shadows](https://texelatlas.vercel.app/t/contact-shadows.md) for a screen-space supplement. ## Cost medium — Tens of SDF evaluations per pixel; cost depends on the complexity of the field function. Measured GPU Weight: 24.84× baseline (heavy) — 0.8173 ms median / 0.842 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 22.43× baseline (heavy) — 0.3566 ms median (2.29× faster on L4). Ampere A100 scaling: 14.67× baseline (moderate) — 0.4224 ms median (1.93× faster on A100). ## Failure modes - Penumbra is an approximation of one light cone and is not physically accurate for large lights - Banding or light leaks if the step size is clamped too low or too high - Inexact (Lipschitz-violating) SDFs from domain warping give artifacts - Self-shadowing at grazing angles needs a normal offset ## Engine support - unreal: builtin — `Project Settings > Rendering > Generate Mesh Distance Fields; Light > Mobility = Movable/Stationary > Distance Field Shadows` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/distance-field-soft-shadows-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: sdf - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Raymarched spheres and box with soft shadows (glsl-fragment; rendered 2026-11-29) ```json { "SHADOW_K": 10, "SHADOW_STEPS": 48 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: raymarched SDF scene with soft shadows const float SHADOW_K = 10.0; // penumbra sharpness (higher = harder) const int SHADOW_STEPS = 48; const vec3 LIGHT_DIR = normalize(vec3(-0.6, 0.8, 0.4)); float sdSphere(vec3 p, float r) { return length(p) - r; } 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); } float map(vec3 p) { float ground = p.y + 1.0; float s = sdSphere(p - vec3(-0.9, -0.1 + 0.15 * sin(iTime), 0.0), 0.9); float b = sdBox(p - vec3(1.1, -0.4, 0.3), vec3(0.6, 0.6, 0.6)); return min(ground, min(s, b)); } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.001, 0.0); return normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx))); } // Soft shadow: track the narrowest cone (min of k*d/t) seen along the ray to the light. float softShadow(vec3 ro, vec3 rd) { float res = 1.0; float t = 0.02; for (int i = 0; i < SHADOW_STEPS; i++) { float d = map(ro + rd * t); res = min(res, SHADOW_K * d / t); t += clamp(d, 0.02, 0.5); if (res < 0.001 || t > 12.0) break; } res = clamp(res, 0.0, 1.0); return res * res * (3.0 - 2.0 * res); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 1.6, -5.5); vec3 rd = normalize(vec3(uv.x, uv.y - 0.2, 1.6)); float t = 0.0; bool hit = false; for (int i = 0; i < 100; i++) { float d = map(ro + rd * t); if (d < 0.001) { hit = true; break; } t += d; if (t > 30.0) break; } vec3 col = mix(vec3(0.75, 0.85, 1.0), vec3(0.3, 0.5, 0.9), clamp(uv.y + 0.6, 0.0, 1.0)); if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); float diff = clamp(dot(n, LIGHT_DIR), 0.0, 1.0); float sh = softShadow(p + n * 0.01, LIGHT_DIR); vec3 albedo = (p.y < -0.99) ? vec3(0.8) * (0.8 + 0.2 * step(0.0, sin(p.x * 3.0) * sin(p.z * 3.0))) : vec3(0.9, 0.45, 0.3); float sky = 0.5 + 0.5 * n.y; col = albedo * (vec3(1.0, 0.95, 0.85) * diff * sh * 1.2 + vec3(0.3, 0.4, 0.55) * sky * 0.35); } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Inigo Quilez Soft shadows in raymarched SDFs. iquilezles.org. https://iquilezles.org/articles/rmshadows (verified via http on 2026-11-29) ## Cite this entry Texel. "SDF Soft Shadows." https://texelatlas.vercel.app/t/sdf-soft-shadows/ (accessed 2026-12-01). --- id: "segment-anything" title: "Segment Anything (SAM)" aliases: [SAM] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python, webgpu] year_introduced: 2023 inputs: [photos] outputs: [visibility-mask] style: "both" dynamic: "both" cost: "medium" authority: "Kirillov et al., 2023" url: "https://texelatlas.vercel.app/t/segment-anything/" sources_verified_at: "2026-11-29" --- # Segment Anything (SAM) (Kirillov et al., 2023) > A promptable image segmentation model: a heavy image encoder runs once, then a light decoder turns points, boxes or masks into object masks in milliseconds. ## Reach for it when - need to cut out a subject from a photo quickly - isolate objects before 3d reconstruction - want masks from a click or a box - label parts of a splat or image interactively ## How it works A ViT image encoder computes an embedding once per image. A prompt encoder converts clicks, boxes or rough masks into tokens, and a lightweight mask decoder attends between the prompt tokens and the embedding to predict several candidate masks with predicted quality scores, handling ambiguity such as part versus whole. The model was trained on a very large mask dataset built with a model-in-the-loop data engine. An automatic mode prompts a regular grid of points and filters the resulting masks by predicted IoU, stability under thresholding and non-maximum suppression, producing masks for everything in the image. Since the decoder is cheap, interactive use is possible in a browser after the embedding step. ## When to use it Choose it for object masks to isolate subjects before reconstruction, to build [Visual Hull (Shape from Silhouette)](https://texelatlas.vercel.app/t/visual-hull.md) silhouettes or to label splats. Prefer [SAM 2](https://texelatlas.vercel.app/t/sam2.md) for video or multi-view propagation of masks, and plain thresholding when the background is controlled. ## Cost medium — Encoder is heavy (about a hundred milliseconds or more on a GPU for large variants); prompts are cheap afterwards. ## Failure modes - Fine structures and thin boundaries are rounded off - Masks are not semantically labelled, so class names need another model - Ambiguous prompts return the wrong granularity (part or whole) - No temporal consistency across frames or views ## Dataflow - Inputs: photos - Outputs: visibility-mask - Platforms: cuda, python, webgpu ## Presets ### SAM automatic mask generator defaults (json-params; parameter preset) ```json { "points_per_side": 32, "pred_iou_thresh": 0.88, "stability_score_thresh": 0.95, "stability_score_offset": 1, "box_nms_thresh": 0.7, "crop_n_layers": 0, "min_mask_region_area": 0 } ``` Attribution: Parameter names follow facebookresearch/segment-anything (Apache-2.0); values are the SamAutomaticMaskGenerator defaults, written for this index. ## Lineage - extended by [SAM 2](https://texelatlas.vercel.app/t/sam2.md) ## Combines with - [Visual Hull (Shape from Silhouette)](https://texelatlas.vercel.app/t/visual-hull.md): Per-view SAM masks give the silhouettes that visual hull carving intersects. ## Sources 1. [primary] Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alexander C. Berg, Wan-Yen Lo, Piotr Dollár, Ross Girshick (2023) Segment Anything. arXiv preprint (cs.CV). https://arxiv.org/abs/2304.02643 (verified via arxiv on 2026-11-29) 2. [implementation] facebookresearch (2023) facebookresearch/segment-anything. https://github.com/facebookresearch/segment-anything License: Apache-2.0. (verified via github on 2026-11-29) 3. [tutorial] Meta AI Segment Anything project page. aidemos.meta.com. https://aidemos.meta.com/segment-anything (verified via http on 2026-11-29) ## Cite this entry Texel. "Segment Anything (SAM)." https://texelatlas.vercel.app/t/segment-anything/ (accessed 2026-12-01). --- id: "segment-tracing" title: "Segment Tracing" domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda] year_introduced: 2020 inputs: [sdf] outputs: [depth, normals] style: "both" dynamic: "dynamic" cost: "medium" authority: "Galin et al., 2020" url: "https://texelatlas.vercel.app/t/segment-tracing/" sources_verified_at: "2026-11-29" --- # Segment Tracing (Galin et al., 2020) > Ray marching that uses local Lipschitz bounds over ray segments instead of a global bound, so it can safely trace fields that are not distance functions (warped, displaced, procedural) with long, efficient steps. ## Reach for it when - ray marching overshoots on warped or noisy fields - distance function isn't exact so marching artefacts appear - displaced sdf needs tiny steps and runs slowly - smooth blends with large radii break the marcher - trace non-distance fields safely with long steps ## How it works Sphere tracing needs the global Lipschitz constant of the field to be 1. For general functions F, a safe step along the ray is the field value divided by a Lipschitz bound valid on the segment that will be covered. Segment tracing computes that bound locally: it estimates the bound over a segment starting at the current point (from the function's structure, e.g. through interval-friendly primitives and operators that propagate local bounds), and uses it to jump while still not missing the root. Because the bound only needs to hold in the region the step could reach, it is far tighter than a global constant, and long steps are possible far from the surface. It also gives a clean way to handle blending, displacement and domain deformations with provable correctness. ## When to use it Choose it when your function is built from operators that break exact distances (smooth blends with large radii, warps, noise displacement) and sphere tracing either overshoots or needs very small step factors. Prefer [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md) or [Enhanced Sphere Tracing](https://texelatlas.vercel.app/t/enhanced-sphere-tracing.md) for exact SDF primitives and [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) when you want a mesh rather than per-pixel evaluation. ## Cost medium — Per-step overhead for the local bound, offset by fewer steps on warped fields; depends heavily on how bounds are propagated in the shader. Measured GPU Weight: 24.77× baseline (heavy) — 0.7778 ms median / 0.7945 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 23.77× baseline (heavy) — 0.3756 ms median (2.07× faster on L4). Ampere A100 scaling: 15.46× baseline (moderate) — 0.4452 ms median (1.75× faster on A100). ## Failure modes - Requires the modelling language to expose local Lipschitz bounds for every operator - Implementation is more complex than a one-line step - Bound estimation can be conservative and eat the speed-up on rough noise displacements - Needs per-primitive analysis to avoid very loose bounds ## Dataflow - Inputs: sdf - Outputs: depth, normals - Platforms: webgl2, webgpu, desktop-gpu, cuda ## Presets ### Segment Tracing — global-Lipschitz sphere tracing steps (left) vs accelerated local-Lipschitz segment tracing (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_LIPSCHITZ_GAIN": 1, "P_HEATMAP": 0.78, "P_SPLIT": 0.48, "P_WAVE_AMP": 0.85 } ``` ```glsl const float P_LIPSCHITZ_GAIN = 1.0; // P Local Bound Gain [0.2, 1.5, 0.04] const float P_HEATMAP = 0.78; // P Step Heatmap Mix [0.0, 1.0, 0.02] const float P_SPLIT = 0.48; // P Sphere / Segment [0.0, 1.0, 0.02] const float P_WAVE_AMP = 0.85; // P Field Gradient [0.2, 1.5, 0.04] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Non-unit-Lipschitz implicit surface f(p) = 0 (gyroid-modulated metaball cluster with steep local gradient!) float evalField(vec3 p, float amp, float spin) { vec3 q = p; q.xz = rot2(spin * 0.32) * q.xz; q.yz = rot2(0.25) * q.yz; float dBase = length(q) - 0.82; // High-frequency gyroid displacement whose global Lipschitz constant is large (~1 + 4.5*amp), // but whose local directional gradient |grad(f).rd| is tiny in empty space and along tangent rays! float freq = 5.2; float g = sin(q.x * freq) * cos(q.y * freq) + sin(q.y * freq) * cos(q.z * freq) + sin(q.z * freq) * cos(q.x * freq); float env = exp(-max(dBase, 0.0) * 1.4); return dBase + 0.14 * amp * g * env; } // Analytical directional gradient magnitude |grad(f) . rd| along ray segment for Segment Tracing bound float localDirLipschitz(vec3 p, vec3 rd, float amp, float spin) { float e = 0.025; float df = abs(evalField(p + rd * e, amp, spin) - evalField(p - rd * e, amp, spin)) / (2.0 * e); // Conservative safety floor over segment interval return max(df * 1.18, 0.72); } vec3 calcNormal(vec3 p, float amp, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( evalField(p + e.xyy, amp, spin) - evalField(p - e.xyy, amp, spin), evalField(p + e.yxy, amp, spin) - evalField(p - e.yxy, amp, spin), evalField(p + e.yyx, amp, spin) - evalField(p - e.yyx, amp, spin) )); } // Turbo-like step-count heatmap (deep blue = few fast steps, cyan/green = moderate, amber/red = heavy iteration cost) vec3 stepHeatmap(float s) { s = clamp(s, 0.0, 1.0); vec3 c0 = vec3(0.06, 0.14, 0.38); vec3 c1 = vec3(0.10, 0.72, 0.84); vec3 c2 = vec3(0.96, 0.78, 0.16); vec3 c3 = vec3(0.98, 0.18, 0.24); if (s < 0.35) return mix(c0, c1, s / 0.35); if (s < 0.70) return mix(c1, c2, (s - 0.35) / 0.35); return mix(c2, c3, (s - 0.70) / 0.30); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float lipGain = clamp(P_LIPSCHITZ_GAIN, 0.15, 1.6); float heatMix = clamp(P_HEATMAP, 0.0, 1.0); float amp = clamp(P_WAVE_AMP, 0.15, 1.6); float spin = iTime; vec3 ro = vec3(0.0, 0.05, 2.48); vec3 rd = normalize(vec3(uv, -1.52)); bool isSegment = screenX >= split; // Global worst-case Lipschitz constant required for conservative Sphere Tracing float globalLip = 1.0 + 2.45 * amp; float t = 0.0; bool hit = false; int steps = 0; const int MAX_STEPS = 72; for (int i = 0; i < MAX_STEPS; i++) { steps = i + 1; vec3 p = ro + rd * t; float f = evalField(p, amp, spin); if (f < 0.0025) { hit = true; break; } float stepSize; if (!isSegment) { // Standard Sphere Tracing: forced to divide by global worst-case Lipschitz bound everywhere! stepSize = f / globalLip; } else { // Segment Tracing: compute tight local directional Lipschitz bound over candidate segment! float locLip = mix(globalLip, localDirLipschitz(p, rd, amp, spin), clamp(lipGain, 0.0, 1.0)); stepSize = f / max(locLip, 0.55); } t += max(stepSize, 0.004); if (t > 6.0) break; } float stepNorm = float(steps) / float(MAX_STEPS); vec3 heatCol = stepHeatmap(stepNorm); // Background shows the marching step-count cost in empty silhouette space (where Segment Tracing shines brightest!) vec3 bgCol = mix(vec3(0.03, 0.04, 0.068), vec3(0.08, 0.11, 0.16), smoothstep(-0.55, 0.55, uv.y)); vec3 col = mix(bgCol, heatCol * 0.72, heatMix * 0.85); if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, amp, spin); vec3 l1 = normalize(vec3(0.62, 0.86, 0.55)); vec3 l2 = normalize(vec3(-0.75, -0.22, 0.52)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); float spec = pow(max(dot(n, hVec), 0.0), 42.0) * 0.48; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.28; vec3 surfBase = mix(vec3(0.76, 0.78, 0.82), heatCol, heatMix * 0.78); col = surfBase * (0.26 + 0.84 * diff1 + 0.24 * diff2) + vec3(spec) + vec3(0.45, 0.75, 1.0) * rim; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md) ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): Provides the operators whose local bounds it propagates. ## Sources 1. [primary] Eric Galin, Eric Guérin, Axel Paris, Adrien Peytavie (2020) Segment Tracing Using Local Lipschitz Bounds. Computer Graphics Forum. https://doi.org/10.1111/cgf.13951 (verified via crossref on 2026-11-29) 2. [tutorial] Inigo Quilez Distance functions. iquilezles.org. https://iquilezles.org/articles/distfunctions (verified via http on 2026-11-29) ## Cite this entry Texel. "Segment Tracing." https://texelatlas.vercel.app/t/segment-tracing/ (accessed 2026-12-01). --- id: "self-organizing-gaussians-compression" title: "Self-Organizing Gaussians (SOG) 2D Codebook Image Compression" aliases: [SOG, Self-Organizing Gaussian Grids, SOGS] domain: "capture" stage: "capture" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, cuda, python] year_introduced: 2024 inputs: [gaussians] outputs: [texture, gaussians] style: "photoreal" dynamic: "static" cost: "cheap" authority: "Morgenstern et al., 2024" url: "https://texelatlas.vercel.app/t/self-organizing-gaussians-compression/" sources_verified_at: "2026-11-30" --- # Self-Organizing Gaussians (SOG) 2D Codebook Image Compression (Morgenstern et al., 2024) > Arranges unstructured 3D Gaussian attributes onto locally smooth 2D grids via spatial sorting and k-means codebooks, compressing splat scenes by over an order of magnitude with standard PNG or WebP image codecs. ## Reach for it when - 3d gaussian splat ply files are too huge to stream over the web - compress splat attributes into standard image formats like png or webp - exploit spatial coherence among neighboring gaussians for 10x smaller files - pack 3dgs positions scales and colors into smooth 2d texture atlases - reduce gaussian splatting vram footprint without slow runtime neural decoding ## How it works Uncompressed 3D Gaussian Splatting PLY files store floating-point positions, rotations, scales, opacities, and spherical-harmonic coefficients in arbitrary order, routinely reaching hundreds of megabytes. Self-Organizing Gaussians (SOG) turns this irregular point set into smooth **2D attribute images** that conventional image compressors handle efficiently. First, Gaussians are mapped onto a 2D pixel grid using a **parallel linear assignment / Morton-to-grid sorting** pass (such as PLAS) that places spatially and attribute-similar splats at neighboring texels. Continuous attributes—scales, base colors, quaternion rotations, and higher-order spherical harmonics—are quantized via **1D or vector k-means codebooks** stored as compact lookup tables, while positions are split across low- and high-byte log-encoded channels to retain precision. Because adjacent pixels now share strongly correlated indices and values, lossless WebP or PNG compression shrinks the packed attribute textures by roughly 15×–40× with minimal PSNR loss. At load time, browsers decode the images natively with hardware or OS image decoders and reconstruct splats directly from textures and tiny JSON codebook metadata on the GPU. ## When to use it Choose it when shipping 3D Gaussian splats over the web or storing large libraries of static captures where download size, native browser decoding speed, and low GPU memory footprint matter. Prefer [gaussian-splatting-3dgs](gaussian-splatting-3dgs) raw PLY/SPZ storage during active training or iterative editing before final export. Prefer [basis-universal-ktx2](basis-universal-ktx2) when compressing conventional PBR surface textures rather than unstructured splat attributes. Prefer [draco-mesh-compression](draco-mesh-compression) for indexed triangle meshes. ## Cost cheap — Decoding uses native browser PNG/WebP decoders plus simple texel/codebook lookups on the GPU; offline grid sorting and k-means clustering take seconds to minutes depending on splat count. ## Failure modes - Over-aggressive codebook quantization can band smooth specular highlights or flatten subtle spherical-harmonic color shifts - Lossy image compression applied to position or index textures corrupts splat coordinates catastrophically; index/position maps must stay lossless - Spatial grid sorting is offline and breaks incremental insertion or deletion of individual splats - Very large scenes can exceed GPU maximum 2D texture dimensions unless split into tiled regions or LOD chunks ## Dataflow - Inputs: gaussians - Outputs: texture, gaussians - Platforms: webgpu, webgl2, desktop-gpu, cuda, python ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combines with - [Hierarchical Binary-Tree 3DGS LOD & Paged Streaming](https://texelatlas.vercel.app/t/hierarchical-binary-tree-3dgs-lod.md): Packs each streamed spatial LOD node into compact lossless WebP codebook textures for low-latency web streaming. - [Web Gaussian Splat Renderers (three.js)](https://texelatlas.vercel.app/t/web-gaussian-splat-viewers.md): Lets browser viewers decode and render compressed splats directly from image textures without shipping huge PLY files. ## Sources 1. [primary] Wieland Morgenstern, Florian Barthel, Anna Hilsmann, Peter Eisert (2024) Compact 3D Scene Representation via Self-Organizing Gaussian Grids. Lecture Notes in Computer Science. https://doi.org/10.1007/978-3-031-73013-9_2 (verified via crossref on 2026-11-30) 2. [implementation] fraunhoferhhi (2023) fraunhoferhhi/Self-Organizing-Gaussians. https://github.com/fraunhoferhhi/Self-Organizing-Gaussians License: NOASSERTION. (verified via github on 2026-11-30) 3. [implementation] WilliamLiu-1997 (2026) WilliamLiu-1997/Gaussian-Splat-Lite. https://github.com/WilliamLiu-1997/Gaussian-Splat-Lite License: Apache-2.0. (verified via github on 2026-11-30) 4. [implementation] playcanvas (2024) playcanvas/splat-transform. https://github.com/playcanvas/splat-transform License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Self-Organizing Gaussians (SOG) 2D Codebook Image Compression." https://texelatlas.vercel.app/t/self-organizing-gaussians-compression/ (accessed 2026-12-01). --- id: "semi-sharp-creases" title: "Semi-Sharp Creases" domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, blender, unity, unreal, desktop-gpu] year_introduced: 1998 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "DeRose et al., 1998" url: "https://texelatlas.vercel.app/t/semi-sharp-creases/" sources_verified_at: "2026-11-29" --- # Semi-Sharp Creases (DeRose et al., 1998) > Gives each subdivision edge a real-valued sharpness: for that many levels it follows sharp (crease) rules, then switches to smooth rules. Lets a coarse cage carry bevels and hard-to-soft transitions without extra edge loops. ## Reach for it when - subdivision surface rounds off hard edges - need partially sharp edges on a smooth model - control edge sharpness on subdivided mesh - hard-surface models look blobby when subdivided ## How it works Tag edges with a sharpness s >= 0. At each subdivision level, edges with s > 0 use the crease rules (new edge point on the edge midpoint; vertices on two creases follow a cubic B-spline curve along the crease) and their children receive s-1. Edges with s <= 0 use the standard smooth rule. A fractional s blends between the sharp and smooth outcomes, giving a continuum from soft bevel to hard line. A crease vertex touched by three or more creases is a corner. Integer sharpness ties the visual result to the number of subdivision levels used for display, so renderers evaluate the limit surface with the same sharpness semantics. The rules are defined on top of Catmull-Clark and extend to Loop. ## When to use it Choose it when modelling hard-surface or mechanical forms on a subdivision cage and you want crisp edges that stay editable by a single number. Prefer extra support loops when the DCC pipeline or target engine does not support crease tags, and [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md) alone for organic shapes. ## Cost cheap — Negligible beyond plain subdivision: a handful of extra branches per edge at each refinement level. Measured GPU Weight: 21.52× baseline (heavy) — 0.667 ms median / 0.6933 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.53× baseline (moderate) — 0.2788 ms median (2.39× faster on L4). Ampere A100 scaling: 14.12× baseline (moderate) — 0.4067 ms median (1.64× faster on A100). ## Failure modes - Results differ if a viewer uses fewer subdivision levels than the sharpness value - Creases ending inside a smooth region leave a visible dart-shaped pinch - Fractional sharpness varies between implementations unless they follow the same blending rule - Exports to formats without crease support silently turn them into smooth edges ## Engine support - blender: builtin — `Edit Mode > Edge > Edge Crease (Shift-E); Subdivision Surface modifier honours it` (evidence: https://docs.blender.org/manual/en/5.2/modeling/modifiers/generate/subdivision_surface.html, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, blender, unity, unreal, desktop-gpu ## Presets ### Semi-Sharp Creases — smooth C^2 fillet s=0 (left) vs tunable sharpness weight s (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SHARPNESS": 3.5, "P_ZEBRA_VIS": 0.7, "P_ROT_SPEED": 0.7, "P_SPLIT": 0.48 } ``` ```glsl const float P_SHARPNESS = 3.5; // P Crease Weight s [0.0, 6.0, 0.1] const float P_ZEBRA_VIS = 0.70; // P Zebra Curvature [0.0, 1.0, 0.05] const float P_ROT_SPEED = 0.70; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Smooth / Crease Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdRoundBox(vec3 p, vec3 b, float r) { vec3 q = abs(p) - b + vec3(r); return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r; } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / max(k, 1e-4), 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Mechanical cross-block with semi-sharp crease edges whose bevel radius decays as 2^(-s) float mapCreaseObj(vec3 p, float sharpness, float spin, out float creaseDist) { vec3 q = p; q.xz = rot2(spin * 0.55) * q.xz; q.yz = rot2(0.45) * q.yz; // Semi-sharp subdivision rule: sharpness s delays smooth averaging for s levels => fillet radius ~ r0 * 2^(-s) float rCrease = 0.24 * pow(0.5, clamp(sharpness, 0.0, 6.0)) + 0.004; float dMain = sdRoundBox(q, vec3(0.56, 0.56, 0.56), rCrease); float dRib = sdRoundBox(q, vec3(0.76, 0.24, 0.24), rCrease * 0.85); float dRib2 = sdRoundBox(q, vec3(0.24, 0.76, 0.24), rCrease * 0.85); float d = smin(dMain, min(dRib, dRib2), rCrease * 0.9); // Measure proximity to the tagged crease lines on the cube boundary vec3 aq = abs(q); float eXY = length(aq.xy - vec2(0.56)); float eYZ = length(aq.yz - vec2(0.56)); float eXZ = length(aq.xz - vec2(0.56)); creaseDist = min(eXY, min(eYZ, eXZ)); return d; } vec3 calcNormal(vec3 p, float sharpness, float spin) { vec2 e = vec2(0.0018, 0.0); float tmp; return normalize(vec3( mapCreaseObj(p + e.xyy, sharpness, spin, tmp) - mapCreaseObj(p - e.xyy, sharpness, spin, tmp), mapCreaseObj(p + e.yxy, sharpness, spin, tmp) - mapCreaseObj(p - e.yxy, sharpness, spin, tmp), mapCreaseObj(p + e.yyx, sharpness, spin, tmp) - mapCreaseObj(p - e.yyx, sharpness, spin, tmp) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isCrease = screenX >= split; float sharp = isCrease ? clamp(P_SHARPNESS, 0.0, 6.0) : 0.0; float zebraAmt = clamp(P_ZEBRA_VIS, 0.0, 1.0); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.04, 2.55); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.025, 0.035, 0.055), vec3(0.072, 0.092, 0.138), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; float cDist = 1.0; for (int i = 0; i < 64; i++) { float d = mapCreaseObj(ro + rd * t, sharp, spin, cDist); if (d < 0.0018) { hit = true; break; } t += d * 0.85; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, sharp, spin); vec3 rDir = reflect(rd, n); // Studio zebra reflection stripes reveal exact G1/G2 continuity across the semi-sharp crease! float zebra = smoothstep(-0.12, 0.12, sin(rDir.y * 26.0 + rDir.x * 10.0)); vec3 zebraCol = mix(vec3(0.10, 0.14, 0.22), vec3(0.92, 0.96, 1.0), zebra); vec3 l1 = normalize(vec3(0.58, 0.82, 0.55)); float diff = max(dot(n, l1), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 64.0); float fres = 0.10 + 0.90 * pow(1.0 - max(dot(n, -rd), 0.0), 4.0); vec3 baseAlb = isCrease ? vec3(0.20, 0.68, 0.82) : vec3(0.76, 0.54, 0.36); vec3 litCol = baseAlb * (0.28 + 0.82 * diff) + vec3(1.0) * spec * 0.65; col = mix(litCol, zebraCol * (0.72 + 0.28 * baseAlb), zebraAmt * (0.45 + 0.45 * fres)); // Tag semi-sharp crease edges with crisp amber line on right side if (isCrease && sharp > 0.2) { float tagLine = smoothstep(0.038, 0.008, cDist); col = mix(col, vec3(1.0, 0.78, 0.20), tagLine * 0.82 * clamp(sharp / 2.5, 0.0, 1.0)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md) ## Combines with - [Catmull-Clark Subdivision](https://texelatlas.vercel.app/t/catmull-clark-subdivision.md): Edge sharpness tags modify the refinement rules at each level. ## Combination ideas - [Crease sharpness steers generated wear](https://texelatlas.vercel.app/ideas/crease-aware-generative-texturing/) - [Triangle-native Loop subdivision with continuous semi-sharp creases](https://texelatlas.vercel.app/ideas/loop-subdivision-semi-sharp-creases/) ## Sources 1. [primary] Tony DeRose, Michael Kass, Tien Truong (1998) Subdivision surfaces in character animation. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280826 (verified via crossref on 2026-11-29) 2. [implementation] PixarAnimationStudios (2012) PixarAnimationStudios/OpenSubdiv. https://github.com/PixarAnimationStudios/OpenSubdiv License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Semi-Sharp Creases." https://texelatlas.vercel.app/t/semi-sharp-creases/ (accessed 2026-12-01). --- id: "separable-sss" title: "Separable subsurface scattering" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2015 inputs: [gbuffer, depth, material-params] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Jimenez et al., 2015" url: "https://texelatlas.vercel.app/t/separable-sss/" sources_verified_at: "2026-11-29" --- # Separable subsurface scattering (Jimenez et al., 2015) > Real-time screen-space SSS that replaces a full 2D diffusion blur with two 1D Gaussian-like passes (horizontal and vertical), cutting cost while matching the full profile closely. Used for skin in games. ## Reach for it when - skin looks like hard plastic or stone - full screen-space diffusion blur is too slow - need real-time translucent skin, wax or marble - ears and nostrils should glow softly under light ## How it works After shading the diffuse irradiance of a character, the engine blurs it in screen space with the diffusion profile of skin. Jimenez et al. observe that the true kernel can be approximated as a separable product when the profile is expanded into a mean-free-path-scaled Gaussian sum, so the blur splits into a horizontal and a vertical pass, each with a modest number of taps. Sample weights and offsets are precomputed per profile (as a 1D kernel, with the central sample kept in colour-preserving RGB weights). Blur width is scaled by depth and its screen-space derivatives so scattering stays constant in world space, and masked by a stencil to skin regions. Specular is added after the blur so highlights stay crisp. A transmittance term estimates light passing through thin ears. ## When to use it Choose it for real-time skin, wax and marble on characters in a deferred or forward+ pipeline. Prefer [Christensen-Burley diffusion profile](https://texelatlas.vercel.app/t/christensen-burley-sss.md) for offline rendering where ray queries are available. Prefer texture-space SSS when you need to blur across UV islands. Combine with [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) detail so microdetail is kept sharp. ## Cost medium — Two screen-space blur passes over skin pixels; scales with screen coverage and kernel tap count. Measured GPU Weight: 2.19× baseline (light) — 0.0719 ms median / 0.0737 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.84× baseline (feather) — 0.0292 ms median (2.46× faster on L4). Ampere A100 scaling: 1.34× baseline (feather) — 0.0386 ms median (1.86× faster on A100). ## Failure modes - Screen-space blur bleeds across depth discontinuities (ears over background, nose over cheek) unless depth-aware - Colour bleed from other geometry into skin at silhouettes - No light transport through thin geometry beyond the cheap transmittance term - Flickering under TAA when jittered input is blurred inconsistently ## Engine support - blender: builtin — `EEVEE SubsurfaceModule evaluates screen-space Burley subsurface scattering on deferred closure buffers` (evidence: https://github.com/blender/blender/blob/main/source/blender/draw/engines/eevee/eevee_subsurface.cc, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.subsurf_scatter_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) — Screen-space SSS; Forward+ and Mobile. - unreal: builtin — `Subsurface Profile asset > Separable; Material > Shading Model = Subsurface Profile` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, depth, material-params - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Light skin (Fitzpatrick I) base colour (three-material; rendered 2026-11-29) ```json { "color": "#edd1c4", "roughness": 0.5, "metalness": 0, "ior": 1.4 } ``` Attribution: written for this index; skin colour and IOR from physicallybased.info (CC0), roughness chosen here; SSS itself is a screen-space pass and is not part of MeshPhysicalMaterial; basis: 3 ## Lineage - extends [Pre-integrated skin shading](https://texelatlas.vercel.app/t/pre-integrated-skin-shading.md) ## Sources 1. [primary] Jorge Jimenez, Károly Zsolnai, Adrian Jarabo, Christian Freude, Thomas Auzinger, Xian‐Chun Wu, Javier von der Pahlen, Michael Wimmer, Diego Gutierrez (2015) Separable Subsurface Scattering. Computer Graphics Forum. https://doi.org/10.1111/cgf.12529 (verified via crossref on 2026-11-29) 2. [implementation] iryoku (2012) iryoku/separable-sss. https://github.com/iryoku/separable-sss License: NOASSERTION. (verified via github on 2026-11-29) 3. [dataset] Anton Palmqvist physicallybased.info. physicallybased.info. https://physicallybased.info/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Separable subsurface scattering." https://texelatlas.vercel.app/t/separable-sss/ (accessed 2026-12-01). --- id: "sequential-impulses" title: "Sequential impulses (rigid bodies)" aliases: [PGS, projected Gauss-Seidel] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, webgl2, webgpu, unity, godot] year_introduced: 2006 inputs: [mesh] outputs: [animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Catto" url: "https://texelatlas.vercel.app/t/sequential-impulses/" sources_verified_at: "2026-11-29" --- # Sequential impulses (rigid bodies) (Catto) > Iterative velocity-level rigid-body solver: apply impulses to each contact and joint constraint in turn, with warm starting, which is the core of Box2D and many game engines. ## Reach for it when - box stacks wobble or collapse in my physics - need stable contacts and joints for game rigid bodies - rigid body solver that handles many constraints iteratively - objects jitter at rest on the ground - build a box2d-style physics engine ## How it works Each step finds contact manifolds, then builds velocity constraints (normal, friction, joints) in terms of Jacobians. Constraints are solved one at a time, applying an impulse that drives its relative velocity to the target, clamped to a valid range (non-negative normal impulse, friction within the Coulomb cone), and accumulated across iterations. Warm starting reuses last frame's accumulated impulses so stacks converge in a handful of iterations. Position error is corrected either by Baumgarte stabilisation (adds bias velocity) or by a separate position solve. Sleeping islands and a persistent contact cache keep it fast. It is projected Gauss-Seidel on the velocity-level LCP. ## When to use it Choose it for stacking, joints and general game rigid bodies. Prefer [Soft Step solver / substepping](https://texelatlas.vercel.app/t/soft-step-solver.md) for the modern Box2D v3 approach with substeps and soft constraints, [MuJoCo articulated-body dynamics with convex contacts](https://texelatlas.vercel.app/t/mujoco-articulated-dynamics.md) for robotics and articulated mechanisms in reduced coordinates, and [Verlet integration with relaxation constraints](https://texelatlas.vercel.app/t/verlet-integration-constraints.md) for loose particle chains where stacking fidelity isn't needed. ## Cost cheap — Linear in constraints x iterations; cheap per body. ## Failure modes - Baumgarte stabilisation adds energy: objects jitter or pop out of penetration - Iteration limits give soft, squishy stacks and slow tall towers - Joint chains with large mass ratios stretch - Restitution plus warm starting gives energy gain on resting contacts if not handled ## Engine support - babylonjs: official — `@babylonjs/havok with new BABYLON.HavokPlugin(true, havokInstance) via scene.enablePhysics(...)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Physics/v2/Plugins/havokPlugin.ts, checked 2026-12-01) - blender: builtin — `Scene Properties > Rigid Body World > Solver Iterations (Bullet impulse solver)` (evidence: https://docs.blender.org/manual/en/5.2/physics/rigid_body/world.html, checked 2026-12-01) - godot: builtin — `Built-in JoltPhysics3D (Project Settings > Physics > 3D > Physics Engine = Jolt Physics) and GodotPhysics3D` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/jolt_physics/jolt_project_settings.cpp, checked 2026-12-01) - unity: builtin — `Project Settings > Physics > Default Solver Iterations (Physics.defaultSolverIterations; PhysX iterative velocity-level constraint solver)` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics-defaultSolverIterations.html, checked 2026-12-01) - unreal: builtin — `Chaos Physics iterative rigid-body solver (BodyInstance.position_solver_iteration_count and velocity_solver_iteration_count)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/BodyInstance, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: animation - Platforms: cpu, webgl2, webgpu, unity, godot ## Lineage - extended by [Soft Step solver / substepping](https://texelatlas.vercel.app/t/soft-step-solver.md) ## Combination ideas - [Captured rooms you can bump into](https://texelatlas.vercel.app/ideas/walkable-captured-scenes/) ## Sources 1. [primary] Erin Catto Fast and Simple Physics using Sequential Impulses. GDC 2006. https://box2d.org/files/ErinCatto_SequentialImpulses_GDC2006.pdf (verified via http on 2026-11-29) 2. [primary] Erin Catto Modeling and Solving Constraints. GDC 2009. https://box2d.org/files/ErinCatto_ModelingAndSolvingConstraints_GDC2009.pdf (verified via http on 2026-11-29) 3. [implementation] erincatto (2015) erincatto/box2d. https://github.com/erincatto/box2d License: MIT. (verified via github on 2026-11-29) 4. [implementation] dimforge (2020) dimforge/rapier. https://github.com/dimforge/rapier License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Sequential impulses (rigid bodies)." https://texelatlas.vercel.app/t/sequential-impulses/ (accessed 2026-12-01). --- id: "shadow-map-bias-slope-scale-normal-offset" title: "Shadow map depth bias (constant, slope-scale, normal offset)" aliases: [shadow bias, depth bias, slope-scaled depth bias, normal-offset shadows, shadow acne fix] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2014 inputs: [depth, normals, mesh] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Dou et al., 2014" url: "https://texelatlas.vercel.app/t/shadow-map-bias-slope-scale-normal-offset/" sources_verified_at: "2026-11-29" --- # Shadow map depth bias (constant, slope-scale, normal offset) (Dou et al., 2014) > A family of offsets that keep a surface from shadowing itself in a shadow map: a constant depth offset, a term scaled by the surface's slope to the light, and a shift along the normal before lookup. ## Reach for it when - shadows covered in stripes on surfaces facing away from light - shadow detaches from the bottom of objects - floor looks striped or moire-patterned in shadowed areas - characters seem to float above ground because shadow is offset - shadow leaks through thin walls near contact point ## How it works A shadow map stores depth at texel centres, but a receiver sampled between centres sits at a slightly different light-space depth, so a tilted surface compares itself against a sample that can be nearer than the point being shaded. Without correction half of every texel reads as shadowed (acne). Three fixes are combined. A **constant bias** subtracts a fixed amount from the receiver depth. A **slope-scaled bias** grows with the tangent of the angle between normal and light (or the depth gradient, as hardware polygon offset does), because the error grows as the surface becomes grazing. A **normal offset** moves the world position along the geometric normal by about one shadow texel (scaled by the sine of the light angle) before projecting, which shrinks the needed depth bias and avoids light leaking at contact points. Biases are best expressed in texel or world-space units per cascade, not clip-space depth, because texel footprint changes with every cascade and light type. Adaptive schemes compute the bias from the receiver's actual depth gradient. ## When to use it Use it in every shadow-mapped renderer; it is the first thing to tune before blaming filtering. Prefer normal offset plus a small slope-scaled term over a big constant bias, which causes peter-panning (shadows detached from their casters). Reach for [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) or [Variance Shadow Maps](https://texelatlas.vercel.app/t/variance-shadow-maps.md) when the remaining artifact is blocky edges rather than self-shadowing, and use [Screen-Space Contact Shadows](https://texelatlas.vercel.app/t/contact-shadows.md) to recover the small-scale detail that bias removes. Per-cascade tuning matters with [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md); [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md) and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) reduce but do not remove the need. ## Cost cheap — A few ALU operations in the shadow lookup; the depth-bias state in the caster pass is free on fixed-function hardware. Measured GPU Weight: 0.99× baseline (feather) — 0.0325 ms median / 0.0397 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 0.99× baseline (feather) — 0.0157 ms median (2.07× faster on L4). Ampere A100 scaling: 1× baseline (feather) — 0.0288 ms median (1.13× faster on A100). ## Failure modes - Shadow acne stripes on surfaces near-parallel to the light when bias is too small - Peter-panning: the shadow visibly detaches from the base of the caster when constant bias is too large - Light leaking at thin walls and contact edges because bias exceeds wall thickness - A bias tuned for one cascade or light range shows acne or detachment in another - Normal offset shrinks or grows silhouettes of shadows on curved or finely tessellated geometry - Back-face casting hides acne on closed meshes but leaks on thin or open geometry ## Engine support - babylonjs: builtin — `shadowGenerator.bias, shadowGenerator.normalBias` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Shadows/shadowGenerator.ts, checked 2026-12-01) - blender: builtin — `EEVEE > Render Properties > Sampling > Shadows (virtual shadow maps + normal/jitter bias)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/sampling.html, checked 2026-12-01) - godot: builtin — `Light3D.shadow_bias and Light3D.shadow_normal_bias` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Light3D.xml, checked 2026-12-01) — Constant plus normal offset; no separate slope-scale parameter. - metal: builtin — `MTLRenderCommandEncoder.setDepthBias(_:slopeScale:clamp:)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlrendercommandencoder/setdepthbias(_:slopescale:clamp:).json, checked 2026-12-01) — Constant and slope-scale bias; normal-offset bias is done in MSL. - threejs: builtin — `light.shadow.bias, light.shadow.normalBias` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/lights/LightShadow.js, checked 2026-12-01) - unity: builtin — `Light > Shadow Type; Light.shadowBias and Light.shadowNormalBias` (evidence: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Light-shadowBias.html, checked 2026-12-01) - unreal: builtin — `Light component > Details > Shadow Bias properties (set per light)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/shadowing-in-unreal-engine, checked 2026-12-01) — Per-light bias properties. - webgpu: builtin — `GPUDepthStencilState: depthBias, depthBiasSlopeScale, depthBiasClamp` (evidence: https://www.w3.org/TR/webgpu/, checked 2026-12-01) — Hardware constant and slope-scale bias; normal-offset bias is done in WGSL. ## Dataflow - Inputs: depth, normals, mesh - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Bias comparison: acne, tuned, peter-panning (glsl-fragment; rendered 2026-11-29) ```json { "slope": 2, "texels": 32, "bias_panels": [ 0, 0.08, 0.3 ] } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Three panels: no bias (acne), tuned bias, huge bias (peter-panning). // Top-down view of a ground plane lit at a grazing angle, shadowed by a wall, with a low-res shadow map. const float SLOPE = 2.0; // receiver light-depth gradient across the plane (grazing light) const float TEXELS = 32.0; // shadow-map resolution across one panel const float GAP = 0.8; // depth separation gained per unit of shadow length behind the wall const vec3 BIAS = vec3(0.0, 0.08, 0.3); const float WALL_X = -0.5; float lit(vec2 p, float bias) { float t = 2.0 / TEXELS; vec2 c = (floor((p + 1.0) / t) + 0.5) * t - 1.0; // texel centre: what the map actually stored bool inShadowTexel = c.x > WALL_X && c.x < WALL_X + 0.6 && abs(c.y) < 0.35; float stored = SLOPE * c.x - (inShadowTexel ? GAP * (c.x - WALL_X) : 0.0); float receiver = SLOPE * p.x; return (receiver - bias > stored) ? 0.0 : 1.0; // 0 = shadowed } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float panel = floor(uv.x * 3.0); vec2 p = vec2(fract(uv.x * 3.0) * 2.0 - 1.0, uv.y * 2.0 - 1.0); float bias = panel < 0.5 ? BIAS.x : (panel < 1.5 ? BIAS.y : BIAS.z); float l = lit(p, bias); vec3 ground = vec3(0.86, 0.80, 0.68) * (0.30 + 0.70 * l); ground *= 0.92 + 0.08 * sin(p.y * 40.0); bool wall = p.x > WALL_X - 0.08 && p.x < WALL_X && abs(p.y) < 0.35; vec3 col = wall ? vec3(0.35, 0.22, 0.18) : ground; float edge = abs(fract(uv.x * 3.0) - 0.5); if (edge > 0.495) col = vec3(1.0); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Lineage - extends [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) ## Combines with - [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md): Per-cascade texel size defines the bias and normal-offset magnitude applied in each cascade lookup. - [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md): Bias must cover the whole PCF kernel footprint, so the receiver depth is plane-fitted or offset before the multi-tap compare. ## Sources 1. [primary] Hang Dou, Yajie Yan, Ethan Kerzner, Zeng Dai, Chris Wyman (2014) Adaptive depth bias for shadow maps. Proceedings of the 18th meeting of the ACM SIGGRAPH Symposium on Interactive 3D Graphics and Games. https://doi.org/10.1145/2556700.2556706 (verified via crossref on 2026-11-29) 2. [tutorial] Microsoft Common Techniques to Improve Shadow Depth Maps. learn.microsoft.com. https://learn.microsoft.com/en-us/windows/win32/dxtecharts/common-techniques-to-improve-shadow-depth-maps (verified via http on 2026-11-29) 3. [tutorial] Matt Pettineo A Sampling of Shadow Techniques. therealmjp.github.io. https://therealmjp.github.io/posts/shadow-maps (verified via http on 2026-11-29) 4. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Shadow map depth bias (constant, slope-scale, normal offset)." https://texelatlas.vercel.app/t/shadow-map-bias-slope-scale-normal-offset/ (accessed 2026-12-01). --- id: "shadow-mapping" title: "Shadow Mapping" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 1978 inputs: [mesh, depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Williams, 1978" url: "https://texelatlas.vercel.app/t/shadow-mapping/" sources_verified_at: "2026-11-29" --- # Shadow Mapping (Williams, 1978) > Render scene depth from the light, then test each shaded point's light-space depth against that stored depth to decide whether it is shadowed. ## Reach for it when - objects need to cast shadows in real time - scene has no depth cues because it lacks shadows - dynamic lights with moving objects need shadowing - simple gpu-friendly shadow technique for any geometry ## How it works Pass one renders the scene from the light's point of view into a depth texture. Pass two shades the camera view: each fragment is transformed into light clip space, its depth is compared with the texel stored in the shadow map, and the fragment is in shadow if something nearer to the light was recorded there. Because the map is a discretised image, the test is binary and suffers from aliasing, self-shadowing (acne) and light leaking, so practical implementations add a constant plus slope-scaled depth bias, normal-offset along the surface normal, and a tight light frustum fit. Directional lights use orthographic projections, spot lights perspective, and point lights six faces or a dual-paraboloid layout. Almost every other technique in this domain is a filter, partition or reformulation of this basic test. ## When to use it Choose it as the default shadow source for dynamic scenes in rasterised engines; it is what three.js `castShadow` uses. Prefer [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) when you need soft edges, [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) when the sun must cover a large view distance, [Shadow Volumes](https://texelatlas.vercel.app/t/shadow-volumes.md) when you need pixel-exact hard edges without resolution limits, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) when hardware ray tracing is available and exact contact is required. ## Cost cheap — One extra depth-only pass per light plus a texture fetch per fragment; cost grows with shadow-map resolution and casters, not with screen resolution. Measured GPU Weight: 2.99× baseline (light) — 0.0984 ms median / 0.1036 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.23× baseline (light) — 0.0355 ms median (2.77× faster on L4). Ampere A100 scaling: 1.78× baseline (feather) — 0.0514 ms median (1.91× faster on A100). ## Failure modes - Shadow acne from depth quantisation and receiver slope - Peter-panning: too much bias detaches the shadow from its caster - Jagged or swimming edges at low map resolution (perspective aliasing) - Light leaking at thin walls and contact points ## Engine support - babylonjs: builtin — `new BABYLON.ShadowGenerator(1024, light); shadowGenerator.getShadowMap().renderList.push(mesh)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Lights/Shadows/shadowGenerator.ts, checked 2026-12-01) - blender: builtin — `Light Properties > Shadow (EEVEE)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_settings.html, checked 2026-12-01) - godot: builtin — `Light3D.shadow_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Light3D.xml, checked 2026-12-01) - threejs: builtin — `renderer.shadowMap.enabled = true; light.castShadow = true` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/lights/LightShadow.js, checked 2026-12-01) - unity: builtin — `Light > Shadow Type = Soft/Hard Shadows (URP and HDRP)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Shadows-in-HDRP.md, checked 2026-12-01) — URP and HDRP. - unreal: builtin — `Directional, Point, Spot, and Rect Lights > Cast Shadows (Virtual Shadow Maps or Cascaded/standard Shadow Maps)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/shadowing-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: shadow-map depth test with no bias (acne). Right: slope-scaled bias; both on a 64x64 map (glsl-fragment; rendered 2026-11-29) ```json { "RES": 64, "BIAS": 0.03, "SLOPE": 1 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float EXT=3.2; vec3 lU(){return normalize(cross(vec3(0.,1.,0.),LD));} vec3 lV(){return cross(LD,lU());} vec2 toL(vec3 P){return vec2(dot(P,lU()),dot(P,lV()));} float recv(vec3 P){return 10.-dot(P,LD);} float smTex(vec2 st,float res){float tx=2.*EXT/res;vec2 c=(floor(st/tx)+.5)*tx;vec3 n; return isect(LD*10.+lU()*c.x+lV()*c.y,-LD,n);} float vis1(vec3 P,vec3 N,vec2 st,vec2 o,float res,float b){float tx=2.*EXT/res;vec2 cc=(floor((st+o)/tx)+.5)*tx;vec3 q; float d=isect(LD*10.+lU()*cc.x+lV()*cc.y,-LD,q);vec2 e=cc-st; float zr=recv(P)+(e.x*dot(N,lU())+e.y*dot(N,lV()))/max(dot(N,LD),.15); return zr-b>d?0.:1.;} vec3 shadeV(vec3 P,vec3 N,float vis){return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*vis*1.3);} const float RES=64.0; // P const float BIAS=0.03; // P const float SLOPE=1.0; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t; float cn=max(dot(n,LD),.05),bz=R?BIAS+SLOPE*2.*EXT/RES*min(sqrt(1.-cn*cn)/cn,6.):0.; float vis=recv(P)-bz>smTex(toL(P),RES)?0.:1.; col=mix(shadeV(P,n,vis),sky(rd),smoothstep(6.,25.,t)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extended by [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) - extended by [Deep shadow maps](https://texelatlas.vercel.app/t/deep-shadow-maps.md) - extended by [Omnidirectional (cube) shadow maps for point lights](https://texelatlas.vercel.app/t/omnidirectional-shadow-maps.md) - extended by [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) - extended by [Shadow map depth bias (constant, slope-scale, normal offset)](https://texelatlas.vercel.app/t/shadow-map-bias-slope-scale-normal-offset.md) - extended by [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md) ## Sources 1. [primary] Lance Williams (1978) Casting curved shadows on curved surfaces. Proceedings of the 5th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/800248.807402 (verified via crossref on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) 3. [tutorial] Joey de Vries Shadow Mapping. learnopengl.com. https://learnopengl.com/Advanced-Lighting/Shadows/Shadow-Mapping (verified via http on 2026-11-29) ## Cite this entry Texel. "Shadow Mapping." https://texelatlas.vercel.app/t/shadow-mapping/ (accessed 2026-12-01). --- id: "shadow-volumes" title: "Shadow Volumes" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [desktop-gpu, webgl2, unity, unreal, godot] year_introduced: 1977 inputs: [mesh] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "medium" authority: "Crow, 1977" url: "https://texelatlas.vercel.app/t/shadow-volumes/" sources_verified_at: "2026-11-29" --- # Shadow Volumes (Crow, 1977) > Extrudes occluder silhouettes away from the light into volumes, then uses a stencil counter to decide whether each pixel lies inside any of them. ## Reach for it when - shadow map edges are jaggy or aliased - need razor sharp pixel-accurate hard shadows - shadow acne and peter-panning in simple scenes - stencil-based shadows for closed meshes ## How it works For each point light, find silhouette edges of casters (edges shared by a front-facing and a back-facing triangle) and extrude them to infinity, forming closed volumes. Render the scene depth first, then draw volume faces into the stencil buffer: increment on back faces and decrement on front faces that pass depth (z-fail, Carmack's reverse) or the opposite for z-pass. Pixels with a non-zero count lie in shadow and are excluded from the lighting pass. The result has exact, pixel-accurate hard edges independent of any shadow-map resolution, but requires watertight, manifold geometry, silhouette computation and heavy fill rate. ## When to use it Choose it for razor-sharp hard shadows on simple, closed meshes where shadow-map aliasing is unacceptable. Prefer [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) for any content with alpha tests, foliage, skinned or non-manifold meshes, [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) for soft edges, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) for exact results on modern hardware. ## Cost medium — Fill-rate bound: large extruded quads cover many pixels, so cost scales with overdraw of volume faces. Measured GPU Weight: 51.13× baseline (heavy) — 1.6822 ms median / 1.7911 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 51.33× baseline (heavy) — 0.8161 ms median (2.06× faster on L4). Ampere A100 scaling: 33.22× baseline (heavy) — 0.9567 ms median (1.76× faster on A100). ## Failure modes - Requires closed, manifold meshes or shadows fail - Cap and far-plane handling needed for z-fail correctness - Hard edges only; softening needs extra tricks - Very high fill-rate cost with many lights ## Dataflow - Inputs: mesh - Outputs: visibility-mask - Platforms: desktop-gpu, webgl2, unity, unreal, godot ## Presets ### Shadow Volumes (Carmack Reverse) — extruded silhouette shadow wedges & stencil count (left) vs razor-sharp stencil-masked shadows (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VOL_ALPHA": 0.6, "P_LIGHT_SWEEP": 0.55, "P_AMBIENT": 0.28, "P_SPLIT": 0.48 } ``` ```glsl const float P_VOL_ALPHA = 0.60; // P Volume Extrusion Vis [0.1, 1.0, 0.05] const float P_LIGHT_SWEEP = 0.55; // P Light Motion [0.0, 1.6, 0.05] const float P_AMBIENT = 0.28; // P Ambient Level [0.05, 0.6, 0.05] const float P_SPLIT = 0.48; // P Volumes / Stencil [0.0, 1.0, 0.02] 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); } // Sharp polygonal obelisks & floating prism casting extruded geometric shadow volumes vec2 mapCasters(vec3 p) { float d1 = sdBox(p - vec3(-0.36, -0.10, -0.15), vec3(0.14, 0.42, 0.14)); float d2 = sdBox(p - vec3(0.34, 0.06, -0.05), vec3(0.16, 0.16, 0.16)); vec2 res = (d1 < d2) ? vec2(d1, 2.0) : vec2(d2, 3.0); return res; } vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.52, 1.0); vec2 c = mapCasters(p); if (c.x < res.x) res = c; return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Exact point-in-extruded-shadow-volume test (projects ray backward toward lightPos to see if a caster blocks it) bool inShadowVolume(vec3 p, vec3 lPos) { vec3 toL = lPos - p; float distL = length(toL); vec3 dir = toL / max(distL, 1e-4); float t = 0.025; for (int i = 0; i < 24; i++) { float h = mapCasters(p + dir * t).x; if (h < 0.0025) return true; t += max(h, 0.025); if (t > distL - 0.04) break; } return false; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float volVis = clamp(P_VOL_ALPHA, 0.05, 1.0); float amb = clamp(P_AMBIENT, 0.05, 0.7); float t = iTime * max(P_LIGHT_SWEEP, 0.0); vec3 lPos = vec3(0.95 * cos(t * 0.65), 0.78, 0.75 * sin(t * 0.65) + 0.15); vec3 ro = vec3(0.0, 0.42, 2.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.15, -1.48)); vec3 col = mix(vec3(0.04, 0.05, 0.09), vec3(0.11, 0.15, 0.24), smoothstep(-0.3, 0.6, uv.y)); float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * dist); if (h.x < 0.002) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 9.0) break; } float maxMarch = min(hit.x, 5.5); if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 lDir = normalize(lPos - p); float lDist = length(lPos - p); float atten = 2.6 / (0.4 + lDist * lDist); // Exact binary stencil shadow test (pixel-sharp, zero shadow-map texel aliasing!) float lit = inShadowVolume(p + n * 0.008, lPos) ? 0.0 : 1.0; vec3 alb = vec3(0.68, 0.66, 0.62); if (hit.y < 1.5) { float chk = mod(floor(p.x * 3.0) + floor(p.z * 3.0), 2.0); alb = mix(vec3(0.50, 0.52, 0.56), vec3(0.76, 0.75, 0.72), chk); } else if (hit.y < 2.5) { alb = vec3(0.86, 0.54, 0.26); } else { alb = vec3(0.26, 0.72, 0.88); } float ndl = max(dot(n, lDir), 0.0); col = alb * (vec3(0.16, 0.22, 0.34) * amb * 2.2 + vec3(1.40, 1.24, 1.02) * ndl * lit * atten); if (hit.y < 1.5) col = mix(vec3(0.04, 0.05, 0.09), col, exp(-hit.x * 0.11)); } // Left: Visualize the translucent extruded silhouette shadow-volume wedges & entry/exit stencil faces! if (screenX < split) { float volHits = 0.0; float edgeHits = 0.0; bool prevIn = false; for (int s = 1; s <= 22; s++) { float ts = (float(s) / 22.0) * maxMarch; vec3 sp = ro + rd * ts; bool curIn = inShadowVolume(sp, lPos); if (curIn) volHits += 1.0; if (curIn != prevIn && s > 1) edgeHits += 1.0; prevIn = curIn; } vec3 wedgeCol = mix(vec3(0.16, 0.78, 1.0), vec3(1.0, 0.28, 0.54), clamp(edgeHits * 0.5, 0.0, 1.0)); col += wedgeCol * (volHits / 22.0) * volVis * 0.85; col += vec3(0.28, 0.96, 1.0) * clamp(edgeHits, 0.0, 2.0) * volVis * 0.24; } // Glowing point light indicator float glowD = length(cross(lPos - ro, rd)); col += vec3(1.4, 1.15, 0.75) * exp(-glowD * 12.0) * 0.55; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Franklin C. Crow (1977) Shadow algorithms for computer graphics. Proceedings of the 4th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/563858.563901 (verified via crossref on 2026-11-29) 2. [tutorial] Cass Everitt, Mark J. Kilgard (2003) Practical and Robust Stenciled Shadow Volumes for Hardware-Accelerated Rendering. arXiv preprint (cs.GR). https://arxiv.org/abs/cs/0301002 (verified via arxiv on 2026-11-29) ## Cite this entry Texel. "Shadow Volumes." https://texelatlas.vercel.app/t/shadow-volumes/ (accessed 2026-12-01). --- id: "shallow-water-equations" title: "Shallow Water Equations (Height-field Water)" aliases: [SWE, height-field water, virtual pipes] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu] year_introduced: 1990 inputs: [heightfield] outputs: [heightfield, normals] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Kass & Miller, 1990" url: "https://texelatlas.vercel.app/t/shallow-water-equations/" sources_verified_at: "2026-11-29" --- # Shallow Water Equations (Height-field Water) (Kass & Miller, 1990) > Simulate water as a 2D height field plus a velocity field, so waves, ripples and shoreline flow update on a grid with one cheap pass per step. ## Reach for it when - interactive ripples when objects touch water - pool or river flow that reacts to the player - flood or shoreline movement on a grid - cheap water simulation for mobile or webgl - splashes and waves on a height field ## How it works The 3D flow is vertically averaged, which leaves a water height h and horizontal velocity per grid cell. Momentum is changed by the gradient of the water surface plus terrain height (gravity pushes water downhill) and mass moves as the divergence of the flux. A simple form stores a height and a vertical velocity per cell and sets acceleration proportional to the average of the four neighbour heights minus the cell height, then damps; a better form uses per-edge flux (virtual pipes) to stay mass-conserving over a terrain. Each step is explicit and needs a time step below the wave speed over cell size (CFL). Interaction is easy: add a bump to h for a drop or a moving object. The height field becomes a displaced grid with normals from central differences, and the same grid can store foam and flow for shading. ## When to use it Choose it for interactive ripples, splashes, pools and river or flood flow where the surface is single-valued and interaction by objects is required, at a cost that fits a mobile or WebGL budget. Prefer [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md) for an open-sea surface, and [Gerstner (Trochoidal) Waves](https://texelatlas.vercel.app/t/gerstner-waves.md) for analytic swells. Prefer a particle or grid-based 3D fluid solver when you need breaking waves, overturning or splashes that leave the surface. Use [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md) to light the floor under it. ## Cost cheap — One or two grid passes per step; resolution and number of substeps are the cost control. Measured GPU Weight: 35.07× baseline (heavy) — 1.1539 ms median / 1.191 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 33.77× baseline (heavy) — 0.5369 ms median (2.15× faster on L4). Ampere A100 scaling: 24.74× baseline (heavy) — 0.7124 ms median (1.62× faster on A100). ## Failure modes - Instability or explosion when the time step violates the CFL condition - Energy and mass drift with the simple 4-neighbour wave equation, giving ever-growing or dying ripples - Cannot represent overturning waves, splashes or vertical surfaces because the surface is a single-valued height - Reflection from the grid boundary unless an absorbing sponge layer is added - Shoreline wet/dry cells produce negative depths and flickering without careful handling ## Engine support - unreal: official — `Enable Niagara Fluids plugin; Niagara system from the Shallow Water template` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/niagara-fluids-reference-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: heightfield - Outputs: heightfield, normals - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu ## Presets ### Shallow water equations — interactive rippling wave interference & pool caustics (glsl-fragment; rendered 2026-11-30) ```json { "P_WAVE_AMP": 1, "P_DAMPING": 0.55, "P_CAUSTICS": 1.15, "P_SPEED": 1 } ``` ```glsl const float P_WAVE_AMP = 1.0; // P Wave Height [0.2, 2.2, 0.05] const float P_DAMPING = 0.55; // P Spatial Damping [0.1, 1.4, 0.04] const float P_CAUSTICS = 1.15; // P Floor Caustics [0.0, 2.2, 0.05] const float P_SPEED = 1.0; // P Wave Speed c [0.0, 2.5, 0.05] // Evaluate shallow-water wave height h(x,z,t) solving d2h/dt2 = c^2 * laplacian(h) - damp * dh/dt // Superposition of periodic droplet impulses, orbiting wake source, and basin-wall boundary reflections float wavePacket(vec2 p, vec2 src, float t, float k, float c, float damp) { float r = length(p - src); float phase = k * (r - c * t); float env = exp(-r * damp * 1.15) / (0.35 + r * 1.1); return sin(phase) * env; } float evalHeight(vec2 p, float t, float amp, float damp, float c) { float h = 0.0; // 4 staggered droplet impulse centers with shallow-water phase speed c = sqrt(g * H) vec2 s0 = vec2(-0.52, -0.26); vec2 s1 = vec2(0.56, 0.34); vec2 s2 = vec2(0.18 * cos(t * 0.85), 0.32 * sin(t * 0.65)); // moving wake emitter vec2 s3 = vec2(-0.28, 0.44); h += 0.34 * wavePacket(p, s0, t, 14.0, c * 0.42, damp); h += 0.30 * wavePacket(p, s1, t + 1.3, 16.5, c * 0.46, damp); h += 0.38 * wavePacket(p, s2, t * 1.15, 19.0, c * 0.38, damp * 1.1); h += 0.24 * wavePacket(p, s3, t + 2.7, 12.5, c * 0.44, damp); // Mirror-image boundary reflections from square basin walls at |x|=1.4, |z|=1.4 h += 0.16 * wavePacket(p, vec2(2.8 - s1.x, s1.y), t + 1.3, 16.5, c * 0.46, damp); h += 0.16 * wavePacket(p, vec2(-2.8 - s0.x, s0.y), t, 14.0, c * 0.42, damp); // Circular diffraction scatter off submerged limestone pillar at (-0.12, -0.05) vec2 pil = vec2(-0.12, -0.05); float rp = length(p - pil); h += 0.22 * sin(18.0 * (rp - c * 0.4 * t)) * exp(-abs(rp - 0.24) * 3.8); return h * amp * 0.11; } vec3 evalNormal(vec2 p, float t, float amp, float damp, float c) { float e = 0.012; float hx = evalHeight(p + vec2(e, 0.0), t, amp, damp, c) - evalHeight(p - vec2(e, 0.0), t, amp, damp, c); float hz = evalHeight(p + vec2(0.0, e), t, amp, damp, c) - evalHeight(p - vec2(0.0, e), t, amp, damp, c); return normalize(vec3(-hx, 2.0 * e, -hz)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float amp = clamp(P_WAVE_AMP, 0.1, 2.5); float damp = clamp(P_DAMPING, 0.08, 1.6); float caustGain = clamp(P_CAUSTICS, 0.0, 2.4); float spd = max(P_SPEED, 0.0); float t = iTime * spd; // Elevated isometric-perspective view looking down into a sunlit turquoise water basin vec3 ro = vec3(0.0, 2.15, 2.05); vec3 ta = vec3(0.0, -0.15, 0.0); vec3 ww = normalize(ta - ro); vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.55 * ww); vec3 sunDir = normalize(vec3(0.45, 0.85, -0.35)); // Intersect water plane y = 0 float tWater = -ro.y / min(rd.y, -0.001); vec3 pW = ro + rd * tWater; vec2 wp = pW.xz; // Check raised cylindrical stone pillar piercing the water surface at (-0.12, -0.05) vec2 pilC = vec2(-0.12, -0.05); float pilRad = 0.24; float hW = evalHeight(wp, t, amp, damp, 1.0); vec3 nW = evalNormal(wp, t, amp, damp, 1.0); // Refract view ray into shallow water depth H = 0.52 down to tiled seabed vec3 refr = refract(rd, nW, 0.75); float depth = 0.52 + hW; vec2 floorP = wp + refr.xz * (depth / max(-refr.y, 0.2)); // Sunlit ceramic pool tiles on basin floor vec2 tileGrid = abs(fract(floorP * 4.5 - 0.5) - 0.5); float grout = smoothstep(0.06, 0.015, min(tileGrid.x, tileGrid.y)); vec2 tid = floor(floorP * 4.5); float tileVar = 0.92 + 0.08 * sin(tid.x * 7.1 + tid.y * 11.3); vec3 tileCol = mix(vec3(0.14, 0.62, 0.72), vec3(0.07, 0.36, 0.48), grout) * tileVar; // Refractive caustics from surface Laplacian curvature (focusing of parallel sun rays!) float eC = 0.024; float hC = evalHeight(floorP, t, amp, damp, 1.0); float lap = ( evalHeight(floorP + vec2(eC, 0.0), t, amp, damp, 1.0) + evalHeight(floorP - vec2(eC, 0.0), t, amp, damp, 1.0) + evalHeight(floorP + vec2(0.0, eC), t, amp, damp, 1.0) + evalHeight(floorP - vec2(0.0, eC), t, amp, damp, 1.0) - 4.0 * hC ) / (eC * eC); float caustic = pow(clamp(-lap * 0.065 + 0.25, 0.0, 2.2), 2.2) * caustGain; // Subtle chromatic dispersion on caustic edges float causticB = pow(clamp(-lap * 0.072 + 0.20, 0.0, 2.2), 2.5) * caustGain; vec3 floorLit = tileCol * 0.82 + vec3(0.95, 1.02, 0.88) * caustic * 0.62 + vec3(0.15, 0.65, 1.0) * causticB * 0.22; // Beer-Lambert shallow water absorption vec3 absorb = exp(-vec3(0.45, 0.14, 0.09) * depth * 1.5); vec3 underWater = floorLit * absorb; // Fresnel sky reflection & crisp sun sparkle on rippling surface float ndv = max(dot(nW, -rd), 0.001); float fres = 0.025 + 0.975 * pow(1.0 - ndv, 5.0); vec3 refl = reflect(rd, nW); vec3 skyRefl = mix(vec3(0.74, 0.86, 0.96), vec3(0.18, 0.45, 0.82), clamp(refl.y, 0.0, 1.0)); vec3 hVec = normalize(sunDir - rd); float sunSpec = pow(max(dot(nW, hVec), 0.0), 160.0) * 4.2; vec3 col = mix(underWater, skyRefl, clamp(fres * 1.15, 0.0, 0.92)) + vec3(1.0, 0.95, 0.84) * sunSpec; // Subtle submerged pillar occlusion + emergent limestone column cylinder float dPilFloor = length(floorP - pilC); col *= mix(0.45, 1.0, smoothstep(pilRad * 0.8, pilRad * 1.85, dPilFloor)); // Ray-cylinder hit for stone pillar sticking out above water (y in [-0.5, 0.32]) vec2 oc = ro.xz - pilC; float a = dot(rd.xz, rd.xz); float b = dot(oc, rd.xz); float cEq = dot(oc, oc) - pilRad * pilRad; float disc = b * b - a * cEq; if (disc > 0.0) { float tp = (-b - sqrt(disc)) / a; vec3 pp = ro + rd * tp; if (tp > 0.0 && tp < tWater + 0.2 && pp.y > hW - 0.02 && pp.y < 0.28) { vec3 pn = normalize(vec3(pp.x - pilC.x, 0.0, pp.z - pilC.y)); float ndl = max(dot(pn, sunDir), 0.0); vec3 stone = vec3(0.76, 0.72, 0.65) * (0.28 + 0.95 * ndl); // Wet darkening waterline + foam collar float wet = smoothstep(hW + 0.08, hW, pp.y); stone *= mix(1.0, 0.58, wet); col = mix(stone, vec3(0.92, 0.97, 1.0), smoothstep(0.025, 0.0, abs(pp.y - hW)) * 0.7); } } // Pillar cap at y = 0.28 float tCap = (0.28 - ro.y) / min(rd.y, -0.001); vec3 pCap = ro + rd * tCap; if (tCap > 0.0 && length(pCap.xz - pilC) < pilRad) { float rRing = smoothstep(pilRad - 0.03, pilRad, length(pCap.xz - pilC)); col = mix(vec3(0.84, 0.80, 0.73), vec3(0.62, 0.58, 0.52), rRing); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Real-time Water Caustics](https://texelatlas.vercel.app/t/water-caustics-realtime.md): Provides the surface normals that the caustic pass refracts. - [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md): Interactive ripples from the SWE grid are added as local displacement over the FFT ocean. ## Sources 1. [primary] Michael Kass, Gavin Miller (1990) Rapid, stable fluid dynamics for computer graphics. Proceedings of the 17th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/97879.97884 (verified via crossref on 2026-11-29) 2. [implementation] evanw (2015) evanw/webgl-water. https://github.com/evanw/webgl-water (verified via github on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Shallow Water Equations (Height-field Water)." https://texelatlas.vercel.app/t/shallow-water-equations/ (accessed 2026-12-01). --- id: "shap-e" title: "Shap-E" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [text-prompt, ldr-image] outputs: [mesh, radiance-field] style: "stylized" dynamic: "static" cost: "heavy" authority: "Jun & Nichol, 2023" url: "https://texelatlas.vercel.app/t/shap-e/" sources_verified_at: "2026-11-29" --- # Shap-E (Jun & Nichol, 2023) > Trains an encoder that maps 3D assets to the weights of an implicit function, then trains a conditional diffusion model directly over those weights, so one sample can be rendered as NeRF or extracted as a textured mesh. ## Reach for it when - text to 3d that outputs meshes and radiance fields - generate 3d assets in seconds from a prompt - want an implicit 3d representation I can render and mesh - conditional 3d generation from images ## How it works Stage one is an encoder that ingests point clouds and rendered views of a training asset and outputs the parameters of a small MLP that represents both a radiance field and a signed-distance-plus-colour field. Stage two is a diffusion transformer that learns to generate those parameter vectors conditioned on a text embedding or an image embedding. At sampling time you denoise a parameter vector, instantiate the MLP and either volume-render it or run marching cubes on its SDF branch. Treating the network weights as the data lets one model emit multiple output representations, which Point-E, with its single point-cloud output, could not. ## When to use it Choose it for quick prototyping where a rough mesh in seconds is enough and the MIT-licensed code is convenient. Prefer [Point-E](https://texelatlas.vercel.app/t/point-e.md) only if you specifically need a point cloud, and [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md), [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) or [TripoSR](https://texelatlas.vercel.app/t/triposr.md) when you need sharper geometry. Prefer [Score Distillation Sampling (DreamFusion)](https://texelatlas.vercel.app/t/score-distillation-sampling.md) when you need higher 2D-prior fidelity and can pay the optimisation time. ## Cost heavy — Seconds per sample on a single GPU; qualitative. ## Failure modes - Low-resolution, blobby geometry with missing thin structures - Textures are smeared vertex-ish colour rather than crisp maps - Prompt adherence is weak for multi-part or uncommon objects - Marching-cubes meshes are dense, noisy and lack UVs ## Dataflow - Inputs: text-prompt, ldr-image - Outputs: mesh, radiance-field - Platforms: cuda, python ## Sources 1. [primary] Heewoo Jun, Alex Nichol (2023) Shap-E: Generating Conditional 3D Implicit Functions. arXiv preprint (cs.CV). https://arxiv.org/abs/2305.02463 (verified via arxiv on 2026-11-29) 2. [implementation] openai (2023) openai/shap-e. https://github.com/openai/shap-e License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Shap-E." https://texelatlas.vercel.app/t/shap-e/ (accessed 2026-12-01). --- id: "shape-matching-deformation" title: "Shape matching (meshless deformation)" aliases: [Meshless deformations] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity] year_introduced: 2005 inputs: [particles] outputs: [particles, mesh] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Müller et al., 2005" url: "https://texelatlas.vercel.app/t/shape-matching-deformation/" sources_verified_at: "2026-11-29" --- # Shape matching (meshless deformation) (Müller et al., 2005) > Soft-body method that pulls each particle toward the best-fit rigid transform of its rest shape, giving stable, controllable deformable objects without a mesh. ## Reach for it when - want cheap jelly or plush squishy objects - soft body without a volumetric mesh - need stable secondary motion in games - deformable objects explode with spring-based methods ## How it works Given particles with rest positions and current positions, compute the optimal rotation (and translation) that maps the rest shape onto the current one: the centre of mass for translation and a polar decomposition of the covariance matrix `A_pq` for rotation. Each particle's goal position is its rest position under this transform, and particles are moved toward their goals by a stiffness factor. Adding a linear or quadratic transformation to the fit lets the object shear, stretch or bend. Multiple overlapping clusters give local deformation instead of a single global one. Time integration is explicit and unconditionally stable because the goal is geometric. ## When to use it Choose it for cheap jelly, plush and secondary-motion deformation in games. Prefer [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) when you need volume constraints and calibrated stiffness, [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) for cloth/ropes, and [Vertex Block Descent](https://texelatlas.vercel.app/t/vertex-block-descent.md) when you need accurate elasticity. ## Cost cheap — Cheap: a covariance and polar decomposition per cluster. Measured GPU Weight: 49.32× baseline (heavy) — 1.5288 ms median / 1.6285 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 43.44× baseline (heavy) — 0.6907 ms median (2.21× faster on L4). Ampere A100 scaling: 33.35× baseline (heavy) — 0.9605 ms median (1.59× faster on A100). ## Failure modes - Does not model true elasticity; large deformations look like a springy blob - Polar decomposition can flip on inverted configurations - Global fit makes the object too rigid, clusters give seams - Stiffness is a blend factor, not a material parameter ## Dataflow - Inputs: particles - Outputs: particles, mesh - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity ## Presets ### Shape Matching Deformation — meshless soft-body polar-decomposition goal lattice & elastic pull (glsl-fragment; rendered 2026-11-30) ```json { "P_STIFFNESS": 0.62, "P_SQUASH_AMP": 1, "P_GOAL_VIS": 0.85, "P_BOUNCE_SPD": 1 } ``` ```glsl const float P_STIFFNESS = 0.62; // P Stiffness Alpha [0.1, 1.0, 0.02] const float P_SQUASH_AMP = 1.0; // P Impact Squash [0.2, 1.8, 0.05] const float P_GOAL_VIS = 0.85; // P Goal Pose Overlay [0.0, 1.5, 0.05] const float P_BOUNCE_SPD = 1.0; // P Bounce Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float sdSeg(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a; vec2 ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } // Compute bouncing rigid goal center, polar-decomposition rotation, and deformed lattice point void evalSoftBody(vec2 rest, float t, float stiff, float amp, out vec2 goalPos, out vec2 defPos) { // Periodic bounce cycle on floor y = -0.34 float cyc = fract(t * 0.42); float air = 4.0 * cyc * (1.0 - cyc); float impact = exp(-pow((cyc - 0.03) * 8.0, 2.0)) + exp(-pow((cyc - 0.97) * 8.0, 2.0)); float centerY = -0.14 + air * 0.34; float centerX = 0.14 * sin(t * 0.85); float rotAng = 0.45 * sin(t * 1.1) + 0.18 * (1.0 - air); // Best-fit rigid goal configuration g_i = R * q_i + c_cm vec2 c = vec2(centerX, centerY); goalPos = c + rot2(rotAng) * rest; // Non-rigid squash-and-stretch + shear modes damped by shape-matching stiffness alpha float compliance = (1.0 - stiff * 0.78) * amp; float sy = 1.0 - 0.36 * impact * compliance + 0.14 * sin(t * 7.5) * compliance * 0.45; float sx = 1.0 / max(sy, 0.45); // area-preserving deformation float shear = 0.24 * cos(t * 2.6) * compliance * (rest.y + 0.16); vec2 localDef = vec2(rest.x * sx + shear, rest.y * sy); // Quadratic bend mode during impact localDef.y += 0.35 * impact * compliance * (rest.x * rest.x - 0.018); vec2 rawDef = c + rot2(rotAng) * localDef; // Clamp against floor plane y = -0.34 rawDef.y = max(rawDef.y, -0.335); // Shape matching pull: x_i <- x_i + alpha * (g_i - x_i) defPos = mix(rawDef, goalPos, stiff * 0.48); defPos.y = max(defPos.y, -0.335); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float stiff = clamp(P_STIFFNESS, 0.08, 1.0); float amp = clamp(P_SQUASH_AMP, 0.15, 2.0); float goalVis = clamp(P_GOAL_VIS, 0.0, 1.5); float t = iTime * max(P_BOUNCE_SPD, 0.0); // Lab backdrop + floor vec3 col = mix(vec3(0.025, 0.036, 0.058), vec3(0.056, 0.076, 0.118), smoothstep(-0.5, 0.5, uv.y)); vec2 grid = abs(fract(uv * 10.0 - 0.5) - 0.5); col += vec3(0.015, 0.024, 0.040) * smoothstep(0.035, 0.008, min(grid.x, grid.y)); // Rigid floor surface at y = -0.34 if (uv.y < -0.34) { float floorGrid = smoothstep(0.04, 0.01, abs(fract(uv.x * 8.0) - 0.5)); col = mix(vec3(0.07, 0.09, 0.13), vec3(0.14, 0.18, 0.25), floorGrid * 0.6); } col = mix(col, vec3(0.55, 0.72, 0.90), smoothstep(px * 3.0, px * 0.6, abs(uv.y + 0.34)) * 0.85); // Evaluate 5x5 meshless particle grid (25 particles) float bodyField = 0.0; float dispSum = 0.0; float minDef = 1e5; float minGoal = 1e5; float pullLine = 0.0; float goalHull = 0.0; for (int iy = 0; iy < 5; iy++) { for (int ix = 0; ix < 5; ix++) { vec2 rest = (vec2(float(ix), float(iy)) - 2.0) * 0.078; vec2 gPos, dPos; evalSoftBody(rest, t, stiff, amp, gPos, dPos); float dd = length(uv - dPos); float dg = length(uv - gPos); minDef = min(minDef, dd); minGoal = min(minGoal, dg); float disp = length(gPos - dPos); float w = exp(-dd * dd / 0.0036); bodyField += w; dispSum += w * disp; // Elastic restoration vector alpha * (g_i - x_i) float dPull = sdSeg(uv, dPos, gPos); pullLine = max(pullLine, smoothstep(px * 2.6, px * 0.6, dPull) * smoothstep(0.004, 0.02, disp)); // Draw goal rigid wireframe boundary if (ix < 4) { vec2 gNext, dNext; evalSoftBody(rest + vec2(0.078, 0.0), t, stiff, amp, gNext, dNext); if (iy == 0 || iy == 4) { goalHull = max(goalHull, smoothstep(px * 2.5, px * 0.6, sdSeg(uv, gPos, gNext))); } } if (iy < 4) { vec2 gNext, dNext; evalSoftBody(rest + vec2(0.0, 0.078), t, stiff, amp, gNext, dNext); if (ix == 0 || ix == 4) { goalHull = max(goalHull, smoothstep(px * 2.5, px * 0.6, sdSeg(uv, gPos, gNext))); } } } } // Smooth gelatin soft-body metaball fill colored by local displacement from rigid goal float mask = smoothstep(0.32, 0.58, bodyField); if (mask > 0.005) { float avgDisp = clamp((dispSum / max(bodyField, 1e-4)) * 12.0, 0.0, 1.0); vec3 softCol = mix(vec3(0.10, 0.66, 0.82), vec3(0.98, 0.52, 0.18), avgDisp); float rim = smoothstep(0.95, 0.36, bodyField); vec3 shaded = softCol * (0.62 + 0.38 * smoothstep(-0.35, 0.25, uv.y)) + vec3(0.85, 0.96, 1.0) * rim * 0.42; col = mix(col, shaded, mask * 0.86); } // Overlay best-fit rigid goal frame (R * q_i + c), goal positions, and pull arrows col = mix(col, vec3(0.98, 0.84, 0.32), goalHull * 0.72 * min(goalVis, 1.2)); col = mix(col, vec3(1.0, 0.92, 0.45), smoothstep(0.011, 0.005, minGoal) * 0.75 * min(goalVis, 1.2)); col += vec3(0.96, 0.42, 0.78) * pullLine * 0.85 * min(goalVis, 1.2); col = mix(col, vec3(0.92, 0.98, 1.0), smoothstep(0.016, 0.007, minDef) * 0.88); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Concavity-aware deformable clusters via CoACD and shape matching](https://texelatlas.vercel.app/ideas/coacd-cluster-shape-matching/) ## Sources 1. [primary] Matthias Müller, Bruno Heidelberger, Matthias Teschner, Markus Gross (2005) Meshless deformations based on shape matching. ACM Transactions on Graphics. https://doi.org/10.1145/1073204.1073216 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Shape matching (meshless deformation)." https://texelatlas.vercel.app/t/shape-matching-deformation/ (accessed 2026-12-01). --- id: "shapelib" title: "ShapeLib" domain: "genai" stage: "generation" realtime: "offline" platforms: [python] year_introduced: 2025 inputs: [text-prompt, mesh, point-cloud, voxels] outputs: [graph, mesh] style: "both" dynamic: "static" cost: "offline" authority: "Jones et al., 2025" url: "https://texelatlas.vercel.app/t/shapelib/" sources_verified_at: "2026-11-29" --- # ShapeLib (Jones et al., 2025) > Uses an LLM to design a library of reusable programmatic shape functions from text descriptions and a few exemplars, then trains recognisers to map shapes into programs built from that library. ## Reach for it when - need a reusable library of shape-building functions from a text description - want editable programs instead of raw meshes for a category - llm should invent helper functions for a family of shapes - recognise shapes and turn them into code - compact programmatic shape representation from few examples ## How it works The user supplies text describing desired functions and a small seed set of example shapes. An LLM workflow proposes functions and implementations, then validates that each function actually helps to express the seed shapes, keeping those that make programs shorter or more faithful (an abstraction-discovery step in the style of library learning). To handle shapes beyond the seed set, recognition networks are trained to map primitives, voxels or point clouds to programs that call the discovered functions. The end result is a domain-specific language with LLM-written but verified functions, plus an inference path from raw shapes to short programs. ## When to use it Choose it when you need a compact, editable program representation for a shape category and can supply a handful of exemplars. Prefer [LLM-written procedural kits with verification gates](https://texelatlas.vercel.app/t/procgen-kit-llm-harness.md) when the output is a parametric kit with strict manifold and collision checks, [LL3M (Large Language 3D Modelers)](https://texelatlas.vercel.app/t/ll3m.md) for one-off Blender asset authoring, and learned latent generators like [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) when program structure is not needed. ## Cost offline — LLM library design plus recogniser training; research workflow, not an interactive tool. ## Failure modes - Library quality depends on the seed exemplars and prompt; poor seeds yield narrow functions - Recognition networks fail on shapes outside the learned domain - Program edits may break geometry validity without a separate checker - No public repository found for it ## Dataflow - Inputs: text-prompt, mesh, point-cloud, voxels - Outputs: graph, mesh - Platforms: python ## Sources 1. [primary] R. Kenny Jones, Paul Guerrero, Niloy J. Mitra, Daniel Ritchie (2025) ShapeLib: Designing a library of programmatic 3D shape abstractions with Large Language Models. arXiv preprint (cs.CV). https://arxiv.org/abs/2502.08884 (verified via arxiv on 2026-11-29) ## Cite this entry Texel. "ShapeLib." https://texelatlas.vercel.app/t/shapelib/ (accessed 2026-12-01). --- id: "sharc" title: "SHaRC: Spatially Hashed Radiance Cache" aliases: [SHaRC, hash-grid radiance cache] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu] year_introduced: 2023 inputs: [gbuffer, mesh] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "NVIDIA" url: "https://texelatlas.vercel.app/t/sharc/" sources_verified_at: "2026-11-29" --- # SHaRC: Spatially Hashed Radiance Cache (NVIDIA) > A world-space radiance cache stored in a GPU hash table keyed by quantized position and normal. Path-tracing paths end early by reading cached radiance, and a few extra paths update the cache. ## Reach for it when - real-time gi on ray tracing with limited rays - indirect lighting noise too high for the budget - cache radiance in world space across frames - path traced gi slows frame rate on mid range gpus ## How it works The cache is a hash map from a voxel key (position quantized by a camera-dependent cell size, plus a coarse normal bucket) to an accumulated radiance and a sample count. There is no neural network. A frame has three steps. **Update**: a sparse subset of screen pixels traces full paths of several bounces. At each vertex, the throughput-weighted contribution of the rest of the path is written to the hash entry for that vertex's cell with atomic adds, so each path trains many cells. **Resolve**: a pass converts raw accumulation to stable averages, blending with the previous frame using an exponential moving average and decaying old entries. **Query**: the normal render traces paths for each pixel but stops after one or two bounces, reading the cell's cached radiance in place of the remaining transport. Cells are quantized with a level-of-detail that grows with distance from the camera, so the cache is compact and fine resolution is spent near the viewer. A compaction and stale-entry eviction scheme keep the table bounded. ## When to use it Choose it as a simple, drop-in multi-bounce radiance cache for a path tracer, particularly when you want to avoid a neural network and need broad GPU support. Prefer [neural-radiance-caching](neural-radiance-caching) when you want a smoother, learned cache and have the hardware for it. Prefer [surfel-gi](surfel-gi) when you want an explicit surface-based cache. Prefer [restir-gi](restir-gi) for high-frequency per-pixel indirect. Prefer [ddgi](ddgi) for regular-grid probes of diffuse irradiance. ## Cost medium — Cost is one extra sparse path pass plus hash lookups at path ends; the number of update paths and cache capacity are the main tuning knobs. Measured GPU Weight: 25.71× baseline (heavy) — 0.8459 ms median / 0.8751 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 23.81× baseline (heavy) — 0.3785 ms median (2.23× faster on L4). Ampere A100 scaling: 15.57× baseline (moderate) — 0.4483 ms median (1.89× faster on A100). ## Failure modes - Blocky or noisy indirect where the voxel size is coarse compared with lighting variation, with visible cell boundaries - Light leaking across thin walls because cells key only on position and a coarse normal - Hash collisions and eviction cause flicker if the table is undersized for the scene - Cached radiance is diffuse-like: glossy and specular reflection hits get inaccurate values ## Dataflow - Inputs: gbuffer, mesh - Outputs: radiance - Platforms: desktop-gpu ## Presets ### SHaRC (Spatial Hash Radiance Cache) — quantized world-space hash voxels (left) vs smooth multi-bounce GI (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VOXEL_RES": 7, "P_BOUNCE_STR": 1.2, "P_SUN_SWEEP": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_VOXEL_RES = 7.0; // P Hash Grid Density [4.0, 14.0, 1.0] const float P_BOUNCE_STR = 1.20; // P Radiance Gain [0.2, 2.0, 0.05] const float P_SUN_SWEEP = 0.55; // P Sun Motion [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Hash Voxels / GI [0.0, 1.0, 0.02] vec2 mapCourtyard(vec3 p) { float dFloor = p.y + 0.72; float dBack = p.z + 1.45; vec2 res = vec2(dFloor, 1.0); if (dBack < res.x) res = vec2(dBack, 2.0); // terracotta sun-baked back wall // Two staggered modern architectural monoliths casting colored sky/sun bounce vec3 b1 = abs(p - vec3(-0.62, -0.08, -0.25)) - vec3(0.26, 0.64, 0.34); float d1 = length(max(b1, 0.0)) + min(max(b1.x, max(b1.y, b1.z)), 0.0); if (d1 < res.x) res = vec2(d1, 3.0); vec3 b2 = abs(p - vec3(0.56, -0.22, -0.45)) - vec3(0.30, 0.50, 0.28); float d2 = length(max(b2, 0.0)) + min(max(b2.x, max(b2.y, b2.z)), 0.0); if (d2 < res.x) res = vec2(d2, 4.0); float dSph = length(p - vec3(0.0, -0.40, 0.05)) - 0.32; if (dSph < res.x) res = vec2(dSph, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapCourtyard(p + e.xyy).x - mapCourtyard(p - e.xyy).x, mapCourtyard(p + e.yxy).x - mapCourtyard(p - e.yxy).x, mapCourtyard(p + e.yyx).x - mapCourtyard(p - e.yyx).x )); } // Compute indirect radiance stored at a world position p & normal n (evaluated at voxel center on left, smooth on right!) vec3 evalSharcRadiance(vec3 p, vec3 n, vec3 sunDir, float gain) { // Warm terracotta bounce from sun-lit back wall + cool zenith sky fill + emerald monolith bounce float backBounce = max(dot(n, vec3(0.0, 0.15, -1.0)), 0.0) / (0.65 + (p.z + 1.45) * (p.z + 1.45)); float leftBounce = max(dot(n, normalize(vec3(-0.62, -0.1, -0.25) - p)), 0.0) / (0.55 + dot(p - vec3(-0.62, -0.1, -0.25), p - vec3(-0.62, -0.1, -0.25))); float skyFill = 0.5 + 0.5 * n.y; vec3 rad = vec3(0.95, 0.42, 0.22) * backBounce * 0.95 + vec3(0.16, 0.72, 0.88) * leftBounce * 0.45 + vec3(0.24, 0.44, 0.78) * skyFill * 0.42 + vec3(0.98, 0.86, 0.62) * max(dot(n, sunDir), 0.0) * 0.22; return rad * gain; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isFinalGI = screenX >= split; float voxRes = clamp(floor(P_VOXEL_RES + 0.5), 3.0, 16.0); float gain = clamp(P_BOUNCE_STR, 0.15, 2.2); float sweep = iTime * max(P_SUN_SWEEP, 0.0); vec3 ro = vec3(0.0, 0.35, 2.22); vec3 rd = normalize(vec3(uv.x, uv.y - 0.12, -1.38)); vec3 sky = mix(vec3(0.76, 0.82, 0.90), vec3(0.16, 0.38, 0.72), smoothstep(-0.08, 0.52, rd.y)); vec3 col = sky; float t = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapCourtyard(ro + rd * t); if (h.x < 0.0025) { hit = vec2(t, h.y); break; } t += h.x; if (t > 8.0) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 sunDir = normalize(vec3(0.62 * cos(sweep * 0.45), 0.72, 0.48)); // Direct sun shadow ray float sh = 1.0; float ts = 0.03; for (int s = 0; s < 20; s++) { float ds = mapCourtyard(p + sunDir * ts).x; if (ds < 0.003) { sh = 0.0; break; } ts += max(ds, 0.03); if (ts > 3.5) break; } vec3 alb = vec3(0.70, 0.68, 0.64); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.86, 0.38, 0.22); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.18, 0.64, 0.78); else if (hit.y > 3.5 && hit.y < 4.5) alb = vec3(0.84, 0.80, 0.74); else if (hit.y > 4.5) alb = vec3(0.90, 0.88, 0.84); // Distance-adaptive SHaRC cascade LOD level (coarser voxels further from camera!) float camDist = length(p - ro); float lodScale = (camDist > 2.6) ? (voxRes * 0.5) : voxRes; vec3 cellPos = (floor(p * lodScale) + 0.5) / lodScale; // Quantized surface normal direction into octants as in SHaRC hash key vec3 qNorm = normalize(floor(n * 2.5 + 0.5) + vec3(1e-4)); vec3 direct = alb * vec3(1.0, 0.94, 0.84) * max(dot(n, sunDir), 0.0) * sh * 1.15; if (!isFinalGI) { // Left: Raw SHaRC spatial hash-grid cache cells visualized directly (discrete LOD voxel cells + cell borders!) vec3 cellRad = evalSharcRadiance(cellPos, qNorm, sunDir, gain); vec3 fracC = abs(fract(p * lodScale) - 0.5); float border = smoothstep(0.05, 0.012, min(min(0.5 - fracC.x, 0.5 - fracC.y), 0.5 - fracC.z)); // Color-tint cascade boundary subtly to reveal camera-distance LOD transition vec3 lodEdgeCol = (camDist > 2.6) ? vec3(0.98, 0.76, 0.20) : vec3(0.20, 0.92, 0.98); col = cellRad * 1.25 + lodEdgeCol * border * 0.38; } else { // Right: Final path-traced render reading SHaRC cache at secondary bounce vertices -> clean, vivid multi-bounce GI! vec3 smoothGI = evalSharcRadiance(p, n, sunDir, gain); col = direct + alb * smoothGI; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Unidirectional Path Tracing](https://texelatlas.vercel.app/t/path-tracing.md): Paths terminate at the hash-grid cache instead of tracing every bounce. ## Sources 1. [primary] NVIDIA SHaRC Guide (RTXGI SDK documentation). github.com. https://github.com/NVIDIA-RTX/RTXGI/blob/main/Docs/SharcGuide.md (verified via http on 2026-11-29) 2. [implementation] NVIDIA-RTX (2024) NVIDIA-RTX/SHARC. https://github.com/NVIDIA-RTX/SHARC License: NOASSERTION. (verified via github on 2026-11-29) 3. [implementation] NVIDIA-RTX (2024) NVIDIA-RTX/RTXGI. https://github.com/NVIDIA-RTX/RTXGI License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "SHaRC: Spatially Hashed Radiance Cache." https://texelatlas.vercel.app/t/sharc/ (accessed 2026-12-01). --- id: "shell-fur-rendering" title: "Shell and fin fur rendering" aliases: [shell texturing, shells and fins, volumetric fur shells] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2001 inputs: [mesh, texture] outputs: [radiance] style: "both" dynamic: "dynamic" cost: "medium" authority: "Lengyel et al., 2001" url: "https://texelatlas.vercel.app/t/shell-fur-rendering/" sources_verified_at: "2026-11-29" --- # Shell and fin fur rendering (Lengyel et al., 2001) > Renders short fur by drawing the mesh many times, each copy pushed out a little along the normal with a strand-density alpha texture, plus extruded fin quads along silhouettes. It is cheap, GPU friendly and easy to animate. ## Reach for it when - cheap fur on animal character for games - want short fuzzy fur without strand geometry - fur shows visible slices at silhouette - need wind or gravity bending fuzzy surface - stylised furry or grassy surface using layered shells ## How it works Shells: draw N offset copies of the skin mesh, shell k displaced by k/N times the fur length along the vertex normal. A texture or procedural hash holds a random strand pattern; each shell keeps only texels whose strand height exceeds k/N, so layers stack into tapered strands when viewed from above. Colour darkens toward the root for fake self-shadowing, and lighting uses a Kajiya-Kay-style tangent or a simple normal blend. Forces such as gravity, wind or animation velocity bend higher shells by an increasing offset. Shells look like stacked slices at the silhouette, so Lengyel's fins add quads extruded perpendicular to the surface along edges facing sideways, textured with a side view of the fur. Modern versions generate the shells with instancing and a hash-based strand mask in the fragment shader, avoiding a texture entirely. ## When to use it Choose it for short fur on characters, creatures and stylised props where overdraw is acceptable and strands do not need to be individual curves. Prefer [Strand-based real-time hair (TressFX style)](https://texelatlas.vercel.app/t/strand-based-real-time-hair.md) for long hair with simulation and silhouettes. Prefer [Kajiya-Kay hair shading](https://texelatlas.vercel.app/t/kajiya-kay-hair-shading.md) on hair cards for long styles. For stylised grass or carpet the same shell approach works with a different mask. For path-traced fur use [Disney / Chiang hair and fur BSDF](https://texelatlas.vercel.app/t/disney-hair-bsdf.md). ## Cost medium — Scales with shell count times covered pixels; 16-64 shells is typical and is overdraw-bound. Measured GPU Weight: 36.7× baseline (heavy) — 1.2074 ms median / 1.2413 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 29.43× baseline (heavy) — 0.468 ms median (2.58× faster on L4). Ampere A100 scaling: 23.67× baseline (heavy) — 0.6816 ms median (1.77× faster on A100). ## Failure modes - Visible layering and gaps at silhouettes when viewed from low angles, unless fins or more shells are added - Heavy overdraw and alpha-test cost when many characters are covered with fur - Shimmering strand pattern when shells alias at distance without LOD shell reduction - Strands penetrate or stretch where vertex normals change sharply, because offsets follow the normal - Shadow casting is poor since shells are alpha-tested slices ## Engine support - babylonjs: official — `import { FurMaterial } from "@babylonjs/materials/fur"` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/materials/src/fur/furMaterial.ts, checked 2026-12-01) ## Dataflow - Inputs: mesh, texture - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Concentric volumetric fur shells — procedural tapered strands, root AO and wind sway (glsl-fragment; rendered 2026-11-30) ```json { "SHELLS": 24, "FUR_LENGTH": 0.16, "STRAND_DENSITY": 46, "GRAVITY_SWAY": 0.32 } ``` ```glsl const int SHELLS = 24; // P const float FUR_LENGTH = 0.16; // P const float STRAND_DENSITY = 46.0; // P const float GRAVITY_SWAY = 0.32; // P vec2 hash22(vec2 p) { vec3 q = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); q += dot(q, q.yzx + 33.33); return fract((q.xx + q.yz) * q.zy); } // Cube-face octahedral projection avoids spherical UV pinching at poles vec2 sphereFaceUV(vec3 d) { vec3 a = abs(d); if (a.x >= a.y && a.x >= a.z) return d.yz / a.x + vec2(d.x > 0.0 ? 2.0 : -2.0, 0.0); if (a.y >= a.x && a.y >= a.z) return d.xz / a.y + vec2(0.0, d.y > 0.0 ? 4.0 : -4.0); return d.xy / a.z + vec2(d.z > 0.0 ? 6.0 : -6.0, 0.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.08, 2.55); vec3 rd = normalize(vec3(uv, -1.55)); float baseR = 0.68; float furL = clamp(FUR_LENGTH, 0.01, 0.36); float outerR = baseR + furL; vec3 bg = mix(vec3(0.045, 0.055, 0.075), vec3(0.14, 0.16, 0.21), clamp(uv.y + 0.55, 0.0, 1.0)); float b = dot(ro, rd); float cOut = dot(ro, ro) - outerR * outerR; float hOut = b * b - cOut; if (hOut < 0.0) { fragColor = vec4(pow(clamp(aces(bg), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); return; } float tEnter = max(-b - sqrt(hOut), 0.0); float tExit = -b + sqrt(hOut); float cIn = dot(ro, ro) - baseR * baseR; float hIn = b * b - cIn; if (hIn > 0.0) tExit = min(tExit, -b - sqrt(hIn)); float yaw = iTime * 0.28; if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { yaw = (iMouse.x / iResolution.x - 0.5) * 3.14159; } float cy = cos(yaw), sy = sin(yaw); mat2 rotY = mat2(cy, -sy, sy, cy); vec3 lightDir = normalize(vec3(0.62, 0.72, 0.55)); vec3 rimDir = normalize(vec3(-0.75, 0.35, -0.45)); int nShells = clamp(SHELLS, 4, 48); float dens = max(STRAND_DENSITY, 8.0); float sway = max(GRAVITY_SWAY, 0.0); // March front-to-back through concentric fur shells vec3 accum = vec3(0.0); float alpha = 0.0; for (int i = 0; i < 48; i++) { if (i >= nShells || alpha > 0.98) break; float f = (float(i) + 0.5) / float(nShells); float t = mix(tEnter, tExit, f); vec3 wp = ro + rd * t; float r = length(wp); float hNorm = clamp((r - baseR) / furL, 0.0, 1.0); vec3 n = wp / max(r, 1e-4); // Gravity droop + animated wind wave increasing quadratically from root to tip vec3 wind = vec3(sin(iTime * 1.8 + wp.y * 3.0) * 0.35, -0.65, cos(iTime * 1.4 + wp.x * 3.0) * 0.25); vec3 bentDir = normalize(n - wind * (hNorm * hNorm * sway * 0.55)); vec3 locDir = vec3(rotY * bentDir.xz, bentDir.y).xzy; vec2 fuv = sphereFaceUV(locDir) * dens; vec2 cell = floor(fuv); vec2 frac = fract(fuv) - 0.5; vec2 rnd = hash22(cell); vec2 jitter = (rnd - 0.5) * 0.42; float strandH = 0.32 + 0.68 * hash22(cell + vec2(17.3, 41.9)).x; float taper = mix(0.46, 0.05, hNorm / max(strandH, 0.01)); float dist = length(frac - jitter); float hitStrand = (hNorm < strandH) ? smoothstep(taper + 0.06, taper - 0.06, dist) : 0.0; if (hitStrand > 0.01) { // Subtle warm feline/fox coat striping + root-to-tip self-occlusion float stripe = 0.5 + 0.5 * sin(locDir.y * 14.0 + sin(locDir.x * 7.0) * 1.2); vec3 rootCol = vec3(0.24, 0.13, 0.07); vec3 tipCol = mix(vec3(0.86, 0.54, 0.26), vec3(0.95, 0.84, 0.68), stripe * 0.55); vec3 furCol = mix(rootCol, tipCol, pow(hNorm, 0.65)); float rootAO = mix(0.16, 1.0, pow(hNorm, 0.78)); float wrapDiff = clamp((dot(n, lightDir) + 0.35) / 1.35, 0.0, 1.0); float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * (0.35 + 0.65 * max(dot(n, rimDir) + 0.4, 0.0)); vec3 lit = furCol * rootAO * (vec3(0.14, 0.16, 0.22) + vec3(1.55, 1.42, 1.24) * wrapDiff) + vec3(0.75, 0.82, 0.95) * rim * rootAO * 0.65; float aLayer = hitStrand * (1.0 - alpha); accum += lit * aLayer; alpha += aLayer; } } // Inner skin core if ray reaches baseR if (hIn > 0.0 && alpha < 0.99) { vec3 wp = ro + rd * tExit; vec3 n = normalize(wp); float nl = max(dot(n, lightDir), 0.0); vec3 skin = vec3(0.18, 0.10, 0.06) * (0.15 + 0.7 * nl); accum += skin * (1.0 - alpha); alpha = 1.0; } vec3 col = mix(bg, accum, alpha); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index ## Combines with - [Kajiya-Kay hair shading](https://texelatlas.vercel.app/t/kajiya-kay-hair-shading.md): Each shell can use the fibre tangent lobes to get a directional highlight along the strand. ## Sources 1. [primary] Jerome Lengyel, Emil Praun, Adam Finkelstein, Hugues Hoppe (2001) Real-time fur over arbitrary surfaces. Proceedings of the 2001 symposium on Interactive 3D graphics. https://doi.org/10.1145/364338.364407 (verified via crossref on 2026-11-29) 2. [implementation] Gökay Aydoğan (2026) gokayfem/glsl-studies. https://github.com/gokayfem/glsl-studies License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Shell and fin fur rendering." https://texelatlas.vercel.app/t/shell-fur-rendering/ (accessed 2026-12-01). --- id: "silhouette-strip-octahedral-impostors" title: "Silhouette-Strip Depth-Parallax Octahedral Impostors" aliases: [GTA 6 octahedral impostors, silhouette-strip impostors, depth-parallax octahedral tree impostors, bit-packed silhouette strip impostors] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal, godot] year_introduced: 2026 inputs: [mesh, material-params] outputs: [texture, gbuffer] style: "both" dynamic: "both" cost: "cheap" authority: "Krutenyuk, 2026" url: "https://texelatlas.vercel.app/t/silhouette-strip-octahedral-impostors/" sources_verified_at: "2026-11-30" --- # Silhouette-Strip Depth-Parallax Octahedral Impostors (Krutenyuk, 2026) > Refines 64-view octahedral impostors with vertex-merged 8-strip bit-packed silhouettes to cut transparent overdraw and per-fragment camera-ray depth parallax to eliminate ghosting across the three blended views. ## Reach for it when - octahedral tree impostor ghosting between three blended views - reduce alpha overdraw on distant billboard trees with silhouette strips - gta 6 style octahedral impostors with depth parallax in threejs - fix impostor trunk seams and coarse mip halos at depth edges - pack 8 silhouette strip bounds into two uints in vertex shader ## How it works Standard single-quad [octahedral-impostors](octahedral-impostors) waste substantial fragment shader work on empty alpha pixels around irregular silhouettes such as trees and suffer double- or triple-image ghosting when barycentric weights blend three neighboring atlas views. **Tight silhouette strips:** During the 64-view octahedral bake, each view's alpha silhouette is quantized into 8 horizontal strips whose 4-bit left and right bounds pack tightly into two `uint32` words per view. At runtime, the vertex shader unpacks the strip bounds for the three active octahedral views and merges their union directly on an 8-strip mesh, collapsing empty quad corners and eliminating trunk seams between adjacent strips. **Per-fragment depth parallax:** Instead of interpolating view vectors per vertex, every fragment casts the exact camera ray against each view's frame plane, reads baked depth dilated past the silhouette edge, and steps along the ray onto the reconstructed surface point. Because all three views reproject onto the same 3D surface position before blending, cross-view ghosting vanishes. Texture mip levels are chosen from the unshifted UVs so depth discontinuities never trigger coarse mip halos along foliage edges. ## When to use it Choose it for dense open-world forests and irregular foliage silhouettes in WebGL2, WebGPU, or desktop engines where plain billboard quads cause heavy alpha overdraw and classic 3-view octahedral blending produces visible ghosting. Prefer [octahedral-impostors](octahedral-impostors) when rendering convex rocks or props whose quad fill ratio is already high and minimal vertex complexity matters most. Prefer [meshlets](meshlets) or [nanite-virtualized-geometry](nanite-virtualized-geometry) for mid-range trees that still need true silhouette deformation and close-up inspection. Pair with [gpu-driven-rendering](gpu-driven-rendering) to switch thousands of distant trees into instanced 8-strip draws. ## Cost cheap — 8 horizontal strips (16 triangles) per instance with two uint32 bitmask reads in the vertex shader and three depth-parallaxed atlas lookups per covered fragment; substantially lower alpha overdraw than full-quad impostors. Measured GPU Weight: 27.77× baseline (heavy) — 0.9135 ms median / 0.9563 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 25.45× baseline (heavy) — 0.4047 ms median (2.26× faster on L4). Ampere A100 scaling: 18.62× baseline (moderate) — 0.5363 ms median (1.7× faster on A100). ## Failure modes - Single-layer baked depth cannot represent deep multi-layered canopy self-occlusion at extreme grazing angles - Undilated depth buffers leak background depth along silhouette edges unless depth dilation is applied during atlas baking - Sampling mipmaps from depth-shifted UVs causes derivative spikes and blocky mip seams unless LOD is evaluated from unshifted UVs - Tight 4-bit strip bounds must be merged conservatively across all three active views to prevent clipping branches mid-transition ## Dataflow - Inputs: mesh, material-params - Outputs: texture, gbuffer - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal, godot ## Presets ### Silhouette-Strip Octahedral Impostors — full alpha-quad overdraw & ghosting (left) vs 8-strip silhouette + depth parallax (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PARALLAX": 0.8, "P_OVERDRAW_VIS": 0.65, "P_ORBIT": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_PARALLAX = 0.80; // P Ray Depth Parallax [0.0, 1.0, 0.05] const float P_OVERDRAW_VIS = 0.65; // P Overdraw Mask Vis [0.0, 1.0, 0.05] const float P_ORBIT = 0.55; // P Orbit Speed [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Naive Quad / Strips [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Irregular botanical-tree crown + trunk SDF (high transparent alpha waste on a bounding quad!) vec2 mapTree(vec3 p) { // Trunk vec2 tr = vec2(length(p.xz) - mix(0.085, 0.045, clamp((p.y + 0.48) * 1.4, 0.0, 1.0)), abs(p.y + 0.22) - 0.28); float dTrunk = length(max(tr, 0.0)) + min(max(tr.x, tr.y), 0.0); vec2 res = vec2(dTrunk, 1.0); // Asymmetric multi-lobe canopy spheres float d1 = length(p - vec3(0.0, 0.18, 0.0)) - 0.24; float d2 = length(p - vec3(-0.22, 0.06, 0.08)) - 0.17; float d3 = length(p - vec3(0.20, 0.10, -0.06)) - 0.18; float d4 = length(p - vec3(0.04, 0.34, 0.05)) - 0.15; float d5 = length(p - vec3(-0.10, 0.24, -0.14)) - 0.15; float dCanopy = min(min(d1, d2), min(min(d3, d4), d5)); // Subtle foliage bump dCanopy += 0.015 * sin(p.x * 26.0) * sin(p.y * 26.0) * sin(p.z * 26.0); if (dCanopy < res.x) res = vec2(dCanopy, 2.0); return res; } vec3 shadeTreeRay(vec3 ro, vec3 rd, out float hitA, out float hitD) { hitA = 0.0; hitD = 10.0; float t = 0.1; vec2 h = vec2(10.0, 0.0); for (int i = 0; i < 48; i++) { vec2 m = mapTree(ro + rd * t); if (m.x < 0.003) { h = vec2(t, m.y); break; } t += m.x * 0.85; if (t > 4.5) break; } if (h.y < 0.5) return vec3(0.0); hitA = 1.0; hitD = h.x; vec3 p = ro + rd * h.x; vec2 e = vec2(0.004, 0.0); vec3 n = normalize(vec3( mapTree(p + e.xyy).x - mapTree(p - e.xyy).x, mapTree(p + e.yxy).x - mapTree(p - e.yxy).x, mapTree(p + e.yyx).x - mapTree(p - e.yyx).x )); vec3 lDir = normalize(vec3(0.62, 0.78, 0.45)); float ndl = max(dot(n, lDir), 0.0); vec3 alb = (h.y < 1.5) ? vec3(0.38, 0.24, 0.15) : mix(vec3(0.16, 0.48, 0.22), vec3(0.46, 0.78, 0.28), 0.5 + 0.5 * n.y); return alb * (0.28 + 0.95 * ndl) + vec3(0.18, 0.30, 0.45) * (0.5 + 0.5 * n.y) * 0.35; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float parallax = clamp(P_PARALLAX, 0.0, 1.0); float overVis = clamp(P_OVERDRAW_VIS, 0.0, 1.0); float ang = iTime * max(P_ORBIT, 0.0) * 0.65; // Orbiting camera around the impostor asset vec3 ro = vec3(1.85 * sin(ang), 0.18, 1.85 * cos(ang)); vec3 fwd = normalize(-ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.48 + right * uv.x + up * uv.y); vec3 bg = mix(vec3(0.06, 0.09, 0.15), vec3(0.18, 0.27, 0.42), smoothstep(-0.4, 0.5, uv.y)); vec3 col = bg; // Bounding billboard quad region in screen space [-0.34, 0.34] x [-0.38, 0.38] bool inQuad = (abs(uv.x) < 0.34 && abs(uv.y) < 0.38); if (screenX < split) { // Left: Naive single-quad octahedral impostor -- suffers wasted transparent overdraw across entire quad // AND double/triple-view barycentric ghosting between adjacent octahedral atlas angles! float a1, d1, a2, d2; float snapAng = floor(ang * 4.0) / 4.0; float nextAng = snapAng + 0.25; float blendW = fract(ang * 4.0); vec3 ro1 = vec3(1.85 * sin(snapAng), 0.18, 1.85 * cos(snapAng)); vec3 f1 = normalize(-ro1), r1 = normalize(cross(f1, vec3(0.0, 1.0, 0.0))), u1 = cross(r1, f1); vec3 c1 = shadeTreeRay(ro1, normalize(f1 * 1.48 + r1 * uv.x + u1 * uv.y), a1, d1); vec3 ro2 = vec3(1.85 * sin(nextAng), 0.18, 1.85 * cos(nextAng)); vec3 f2 = normalize(-ro2), r2 = normalize(cross(f2, vec3(0.0, 1.0, 0.0))), u2 = cross(r2, f2); vec3 c2 = shadeTreeRay(ro2, normalize(f2 * 1.48 + r2 * uv.x + u2 * uv.y), a2, d2); vec3 ghostCol = mix(c1, c2, blendW); float ghostA = mix(a1, a2, blendW); // Highlight wasted transparent quad pixels in crimson overdraw tint if (inQuad) { vec2 qEdge = abs(uv) - vec2(0.34, 0.38); float border = smoothstep(0.012, 0.002, abs(max(qEdge.x, qEdge.y))); col = mix(col, vec3(0.95, 0.22, 0.30), (1.0 - ghostA) * overVis * 0.32); col = mix(col, vec3(1.0, 0.42, 0.48), border * overVis * 0.85); } col = mix(col, ghostCol, ghostA); } else { // Right: Tight 8-strip bit-packed silhouette mesh + per-fragment camera-ray depth parallax (zero ghosting!) float aExact, dExact; vec3 cExact = shadeTreeRay(ro, rd, aExact, dExact); // Visualize the tight 8 horizontal bit-packed silhouette strips hugging the tree outline (cutting ~65% overdraw!) if (inQuad) { float stripIdx = floor((uv.y + 0.38) / 0.76 * 8.0); float stripY = (stripIdx + 0.5) / 8.0 * 0.76 - 0.38; // Tight per-strip half-width matching trunk vs canopy silhouette float stripHalfW = (stripIdx < 2.5) ? 0.095 : (stripIdx < 6.5 ? 0.295 : 0.165); bool inStrip = abs(uv.x) < stripHalfW; float stripEdgeX = smoothstep(0.010, 0.002, abs(abs(uv.x) - stripHalfW)); float stripEdgeY = smoothstep(0.008, 0.002, abs(fract((uv.y + 0.38) / 0.76 * 8.0) - 0.5) * 0.095 - 0.044); if (inStrip) { col = mix(col, vec3(0.16, 0.88, 0.96), (1.0 - aExact) * overVis * 0.14); col = mix(col, vec3(0.20, 0.96, 0.82), clamp(stripEdgeX + stripEdgeY, 0.0, 1.0) * overVis * 0.55); } } // Depth-parallax blends smoothly into exact ray intersection (eliminates multi-view ghosting!) float aSnap, dSnap; float snapAng = floor(ang * 4.0) / 4.0; vec3 ro1 = vec3(1.85 * sin(snapAng), 0.18, 1.85 * cos(snapAng)); vec3 f1 = normalize(-ro1), r1 = normalize(cross(f1, vec3(0.0, 1.0, 0.0))), u1 = cross(r1, f1); vec3 cSnap = shadeTreeRay(ro1, normalize(f1 * 1.48 + r1 * uv.x + u1 * uv.y), aSnap, dSnap); vec3 finalTree = mix(cSnap, cExact, parallax); float finalA = mix(aSnap, aExact, parallax); col = mix(col, finalTree, finalA); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Octahedral impostors](https://texelatlas.vercel.app/t/octahedral-impostors.md) ## Combines with - [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md): GPU frustum and Hi-Z culling routes distant forest instances into indirect 8-strip impostor draws. - [Procedural foliage wind animation](https://texelatlas.vercel.app/t/foliage-wind-animation.md): Subtle vertex sway on the upper silhouette strips blends distant tree impostors seamlessly with nearby animated canopy meshes. ## Sources 1. [primary] Vlad Krutenyuk (2026) Octahedral Tree Impostors with Depth Parallax and Silhouette Strips. kvyverse. https://kvyverse.com/octahedral-tree-impostors (verified via http on 2026-11-30) 2. [implementation] Vlad Krutenyuk (2026) Octahedral Tree Impostors Live Source (Three.js). kvyverse Editor. https://kvyverse.com/editor/world/6b0041d2e78fe5de949e5722 (verified via http on 2026-11-30) 3. [tutorial] Ryan Brucks Octahedral Impostors. shaderbits.com. https://shaderbits.com/blog/octahedral-impostors (verified via http on 2026-11-30) ## Cite this entry Texel. "Silhouette-Strip Depth-Parallax Octahedral Impostors." https://texelatlas.vercel.app/t/silhouette-strip-octahedral-impostors/ (accessed 2026-12-01). --- id: "sillage-brush-splatting" title: "Gaussian splats drawn as brush marks" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu] inputs: [gaussians, camera-poses] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Kerbl et al., 2023" url: "https://texelatlas.vercel.app/t/sillage-brush-splatting/" sources_verified_at: "2026-11-29" --- # Gaussian splats drawn as brush marks (Kerbl et al., 2023) > Renders a Gaussian-splat scene by replacing each splat's smooth blob with a textured brush mark, so a captured or authored splat cloud reads as a painting. ## Reach for it when - want captured splat scene to look hand-painted - need painterly strokes in a browser viewer - splat renders look too photographic - turn a gaussian cloud into brush marks without retraining ## How it works Standard 3D Gaussian splatting projects each anisotropic Gaussian to a screen ellipse and alpha-blends it in depth order. The brush-mark approach keeps real 3D splats (position, direction, size) but draws each one as a stroke-like mark rather than a smooth blob, so marks overlap, break edges and hold still as the camera orbits. The `sillage3D` engine is a WebGL2 renderer with several mark styles (paint, gaussian, gouache), oil and watercolour variants, baked bounce light, depth of field and ambient occlusion. Scenes are JSON documents built from primitive forms, hand-placed splats, or trained `.splat` files. It is alpha software; its licence is PolyForm Noncommercial 1.0.0 (GitHub shows NOASSERTION), so commercial use needs separate terms ## When to use it Choose it when you have a splat scene and want a painted look with coherent strokes in a browser. Prefer [Stylized Gaussian splatting (G-Style)](https://texelatlas.vercel.app/t/stylized-gaussian-splatting.md) when you want to restyle the splat colours/geometry with a learned style transfer rather than change the footprint. Prefer [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) for a plain image-space filter on any frame. ## Cost medium — Same order of cost as standard splat rendering, plus brush texture sampling; depends on splat count. Measured GPU Weight: 70.84× baseline (extreme) — 2.3305 ms median / 2.418 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 60.14× baseline (extreme) — 0.9562 ms median (2.44× faster on L4). Ampere A100 scaling: 50.68× baseline (heavy) — 1.4597 ms median (1.6× faster on A100). ## Failure modes - Splat count and sort cost limit scene size on integrated GPUs - Brush marks reveal the splat sampling pattern in sparse regions - Hard clean edges, lettering and fine mechanical detail do not suit the painted look - PolyForm Noncommercial licence restricts commercial reuse of the code - Alpha-stage engine; API and scene format may change ## Dataflow - Inputs: gaussians, camera-poses - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu ## Presets ### Sillage Brush Splatting — smooth 3D Gaussian blobs (left) vs textured gouache brush-mark 3D splats (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BRISTLE": 0.8, "P_MARK_SCALE": 1, "P_ORBIT": 0.5, "P_SPLIT": 0.48 } ``` ```glsl const float P_BRISTLE = 0.80; // P Bristle Grain [0.1, 1.3, 0.05] const float P_MARK_SCALE = 1.00; // P Brush Mark Size [0.5, 1.6, 0.05] const float P_ORBIT = 0.50; // P Camera Orbit [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Gaussian / Brush [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isBrush = screenX >= split; float bristleAmt = clamp(P_BRISTLE, 0.05, 1.4); float mScale = clamp(P_MARK_SCALE, 0.4, 1.8); float t = iTime * max(P_ORBIT, 0.0); // Subtle linen-paper studio background float weave = 0.96 + 0.04 * sin(fragCoord.x * 0.85) * sin(fragCoord.y * 0.85); vec3 bg = mix(vec3(0.86, 0.83, 0.77), vec3(0.70, 0.74, 0.80), smoothstep(-0.45, 0.55, uv.y)) * weave; if (!isBrush) bg = mix(vec3(0.08, 0.10, 0.15), vec3(0.18, 0.23, 0.32), smoothstep(-0.45, 0.55, uv.y)); // Orbiting 3D Gaussian splat bouquet/arch composed of 34 anisotropic 3D splats vec3 accum = vec3(0.0); float trans = 1.0; for (int i = 0; i < 34; i++) { float fi = float(i); float u = fi / 34.0; // Arrange splats along a sculptural 3D floral-crown / vase volume float theta = u * 6.2831853 * 3.0; float y = (u - 0.5) * 0.72; float rad = 0.28 + 0.14 * sin(u * 9.4247); vec3 p3 = vec3(rad * cos(theta), y, rad * sin(theta)); p3.xz = rot2(p3.xz, t * 0.65); p3.yz = rot2(p3.yz, 0.22 * sin(t * 0.4)); float zCam = 1.85 - p3.z; vec2 proj = p3.xy / max(zCam * 0.64, 0.3); vec2 d = uv - proj; // 3D splat orientation projected to screen float splatAng = theta + t * 0.65 + hash11(fi * 17.3) * 1.4; vec2 dl = rot2(d, splatAng); vec2 axis = vec2(0.115, 0.048) * mScale / max(zCam * 0.58, 0.35); vec2 q = dl / axis; // Rich botanical gouache palette driven by 3D position + height vec3 baseCol = mix(vec3(0.14, 0.42, 0.56), vec3(0.94, 0.46, 0.24), smoothstep(-0.35, 0.30, y)); baseCol = mix(baseCol, vec3(0.96, 0.80, 0.28), smoothstep(0.18, 0.42, y) * 0.85); baseCol *= 0.78 + 0.38 * smoothstep(-0.35, 0.35, p3.z + 0.2 * p3.y); float alpha = 0.0; vec3 markCol = baseCol; if (!isBrush) { // Left: Standard smooth analytical 3D Gaussian splat ellipse float g = exp(-0.5 * dot(q, q)); alpha = clamp(g * 0.76, 0.0, 0.94); } else { // Right: Sillage brush-splatting -- replace smooth Gaussian with crisp dry-bristle gouache mark! // Rounded-rectangle tapered brush body + frayed bristle tips along major axis q.x float bristleWave = sin(q.y * 16.0 + fi * 4.3) * 0.5 + 0.5; float tipFray = 1.0 - 0.32 * bristleAmt * bristleWave; float bodyX = abs(q.x) - 1.15 * tipFray; float bodyY = abs(q.y) - (0.86 - 0.16 * q.x * q.x); float sdf = max(bodyX, bodyY); float edgeMask = smoothstep(0.16, -0.06, sdf); // Bristle striations & subtle pigment pooling along outer edge of stroke float grain = mix(1.0, 0.76 + 0.34 * sin(q.y * 26.0 + q.x * 2.0 + fi * 9.1), bristleAmt * 0.75); float edgePool = smoothstep(-0.35, 0.05, sdf) * 0.16; markCol = baseCol * grain * (1.0 - edgePool); alpha = edgeMask * 0.88; } if (alpha > 0.01) { float depthShade = exp(-max(zCam - 1.35, 0.0) * 0.45); accum += markCol * depthShade * alpha * trans; trans *= (1.0 - alpha * 0.62); } } vec3 col = accum + bg * trans; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.96, 0.97, 0.99), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Bernhard Kerbl, Georgios Kopanas, Thomas Leimkuehler, George Drettakis (2023) 3D Gaussian Splatting for Real-Time Radiance Field Rendering. ACM Transactions on Graphics. https://doi.org/10.1145/3592433 (verified via crossref on 2026-11-29) 2. [implementation] wrong-nebula (2026) wrong-nebula/sillage3D. https://github.com/wrong-nebula/sillage3D License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Gaussian splats drawn as brush marks." https://texelatlas.vercel.app/t/sillage-brush-splatting/ (accessed 2026-12-01). --- id: "simplex-noise" title: "Simplex Noise" aliases: [OpenSimplex (patent-free relative)] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, python] year_introduced: 2001 outputs: [texture, heightfield, volume-density] style: "both" dynamic: "both" cost: "cheap" authority: "Gustavson" url: "https://texelatlas.vercel.app/t/simplex-noise/" sources_verified_at: "2026-11-29" --- # Simplex Noise (Gustavson) > Gradient noise evaluated on a simplicial grid (triangles in 2D, tetrahedra in 3D) rather than a cubic one, so the number of contributing corners grows linearly with dimension and directional artifacts shrink. ## Reach for it when - perlin noise shows grid-aligned artefacts - need animated 3d or 4d noise cheaply - noise for volumetric density with less directional bias - noise cost grows too fast in higher dimensions - smoother organic noise for clouds or terrain ## How it works The input is skewed so the unit hypercubes become sets of simplices; the cell containing the point is found by sorting the fractional coordinates. Only n+1 corners contribute instead of 2^n. Each corner gets a hashed gradient, and its contribution is the dot product times a radially symmetric falloff kernel of the form (r^2 - d^2)^4 clipped at zero beyond the corner's influence radius. Contributions are summed and scaled to roughly unit range, then unskewed coordinates are used for distance. The summation kernel instead of interpolation gives a visually more isotropic field with no axis-aligned bias. The original idea is Perlin's 2001 course material; Gustavson's write-up and GLSL implementations made it practical on GPUs. ## When to use it Choose it for 3D/4D animated noise (time as fourth dimension), for volumetric density, or when grid alignment in [Improved Perlin Noise](https://texelatlas.vercel.app/t/improved-perlin-noise.md) is visible. Prefer [Improved Perlin Noise](https://texelatlas.vercel.app/t/improved-perlin-noise.md) in 2D when you need simplicity or analytic derivatives are already derived for it, and note that classic 3D simplex was patented in the US until 2022, so older engines ship OpenSimplex variants. ## Cost cheap — Fewer corners than cubic Perlin in 3D and above; in 2D the two are comparable. Measured GPU Weight: 4.92× baseline (light) — 0.1619 ms median / 0.1711 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.92× baseline (light) — 0.0623 ms median (2.6× faster on L4). Ampere A100 scaling: 2.77× baseline (light) — 0.0798 ms median (2.03× faster on A100). ## Failure modes - Patent history (US 6867776, expired January 2022) led many libraries to ship look-alike variants with different output, so seeds are not portable across implementations - Visible diagonal bias in some 2D implementations that skew incorrectly - Sharp falloff kernel makes derivatives noisier than quintic Perlin when used for normals - Output range differs per dimension and per library, so scale constants copied between codebases are wrong ## Engine support - babylonjs: builtin — `SimplexPerlin3DBlock in Node Material Editor` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Node/Blocks/simplexPerlin3DBlock.ts, checked 2026-12-01) - blender: builtin — `Shader / Geometry Nodes > Noise Texture (multi-dimensional FBM gradient noise)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/noise.html, checked 2026-12-01) - godot: builtin — `FastNoiseLite.noise_type = FastNoiseLite.TYPE_SIMPLEX` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/noise/doc_classes/FastNoiseLite.xml, checked 2026-12-01) - threejs: official — `import { SimplexNoise } from 'three/addons/math/SimplexNoise.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/math/SimplexNoise.js, checked 2026-12-01) - unity: official — `Package Manager > Mathematics > noise.snoise` (evidence: https://github.com/Unity-Technologies/Unity.Mathematics/blob/master/src/Unity.Mathematics/Noise/noise3D.cs, checked 2026-12-01) — Unity.Mathematics simplex noise (Gustavson/McEwan). - unreal: builtin — `Material Noise expression > Function = Simplex (texture based)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/utility-material-expressions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: texture, heightfield, volume-density - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, unity, unreal, godot, python ## Presets ### 2D simplex noise over its skewed triangular lattice (glsl-fragment; rendered 2026-11-29) ```json { "SCALE": 5 } ``` ```glsl // 2D simplex noise: skewed triangular lattice (white lines) with three radially-attenuated gradient contributions per triangle. const float SCALE = 5.0; vec2 grad(vec2 i) { float a = 6.2831853 * fract(sin(dot(i, vec2(127.1, 311.7))) * 43758.5453); return vec2(cos(a), sin(a)); } float simplex(vec2 v) { const float F = 0.3660254, G = 0.2113249; vec2 i = floor(v + (v.x + v.y) * F); vec2 x0 = v - i + (i.x + i.y) * G; vec2 o = x0.x > x0.y ? vec2(1, 0) : vec2(0, 1); vec2 x1 = x0 - o + G, x2 = x0 - 1.0 + 2.0 * G; float n = 0.0; float t0 = max(0.5 - dot(x0, x0), 0.0); n += t0 * t0 * t0 * t0 * dot(grad(i), x0); float t1 = max(0.5 - dot(x1, x1), 0.0); n += t1 * t1 * t1 * t1 * dot(grad(i + o), x1); float t2 = max(0.5 - dot(x2, x2), 0.0); n += t2 * t2 * t2 * t2 * dot(grad(i + 1.0), x2); return 70.0 * n; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 p = uv * SCALE; float n = simplex(p) * 0.5 + 0.5; float n2 = simplex(p * 2.0 + 7.0) * 0.5 + 0.5; float h = 0.7 * n + 0.3 * n2; vec3 col = 0.5 + 0.5 * cos(6.2831 * (h * 1.1 + vec3(0.0, 0.1, 0.2))); col *= 0.7 + 0.3 * smoothstep(0.0, 0.5, abs(fract(h * 10.0) - 0.5)); vec2 s = p + (p.x + p.y) * 0.3660254; vec2 f = fract(s); float edge = min(min(f.x, 1.0 - f.x), min(min(f.y, 1.0 - f.y), abs(f.x + f.y - 1.0) * 0.7071)); col = mix(col, vec3(1.0), smoothstep(0.02, 0.008, edge) * 0.8); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) ## Sources 1. [primary] Stefan Gustavson Simplex noise demystified. weber.itn.liu.se. https://weber.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf (verified via wayback on 2026-11-29) 2. [primary] Ian McEwan, David Sheets, Mark Richardson, Stefan Gustavson (2012) Efficient Computational Noise in GLSL. Journal of Graphics Tools. https://doi.org/10.1080/2151237x.2012.649621 (verified via crossref on 2026-11-29) 3. [implementation] stegu (2016) stegu/webgl-noise. https://github.com/stegu/webgl-noise License: MIT. (verified via github on 2026-11-29) 4. [implementation] jwagner (2012) jwagner/simplex-noise.js. https://github.com/jwagner/simplex-noise.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Simplex Noise." https://texelatlas.vercel.app/t/simplex-noise/ (accessed 2026-12-01). --- id: "smaa" title: "SMAA" aliases: [Subpixel Morphological Anti-Aliasing] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity] year_introduced: 2012 inputs: [ldr-image] outputs: [ldr-image] style: "both" dynamic: "both" cost: "cheap" authority: "Jimenez et al., 2012" url: "https://texelatlas.vercel.app/t/smaa/" sources_verified_at: "2026-11-29" --- # SMAA (Jimenez et al., 2012) > Morphological anti-aliasing in three passes: detect edges, compute per-pixel blending weights from pattern area lookups, then blend neighbours. Sharper than FXAA and with optional temporal and MSAA extensions. ## Reach for it when - jagged edges without heavy msaa cost - post process anti aliasing that stays sharp - fxaa blurs the whole image too much - deferred renderer can't use hardware msaa ## How it works SMAA first detects edges from luma, colour or depth deltas, using local contrast adaptation to suppress false positives near strong edges. The second pass is the core: for every edge pixel it searches along the edge in both directions to find its endpoints, reads the crossing edges at each end to classify the line shape (L, Z, U), and looks the coverage up in a precomputed area texture. A separate search texture accelerates the walk. The output is a four-channel weight buffer. The third pass blends each pixel with its neighbours according to those weights, using bilinear taps to apply two blends in one fetch. Variants add diagonal pattern detection, corner rounding and a 2x temporal mode. ## When to use it Choose it when you want clean geometric edges at modest cost and no motion vectors. Prefer [FXAA](https://texelatlas.vercel.app/t/fxaa.md) when you must stay in a single pass. Prefer [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md) when shading and subpixel aliasing matter more than edge shape. SMAA T2x gives a taste of temporal supersampling if you have jitter and velocity. ## Cost cheap — Three passes plus two small lookup textures; still around a millisecond or less at 1080p (qualitative). Measured GPU Weight: 6.61× baseline (moderate) — 0.2174 ms median / 0.2189 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.66× baseline (light) — 0.09 ms median (2.42× faster on L4). Ampere A100 scaling: 4.44× baseline (light) — 0.1279 ms median (1.7× faster on A100). ## Failure modes - Cannot reconstruct subpixel features thinner than a pixel - Shading aliasing and specular crawl are untouched - Edge detection thresholds need tuning per content; noisy scenes produce spurious blur - Needs a render target format that preserves the weight buffer, and three passes cost bandwidth on mobile ## Engine support - blender: builtin — `Preferences > Viewport > Quality > Viewport Anti-Aliasing (morphological screen-space AA)` (evidence: https://docs.blender.org/manual/en/5.2/editors/preferences/viewport.html, checked 2026-12-01) - godot: builtin — `Viewport.screen_space_aa = Viewport.SCREEN_SPACE_AA_SMAA` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Viewport.xml, checked 2026-12-01) - threejs: official — `import { smaa } from 'three/addons/tsl/display/SMAANode.js' (WebGL: SMAAPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SMAANode.js, checked 2026-12-01) - unity: builtin — `Camera > Rendering > Anti-aliasing = Subpixel Morphological Anti-aliasing (SMAA)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.shader, checked 2026-12-01) — URP and HDRP. ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity ## Presets ### SMAA — aliased 1x raster edges (left) vs morphological L/Z/U edge search & subpixel coverage blending (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PIXEL_SIZE": 3.5, "P_EDGE_THRESH": 0.12, "P_EDGE_DEBUG": 0.25, "P_SPLIT": 0.48 } ``` ```glsl const float P_PIXEL_SIZE = 3.50; // P Raster Pixel Zoom [1.5, 7.0, 0.25] const float P_EDGE_THRESH = 0.12; // P Edge Threshold [0.04, 0.35, 0.02] const float P_EDGE_DEBUG = 0.25; // P Edge Overlay [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P Aliased / SMAA [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Sharp high-contrast geometric blades & polygons that produce classic 1x stair-step jaggies vec3 evalAliased(vec2 uv, float t) { vec3 col = mix(vec3(0.07, 0.10, 0.16), vec3(0.16, 0.24, 0.36), smoothstep(-0.5, 0.5, uv.y)); vec2 p = rot2(uv, 0.18 * sin(t * 0.45) + 0.12); // Sharp tilted white & orange architectural monoliths vec2 b1 = abs(p - vec2(-0.18, 0.02)) - vec2(0.24, 0.34); if (max(b1.x, b1.y) < 0.0) { col = mix(vec3(0.86, 0.89, 0.94), vec3(0.68, 0.74, 0.84), smoothstep(-0.3, 0.3, p.y)); } vec2 p2 = rot2(uv - vec2(0.14, -0.04), -0.34 + 0.10 * cos(t * 0.5)); vec2 b2 = abs(p2) - vec2(0.26, 0.18); if (max(b2.x, b2.y) < 0.0) { col = vec3(0.95, 0.44, 0.16); } // Crisp diagonal cyan blade cutting across both shapes vec2 p3 = rot2(uv, 0.28); if (abs(p3.y - 0.05) < 0.048 && abs(p3.x) < 0.55) { col = vec3(0.14, 0.86, 0.96); } // Fine circular ring with high-contrast boundary float rc = length(uv - vec2(0.02, 0.02)); if (abs(rc - 0.28) < 0.024) { col = vec3(0.10, 0.12, 0.18); } return col; } vec3 fetchPx(vec2 cellCoord, float cell, float t) { vec2 fc = (cellCoord + 0.5) * cell; vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; return evalAliased(uv, t); } float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float cell = clamp(P_PIXEL_SIZE, 1.2, 8.0); float thresh = clamp(P_EDGE_THRESH, 0.03, 0.4); float dbg = clamp(P_EDGE_DEBUG, 0.0, 1.0); vec2 pix = floor(fragCoord / cell); vec3 cC = fetchPx(pix, cell, iTime); vec3 cL = fetchPx(pix + vec2(-1.0, 0.0), cell, iTime); vec3 cR = fetchPx(pix + vec2(1.0, 0.0), cell, iTime); vec3 cD = fetchPx(pix + vec2(0.0, -1.0), cell, iTime); vec3 cU = fetchPx(pix + vec2(0.0, 1.0), cell, iTime); // Pass 1: Local-contrast-adapted luma edge detection float lC = luma(cC); float dH = max(abs(lC - luma(cD)), abs(lC - luma(cU))); float dV = max(abs(lC - luma(cL)), abs(lC - luma(cR))); float edgeH = step(thresh, dH); float edgeV = step(thresh, dV); vec3 col = cC; if (screenX < split) { // Left: Raw 1x aliased pixels + optional SMAA Pass-1 edge detection highlight (red=horiz, green=vert) vec3 edgeTint = vec3(edgeH, edgeV, 0.0); col = mix(cC, edgeTint * 1.25, dbg * clamp(edgeH + edgeV, 0.0, 1.0) * 0.65); } else { // Right: Pass 2 & 3 -- Search along horizontal/vertical span to measure stair-step run length & blend coverage! vec3 blended = cC; if (edgeH > 0.5) { float spanL = 0.0; float spanR = 0.0; float upSide = step(abs(lC - luma(cD)), abs(lC - luma(cU))); float dirY = (upSide > 0.5) ? 1.0 : -1.0; for (int s = 1; s <= 6; s++) { float fs = float(s); float l1 = luma(fetchPx(pix + vec2(-fs, 0.0), cell, iTime)); float l2 = luma(fetchPx(pix + vec2(-fs, dirY), cell, iTime)); if (abs(l1 - l2) < thresh) break; spanL = fs; } for (int s = 1; s <= 6; s++) { float fs = float(s); float l1 = luma(fetchPx(pix + vec2(fs, 0.0), cell, iTime)); float l2 = luma(fetchPx(pix + vec2(fs, dirY), cell, iTime)); if (abs(l1 - l2) < thresh) break; spanR = fs; } float totalSpan = max(spanL + spanR + 1.0, 1.0); float posAlong = (spanL + 0.5) / totalSpan; // Trapezoidal area coverage lookup approximation for L/Z crossing patterns float cov = clamp(0.5 - abs(posAlong - 0.5), 0.0, 0.5) * 1.15; vec3 neigh = (dirY > 0.0) ? cU : cD; blended = mix(blended, neigh, cov); } if (edgeV > 0.5) { float spanD = 0.0; float spanU = 0.0; float rightSide = step(abs(lC - luma(cL)), abs(lC - luma(cR))); float dirX = (rightSide > 0.5) ? 1.0 : -1.0; for (int s = 1; s <= 6; s++) { float fs = float(s); float l1 = luma(fetchPx(pix + vec2(0.0, -fs), cell, iTime)); float l2 = luma(fetchPx(pix + vec2(dirX, -fs), cell, iTime)); if (abs(l1 - l2) < thresh) break; spanD = fs; } for (int s = 1; s <= 6; s++) { float fs = float(s); float l1 = luma(fetchPx(pix + vec2(0.0, fs), cell, iTime)); float l2 = luma(fetchPx(pix + vec2(dirX, fs), cell, iTime)); if (abs(l1 - l2) < thresh) break; spanU = fs; } float totalSpan = max(spanD + spanU + 1.0, 1.0); float posAlong = (spanD + 0.5) / totalSpan; float cov = clamp(0.5 - abs(posAlong - 0.5), 0.0, 0.5) * 1.15; vec3 neigh = (dirX > 0.0) ? cR : cL; blended = mix(blended, neigh, cov * 0.85); } // Smooth sub-cell anti-aliased readout at display resolution vec2 uvExact = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 fineRef = evalAliased(uvExact, iTime); col = mix(blended, fineRef, 0.35); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [FXAA](https://texelatlas.vercel.app/t/fxaa.md) ## Combines with - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): SMAA handles geometric edges while TAA handles shading; the T2x mode shares jitter. ## Sources 1. [primary] Jorge Jimenez, Jose I. Echevarria, Tiago Sousa, Diego Gutierrez (2012) SMAA: Enhanced Subpixel Morphological Antialiasing. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2012.03014.x (verified via crossref on 2026-11-29) 2. [implementation] iryoku (2011) iryoku/smaa. https://github.com/iryoku/smaa License: NOASSERTION. (verified via github on 2026-11-29) 3. [implementation] pmndrs (2015) pmndrs/postprocessing. https://github.com/pmndrs/postprocessing License: Zlib. (verified via github on 2026-11-29) ## Cite this entry Texel. "SMAA." https://texelatlas.vercel.app/t/smaa/ (accessed 2026-12-01). --- id: "small-angle-underwater-psf-scattering" title: "Multi-Lobe Small-Angle Forward-Scattering Optical PSF Convolution" aliases: [underwater optical PSF, small-angle forward scattering glow, Wells-Jaffe underwater scattering] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 1969 inputs: [hdr-image, depth, volume-density] outputs: [hdr-image] style: "photoreal" dynamic: "dynamic" cost: "cheap" authority: "Wells, 1969" url: "https://texelatlas.vercel.app/t/small-angle-underwater-psf-scattering/" sources_verified_at: "2026-11-30" --- # Multi-Lobe Small-Angle Forward-Scattering Optical PSF Convolution (Wells, 1969) > Models underwater image blur and luminous halation by convolving the HDR scene with a depth-dependent multi-lobe point spread function derived from small-angle forward scattering theory. ## Reach for it when - exponential underwater fog looks flat and misses bright silhouette halation - need realistic turbid water blur that grows with optical distance - simulate forward scattering glow around underwater sunbeams and lights - distant reef and kelp outlines stay unrealistically crisp in murky water - apply physically grounded underwater point spread filtering in post ## How it works Underwater visibility degrades through three distinct radiative components (Jaffe 1990): exponentially attenuated direct radiance, ambient **backscatter** veiling light, and **small-angle forward scattering** of light leaving scene surfaces toward the camera. Because suspended marine particulates scatter strongly in the forward direction, photons deflected by small angles still reach nearby camera pixels, blurring distant edges and wrapping bright highlights in soft turquoise-gold haloes. Following **Wells' small-angle approximation**, the medium's optical transfer function decays exponentially with optical depth `b * z` and spatial frequency, yielding a radial **point spread function (PSF)** whose width grows with range `z` and scattering coefficient `b`. Because a real-time spatially varying convolution over arbitrary radii is expensive, the PSF is decomposed into a **weighted sum of concentric Gaussian lobes** (narrow core plus progressively wider forward-scatter tails) evaluated on a hierarchical HDR mip pyramid. During compositing, each pixel blends the sharp direct image with depth-weighted taps across pyramid levels—rejecting foreground bleed with bilateral depth weights—while applying wavelength-selective Beer-Lambert absorption (red fading first, then green, leaving blue-cyan) and in-scattered ambient veiling light. ## When to use it Choose it when rendering submerged scenes, kelp forests, reefs, or underwater ROV/camera optics where realistic range-dependent contrast loss and forward-scattered light haloes matter more than simple uniform fog. Prefer [exponential-height-fog](exponential-height-fog) when cheap distance tinting alone is sufficient and edge blurring is unnecessary. Prefer [froxel-volumetric-fog](froxel-volumetric-fog) or [volume-ray-marching](volume-ray-marching) when heterogeneous light shafts, local spotlights, and shadowed 3D turbidity plumes dominate over image-space forward blur. ## Cost cheap — Separable downsample/upsample pyramid passes plus depth-weighted multi-lobe compositing run well under 1 ms at 1080p on mid-range desktop GPUs. Measured GPU Weight: 8.69× baseline (moderate) — 0.2859 ms median / 0.2879 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.12× baseline (moderate) — 0.1132 ms median (2.53× faster on L4). Ampere A100 scaling: 6.05× baseline (moderate) — 0.1742 ms median (1.64× faster on A100). ## Failure modes - Without bilateral depth weighting, bright foreground objects bleed halo energy onto dark backgrounds and distant bright highlights leak across sharp foreground silhouettes - Screen-space convolution cannot scatter light from bright submerged objects or sunbeams located just outside the camera frustum - Approximating the continuous range-dependent Wells PSF with too few discrete pyramid lobes creates visible depth banding across steep turbidity gradients - Ignoring spectral absorption coupling causes forward-scattered haloes to keep unnaturally warm red tones at long distances ## Dataflow - Inputs: hdr-image, depth, volume-density - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Underwater Small-Angle PSF Scattering — Beer-Lambert only (left) vs depth-dependent multi-lobe optical PSF halation (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TURBIDITY": 0.72, "P_PSF_WIDTH": 1.15, "P_LAMP_POWER": 1.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_TURBIDITY = 0.72; // P Water Turbidity [0.2, 1.6, 0.05] const float P_PSF_WIDTH = 1.15; // P Forward PSF Spread [0.3, 2.2, 0.05] const float P_LAMP_POWER = 1.65; // P Beacon Power [0.5, 3.0, 0.1] const float P_SPLIT = 0.48; // P Sharp / PSF Split [0.0, 1.0, 0.02] // Evaluate crisp HDR underwater scene (coral archway + 3 glowing diver beacon lamps at near, mid, and far depths!) void evalUnderwaterScene(vec2 uv, float turb, float lampPow, out vec3 hdrCol, out float depthZ) { // Deep ocean vertical caustic & veil gradient float caustic = 0.5 + 0.5 * sin(uv.x * 16.0 + iTime * 1.4) * cos(uv.y * 12.0 - iTime * 1.1); vec3 waterBg = mix(vec3(0.015, 0.09, 0.16), vec3(0.04, 0.28, 0.38), smoothstep(-0.5, 0.5, uv.y)); waterBg += vec3(0.03, 0.14, 0.18) * caustic * smoothstep(-0.1, 0.5, uv.y); hdrCol = waterBg; depthZ = 18.0; // Seabed floor receding into distance if (uv.y < -0.14) { float z = 1.6 / max(-uv.y - 0.10, 0.04); depthZ = min(z, 18.0); float sandC = 0.5 + 0.5 * sin(uv.x * z * 4.5 + iTime * 1.6) * cos(z * 3.2 - iTime * 1.2); vec3 sand = vec3(0.16, 0.24, 0.22) * (0.7 + 0.65 * sandC); vec3 atten = exp(-vec3(0.45, 0.16, 0.11) * depthZ * turb * 0.45); hdrCol = mix(waterBg, sand * atten, exp(-depthZ * turb * 0.08)); } // Silhouetted sunken stone archway at mid depth (z = 7.5m) vec2 ap = uv - vec2(0.0, -0.02); float dArch = abs(length(ap * vec2(1.0, 1.15)) - 0.34) - 0.075; if (dArch < 0.0 && ap.y > -0.28) { depthZ = 7.5; vec3 stone = vec3(0.06, 0.13, 0.16); hdrCol = mix(waterBg, stone, exp(-depthZ * turb * 0.08)); } // Three bright underwater beacon lamps at increasing depths: Near (z=2.5m), Mid (z=7.2m), Far (z=13.5m)! vec2 lPos[3]; float lDepth[3]; vec3 lHue[3]; lPos[0] = vec2(-0.42 + 0.05 * sin(iTime * 0.7), -0.16); lDepth[0] = 2.6; lHue[0] = vec3(2.8, 2.2, 1.2); lPos[1] = vec2(0.02 + 0.04 * cos(iTime * 0.6), 0.12); lDepth[1] = 7.2; lHue[1] = vec3(1.1, 2.8, 2.4); lPos[2] = vec2(0.42 + 0.04 * sin(iTime * 0.5), 0.04); lDepth[2] = 13.5; lHue[2] = vec3(2.8, 1.3, 0.7); for (int i = 0; i < 3; i++) { float r = length(uv - lPos[i]); float rad = 0.048 / sqrt(lDepth[i] * 0.35); if (r < rad * 1.4) { depthZ = min(depthZ, lDepth[i]); float core = smoothstep(rad * 1.35, rad * 0.35, r); vec3 atten = exp(-vec3(0.32, 0.11, 0.08) * lDepth[i] * turb * 0.32); hdrCol += lHue[i] * atten * core * lampPow * 2.6; } } } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool usePSF = sx >= split; float turb = clamp(P_TURBIDITY, 0.15, 2.0); float psfW = clamp(P_PSF_WIDTH, 0.2, 2.5); float lampPow = clamp(P_LAMP_POWER, 0.3, 3.5); vec3 col; float z; evalUnderwaterScene(uv, turb, lampPow, col, z); if (usePSF) { // Right: Multi-lobe Small-Angle Forward-Scattering Optical PSF convolution (depth-dependent narrow + wide Gaussian lobes!) vec2 lPos[3]; float lDepth[3]; vec3 lHue[3]; lPos[0] = vec2(-0.42 + 0.05 * sin(iTime * 0.7), -0.16); lDepth[0] = 2.6; lHue[0] = vec3(2.8, 2.2, 1.2); lPos[1] = vec2(0.02 + 0.04 * cos(iTime * 0.6), 0.12); lDepth[1] = 7.2; lHue[1] = vec3(1.1, 2.8, 2.4); lPos[2] = vec2(0.42 + 0.04 * sin(iTime * 0.5), 0.04); lDepth[2] = 13.5; lHue[2] = vec3(2.8, 1.3, 0.7); // Subtle spatial small-angle PSF blur on background archway & seabed proportional to optical depth vec3 blurAcc = col * 0.45; float blurRad = clamp(z * turb * 0.0018 * psfW, 0.001, 0.028); for (int k = 0; k < 6; k++) { float ang = float(k) * 1.0471975; vec3 cN; float zN; evalUnderwaterScene(uv + vec2(cos(ang), sin(ang)) * blurRad, turb, lampPow, cN, zN); blurAcc += cN * (0.55 / 6.0); } col = blurAcc; // Analytical multi-lobe small-angle forward-scattering PSF halation around each underwater emitter: // Lobe 1 (tight core), Lobe 2 (mid forward-scatter glow), Lobe 3 (broad multiple-scatter aureole) // Spread grows with optical depth tau = turb * depth! for (int i = 0; i < 3; i++) { float r = length(uv - lPos[i]); float tau = lDepth[i] * turb * 0.12; float s1 = max(0.015 + 0.025 * tau * psfW, 0.01); float s2 = max(0.045 + 0.085 * tau * psfW, 0.02); float s3 = max(0.110 + 0.180 * tau * psfW, 0.05); float psf = 0.55 * exp(-r * r / (2.0 * s1 * s1)) + 0.32 * exp(-r * r / (2.0 * s2 * s2)) + 0.16 * exp(-r / s3); vec3 atten = exp(-vec3(0.32, 0.11, 0.08) * lDepth[i] * turb * 0.28); // Forward scatter grows in relative energy as optical depth increases! float scatFrac = 1.0 - exp(-tau * 1.85); col += lHue[i] * atten * psf * scatFrac * lampPow * 0.88; } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Dual-filter and progressive-downsample bloom](https://texelatlas.vercel.app/t/dual-filter-bloom.md): Provides fast hierarchical downsample/upsample mip levels whose radii map directly onto the concentric underwater PSF lobes. - [Screen-space Volumetric Light Scattering (God Rays)](https://texelatlas.vercel.app/t/volumetric-light-scattering-god-rays.md): Supplies directional sun shafts and backscatter veiling light that complement the forward-scattered image blur. ## Combination ideas - [Meshlet kelp forests through underwater PSF scattering](https://texelatlas.vercel.app/ideas/meshlet-kelp-small-angle-underwater-psf/) ## Sources 1. [primary] Willard H. Wells (1969) Loss of Resolution in Water as a Result of Multiple Small-Angle Scattering. Journal of the Optical Society of America. https://doi.org/10.1364/josa.59.000686 (verified via doi.org on 2026-11-30) 2. [primary] J.S. Jaffe (1990) Computer modeling and the design of optimal underwater imaging systems. IEEE Journal of Oceanic Engineering. https://doi.org/10.1109/48.50695 (verified via crossref on 2026-11-30) 3. [implementation] mrdoob (2026) mrdoob/codevember-2026. https://github.com/mrdoob/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Multi-Lobe Small-Angle Forward-Scattering Optical PSF Convolution." https://texelatlas.vercel.app/t/small-angle-underwater-psf-scattering/ (accessed 2026-12-01). --- id: "smith-masking-shadowing" title: "Smith masking-shadowing function" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2014 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Heitz" url: "https://texelatlas.vercel.app/t/smith-masking-shadowing/" sources_verified_at: "2026-11-29" --- # Smith masking-shadowing function (Heitz) > The statistically grounded geometry term for microfacet BRDFs. Heitz's JCGT analysis shows how to pair Smith's G with the normal distribution, why height-correlated G is the right choice, and where the separable form falls short. ## Reach for it when - specular looks too bright at grazing angles - which geometry term pairs with ggx - microfacet highlights lose energy or look wrong when rough - need a correct shadowing-masking term in a pbr shader ## How it works A microfacet only contributes if both the incoming and outgoing rays reach it unobstructed. Smith's model derives masking G1(v) from the normal distribution itself via the auxiliary function Lambda, which for GGX has a closed form involving sqrt(1 + a^2 tan^2 theta). The simplest combination multiplies G1(l)*G1(v) (separable, assumes uncorrelated visibility). Heitz showed that the height-correlated form, G2 = 1 / (1 + Lambda(l) + Lambda(v)), is more accurate because rays at similar heights are visible together, and the same paper clarifies the roles of height versus direction correlation. Real-time engines fold G2 and the 1/(4 n.l n.v) denominator into one visibility term V that is cheaper and better behaved. Approximations to Lambda avoid the square roots. ## When to use it Choose it for the G term of any GGX-based shader; use the height-correlated form unless matching a legacy look. Prefer a simplified Schlick-GGX masking (as in early Unreal) only on very constrained mobile hardware. If bright rough metals look too dark, the missing piece is not G but [Kulla-Conty multiple-scattering compensation](https://texelatlas.vercel.app/t/kulla-conty-multiscatter.md). ## Cost cheap — Two sqrt-and-divide evaluations, or an approximation of Lambda; commonly merged into the visibility term. Measured GPU Weight: 1.62× baseline (feather) — 0.0533 ms median / 0.0587 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.31× baseline (feather) — 0.0208 ms median (2.56× faster on L4). Ampere A100 scaling: 1.05× baseline (feather) — 0.0302 ms median (1.76× faster on A100). ## Failure modes - Separable G darkens grazing angles and slightly overestimates energy loss compared with the correlated form - Fast Lambda approximations (e.g. fused sqrt-free forms) introduce small errors at high roughness - Smith assumes uncorrelated microfacet heights and normals, so sharply structured surfaces such as scratches and brushed metals deviate from it - Lost inter-facet bounces make rough conductors darker than reality ## Engine support - babylonjs: builtin — `pbrMaterial.brdf.useSmithVisibilityHeightCorrelated = true` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBRDFConfiguration.ts, checked 2026-12-01) - blender: builtin — `Cycles Principled / Glossy GGX microfacet closures evaluate Smith masking-shadowing in intern/cycles/kernel/closure/bsdf_microfacet.h` (evidence: https://github.com/blender/blender/blob/main/intern/cycles/kernel/closure/bsdf_microfacet.h, checked 2026-12-01) - godot: builtin — `BaseMaterial3D SPECULAR_SCHLICK_GGX evaluates height-correlated Smith visibility (V_GGX / V_GGX_anisotropic)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl, checked 2026-12-01) - threejs: builtin — `MeshStandardMaterial / MeshPhysicalMaterial` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/functions/BSDF/V_GGX_SmithCorrelated.js, checked 2026-12-01) — Height-correlated Smith visibility. - unity: builtin — `Lit shaders in URP and HDRP` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl, checked 2026-12-01) — HDRP uses height-correlated Smith joint GGX. ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### GGX specular without (left) vs with (right) Smith masking-shadowing (glsl-fragment; rendered 2026-11-29) ```json { "ROUGH": 0.45 } ``` ```glsl // GGX specular with and without the Smith masking-shadowing term G (roughness 0.45), rim-lit from behind. // Left: G = 1, specular D*F/(4 NL NV) blows up at grazing angles. Right: height-correlated Smith G. const float ROUGH = 0.45; float D_ggx(float nh, float a) { float a2 = a * a; float d = nh * nh * (a2 - 1.0) + 1.0; return a2 / (3.14159 * d * d); } float G_smith(float nl, float nv, float a) { float a2 = a * a; float gv = nl * sqrt((-nv * a2 + nv) * nv + a2), gl = nv * sqrt((-nl * a2 + nl) * nl + a2); return 2.0 * nl * nv / max(gv + gl, 1e-5); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -2.4)); vec3 col = vec3(0.02) + 0.02 * uv.y; for (int i = 0; i < 2; i++) { vec3 c = vec3(i == 0 ? -0.5 : 0.5, 0.0, 0.0); vec3 oc = ro - c; float b = dot(oc, rd); float h = b * b - dot(oc, oc) + 0.46 * 0.46; if (h < 0.0) continue; float t = -b - sqrt(h); vec3 n = normalize(ro + rd * t - c); vec3 v = -rd; vec3 tot = vec3(0.02, 0.03, 0.05); for (int k = 0; k < 2; k++) { vec3 l = k == 0 ? normalize(vec3(-0.3, 0.6, -0.75)) : normalize(vec3(0.2, 0.2, 1.0)); float nl = dot(n, l); if (nl <= 0.0) continue; float nv = max(dot(n, v), 1e-3); vec3 hv = normalize(l + v); float a = ROUGH * ROUGH; float F = 0.04 + 0.96 * pow(1.0 - max(dot(l, hv), 0.0), 5.0); float G = i == 0 ? 1.0 : G_smith(nl, nv, a); float spec = D_ggx(max(dot(n, hv), 0.0), a) * F * G / (4.0 * nl * nv); tot += (k == 0 ? 2.5 : 1.2) * (spec + vec3(0.06, 0.09, 0.15) / 3.14159) * nl; } col = tot; } col = col / (1.0 + col); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) - extended by [Visible normal distribution sampling (GGX VNDF)](https://texelatlas.vercel.app/t/vndf-sampling.md) ## Sources 1. [primary] Eric Heitz Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs. JCGT 2014. https://jcgt.org/published/0003/02/03 (verified via http on 2026-11-29) ## Cite this entry Texel. "Smith masking-shadowing function." https://texelatlas.vercel.app/t/smith-masking-shadowing/ (accessed 2026-12-01). --- id: "snow-terrain-deformation" title: "Real-time snow and terrain deformation" aliases: [deformable snow] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [desktop-gpu, unreal, unity] year_introduced: 2014 inputs: [heightfield, depth] outputs: [heightfield, normals] style: "both" dynamic: "dynamic" cost: "medium" authority: "Barre-Brisebois" url: "https://texelatlas.vercel.app/t/snow-terrain-deformation/" sources_verified_at: "2026-11-29" --- # Real-time snow and terrain deformation (Barre-Brisebois) > Game technique that renders footprints and trails by writing collider depth into a heightfield or displacement texture and displacing or tessellating the terrain from it. ## Reach for it when - characters should leave footprints in snow or sand - tire tracks in mud on a game terrain - wading through ground that stays dented - cheap trails without full simulation - terrain should dent where objects touch it ## How it works A top-down depth render of the moving colliders (feet, vehicles) relative to the ground height is made each frame around the player. Where the collider pushes below the snow surface, the snow height is lowered and the displaced volume is optionally pushed outward as a rim. The result is accumulated in a persistent displacement texture that is scrolled with the player and relaxed or blurred over time so trails slowly fill in or soften. The terrain shader samples this texture to displace tessellated vertices (or uses parallax occlusion), recompute normals and darken or compress the albedo in deformed areas. The Batman: Arkham Origins talk diced snow meshes at runtime for real geometry with shadows. ## When to use it Choose it for cheap, local and visually convincing footprints, tire tracks and wading through snow, sand or mud in games. Prefer [Material Point Method (snow)](https://texelatlas.vercel.app/t/mpm-snow.md) for physically simulated snow with fracture and piling, [Stable Fluids](https://texelatlas.vercel.app/t/stable-fluids.md) / [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) for liquids, and decals for static or distant interaction. ## Cost medium — Cheap to medium: a small render target plus tessellation or parallax in the terrain shader. Measured GPU Weight: 86.55× baseline (extreme) — 2.683 ms median / 2.7601 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 82.53× baseline (extreme) — 1.3123 ms median (2.04× faster on L4). Ampere A100 scaling: 59.9× baseline (heavy) — 1.7252 ms median (1.56× faster on A100). ## Failure modes - Texture is local to the player, so deformation vanishes or pops when scrolling - Tessellation cracks or silhouette artefacts at deformation edges without crack-free dicing - No volume conservation: displaced snow does not pile unless a rim is added explicitly - Network/replay consistency is hard because state lives in a GPU texture ## Dataflow - Inputs: heightfield, depth - Outputs: heightfield, normals - Platforms: desktop-gpu, unreal, unity ## Presets ### Snow Terrain Deformation — dynamic heightfield trench compression, displaced berms & subsurface glints (glsl-fragment; rendered 2026-11-30) ```json { "P_TRENCH_DEPTH": 0.24, "P_BERM_HEIGHT": 0.14, "P_GLINT_GAIN": 1, "P_TRAIL_SPEED": 0.9 } ``` ```glsl const float P_TRENCH_DEPTH = 0.24; // P Trench Depth [0.06, 0.42, 0.02] const float P_BERM_HEIGHT = 0.14; // P Displaced Berm [0.0, 0.30, 0.01] const float P_GLINT_GAIN = 1.0; // P Crystal Glints [0.0, 2.0, 0.05] const float P_TRAIL_SPEED = 0.9; // P Trail Speed [0.0, 2.2, 0.05] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float noise2(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } // Compute snow deformation heightfield along a curving trail + discrete boot impressions void snowField(vec2 xz, float t, float depthG, float bermG, out float h, out float compact) { // Undisturbed undulating snowdrifts float drift = 0.085 * sin(xz.x * 1.4 + xz.y * 0.9) + 0.045 * noise2(xz * 2.2) + 0.014 * noise2(xz * 8.5); // Curved S-path collider trail extending behind moving snow-sphere/boot float pathX = 0.42 * sin(xz.y * 0.85 + 0.4); float headZ = 1.1 - mod(t * 0.55, 3.2); float behindMask = smoothstep(headZ - 0.16, headZ + 0.14, xz.y); // Lateral distance to trail centerline float dLat = abs(xz.x - pathX); // Continuous sled trough + alternating left/right boot stamps float trough = exp(-pow(dLat / 0.19, 2.0)) * behindMask; float stepPhase = sin(xz.y * 6.5); float footSide = (stepPhase > 0.0) ? 0.11 : -0.11; float footDist = length(vec2(xz.x - pathX - footSide, fract(xz.y * 1.05) - 0.5) * vec2(1.0, 0.55)); float bootStamp = exp(-footDist * footDist * 28.0) * behindMask; // Volume-conserving displaced snow berm piled along outside edges of trench float berm = exp(-pow((dLat - 0.27) / 0.105, 2.0)) * behindMask; compact = clamp(trough * 0.78 + bootStamp * 0.55, 0.0, 1.0); h = drift - compact * depthG + berm * bermG; } float mapScene(vec3 p, float t, float depthG, float bermG, out float matId, out float compact) { float h; snowField(p.xz, t, depthG, bermG, h, compact); float dSnow = (p.y - h) * 0.72; matId = 1.0; // Moving collider sphere carving the snow trail in real time float headZ = 1.1 - mod(t * 0.55, 3.2); float headX = 0.42 * sin(headZ * 0.85 + 0.4); float dBall = length(p - vec3(headX, 0.06, headZ)) - 0.19; if (dBall < dSnow) { matId = 2.0; return dBall; } return dSnow; } vec3 calcNormal(vec3 p, float t, float depthG, float bermG) { vec2 e = vec2(0.004, 0.0); float m, c; return normalize(vec3( mapScene(p + e.xyy, t, depthG, bermG, m, c) - mapScene(p - e.xyy, t, depthG, bermG, m, c), mapScene(p + e.yxy, t, depthG, bermG, m, c) - mapScene(p - e.yxy, t, depthG, bermG, m, c), mapScene(p + e.yyx, t, depthG, bermG, m, c) - mapScene(p - e.yyx, t, depthG, bermG, m, c) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float depthG = clamp(P_TRENCH_DEPTH, 0.04, 0.45); float bermG = clamp(P_BERM_HEIGHT, 0.0, 0.35); float glintG = clamp(P_GLINT_GAIN, 0.0, 2.2); float t = iTime * max(P_TRAIL_SPEED, 0.0); vec3 ro = vec3(0.65, 1.38, 2.05); vec3 ta = vec3(0.0, -0.10, -0.35); vec3 fwd = normalize(ta - ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.55 + right * uv.x + up * uv.y); // Crisp alpine winter sky gradient vec3 col = mix(vec3(0.52, 0.68, 0.88), vec3(0.14, 0.28, 0.56), smoothstep(-0.15, 0.65, rd.y)); float tHit = 0.0; float matId = 0.0; float compact = 0.0; bool hit = false; for (int i = 0; i < 72; i++) { vec3 p = ro + rd * tHit; float d = mapScene(p, t, depthG, bermG, matId, compact); if (d < 0.0025) { hit = true; break; } tHit += d; if (tHit > 12.0) break; } if (hit) { vec3 p = ro + rd * tHit; vec3 n = calcNormal(p, t, depthG, bermG); vec3 lDir = normalize(vec3(0.68, 0.55, 0.45)); float diff = max(dot(n, lDir), 0.0); float wrap = max((dot(n, lDir) + 0.45) / 1.45, 0.0); vec3 hVec = normalize(lDir - rd); if (matId > 1.5) { // Matte charcoal-orange weighted test sphere carving the trench float spec = pow(max(dot(n, hVec), 0.0), 42.0); vec3 ballCol = mix(vec3(0.86, 0.34, 0.16), vec3(0.22, 0.26, 0.32), smoothstep(-0.08, 0.08, sin(p.y * 22.0))); col = ballCol * (0.22 + 0.85 * diff) + vec3(0.95) * spec * 0.48; } else { // Compacted snow absorbs warm light & shifts icy-cyan; powdery berms scatter warm sunlit SSS vec3 snowAlb = mix(vec3(0.92, 0.95, 0.99), vec3(0.56, 0.74, 0.94), compact * 0.72); vec3 skyAmb = vec3(0.26, 0.42, 0.68) * (0.5 + 0.5 * n.y); vec3 sunLit = vec3(1.18, 1.08, 0.94) * (0.65 * diff + 0.35 * wrap); // High-frequency snow crystal specular glints vec2 microCell = floor(p.xz * 48.0); float rndG = hash21(microCell); vec3 microN = normalize(n + vec3(rndG - 0.5, 0.0, hash21(microCell + 19.3) - 0.5) * 0.65); float glint = pow(max(dot(microN, hVec), 0.0), 96.0) * step(0.72, rndG) * (1.0 - compact * 0.65); col = snowAlb * (skyAmb * 0.55 + sunLit * 0.85) + vec3(1.0, 0.98, 0.92) * glint * 1.65 * glintG; // Subtle atmospheric depth mist float fog = 1.0 - exp(-tHit * tHit * 0.022); col = mix(col, vec3(0.56, 0.70, 0.86), clamp(fog, 0.0, 0.78)); } } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Dynamic surfel GI inside carved snow trenches and footprints](https://texelatlas.vercel.app/ideas/deformed-snow-surfel-gi/) ## Sources 1. [primary] Colin Barre-Brisebois Deformable Snow Rendering in Batman: Arkham Origins. GDC 2014. https://www.gdcvault.com/play/1020177/Deformable-Snow-Rendering-in-Batman (verified via http on 2026-11-29) ## Cite this entry Texel. "Real-time snow and terrain deformation." https://texelatlas.vercel.app/t/snow-terrain-deformation/ (accessed 2026-12-01). --- id: "soft-particles" title: "Soft particles (depth-fade billboards)" aliases: [depth fade, depth-blended sprites] domain: "simulation" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2007 inputs: [particles, depth] outputs: [hdr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Lorach" url: "https://texelatlas.vercel.app/t/soft-particles/" sources_verified_at: "2026-11-29" --- # Soft particles (depth-fade billboards) (Lorach) > Fade a particle sprite's opacity by how far it sits in front of the opaque scene depth, so smoke and fire blend into surfaces instead of cutting a hard line. ## Reach for it when - smoke sprites show a hard line where they hit the floor - billboard fire cuts visibly through nearby walls - particle quads need to fade out against scene geometry - want sprites to blend softly into surfaces behind them ## How it works While drawing the quad, the fragment shader samples the scene depth buffer at its screen position and converts both that depth and the particle's own fragment depth to the same linear view-space measure. The difference is the thickness of empty space between the sprite and the surface behind it. The alpha is multiplied by a saturating function of that difference divided by a fade distance, often a smoothstep or a contrast curve. Where the sprite touches geometry the difference approaches zero and alpha goes to zero, hiding the intersection seam. The effect needs the opaque depth available as a texture while writing to a colour target with depth test off or read-only, so renderers copy depth or bind the depth attachment read-only. Refinements add a near-camera fade to avoid sprites clipping the near plane, and scale the fade distance by sprite size or density. ## When to use it Choose it whenever billboard smoke, fire, dust or mist touches the ground or walls. Prefer [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) or [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md) when you need genuine thickness-based extinction and lighting, which soft particles only imitate at the edges. Prefer [Particle systems](https://texelatlas.vercel.app/t/particle-systems.md) plain rendering for effects that never meet geometry. It is a final shading step in [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md), and works with depth available from deferred or forward depth prepasses. ## Cost cheap — One depth texture fetch per particle fragment; the main cost is overdraw you already pay for and a possible depth copy. Measured GPU Weight: 27.45× baseline (heavy) — 0.851 ms median / 0.9075 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 25.74× baseline (heavy) — 0.4093 ms median (2.08× faster on L4). Ampere A100 scaling: 17.92× baseline (moderate) — 0.5162 ms median (1.65× faster on A100). ## Failure modes - Particles inside large nearby volumes fade out entirely when the fade distance is too large relative to sprite size - MSAA depth must be resolved or sampled per sample, otherwise edges show halos - Reading and writing the same depth buffer without a copy is undefined on some platforms - Only fades along the view ray, so sprite edges seen at grazing angles still intersect visibly - Near-plane clipping hard-cuts big sprites unless a camera-distance fade is added ## Engine support - godot: builtin — `BaseMaterial3D.proximity_fade_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) — Depth-based fade against opaque geometry. - threejs: official — `import { softParticles } from 'three/addons/tsl/utils/SoftParticles.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/utils/SoftParticles.js, checked 2026-12-01) - unity: official — `VFX Graph output > Use Soft Particle` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.visualeffectgraph/Documentation~/Context-OutputSharedSettings.md, checked 2026-12-01) — VFX Graph package. - unreal: builtin — `Material graph: DepthFade expression on translucent particle materials` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/utility-material-expressions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: particles, depth - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Soft Particles — hard billboard intersection clip (left) vs smooth depth-fade alpha (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FADE_DIST": 0.48, "P_SMOKE_DENS": 1.05, "P_TURB_SPEED": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_FADE_DIST = 0.48; // P Depth Fade Range [0.05, 1.2, 0.02] const float P_SMOKE_DENS = 1.05; // P Plume Opacity [0.3, 1.8, 0.05] const float P_TURB_SPEED = 0.85; // P Rise Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P Hard / Soft Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float noise2(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } float fbm(vec2 p) { float s = 0.0; float a = 0.5; for (int i = 0; i < 4; i++) { s += a * noise2(p); p = p * 2.04 + vec2(13.1, 7.7); a *= 0.5; } return s; } 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); } // Solid opaque scene: tiled floor, angled concrete wall, and central pillar intersecting smoke sprites vec2 mapOpaque(vec3 p) { vec2 res = vec2(p.y + 0.62, 1.0); // floor float dWall = sdBox(p - vec3(0.0, 0.2, -0.78), vec3(2.4, 1.2, 0.14)); if (dWall < res.x) res = vec2(dWall, 2.0); float dPillar = sdBox(p - vec3(-0.02, -0.05, 0.08), vec3(0.22, 0.72, 0.22)) - 0.02; if (dPillar < res.x) res = vec2(dPillar, 3.0); float dCrate = sdBox(p - vec3(0.68, -0.34, 0.22), vec3(0.28, 0.28, 0.28)) - 0.02; if (dCrate < res.x) res = vec2(dCrate, 3.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapOpaque(p + e.xyy).x - mapOpaque(p - e.xyy).x, mapOpaque(p + e.yxy).x - mapOpaque(p - e.yxy).x, mapOpaque(p + e.yyx).x - mapOpaque(p - e.yyx).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSoft = screenX >= split; float fadeDist = max(P_FADE_DIST, 0.02); float smokeDens = clamp(P_SMOKE_DENS, 0.2, 2.0); float tAnim = iTime * max(P_TURB_SPEED, 0.0); vec3 ro = vec3(0.0, 0.24, 2.35); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.06), -1.55)); // 1. Render opaque scene depth buffer (zScene) and lit shading float tScene = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapOpaque(ro + rd * tScene); if (h.x < 0.002) { hit = true; matId = h.y; break; } tScene += h.x; if (tScene > 9.0) break; } vec3 col = mix(vec3(0.04, 0.06, 0.10), vec3(0.11, 0.15, 0.22), smoothstep(-0.4, 0.6, uv.y)); if (hit) { vec3 p = ro + rd * tScene; vec3 n = calcNormal(p); vec3 lDir = normalize(vec3(0.52, 0.84, 0.45)); float diff = max(dot(n, lDir), 0.0); float ao = clamp(0.42 + 0.58 * mapOpaque(p + n * 0.22).x / 0.22, 0.2, 1.0); vec3 alb = vec3(0.32, 0.36, 0.42); if (matId < 1.5) { float chk = mod(floor(p.x * 2.5) + floor(p.z * 2.5), 2.0); alb = mix(vec3(0.16, 0.19, 0.24), vec3(0.28, 0.32, 0.38), chk); } else if (matId > 2.5) { alb = vec3(0.42, 0.46, 0.52); } col = alb * (0.25 + 0.85 * diff) * ao; } else { tScene = 9.0; } // 2. Composite 10 back-to-front camera-facing smoke billboard sprites that cut through the floor & pillar for (int i = 0; i < 10; i++) { float fi = float(i); float zPlane = -0.35 + fi * 0.11; float tSprite = (zPlane - ro.z) / rd.z; if (tSprite <= 0.05) continue; // Depth difference between opaque scene and particle sprite float deltaZ = tScene - tSprite; if (deltaZ <= 0.0) continue; // behind opaque geometry vec3 pHit = ro + rd * tSprite; vec2 center = vec2(-0.55 + mod(fi * 0.37, 1.18), -0.44 + mod(fi * 0.19 + tAnim * 0.16, 0.72)); float rad = 0.44 + 0.06 * sin(fi * 2.1); vec2 local = (pHit.xy - center) / rad; float r2 = dot(local, local); if (r2 >= 1.0) continue; float puffNoise = fbm(local * 2.6 + vec2(fi * 3.1, -tAnim * 0.55)); float radial = pow(max(1.0 - r2, 0.0), 1.35); float baseAlpha = clamp(radial * (0.45 + 0.95 * puffNoise) * 0.62 * smokeDens, 0.0, 0.92); // Core technique: Hard depth-test clip (left) vs Soft Particle depth fade (right) float depthFade = isSoft ? smoothstep(0.0, fadeDist, deltaZ) : 1.0; float alpha = baseAlpha * depthFade; // Subtle warm backlit smoke shading float topLit = clamp(local.y * 0.5 + 0.55 + puffNoise * 0.25, 0.0, 1.0); vec3 smokeCol = mix(vec3(0.28, 0.34, 0.44), vec3(0.98, 0.84, 0.68), topLit); // Highlight the ugly hard intersection seam on left so the failure mode is crystal clear if (!isSoft && deltaZ < 0.045) { smokeCol = mix(smokeCol, vec3(1.0, 0.42, 0.28), 0.35); } col = mix(col, smokeCol, alpha); } // Split divider float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [GPU particle systems](https://texelatlas.vercel.app/t/gpu-particle-systems.md): The instanced sprite fragment shader reads scene depth and fades alpha at intersections. - [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md): Soft-faded sprites sit inside the fog, and fog light scattering is applied on top for consistent atmosphere. ## Combination ideas - [Depth-feathered soft-particle mist emitted from PBF splash crests](https://texelatlas.vercel.app/ideas/pbf-crest-soft-particle-spray/) - [Depth-feathered soft-particle smoke wrapping live visual-hull silhouettes](https://texelatlas.vercel.app/ideas/visual-hull-soft-particle-shroud/) ## Sources 1. [primary] Tristan Lorach Soft Particles (NVIDIA SDK 10 white paper). developer.download.nvidia.com. https://developer.download.nvidia.com/whitepapers/2007/SDK10/SoftParticles_hi.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Soft particles (depth-fade billboards)." https://texelatlas.vercel.app/t/soft-particles/ (accessed 2026-12-01). --- id: "soft-step-solver" title: "Soft Step solver / substepping" aliases: [Soft Step] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cpu, webgl2, webgpu] year_introduced: 2024 inputs: [mesh] outputs: [animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Catto" url: "https://texelatlas.vercel.app/t/soft-step-solver/" sources_verified_at: "2026-11-29" --- # Soft Step solver / substepping (Catto) > Box2D v3's rigid-body solver: many small substeps with soft, spring-like constraints, and relaxation passes, replacing iteration-heavy sequential impulses. ## Reach for it when - rigid body stacks jitter and are unstable - physics joints stretch under heavy load - need robust stable game physics at fixed time step - stiff contacts cause bouncing in rigid body solver ## How it works Soft Step integrates with substeps (typically 4). In each substep it runs a soft pass: constraints are formulated as springs with a hertz and damping ratio converted into bias, mass and impulse scales, so large corrections are applied gently and stably. It integrates velocity and then position, and finishes with a relaxation pass at zero bias that removes the velocity added by the bias, followed by restitution. Solving once per substep with substepping instead of many iterations, combined with graph colouring, yields stable stacks that parallelise well. The idea follows the 'small steps beat many iterations' finding for XPBD, and Solver2D compared several solvers (PGS, soft step, TGS, NGS) on identical scenes. ## When to use it Choose it when you want robust stacking, joints and large worlds with predictable behaviour and multithreading. Prefer [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) for the simple, well-documented older approach with fewer parameters, [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) for position-based soft bodies and cloth, and [MuJoCo articulated-body dynamics with convex contacts](https://texelatlas.vercel.app/t/mujoco-articulated-dynamics.md) for articulated robots. ## Cost cheap — Cheap per substep; total cost is substeps x constraint pass plus relaxation. ## Failure modes - Soft contacts give slightly spongy penetration depth under heavy loads, so spring hertz must be tuned - More substeps raise cost linearly; too few and tall stacks wobble - Restitution needs a separate pass and is lossy at fast speeds - Large mass ratios still stretch joints ## Engine support - godot: builtin — `Project Settings > physics/jolt_physics_3d/simulation/velocity_steps and position_steps` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/jolt_physics/jolt_project_settings.cpp, checked 2026-12-01) - unreal: builtin — `Project Settings > Engine > Physics > Framerate > Substepping (PhysicsSettings.substepping and max_substeps)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/PhysicsSettings, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: animation - Platforms: cpu, webgl2, webgpu ## Lineage - extends [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) ## Sources 1. [primary] Erin Catto Solver2D. box2d.org. https://box2d.org/posts/2024/02/solver2d (verified via http on 2026-11-29) 2. [primary] Miles Macklin, Kier Storey, Michelle Lu, Pierre Terdiman, Nuttapong Chentanez, Stefan Jeschke, Matthias Müller (2019) Small steps in physics simulation. Proceedings of the 18th annual ACM SIGGRAPH/Eurographics Symposium on Computer Animation. https://doi.org/10.1145/3309486.3340247 (verified via crossref on 2026-11-29) 3. [implementation] erincatto (2024) erincatto/solver2d. https://github.com/erincatto/solver2d License: MIT. (verified via github on 2026-11-29) 4. [implementation] erincatto (2015) erincatto/box2d. https://github.com/erincatto/box2d License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Soft Step solver / substepping." https://texelatlas.vercel.app/t/soft-step-solver/ (accessed 2026-12-01). --- id: "sort-free-stochastic-splatting-msaa" title: "4× MSAA Sort-Free Stochastic Gaussian Splatting" aliases: [StochasticSplats, stochastic Gaussian splatting, order-independent 3DGS] domain: "capture" stage: "capture" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, cuda] year_introduced: 2025 inputs: [gaussians, camera-poses] outputs: [hdr-image, depth] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Kheradmand et al., 2025" url: "https://texelatlas.vercel.app/t/sort-free-stochastic-splatting-msaa/" sources_verified_at: "2026-11-30" --- # 4× MSAA Sort-Free Stochastic Gaussian Splatting (Kheradmand et al., 2025) > Replaces per-frame depth sorting in 3D Gaussian Splatting with stochastic alpha-to-coverage over 4× MSAA sub-samples, letting standard hardware depth testing resolve arbitrary overlapping splats and solid meshes without popping. ## Reach for it when - per-frame depth sorting slows down large 3d gaussian splat scenes - gaussian splats pop abruptly when rotating the camera across sort order flips - render translucent splats order-independently using hardware msaa - combine dynamic gaussian splats with opaque triangle meshes without custom sorting - eliminate radix sort compute overhead in lightweight web or vr splat viewers ## How it works Conventional 3D Gaussian Splatting requires a global back-to-front radix sort whenever the camera moves, which stalls frame pacing on large scenes, breaks when Gaussians interpenetrate, and makes compositing with opaque triangle meshes awkward. Sort-free stochastic splatting reformulates alpha blending as an unbiased Monte Carlo estimator executed directly inside the rasterizer. Each splat quad evaluates its analytic Gaussian opacity `alpha` at the fragment center and tests it independently against four decorrelated random thresholds—one per **4× MSAA** sub-pixel sample—setting a 4-bit `sample_mask` output. Surviving sub-samples write opaque color and exact per-fragment depth to the hardware depth buffer, so closer splats naturally occlude farther ones without any sorting pass. Hardware MSAA resolve then averages the four stochastic realizations per pixel. Because visibility is handled by the standard Z-buffer, multiple splat clouds, dynamic rigid bodies, and opaque meshes interleave seamlessly, and view-rotation popping artifacts from approximate per-splat sort keys disappear. The trade-off is high-frequency Monte Carlo stipple noise in semi-transparent regions, which is either resolved across frames via temporal accumulation or cleaned up by a lightweight post-process denoiser. ## When to use it Choose it when rendering large or multi-object 3DGS scenes where global depth sorting is too slow, when Gaussians interpenetrate heavily with triangle meshes, or in VR/AR stereo pipelines where view-dependent sorting causes popping between eyes. Prefer [gaussian-splatting-3dgs](gaussian-splatting-3dgs) when you have a single static cloud and need noise-free single-frame output without a denoiser. Prefer [stopthepop](stopthepop) when you want deterministic per-pixel sorting without stochastic stipple. Prefer [3d-gaussian-ray-tracing](3d-gaussian-ray-tracing) when you require secondary rays, reflections, or arbitrary camera distortion. ## Cost medium — Eliminates CPU/GPU radix-sort overhead entirely, trading it for 4× MSAA color/depth bandwidth and an optional temporal or neural denoising pass. ## Failure modes - Visible stochastic stipple noise in semi-transparent edges and wispy volumes when viewed without temporal or neural denoising - High overdraw still stresses ROP bandwidth when many large low-opacity splats overlap the same screen region - Hardware early-Z rejection is disabled on fragments that write custom coverage masks or modified depth - Requires MSAA sample-mask output support, which can be expensive on tile-based mobile GPUs ## Dataflow - Inputs: gaussians, camera-poses - Outputs: hdr-image, depth - Platforms: webgpu, webgl2, desktop-gpu, cuda ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Combines with - [Lightweight WGSL Temporal-Spatial Neural Denoiser for Stochastic Splatting](https://texelatlas.vercel.app/t/temporal-spatial-neural-splat-denoising.md): Reconstructs clean, temporally stable images from the noisy 4× MSAA stochastic splat coverage output. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Integrates randomized sub-pixel coverage masks across jittered frames when a dedicated neural denoiser is unavailable. ## Combination ideas - [Sort-free neural-denoised LOD Gaussian splats](https://texelatlas.vercel.app/ideas/stochastic-lod-neural-splats/) ## Sources 1. [primary] Shakiba Kheradmand, Delio Vicini, George Kopanas, Dmitry Lagun, Kwang Moo Yi, Mark Matthews, Andrea Tagliasacchi (2025) StochasticSplats: Stochastic Rasterization for Sorting-Free 3D Gaussian Splatting. 2025 IEEE/CVF International Conference on Computer Vision (ICCV). https://doi.org/10.1109/iccv51701.2025.02443 (verified via crossref on 2026-11-30) 2. [implementation] WilliamLiu-1997 (2026) WilliamLiu-1997/Gaussian-Splat-Lite. https://github.com/WilliamLiu-1997/Gaussian-Splat-Lite License: Apache-2.0. (verified via github on 2026-11-30) ## Cite this entry Texel. "4× MSAA Sort-Free Stochastic Gaussian Splatting." https://texelatlas.vercel.app/t/sort-free-stochastic-splatting-msaa/ (accessed 2026-12-01). --- id: "space-colonization-trees" title: "Space Colonization Tree Modeling" aliases: [space colonization algorithm, venation-inspired branching] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, webgl2, blender, houdini, unity, unreal, godot, python] year_introduced: 2007 inputs: [point-cloud] outputs: [graph, curves, mesh] style: "both" dynamic: "static" cost: "cheap" authority: "Runions et al., 2007" url: "https://texelatlas.vercel.app/t/space-colonization-trees/" sources_verified_at: "2026-11-29" --- # Space Colonization Tree Modeling (Runions et al., 2007) > Grow a branching skeleton by scattering attractor points in a crown volume. Each branch tip grows toward the average direction of the attractors that choose it, and attractors are deleted when reached. ## Reach for it when - need trees whose crown fits a given silhouette - procedural branches look rigid or repetitive - grow roots, veins or lightning bolts procedurally - want bushes shaped by a volume ## How it works Start with a root node and a cloud of attractor points filling the intended crown volume or shape. In each iteration, every attractor finds its nearest branch node within an influence radius. Nodes that were chosen by at least one attractor grow a new child node in the normalised mean direction toward their attractors. Attractors closer than a kill distance to any node are removed. The loop ends when no attractors remain or no node grows. Competition for space emerges naturally: nodes near each other share attractors, giving self-pruning, gaps and natural-looking crowns. Branch thickness is computed afterwards from the leaf count or pipe model (radius from child radii), and the skeleton is skinned into a mesh. Shape control comes from where attractors are placed; the same algorithm models leaf venation. ## When to use it Choose it for trees and bushes where the silhouette matters, shaping crowns to a volume, and for roots, veins or lightning. Prefer [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) when you need developmental semantics or perfect repetition, and [Interactive Climbing Plant Modeling](https://texelatlas.vercel.app/t/climbing-plants-simulation.md) when growth should follow a surface. ## Cost cheap — Nearest-neighbour search per attractor per iteration; thousands of attractors run interactively with a spatial hash. Measured GPU Weight: 18.71× baseline (moderate) — 0.6155 ms median / 0.6487 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 15.47× baseline (moderate) — 0.2459 ms median (2.5× faster on L4). Ampere A100 scaling: 11.99× baseline (moderate) — 0.3453 ms median (1.78× faster on A100). ## Failure modes - Influence radius too small leaves attractors unreached and branches stall; too large causes straight, bundled branches - Branches may pass through each other or the trunk because no collision test exists - Raw skeleton is jagged; meshing needs smoothing and thickness estimation - Crown shape is entirely determined by the attractor cloud, so poorly sampled volumes make gaps or clumps ## Dataflow - Inputs: point-cloud - Outputs: graph, curves, mesh - Platforms: cpu, webgl2, blender, houdini, unity, unreal, godot, python ## Presets ### Space Colonization Trees — crown attraction points & skeleton (left) vs pipe-model tree & foliage (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_GROWTH_PROG": 0.9, "P_CROWN_SPREAD": 1, "P_BRANCH_THICK": 1, "P_SPLIT": 0.46 } ``` ```glsl const float P_GROWTH_PROG = 0.90; // P Colonization [0.25, 1.0, 0.02] const float P_CROWN_SPREAD = 1.0; // P Crown Width [0.6, 1.4, 0.04] const float P_BRANCH_THICK = 1.0; // P Pipe Thickness [0.5, 1.6, 0.05] const float P_SPLIT = 0.46; // P Attractors / Tree [0.0, 1.0, 0.02] float sdTaperSeg(vec2 p, vec2 a, vec2 b, float rA, float rB, out float h) { vec2 pa = p - a, ba = b - a; h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h) - mix(rA, rB, h); } vec2 hash21(float x) { vec3 p = fract(vec3(x) * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yzx + 33.33); return fract((p.xx + p.yz) * p.zy); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isAttractorVis = screenX < split; float prog = clamp(P_GROWTH_PROG, 0.2, 1.0); float spread = clamp(P_CROWN_SPREAD, 0.5, 1.5); float thick = clamp(P_BRANCH_THICK, 0.4, 1.8); // Twilight botanical backdrop vec3 col = mix(vec3(0.032, 0.044, 0.068), vec3(0.088, 0.125, 0.185), smoothstep(-0.48, 0.52, uv.y)); // Subtle soil ground line if (uv.y < -0.38) { col = mix(vec3(0.09, 0.12, 0.08), vec3(0.04, 0.06, 0.05), smoothstep(-0.38, -0.50, uv.y)); } // Crown envelope bounding ellipse (guides space colonization attraction cloud) vec2 crownCenter = vec2(0.0, 0.12); vec2 crownRad = vec2(0.42 * spread, 0.30); float dCrown = length((uv - crownCenter) / crownRad) - 1.0; if (isAttractorVis) { col += vec3(0.14, 0.56, 0.72) * exp(-abs(dCrown) * 32.0) * 0.35; } // Animated wind sway float wind = sin(iTime * 1.15) * 0.018; // Compute space-colonization branching tree skeleton (trunk -> 3 primary boughs -> 9 secondary -> 18 twigs) float minTreeD = 1e5; float branchAge = 0.0; float hTmp; vec2 pRoot = vec2(0.0, -0.40); vec2 pFork = vec2(wind * 0.4, -0.10); float dTrunk = sdTaperSeg(uv, pRoot, pFork, 0.036 * thick, 0.025 * thick, hTmp); if (dTrunk < minTreeD) { minTreeD = dTrunk; branchAge = 0.1; } // 3 main boughs growing into left, center, and right crown zones for (int i = 0; i < 3; i++) { float fi = float(i) - 1.0; vec2 b1 = pFork + vec2((fi * 0.24 * spread) + wind * 0.9, 0.19 + (1.0 - abs(fi)) * 0.07); vec2 b1Grow = mix(pFork, b1, clamp(prog * 1.6, 0.0, 1.0)); float dB1 = sdTaperSeg(uv, pFork, b1Grow, 0.021 * thick, 0.013 * thick, hTmp); if (dB1 < minTreeD) { minTreeD = dB1; branchAge = 0.35; } // 3 secondary branches per main bough pulled toward crown attractor sectors if (prog > 0.38) { float p2 = clamp((prog - 0.38) / 0.35, 0.0, 1.0); for (int j = 0; j < 3; j++) { float fj = float(j) - 1.0; vec2 angOff = vec2((fi * 0.11 + fj * 0.13) * spread + wind * 1.5, 0.15 + (1.0 - abs(fj)) * 0.06); vec2 b2 = b1 + angOff; vec2 b2Grow = mix(b1, b2, p2); float dB2 = sdTaperSeg(uv, b1, b2Grow, 0.012 * thick, 0.0065 * thick, hTmp); if (dB2 < minTreeD) { minTreeD = dB2; branchAge = 0.65; } // 2 fine terminal twigs reaching remaining attractors if (prog > 0.66) { float p3 = clamp((prog - 0.66) / 0.34, 0.0, 1.0); for (int k = 0; k < 2; k++) { float fk = (float(k) - 0.5) * 2.0; vec2 b3 = b2 + vec2((fk * 0.075 + fj * 0.03) * spread + wind * 2.0, 0.085 + 0.02 * cos(fi + fj)); vec2 b3Grow = mix(b2, b3, p3); float dB3 = sdTaperSeg(uv, b2, b3Grow, 0.0055 * thick, 0.0022 * thick, hTmp); if (dB3 < minTreeD) { minTreeD = dB3; branchAge = 0.92; } // Soft foliage cluster on right side around colonized twig tips! if (!isAttractorVis) { float dLeaf = length(uv - b3Grow); float leafMask = smoothstep(0.085 * p3, 0.018, dLeaf); vec3 leafCol = mix(vec3(0.14, 0.48, 0.22), vec3(0.56, 0.80, 0.24), 0.5 + 0.5 * sin(fi * 2.1 + fj * 3.7 + fk)); // Sunlight gradient on canopy top leafCol *= (0.68 + 0.48 * smoothstep(-0.05, 0.38, uv.y)); col = mix(col, leafCol, leafMask * 0.78); } } } } } } // Draw woody bark skeleton (left: glowing vector-growth skeleton; right: shaded bark) float barkMask = smoothstep(0.004, -0.002, minTreeD); vec3 barkCol = isAttractorVis ? mix(vec3(0.96, 0.72, 0.28), vec3(0.28, 0.95, 0.86), branchAge) : mix(vec3(0.32, 0.22, 0.15), vec3(0.48, 0.36, 0.24), branchAge); col = mix(col, barkCol, barkMask); // On left side, scatter 28 crown attraction points (glowing cyan dots that vanish once colonized!) if (isAttractorVis) { for (int a = 0; a < 28; a++) { vec2 r = hash21(float(a) * 13.7 + 4.1); float ang = r.x * 6.2831853; float rad = sqrt(r.y); vec2 pt = crownCenter + vec2(cos(ang) * crownRad.x, sin(ang) * crownRad.y) * rad * 0.95; float dPt = length(uv - pt); // Outer attractors remain active (bright cyan); inner ones show dim colonized rings float isActive = smoothstep(0.35 * prog, 0.92 * prog, rad); vec3 ptCol = mix(vec3(0.22, 0.36, 0.48), vec3(0.20, 0.95, 1.0), isActive); col += ptCol * exp(-dPt * 95.0) * (0.45 + 0.85 * isActive); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md): Blue-noise attractor points give evenly spread attractors inside the crown volume. ## Combination ideas - [Forests that grow into the gaps](https://texelatlas.vercel.app/ideas/eroded-biome-forests/) - [Trees grown into a described shape](https://texelatlas.vercel.app/ideas/text-shaped-tree-crowns/) ## Sources 1. [primary] Adam Runions, Brendan Lane, Przemyslaw Prusinkiewicz (2007) Modeling Trees with a Space Colonization Algorithm. Eurographics Workshop on Natural Phenomena. https://doi.org/10.2312/nph/nph07/063-070 (verified via doi.org on 2026-11-29) 2. [primary] Adam Runions, Brendan Lane, Przemyslaw Prusinkiewicz Modeling Trees with a Space Colonization Algorithm. algorithmicbotany.org. https://algorithmicbotany.org/papers/colonization.egwnp2007.html (verified via http on 2026-11-29) 3. [implementation] dgreenheck (2024) dgreenheck/ez-tree. https://github.com/dgreenheck/ez-tree License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Space Colonization Tree Modeling." https://texelatlas.vercel.app/t/space-colonization-trees/ (accessed 2026-12-01). --- id: "spectral-upsampling-sigmoid" title: "Spectral upsampling with sigmoid polynomials" domain: "post" stage: "post" realtime: "offline" platforms: [cpu, python, cuda] year_introduced: 2019 inputs: [ldr-image, texture] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "offline" authority: "Jakob & Hanika, 2019" url: "https://texelatlas.vercel.app/t/spectral-upsampling-sigmoid/" sources_verified_at: "2026-11-29" --- # Spectral upsampling with sigmoid polynomials (Jakob & Hanika, 2019) > Maps any RGB colour to a smooth reflectance spectrum by fitting a sigmoid of a quadratic polynomial, stored in a 3D coefficient table. Lets spectral renderers accept ordinary RGB textures. ## Reach for it when - spectral renderer can't use my rgb textures - need to turn rgb colours into plausible spectra - rgb to spectrum and back must round trip - metamerism and colour accuracy in a spectral path tracer - smooth reflectance curves from three numbers ## How it works Reflectance spectra must be smooth and bounded between 0 and 1. Jakob and Hanika model a spectrum as s(lambda) = sigmoid(c0 lambda^2 + c1 lambda + c2). For each RGB colour in the gamut, an offline optimisation finds the three coefficients that make the spectrum, when integrated against the colour matching functions and illuminant, reproduce the colour, and the solution is continuous across the gamut. The coefficients are tabulated on a 3D grid parametrised by the largest channel and the other two, with a nonlinear scale for resolution near the gamut boundary. At render time a texture's RGB is looked up with trilinear interpolation, and a spectrum is evaluated at the sampled wavelength with two multiply-adds and a sigmoid. White maps exactly to a flat spectrum. ## When to use it Choose it when a spectral path tracer must ingest RGB assets with plausible metamerism, or when you need round-trip RGB to spectrum to RGB conversions. Prefer plain RGB rendering when materials are not spectrally sensitive. Prefer measured spectra for scientific accuracy. It pairs with [Film emulation (spectral stock simulation)](https://texelatlas.vercel.app/t/film-emulation.md) pipelines that start from spectral data. ## Cost offline — Table fit is offline, runtime is a table lookup plus a polynomial and sigmoid per wavelength. Measured GPU Weight: 4.77× baseline (light) — 0.1569 ms median / 0.1625 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 4.03× baseline (light) — 0.0641 ms median (2.45× faster on L4). Ampere A100 scaling: 3.35× baseline (light) — 0.0965 ms median (1.63× faster on A100). ## Failure modes - Illuminant-dependent: the same RGB reflects differently under unusual lights and the spectra are not unique - Cannot represent spectra with sharp features such as fluorescent or iridescent materials - Table must be fitted per colour space and illuminant - Out-of-gamut colours need clamping ## Dataflow - Inputs: ldr-image, texture - Outputs: radiance - Platforms: cpu, python, cuda ## Presets ### Spectral Upsampling with Sigmoid Polynomials — RGB multiply (left) vs Jakob-Hanika quadratic sigmoid spectral bounce & scope (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ILLUM_TEMP": 0.55, "P_SATURATION": 0.85, "P_SCOPE_GAIN": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_ILLUM_TEMP = 0.55; // P Illuminant Shift [0.0, 1.0, 0.02] const float P_SATURATION = 0.85; // P Albedo Chroma [0.2, 1.0, 0.02] const float P_SCOPE_GAIN = 0.75; // P Spectrum Scope [0.0, 1.0, 0.05] const float P_SPLIT = 0.48; // P RGB / Spectral [0.0, 1.0, 0.02] // Jakob & Hanika 2019 sigmoid basis: s(x) = 0.5 + x / (2 * sqrt(1 + x^2)) float sigPoly(float lam, vec3 coeff) { float x = (coeff.x * lam + coeff.y) * lam + coeff.z; return 0.5 + 0.5 * x / sqrt(1.0 + x * x); } // Smooth analytic approximation of CIE 1931 RGB-like spectral sensitivities for lam in [0, 1] (380..720nm) vec3 wavelengthToRGB(float lam) { float r = exp(-pow((lam - 0.74) / 0.16, 2.0)) + 0.25 * exp(-pow((lam - 0.14) / 0.09, 2.0)); float g = exp(-pow((lam - 0.48) / 0.15, 2.0)); float b = exp(-pow((lam - 0.18) / 0.12, 2.0)); return vec3(r, g, b); } // Fit quadratic sigmoid coefficients (c0, c1, c2) that reproduce target RGB reflectance smoothly in (0, 1) vec3 rgbToSigmoidCoeff(vec3 rgb) { vec3 c = clamp(rgb, 0.02, 0.98); // Map primary balance into peak wavelength & curvature of quadratic polynomial float c0 = -10.5 * (c.g - 0.5 * (c.r + c.b)); float c1 = 9.5 * (c.r - c.b) - c0; float meanVal = (c.r + c.g + c.b) * 0.3333; float c2 = (meanVal - 0.5) * 4.2 - 0.35 * c1 - 0.22 * c0; return vec3(c0, c1, c2); } // Illuminant spectral power distribution (sweeping from sodium-amber narrowband to cool sky daylight) float evalIlluminant(float lam, float temp) { float warm = 1.45 * exp(-pow((lam - 0.68) / 0.22, 2.0)) + 0.35 * exp(-pow((lam - 0.44) / 0.14, 2.0)); float cool = 1.35 * exp(-pow((lam - 0.24) / 0.24, 2.0)) + 0.90 * exp(-pow((lam - 0.54) / 0.28, 2.0)); return mix(warm, cool, temp); } vec3 integrateSpectralBounce(vec3 alb1, vec3 alb2, float temp) { vec3 k1 = rgbToSigmoidCoeff(alb1); vec3 k2 = rgbToSigmoidCoeff(alb2); vec3 acc = vec3(0.0); vec3 normW = vec3(0.0); for (int i = 0; i < 10; i++) { float lam = (float(i) + 0.5) / 10.0; float s1 = sigPoly(lam, k1); float s2 = sigPoly(lam, k2); float ill = evalIlluminant(lam, temp); vec3 cmf = wavelengthToRGB(lam); acc += cmf * (s1 * s2 * ill); normW += cmf * ill; } return acc / max(normW, vec3(1e-4)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSpectral = screenX >= split; float temp = clamp(P_ILLUM_TEMP + 0.28 * sin(iTime * 0.55), 0.0, 1.0); float sat = clamp(P_SATURATION, 0.15, 1.0); float scopeG = clamp(P_SCOPE_GAIN, 0.0, 1.0); // Illuminant RGB equivalent for left side naive multiplication vec3 illRGB = mix(vec3(1.18, 0.72, 0.34), vec3(0.54, 0.84, 1.22), temp); vec3 col = mix(vec3(0.05, 0.06, 0.09), vec3(0.11, 0.14, 0.20), smoothstep(-0.4, 0.5, uv.y)); // Three colorful ceramic spheres demonstrating spectral vs RGB multi-bounce hue preservation vec3 ro = vec3(0.0, 0.28, 2.35); vec3 rd = normalize(vec3(uv.x, uv.y - 0.04, -1.5)); vec3 lDir = normalize(vec3(0.55, 0.78, 0.42)); vec3 centers[3]; vec3 albedos[3]; centers[0] = vec3(-0.56, 0.04, 0.0); centers[1] = vec3(0.00, 0.08, 0.05); centers[2] = vec3(0.56, 0.04, 0.0); albedos[0] = mix(vec3(0.6), vec3(0.95, 0.24, 0.36), sat); albedos[1] = mix(vec3(0.6), vec3(0.24, 0.86, 0.44), sat); albedos[2] = mix(vec3(0.6), vec3(0.22, 0.48, 0.96), sat); float tMin = 1e5; int hitId = -1; vec3 hp = vec3(0.0); vec3 hn = vec3(0.0, 1.0, 0.0); // Ground reflector plane (warm ochre bounce floor) if (rd.y < -0.005) { float tf = (-0.28 - ro.y) / rd.y; if (tf > 0.05 && tf < 12.0) { tMin = tf; hitId = 10; hp = ro + rd * tf; hn = vec3(0.0, 1.0, 0.0); } } for (int i = 0; i < 3; i++) { vec3 oc = ro - centers[i]; float b = dot(oc, rd); float d = b * b - (dot(oc, oc) - 0.28 * 0.28); if (d > 0.0) { float ts = -b - sqrt(d); if (ts > 0.05 && ts < tMin) { tMin = ts; hitId = i; hp = ro + rd * ts; hn = normalize(hp - centers[i]); } } } vec3 floorAlb = mix(vec3(0.6), vec3(0.92, 0.68, 0.22), sat * 0.85); if (hitId >= 0) { float ndl = max(dot(hn, lDir), 0.0); vec3 surfAlb = (hitId == 10) ? floorAlb : albedos[hitId]; vec3 bounceAlb = (hitId == 10) ? albedos[1] : floorAlb; float bounceMask = (hitId == 10) ? smoothstep(0.95, 0.20, length(hp.xz)) : max(-hn.y * 0.85 + 0.25, 0.0); vec3 directC; vec3 bounceC; if (isSpectral) { // Spectral integration of sigmoid polynomial reflectance * illuminant directC = integrateSpectralBounce(surfAlb, vec3(0.96), temp) * 1.35; bounceC = integrateSpectralBounce(surfAlb, bounceAlb, temp) * 0.95; } else { // Naive RGB tristimulus componentwise multiplication (loses metamerism & shifts secondary bounce hues) directC = surfAlb * illRGB * 1.15; bounceC = surfAlb * bounceAlb * illRGB * 0.95; } float spec = (hitId == 10) ? 0.0 : pow(max(dot(reflect(-lDir, hn), -rd), 0.0), 36.0) * 0.65; col = directC * (0.22 + 0.95 * ndl) + bounceC * bounceMask * 0.72 + illRGB * spec; if (hitId == 10) col = mix(vec3(0.05, 0.06, 0.09), col, exp(-tMin * 0.14)); } // Bottom live spectral curve oscilloscope showing s(lambda) = sigmoid(c0*l^2 + c1*l + c2) across 380-720 nm vec2 suv = fragCoord / max(iResolution.xy, vec2(1.0)); if (suv.y < 0.24 && scopeG > 0.01) { float lam = clamp((suv.x - 0.06) / 0.88, 0.0, 1.0); float yLocal = clamp((suv.y - 0.03) / 0.18, 0.0, 1.0); vec3 panel = vec3(0.04, 0.05, 0.08); // Faint wavelength rainbow baseline vec3 rainbow = normalize(wavelengthToRGB(lam) + vec3(0.05)) * 0.25; panel += rainbow * smoothstep(0.18, 0.0, yLocal); // Plot the three smooth quadratic sigmoid spectra for the three spheres for (int k = 0; k < 3; k++) { float sVal = sigPoly(lam, rgbToSigmoidCoeff(albedos[k])); float line = smoothstep(0.038, 0.008, abs(yLocal - sVal)); panel = mix(panel, albedos[k] * 1.45, line); } // Plot current illuminant SPD dashed curve float illV = clamp(evalIlluminant(lam, temp) * 0.55, 0.0, 0.98); float illLine = smoothstep(0.024, 0.006, abs(yLocal - illV)) * step(0.4, fract(suv.x * 48.0)); panel = mix(panel, vec3(0.95, 0.96, 1.0), illLine * 0.85); col = mix(col, panel, scopeG * 0.90); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Film emulation (spectral stock simulation)](https://texelatlas.vercel.app/t/film-emulation.md) ## Combines with - [Film emulation (spectral stock simulation)](https://texelatlas.vercel.app/t/film-emulation.md): Spectral reconstruction of RGB feeds spectral film models. ## Combination ideas - [Film stocks exposed by spectra](https://texelatlas.vercel.app/ideas/spectral-film-for-renders/) ## Sources 1. [primary] Wenzel Jakob, Johannes Hanika (2019) A Low‐Dimensional Function Space for Efficient Spectral Upsampling. Computer Graphics Forum. https://doi.org/10.1111/cgf.13626 (verified via crossref on 2026-11-29) 2. [implementation] mitsuba-renderer (2018) mitsuba-renderer/rgb2spec. https://github.com/mitsuba-renderer/rgb2spec License: BSD-3-Clause. (verified via github on 2026-11-29) 3. [implementation] mitsuba-renderer (2021) mitsuba-renderer/mitsuba3. https://github.com/mitsuba-renderer/mitsuba3 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Spectral upsampling with sigmoid polynomials." https://texelatlas.vercel.app/t/spectral-upsampling-sigmoid/ (accessed 2026-12-01). --- id: "sph-fluids" title: "Smoothed Particle Hydrodynamics (fluids)" aliases: [SPH] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu] year_introduced: 1992 inputs: [particles] outputs: [particles] style: "both" dynamic: "dynamic" cost: "heavy" authority: "Monaghan, 1992" url: "https://texelatlas.vercel.app/t/sph-fluids/" sources_verified_at: "2026-11-29" --- # Smoothed Particle Hydrodynamics (fluids) (Monaghan, 1992) > Meshless Lagrangian fluid method: each particle's density, pressure and viscosity forces come from kernel-weighted sums over neighbouring particles. ## Reach for it when - particle based water simulation for games - splashing liquid with free surface and no grid - fluid interacts with moving objects naturally - simulate honey or water as particles ## How it works Fields are interpolated with a smoothing kernel `W(r,h)`: density is `sum_j m_j W(|x_i-x_j|,h)`, pressure force and viscosity force are kernel gradients/Laplacians of those quantities. Pressure comes from an equation of state (weakly-compressible SPH, stiff and needing tiny steps) or from a pressure solve (PCISPH, IISPH, DFSPH), which allow much larger steps. Neighbours are found with a uniform grid or spatial hash and sorted for coherence on the GPU. Interactive-graphics SPH popularised specialised kernels (poly6 for density, spiky for pressure, viscosity kernel for the Laplacian) to avoid clumping. Surface tension and boundaries are extra particle forces or boundary particles. ## When to use it Choose it when you want a simple, meshless liquid with free surfaces, easy two-way rigid coupling and multiphase support. Prefer [Position Based Fluids](https://texelatlas.vercel.app/t/position-based-fluids.md) for faster, more game-oriented stability, [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) for large-scale splashes with less particle-pairing noise, and [Lattice Boltzmann fluids](https://texelatlas.vercel.app/t/lattice-boltzmann-fluids.md) when a regular grid and straightforward parallelism matter more than free surfaces. ## Cost heavy — Neighbour search dominates; cost grows linearly with particles x neighbours (about 30-60 each). Measured GPU Weight: 20.38× baseline (heavy) — 0.64 ms median / 0.6561 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.99× baseline (moderate) — 0.2842 ms median (2.25× faster on L4). Ampere A100 scaling: 12.17× baseline (moderate) — 0.3504 ms median (1.83× faster on A100). ## Failure modes - Tensile instability: particles clump or pair when pressure goes negative - Weakly-compressible variants force very small time steps, or fluid visibly compresses - Particle deficiency at free surface and boundaries gives density and pressure errors - Lots of particles (millions) needed for visually smooth surfaces; surface reconstruction adds cost and bumpiness ## Engine support - blender: builtin — `Particle Properties > Physics > Fluid` (evidence: https://docs.blender.org/manual/en/5.2/physics/particles/emitter/physics/fluid.html, checked 2026-12-01) ## Dataflow - Inputs: particles - Outputs: particles - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu ## Presets ### Smoothed Particle Hydrodynamics — Poly6 density kernel, Tait pressure heatmap & kernel support rings (glsl-fragment; rendered 2026-11-30) ```json { "P_KERNEL_H": 0.19, "P_SLOSH_SPEED": 1, "P_PRESSURE_VIS": 0.78, "P_SURFACE_ISO": 1 } ``` ```glsl const float P_KERNEL_H = 0.19; // P Kernel Radius h [0.11, 0.30, 0.01] const float P_SLOSH_SPEED = 1.0; // P Slosh Speed [0.0, 2.5, 0.05] const float P_PRESSURE_VIS = 0.78; // P Pressure Map [0.0, 1.5, 0.04] const float P_SURFACE_ISO = 1.0; // P Fluid Threshold [0.5, 1.8, 0.04] vec2 hash21(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } // Poly6 SPH smoothing kernel W(r, h) ~ (1 - (r/h)^2)^3 for r < h float poly6(float r, float h) { float q = r / max(h, 1e-4); if (q >= 1.0) return 0.0; float t = 1.0 - q * q; return t * t * t; } // Sloshing SPH particle trajectory inside rectangular tank x in [-0.62, 0.62], y in [-0.36, 0.36] vec2 particlePos(int idx, float t) { float fi = float(idx); float colIdx = mod(fi, 7.0); float rowIdx = floor(fi / 7.0); vec2 h = hash21(fi * 11.7 + 4.2); // Sloshing basin wave mode + convective circulation roll float baseX = (colIdx - 3.0) * 0.172 + 0.05 * sin(t * 1.45 + rowIdx * 0.9 + h.x * 6.28); float slosh = 0.12 * sin(t * 1.35) * (baseX / 0.55); float splash = 0.055 * sin(t * 2.2 + colIdx * 1.15 + h.y * 6.28) * (rowIdx / 3.0); float baseY = -0.28 + rowIdx * 0.115 + slosh + splash; // Hydrostatic swirl eddy near basin center float eddyAng = t * 0.95 + fi * 0.7; vec2 swirl = vec2(cos(eddyAng), sin(eddyAng)) * (0.025 + 0.02 * h.x); vec2 p = vec2(baseX, baseY) + swirl; p.x = clamp(p.x, -0.58, 0.58); p.y = clamp(p.y, -0.32, 0.32); return p; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float tAnim = iTime * max(P_SLOSH_SPEED, 0.0); float hRad = clamp(P_KERNEL_H, 0.10, 0.34); float presVis = clamp(P_PRESSURE_VIS, 0.0, 1.5); float isoThr = clamp(P_SURFACE_ISO, 0.4, 2.0) * 0.58; // Evaluate SPH density rho(uv) and kernel gradient grad(rho) across 28 fluid particles float rho = 0.0; vec2 gradRho = vec2(0.0); float minDist = 1e5; float ringVis = 0.0; for (int i = 0; i < 28; i++) { vec2 pi = particlePos(i, tAnim); vec2 d = uv - pi; float r = length(d); minDist = min(minDist, r); float w = poly6(r, hRad); rho += w; if (r < hRad && r > 1e-4) { float q = r / hRad; float dw = -6.0 * (1.0 - q * q) * (1.0 - q * q) * q / hRad; gradRho += (d / r) * dw; } // Show kernel support radius h on 3 highlighted probe particles if (i == 10 || i == 17 || i == 23) { ringVis = max(ringVis, smoothstep(px * 3.0, px * 0.6, abs(r - hRad))); } } // Dark lab chamber backdrop + subtle tank grid vec3 col = mix(vec3(0.025, 0.036, 0.058), vec3(0.055, 0.080, 0.125), smoothstep(-0.5, 0.5, uv.y)); vec2 g = abs(fract(uv * 12.0 - 0.5) - 0.5); col += vec3(0.015, 0.025, 0.042) * smoothstep(0.035, 0.005, min(g.x, g.y)); // Tank interior bounds vec2 tankD = abs(uv) - vec2(0.64, 0.38); float dTank = length(max(tankD, 0.0)) + min(max(tankD.x, tankD.y), 0.0); if (dTank < 0.0) { col = mix(col, vec3(0.04, 0.06, 0.10), 0.5); } // Tait equation of state pressure: p = k * ((rho / rho0)^gamma - 1) float rhoNorm = rho / max(isoThr, 0.1); float pressure = max(pow(max(rhoNorm, 0.0), 2.4) - 1.0, 0.0); // Fluid surface extraction where density exceeds isosurface threshold float fluidMask = smoothstep(isoThr * 0.86, isoThr * 1.06, rho) * step(dTank, 0.0); if (fluidMask > 0.005) { // Reconstruct pseudo-3D fluid surface normal from density gradient vec3 n = normalize(vec3(-gradRho.x * 0.18, -gradRho.y * 0.18, 1.0)); vec3 lDir = normalize(vec3(0.45, 0.78, 0.68)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir + vec3(0.0, 0.0, 1.0))), 0.0), 48.0); // Rich deep-water blue -> high-pressure cyan/emerald/amber core vec3 waterCol = mix(vec3(0.05, 0.34, 0.68), vec3(0.12, 0.78, 0.88), clamp(rhoNorm * 0.45, 0.0, 1.0)); vec3 pressCol = mix(waterCol, vec3(0.98, 0.66, 0.18), clamp(pressure * 0.28 * presVis, 0.0, 0.92)); // Crisp specular foam rim along free surface (low density boundary) float foam = smoothstep(isoThr * 1.45, isoThr * 0.92, rho); vec3 shaded = pressCol * (0.36 + 0.74 * diff) + vec3(0.92, 0.98, 1.0) * (spec * 0.85 + foam * 0.42); col = mix(col, shaded, fluidMask); } // Render crisp SPH particle centers & smoothing kernel support radius rings float pCore = smoothstep(0.017, 0.007, minDist); col = mix(col, vec3(0.92, 0.98, 1.0), pCore * 0.72); col += vec3(1.0, 0.86, 0.34) * ringVis * 0.68; // Glass tank border col = mix(col, vec3(0.68, 0.84, 0.98), smoothstep(0.009, 0.002, abs(dTank)) * 0.85); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [Ihmsen Unified Spray, Foam, and Bubble Whitewater Simulation](https://texelatlas.vercel.app/t/ihmsen-unified-whitewater.md) ## Sources 1. [primary] J. J. Monaghan (1992) Smoothed Particle Hydrodynamics. Annual Review of Astronomy and Astrophysics. https://doi.org/10.1146/annurev.aa.30.090192.002551 (verified via crossref on 2026-11-29) 2. [implementation] InteractiveComputerGraphics (2016) InteractiveComputerGraphics/SPlisHSPlasH. https://github.com/InteractiveComputerGraphics/SPlisHSPlasH License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Smoothed Particle Hydrodynamics (fluids)." https://texelatlas.vercel.app/t/sph-fluids/ (accessed 2026-12-01). --- id: "sphere-tracing" title: "Sphere Tracing" aliases: [ray marching, raymarching] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cuda, cpu] year_introduced: 1996 inputs: [sdf] outputs: [depth, normals] style: "both" dynamic: "dynamic" cost: "medium" authority: "Hart, 1996" url: "https://texelatlas.vercel.app/t/sphere-tracing/" sources_verified_at: "2026-11-29" --- # Sphere Tracing (Hart, 1996) > Renders an implicit surface by marching a ray forward by the distance-field value at each point, which is by definition a safe step that cannot cross the surface. Converges quickly in open space. ## Reach for it when - want to render an implicit surface in a shader - need to ray march distance field scenes - demoscene-style procedural scenes without triangles - intersect a signed distance function safely ## How it works Given a ray origin and direction, evaluate the signed distance d at the current point. Because d is a lower bound on the distance to the nearest surface, a sphere of radius d around the point contains no surface, so advancing by d is safe. Repeat until d falls below an epsilon proportional to the distance travelled (hit) or the ray exceeds a maximum range or step count (miss). Normals are the field gradient at the hit; soft shadows and ambient occlusion fall out of the same field cheaply by tracking the closest approach along secondary rays. The method requires the function to be 1-Lipschitz; functions that overestimate distance (twist, scale, domain warp) cause overstepping, usually mitigated by a step scale factor. ## When to use it Choose it for shader-based rendering of procedural or analytic SDF scenes (demoscene, Shadertoy-style, editors). Prefer [Enhanced Sphere Tracing](https://texelatlas.vercel.app/t/enhanced-sphere-tracing.md) when you hit grazing-angle slowness or need fewer iterations, [Segment Tracing](https://texelatlas.vercel.app/t/segment-tracing.md) for non-Euclidean or warped fields with local Lipschitz bounds, and rasterising a mesh from [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) when the scene is static and complex. ## Cost medium — Dozens of field evaluations per pixel; cost scales with scene complexity and with grazing rays that take many small steps. Measured GPU Weight: 12.5× baseline (moderate) — 0.4111 ms median / 0.4269 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.03× baseline (moderate) — 0.1594 ms median (2.58× faster on L4). Ampere A100 scaling: 7.23× baseline (moderate) — 0.2081 ms median (1.98× faster on A100). ## Failure modes - Many tiny steps along rays grazing a surface produce slow pixels and banding in step counts - Overstepping with non-Lipschitz fields shows as holes and thin sliver gaps near silhouettes - Fixed epsilon creates visible self-intersection or staircase at far distance; scale epsilon by distance - Thin objects can be missed if a step jumps across them due to bounding approximations - Step limit exhaustion produces noisy bright or dark outlines ## Engine support - godot: builtin — `Environment.sdfgi_enabled = true (sdfgi_direct_light.glsl sphere-traces 3D SDF cascades by advancing by sampled SDF distance)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/servers/rendering/renderer_rd/shaders/environment/sdfgi_direct_light.glsl, checked 2026-12-01) ## Dataflow - Inputs: sdf - Outputs: depth, normals - Platforms: webgl2, webgpu, desktop-gpu, cuda, cpu ## Presets ### Sphere tracing an SDF scene: shaded half and step-count heat half (glsl-fragment; rendered 2026-11-29) ```json { "MAX_STEPS": 64, "EPS": 0.001 } ``` ```glsl // Sphere tracing of an SDF scene: left half shaded, right half shows the step count per pixel. const int MAX_STEPS = 64; const float EPS = 0.001; float map(vec3 p) { float s = length(p - vec3(-0.9, 0.0, 0.0)) - 0.8; vec2 q = vec2(length(p.xz - vec2(1.0, 0.2)) - 0.8, p.y); float t = length(q) - 0.25; float b = length(max(abs(p - vec3(0.0, -0.9, 0.0)) - vec3(4.0, 0.05, 4.0), 0.0)) - 0.02; return min(min(s, t), b); } vec3 calcN(vec3 p) { vec2 e = vec2(0.001, 0.0); return normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx))); } vec3 heat(float x) { return clamp(vec3(1.5 * x, 1.5 - abs(3.0 * x - 1.5), 1.5 - 1.5 * x) * vec3(1.0, 1.0, 1.0), 0.0, 1.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 1.0, -4.0), rd = normalize(vec3(uv.x, uv.y - 0.12, 1.4)); float t = 0.0; int n = 0; bool hit = false; for (int i = 0; i < MAX_STEPS; i++) { n = i; float d = map(ro + rd * t); if (d < EPS) { hit = true; break; } t += d; if (t > 20.0) break; } vec3 col = mix(vec3(0.12, 0.14, 0.2), vec3(0.03, 0.04, 0.07), uv.y + 0.5); if (hit) { vec3 p = ro + rd * t, nor = calcN(p); vec3 l = normalize(vec3(-0.5, 0.8, -0.4)); float dif = max(dot(nor, l), 0.0); float chk = mod(floor(p.x * 2.0) + floor(p.z * 2.0), 2.0); vec3 alb = p.y < -0.85 ? vec3(0.3 + 0.3 * chk) : vec3(0.85, 0.6, 0.4); col = alb * (0.15 + 0.9 * dif); } if (uv.x > 0.0) col = mix(col * 0.25, heat(float(n) / float(MAX_STEPS)), 0.9); col = mix(col, vec3(1.0), smoothstep(0.003, 0.0, abs(uv.x))); fragColor = vec4(pow(col, vec3(0.45)), 1.0); } ``` Attribution: written for this index ### SDF sphere tracing with soft shadows (WGSL) (webgpu-wgsl; WebGPU WGSL runtime) ```json { "MAX_STEPS": 64, "SOFTNESS": 12 } ``` ```wgsl // WebGPU WGSL fragment specimen: Lipschitz sphere tracing + soft penumbra shadows const MAX_STEPS: i32 = 64; // P const SOFTNESS: f32 = 12.0000; // P fn sd_scene(p: vec3f, t: f32) -> f32 { let s = length(p - vec3f(0.0, 0.18 + 0.08 * sin(t), 0.0)) - 0.56; let q = vec2f(length(p.xz) - 0.72, p.y + 0.12); let tor = length(q) - 0.16; let flr = p.y + 0.65; return min(min(s, tor), flr); } fn calc_normal(p: vec3f, t: f32) -> vec3f { let e = vec2f(0.002, -0.002); return normalize( e.xyy * sd_scene(p + e.xyy, t) + e.yyx * sd_scene(p + e.yyx, t) + e.yxy * sd_scene(p + e.yxy, t) + e.xxx * sd_scene(p + e.xxx, t) ); } fn soft_shadow(ro: vec3f, rd: vec3f, t: f32) -> f32 { var res: f32 = 1.0; var dist: f32 = 0.03; for (var i: i32 = 0; i < 24; i = i + 1) { let h = sd_scene(ro + rd * dist, t); res = min(res, SOFTNESS * h / dist); dist = dist + clamp(h, 0.02, 0.25); if (res < 0.005 || dist > 6.0) { break; } } return clamp(res, 0.0, 1.0); } @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f { let uv = (pos.xy - 0.5 * u.resolution) / u.resolution.y; let ang = u.time * 0.25; let ro = vec3f(sin(ang) * 2.4, 0.72, cos(ang) * 2.4); let fwd = normalize(-ro); let right = normalize(cross(fwd, vec3f(0.0, 1.0, 0.0))); let up = cross(right, fwd); let rd = normalize(fwd * 1.45 + right * uv.x - up * uv.y); var dist: f32 = 0.0; var hit: bool = false; for (var i: i32 = 0; i < MAX_STEPS; i = i + 1) { let d = sd_scene(ro + rd * dist, u.time); if (d < 0.0015) { hit = true; break; } dist = dist + d; if (dist > 14.0) { break; } } var col = mix(vec3f(0.84, 0.86, 0.84), vec3f(0.68, 0.72, 0.76), clamp(-uv.y + 0.5, 0.0, 1.0)); if (hit) { let p = ro + rd * dist; let n = calc_normal(p, u.time); let l = normalize(vec3f(0.65, 0.85, 0.45)); let sh = soft_shadow(p + n * 0.01, l, u.time); let nl = max(dot(n, l), 0.0); let albedo = select(vec3f(0.76, 0.74, 0.70), vec3f(0.24, 0.52, 0.44), p.y > -0.63); col = albedo * (0.22 + 0.95 * nl * sh); } return vec4f(pow(clamp(col, vec3f(0.0), vec3f(1.0)), vec3f(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Enhanced Sphere Tracing](https://texelatlas.vercel.app/t/enhanced-sphere-tracing.md) - extended by [Segment Tracing](https://texelatlas.vercel.app/t/segment-tracing.md) ## Combines with - [SDF Modeling: CSG and Smooth Minimum](https://texelatlas.vercel.app/t/sdf-csg-smooth-min.md): The CSG/smooth-min distance function is what sphere tracing steps through. ## Sources 1. [primary] John C. Hart (1996) Sphere tracing: a geometric method for the antialiased ray tracing of implicit surfaces. The Visual Computer. https://doi.org/10.1007/s003710050084 (verified via crossref on 2026-11-29) 2. [tutorial] Inigo Quilez Distance functions. iquilezles.org. https://iquilezles.org/articles/distfunctions (verified via http on 2026-11-29) 3. [implementation] Gökay Aydoğan (2026) gokayfem/glsl-studies. https://github.com/gokayfem/glsl-studies License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Sphere Tracing." https://texelatlas.vercel.app/t/sphere-tracing/ (accessed 2026-12-01). --- id: "spherical-harmonics-lighting" title: "Spherical-Harmonic Lighting (Irradiance Environment Maps)" aliases: [SH lighting, SH irradiance, L2 SH] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2001 inputs: [hdr-image] outputs: [irradiance-probes] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Ramamoorthi & Hanrahan, 2001" url: "https://texelatlas.vercel.app/t/spherical-harmonics-lighting/" sources_verified_at: "2026-11-29" --- # Spherical-Harmonic Lighting (Irradiance Environment Maps) (Ramamoorthi & Hanrahan, 2001) > Projects an environment's radiance onto nine spherical-harmonic coefficients per color channel, from which diffuse irradiance for any surface normal is evaluated with a tiny quadratic polynomial. ## Reach for it when - need cheap diffuse ambient light from a sky - environment lighting stored in a few numbers - dynamic objects need soft lighting from probes - diffuse irradiance without sampling a cubemap many times - compact baked lighting representation ## How it works Diffuse reflection is a cosine-weighted average of incoming light, and that cosine kernel is smooth. Its spectrum falls off quickly, with about 99 percent of the energy in the first three bands (order 0, 1, 2). So instead of storing a cubemap and convolving it per pixel, you project the radiance onto **spherical harmonics**: nine coefficients `L_lm` per color channel (27 floats). Projection is a one-time integral over the sphere, done by Monte Carlo sampling or by summing a cubemap with solid-angle weights. Irradiance for a normal `n` is then a quadratic form in `n`: the zeroth band contributes a constant, the first band a linear term, the second a quadratic one, with fixed band attenuation constants taken from the cosine lobe's SH coefficients. In a shader this is a dozen multiply-adds. Because the representation is linear, **blending probes or dynamic lights is just adding coefficient vectors**, and rotations are matrix operations on coefficients. Windowing (a gentle filter that reduces ringing) is a common cleanup when the source has high dynamic range. ## When to use it Choose it for diffuse ambient light from a sky or probe, for dynamic objects inside [irradiance-volumes](irradiance-volumes), and as the basis for many baked-lighting formats. Prefer [split-sum-ibl](split-sum-ibl) alongside it for the specular half of image-based lighting; SH cannot represent a sharp reflection. Prefer [precomputed-radiance-transfer](precomputed-radiance-transfer) when you also want self-shadowing and interreflection of the object itself. Prefer a prefiltered diffuse cubemap when you want exact cosine convolution without L2 ringing. ## Cost cheap — A few dozen ALU ops per pixel and 27 floats of storage per probe. Measured GPU Weight: 69.22× baseline (extreme) — 2.2773 ms median / 2.4565 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 52.75× baseline (heavy) — 0.8387 ms median (2.72× faster on L4). Ampere A100 scaling: 48.78× baseline (heavy) — 1.4049 ms median (1.62× faster on A100). ## Failure modes - Ringing: strong, small lights produce negative irradiance or bright halos on the opposite side (visible with a sun in the environment) - Cannot represent sharp directional lights or shadows; the result is a soft ambient wash - L1-only variants lose contrast compared with a true cosine convolution - Banding or color shifts when HDR values are clamped before projection, since peaks dominate the coefficients ## Engine support - babylonjs: builtin — `pbrMaterial.brdf.useSphericalHarmonics = true (SH irradiance from the environment texture)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrBRDFConfiguration.ts, checked 2026-12-01) - blender: builtin — `EEVEE Volume Light Probes encode baked indirect irradiance as spherical harmonic coefficients (sh_coef) in eevee_lightprobe_volume.cc` (evidence: https://github.com/blender/blender/blob/main/source/blender/draw/engines/eevee/eevee_lightprobe_volume.cc, checked 2026-12-01) - godot: builtin — `LightmapGI.directional = true bakes directional lightmaps as spherical harmonics (LightmapGIData.uses_spherical_harmonics)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/LightmapGI.xml, checked 2026-12-01) - threejs: builtin — `new THREE.LightProbe(); LightProbeGenerator.fromCubeTexture()` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/lights/LightProbe.js, checked 2026-12-01) - unity: builtin — `Lighting > Environment > Environment Lighting Source (Gradient / Skybox); Light Probes` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/SphericalHarmonics.cs, checked 2026-12-01) — Ambient and light probes are stored as L1/L2 spherical harmonics. - unreal: builtin — `Sky Light and Volumetric Lightmaps store diffuse lighting as spherical harmonics` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sky-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image - Outputs: irradiance-probes - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### L2 SH irradiance vs brute-force convolution (glsl-fragment; rendered 2026-11-29) ```json { "samples": 192, "albedo": 0.8 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Left: brute-force cosine-convolved env. Right: order-2 SH irradiance. const int N = 192; // projection samples const float ALBEDO = 0.8; vec3 env(vec3 d){ vec3 sky = mix(vec3(0.55,0.7,1.0), vec3(0.15,0.3,0.7), clamp(d.y,0.0,1.0)); vec3 gnd = vec3(0.22,0.16,0.1); vec3 c = d.y > 0.0 ? sky : gnd; vec3 sun = normalize(vec3(0.6,0.5,0.3)); c += vec3(9.0,7.0,4.5) * pow(max(dot(d,sun),0.0), 48.0); return c; } vec3 fib(int i){ float y = 1.0 - 2.0*(float(i)+0.5)/float(N); float r = sqrt(1.0-y*y), a = 2.399963*float(i); return vec3(r*cos(a), y, r*sin(a)); } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = (fragCoord - 0.5*iResolution.xy) / iResolution.y; vec3 bg = mix(vec3(0.12), vec3(0.2), uv.y+0.5); float side = uv.x < 0.0 ? -1.0 : 1.0; vec2 q = uv - vec2(0.25*side, 0.0); float rad = 0.22; if (dot(q,q) > rad*rad) { fragColor = vec4(bg,1.0); return; } vec2 p = q/rad; vec3 n = vec3(p.x, p.y, sqrt(1.0-dot(p,p))); float ca = cos(iTime*0.5), sa = sin(iTime*0.5); n = vec3(ca*n.x + sa*n.z, n.y, -sa*n.x + ca*n.z); vec3 Lc[9]; for (int k=0;k<9;k++) Lc[k] = vec3(0.0); vec3 ref = vec3(0.0); for (int i=0;i Approximates the specular environment lighting integral as a product of two precomputed terms: a roughness-prefiltered environment cubemap and a 2D lookup table of BRDF scale and bias. Costs two texture reads per pixel. ## Reach for it when - reflections from an environment map for pbr - realtime image based lighting for glossy surfaces - specular ibl is too expensive per pixel - metals look dull without environment reflections ## How it works Evaluating the full specular integral `integral L(l) f(l, v) cos(theta) dl` per pixel is too slow. The split-sum approximation separates it into two independent sums: the average incoming radiance weighted by the normal distribution, and the average BRDF response with a constant white environment. **Prefiltered environment map**: an HDR cubemap is convolved offline with a GGX lobe for each roughness level and stored in the mip chain (mip index maps to roughness). The assumption `n = v = r` makes the lookup depend only on the reflection direction and roughness. Importance sampling with a few hundred samples per texel, optionally weighted by `n . l`, builds each mip. **BRDF integration LUT**: a 2D texture indexed by `n . v` and roughness stores a scale and bias applied to `F0`. It is computed once for the BRDF and is independent of the environment. At runtime: `specular = prefilteredColor(r, roughness) * (F0 * A + B)`. Diffuse IBL uses a separate irradiance map or [spherical-harmonics-lighting](spherical-harmonics-lighting). ## When to use it Choose it as the default environment reflection and ambient specular in real-time PBR: skylights, studio HDRIs, reflection probes. Prefer [spherical-harmonics-lighting](spherical-harmonics-lighting) for the diffuse half. Prefer [ltc-area-lights](ltc-area-lights) for local area emitters with proper highlights. Prefer [path-tracing](path-tracing) or screen-space reflections where correct occlusion of the reflection is required, since split-sum environment lookups are unoccluded. ## Cost cheap — Two texture samples and a few multiplies per pixel; offline prefiltering costs a few hundred milliseconds per environment. Measured GPU Weight: 1.86× baseline (feather) — 0.0613 ms median / 0.0648 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.49× baseline (feather) — 0.0237 ms median (2.59× faster on L4). Ampere A100 scaling: 1.17× baseline (feather) — 0.0336 ms median (1.82× faster on A100). ## Failure modes - Specular occlusion missing: reflections of the sky appear inside crevices and under objects unless multiplied by an AO or specular-occlusion term - Assuming n = v = r flattens grazing-angle reflections and misses the stretched highlight of real GGX - Seams or aliasing at cubemap mip boundaries when prefiltered filtering is low-quality - Parallax error for local probes unless box-projected or corrected ## Engine support - babylonjs: builtin — `scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(url, scene) (PBR uses BRDF LUT)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Misc/brdfTextureTools.ts, checked 2026-12-01) - blender: builtin — `EEVEE > Light Probes (environment cubemap + split-sum GGX BRDF lookup)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_probes/introduction.html, checked 2026-12-01) - godot: builtin — `Environment.background_mode = Sky; Sky.radiance_size` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Sky.xml, checked 2026-12-01) — Sky radiance cubemap is prefiltered for specular IBL. - threejs: builtin — `scene.environment = pmremGenerator.fromEquirectangular(hdr).texture` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/extras/PMREMGenerator.js, checked 2026-12-01) - unity: builtin — `Lighting > Environment; Reflection Probe (prefiltered GGX cubemaps)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl, checked 2026-12-01) — HDRP pre-integrated FGD split-sum IBL; URP uses an analytic variant. - unreal: builtin — `Place Actors > Lights > Sky Light and Reflection Captures (prefiltered environment cubemap specular IBL)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/sky-lights-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: hdr-image, material-params, gbuffer - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Split-sum spheres: roughness vs metalness (glsl-fragment; rendered 2026-11-29) ```json { "cols": 5, "rows": 3 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Grid of spheres: roughness left to right, metalness bottom to top. // Specular uses Karis's analytic EnvBRDFApprox in place of the split-sum LUT; the "prefiltered" env is faked // by blending the sharp environment toward its blurred average as roughness grows. const float COLS = 5.0; const float ROWS = 3.0; vec3 env(vec3 d){ vec3 sky = mix(vec3(0.75,0.85,1.0), vec3(0.2,0.4,0.9), clamp(d.y,0.0,1.0)); vec3 gnd = vec3(0.25,0.2,0.16); vec3 c = d.y > 0.0 ? sky : gnd; c += vec3(12.0,10.0,7.0) * pow(max(dot(d, normalize(vec3(0.5,0.6,0.6))),0.0), 80.0); return c; } vec3 envBlur(vec3 d, float r){ return mix(env(d), vec3(0.45,0.5,0.55), r*r*0.8) ; } vec3 envBRDFApprox(vec3 spec, float rough, float NoV){ const vec4 c0 = vec4(-1.0,-0.0275,-0.572,0.022); const vec4 c1 = vec4(1.0,0.0425,1.04,-0.04); vec4 r = rough*c0 + c1; float a004 = min(r.x*r.x, exp2(-9.28*NoV))*r.x + r.y; vec2 AB = vec2(-1.04,1.04)*a004 + r.zw; return spec*AB.x + AB.y; } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = fragCoord / iResolution.xy; vec3 bg = mix(vec3(0.1), vec3(0.2), uv.y); vec2 g = vec2(uv.x*COLS, uv.y*ROWS); vec2 id = floor(g); vec2 p = (fract(g) - 0.5) * 2.0 * 1.12; p.x *= iResolution.x/iResolution.y * ROWS/COLS; if (dot(p,p) > 1.0) { fragColor = vec4(bg,1.0); return; } vec3 n = vec3(p, sqrt(1.0 - dot(p,p))); vec3 v = vec3(0,0,1); float rough = clamp((id.x + 0.5)/COLS, 0.05, 1.0); float metal = id.y/(ROWS-1.0); vec3 base = vec3(0.95,0.64,0.54); vec3 f0 = mix(vec3(0.04), base, metal); vec3 diff = (1.0-metal)*base * env(n)*0.0 ; // irradiance approximated by a very blurred environment diff = (1.0-metal)*base*envBlur(n, 1.0); vec3 r = reflect(-v, n); float NoV = max(dot(n,v), 0.0); vec3 spec = envBlur(r, rough) * envBRDFApprox(f0, rough, NoV); vec3 col = diff + spec; col = col/(1.0+col); fragColor = vec4(pow(col, vec3(1.0/2.2)), 1.0); } ``` Attribution: written for this index; uses the analytic EnvBRDFApprox from Karis's mobile PBR notes in place of the precomputed LUT ## Combines with - [Spherical-Harmonic Lighting (Irradiance Environment Maps)](https://texelatlas.vercel.app/t/spherical-harmonics-lighting.md): SH irradiance covers the diffuse term and the prefiltered cubemap covers the specular term of the same environment. ## Sources 1. [primary] Brian Karis Real Shading in Unreal Engine 4. SIGGRAPH 2013 Physically Based Shading in Theory and Practice. https://blog.selfshadow.com/publications/s2013-shading-course (verified via http on 2026-11-29) 2. [tutorial] Joey de Vries Specular IBL. learnopengl.com. https://learnopengl.com/PBR/IBL/Specular-IBL (verified via http on 2026-11-29) ## Cite this entry Texel. "Split-Sum Image-Based Lighting." https://texelatlas.vercel.app/t/split-sum-ibl/ (accessed 2026-12-01). --- id: "ssao" title: "Screen-Space Ambient Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2007 inputs: [depth, normals] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Mittring, 2007" url: "https://texelatlas.vercel.app/t/ssao/" sources_verified_at: "2026-11-29" --- # Screen-Space Ambient Occlusion (Mittring, 2007) > Approximates how much of the hemisphere above each pixel is blocked by nearby geometry by sampling the depth buffer around it, darkening creases and contacts. ## Reach for it when - flat lighting lacks contact shadows in corners - need the cheapest scene-wide darkening of creases - only have a depth buffer and want depth cues - objects look floating with no grounding ## How it works For each pixel, reconstruct its view-space position from depth, scatter a handful of sample points in a sphere or normal-oriented hemisphere, project each back to the screen and compare its depth with the stored depth there. Samples that fall behind the stored surface (within a range check that rejects distant occluders) count as occlusion; the average gives an occlusion factor. A per-pixel random rotation of the sample pattern trades banding for noise, which a depth-aware blur or temporal accumulation removes. The original Crytek formulation is sphere-based and cheap but ignores orientation, producing grey, flat-surface haze that normal-oriented variants reduce. ## When to use it Choose it as the cheapest scene-wide AO that needs only a depth buffer, for forward or deferred renderers. Prefer [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) or [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) when you want more accurate horizon-based occlusion, [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) or [SDF Ambient Occlusion](https://texelatlas.vercel.app/t/sdf-ambient-occlusion.md) when you need off-screen occluders, and [Visibility Bitmask Ambient Occlusion](https://texelatlas.vercel.app/t/visibility-bitmask-ssao.md) for thickness-aware results. ## Cost cheap — Roughly eight to sixteen depth taps per pixel plus a blur; usually computed at half resolution. Measured GPU Weight: 26.17× baseline (heavy) — 0.861 ms median / 0.9046 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 21.92× baseline (heavy) — 0.3486 ms median (2.47× faster on L4). Ampere A100 scaling: 14.97× baseline (moderate) — 0.4311 ms median (2× faster on A100). ## Failure modes - Haloing around objects from missing depth-range check - Noise or banding from low sample counts - Dark halos or flat-surface grey haze when the sample sphere is not normal-oriented - View-dependent: occluders off-screen or behind other geometry are ignored ## Engine support - babylonjs: builtin — `new BABYLON.SSAO2RenderingPipeline('ssao', scene, ratio, cameras)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.pure.ts, checked 2026-12-01) — SSAORenderingPipeline is the older variant. - blender: builtin — `Properties > Render > Raytracing (enable) > Fast GI Approximation > Method = Ambient Occlusion` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/raytracing.html, checked 2026-12-01) — EEVEE screen-space ray-based AO, used as fast GI fallback. - godot: builtin — `Environment.ssao_enabled = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Environment.xml, checked 2026-12-01) — Forward+ and Mobile renderers only. - threejs: official — `import { ssao } from 'three/addons/tsl/display/SSAONode.js' (WebGL: SSAOPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/SSAONode.js, checked 2026-12-01) - unity: builtin — `URP: Renderer > Add Renderer Feature > Screen Space Ambient Occlusion` (evidence: https://docs.unity3d.com/6000.0/Documentation/Manual/urp/post-processing-ssao.html, checked 2026-12-01) — URP renderer feature (Alchemy AO); HDRP uses GTAO. - unreal: builtin — `Post Process Volume > Rendering Features > Ambient Occlusion` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/post-process-effects-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: flat ambient. Right: SSAO from 24 hemisphere depth-buffer samples with a range check (glsl-fragment; rendered 2026-11-29) ```json { "INT": 1.3, "NS": 24, "RAD": 0.55, "BIAS": 0.05 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} vec3 ambShade(vec3 P,vec3 N,vec3 ao){return alb(P)*(vec3(.95,.97,1.)*.9*ao*(.6+.4*N.y)+.25*max(dot(N,LD),0.));} vec2 rnd2(vec2 uv,float k){return vec2(hash(floor(uv*512.)+vec2(k*17.,k*31.)),hash(floor(uv*512.)+vec2(k*7.+3.,k*13.+5.)));} const float INT=1.3; // P const int NS=24; // P const float RAD=0.55; // P const float BIAS=0.05; // P float ssao(vec3 P,vec3 N,vec2 uv){ float occ=0.;float zp=P.z-RO.z; for(int i=0;i0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){vec3 P=RO+rd*t;float ao=R?clamp(1.-INT*(1.-ssao(P,n,uv)),0.,1.):1.;col=mix(ambShade(P,n,vec3(ao)),sky(rd),smoothstep(6.,25.,t));} if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extended by [Alchemy screen-space ambient obscurance](https://texelatlas.vercel.app/t/alchemy-ambient-obscurance.md) - extended by [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) ## Sources 1. [primary] Martin Mittring (2007) Finding next gen. ACM SIGGRAPH 2007 courses. https://doi.org/10.1145/1281500.1281671 (verified via crossref on 2026-11-29) 2. [tutorial] Joey de Vries SSAO. learnopengl.com. https://learnopengl.com/Advanced-Lighting/SSAO (verified via http on 2026-11-29) 3. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Screen-Space Ambient Occlusion." https://texelatlas.vercel.app/t/ssao/ (accessed 2026-12-01). --- id: "stable-fluids" title: "Stable Fluids" domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 1999 inputs: [voxels] outputs: [volume-density, particles] style: "both" dynamic: "dynamic" cost: "medium" authority: "Stam, 1999" url: "https://texelatlas.vercel.app/t/stable-fluids/" sources_verified_at: "2026-11-29" --- # Stable Fluids (Stam, 1999) > Unconditionally stable grid solver for incompressible smoke and gas: advect semi-Lagrangian, diffuse, project to divergence-free. ## Reach for it when - need smoke or ink that doesn't explode at large timesteps - cheap 2d or 3d smoke on a grid - art-directable gas and fire - fluid solver must be unconditionally stable - interactive swirling smoke in a game ## How it works Each step applies external forces, then advects the velocity field by tracing each cell backwards through the flow and sampling the old field with interpolation (semi-Lagrangian), which is stable for any step size. Viscosity is an implicit diffusion solve. A projection step solves a Poisson equation for pressure and subtracts its gradient so that divergence is zero. Smoke density or temperature are advected as passive scalars through the same velocity field. On GPUs each stage is a fragment pass with ping-pong textures, and the Jacobi pressure solve typically takes 20-40 iterations. Vorticity confinement is commonly added to recover small swirls lost to numerical diffusion. ## When to use it Choose it when you want cheap, robust, art-directable 2D or 3D smoke, fire and ink on a regular grid. Prefer [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) when you need liquid with a free surface, [Lattice Boltzmann fluids](https://texelatlas.vercel.app/t/lattice-boltzmann-fluids.md) for easily parallel grid flow with simple boundaries, and [Smoothed Particle Hydrodynamics (fluids)](https://texelatlas.vercel.app/t/sph-fluids.md) for meshless splashing fluids. ## Cost medium — Cheap in 2D, medium in 3D (pressure Jacobi iterations dominate). Measured GPU Weight: 44.53× baseline (heavy) — 1.4652 ms median / 1.5321 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 39.78× baseline (heavy) — 0.6325 ms median (2.32× faster on L4). Ampere A100 scaling: 26.9× baseline (heavy) — 0.7747 ms median (1.89× faster on A100). ## Failure modes - Semi-Lagrangian advection smears detail (numerical diffusion) and kills small vortices - Fixed grid: no free surface, large domains cost cubically - Jacobi pressure solve with few iterations leaves residual divergence and visible compressibility - Boundary conditions on moving obstacles need care or smoke leaks ## Engine support - blender: builtin — `Physics > Fluid (Mantaflow grid/FLIP Navier-Stokes fluid solver)` (evidence: https://docs.blender.org/manual/en/5.2/physics/fluid/introduction.html, checked 2026-12-01) - unreal: official — `Enable Niagara Fluids plugin > Grid 2D / Grid 3D Gas and Smoke Eulerian fluid solvers` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/niagara-fluids-reference-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: voxels - Outputs: volume-density, particles - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Stable fluids — semi-Lagrangian divergence-free advection & vorticity dye plumes (glsl-fragment; rendered 2026-11-30) ```json { "P_VISCOSITY": 0.35, "P_VORTICITY": 1.35, "P_ADVECTION": 1.1, "P_SPEED": 1 } ``` ```glsl const float P_VISCOSITY = 0.35; // P Viscosity [0.05, 1.2, 0.02] const float P_VORTICITY = 1.35; // P Vorticity [0.2, 2.5, 0.05] const float P_ADVECTION = 1.1; // P Advect Step [0.2, 2.2, 0.05] const float P_SPEED = 1.0; // P Flow Speed [0.0, 2.5, 0.05] // Analytical streamfunction psi(p,t) -> curl(psi) is strictly divergence-free (div u = 0) float streamFunc(vec2 p, float t, float visc) { float damp = exp(-visc * 0.45); float psi = 0.0; // Multi-scale Karman vortex street & dipole eddies psi += 0.48 * sin(p.x * 2.1 - t * 0.65) * cos(p.y * 2.3 + t * 0.42); psi += 0.28 * damp * cos(p.x * 4.3 + p.y * 3.1 + t * 0.92); psi += 0.16 * damp * damp * sin(p.x * 7.8 - p.y * 6.4 - t * 1.35); // Central swirling vortex dipole vec2 c1 = vec2(0.28 * cos(t * 0.55), 0.24 * sin(t * 0.68)); vec2 c2 = -c1; psi += 0.36 * exp(-dot(p - c1, p - c1) * 7.5); psi -= 0.36 * exp(-dot(p - c2, p - c2) * 7.5); return psi; } // Divergence-free velocity u = (dPsi/dy, -dPsi/dx) vec2 evalVelocity(vec2 p, float t, float visc, float vort) { float e = 0.008; float dPsiDx = (streamFunc(p + vec2(e, 0.0), t, visc) - streamFunc(p - vec2(e, 0.0), t, visc)) / (2.0 * e); float dPsiDy = (streamFunc(p + vec2(0.0, e), t, visc) - streamFunc(p - vec2(0.0, e), t, visc)) / (2.0 * e); return vec2(dPsiDy, -dPsiDx) * vort; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float t = iTime * max(P_SPEED, 0.0); float visc = clamp(P_VISCOSITY, 0.02, 1.5); float vort = clamp(P_VORTICITY, 0.1, 2.8); float adv = clamp(P_ADVECTION, 0.1, 2.4); // Semi-Lagrangian backtracing: unconditionally stable RK2 advection through 7 substeps vec2 pos = uv; float dt = 0.055 * adv; float curlAccum = 0.0; for (int i = 0; i < 7; i++) { float ti = t - float(i) * dt * 0.85; vec2 v1 = evalVelocity(pos, ti, visc, vort); vec2 mid = pos - 0.5 * dt * v1; vec2 v2 = evalVelocity(mid, ti - 0.5 * dt, visc, vort); pos -= dt * v2; curlAccum += length(v2); } curlAccum /= 7.0; // Source dye jets injected at advected coordinates (cyan, magenta, amber-gold) float band1 = exp(-pow(sin(pos.y * 3.8 + pos.x * 1.4) * 1.8, 2.0)); float band2 = exp(-pow(cos(pos.x * 4.1 - pos.y * 1.8) * 1.9, 2.0)); float band3 = exp(-pow(sin((pos.x + pos.y) * 5.2) * 2.1, 2.0)); // Viscous diffusion softens filament contrast at higher P_VISCOSITY float crisp = mix(1.45, 0.65, clamp(visc, 0.0, 1.0)); float d1 = pow(clamp(band1, 0.0, 1.0), crisp); float d2 = pow(clamp(band2, 0.0, 1.0), crisp); float d3 = pow(clamp(band3, 0.0, 1.0), crisp); vec3 col = vec3(0.018, 0.024, 0.042); col += vec3(0.08, 0.82, 0.96) * d1 * 1.05; col += vec3(0.96, 0.22, 0.58) * d2 * 0.95; col += vec3(1.05, 0.72, 0.18) * d3 * 0.78; // Specular-like vorticity highlight along high-shear ribbons vec2 vNow = evalVelocity(uv, t, visc, vort); float speedMag = length(vNow); float streamIso = smoothstep(0.92, 0.99, 0.5 + 0.5 * cos(streamFunc(uv, t, visc) * 32.0)); col += vec3(0.75, 0.92, 1.0) * streamIso * 0.12 * clamp(speedMag, 0.0, 1.5); col *= 0.65 + 0.55 * clamp(curlAccum * 0.75, 0.0, 1.4); // Dark subtle frame vignette col *= 1.0 - 0.28 * dot(uv, uv); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extended by [MacCormack Predictor-Corrector Clamped Fluid Advection](https://texelatlas.vercel.app/t/maccormack-clamped-advection.md) ## Combination ideas - [Chladni-vibrated iridescent soap film](https://texelatlas.vercel.app/ideas/chladni-driven-iridescent-soap-film/) - [Storms that form and drift](https://texelatlas.vercel.app/ideas/simulated-weather-for-clouds/) ## Sources 1. [primary] Jos Stam (1999) Stable fluids. Proceedings of the 26th annual conference on Computer graphics and interactive techniques - SIGGRAPH '99. https://doi.org/10.1145/311535.311548 (verified via crossref on 2026-11-29) 2. [tutorial] Jos Stam Real-Time Fluid Dynamics for Games. dgp.toronto.edu. https://www.dgp.toronto.edu/public_user/stam/reality/Research/pdf/GDC03.pdf (verified via http on 2026-11-29) 3. [tutorial] Mark J. Harris GPU Gems Chapter 38: Fast Fluid Dynamics Simulation on the GPU. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems/part-vi-beyond-triangles/chapter-38-fast-fluid-dynamics-simulation-gpu (verified via http on 2026-11-29) ## Cite this entry Texel. "Stable Fluids." https://texelatlas.vercel.app/t/stable-fluids/ (accessed 2026-12-01). --- id: "stopthepop" title: "StopThePop (Sorted Gaussian Splatting)" aliases: [StopThePop] domain: "capture" stage: "capture" realtime: "realtime" platforms: [cuda, desktop-gpu] year_introduced: 2024 inputs: [gaussians, camera-poses] outputs: [ldr-image] style: "photoreal" dynamic: "static" cost: "medium" authority: "Radl et al., 2024" url: "https://texelatlas.vercel.app/t/stopthepop/" sources_verified_at: "2026-11-29" --- # StopThePop (Sorted Gaussian Splatting) (Radl et al., 2024) > Removes the popping artefacts of 3DGS by sorting Gaussians per pixel against ray-based depths in hierarchical tiles, while culling and early-terminating for speed. ## Reach for it when - gaussian splat render flickers when camera rotates - popping artifacts in 3d gaussian splatting - splat sorting order changes visibly between frames - temporal inconsistency in splat viewers in vr ## How it works 3DGS sorts each Gaussian once per tile by its centre depth, and uses a view-plane depth, so adjacent Gaussians swap order as the camera rotates and the image pops. StopThePop evaluates depth along each pixel's actual ray at the point of maximum Gaussian contribution and resolves ordering per pixel. To keep this affordable it sorts hierarchically: a coarse tile sort followed by a small per-pixel local sort within a fixed-size buffer in a tiled rasteriser. Tighter tile culling uses the opacity-aware extent of each ellipse, and early termination avoids useless blends. Rendering uses the same trained scene, so it can often be applied to pretrained models, optionally with retraining to match the new rasteriser. ## When to use it Choose it when camera motion, VR or video makes view-inconsistent popping visible. Prefer [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) for lowest-cost viewing of static stills, and [2D Gaussian Splatting](https://texelatlas.vercel.app/t/2d-gaussian-splatting.md) when ordering plus accurate surface depth are needed. Combine with [Mip-Splatting](https://texelatlas.vercel.app/t/mip-splatting.md) for alias-free sorted splats. ## Cost medium — The authors report faster-than-sort-heavy variants through culling, but exact timings depend on scene and GPU; treat as comparable to 3DGS. ## Failure modes - Per-pixel buffer is bounded, so extremely dense overlap can still mis-sort - Slight quality shift versus the originally trained appearance unless retrained - CUDA reference rasteriser only; web viewers rarely implement it - Does not address aliasing, floaters or geometry quality ## Dataflow - Inputs: gaussians, camera-poses - Outputs: ldr-image - Platforms: cuda, desktop-gpu ## Lineage - extends [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) ## Sources 1. [primary] Lukas Radl, Michael Steiner, Mathias Parger, Alexander Weinrauch, Bernhard Kerbl, Markus Steinberger (2024) StopThePop: Sorted Gaussian Splatting for View-Consistent Real-time Rendering. ACM Transactions on Graphics, volume 43(4), July 2024. https://arxiv.org/abs/2402.00525 (verified via arxiv on 2026-11-29) 2. [implementation] r4dl (2024) r4dl/StopThePop. https://github.com/r4dl/StopThePop License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "StopThePop (Sorted Gaussian Splatting)." https://texelatlas.vercel.app/t/stopthepop/ (accessed 2026-12-01). --- id: "strand-based-real-time-hair" title: "Strand-based real-time hair (TressFX style)" aliases: [TressFX, strand hair, NVIDIA HairWorks style] domain: "materials" stage: "material" realtime: "realtime" platforms: [desktop-gpu, unreal, unity, webgpu] year_introduced: 2012 inputs: [curves, skeleton, material-params] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "GPUOpen-Effects, 2016" url: "https://texelatlas.vercel.app/t/strand-based-real-time-hair/" sources_verified_at: "2026-11-29" --- # Strand-based real-time hair (TressFX style) (GPUOpen-Effects, 2016) > Renders and simulates tens of thousands of individual hair strands on the GPU: guide strands run a position-based simulation, are interpolated into many render strands, expanded to camera-facing ribbons, then shaded and blended with an order-independent technique. ## Reach for it when - want individual simulated hair strands in real time - hero character hair with proper silhouette and motion - hair transparency sorting is expensive - hair strands alias and shimmer in motion - need gpu hair simulation with collisions ## How it works Authoring supplies guide hairs as polylines. A compute pass simulates them with a few constraints (length, local shape against the head's rest pose, global shape, wind) integrated by Verlet-style steps, and collides them with proxy capsules. A second pass interpolates guides to many follower strands and applies clumping and tessellation. Rendering expands each segment into a thin camera-facing quad (or tube), often one or two pixels wide, and shades it with a strand tangent lobe such as Kajiya-Kay or a Marschner approximation. Transparency is the hard part: TressFX stores per-pixel linked lists of fragments and sorts and blends them, while others use alpha-to-coverage or a k-buffer. Self-shadowing is approximated with deep shadow-like opacity maps or a density volume. Antialiasing relies on coverage-based thin-line handling plus temporal methods. ## When to use it Choose it for hero characters on desktop and console where individual strands matter for silhouette and motion. Prefer [Shell and fin fur rendering](https://texelatlas.vercel.app/t/shell-fur-rendering.md) for short fur and [Kajiya-Kay hair shading](https://texelatlas.vercel.app/t/kajiya-kay-hair-shading.md) on cards for crowds or mobile. Use [Marschner hair scattering model](https://texelatlas.vercel.app/t/marschner-hair-scattering.md) or [Disney / Chiang hair and fur BSDF](https://texelatlas.vercel.app/t/disney-hair-bsdf.md) for the shading model instead of Kajiya-Kay if path-traced fidelity is the goal. The simulation part uses ideas from [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) and [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md). ## Cost heavy — Hair is one of the costliest character features; cost scales with strand count, transparency method and shadows. Measured GPU Weight: 32.25× baseline (heavy) — 1.0609 ms median / 1.0723 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 28.02× baseline (heavy) — 0.4455 ms median (2.38× faster on L4). Ampere A100 scaling: 23.03× baseline (heavy) — 0.6632 ms median (1.6× faster on A100). ## Failure modes - Per-pixel linked-list transparency overflows its memory budget in dense close-ups - Strands collide poorly with shoulders and clothing when only head proxies exist - Aliasing and shimmering of one-pixel strands needs temporal accumulation, causing ghosting - Strand count LOD pops without careful width compensation - Self-shadowing is approximate, so hair looks flat or overly bright without it - Stiff constraints under low frame rate or large time steps make hair explode or jitter ## Engine support - blender: builtin — `Render Properties > Curves > Shape = Strand or Strip (EEVEE)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/curves.html, checked 2026-12-01) — Hair curve rendering; not TressFX-style GPU simulation. - unreal: official — `Enable Groom plugins; import a Groom Asset and add a Groom Component` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/hair-rendering-and-simulation-in-unreal-engine, checked 2026-12-01) — Strand rendering plus Niagara-based hair simulation. ## Dataflow - Inputs: curves, skeleton, material-params - Outputs: radiance - Platforms: desktop-gpu, unreal, unity, webgpu ## Presets ### Strand-Based Real-Time Hair — simulated PBD guide strands (left) vs dense interpolated Marschner ribbons (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_STRAND_DENSITY": 26, "P_WIND_SWAY": 0.75, "P_SPEC_SHIFT": 0.22, "P_SPLIT": 0.48 } ``` ```glsl const float P_STRAND_DENSITY = 26.0; // P Render Strands [10.0, 42.0, 2.0] const float P_WIND_SWAY = 0.75; // P Wind & Sway [0.0, 1.8, 0.05] const float P_SPEC_SHIFT = 0.22; // P Cuticle Shift [0.05, 0.45, 0.02] const float P_SPLIT = 0.48; // P Guides / Hair Split [0.0, 1.0, 0.02] float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; return fract(p * (p + p)); } // Compute strand centerline x(y) and tangent for a cascading hair lock swaying in wind void evalStrandCurve(float y, float id, float wind, out float cx, out float dxdy, out float zOff) { float rootX = (id - 0.5) * 0.92; float lenFactor = clamp(0.46 - y, 0.0, 1.15); float phase = iTime * 2.1 + id * 6.8; float wave = sin(phase - lenFactor * 4.2) * 0.085 * wind * lenFactor * lenFactor; float curl = sin(lenFactor * 7.5 + id * 13.0) * 0.045 * (0.25 + lenFactor); // Natural cascade curve over crown and shoulder float drape = 0.12 * sin(lenFactor * 2.6) * sign(rootX + 0.001) * (0.3 + abs(rootX)); cx = rootX * (0.55 + 0.55 * smoothstep(0.46, -0.35, y)) + drape + wave + curl; // Derivative dx/dy for strand tangent float eps = 0.015; float lf2 = clamp(0.46 - (y - eps), 0.0, 1.15); float cx2 = rootX * (0.55 + 0.55 * smoothstep(0.46, -0.35, y - eps)) + 0.12 * sin(lf2 * 2.6) * sign(rootX + 0.001) * (0.3 + abs(rootX)) + sin(phase - lf2 * 4.2) * 0.085 * wind * lf2 * lf2 + sin(lf2 * 7.5 + id * 13.0) * 0.045 * (0.25 + lf2); dxdy = (cx - cx2) / eps; zOff = cos((id - 0.5) * 2.6) * 0.25 + 0.06 * cos(lenFactor * 5.0 + id * 9.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showFullHair = sx >= split; float wind = clamp(P_WIND_SWAY, 0.0, 2.2); float shift = clamp(P_SPEC_SHIFT, 0.02, 0.5); int numStrands = showFullHair ? int(clamp(floor(P_STRAND_DENSITY + 0.5), 8.0, 44.0)) : 7; // Studio backdrop + mannequin head/shoulder silhouette vec3 col = mix(vec3(0.05, 0.06, 0.09), vec3(0.13, 0.16, 0.22), smoothstep(-0.5, 0.5, uv.y)); float headD = length((uv - vec2(0.0, 0.14)) * vec2(1.15, 0.92)) - 0.34; if (headD < 0.0) { vec2 hxy = (uv - vec2(0.0, 0.14)) / 0.34; vec3 hn = normalize(vec3(hxy, sqrt(max(1.0 - dot(hxy, hxy), 0.05)))); float nl = max(dot(hn, normalize(vec3(0.55, 0.7, 0.55))), 0.08); col = vec3(0.18, 0.17, 0.19) * nl + vec3(0.06, 0.08, 0.12); } vec3 L = normalize(vec3(0.58 * cos(iTime * 0.35), 0.68, 0.62)); vec3 V = vec3(0.0, 0.0, 1.0); vec3 H = normalize(L + V); // Order-independent depth-composited ribbons across simulated hair strands vec3 hairAcc = vec3(0.0); float covAcc = 0.0; float crownMask = smoothstep(0.48, 0.36, uv.y) * smoothstep(-0.52, -0.36, uv.y); for (int i = 0; i < 44; i++) { if (i >= numStrands) break; float fi = (float(i) + 0.5) / float(numStrands); float rnd = hash11(float(i) * 19.37 + 1.7); float cx, dxdy, zOff; evalStrandCurve(uv.y, fi, wind, cx, dxdy, zOff); float strandEnd = -0.46 + 0.14 * rnd; float tipFade = smoothstep(strandEnd, strandEnd + 0.10, uv.y); float width = showFullHair ? (0.022 + 0.012 * rnd) : 0.014; float dist = abs(uv.x - cx); if (dist < width * 2.2 && tipFade > 0.01 && crownMask > 0.01) { float alpha = smoothstep(width * 1.15, width * 0.25, dist) * tipFade * crownMask; // Compute 3D ribbon tangent T and cross-strand normal N vec3 T = normalize(vec3(dxdy, 1.0, 0.18 * sin(uv.y * 5.0 + rnd * 6.0))); float across = clamp((uv.x - cx) / max(width, 1e-4), -1.0, 1.0); vec3 N = normalize(vec3(across * 0.85, -dxdy * across * 0.4, sqrt(max(1.0 - across * across * 0.72, 0.1)))); vec3 strandCol; if (!showFullHair) { // Left: Distinct PBD guide strand visualization with animated particle beads along each guide vec3 guideHue = 0.55 + 0.45 * cos(6.28318 * (fi + vec3(0.0, 0.33, 0.67))); float bead = smoothstep(0.014, 0.005, abs(fract(uv.y * 9.0) - 0.5) * 0.11); strandCol = mix(guideHue * 0.9, vec3(1.0, 0.98, 0.9), bead * 0.8); } else { // Right: Marschner / Kajiya-Kay dual-lobe specular (primary R white lobe + secondary TRT warm amber lobe) vec3 baseHair = mix(vec3(0.18, 0.08, 0.04), vec3(0.36, 0.16, 0.07), rnd); // Primary cuticle-shifted tangent T1 (white reflection) vec3 T1 = normalize(T + N * shift); float th1 = dot(T1, H); float sinTH1 = sqrt(max(1.0 - th1 * th1, 0.0)); float specR = pow(sinTH1, 56.0) * 1.25; // Secondary shifted tangent T2 (colored internal TRT reflection) vec3 T2 = normalize(T - N * (shift * 1.65)); float th2 = dot(T2, H); float sinTH2 = sqrt(max(1.0 - th2 * th2, 0.0)); float specTRT = pow(sinTH2, 18.0) * 0.75; // Longitudinal diffuse + self-shadowing across hair volume depth float sinTL = sqrt(max(1.0 - dot(T, L) * dot(T, L), 0.0)); float selfShadow = 0.38 + 0.62 * smoothstep(-0.25, 0.30, zOff); float microFibers = 0.85 + 0.15 * sin(across * 18.0 + rnd * 20.0); strandCol = (baseHair * (0.32 + 0.85 * sinTL) + vec3(1.0, 0.96, 0.90) * specR + vec3(0.95, 0.48, 0.18) * specTRT) * selfShadow * microFibers; } // Depth-biased soft OIT blend float w = alpha * (0.45 + 0.85 * smoothstep(-0.3, 0.35, zOff)); hairAcc += strandCol * w; covAcc += w; } } if (covAcc > 0.001) { vec3 finalHair = hairAcc / max(covAcc, 1e-4); col = mix(col, finalHair, clamp(covAcc, 0.0, 1.0)); } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md): Guide strands use distance and shape constraints solved position-based each frame. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): Resolves the sub-pixel strand coverage that single-frame antialiasing cannot. ## Sources 1. [primary] GPUOpen-Effects (2016) GPUOpen-Effects/TressFX. https://github.com/GPUOpen-Effects/TressFX License: MIT. (verified via github on 2026-11-29) 2. [secondary] Cem Yuksel, Sarah Tariq Advanced techniques in real-time hair rendering and simulation. cemyuksel.com. https://www.cemyuksel.com/courses/conferences/siggraph2010-hair (verified via http on 2026-11-29) ## Cite this entry Texel. "Strand-based real-time hair (TressFX style)." https://texelatlas.vercel.app/t/strand-based-real-time-hair/ (accessed 2026-12-01). --- id: "stream-power-erosion" title: "Stream-Power Erosion (Fluvial Terrain Uplift)" aliases: [stream power law, uplift-erosion, fluvial erosion terrain] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, desktop-gpu, python, houdini, unity, unreal] year_introduced: 2016 inputs: [heightfield, graph] outputs: [heightfield] style: "photoreal" dynamic: "static" cost: "offline" authority: "Cordonnier et al., 2016" url: "https://texelatlas.vercel.app/t/stream-power-erosion/" sources_verified_at: "2026-11-29" --- # Stream-Power Erosion (Fluvial Terrain Uplift) (Cordonnier et al., 2016) > Generates mountain ranges by evolving a heightfield under tectonic uplift and the stream-power law, in which erosion rate depends on drainage area and slope, producing coherent river networks and ridges at large scale. ## Reach for it when - fbm mountains lack believable river networks - need continental-scale terrain with coherent drainage - want artists to paint uplift to shape ranges - droplet erosion doesn't scale to large maps ## How it works The terrain evolves as dh/dt = U - K A^m S^n: uplift U raises the surface while erosion removes material proportional to upstream drainage area A and slope S raised to empirical exponents. Each iteration computes flow direction (steepest descent on a graph), accumulates drainage area from high to low, and applies an implicit update that is unconditionally stable even for large timesteps. Because uplift is a user-paintable map, authors sketch where mountains rise and the erosion then carves a consistent valley network. Cordonnier and colleagues use this to go from a coarse uplift sketch to realistic ranges with only tens of iterations, and note it works naturally on regular grids, triangulations or quadtrees. Pits must be resolved so every cell drains to a sink. ## When to use it Choose it for continental or mountain-range scale terrain where drainage consistency matters, and when artists need to paint uplift rather than tune droplet counts. Prefer [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) or [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md) for local gullies and deposition detail, and [Terrain from Hydrology (River-First Terrain Synthesis)](https://texelatlas.vercel.app/t/hydrology-terrain-synthesis.md) when you want to sketch the river network first. ## Cost offline — Each iteration is a graph pass over all cells (flow routing plus an area accumulation); tens of iterations suffice, so seconds to minutes depending on resolution. Measured GPU Weight: 621.98× baseline (extreme) — 20.463 ms median / 20.5022 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 514.06× baseline (extreme) — 8.1736 ms median (2.5× faster on L4). Ampere A100 scaling: 338.72× baseline (extreme) — 9.7551 ms median (2.1× faster on A100). ## Failure modes - Local minima/lakes produce terraces unless depressions are filled or breached before routing - Single-direction (D8) flow gives blocky, grid-aligned river courses - Pure detachment-limited law yields no sediment deposition, so there are no alluvial fans or flat valley floors - Exponents m,n and K per rock type must be chosen together; bad values give sawtooth ridges or flat plateaus - Resolution-dependent drainage threshold changes river density ## Dataflow - Inputs: heightfield, graph - Outputs: heightfield - Platforms: cpu, desktop-gpu, python, houdini, unity, unreal ## Presets ### Stream-power erosion — tectonic uplift & dendritic fluvial drainage carving (glsl-fragment; rendered 2026-11-30) ```json { "P_UPLIFT": 1.15, "P_INCISION": 0.95, "P_SNOWLINE": 0.56, "P_SUN_ELEV": 0.45 } ``` ```glsl const float P_UPLIFT = 1.15; // P Tectonic Uplift [0.4, 2.0, 0.05] const float P_INCISION = 0.95; // P Fluvial Incision [0.0, 1.8, 0.05] const float P_SNOWLINE = 0.56; // P Snowline Elev [0.2, 1.0, 0.02] const float P_SUN_ELEV = 0.45; // P Sun Elevation [0.1, 1.2, 0.02] vec2 hash22(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); } // Sharp Voronoi ridge distance (models dendritic drainage divides & carved river valleys) float voronoiRidge(vec2 p) { vec2 n = floor(p); vec2 f = fract(p); float d1 = 8.0, d2 = 8.0; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 g = vec2(float(i), float(j)); vec2 o = 0.18 + 0.64 * hash22(n + g); vec2 r = g + o - f; float d = dot(r, r); if (d < d1) { d2 = d1; d1 = d; } else if (d < d2) { d2 = d; } } } return sqrt(d2) - sqrt(d1); } // Stream-power law steady-state terrain: uplift minus multi-scale dendritic fluvial incision vec2 evalTerrain(vec2 p, float uplift, float incise) { // Macro tectonic dome float base = 0.65 * exp(-dot(p, p) * 0.095) + 0.22 * sin(p.x * 0.55) * cos(p.y * 0.52); // Hierarchical dendritic drainage network (3 octaves of warped V-valleys) vec2 q = p * 0.62; float r1 = voronoiRidge(q + 0.18 * vec2(sin(q.y * 1.9), cos(q.x * 1.7))); float r2 = voronoiRidge(q * 2.15 + vec2(3.1, 1.7) + 0.22 * vec2(cos(q.y * 3.1), sin(q.x * 2.8))); float r3 = voronoiRidge(q * 4.4 - vec2(2.4, 4.1)); // Concave stream-power profile: smooth steep ridges, sharp incised V-valleys (A^m * S^n) float ridge1 = 1.0 - exp(-r1 * 2.6); float ridge2 = 1.0 - exp(-r2 * 2.8); float ridge3 = 1.0 - exp(-r3 * 3.0); float carved = 0.56 * ridge1 + 0.28 * ridge2 * (0.35 + 0.65 * ridge1) + 0.14 * ridge3 * ridge2; float h = uplift * mix(base + 0.35, (base + 0.22) * (0.28 + 1.05 * carved), clamp(incise, 0.0, 1.6)); // Drainage accumulation proxy (highest along primary/secondary valley floors) float streamMask = exp(-r1 * 18.0) + 0.45 * exp(-r2 * 20.0) * smoothstep(0.35, 0.05, r1); return vec2(h, streamMask); } vec3 terrainNormal(vec2 p, float uplift, float incise) { float e = 0.025; float hx = evalTerrain(p + vec2(e, 0.0), uplift, incise).x - evalTerrain(p - vec2(e, 0.0), uplift, incise).x; float hz = evalTerrain(p + vec2(0.0, e), uplift, incise).x - evalTerrain(p - vec2(0.0, e), uplift, incise).x; return normalize(vec3(-hx, 2.0 * e, -hz)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float uplift = clamp(P_UPLIFT, 0.35, 2.2); float incise = clamp(P_INCISION, 0.0, 1.8); float snowH = clamp(P_SNOWLINE, 0.15, 1.2); float sunEl = clamp(P_SUN_ELEV, 0.08, 1.3); float camAng = iTime * 0.18 + 0.4; vec3 ro = vec3(sin(camAng) * 3.55, 1.92, cos(camAng) * 3.55); vec3 ta = vec3(0.0, 0.42, 0.0); vec3 ww = normalize(ta - ro); vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.5 * ww); vec3 sunDir = normalize(vec3(cos(0.7 + iTime * 0.15), sunEl, sin(0.7 + iTime * 0.15))); // Crisp alpine sky vec3 skyCol = mix(vec3(0.78, 0.84, 0.90), vec3(0.18, 0.40, 0.72), pow(max(rd.y, 0.0), 0.55)); skyCol += vec3(1.0, 0.86, 0.62) * pow(max(dot(rd, sunDir), 0.0), 40.0) * 0.9; vec3 col = skyCol; float t = 0.8; bool hit = false; vec2 th = vec2(0.0); for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; th = evalTerrain(p.xz, uplift, incise); float d = p.y - th.x; if (d < 0.008 * t) { hit = true; break; } t += max(0.04, d * 0.48); if (t > 14.0) break; } if (hit) { vec3 p = ro + rd * t; th = evalTerrain(p.xz, uplift, incise); vec3 n = terrainNormal(p.xz, uplift, incise); float slope = 1.0 - clamp(n.y, 0.0, 1.0); // Terrain shadow march float sh = 1.0; float st = 0.08; for (int s = 0; s < 16; s++) { vec3 sp = p + sunDir * st; float sd = sp.y - evalTerrain(sp.xz, uplift, incise).x; sh = min(sh, clamp(4.0 * sd / st, 0.0, 1.0)); st += max(0.06, sd * 0.55); if (st > 3.5 || sh < 0.05) break; } // Geomorphological biomes: alluvial green valleys -> granite scree -> alpine snow ridges vec3 valleyCol = vec3(0.14, 0.28, 0.12); vec3 rockCol = mix(vec3(0.28, 0.25, 0.22), vec3(0.46, 0.42, 0.38), smoothstep(0.15, 0.65, th.x)); vec3 snowCol = vec3(0.92, 0.95, 0.99); float rockMask = smoothstep(0.12, 0.34, slope + th.x * 0.22); vec3 alb = mix(valleyCol, rockCol, rockMask); float snowMask = smoothstep(snowH - 0.08, snowH + 0.14, th.x - slope * 0.38); alb = mix(alb, snowCol, snowMask); // Fluvial streams carving glowing turquoise ribbons through valley drainage channels float river = smoothstep(0.45, 0.95, th.y * incise) * smoothstep(snowH + 0.15, 0.25, th.x); vec3 riverCol = vec3(0.08, 0.48, 0.62); float ndl = max(dot(n, sunDir), 0.0); vec3 lit = alb * (vec3(2.25, 1.88, 1.38) * ndl * (0.08 + 0.92 * sh) + vec3(0.14, 0.24, 0.42) * (0.25 + 0.75 * n.y)); // Water specular sparkle in incised channels vec3 hVec = normalize(sunDir - rd); float rSpec = pow(max(dot(vec3(0.0, 1.0, 0.0), hVec), 0.0), 48.0) * 1.8 * sh; vec3 riverLit = riverCol * (0.35 + 0.9 * ndl * sh) + vec3(0.95, 0.98, 1.0) * rSpec; lit = mix(lit, riverLit, clamp(river, 0.0, 0.92)); // Aerial perspective haze float fog = 1.0 - exp(-0.045 * t * t * 0.25); col = mix(lit, skyCol * 0.92, clamp(fog, 0.0, 0.85)); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Terrain from Hydrology (River-First Terrain Synthesis)](https://texelatlas.vercel.app/t/hydrology-terrain-synthesis.md) ## Combines with - [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md): A noise-perturbed initial surface avoids flat starts and seeds drainage randomly. ## Combination ideas - [Planets with rivers across cube seams](https://texelatlas.vercel.app/ideas/drainage-consistent-planets/) ## Sources 1. [primary] Guillaume Cordonnier, Jean Braun, Marie‐Paule Cani, Bedrich Benes, Éric Galin, Adrien Peytavie, Éric Guérin (2016) Large Scale Terrain Generation from Tectonic Uplift and Fluvial Erosion. Computer Graphics Forum. https://doi.org/10.1111/cgf.12820 (verified via crossref on 2026-11-29) 2. [implementation] H-Schott (2023) H-Schott/StreamPowerErosion. https://github.com/H-Schott/StreamPowerErosion License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Stream-Power Erosion (Fluvial Terrain Uplift)." https://texelatlas.vercel.app/t/stream-power-erosion/ (accessed 2026-12-01). --- id: "stroke-based-rendering" title: "Stroke-based rendering" domain: "npr" stage: "post" realtime: "offline" platforms: [cpu, python, desktop-gpu] year_introduced: 1990 inputs: [ldr-image, mesh, curves] outputs: [ldr-image, curves] style: "stylized" dynamic: "both" cost: "offline" authority: "Hertzmann, 2003" url: "https://texelatlas.vercel.app/t/stroke-based-rendering/" sources_verified_at: "2026-11-29" --- # Stroke-based rendering (Hertzmann, 2003) > Umbrella family that builds an image by placing discrete marks such as brush strokes, stipples or hatches, selected by a rule, an optimisation, or a learned model. ## Reach for it when - unsure which painterly approach to pick - want images made of strokes, stipples or hatches - turn a photo into discrete brush marks - compare ways to build an image from marks - non-photorealistic rendering from placed primitives ## How it works Every method in the family defines a stroke model (position, orientation, size, colour, texture), a source of guidance (an image, a 3D scene, a depth map) and a placement strategy. Greedy approaches pick strokes where the canvas differs most from a target; optimisation approaches minimise a loss between the rendered strokes and the source, sometimes with differentiable rasterisation; particle approaches attach strokes to 3D surfaces. Orientation fields, from gradients, a structure tensor or user input, give coherent direction. Ordering and layering (big to small, dark to light) control the final appearance. The survey organises the field by these decisions. ## When to use it Choose it as the conceptual map when picking between painterly options. Use [Painterly rendering with curved brush strokes](https://texelatlas.vercel.app/t/painterly-curved-brush-strokes.md) for a classic greedy implementation, [Painterly rendering for animation (Meier)](https://texelatlas.vercel.app/t/painterly-animation-meier.md) for 3D coherence, [Gaussian splats drawn as brush marks](https://texelatlas.vercel.app/t/sillage-brush-splatting.md) for brush marks on a Gaussian splat scene, and [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) when a filter is enough. ## Cost offline — Varies; typical algorithms are offline, with GPU variants interactive. Measured GPU Weight: 11.53× baseline (moderate) — 0.3795 ms median / 0.3961 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.03× baseline (moderate) — 0.1595 ms median (2.38× faster on L4). Ampere A100 scaling: 7.15× baseline (moderate) — 0.206 ms median (1.84× faster on A100). ## Failure modes - Visual quality depends on stroke placement heuristics, with no single correct answer - Temporal coherence has to be designed in, not assumed - Many strokes (tens of thousands) make rendering and sorting heavy - Optimisation-based methods can converge to blurry local minima ## Dataflow - Inputs: ldr-image, mesh, curves - Outputs: ldr-image, curves - Platforms: cpu, python, desktop-gpu ## Presets ### Stroke-Based Rendering — continuous 3D shading (left) vs curvature-aligned pen hatches, cross-hatching & stipples (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MARK_DENS": 10, "P_HATCH_CONTRAST": 0.85, "P_STIPPLE_MIX": 0.45, "P_SPLIT": 0.42 } ``` ```glsl const float P_MARK_DENS = 10.00; // P Mark Frequency [5.0, 18.0, 1.0] const float P_HATCH_CONTRAST = 0.85; // P Ink Contrast [0.3, 1.4, 0.05] const float P_STIPPLE_MIX = 0.45; // P Midtone Stippling [0.0, 1.0, 0.05] const float P_SPLIT = 0.42; // P Shaded / Strokes [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Classical plaster-cast sculptural form (sphere + torus ring + plinth) for engraving/SBR mark study vec2 mapBust(vec3 p, float t) { float dFloor = p.y + 0.56; vec2 res = vec2(dFloor, 1.0); vec3 rp = p; rp.xz = rot2(rp.xz, 0.35 * sin(t * 0.45)); float dSph = length(rp - vec3(0.0, 0.02, 0.0)) - 0.40; vec2 tq = vec2(length(rp.xy - vec2(0.0, 0.02)) - 0.36, rp.z); float dRing = length(tq) - 0.11; float dBust = min(dSph, dRing); if (dBust < res.x) res = vec2(dBust, 2.0); return res; } vec3 calcNormal(vec3 p, float t) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapBust(p + e.xyy, t).x - mapBust(p - e.xyy, t).x, mapBust(p + e.yxy, t).x - mapBust(p - e.yxy, t).x, mapBust(p + e.yyx, t).x - mapBust(p - e.yyx, t).x )); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float mDens = clamp(P_MARK_DENS, 4.0, 20.0); float contrast = clamp(P_HATCH_CONTRAST, 0.25, 1.5); float stipMix = clamp(P_STIPPLE_MIX, 0.0, 1.0); // Warm archival cotton drawing paper float grain = (hash21(floor(fragCoord * 0.75)) - 0.5) * 0.05; vec3 paper = vec3(0.95, 0.92, 0.85) + grain; vec3 ink = vec3(0.11, 0.13, 0.18); vec3 ro = vec3(0.0, 0.22, 2.15); vec3 rd = normalize(vec3(uv.x, uv.y - 0.06, -1.50)); vec3 lDir = normalize(vec3(0.65 * cos(iTime * 0.35 + 0.5), 0.72, 0.55)); float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapBust(ro + rd * dist, iTime); if (h.x < 0.002) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 7.5) break; } vec3 col = paper * mix(0.90, 1.0, smoothstep(-0.5, 0.5, uv.y)); if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p, iTime); float ndl = max(dot(n, lDir), 0.0); float ndv = max(dot(n, -rd), 0.0); float spec = pow(max(dot(reflect(-lDir, n), -rd), 0.0), 28.0); // Floor contact shadow float sh = (hit.y < 1.5) ? smoothstep(0.24, 0.66, length(p.xz - vec2(-0.12, -0.05))) : 1.0; float tone = clamp((0.14 + 0.82 * ndl) * sh + spec * 0.28, 0.0, 1.0); if (screenX < split) { // Left: Continuous grayscale sculptural lighting reference col = mix(vec3(0.14, 0.16, 0.20), vec3(0.93, 0.91, 0.87), tone); if (hit.y < 1.5) col = mix(paper * 0.92, col, exp(-hit.x * 0.16)); } else { // Right: Discrete Stroke-Based Rendering (curvature-oriented hatches + cross-hatch + stipples + contour!) // Surface-aligned stroke coordinates following principal surface curvature vec2 sc = (hit.y < 1.5) ? (p.xz * 1.4) : vec2(atan(n.z, n.x) * 0.55, asin(clamp(n.y, -1.0, 1.0)) * 0.95); float freq = mDens * 2.8; // Layer 1: Primary pen hatching strokes (engaged below tone < 0.78) float h1Wave = abs(sin(sc.x * freq + sc.y * freq * 0.35 + 0.6 * sin(sc.y * 5.0))); float h1Thick = clamp((0.78 - tone) * 1.35 * contrast, 0.0, 0.92); float hatch1 = smoothstep(h1Thick + 0.08, h1Thick - 0.06, h1Wave) * step(tone, 0.80); // Layer 2: Cross-hatching strokes at 60 deg (engaged in mid-deep shadows tone < 0.48) float h2Wave = abs(sin(sc.y * freq * 1.15 - sc.x * freq * 0.55)); float h2Thick = clamp((0.50 - tone) * 1.65 * contrast, 0.0, 0.92); float hatch2 = smoothstep(h2Thick + 0.08, h2Thick - 0.06, h2Wave) * step(tone, 0.52); // Layer 3: Stipple dot marks in highlight-to-midtone transition (0.42 < tone < 0.88) vec2 stGrid = fragCoord * (0.14 * mDens * 0.12 + 0.12); vec2 stCell = floor(stGrid); vec2 stF = fract(stGrid) - 0.5; vec2 stJit = (vec2(hash21(stCell + 3.1), hash21(stCell + 19.7)) - 0.5) * 0.55; float stR = clamp((0.86 - tone) * 0.48, 0.0, 0.36); float stipple = smoothstep(stR + 0.06, stR - 0.04, length(stF - stJit)) * stipMix * step(tone, 0.88); // Silhouette ink contour stroke around grazing edges float contour = (hit.y > 1.5) ? smoothstep(0.32, 0.14, ndv) : 0.0; float inkCoverage = clamp(max(max(hatch1, hatch2), max(stipple, contour)), 0.0, 1.0); // Warm sepia/cobalt wash tint under strokes vec3 wash = mix(vec3(0.84, 0.80, 0.74), paper, smoothstep(0.15, 0.75, tone)); col = mix(wash, ink, inkCoverage * 0.92); if (hit.y < 1.5) col = mix(paper * 0.94, col, exp(-hit.x * 0.16)); } } else if (screenX >= split) { // Light atmospheric sky hatch lines on paper background float skyH = smoothstep(0.08, 0.02, abs(sin(uv.y * mDens * 5.0 + 0.25 * sin(uv.x * 6.0)))) * smoothstep(0.05, 0.55, uv.y) * 0.16; col = mix(col, vec3(0.24, 0.34, 0.48), skyH); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.12, 0.14, 0.18), sep); fragColor = vec4(clamp(col, 0.0, 1.0), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [Painterly rendering for animation (Meier)](https://texelatlas.vercel.app/t/painterly-animation-meier.md) - extended by [Painterly rendering with curved brush strokes](https://texelatlas.vercel.app/t/painterly-curved-brush-strokes.md) ## Sources 1. [primary] A. Hertzmann (2003) A survey of stroke-based rendering. IEEE Computer Graphics and Applications. https://doi.org/10.1109/mcg.2003.1210867 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Stroke-based rendering." https://texelatlas.vercel.app/t/stroke-based-rendering/ (accessed 2026-12-01). --- id: "structure-from-motion-colmap" title: "Structure-from-Motion (COLMAP)" aliases: [SfM, COLMAP, incremental SfM] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, cpu] year_introduced: 2016 inputs: [photos] outputs: [camera-poses, point-cloud] style: "photoreal" dynamic: "static" cost: "offline" authority: "Schonberger & Frahm, 2016" url: "https://texelatlas.vercel.app/t/structure-from-motion-colmap/" sources_verified_at: "2026-11-29" --- # Structure-from-Motion (COLMAP) (Schonberger & Frahm, 2016) > Recovers camera poses, intrinsics and a sparse 3D point cloud from an unordered photo set by matching features and incrementally registering images with bundle adjustment. ## Reach for it when - recover camera positions from a photo collection - need sparse 3d point cloud from unordered images - photogrammetry pipeline starting point - prepare camera poses for nerf or splat training ## How it works Local features (SIFT by default) are extracted per image and matched between candidate pairs, then geometrically verified with fundamental or essential matrix estimation to build a scene graph. Incremental SfM seeds a reconstruction from a well-conditioned image pair, triangulates points, and repeatedly registers the next best image with PnP. After each registration it triangulates new points and runs local, and periodically global, bundle adjustment, refining poses, intrinsics and points together by minimising reprojection error. Outlier tracks are filtered and drift is limited by re-triangulation and loop-closure-like track merging. The output is a sparse model plus calibrated cameras, which is exactly the input that NeRF and Gaussian splatting pipelines expect. Dense geometry needs a separate multi-view stereo step. ## When to use it Choose it as the default pose-estimation front end for any radiance-field or splat capture from ordinary photos or video frames. Prefer [DUSt3R](https://texelatlas.vercel.app/t/dust3r.md) or [VGGT (Visual Geometry Grounded Transformer)](https://texelatlas.vercel.app/t/vggt.md) when you have very few views, little texture, or need poses in seconds rather than minutes. Prefer [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md) after it when you need a dense surface rather than camera poses. ## Cost offline — Minutes to hours depending on image count; matching is the bottleneck and scales roughly quadratically unless a vocabulary tree or sequential matcher is used. ## Failure modes - Texture-poor, reflective or transparent surfaces yield few verified matches, so images fail to register or the model splits into disconnected components - Repetitive structure (facades, tiles) produces false matches that fold the reconstruction onto itself - Pure rotation or near-planar scenes make the initial pair degenerate, giving a bad seed and drift - Result has arbitrary scale and orientation; metric units need a known distance or GPS ## Engine support - blender: plugin — `Blender add-on: Photogrammetry Importer (imports COLMAP reconstructions)` (evidence: https://github.com/SBCV/Blender-Addon-Photogrammetry-Importer, checked 2026-12-01) — Imports results; the SfM itself runs in COLMAP. ## Dataflow - Inputs: photos - Outputs: camera-poses, point-cloud - Platforms: cuda, cpu ## Presets ### COLMAP default SIFT reconstruction settings (json-params; parameter preset) ```json { "feature_extractor.SiftExtraction.max_image_size": 3200, "feature_extractor.SiftExtraction.max_num_features": 8192, "camera_model": "SIMPLE_RADIAL", "single_camera": true, "matcher": "exhaustive_matcher", "mapper.ba_global_function_tolerance": 0.000001 } ``` Attribution: Parameter names follow colmap/colmap (BSD-3-Clause); values are the commonly used defaults, written for this index. ## Combines with - [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md): COLMAP supplies camera poses and the sparse point cloud that initialise the Gaussians. - [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md): SfM poses and sparse points are the input to dense depth-map estimation. ## Sources 1. [primary] Johannes L. Schonberger, Jan-Michael Frahm (2016) Structure-from-Motion Revisited. 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/cvpr.2016.445 (verified via crossref on 2026-11-29) 2. [implementation] colmap (2014) colmap/colmap. https://github.com/colmap/colmap License: NOASSERTION. (verified via github on 2026-11-29) 3. [tutorial] COLMAP authors COLMAP documentation. colmap.github.io. https://colmap.github.io/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Structure-from-Motion (COLMAP)." https://texelatlas.vercel.app/t/structure-from-motion-colmap/ (accessed 2026-12-01). --- id: "stylized-gaussian-splatting" title: "Stylized Gaussian splatting (G-Style)" domain: "npr" stage: "capture" realtime: "interactive" platforms: [cuda, python, desktop-gpu] year_introduced: 2024 inputs: [gaussians, ldr-image] outputs: [gaussians] style: "stylized" dynamic: "static" cost: "offline" authority: "Kovács et al., 2024" url: "https://texelatlas.vercel.app/t/stylized-gaussian-splatting/" sources_verified_at: "2026-11-29" --- # Stylized Gaussian splatting (G-Style) (Kovács et al., 2024) > Restyles a trained Gaussian splat scene to match a reference image's style by optimising splat colours (and geometry) with a style loss, then renders it at normal splat speeds. ## Reach for it when - want my splat scene restyled like a reference image - need artistic look that still runs in a normal splat viewer - style transfer on a captured 3d scene - make a photo capture look like a painting ## How it works A scene is first reconstructed with ordinary 3D Gaussian splatting. A style image is then given, and the splat parameters are optimised with a loss computed on rendered views, combining a Gram-matrix-style statistic from a pretrained network with content preservation. The method adds measures to keep geometry stable, such as pruning and control over densification, so that stylization does not introduce floaters. After optimisation, the stylised scene is just another splat file and renders in real time with any splat viewer. The approach is from the arbitrary-style-transfer line applied to a point-based representation. ## When to use it Choose it when you need a stylised splat scene that still runs in a normal splat viewer. Prefer [Gaussian splats drawn as brush marks](https://texelatlas.vercel.app/t/sillage-brush-splatting.md) for painting by replacing the splat footprint at render time without a per-style optimisation step. ## Cost offline — Optimisation takes minutes per style on a desktop GPU; rendering is standard splat cost. Measured GPU Weight: 97.14× baseline (extreme) — 3.1958 ms median / 3.2733 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 87.4× baseline (extreme) — 1.3896 ms median (2.3× faster on L4). Ampere A100 scaling: 70.11× baseline (extreme) — 2.0193 ms median (1.58× faster on A100). ## Failure modes - Style is baked into the splats; changing style means re-optimising - Multi-view inconsistency can show as flicker between views - Geometry is only weakly altered, so strong stylisation of shape is limited - Depends on a good base reconstruction ## Dataflow - Inputs: gaussians, ldr-image - Outputs: gaussians - Platforms: cuda, python, desktop-gpu ## Presets ### Stylized Gaussian Splatting (G-Style) — photorealistic 3D Gaussian splats (left) vs style-optimized Van Gogh / Fauvist splat scene (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_STYLE_STR": 0.9, "P_SWIRL": 0.7, "P_ORBIT": 0.5, "P_SPLIT": 0.48 } ``` ```glsl const float P_STYLE_STR = 0.90; // P Style Loss Weight [0.0, 1.0, 0.05] const float P_SWIRL = 0.70; // P Chromatic Swirl [0.0, 1.2, 0.05] const float P_ORBIT = 0.50; // P Camera Orbit [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Photoreal / G-Style [0.0, 1.0, 0.02] vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isStyled = screenX >= split; float styleStr = clamp(P_STYLE_STR, 0.0, 1.0); float swirlAmt = clamp(P_SWIRL, 0.0, 1.3); float t = iTime * max(P_ORBIT, 0.0); // Photorealistic neutral studio sky vs Starry-Night cobalt-and-gold stylized sky vec3 photoBg = mix(vec3(0.14, 0.16, 0.20), vec3(0.32, 0.38, 0.46), smoothstep(-0.45, 0.55, uv.y)); float skyFlow = sin(uv.x * 9.0 + sin(uv.y * 7.0 + t * 0.3) * 1.8) * cos(uv.y * 10.0 - uv.x * 5.0); vec3 styleBg = mix(vec3(0.05, 0.12, 0.34), vec3(0.16, 0.42, 0.72), 0.5 + 0.5 * skyFlow); styleBg += vec3(0.98, 0.80, 0.22) * smoothstep(0.62, 0.96, skyFlow) * 0.45; vec3 bg = isStyled ? mix(photoBg, styleBg, styleStr) : photoBg; vec3 accum = vec3(0.0); float trans = 1.0; // 36 3D Gaussian splats forming an orbiting architectural arch + floating centerpiece for (int i = 0; i < 36; i++) { float fi = float(i); float u = fi / 36.0; vec3 p3; vec3 photoCol; if (i < 22) { // Sculptural 3D torus/arch ring float ang = (fi / 22.0) * 6.2831853; p3 = vec3(0.38 * cos(ang), 0.30 * sin(ang), 0.12 * sin(ang * 2.0)); photoCol = mix(vec3(0.68, 0.64, 0.58), vec3(0.84, 0.78, 0.70), 0.5 + 0.5 * sin(ang)); } else { // Inner botanical/ceramic core cluster float ang = ((fi - 22.0) / 14.0) * 6.2831853 * 2.0; float yy = ((fi - 22.0) / 14.0 - 0.5) * 0.36; p3 = vec3(0.16 * cos(ang), yy, 0.16 * sin(ang)); photoCol = mix(vec3(0.28, 0.46, 0.36), vec3(0.74, 0.36, 0.28), (fi - 22.0) / 14.0); } p3.xz = rot2(p3.xz, t * 0.62); p3.yz = rot2(p3.yz, 0.18 * sin(t * 0.45)); float zCam = 1.85 - p3.z; vec2 proj = p3.xy / max(zCam * 0.64, 0.3); vec2 d = uv - proj; // Style-optimized G-Style aligns splat covariance ellipses tangentially along painterly swirl flow // and transfers Gram-matrix chromatic contrast (ultramarine shadows + cadmium yellow/vermilion highlights!) float photoAng = fi * 0.7; float flowAng = atan(p3.y, p3.x) + 1.5708 + 0.55 * swirlAmt * sin(p3.x * 5.0 + p3.y * 4.0); float angUse = isStyled ? mix(photoAng, flowAng, styleStr) : photoAng; vec2 dl = rot2(d, -angUse); vec2 axisPhoto = vec2(0.088, 0.068) / max(zCam * 0.58, 0.35); vec2 axisStyle = vec2(0.125 * (1.0 + 0.25 * swirlAmt), 0.042) / max(zCam * 0.58, 0.35); vec2 axis = isStyled ? mix(axisPhoto, axisStyle, styleStr) : axisPhoto; vec2 q = dl / axis; // 3D directional lighting on splat center vec3 approxN = normalize(p3 + vec3(0.0, 0.05, 0.15)); float ndl = max(dot(approxN, normalize(vec3(0.6, 0.7, 0.5))), 0.0); vec3 litPhoto = photoCol * (0.28 + 0.88 * ndl); // G-Style optimized splat spherical-harmonics color palette (bold Fauvist/Post-Impressionist transfer) vec3 stylePal = mix(vec3(0.09, 0.24, 0.68), vec3(0.98, 0.42, 0.14), smoothstep(0.15, 0.62, ndl)); stylePal = mix(stylePal, vec3(1.0, 0.88, 0.26), smoothstep(0.58, 0.92, ndl)); if (i >= 22) stylePal = mix(vec3(0.12, 0.72, 0.58), vec3(1.0, 0.62, 0.18), 0.5 + 0.5 * sin(fi * 1.4)); vec3 splatCol = isStyled ? mix(litPhoto, stylePal, styleStr) : litPhoto; float g = exp(-0.5 * dot(q, q)); // Stylized splats sharpen opacity profile slightly for crisp painterly ribbons float alpha = isStyled ? mix(g * 0.78, smoothstep(0.24, 0.72, g) * 0.90, styleStr * 0.75) : (g * 0.78); if (alpha > 0.01) { accum += splatCol * alpha * trans; trans *= (1.0 - alpha * 0.64); } } vec3 col = accum + bg * trans; float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.96, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Áron S. Kovács, Pedro Hermosilla, Renata G. Raidou (2024) 𝒢‐Style: Stylized Gaussian Splatting. Computer Graphics Forum. https://doi.org/10.1111/cgf.15259 (verified via crossref on 2026-11-29) 2. [primary] Bernhard Kerbl, Georgios Kopanas, Thomas Leimkuehler, George Drettakis (2023) 3D Gaussian Splatting for Real-Time Radiance Field Rendering. ACM Transactions on Graphics. https://doi.org/10.1145/3592433 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Stylized Gaussian splatting (G-Style)." https://texelatlas.vercel.app/t/stylized-gaussian-splatting/ (accessed 2026-12-01). --- id: "stylized-nonlinear-monte-carlo" title: "Stylized nonlinear Monte Carlo rendering" domain: "npr" stage: "lighting" realtime: "offline" platforms: [cuda, cpu] year_introduced: 2025 inputs: [mesh, material-params] outputs: [hdr-image, ldr-image] style: "stylized" dynamic: "both" cost: "offline" authority: "Tong & Hachisuka, 2025" url: "https://texelatlas.vercel.app/t/stylized-nonlinear-monte-carlo/" sources_verified_at: "2026-11-29" --- # Stylized nonlinear Monte Carlo rendering (Tong & Hachisuka, 2025) > Applies nonlinear artistic operators inside the path-tracing estimator, so stylization such as banding or thresholding is applied to light transport before it is averaged. ## Reach for it when - stylisation breaks when path tracing averages samples - toon banding on indirect light in offline renders - thresholded shading gets noisy or washed out in pt - need stylised global illumination in film rendering - art operators applied before averaging light ## How it works Ordinary path tracing averages unbiased samples, so applying a nonlinear stylisation (a toon ramp, a threshold) to the final pixel average is not the same as applying it inside the light-transport integral. The paper studies rendering in which artist-defined nonlinear operators act within the Monte Carlo estimator, so that stylisation becomes part of how light bounces (for example banded or thresholded indirect lighting), and develops practical estimators for evaluating those nonlinear expressions from path samples. The result is stylised global illumination rather than a stylised final image. A reference implementation accompanies the paper; see the sources for the project page and code ## When to use it Choose it for offline stylised films or stills where indirect light must stay stylised. Prefer [Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md) for real-time use where only direct lighting is shaded in toon style, and [Guilty Gear Xrd anime-style 3D shading](https://texelatlas.vercel.app/t/guilty-gear-xrd-shading.md) for artist-directed real-time looks. ## Cost offline — Offline path-tracing cost; the nonlinearity needs extra samples or estimators for low noise. Measured GPU Weight: 61.52× baseline (extreme) — 2.024 ms median / 2.1282 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 58.54× baseline (heavy) — 0.9308 ms median (2.17× faster on L4). Ampere A100 scaling: 40.69× baseline (heavy) — 1.172 ms median (1.73× faster on A100). ## Failure modes - Nonlinear functions amplify noise, so more samples are needed than for a plain path tracer - Nonlinear estimators can trade bias against variance - Hard to preview interactively - Reference code repository is archived ## Dataflow - Inputs: mesh, material-params - Outputs: hdr-image, ldr-image - Platforms: cuda, cpu ## Presets ### Stylized Nonlinear Monte Carlo — post-average toon ramp (left) vs in-integrator nonlinear sample stylization (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BANDS": 4, "P_PENUMBRA": 0.75, "P_BOUNCE_STYLE": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_BANDS = 4.00; // P Toon Bands [2.0, 6.0, 1.0] const float P_PENUMBRA = 0.75; // P Area Light Size [0.15, 1.3, 0.05] const float P_BOUNCE_STYLE = 0.85; // P Nonlinear Bounce [0.0, 1.2, 0.05] const float P_SPLIT = 0.48; // P Post-Toon / NL-MC [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Nonlinear artistic stylization operator phi(L): quantizes luminance into crisp chromatic ink bands! vec3 nonlinearOp(vec3 rad, float bands) { float lum = dot(rad, vec3(0.299, 0.587, 0.114)); float qLum = floor(clamp(lum, 0.0, 1.4) * bands + 0.35) / bands; // Subtle artistic warm-highlight / cool-shadow chromatic shift inside the operator vec3 tint = mix(vec3(0.72, 0.84, 1.16), vec3(1.14, 0.98, 0.82), clamp(qLum, 0.0, 1.0)); return (rad / max(lum, 0.02)) * qLum * tint; } vec2 mapRoom(vec3 p) { float dFloor = p.y + 0.54; vec2 res = vec2(dFloor, 1.0); // Coral bounce wall on left float dWall = p.x + 1.05; if (dWall < res.x) res = vec2(dWall, 2.0); // Hero central ceramic sphere float dSph1 = length(p - vec3(0.06, -0.14, -0.05)) - 0.40; if (dSph1 < res.x) res = vec2(dSph1, 3.0); // Floating small blocker orb casting a rich soft penumbra across sphere & floor! float dSph2 = length(p - vec3(0.32, 0.36, 0.25)) - 0.16; if (dSph2 < res.x) res = vec2(dSph2, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapRoom(p + e.xyy).x - mapRoom(p - e.xyy).x, mapRoom(p + e.yxy).x - mapRoom(p - e.yxy).x, mapRoom(p + e.yyx).x - mapRoom(p - e.yyx).x )); } float softShadowRay(vec3 p, vec3 lPos) { vec3 toL = lPos - p; float dL = length(toL); vec3 dir = toL / max(dL, 1e-4); float t = 0.03; for (int i = 0; i < 20; i++) { float h = mapRoom(p + dir * t).x; if (h < 0.003) return 0.0; t += max(h, 0.03); if (t > dL - 0.04) break; } return 1.0; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isNLMC = screenX >= split; float bands = clamp(floor(P_BANDS + 0.5), 2.0, 6.0); float lightR = clamp(P_PENUMBRA, 0.10, 1.4) * 0.42; float bStyle = clamp(P_BOUNCE_STYLE, 0.0, 1.4); vec3 ro = vec3(0.12, 0.24, 2.22); vec3 rd = normalize(vec3(uv.x, uv.y - 0.08, -1.48)); vec3 col = mix(vec3(0.08, 0.11, 0.18), vec3(0.20, 0.28, 0.42), smoothstep(-0.4, 0.5, uv.y)); float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapRoom(ro + rd * dist); if (h.x < 0.002) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 8.0) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 alb = vec3(0.84, 0.82, 0.78); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.92, 0.34, 0.24); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.92, 0.86, 0.76); else if (hit.y > 3.5) alb = vec3(0.22, 0.68, 0.84); // Area light center orbiting gently overhead vec3 areaCenter = vec3(0.72 + 0.22 * cos(iTime * 0.5), 1.05, 0.62 + 0.22 * sin(iTime * 0.5)); // Evaluate 8 stratified Monte Carlo light-transport samples across the area light & bounce hemisphere: // Left (Post-process toon): linear average FIRST, then apply phi(E[L]) -> harsh binary cut, flat indirect! // Right (Nonlinear MC): apply phi(L_i) INSIDE the estimator E[phi(L)] -> smooth painterly penumbra transitions // AND vivid quantized coral indirect bounce bands! vec3 linearAcc = vec3(0.0); vec3 nlAcc = vec3(0.0); float jitter = hash21(floor(fragCoord) * 0.5) * 6.2831853; for (int s = 0; s < 8; s++) { float fs = float(s); float ang = (fs / 8.0) * 6.2831853 + jitter * 0.25; float rr = sqrt((fs + 0.5) / 8.0) * lightR; vec3 lPt = areaCenter + vec3(cos(ang) * rr, 0.0, sin(ang) * rr); vec3 lDir = normalize(lPt - p); float vis = softShadowRay(p + n * 0.01, lPt); float ndl = max(dot(n, lDir), 0.0); // Colored indirect bounce contribution from coral left wall (x = -1.05) float wallFactor = max(dot(n, normalize(vec3(-1.05, 0.0, 0.0) - p)), 0.0) / (0.65 + (p.x + 1.05) * (p.x + 1.05)); vec3 bounceS = vec3(0.96, 0.36, 0.24) * wallFactor * (0.45 + 0.55 * sin(ang) * 0.3 + 0.35) * bStyle; vec3 skyS = vec3(0.22, 0.34, 0.54) * (0.5 + 0.5 * n.y) * 0.36; vec3 sampleRad = alb * (vec3(1.28, 1.18, 1.02) * ndl * vis + bounceS + skyS); linearAcc += sampleRad; nlAcc += nonlinearOp(sampleRad, bands); } vec3 avgLinear = linearAcc * 0.125; vec3 avgNL = nlAcc * 0.125; if (!isNLMC) { // Left: Standard post-process toon ramp phi(E[L]) -- rigid stair-step contour cutting penumbra harshly col = nonlinearOp(avgLinear, bands); } else { // Right: Stylized Nonlinear Monte Carlo E[phi(L)] -- rich ink-wash penumbra + vibrant banded indirect bounce! col = avgNL; } if (hit.y < 1.5) col = mix(vec3(0.08, 0.11, 0.18), col, exp(-hit.x * 0.10)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.96, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Toon-banded bounce light, learned live](https://texelatlas.vercel.app/ideas/stylized-bounce-radiance-cache/) ## Sources 1. [primary] Xiaochun Tong, Toshiya Hachisuka (2025) Practical Stylized Nonlinear Monte Carlo Rendering. Proceedings of the Special Interest Group on Computer Graphics and Interactive Techniques Conference Conference Papers. https://doi.org/10.1145/3721238.3730686 (verified via crossref on 2026-11-29) 2. [implementation] LuisaGroup (2025) LuisaGroup/practical-stylized. https://github.com/LuisaGroup/practical-stylized (verified via github on 2026-11-29) 3. [primary] Toshiya Hachisuka Toshiya Hachisuka's page (paper link). cs.uwaterloo.ca. https://cs.uwaterloo.ca/~thachisu (verified via http on 2026-11-29) ## Cite this entry Texel. "Stylized nonlinear Monte Carlo rendering." https://texelatlas.vercel.app/t/stylized-nonlinear-monte-carlo/ (accessed 2026-12-01). --- id: "suggestive-contours" title: "Suggestive contours" domain: "npr" stage: "material" realtime: "interactive" platforms: [desktop-gpu, cpu, webgl2] year_introduced: 2003 inputs: [mesh, normals] outputs: [curves, ldr-image] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "DeCarlo et al., 2003" url: "https://texelatlas.vercel.app/t/suggestive-contours/" sources_verified_at: "2026-11-29" --- # Suggestive contours (DeCarlo et al., 2003) > Line-drawing technique that adds, beyond true silhouettes, lines at places where a contour would appear under a small viewpoint change, conveying shape the way an artist's sketch does. ## Reach for it when - line drawing misses important shape features - silhouettes alone don't convey the model's form - non-photorealistic line art from 3d mesh - illustration style outlines that show hidden ridges ## How it works True contours occur where the surface normal is perpendicular to the view vector. Suggestive contours are the nearby points where the surface is a minimum of the normal-dot-view function along the view-projected direction; equivalently, the radial curvature crosses zero while the derivative of curvature along the view direction is positive. These loci can be computed per vertex, linearly interpolated across triangles to extract line segments, and drawn with thickness by view-dependent criteria. Because they depend on the camera, they must be recomputed every frame or approximated in image space. Subsequent work added temporal coherence and GPU evaluation. ## When to use it Choose it when you need line-art depiction of smooth organic shapes, such as anatomy or scanned sculptures, that silhouettes alone render as a bare outline. Prefer [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md) when you want a cheap image-space look for hard-surface scenes, and [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md) for plain game-style outlines. It is not a good fit for noisy meshes. ## Cost medium — Per-vertex curvature derivatives plus line extraction each frame; interactive on CPU for moderate meshes, cheap on GPU after precomputation. Measured GPU Weight: 68.97× baseline (extreme) — 2.2692 ms median / 2.4881 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 52.15× baseline (heavy) — 0.8292 ms median (2.74× faster on L4). Ampere A100 scaling: 41.37× baseline (heavy) — 1.1914 ms median (1.9× faster on A100). ## Failure modes - Needs clean, well-tessellated smooth meshes; noisy scans produce spurious squiggles - Curvature derivative estimation is sensitive to mesh quality and sampling - Lines flicker or pop in animation without temporal smoothing - Creates no lines on flat or developable surfaces ## Engine support - blender: builtin — `View Layer Properties > Freestyle Line Set > Edge Types > Suggestive Contour` (evidence: https://docs.blender.org/manual/en/5.2/render/freestyle/view_layer/freestyle.html, checked 2026-12-01) ## Dataflow - Inputs: mesh, normals - Outputs: curves, ldr-image - Platforms: desktop-gpu, cpu, webgl2 ## Presets ### Suggestive contours — radial curvature D_w(N·V)=0 ink lines on 3D sculpted form (glsl-fragment; rendered 2026-11-30) ```json { "P_CONTOUR_WIDTH": 1, "P_SUGGESTIVE_TH": 0.48, "P_PAPER_TONE": 0.62, "P_SPIN_SPEED": 1 } ``` ```glsl const float P_CONTOUR_WIDTH = 1.0; // P Ink Width [0.4, 2.2, 0.05] const float P_SUGGESTIVE_TH = 0.48; // P Suggestive Sens [0.1, 1.0, 0.02] const float P_PAPER_TONE = 0.62; // P Wash Shading [0.0, 1.0, 0.02] const float P_SPIN_SPEED = 1.0; // P Turntable Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } // Sculpted organic classical bust/metaball form with rich concave valleys & cheekbones // (concave inflections are exactly where DeCarlo suggestive contours emerge!) float mapSculpt(vec3 p) { vec3 q = p; q.xz = rot2(iTime * 0.42 * max(P_SPIN_SPEED, 0.0) + 0.35) * q.xz; q.yz = rot2(0.18 * sin(iTime * 0.35)) * q.yz; // Torus core blended with sculpted lobes to form valleys, brow ridges & flutes vec2 tq = vec2(length(q.xz) - 0.56, q.y); float dTorus = length(tq) - 0.28; float dHead = length(q - vec3(0.0, 0.24, 0.0)) - 0.46; float dChin = length(q - vec3(0.0, -0.34, 0.22)) - 0.34; float d = smin(dTorus, dHead, 0.26); d = smin(d, dChin, 0.24); // Subtle carved organic flutes producing vivid radial-curvature valleys float ang = atan(q.z, q.x); d += 0.048 * sin(ang * 5.0 + q.y * 4.5) * smoothstep(0.15, 0.65, length(q.xz)); d += 0.032 * cos(q.y * 9.5 - q.x * 3.5); return d * 0.72; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSculpt(p + e.xyy) - mapSculpt(p - e.xyy), mapSculpt(p + e.yxy) - mapSculpt(p - e.yxy), mapSculpt(p + e.yyx) - mapSculpt(p - e.yyx) )); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.04, 2.02); vec3 rd = normalize(vec3(uv, -1.55)); // Warm museum sketchbook paper with fine fiber grain float grain = 0.97 + 0.03 * sin(uv.x * 210.0 + sin(uv.y * 140.0)) * cos(uv.y * 195.0); vec3 paper = vec3(0.955, 0.925, 0.865) * grain; vec3 col = paper * (1.0 - 0.14 * dot(uv, uv)); float t = 0.0; bool hit = false; for (int i = 0; i < 68; i++) { float d = mapSculpt(ro + rd * t); if (d < 0.0018) { hit = true; break; } t += d; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 v = -rd; float ndv = dot(n, v); // Projected view vector w onto the surface tangent plane: w = normalize(v - (n·v) n) vec3 wRaw = v - n * ndv; float wLen = length(wRaw) + 1e-4; vec3 w = wRaw / wLen; // Evaluate DeCarlo directional derivatives along w in the tangent plane: // Radial curvature k_r proportional to D_w(n·v) = (n(p+eps*w)·v - n(p-eps*w)·v) / (2*eps) float eps = 0.014; vec3 pPlus = p + w * eps; vec3 pMinus = p - w * eps; // Project back onto isosurface for exact surface derivative pPlus -= calcNormal(pPlus) * mapSculpt(pPlus); pMinus -= calcNormal(pMinus) * mapSculpt(pMinus); float ndvPlus = dot(calcNormal(pPlus), normalize(ro - pPlus)); float ndvMinus = dot(calcNormal(pMinus), normalize(ro - pMinus)); // First derivative D_w(N·V) ~ 0 at suggestive contours float dw = (ndvPlus - ndvMinus) / (2.0 * eps); // Second derivative D_w^2(N·V) > 0 guarantees local MINIMUM of N·V (concave valley, not ridge!) float d2w = (ndvPlus - 2.0 * ndv + ndvMinus) / (eps * eps); float wScale = clamp(P_CONTOUR_WIDTH, 0.35, 2.5); float sens = clamp(P_SUGGESTIVE_TH, 0.08, 1.1); // 1) True occluding silhouette contour: N·V -> 0 float occluding = smoothstep(0.28 * wScale, 0.08 * wScale, ndv); // 2) Suggestive contour: D_w(N·V) crosses 0 with positive second derivative d2w > threshold // and grazing filter so front-facing flat spots do not trigger noise float nearZeroDw = exp(-pow(dw / (0.34 * wScale), 2.0)); float posCurv = smoothstep(0.65 / sens, 3.8 / sens, d2w); float viewWindow = smoothstep(0.92, 0.35, ndv) * smoothstep(0.06, 0.16, ndv); float suggestive = clamp(nearZeroDw * posCurv * viewWindow * 1.35, 0.0, 1.0); // Subtle soft archival wash + cool/warm technical pencil tint vec3 lDir = normalize(vec3(0.58, 0.78, 0.55)); float diff = max(dot(n, lDir), 0.0); float washAmt = clamp(P_PAPER_TONE, 0.0, 1.0); vec3 warmPaper = vec3(0.96, 0.93, 0.87); vec3 coolShadow = vec3(0.56, 0.63, 0.72); vec3 surfCol = mix(warmPaper, mix(coolShadow, warmPaper, 0.25 + 0.75 * diff), washAmt); // Distinct ink hierarchy: deep charcoal for true contours, rich sepia-slate ink for suggestive contours vec3 contourInk = vec3(0.06, 0.065, 0.085); vec3 suggInk = vec3(0.16, 0.19, 0.28); col = mix(surfCol, suggInk, suggestive * 0.92); col = mix(col, contourInk, occluding * 0.96); } fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Sources 1. [primary] Doug DeCarlo, Adam Finkelstein, Szymon Rusinkiewicz, Anthony Santella (2003) Suggestive contours for conveying shape. ACM Transactions on Graphics. https://doi.org/10.1145/882262.882354 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Suggestive contours." https://texelatlas.vercel.app/t/suggestive-contours/ (accessed 2026-12-01). --- id: "surface-gradient-bump-mapping" title: "Surface gradient based bump mapping framework" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2020 inputs: [normals, texture, mesh] outputs: [normals] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Mikkelsen" url: "https://texelatlas.vercel.app/t/surface-gradient-bump-mapping/" sources_verified_at: "2026-11-29" --- # Surface gradient based bump mapping framework (Mikkelsen) > Mikkelsen's framework for combining bump, normal and procedural height maps in any projection by summing surface gradients rather than blending normals. Removes tangent-space dependence and makes triplanar, decals and layering consistent. ## Reach for it when - blending normal maps gives wrong flattened detail - layering decals, triplanar and detail normals looks off - mesh has no reliable tangents - need consistent combining of bump sources ## How it works A surface gradient is the 2D-slope vector of a height perturbation expressed in the tangent plane of the unperturbed geometric normal. Because gradients simply add, any number of perturbations (UV normal maps, triplanar projections, procedural bumps, decals) can be accumulated as sum of gradients and resolved once into a final perturbed normal: n' = normalize(n - grad). Mikkelsen gives resolve routines for UV-mapped data (using the screen-space derivatives of position and texture coordinates, i.e. the MikkTSpace-compatible basis), for world-space and object-space normal data, and for height maps with dFdx/dFdy. It avoids the artifacts of lerp-ing normals and handles flipped or mirrored UVs deterministically. ## When to use it Choose it when layering several normal sources (terrain triplanar plus detail, decals, wetness ripples) or when a mesh lacks reliable tangents. Prefer plain [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) for a single UV-mapped normal map with baked tangents. Pair with [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md) and [Hex-tiling](https://texelatlas.vercel.app/t/hex-tiling.md) for blended world-space normals. ## Cost cheap — Derivative-based basis plus a few vector ops; slightly more ALU than a tangent-frame fetch. Measured GPU Weight: 10.16× baseline (moderate) — 0.3341 ms median / 0.3452 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.77× baseline (moderate) — 0.1236 ms median (2.7× faster on L4). Ampere A100 scaling: 6.32× baseline (moderate) — 0.1819 ms median (1.84× faster on A100). ## Failure modes - Screen-space derivative bases break at helper-pixel quad boundaries and on very small triangles - Height-map bump from derivatives yields faceted look if the height is low resolution or under-filtered - Gradient scale must be unit-consistent across sources or contributions mix wrongly - Differences from baked tangent-space shading mean authored normal maps may look slightly different ## Engine support - babylonjs: builtin — `bumpFragmentMainFunctions.fx perturbNormal screen-space surface-gradient perturbation` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Shaders/ShadersInclude/bumpFragmentMainFunctions.fx, checked 2026-12-01) - threejs: builtin — `material.bumpMap = texture` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/display/BumpMapNode.js, checked 2026-12-01) — Derivative-based bump map after Mikkelsen's surface-gradient paper. - unity: builtin — `HDRP Lit normal and detail mapping (always on)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl, checked 2026-12-01) — HDRP shaders blend normals via the surface-gradient framework. ## Dataflow - Inputs: normals, texture, mesh - Outputs: normals - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Surface Gradient Bump Mapping — UV tangent seam & pole pinch (left) vs tangent-free surface gradient (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_BUMP_FREQ": 12, "P_GRAD_STR": 0.85, "P_ROT_SPEED": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_BUMP_FREQ = 12.0; // P Bump Scale [5.0, 22.0, 0.5] const float P_GRAD_STR = 0.85; // P Gradient Strength [0.1, 1.6, 0.05] const float P_ROT_SPEED = 0.55; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P UV Seam / SurfGrad [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // 3D volumetric procedural bump scalar field h(p) (gyroid + cellular dimples) float bumpField3D(vec3 p, float freq) { vec3 q = p * freq; float g = sin(q.x) * cos(q.y) + sin(q.y) * cos(q.z) + sin(q.z) * cos(q.x); float fine = 0.45 * sin(q.x * 2.1 + q.z * 1.9) * cos(q.y * 2.3); return g * 0.5 + fine; } // Mikkelsen (2020) tangent-free Surface Gradient: project 3D gradient onto surface tangent plane! // surfGrad = grad3D - n * dot(n, grad3D), then n_perturbed = normalize(n - str * surfGrad) vec3 resolveSurfaceGradient(vec3 p, vec3 n, float freq, float str) { float e = 0.004; vec3 grad3D = vec3( bumpField3D(p + vec3(e, 0.0, 0.0), freq) - bumpField3D(p - vec3(e, 0.0, 0.0), freq), bumpField3D(p + vec3(0.0, e, 0.0), freq) - bumpField3D(p - vec3(0.0, e, 0.0), freq), bumpField3D(p + vec3(0.0, 0.0, e), freq) - bumpField3D(p - vec3(0.0, 0.0, e), freq) ) / (2.0 * e); // Also layer a second triplanar height bump using pure additive surface gradients! vec3 surfGrad = grad3D - n * dot(n, grad3D); return normalize(n - surfGrad * (str * 0.045)); } // Sculpted organic knob / pinched sphere showing poles & seam clearly float mapSculpt(vec3 p) { float d1 = length(p) - 0.68; float d2 = length(vec2(length(p.xz) - 0.52, p.y)) - 0.24; float h = clamp(0.5 + 0.5 * (d2 - d1) / 0.18, 0.0, 1.0); return (mix(d2, d1, h) - 0.18 * h * (1.0 - h)) * 0.85; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSculpt(p + e.xyy) - mapSculpt(p - e.xyy), mapSculpt(p + e.yxy) - mapSculpt(p - e.yxy), mapSculpt(p + e.yyx) - mapSculpt(p - e.yyx) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSurfGrad = screenX >= split; float freq = clamp(P_BUMP_FREQ, 4.0, 24.0); float str = clamp(P_GRAD_STR, 0.05, 1.8); float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.48; vec3 ro = vec3(0.0, 0.32, 2.28); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.06), -1.52)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 col = mix(vec3(0.022, 0.028, 0.048), vec3(0.060, 0.076, 0.122), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapSculpt(ro + rd * t); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 nGeo = calcNormal(p); vec3 n; float seamAlert = 0.0; if (isSurfGrad) { // Right: Mikkelsen tangent-space-free Surface Gradient Bump Mapping (zero seams, zero pole pinching!) n = resolveSurfaceGradient(p, nGeo, freq, str); } else { // Left: Naive spherical UV-mapped tangent-space bump (suffers atan seam flip & severe north-pole distortion!) vec3 pn = normalize(p + vec3(1e-5)); float uS = atan(pn.z, pn.x) / 6.2831853 + 0.5; float vS = asin(clamp(pn.y, -0.999, 0.999)) / 3.14159265 + 0.5; vec2 suv = vec2(uS * 3.0, vS * 1.5) * freq; float e = 0.03; float h0 = sin(suv.x) * cos(suv.y) + 0.45 * sin(suv.x * 2.1) * cos(suv.y * 2.3); float hx = sin(suv.x + e) * cos(suv.y) + 0.45 * sin((suv.x + e) * 2.1) * cos(suv.y * 2.3); float hy = sin(suv.x) * cos(suv.y + e) + 0.45 * sin(suv.x * 2.1) * cos((suv.y + e) * 2.3); vec3 tang = normalize(cross(vec3(0.0, 1.0, 0.0), nGeo) + vec3(1e-4, 0.0, 0.0)); vec3 bitang = cross(nGeo, tang); // Tangent sign flips across UV seam & stretches near poles! float seamSign = (pn.x > 0.0 && abs(pn.z) < 0.04) ? -1.0 : 1.0; seamAlert = smoothstep(0.06, 0.01, abs(pn.z)) * step(0.0, pn.x) + smoothstep(0.82, 0.98, abs(pn.y)); n = normalize(nGeo - (tang * ((hx - h0) / e) * seamSign + bitang * ((hy - h0) / e)) * str * 0.25); } vec3 l1 = normalize(vec3(0.62, 0.78, 0.52)); vec3 l2 = normalize(vec3(-0.68, 0.15, -0.58)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 42.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 bronze = mix(vec3(0.24, 0.46, 0.62), vec3(0.86, 0.64, 0.34), 0.5 + 0.5 * n.y); col = bronze * (0.24 + 0.85 * diff1 + 0.26 * diff2) + vec3(1.0, 0.96, 0.90) * spec * 0.62 + vec3(0.26, 0.80, 0.96) * fres * 0.32; if (!isSurfGrad) { // Tint UV seam & pole pinch artifacts in warning crimson col = mix(col, vec3(0.95, 0.24, 0.30), clamp(seamAlert * 0.42, 0.0, 0.65)); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Reoriented normal map blending (detail normals)](https://texelatlas.vercel.app/t/reoriented-normal-mapping.md) ## Combines with - [Triplanar mapping](https://texelatlas.vercel.app/t/triplanar-mapping.md): Accumulates the three projected normals as gradients, giving correct lighting at blends. ## Sources 1. [primary] Morten S. Mikkelsen Surface Gradient–Based Bump Mapping Framework. JCGT 2020. https://jcgt.org/published/0009/03/04 (verified via http on 2026-11-29) ## Cite this entry Texel. "Surface gradient based bump mapping framework." https://texelatlas.vercel.app/t/surface-gradient-bump-mapping/ (accessed 2026-12-01). --- id: "surface-nets" title: "Surface Nets" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, desktop-gpu, cuda, unity] year_introduced: 1998 inputs: [voxels, sdf] outputs: [mesh] style: "both" dynamic: "both" cost: "cheap" authority: "Gibson, 1998" url: "https://texelatlas.vercel.app/t/surface-nets/" sources_verified_at: "2026-11-29" --- # Surface Nets (Gibson, 1998) > A dual meshing method: one vertex per surface-crossing cell, placed at the average of that cell's edge crossings, with quads across sign-changing edges. Simple, fast, smooth, with better triangle quality than marching cubes. ## Reach for it when - marching cubes gives ugly thin triangles - smooth voxel terrain meshing at speed - chunked meshing for sculpting tools - need tidy quads from a scalar field - simple fast isosurface extraction ## How it works Find every cell whose corners have mixed signs. For each, compute the linearly interpolated crossing on each of its sign-changing edges and average them (the 'naive' variant) to get a single vertex. Then, for each grid edge that changes sign, connect the vertices of the four cells sharing that edge into a quad, oriented by the sign. The original paper starts from this net and relaxes it by moving vertices toward neighbour averages under a constraint that keeps each inside its cell. The result is a quad-dominant mesh with roughly regular valence and no sliver triangles, built with a simple two-pass loop and no lookup table. ## When to use it Choose it for voxel terrain, smooth sculpting and fast chunked meshing where speed and tidy triangles matter more than sharp edges. Prefer [Dual Contouring](https://texelatlas.vercel.app/t/dual-contouring.md) when you need crisp corners (add normals and a QEF), [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md) when a well-known lookup-table implementation or GPU compaction path is already in hand. ## Cost cheap — Two linear passes over cells and no table lookups; usually the cheapest grid mesher in practice. Measured GPU Weight: 19.62× baseline (moderate) — 0.6454 ms median / 0.7286 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.86× baseline (moderate) — 0.2999 ms median (2.15× faster on L4). Ampere A100 scaling: 12.47× baseline (moderate) — 0.3591 ms median (1.8× faster on A100). ## Failure modes - Corners and creases get rounded because vertices sit at crossing averages - Thin features one voxel wide can collapse or leave holes - Quads may be non-planar, so triangulating along the wrong diagonal gives faceting - Minor vertex shrinkage on convex regions versus the true surface ## Dataflow - Inputs: voxels, sdf - Outputs: mesh - Platforms: cpu, webgl2, webgpu, desktop-gpu, cuda, unity ## Presets ### Toy 2D surface nets: mean-of-crossings cell vertices joined into a contour (glsl-fragment; rendered 2026-11-29) ```json { "CELLS": 9 } ``` ```glsl // Toy 2D surface nets: one vertex per mixed cell at the mean of its edge crossings, joined across shared crossing edges. const float CELLS = 9.0; float field(vec2 p) { vec2 q = abs(p - 0.5) - vec2(0.27, 0.19 + 0.04 * sin(iTime)); return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 0.07; } float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0)); } // vertex of cell (i,j); w = 0 when the cell is not mixed vec3 vtx(vec2 ij, float cs) { vec2 c0 = ij * cs; vec2 P[4]; float F[4]; P[0] = c0; P[1] = c0 + vec2(cs, 0); P[2] = c0 + cs; P[3] = c0 + vec2(0, cs); for (int i = 0; i < 4; i++) F[i] = field(P[i]); vec2 s = vec2(0); float n = 0.0; for (int i = 0; i < 4; i++) { int j = (i + 1) % 4; if ((F[i] > 0.0) != (F[j] > 0.0)) { s += mix(P[i], P[j], F[i] / (F[i] - F[j])); n += 1.0; } } return n > 0.0 ? vec3(s / n, 1.0) : vec3(0.0); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float cs = 1.0 / CELLS; vec2 cell = floor(uv / cs); float dl = 1e9, dv = 1e9; for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { vec2 ij = cell + vec2(i, j); vec3 v = vtx(ij, cs); if (v.z == 0.0) continue; dv = min(dv, length(uv - v.xy)); vec3 vr = vtx(ij + vec2(1, 0), cs), vu = vtx(ij + vec2(0, 1), cs); vec2 e1 = (ij + vec2(1, 0)) * cs, e2 = e1 + vec2(0, cs); if (vr.z > 0.0 && (field(e1) > 0.0) != (field(e2) > 0.0)) dl = min(dl, segd(uv, v.xy, vr.xy)); vec2 f1 = (ij + vec2(0, 1)) * cs, f2 = f1 + vec2(cs, 0); if (vu.z > 0.0 && (field(f1) > 0.0) != (field(f2) > 0.0)) dl = min(dl, segd(uv, v.xy, vu.xy)); } float f = field(uv); vec3 col = vec3(0.07, 0.08, 0.11) + (f < 0.0 ? vec3(0.06, 0.1, 0.16) : vec3(0.0)); vec2 g = abs(fract(uv / cs) - 0.5); col = mix(col, vec3(0.22, 0.24, 0.32), smoothstep(0.02, 0.0, 0.5 - max(g.x, g.y))); col = mix(col, vec3(0.95, 0.75, 0.3), smoothstep(0.005, 0.003, dl)); col = mix(col, vec3(0.35, 0.9, 1.0), smoothstep(0.012, 0.009, dv)); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Combines with - [Taubin Smoothing](https://texelatlas.vercel.app/t/taubin-smoothing.md): Optional post-relaxation without shrinkage for binary-segmentation input. ## Sources 1. [primary] Sarah F. F. Gibson (1998) Constrained elastic surface nets: Generating smooth surfaces from binary segmented data. Lecture Notes in Computer Science. https://doi.org/10.1007/bfb0056277 (verified via crossref on 2026-11-29) 2. [tutorial] Mikola Lysenko Smooth Voxel Terrain (Part 2). 0fps.net. https://0fps.net/2012/07/12/smooth-voxel-terrain-part-2 (verified via http on 2026-11-29) 3. [implementation] mikolalysenko (2013) mikolalysenko/isosurface. https://github.com/mikolalysenko/isosurface License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Surface Nets." https://texelatlas.vercel.app/t/surface-nets/ (accessed 2026-12-01). --- id: "surfel-gi" title: "Surfel-Based Global Illumination (GIBS)" aliases: [GIBS, surfel cache] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu] year_introduced: 2021 inputs: [gbuffer, depth, mesh] outputs: [radiance, irradiance-probes] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Halen et al." url: "https://texelatlas.vercel.app/t/surfel-gi/" sources_verified_at: "2026-11-29" --- # Surfel-Based Global Illumination (GIBS) (Halen et al.) > Covers visible geometry with small oriented discs (surfels) that cache irradiance, updated by hardware ray tracing and reused across frames; pixels shade by gathering nearby surfels. No bake, no UVs. ## Reach for it when - dynamic gi without probes or baked data - indirect light on large open worlds in real time - diffuse bounce that follows geometry detail - gi must work with fully dynamic scenes cheaply ## How it works Surfels are position, normal and radius records spawned on demand from the G-buffer. Each frame the pipeline tests screen tiles for coverage by existing surfels; where coverage is insufficient, new surfels are spawned (and ones that fall out of use are recycled), so the cache follows the camera. A spatial hash or grid lets any point quickly find the surfels around it. Each surfel owns a small budget of rays per frame. It traces them with hardware ray tracing, shading hits using the surfel cache itself as a source of multi-bounce light, and blends the new samples into the stored irradiance (stored as a low-order basis or a small octahedral map). Allocating more rays to surfels that are new or whose result changed concentrates work where it matters. At shading time, a pixel finds nearby surfels whose disks contain its position, weights them by distance and normal, and sums their irradiance. The result is combined with other contributors in a lighting buffer. ## When to use it Choose it for fully dynamic diffuse GI in an engine where baking or UV unwrapping is not acceptable, you can afford hardware ray tracing, and the camera sees a bounded amount of geometry. Prefer [ddgi](ddgi) when you want a regular grid with simple lookups and a fixed memory footprint. Prefer [lumen-gi](lumen-gi) for SDF-based software tracing and large scenes. Prefer [restir-gi](restir-gi) when you need per-pixel indirect accuracy. Prefer [lightmap-baking](lightmap-baking) when the scene is static and you need the lowest runtime cost. ## Cost medium — Cost scales with the surfel count times rays per surfel plus spatial hash lookups in shading; the cache is capped for a fixed memory budget. Measured GPU Weight: 69.78× baseline (extreme) — 2.1631 ms median / 2.3056 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 59.99× baseline (heavy) — 0.9539 ms median (2.27× faster on L4). Ampere A100 scaling: 47.93× baseline (heavy) — 1.3804 ms median (1.57× faster on A100). ## Failure modes - Surfel popping and temporal instability when surfels spawn or retire as the camera moves - Light leaking at thin walls or corners where a surfel disk spans two surfaces - Coverage gaps and noise in fast-moving or newly revealed areas until the cache converges - Large dynamic moving objects can invalidate surfels and produce trailing lighting ## Engine support - unreal: builtin — `Lumen Global Illumination parameterizes scene geometry into Surface Cache Mesh Cards and world-space Radiance Cache probes` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/lumen-technical-details-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: gbuffer, depth, mesh - Outputs: radiance, irradiance-probes - Platforms: desktop-gpu ## Presets ### Surfel GI (GIBS) — world-space oriented surfel disks (left) vs filtered surfel irradiance (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SURFEL_SIZE": 0.16, "P_BOUNCE_GAIN": 1.3, "P_DISK_EDGE": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_SURFEL_SIZE = 0.16; // P Surfel Radius [0.08, 0.28, 0.01] const float P_BOUNCE_GAIN = 1.30; // P Indirect GI [0.3, 2.2, 0.05] const float P_DISK_EDGE = 0.85; // P Disk Outlines [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Surfels / GI Split [0.0, 1.0, 0.02] vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); } 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); } vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); float dC = 1.05 - p.y; if (dC < res.x) res = vec2(dC, 1.0); float dB = p.z + 1.42; if (dB < res.x) res = vec2(dB, 1.0); float dL = p.x + 1.30; if (dL < res.x) res = vec2(dL, 2.0); float dR = 1.30 - p.x; if (dR < res.x) res = vec2(dR, 3.0); float dSph = length(p - vec3(-0.32, -0.45, -0.20)) - 0.39; if (dSph < res.x) res = vec2(dSph, 4.0); float dBlk = sdBox(p - vec3(0.50, -0.50, -0.32), vec3(0.28, 0.35, 0.28)) - 0.02; if (dBlk < res.x) res = vec2(dBlk, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } vec3 evalBounce(vec3 p, vec3 n, float t) { vec3 sunHit = vec3(0.42 * sin(t * 0.6), -0.84, -0.25); float dSun = length(p - sunHit); vec3 warmBounce = vec3(1.25, 0.72, 0.28) * exp(-dSun * 1.15) * (0.35 + 0.65 * max(dot(n, normalize(sunHit - p)), 0.0)); vec3 redWall = vec3(0.90, 0.22, 0.20) * clamp(1.0 - (p.x + 1.30) * 0.5, 0.0, 1.0) * 0.55; vec3 tealWall = vec3(0.14, 0.76, 0.82) * clamp(1.0 - (1.30 - p.x) * 0.5, 0.0, 1.0) * 0.55; float ao = clamp(0.38 + 0.62 * mapScene(p + n * 0.26).x / 0.26, 0.18, 1.0); return (warmBounce + redWall + tealWall + vec3(0.14, 0.16, 0.22)) * ao; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isSmooth = screenX >= split; float sRad = clamp(P_SURFEL_SIZE, 0.07, 0.30); float giGain = clamp(P_BOUNCE_GAIN, 0.2, 2.4); float edgeVis = clamp(P_DISK_EDGE, 0.0, 1.5); vec3 ro = vec3(0.0, 0.04, 2.35); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = vec3(0.02); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { hit = true; matId = h.y; break; } t += h.x; if (t > 9.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = vec3(0.76, 0.76, 0.78); if (matId > 1.5 && matId < 2.5) alb = vec3(0.90, 0.24, 0.20); if (matId > 2.5 && matId < 3.5) alb = vec3(0.14, 0.74, 0.80); vec3 lPos = vec3(0.42 * sin(iTime * 0.6), 0.94, -0.20); vec3 lDir = normalize(lPos - p); float ndl = max(dot(n, lDir), 0.0); // Allocate world-space surfels in a 3D uniform hash grid and gather Mahalanobis disk weights float cell = sRad * 1.15; vec3 cid = floor(p / cell); vec3 surfelIrr = vec3(0.0); float wTot = 0.0; float bestD = 1e5; vec3 bestIdCol = vec3(0.5); vec3 bestIrr = vec3(0.0); float diskRim = 0.0; for (int dz = -1; dz <= 1; dz++) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec3 nb = cid + vec3(float(dx), float(dy), float(dz)); vec3 rnd = hash33(nb); vec3 sp = (nb + 0.18 + 0.64 * rnd) * cell; // Project surfel disk onto surface plane so disks tile cleanly across geometry vec3 sOnSurf = sp - n * dot(sp - p, n); float d = length(p - sOnSurf); float q = d / max(sRad, 0.04); if (q < 1.0) { // Smooth cubic surfel kernel weight (1 - q)^2 float w = (1.0 - q) * (1.0 - q); vec3 irr = evalBounce(sOnSurf, n, iTime) * giGain; surfelIrr += irr * w; wTot += w; diskRim = max(diskRim, smoothstep(0.09, 0.015, abs(q - 0.86))); } if (d < bestD) { bestD = d; bestIdCol = 0.35 + 0.65 * hash33(nb + 19.7); bestIrr = evalBounce(sOnSurf, n, iTime) * giGain; } } } } vec3 filteredGI = (wTot > 1e-4) ? (surfelIrr / wTot) : evalBounce(p, n, iTime) * giGain; if (!isSmooth) { // Left: raw discrete world-space surfel disks showing cached radiance & allocation tiling float inDisk = smoothstep(sRad * 0.94, sRad * 0.84, bestD); vec3 diskFill = mix(bestIrr * 0.85, bestIdCol * 0.45 + bestIrr * 0.65, 0.25); col = mix(vec3(0.05, 0.07, 0.10), diskFill, inDisk); col = mix(col, vec3(0.95, 0.97, 1.0), diskRim * 0.42 * min(edgeVis, 1.2)); } else { // Right: smoothly filtered surfel GI + direct key light col = alb * (ndl * 0.55 + filteredGI); } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [ReSTIR GI: Path Resampling for Real-Time Path Tracing](https://texelatlas.vercel.app/t/restir-gi.md): Surfel irradiance gives a stable low-frequency fallback while resampling adds detail. ## Combination ideas - [Dynamic surfel GI inside carved snow trenches and footprints](https://texelatlas.vercel.app/ideas/deformed-snow-surfel-gi/) ## Sources 1. [primary] Henrik Halen, Andreas Brinck, Kyle Hayward, Xiangshun Bei Global Illumination Based on Surfels. SIGGRAPH 2021 Advances in Real-Time Rendering. https://advances.realtimerendering.com/s2021/index.html (verified via http on 2026-11-29) ## Cite this entry Texel. "Surfel-Based Global Illumination (GIBS)." https://texelatlas.vercel.app/t/surfel-gi/ (accessed 2026-12-01). --- id: "svbrdf-single-photo-capture" title: "Single-photo SVBRDF capture" domain: "materials" stage: "material" realtime: "interactive" platforms: [python, cuda] year_introduced: 2018 inputs: [photos] outputs: [material-params, texture] style: "photoreal" dynamic: "static" cost: "offline" authority: "Deschaintre et al., 2018" url: "https://texelatlas.vercel.app/t/svbrdf-single-photo-capture/" sources_verified_at: "2026-11-29" --- # Single-photo SVBRDF capture (Deschaintre et al., 2018) > A rendering-aware CNN predicts diffuse, specular, roughness and normal maps from one flash-lit photo of a flat material sample. Gives an instant starting material from a phone picture. ## Reach for it when - want pbr maps from one phone photo of a surface - need quick material scan of flat sample - no rig for capturing roughness and normals - seed a texture set artists can refine ## How it works Deschaintre et al. train a U-Net-like network with a global feature track that propagates image-wide context to every pixel, so highlights in one region inform appearance elsewhere. Training data are procedurally mixed SVBRDF maps rendered under a near-field flash light with a microfacet model. The loss is a mix of L1 error on predicted maps and a differentiable rendering loss comparing renders of predicted and ground-truth maps under random lighting, which resolves ambiguities where multiple maps explain the same photo. At inference the output is a set of four maps (diffuse albedo, specular albedo, roughness, normals) on a Cook-Torrance-GGX style model. A multi-image follow-up (Deschaintre 2019) accepts any number of photos with different light positions and pools features order-invariantly. ## When to use it Choose it for quick material scanning of flat samples, or to seed PBR textures that artists refine. Prefer photometric stereo ([Photometric Stereo](https://texelatlas.vercel.app/t/photometric-stereo.md)) or gantry-based capture when accuracy matters. Prefer [Procedural noise for texturing](https://texelatlas.vercel.app/t/procedural-noise-texturing.md) for fully procedural materials. Use [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) conventions for output normals. ## Cost offline — Single forward pass is fast (milliseconds on GPU) but the output is for authoring, not per-frame. Measured GPU Weight: 20.25× baseline (heavy) — 0.6663 ms median / 0.6902 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 17.64× baseline (moderate) — 0.2804 ms median (2.38× faster on L4). Ampere A100 scaling: 14.86× baseline (moderate) — 0.4279 ms median (1.56× faster on A100). ## Failure modes - Baked-in highlights and shadows leak into albedo when lighting is not near the training distribution - Domain gap on real photos: glossy or anisotropic materials are mispredicted - Output is limited to flat, tileable-ish samples; 3D structures confuse height and shading - Resolution fixed by network input, producing blurry fine detail without upsampling ## Dataflow - Inputs: photos - Outputs: material-params, texture - Platforms: python, cuda ## Presets ### Single-Photo SVBRDF Capture — flash-lit photo & predicted maps (left) vs relit reconstructed 3D material (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_FLASH_INT": 1.2, "P_RELIGHT_ANG": 0.65, "P_RELIEF": 0.9, "P_SPLIT": 0.48 } ``` ```glsl const float P_FLASH_INT = 1.20; // P Flash Hotspot [0.4, 2.2, 0.1] const float P_RELIGHT_ANG = 0.65; // P Relight Orbit [0.0, 2.0, 0.05] const float P_RELIEF = 0.90; // P Normal Depth [0.2, 1.6, 0.05] const float P_SPLIT = 0.48; // P Flash / Relit Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), f.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), f.x), f.y ); } float fbm(vec2 p) { float s = 0.0, a = 0.5; for (int i = 0; i < 4; i++) { s += a * vnoise(p); p *= 2.03; a *= 0.5; } return s; } // Underlying stone-and-patinated-copper tile SVBRDF maps void evalSVBRDF(vec2 uv, float relief, out vec3 alb, out vec3 tn, out float rough, out float specF0) { vec2 tile = uv * vec2(4.0, 6.0); float row = floor(tile.y); tile.x += mod(row, 2.0) * 0.5; vec2 id = floor(tile); vec2 f = fract(tile) - 0.5; float mortar = smoothstep(0.43, 0.48, max(abs(f.x), abs(f.y))); float n1 = fbm(uv * 9.0 + id * 0.37); float n2 = fbm(uv * 22.0 + 4.1); float tileRnd = hash21(id); vec3 stoneA = vec3(0.46, 0.26, 0.18); vec3 stoneB = vec3(0.24, 0.38, 0.36); vec3 tileCol = mix(stoneA, stoneB, smoothstep(0.35, 0.72, tileRnd + (n1 - 0.5) * 0.35)); alb = mix(tileCol * (0.72 + 0.55 * n2), vec3(0.22, 0.21, 0.19), mortar); rough = clamp(mix(0.26 + 0.35 * (1.0 - n1), 0.88, mortar), 0.12, 0.95); specF0 = mix(0.06 + 0.14 * smoothstep(0.55, 0.85, tileRnd), 0.02, mortar); // Normal gradient from bevel + micro-relief vec2 bev = smoothstep(0.36, 0.46, abs(f)) * sign(f); float eps = 0.01; float hx = fbm((uv + vec2(eps, 0.0)) * 18.0) - fbm(uv * 18.0); float hy = fbm((uv + vec2(0.0, eps)) * 18.0) - fbm(uv * 18.0); tn = normalize(vec3(-(bev.x * 0.85 + hx * 4.5) * relief, -(bev.y * 0.85 + hy * 4.5) * relief, 1.0)); } float D_GGX(float ndh, float a) { float a2 = a * a; float d = ndh * ndh * (a2 - 1.0) + 1.0; return a2 / max(3.1415926 * d * d, 1e-5); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showRelit = sx >= split; float flashPow = clamp(P_FLASH_INT, 0.2, 2.6); float orb = iTime * max(P_RELIGHT_ANG, 0.0); float relief = clamp(P_RELIEF, 0.1, 2.0); vec3 col = vec3(0.05, 0.06, 0.08); if (!showRelit) { // Left: Flat phone flash-capture photo (top 68%) + CNN predicted SVBRDF map strip (bottom 32%) float sy = fragCoord.y / max(iResolution.y, 1.0); if (sy > 0.30) { vec2 puv = vec2(sx / max(split, 0.05), (sy - 0.30) / 0.70); vec3 alb, tn; float rough, f0; evalSVBRDF(puv, relief, alb, tn, rough, f0); // Co-located camera + point flash at center (0.5, 0.5, 0.55) vec3 surfP = vec3(puv - 0.5, 0.0); vec3 camP = vec3(0.0, 0.0, 0.58); vec3 L = normalize(camP - surfP); float dist2 = dot(camP - surfP, camP - surfP); float ndl = max(dot(tn, L), 0.0); float D = D_GGX(ndl, max(rough * rough, 0.05)); float atten = flashPow / max(dist2 * 1.9, 0.2); col = (alb * ndl * 0.9 + vec3(D * f0 * 0.45)) * atten + alb * 0.06; } else { // Bottom CNN output map strip: Albedo | Normal | Roughness | Specular float bx = (sx / max(split, 0.05)) * 4.0; int idx = int(clamp(floor(bx), 0.0, 3.0)); vec2 muv = vec2(fract(bx), sy / 0.30); vec3 alb, tn; float rough, f0; evalSVBRDF(muv * 0.75, relief, alb, tn, rough, f0); if (idx == 0) col = alb * 1.1; else if (idx == 1) col = tn * 0.5 + 0.5; else if (idx == 2) col = vec3(rough); else col = vec3(f0 * 4.5); // Crisp border between predicted maps if (fract(bx) < 0.03 || fract(bx) > 0.97 || sy > 0.285) col = vec3(0.85, 0.88, 0.94); } } else { // Right: Reconstructed SVBRDF relit on a 3D curved cylinder/sphere under orbiting directional + cool IBL vec3 ro = vec3(0.18, 0.05, 2.20); vec3 rd = normalize(vec3(uv - vec2(0.14, 0.0), -1.48)); col = mix(vec3(0.05, 0.07, 0.11), vec3(0.16, 0.22, 0.34), smoothstep(-0.3, 0.6, rd.y)); vec3 sc = vec3(0.18, 0.0, 0.0); vec3 oc = ro - sc; float b = dot(oc, rd); float c = dot(oc, oc) - 0.62 * 0.62; float disc = b * b - c; if (disc > 0.0) { float t = -b - sqrt(disc); if (t > 0.05) { vec3 p = ro + rd * t; vec3 n = normalize(p - sc); float phi = atan(n.z, n.x) + orb * 0.35; float th = acos(clamp(n.y, -1.0, 1.0)); vec2 muv = vec2(phi / 3.14159, th / 1.57079); vec3 T = normalize(vec3(-sin(phi), 0.0, cos(phi))); vec3 B = cross(n, T); vec3 alb, tn; float rough, f0; evalSVBRDF(muv, relief, alb, tn, rough, f0); vec3 wN = normalize(T * tn.x + B * tn.y + n * tn.z); vec3 v = -rd; vec3 L1 = normalize(vec3(cos(orb) * 0.85, 0.65, sin(orb) * 0.65 + 0.45)); vec3 L2 = normalize(vec3(-0.7, 0.35, 0.55)); vec3 H1 = normalize(L1 + v); float ndl1 = max(dot(wN, L1), 0.0); float ndl2 = max(dot(wN, L2), 0.0); float ndh1 = max(dot(wN, H1), 0.0); float ndv = max(dot(wN, v), 0.005); float D = D_GGX(ndh1, max(rough * rough, 0.05)); float F = f0 + (1.0 - f0) * pow(1.0 - max(dot(v, H1), 0.0), 5.0); vec3 spec = vec3(1.15, 1.05, 0.90) * (D * F / max(4.0 * ndv, 0.08)) * ndl1; vec3 diff = alb * (vec3(1.25, 1.08, 0.88) * ndl1 + vec3(0.32, 0.52, 0.85) * ndl2 * 0.65 + vec3(0.12, 0.16, 0.22)); col = diff + spec; } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [One phone photo, a whole floor](https://texelatlas.vercel.app/ideas/one-photo-endless-material/) ## Sources 1. [primary] Valentin Deschaintre, Miika Aittala, Fredo Durand, George Drettakis, Adrien Bousseau (2018) Single-image SVBRDF capture with a rendering-aware deep network. ACM Transactions on Graphics. https://doi.org/10.1145/3197517.3201378 (verified via crossref on 2026-11-29) 2. [primary] Valentin Deschaintre, Miika Aittala, Fredo Durand, George Drettakis, Adrien Bousseau (2019) Flexible SVBRDF Capture with a Multi‐Image Deep Network. Computer Graphics Forum. https://doi.org/10.1111/cgf.13765 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Single-photo SVBRDF capture." https://texelatlas.vercel.app/t/svbrdf-single-photo-capture/ (accessed 2026-12-01). --- id: "svgf" title: "Spatiotemporal Variance-Guided Filtering (SVGF)" aliases: [SVGF, A-SVGF] domain: "post" stage: "post" realtime: "realtime" platforms: [desktop-gpu, webgpu, unity, unreal] year_introduced: 2017 inputs: [radiance, gbuffer, normals, depth] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Schied et al., 2017" url: "https://texelatlas.vercel.app/t/svgf/" sources_verified_at: "2026-11-29" --- # Spatiotemporal Variance-Guided Filtering (SVGF) (Schied et al., 2017) > A real-time denoiser for 1-sample-per-pixel path-traced lighting: it reprojects history, estimates per-pixel variance, and drives an edge-aware wavelet blur whose strength follows that variance. ## Reach for it when - path traced one sample per pixel image is very noisy - denoise ray traced global illumination in real time - noisy indirect lighting flickers between frames - need a temporal denoiser that keeps texture detail - ray traced shadows look grainy at low sample counts ## How it works Input is noisy irradiance (demodulated from albedo) at roughly one path per pixel plus a G-buffer with normals, depth and motion vectors. Stage one reprojects the previous frame's accumulated colour and its first two luminance moments, rejecting history at disocclusions or when normals and depth differ, and blends it exponentially. The moments give a temporal variance estimate; where history is too young (just revealed pixels) a small spatial neighbourhood supplies the variance instead. Stage two runs several iterations of an edge-avoiding à-trous wavelet filter (see [Edge-avoiding a-trous wavelet filter](https://texelatlas.vercel.app/t/atrous-wavelet-filter.md)), with steps 1, 2, 4, 8, 16. Edge-stopping weights combine depth gradient, normal similarity and a luminance term normalised by the smoothed local standard deviation, so noisy regions blur broadly while clean ones keep detail. The first iteration's output is fed back as next frame's history. The filtered irradiance is finally multiplied by albedo again, preserving texture detail. ## When to use it Choose it as the default open, well-documented denoiser for diffuse and rough-glossy path-traced or ray-traced GI and shadows at one sample per pixel. Prefer [NVIDIA Real-time Denoisers (ReBLUR, ReLAX)](https://texelatlas.vercel.app/t/nvidia-nrd-relax-reblur.md) when you want a maintained production library that separates diffuse, specular and shadow signals, [Intel Open Image Denoise (OIDN)](https://texelatlas.vercel.app/t/open-image-denoise.md) for offline or interactive final-quality output, and [Neural Radiance Caching](https://texelatlas.vercel.app/t/neural-radiance-caching.md) or [ReSTIR GI: Path Resampling for Real-Time Path Tracing](https://texelatlas.vercel.app/t/restir-gi.md) to reduce the noise at the source before filtering. ## Cost medium — Five wavelet passes plus a temporal pass at full resolution; the original paper reports about 10 ms at 720p on a Titan X-class GPU in its own test scenes, so budget scales with resolution. Measured GPU Weight: 45.88× baseline (heavy) — 1.5093 ms median / 1.6104 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 43.57× baseline (heavy) — 0.6927 ms median (2.18× faster on L4). Ampere A100 scaling: 30.56× baseline (heavy) — 0.8801 ms median (1.71× faster on A100). ## Failure modes - Ghosting and lag in lighting after fast-moving lights or objects because history rejection is only geometric - Over-blurred sharp specular reflections and mirror-like surfaces, since the filter assumes diffuse-like signals - Blotchy low-frequency 'boiling' where variance estimates are noisy after disocclusion - Loss of fine shadow or contact detail at the largest wavelet steps - Needs accurately demodulated albedo and a clean motion-vector buffer; errors become smear ## Dataflow - Inputs: radiance, gbuffer, normals, depth - Outputs: radiance - Platforms: desktop-gpu, webgpu, unity, unreal ## Presets ### SVGF — raw 1-spp path-traced variance (left) vs albedo-demodulated variance-guided a-trous wavelet filter (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VARIANCE": 0.8, "P_ATROUS_STR": 1, "P_EDGE_STOP": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_VARIANCE = 0.80; // P 1-spp Variance [0.2, 1.5, 0.05] const float P_ATROUS_STR = 1.00; // P Wavelet Stride [0.4, 1.8, 0.05] const float P_EDGE_STOP = 0.85; // P Normal/Depth Stop [0.2, 1.5, 0.05] const float P_SPLIT = 0.48; // P 1-spp / SVGF [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Architectural room with crisp albedo stripes & shadow boundaries for SVGF demodulation + a-trous wavelet test void evalSVGFScene(vec2 uv, float t, out vec3 irr, out vec3 alb, out vec3 nrm, out float dep) { vec3 ro = vec3(0.0, 0.30, 2.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.08, -1.46)); vec3 sun = normalize(vec3(0.62 * cos(t * 0.45), 0.75, 0.45)); dep = 10.0; alb = vec3(0.18, 0.22, 0.28); nrm = vec3(0.0, 0.0, 1.0); irr = vec3(0.28, 0.38, 0.55); // Checker floor if (rd.y < -0.005) { float tf = (-0.52 - ro.y) / rd.y; if (tf > 0.05 && tf < dep) { dep = tf; vec3 hp = ro + rd * tf; nrm = vec3(0.0, 1.0, 0.0); float chk = mod(floor(hp.x * 4.0) + floor(hp.z * 4.0), 2.0); alb = mix(vec3(0.26, 0.30, 0.36), vec3(0.82, 0.80, 0.76), chk); float sh = smoothstep(0.25, 0.56, length(hp.xz - vec2(0.0, -0.05))); irr = vec3(1.35, 1.24, 1.08) * (0.18 + 0.82 * sh) + vec3(0.18, 0.32, 0.52) * 0.45; } } // Faceted plinth box + sphere vec3 sc = vec3(0.0, -0.10, -0.05); vec3 oc = ro - sc; float b = dot(oc, rd), d = b * b - (dot(oc, oc) - 0.42 * 0.42); if (d > 0.0) { float ts = -b - sqrt(d); if (ts > 0.05 && ts < dep) { dep = ts; vec3 hp = ro + rd * ts; nrm = normalize(hp - sc); float band = step(0.5, fract(hp.y * 12.0 + hp.x * 4.0)); alb = mix(vec3(0.88, 0.42, 0.20), vec3(0.92, 0.86, 0.72), band); float ndl = max(dot(nrm, sun), 0.0); irr = vec3(1.42, 1.28, 1.08) * ndl + vec3(0.22, 0.42, 0.68) * (0.5 + 0.5 * nrm.y) + vec3(0.40, 0.24, 0.16) * max(-nrm.y, 0.0); } } // Side accent monolith vec3 bc = vec3(-0.75, -0.04, -0.45); vec3 br = vec3(0.22, 0.48, 0.24); vec3 invR = 1.0 / (rd + vec3(1e-6)); vec3 t0 = (bc - br - ro) * invR; vec3 t1 = (bc + br - ro) * invR; vec3 tnV = min(t0, t1); vec3 tfV = max(t0, t1); float tn = max(max(tnV.x, tnV.y), tnV.z); float tf = min(min(tfV.x, tfV.y), tfV.z); if (tf > max(tn, 0.05) && tn < dep) { dep = tn; vec3 hp = ro + rd * tn; vec3 lp = (hp - bc) / br; vec3 ap = abs(lp); nrm = (ap.x > ap.y && ap.x > ap.z) ? vec3(sign(lp.x), 0.0, 0.0) : (ap.y > ap.z ? vec3(0.0, sign(lp.y), 0.0) : vec3(0.0, 0.0, sign(lp.z))); alb = vec3(0.18, 0.72, 0.82); irr = vec3(1.35, 1.24, 1.08) * max(dot(nrm, sun), 0.0) + vec3(0.24, 0.34, 0.48); } } vec3 noisyDemodIrr(vec2 fc, float varAmp, float t, out vec3 alb, out vec3 nrm, out float dep) { vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; vec3 irr; evalSVGFScene(uv, t, irr, alb, nrm, dep); vec2 p = floor(fc); float fr = floor(t * 12.0) * 0.17; vec3 rnd = vec3( hash21(p + vec2(fr * 23.1, 9.7)), hash21(p + vec2(51.3, fr * 17.3)), hash21(p + vec2(fr * 71.7, 37.9)) ) - 0.5; return max(irr + rnd * varAmp * (0.5 + 0.75 * irr), 0.0); } float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float varAmp = clamp(P_VARIANCE, 0.1, 1.6); float stride = clamp(P_ATROUS_STR, 0.4, 2.2); float edgeStop = clamp(P_EDGE_STOP, 0.1, 1.8); vec3 cAlb, cNrm; float cDep; vec3 cIrr = noisyDemodIrr(fragCoord, varAmp, iTime, cAlb, cNrm, cDep); vec3 col = cIrr * cAlb; if (screenX >= split) { // Right: SVGF variance-guided edge-stopping a-trous wavelet filter on demodulated irradiance! // Step 1: Estimate local luminance moments (mu1, mu2 -> variance) in 3x3 neighborhood float m1 = 0.0; float m2 = 0.0; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec3 qa, qn; float qd; float yl = luma(noisyDemodIrr(fragCoord + vec2(float(i), float(j)), varAmp, iTime, qa, qn, qd)); m1 += yl; m2 += yl * yl; } } m1 /= 9.0; m2 /= 9.0; float localVar = max(m2 - m1 * m1, 0.002); float phiL = 4.0 * sqrt(localVar) + 0.05; // Step 2: 5x5 a-trous wavelet pass with B3-spline kernel [1/16, 1/4, 3/8, 1/4, 1/16] float kW[5]; kW[0] = 0.0625; kW[1] = 0.25; kW[2] = 0.375; kW[3] = 0.25; kW[4] = 0.0625; float cLuma = luma(cIrr); vec3 acc = vec3(0.0); float wSum = 0.0; for (int j = -2; j <= 2; j++) { for (int i = -2; i <= 2; i++) { vec2 off = vec2(float(i), float(j)) * (2.0 * stride); vec3 qAlb, qNrm; float qDep; vec3 qIrr = noisyDemodIrr(fragCoord + off, varAmp, iTime, qAlb, qNrm, qDep); float wKern = kW[i + 2] * kW[j + 2]; float wN = pow(max(dot(cNrm, qNrm), 0.0), 28.0 * edgeStop); float wZ = exp(-abs(cDep - qDep) * 5.0 * edgeStop); float wL = exp(-abs(cLuma - luma(qIrr)) / max(phiL, 0.02)); float w = wKern * wN * wZ * wL; acc += qIrr * w; wSum += w; } } // Re-modulate filtered irradiance by noise-free G-buffer albedo col = (acc / max(wSum, 1e-4)) * cAlb; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Edge-avoiding a-trous wavelet filter](https://texelatlas.vercel.app/t/atrous-wavelet-filter.md) - extended by [NVIDIA Real-time Denoisers (ReBLUR, ReLAX)](https://texelatlas.vercel.app/t/nvidia-nrd-relax-reblur.md) ## Combines with - [ReSTIR DI: Spatiotemporal Reservoir Resampling for Direct Lighting](https://texelatlas.vercel.app/t/restir-di.md): ReSTIR reduces direct-lighting variance upstream; SVGF then cleans the remaining per-pixel noise. - [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md): SVGF's denoised irradiance is remodulated by albedo and then goes through TAA for edge and specular stability. ## Sources 1. [primary] Christoph Schied, Anton Kaplanyan, Chris Wyman, Anjul Patney, Chakravarty R. Alla Chaitanya, John Burgess, Shiqiu Liu, Carsten Dachsbacher, Aaron Lefohn, Marco Salvi (2017) Spatiotemporal variance-guided filtering. Proceedings of High Performance Graphics. https://doi.org/10.1145/3105762.3105770 (verified via crossref on 2026-11-29) 2. [primary] Schied et al. Spatiotemporal Variance-Guided Filtering: Real-Time Reconstruction for Path-Traced Global Illumination. research.nvidia.com. https://research.nvidia.com/publication/2017-07_spatiotemporal-variance-guided-filtering-real-time-reconstruction-path-traced (verified via http on 2026-11-29) 3. [implementation] NVIDIAGameWorks (2017) NVIDIAGameWorks/Falcor. https://github.com/NVIDIAGameWorks/Falcor License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Spatiotemporal Variance-Guided Filtering (SVGF)." https://texelatlas.vercel.app/t/svgf/ (accessed 2026-12-01). --- id: "syncmvd" title: "SyncMVD" aliases: [Synchronized Multi-View Diffusion] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [mesh, text-prompt] outputs: [texture, uv-atlas] style: "both" dynamic: "static" cost: "heavy" authority: "Liu et al., 2023" url: "https://texelatlas.vercel.app/t/syncmvd/" sources_verified_at: "2026-11-29" --- # SyncMVD (Liu et al., 2023) > Textures a mesh by denoising all views simultaneously and averaging the per-pixel predictions that map to the same UV texel at every step, so the views stay consistent without sequential inpainting. ## Reach for it when - texturing a mesh from a prompt gives seams between views - multi-view textures disagree in overlapping areas - need open-source text-driven texturing for a uv mesh - avoid slow sequential inpainting for texture painting - views must stay consistent while generating ## How it works Several depth-conditioned diffusion samples (one per camera) run in lock-step. At each denoising step, each view's predicted clean image is projected into a shared UV texture, where overlapping texels are averaged, and the merged texture is rendered back into each view as the target for the next step. This synchronisation removes the order dependence of progressive texturing. The authors use an unmodified ControlNet-style depth model and report completion in tens of seconds, followed by a final pass that fills texels no view covered. ## When to use it Choose it as a practical, MIT-licensed prompt-driven texturer for meshes with UVs. Prefer [TexFusion](https://texelatlas.vercel.app/t/texfusion.md) when you want latent-space merging research results, [Text2Tex](https://texelatlas.vercel.app/t/text2tex.md) for iterative inpainting, [Paint3D](https://texelatlas.vercel.app/t/paint3d.md) for shading-free output, and [Hunyuan3D-Paint](https://texelatlas.vercel.app/t/hunyuan3d-paint.md) for image-referenced PBR-ready results. ## Cost heavy — Tens of seconds per mesh on a single GPU per authors; qualitative. ## Failure modes - Averaging blurs fine detail and text - Sharp features can duplicate across views in areas with little overlap - Baked shading from the 2D model - Quality depends on UV layout and chosen camera set ## Dataflow - Inputs: mesh, text-prompt - Outputs: texture, uv-atlas - Platforms: cuda, python ## Combination ideas - [Crease sharpness steers generated wear](https://texelatlas.vercel.app/ideas/crease-aware-generative-texturing/) ## Sources 1. [primary] Yuxin Liu, Minshan Xie, Hanyuan Liu, Tien-Tsin Wong (2023) Text-Guided Texturing by Synchronized Multi-View Diffusion. arXiv preprint (cs.CV). https://arxiv.org/abs/2311.12891 (verified via arxiv on 2026-11-29) 2. [implementation] LIU-Yuxin (2023) LIU-Yuxin/SyncMVD. https://github.com/LIU-Yuxin/SyncMVD License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "SyncMVD." https://texelatlas.vercel.app/t/syncmvd/ (accessed 2026-12-01). --- id: "tangent-frame-diffraction-grating" title: "Multi-Order Tangent-Frame Diffraction Grating & Spectral Replay Hologram" aliases: [diffraction shader, grating iridescence, spectral replay hologram, Stam diffraction BRDF] domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, blender] year_introduced: 1999 inputs: [normals, uv-atlas, material-params, gbuffer, radiance] outputs: [radiance] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Stam, 1999" url: "https://texelatlas.vercel.app/t/tangent-frame-diffraction-grating/" sources_verified_at: "2026-11-30" --- # Multi-Order Tangent-Frame Diffraction Grating & Spectral Replay Hologram (Stam, 1999) > Evaluates wave-optical grating diffraction in a surface tangent frame, summing integer diffraction orders into spectral RGB lobes to render holographic foils, optical discs, and white-light replay holograms in real time. ## Reach for it when - render rainbow sheen on cds dvds brushed vinyl or insect wings - micro-grooved metal surfaces lack angle-dependent spectral iridescence - thin film shader does not capture periodic groove diffraction orders - align anisotropic rainbow reflection bands along mesh uv tangents - simulate holographic foil and diffraction stickers in real time ## How it works Periodic microscopic grooves or recorded interference fringes scatter incident light into angle-dependent spectral orders rather than a single mirror lobe. At each shaded point, the shader builds a local **tangent frame** `(T, B, N)` whose tangent aligns with the grating groove direction—derived either from UV derivatives, polar coordinates on discs, or a brushed-foil anisotropy map. Projecting the half-vector `H = L + V` (the optical path-difference vector between light and view directions) onto the groove axis gives the grating phase offset `u = dot(H, T)`. For a grating pitch `d` and non-zero integer order `m`, constructive interference selects the wavelength `lambda = d * |u| / |m|`. Summing visible orders `m = ±1, ±2, …` weighted by groove-profile envelope falloff and converting each wavelength to linear RGB (via CIE color-matching curves or spectral basis fits) produces sharp rainbow dispersion bands. For **white-light reflection holograms** (such as dichromated gelatin or foil cards), a pre-baked depth or multi-view parallax field is sampled along the refracted view ray inside the plate and modulated by this grating dispersion term, replaying a floating 3D motif whose hue shifts continuously as the card tilts. ## When to use it Choose it when shading periodic micro-structured surfaces—optical media, embossed holographic trading cards, security foils, or diffraction-etched metals—where dispersion depends on groove orientation and viewing angle. Prefer [thin-film-iridescence](thin-film-iridescence) when interference comes from a smooth dielectric coating thickness (soap bubbles, oil slicks, oxide layers) without directional grooves. Prefer [anisotropic-ggx](anisotropic-ggx) when brushed metal needs elongated highlights without rainbow spectral splitting. Prefer [real-time-glints](real-time-glints) when discrete stochastic micro-facets dominate rather than coherent periodic fringes. ## Cost cheap — Evaluating the grating condition across a handful of integer diffraction orders and converting wavelengths to RGB takes tens of ALU instructions per light sample, staying well under 1 ms at 1080p on mid-range desktop GPUs. Measured GPU Weight: 10.63× baseline (moderate) — 0.3496 ms median / 0.356 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 8.33× baseline (moderate) — 0.1325 ms median (2.64× faster on L4). Ampere A100 scaling: 7.21× baseline (moderate) — 0.2077 ms median (1.68× faster on A100). ## Failure modes - Aliasing and shimmering when UV seams or high-frequency tangent maps flip groove orientation across adjacent pixels - Over-saturated out-of-gamut spectral spikes if narrow-band wavelengths are summed without bandwidth integration or gamut-aware tonemapping - Zero-order specular energy and diffracted orders can violate energy conservation unless balanced against the base microfacet BRDF - Point-sampled grating pitch assumes strictly periodic grooves and misses broadband blur caused by irregular groove spacing ## Dataflow - Inputs: normals, uv-atlas, material-params, gbuffer, radiance - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, blender ## Presets ### Tangent-Frame Diffraction Grating — plain brushed metal (left) vs multi-order wave-optical grating hologram (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PITCH_UM": 1.45, "P_DIFFRACT": 1.2, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.44 } ``` ```glsl const float P_PITCH_UM = 1.45; // P Grating Pitch um [0.8, 2.8, 0.05] const float P_DIFFRACT = 1.20; // P Diffraction Gain [0.2, 2.0, 0.05] const float P_ROT_SPEED = 0.65; // P Disc Spin [0.0, 2.2, 0.05] const float P_SPLIT = 0.44; // P Metal / Diffraction [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Spectral wavelength-to-RGB response for lambda in micrometers [0.38, 0.72] vec3 lambdaToRGB(float lam) { float t = (lam - 0.38) / (0.72 - 0.38); if (t < 0.0 || t > 1.0) return vec3(0.0); vec3 c = clamp(vec3( 1.45 - abs(t - 0.76) * 3.8 + 0.32 * exp(-pow((t - 0.12) * 5.2, 2.0)), 1.42 - abs(t - 0.48) * 3.4, 1.48 - abs(t - 0.18) * 3.6 ), 0.0, 1.0); float env = smoothstep(0.0, 0.08, t) * smoothstep(1.0, 0.90, t); return c * c * env; } // Sculpted holographic optical disc + embossed concentric bevel rings float mapDisc(vec3 p, float spin) { vec3 q = p; q.yz = rot2(0.45) * q.yz; q.xz = rot2(spin * 0.42) * q.xz; float r = length(q.xz); float disc = max(r - 0.88, abs(q.y) - 0.055); float hole = 0.16 - r; float bevel = abs(r - 0.56) - 0.025; float d = max(disc, hole); d -= 0.012 * exp(-bevel * bevel * 900.0); return d * 0.85; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapDisc(p + e.xyy, spin) - mapDisc(p - e.xyy, spin), mapDisc(p + e.yxy, spin) - mapDisc(p - e.yxy, spin), mapDisc(p + e.yyx, spin) - mapDisc(p - e.yyx, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isDiff = screenX >= split; float pitch = clamp(P_PITCH_UM, 0.75, 3.0); float gain = clamp(P_DIFFRACT, 0.1, 2.2); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.15, 2.22); vec3 rd = normalize(vec3(uv, -1.52)); vec3 col = mix(vec3(0.016, 0.020, 0.034), vec3(0.048, 0.058, 0.092), smoothstep(-0.55, 0.55, uv.y)); float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapDisc(ro + rd * t, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec3 q = p; q.yz = rot2(0.45) * q.yz; q.xz = rot2(spin * 0.42) * q.xz; // Radial tangent frame in disc space (concentric circular optical grooves + holographic sector modulation) vec3 radObj = normalize(vec3(q.x, 0.0, q.z) + vec3(1e-5, 0.0, 0.0)); float sector = floor((atan(q.z, q.x) + 3.14159265) * 4.0 / 6.2831853); float sectorTilt = (length(q.xz) > 0.56) ? (sector * 0.35) : 0.0; vec3 gObj = vec3( radObj.x * cos(sectorTilt) - radObj.z * sin(sectorTilt), 0.0, radObj.x * sin(sectorTilt) + radObj.z * cos(sectorTilt) ); // Transform groove vector back to world space vec3 gWorld = gObj; gWorld.xz = rot2(-spin * 0.42) * gWorld.xz; gWorld.yz = rot2(-0.45) * gWorld.yz; gWorld = normalize(gWorld - n * dot(gWorld, n) + vec3(1e-5)); vec3 l1 = normalize(vec3(0.55 * cos(iTime * 0.45), 0.78, 0.62)); vec3 l2 = normalize(vec3(-0.62, 0.52, 0.58)); vec3 v = -rd; // Base metallic silver substrate reflection vec3 h1 = normalize(l1 + v); vec3 h2 = normalize(l2 + v); float specBase = pow(max(dot(n, h1), 0.0), 48.0) + 0.65 * pow(max(dot(n, h2), 0.0), 36.0); float fres = 0.62 + 0.38 * pow(1.0 - max(dot(n, v), 0.0), 4.0); float brush = 0.90 + 0.10 * sin(length(q.xz) * 180.0); vec3 metalCol = vec3(0.42, 0.45, 0.50) * brush * (0.25 + 0.55 * max(dot(n, l1), 0.0)) + vec3(0.95, 0.97, 1.0) * specBase * fres * 0.85; if (!isDiff) { col = metalCol; } else { // Multi-order grating equation along tangent groove normal gWorld: // d * |dot(l + v, gWorld)| = |m| * lambda for integer orders m = 1, 2, 3! float u1 = abs(dot(l1 + v, gWorld)); float u2 = abs(dot(l2 + v, gWorld)); vec3 diffSum = vec3(0.0); for (int m = 1; m <= 3; m++) { float fm = float(m); float wOrder = 1.0 / (fm * 0.85 + 0.15); float lam1 = (pitch * u1) / fm; float lam2 = (pitch * u2) / fm; // Spectral coherence window around each diffraction order diffSum += (lambdaToRGB(lam1) + 0.65 * lambdaToRGB(lam2)) * wOrder; } // Micro-groove envelope fade at grazing float vis = smoothstep(0.05, 0.25, max(dot(n, v), 0.0)); col = metalCol * 0.55 + diffSum * gain * vis * 1.15; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md): Provides consistent orthonormal tangent frames across curved meshes so grating grooves orient without seam discontinuities. - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): Compresses highly saturated spectral diffraction orders into display gamut gracefully without harsh hue clipping. ## Sources 1. [primary] Jos Stam (1999) Diffraction shaders. Proceedings of the 26th annual conference on Computer graphics and interactive techniques - SIGGRAPH '99. https://doi.org/10.1145/311535.311546 (verified via crossref on 2026-11-30) 2. [secondary] Sebastian Werner, Zdravko Velinov, Wenzel Jakob, Matthias B. Hullin (2017) Scratch iridescence. ACM Transactions on Graphics. https://doi.org/10.1145/3130800.3130840 (verified via crossref on 2026-11-30) 3. [implementation] spite (2026) spite/codevember-2026. https://github.com/spite/codevember-2026 License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Multi-Order Tangent-Frame Diffraction Grating & Spectral Replay Hologram." https://texelatlas.vercel.app/t/tangent-frame-diffraction-grating/ (accessed 2026-12-01). --- id: "taubin-smoothing" title: "Taubin Smoothing" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, webgl2, webgpu, blender, python] year_introduced: 1995 inputs: [mesh] outputs: [mesh] style: "both" dynamic: "static" cost: "cheap" authority: "Taubin" url: "https://texelatlas.vercel.app/t/taubin-smoothing/" sources_verified_at: "2026-11-29" --- # Taubin Smoothing (Taubin) > Low-pass filters a mesh with alternating shrinking and inflating Laplacian steps, so noise disappears without the volume loss of plain Laplacian smoothing. Cheap and local. ## Reach for it when - laplacian smoothing makes the mesh shrink - denoise scanned mesh while preserving volume - remove surface noise without collapsing the shape - smooth marching cubes output staircase artifacts ## How it works Plain Laplacian smoothing moves every vertex a fraction lambda toward the centroid of its neighbours; it reduces noise but also shrinks the shape. Taubin's trick alternates this with a second step of negative factor mu (with |mu| slightly larger than lambda): the second step expands a little. Together the two steps form a polynomial filter that damps high frequencies yet leaves low frequencies nearly untouched. The pass-band frequency k_pb = 1/lambda + 1/mu is chosen small, e.g. 0.1, which fixes mu given lambda. Iterate 10 to 50 times. Weights can be uniform, cotangent or other; with cotangent weights the filter is closer to a geometric flow. The method is a signal-processing view of mesh fairing. ## When to use it Choose it for denoising scan meshes, fixing marching-cubes stair-steps and smoothing sculpts when volume should stay almost fixed. Prefer [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md) when you also want triangles evened out, [Screened Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction.md) to regularise from points, and bilateral or feature-preserving filters when sharp edges must stay. ## Cost cheap — Each iteration is one parallel sweep over vertices. Measured GPU Weight: 989.39× baseline (extreme) — 32.551 ms median / 32.8625 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 725.36× baseline (extreme) — 11.5333 ms median (2.82× faster on L4). Ampere A100 scaling: 643.7× baseline (extreme) — 18.5385 ms median (1.76× faster on A100). ## Failure modes - Sharp edges and fine details smooth away like any isotropic low-pass filter - Many iterations on irregular triangulations drift or clump vertices tangentially - Needs good parameters: mu too small keeps shrinking, too large oscillates - Open boundaries shrink unless pinned ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cpu, webgl2, webgpu, blender, python ## Presets ### Toy 2D curve: Laplacian smoothing shrinks, Taubin lambda|mu keeps size (glsl-fragment; rendered 2026-11-29) ```json { "N": 40, "ITERS": 60, "LAMBDA": 0.6, "MU": -0.64 } ``` ```glsl // Toy 2D polyline version: grey = noisy closed curve, red = plain Laplacian smoothing (shrinks), green = Taubin lambda|mu smoothing. const int N = 40; const int ITERS = 60; const float LAMBDA = 0.6; const float MU = -0.64; float h(float n) { return fract(sin(n * 78.233) * 43758.5453); } float segd(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); } void smoothStep(inout vec2 p[N], float k) { vec2 q[N]; for (int i = 0; i < N; i++) { vec2 avg = 0.5 * (p[(i + N - 1) % N] + p[(i + 1) % N]); q[i] = p[i] + k * (avg - p[i]); } for (int i = 0; i < N; i++) p[i] = q[i]; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 a[N], b[N], c[N]; for (int i = 0; i < N; i++) { float t = 6.2831853 * float(i) / float(N); float r = 0.34 * (1.0 + 0.25 * sin(3.0 * t) + 0.12 * cos(5.0 * t)) + 0.035 * (h(float(i)) - 0.5); a[i] = vec2(cos(t), sin(t)) * r; b[i] = a[i]; c[i] = a[i]; } for (int it = 0; it < ITERS; it++) { smoothStep(b, LAMBDA); smoothStep(c, LAMBDA); smoothStep(c, MU); } float da = 1e9, db = 1e9, dc = 1e9; for (int i = 0; i < N; i++) { int j = (i + 1) % N; da = min(da, segd(uv, a[i], a[j])); db = min(db, segd(uv, b[i], b[j])); dc = min(dc, segd(uv, c[i], c[j])); } vec3 col = vec3(0.06, 0.07, 0.1); col = mix(col, vec3(0.5), smoothstep(0.004, 0.002, da)); col = mix(col, vec3(1.0, 0.35, 0.3), smoothstep(0.006, 0.0035, db)); col = mix(col, vec3(0.35, 1.0, 0.5), smoothstep(0.006, 0.0035, dc)); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Combines with - [Marching Cubes](https://texelatlas.vercel.app/t/marching-cubes.md): Removes the staircase noise of voxel input. - [Tufted Cover Laplacian](https://texelatlas.vercel.app/t/tufted-laplacian.md): A Laplacian built for messy meshes can replace the uniform one. ## Sources 1. [primary] G. Taubin Curve and surface smoothing without shrinkage. Proceedings of IEEE International Conference on Computer Vision. https://doi.org/10.1109/iccv.1995.466848 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Taubin Smoothing." https://texelatlas.vercel.app/t/taubin-smoothing/ (accessed 2026-12-01). --- id: "temporal-anti-aliasing" title: "Temporal Anti-Aliasing" aliases: [TAA, TAAU] domain: "post" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2014 inputs: [ldr-image, depth, gbuffer] outputs: [ldr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Karis" url: "https://texelatlas.vercel.app/t/temporal-anti-aliasing/" sources_verified_at: "2026-11-29" --- # Temporal Anti-Aliasing (Karis) > Accumulates sub-pixel-jittered frames over time, reprojecting the previous result with motion vectors and clamping it to the current neighbourhood, so aliasing averages out across frames at the cost of a one-frame history. ## Reach for it when - specular and thin geometry shimmer - edge filters don't fix shading aliasing - alpha-tested foliage crawls and shimmers - noisy effects need smoothing across frames ## How it works Each frame the projection matrix is offset by a sub-pixel jitter taken from a low-discrepancy sequence (Halton is typical), so over N frames the pixel centre samples N positions. The resolve pass reads the current colour, fetches the history buffer at the position given by per-pixel motion vectors, and blends them with a small weight on the current frame, usually around 5 to 10 percent. History is validated before blending. The common approach clamps the reprojected colour to the min/max (or a variance-based ellipsoid) of the 3x3 neighbourhood in the current frame, which rejects stale colours from disocclusions and lighting changes. Karis' variant also weights samples by inverse luminance after tonemapping to suppress fireflies. A sharpening or bicubic history fetch counters the blur caused by repeated bilinear resampling. ## When to use it Choose it when the frame has shading aliasing (specular, thin geometry, alpha test, noisy stochastic effects) that MSAA or morphological filters cannot touch, and you have reliable motion vectors. It also denoises SSAO, SSR and volumetrics for free. Prefer [FXAA](https://texelatlas.vercel.app/t/fxaa.md) or [SMAA](https://texelatlas.vercel.app/t/smaa.md) when there are no motion vectors, the camera is rarely still, or ghosting is unacceptable. Prefer [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) or [AMD FidelityFX Super Resolution](https://texelatlas.vercel.app/t/fidelityfx-super-resolution.md) when you also want upscaling, since they are TAA with a larger reconstruction step. ## Cost cheap — One full-screen resolve plus a motion-vector pass; well under a millisecond at 1080p on desktop hardware, qualitative estimate. Measured GPU Weight: 5.95× baseline (light) — 0.1956 ms median / 0.2038 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 5.31× baseline (light) — 0.0845 ms median (2.31× faster on L4). Ampere A100 scaling: 3.88× baseline (light) — 0.1117 ms median (1.75× faster on A100). ## Failure modes - Ghosting trails behind moving objects when motion vectors are missing (transparents, particles, skinned vertex animation) - Blurring and shimmering of thin high-contrast detail after the neighbourhood clamp - Flicker on disocclusion for a frame or two as history is rejected - Jitter-induced crawl in texture sampling unless mip bias is applied - Smearing of dynamic lighting changes that history rejection misses ## Engine support - babylonjs: builtin — `new BABYLON.TAARenderingPipeline('taa', scene, cameras)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/RenderPipeline/Pipelines/taaRenderingPipeline.pure.ts, checked 2026-12-01) - blender: builtin — `Properties > Render > Sampling (EEVEE); Samples accumulate temporally` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/render_settings/sampling.html, checked 2026-12-01) - godot: builtin — `Viewport.use_taa = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/Viewport.xml, checked 2026-12-01) — Forward+ and Mobile. - metal: builtin — `MTLFXTemporalScalerDescriptor (MetalFX Temporal Scaler: jittered color + depth + motion vectors)` (evidence: https://developer.apple.com/tutorials/data/documentation/metalfx/mtlfxtemporalscalerdescriptor.json, checked 2026-12-01) — Provides temporal anti-aliasing and spatial/temporal upscaling via MetalFX. - threejs: official — `import { traa } from 'three/addons/tsl/display/TRAANode.js' (WebGL: TAARenderPass)` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/TRAANode.js, checked 2026-12-01) - unity: builtin — `Camera > Rendering > Anti-aliasing = Temporal Anti-aliasing (TAA)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Anti-Aliasing.md, checked 2026-12-01) — HDRP, and URP in Unity 6. - unreal: builtin — `Project Settings > Rendering > Default Settings > Anti-Aliasing Method = Temporal Anti-Aliasing (TAA) or Temporal Super Resolution (TSR)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/anti-aliasing-and-upscaling-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: ldr-image, depth, gbuffer - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: one aliased sample per pixel. Right: 8 Halton-jittered frames blended with an exponential history (static scene) (glsl-fragment; rendered 2026-11-29) ```json { "ALPHA": 0.25 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} vec3 scnA(vec2 px){vec2 p=(px-256.)/512.; vec3 c=vec3(.93,.92,.88); float s=fract((p.x*.866+p.y*.5)*11.);c=mix(c,vec3(.1,.12,.2),step(s,.18)*step(abs(p.y+p.x*.3),.38)); float d=length(p-vec2(.0,.0));c=mix(c,vec3(.85,.25,.2),step(abs(d-.2),.02)); c=mix(c,vec3(.1,.5,.4),step(length(p-vec2(-.25,.28)),.1)); c=mix(c,vec3(.1),step(abs(p.x-.2),.004)*step(abs(p.y-.1),.3)); return c;} const float ALPHA=0.25; // P const vec2 J[8]=vec2[8](vec2(0.,-.1667),vec2(-.25,.1667),vec2(.25,-.3889),vec2(-.375,-.0556),vec2(.125,.2778),vec2(-.125,-.2778),vec2(.375,.0556),vec2(-.4375,.3889)); void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 uv=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=uv.x>0.;vec2 q=vec2(uv.x+(R?-.25:.25),uv.y); vec3 col=scnA(fragCoord); if(R){vec3 acc=vec3(0.);float ws=0.,w=ALPHA; for(int k=0;k<8;k++){acc+=w*scnA(fragCoord+J[k]*2.);ws+=w;w*=1.-ALPHA;} col=acc/ws;} if(abs(uv.x)<.0015)col=vec3(1.);fragColor=vec4(clamp(col,0.,1.),1.); } ``` Attribution: written for this index ## Lineage - extended by [NVIDIA DLSS](https://texelatlas.vercel.app/t/dlss.md) - extended by [AMD FidelityFX Super Resolution](https://texelatlas.vercel.app/t/fidelityfx-super-resolution.md) - extended by [Intel XeSS](https://texelatlas.vercel.app/t/intel-xess.md) ## Combines with - [Plausible motion blur (reconstruction filter)](https://texelatlas.vercel.app/t/per-object-motion-blur.md): Motion vectors produced for TAA are the same buffer the motion blur pass consumes. - [Contrast Adaptive Sharpening](https://texelatlas.vercel.app/t/contrast-adaptive-sharpening.md): CAS restores the detail lost to history blur after the resolve. ## Sources 1. [primary] Brian Karis Advances in Real-Time Rendering in Games, SIGGRAPH 2014. SIGGRAPH 2014 (High Quality Temporal Supersampling). https://advances.realtimerendering.com/s2014 (verified via http on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Temporal Anti-Aliasing." https://texelatlas.vercel.app/t/temporal-anti-aliasing/ (accessed 2026-12-01). --- id: "temporal-spatial-neural-splat-denoising" title: "Lightweight WGSL Temporal-Spatial Neural Denoiser for Stochastic Splatting" aliases: [stochastic splat neural denoiser, WGSL temporal-spatial denoiser, recurrent splat denoiser] domain: "post" stage: "post" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, mobile-gpu] year_introduced: 2017 inputs: [hdr-image, depth, camera-poses] outputs: [hdr-image] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Chaitanya et al., 2017" url: "https://texelatlas.vercel.app/t/temporal-spatial-neural-splat-denoising/" sources_verified_at: "2026-11-30" --- # Lightweight WGSL Temporal-Spatial Neural Denoiser for Stochastic Splatting (Chaitanya et al., 2017) > Reconstructs temporally stable frames from noisy stochastic 3D Gaussian splats using a compact recurrent neural filter compiled directly into WGSL/GLSL shaders with packed vec4 feature targets and camera-reprojected history. ## Reach for it when - stochastic sort-free gaussian splats look noisy and stippled in motion - reconstruct clean smooth splat images from low-sample stochastic coverage - need a lightweight neural filter tailored to 3dgs depth and motion guides - reduce flicker and crawling grain on real-time stochastic splat renders - combine temporal reprojection with compact spatial filtering for splat pipelines ## How it works Sort-free stochastic Gaussian splatting trades global sorting for high-frequency sub-pixel alpha stipple, while real-time browser renderers cannot afford multi-megabyte desktop denoisers like OIDN every frame. Drawing on recurrent Monte Carlo denoising autoencoders, a lightweight temporal-spatial neural denoiser executes a tiny convolutional/pointwise network directly inside standard **WGSL or GLSL fragment passes**. Each frame's noisy 4× MSAA stochastic color and depth buffer is paired with the previous frame's **camera-reprojected history** (computed from current and previous view-projection matrices and depth). Instead of shipping an external ML runtime, trained weights are baked straight into shader constants as groups of `mat4x4` pointwise convolutions and small spatial taps operating on packed `rgba16float` render targets—four hidden channels per attachment. A multi-scale spatial block aggregates neighborhood context to dissolve stipple while respecting depth edges, and a final residual head blends the spatial prediction with reprojected temporal history, rejecting stale history across disocclusions. Because the network has only a few tens of channels and runs purely in native shader passes, it achieves real-time frame rates in WebGPU and WebGL2, including stereo XR. ## When to use it Choose it when pairing sort-free stochastic Gaussian splatting with real-time interactive or XR camera motion in the browser and you need immediate noise suppression without heavy external ML runtimes. Prefer [temporal-anti-aliasing](temporal-anti-aliasing) when GPU budget is too tight for multi-pass neural inference and mild motion ghosting is acceptable. Prefer [svgf](svgf) when you have full path-traced G-buffers (normals, albedo, mesh IDs) and want an analytic spatiotemporal filter. Prefer [open-image-denoise](open-image-denoise) for offline or converged single-frame denoising. ## Cost medium — Runs as a fixed sequence of fullscreen WGSL/GLSL fragment passes over packed rgba16float targets; lightweight enough for real-time desktop and WebGPU rendering, though fill-rate sensitive at 4K or high-resolution XR. Measured GPU Weight: 261.5× baseline (extreme) — 8.6033 ms median / 8.648 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 280.44× baseline (extreme) — 4.459 ms median (1.93× faster on L4). Ampere A100 scaling: 188.92× baseline (extreme) — 5.441 ms median (1.58× faster on A100). ## Failure modes - Disocclusion trails or brief stipple bursts when the camera moves rapidly and reprojected history is invalidated - Over-smoothing of sub-pixel high-frequency foliage or fine text that resembles stochastic alpha noise - Domain shift artifacts if applied to stylized or out-of-distribution splat opacity statistics not seen during training - Floating-point half-precision truncation can introduce faint color banding in dark gradients without rounding bias compensation ## Dataflow - Inputs: hdr-image, depth, camera-poses - Outputs: hdr-image - Platforms: webgpu, webgl2, desktop-gpu, mobile-gpu ## Presets ### Temporal-Spatial Neural Splat Denoiser — stochastic sort-free alpha-stipple splats (left) vs recurrent neural-filtered cloud (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_STIPPLE": 0.85, "P_SPLAT_SIZE": 0.65, "P_RECURRENT": 0.88, "P_SPLIT": 0.48 } ``` ```glsl const float P_STIPPLE = 0.85; // P Stochastic Stipple [0.2, 1.0, 0.05] const float P_SPLAT_SIZE = 0.65; // P Gaussian Radius [0.35, 1.2, 0.05] const float P_RECURRENT = 0.88; // P Recurrent Blend [0.2, 0.96, 0.04] const float P_SPLIT = 0.48; // P Stipple / Denoised [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec2 rot2(vec2 p, float a) { float c = cos(a); float s = sin(a); return vec2(c * p.x - s * p.y, s * p.x + c * p.y); } // Render 28 orbiting 3D Gaussian splats using sort-free stochastic alpha testing (left) vs clean analytic/denoised (right) void evalSplatCloud(vec2 uv, vec2 fragPx, float t, float radScale, float stippleMode, float seedOff, out vec3 outCol, out float outDepth) { vec3 bg = mix(vec3(0.05, 0.07, 0.12), vec3(0.12, 0.16, 0.24), smoothstep(-0.5, 0.5, uv.y)); outCol = bg; outDepth = 10.0; vec3 accum = vec3(0.0); float trans = 1.0; float bestZ = 10.0; vec3 winnerCol = bg; for (int i = 0; i < 28; i++) { float fi = float(i); float u = fi / 28.0; float ang = u * 6.2831853 * 2.0 + t * 0.55; float phi = (u - 0.5) * 2.4; // Sculptural double-helix / botanical coral splat cluster in 3D vec3 sp = vec3( 0.42 * cos(ang) * cos(phi * 0.6), 0.34 * sin(phi), 0.42 * sin(ang) * cos(phi * 0.6) ); sp.xz = rot2(sp.xz, t * 0.35); float zCam = 1.95 - sp.z; vec2 proj = sp.xy / max(zCam * 0.62, 0.3); vec2 d = uv - proj; // Anisotropic splat orientation vec2 dl = rot2(d, ang * 0.7 + fi); vec2 rAxis = vec2(0.095, 0.055) * radScale / max(zCam * 0.55, 0.35); float g = exp(-0.5 * dot(dl / rAxis, dl / rAxis)); float alpha = clamp(g * 0.82, 0.0, 0.96); vec3 splatCol = 0.52 + 0.45 * cos(vec3(0.0, 2.05, 4.10) + u * 5.2 + sp.y * 2.4); splatCol *= 0.75 + 0.45 * smoothstep(-0.4, 0.4, sp.y + 0.2 * sp.z); if (stippleMode > 0.5) { // Sort-free stochastic splatting: accept fragment if random threshold < alpha, keep closest Z! float rnd = hash21(floor(fragPx) + vec2(fi * 17.3 + seedOff * 31.7, fi * 9.1 - seedOff * 13.3)); if (rnd < alpha && zCam < bestZ) { bestZ = zCam; winnerCol = splatCol; } } else { // Soft volumetric reference weighting for recurrent spatial-temporal denoiser float wDepth = exp(-max(zCam - 1.2, 0.0) * 0.65); accum += splatCol * alpha * wDepth * trans; trans *= (1.0 - alpha * 0.55); if (alpha > 0.25 && zCam < bestZ) bestZ = zCam; } } if (stippleMode > 0.5) { outCol = winnerCol; outDepth = bestZ; } else { outCol = accum + bg * trans; outDepth = bestZ; } } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float stipple = clamp(P_STIPPLE, 0.1, 1.0); float radScale = clamp(P_SPLAT_SIZE, 0.3, 1.3); float recW = clamp(P_RECURRENT, 0.1, 0.97); float fr = floor(iTime * 16.0); vec3 col = vec3(0.0); if (screenX < split) { // Left: Raw sort-free stochastic splatting (sub-pixel Bernoulli stipple noise) vec3 stCol, refCol; float stZ, refZ; evalSplatCloud(uv, fragCoord, iTime, radScale, 1.0, fr, stCol, stZ); evalSplatCloud(uv, fragCoord, iTime, radScale, 0.0, fr, refCol, refZ); col = mix(refCol, stCol, stipple); } else { // Right: Compact recurrent temporal-spatial neural-style filter (depth-aware 3x3 spatial + multi-frame reprojected history) vec3 cRef; float cZ; evalSplatCloud(uv, fragCoord, iTime, radScale, 0.0, fr, cRef, cZ); vec3 acc = vec3(0.0); float wSum = 0.0; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 qPx = fragCoord + vec2(float(i), float(j)) * 1.5; vec2 qUv = (qPx - 0.5 * iResolution.xy) / iResolution.y; vec3 qCol; float qZ; evalSplatCloud(qUv, qPx, iTime, radScale, 1.0, fr + float(i * 3 + j), qCol, qZ); float wZ = exp(-abs(cZ - qZ) * 2.2); float w = wZ * exp(-dot(vec2(float(i), float(j)), vec2(float(i), float(j))) * 0.45); acc += qCol * w; wSum += w; } } vec3 spatialEst = acc / max(wSum, 1e-4); // Recurrent temporal feedback stabilizes the spatial estimate without ghosting col = mix(spatialEst, cRef, recW); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [4× MSAA Sort-Free Stochastic Gaussian Splatting](https://texelatlas.vercel.app/t/sort-free-stochastic-splatting-msaa.md): Consumes noisy 4× MSAA stochastic splat color and depth targets to output smooth, temporally coherent frames. - [AgX](https://texelatlas.vercel.app/t/agx-tonemapping.md): Applies display tone mapping after temporal-spatial neural reconstruction completes in linear HDR space. ## Combination ideas - [Sort-free neural-denoised LOD Gaussian splats](https://texelatlas.vercel.app/ideas/stochastic-lod-neural-splats/) ## Sources 1. [primary] Chakravarty R. Alla Chaitanya, Anton S. Kaplanyan, Christoph Schied, Marco Salvi, Aaron Lefohn, Derek Nowrouzezahrai, Timo Aila (2017) Interactive reconstruction of Monte Carlo image sequences using a recurrent denoising autoencoder. ACM Transactions on Graphics. https://doi.org/10.1145/3072959.3073601 (verified via crossref on 2026-11-30) 2. [primary] WilliamLiu-1997 (2026) WilliamLiu-1997/Gaussian-Splat-Lite. https://github.com/WilliamLiu-1997/Gaussian-Splat-Lite License: Apache-2.0. (verified via github on 2026-11-30) ## Cite this entry Texel. "Lightweight WGSL Temporal-Spatial Neural Denoiser for Stochastic Splatting." https://texelatlas.vercel.app/t/temporal-spatial-neural-splat-denoising/ (accessed 2026-12-01). --- id: "tethered-lattice-adhesive-delamination" title: "Tethered Lattice Adhesive Peeling and Delamination Front" aliases: [taut membrane peeling, interactive adhesive delamination, cohesive front peeling simulation] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgpu, webgl2, desktop-gpu, cpu] year_introduced: 2026 inputs: [mesh, texture, uv-atlas] outputs: [mesh, texture, visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "ttillberg, 2026" url: "https://texelatlas.vercel.app/t/tethered-lattice-adhesive-delamination/" sources_verified_at: "2026-11-30" --- # Tethered Lattice Adhesive Peeling and Delamination Front (ttillberg, 2026) > Simulate interactive peeling of thin adhesive films over curved surfaces using a coarse particle lattice whose stuck nodes detach irreversibly along a load-sharing delamination front while loose nodes relax taut like a soap film. ## Reach for it when - simulate tape stickers paint or biological tissue peeling off a surface - need cohesive sticky bonds that stretch and snap progressively under pull - model adhesive fracture and delamination smoothly in real-time physics - hard pin constraints detach abruptly instead of peeling along a crack front - couple cloth or soft-body sheets to breakable spring-lattice glue links ## How it works Simulating a peeling sticker, protective film, or biological membrane with ordinary cloth solvers creates distracting wrinkles and sails, while geometric page-curl deformations cannot navigate arbitrary hand-drawn cuts or multi-layer stacks. A tethered lattice formulation separates **surface coverage** from **peeling mechanics**. Each film layer stores its intact mask and connected-component IDs in a UV atlas (such as a cube-unwrapped sphere), letting knife cuts paint hairline grooves without remeshing; fragment discard hides removed regions. When the user grabs a cut edge, a coarse lattice of particles over that patch marks nodes as either *stuck* to the substrate or *loose*. A stuck node detaches irreversibly once a connected loose neighbor pulls past its adhesive peel threshold—anisotropically tuned so folding the film back over itself detaches easily in peel mode while dragging flat resists in shear, distributing tension across the entire active front so it naturally curves around the pointer and catches on cut tips. Rather than integrating velocity-driven cloth, loose nodes relax purely quasi-statically toward the mean of their graph neighbors while clamped within geodesic arc-length limits from both the grab point and the stuck front, and pushed outside the substrate surface. On release, flood-filling the detached region removes it cleanly without crossing cuts. ## When to use it Choose it for tactile interactive peeling of thin films, tape, decals, packaging, or layered membranes over curved 3D objects where arbitrary cuts and crisp delamination fronts are required. Prefer [position-based-dynamics](position-based-dynamics) or [xpbd](xpbd) when simulating slack, billowing, or gravity-draping fabric and ribbons that need inertia and wrinkling. Prefer [weathering-simulation](weathering-simulation) for non-interactive, aging-driven paint flaking and curling across large architectural scenes. ## Cost cheap — Quasi-static relaxation runs on a coarse particle lattice (hundreds to a few thousand nodes) per active peel, with atlas flood-fills triggered only when cuts or releases occur. ## Failure modes - Coarse lattice spacing limits how tightly the peel front can conform to intricate narrow cuts or sharp acute corners - Purely quasi-static taut relaxation omits inertia, flapping, and elastic snap-back when a peeled flap tears free - Excessive pull width across a stuck front can cause abrupt tearing artifacts unless cohesive load sharing and tear thresholds are tuned together - Multi-layer film stacks require strict ordering constraints so lower layers cannot detach beneath intact upper layers ## Dataflow - Inputs: mesh, texture, uv-atlas - Outputs: mesh, texture, visibility-mask - Platforms: webgpu, webgl2, desktop-gpu, cpu ## Lineage - extends [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) ## Combines with - [Cube-Sphere Planet Mapping](https://texelatlas.vercel.app/t/cube-sphere-mapping.md): Cube-mapped coverage and component atlases track arbitrary curved knife cuts and peeled islands on spherical substrates without remeshing. - [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md): Iterative distance-clamping relaxation along lattice edges keeps the pulled fan taut and collision-free against the underlying mesh. ## Sources 1. [primary] ttillberg (2026) ttillberg/codevember-2026. https://github.com/ttillberg/codevember-2026 License: MIT. (verified via github on 2026-11-30) 2. [secondary] Eric Paquette, Pierre Poulin, George Drettakis (2002) The Simulation of Paint Cracking and Peeling. Proceedings of Graphics Interface 2002. https://doi.org/10.20380/gi2002.08 (verified via doi.org on 2026-11-30) 3. [secondary] Daniele Liprandi, Federico Bosia, Nicola M. Pugno (2020) A theoretical-numerical model for the peeling of elastic membranes. Journal of the Mechanics and Physics of Solids. https://doi.org/10.1016/j.jmps.2019.103733 (verified via crossref on 2026-11-30) ## Cite this entry Texel. "Tethered Lattice Adhesive Peeling and Delamination Front." https://texelatlas.vercel.app/t/tethered-lattice-adhesive-delamination/ (accessed 2026-12-01). --- id: "texfusion" title: "TexFusion" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [mesh, text-prompt] outputs: [texture, uv-atlas] style: "both" dynamic: "static" cost: "heavy" authority: "Cao et al., 2023" url: "https://texelatlas.vercel.app/t/texfusion/" sources_verified_at: "2026-11-29" --- # TexFusion (Cao et al., 2023) > Textures a mesh by running a 2D diffusion model in several views at once while denoising a shared latent texture map, so no per-asset optimisation or distillation is needed. ## Reach for it when - text-prompt texturing of a fixed mesh without training - avoid per-asset optimisation for texture generation - merge diffusion output from several views into one texture - consistent texture from 2d diffusion on a uv-mapped model - no distillation step for painting meshes ## How it works A latent diffusion model is sampled in several camera views at every denoising step. At each step, the predicted clean latents from the views are back-projected into a shared latent texture, merged, and then re-rendered to become the next-step input, which forces agreement across views. A final decode gives a texture in the model's latent space turned into pixel space. The method uses an unmodified image model, avoids the long optimisation of distillation, and finishes in about a minute per asset according to its authors. ## When to use it Choose it for prompt-driven texturing of a fixed UV-mapped mesh without training. Prefer [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md) for a runnable open-source implementation of a similar synchronised-view idea, [Text2Tex](https://texelatlas.vercel.app/t/text2tex.md) when iterative inpainting from many views is acceptable, and [Paint3D](https://texelatlas.vercel.app/t/paint3d.md) for lighting-free albedo. ## Cost heavy — About a minute per object reported by the authors on a single GPU; qualitative here. ## Failure modes - Latent-space merging blurs high-frequency detail - Features appear shifted near silhouettes and occlusion boundaries - Shading and highlights from the 2D model get baked into colour - No official public code found, so reproduction is hard ## Dataflow - Inputs: mesh, text-prompt - Outputs: texture, uv-atlas - Platforms: cuda, python ## Sources 1. [primary] Tianshi Cao, Karsten Kreis, Sanja Fidler, Nicholas Sharp, Kangxue Yin (2023) TexFusion: Synthesizing 3D Textures with Text-Guided Image Diffusion Models. Proceedings of the IEEE/CVF International Conference on Computer Vision (2023) 4169-4181. https://arxiv.org/abs/2310.13772 (verified via arxiv on 2026-11-29) ## Cite this entry Texel. "TexFusion." https://texelatlas.vercel.app/t/texfusion/ (accessed 2026-12-01). --- id: "text2tex" title: "Text2Tex" domain: "genai" stage: "generation" realtime: "offline" platforms: [cuda, python] year_introduced: 2023 inputs: [mesh, text-prompt] outputs: [texture, uv-atlas] style: "both" dynamic: "static" cost: "offline" authority: "Chen et al., 2023" url: "https://texelatlas.vercel.app/t/text2tex/" sources_verified_at: "2026-11-29" --- # Text2Tex (Chen et al., 2023) > Paints a mesh by looping through camera views: render a depth-conditioned view, inpaint the not-yet-textured pixels with a diffusion model, project back, and pick next views from where coverage is poor. ## Reach for it when - texture an untextured mesh from a text prompt - ai texturing leaves seams between viewpoints - need consistent texture across a 3d model with diffusion - paint uv maps from description automatically ## How it works A depth-conditioned diffusion model generates the appearance for the first view. Pixels that have been projected before are kept fixed, and new regions are generated by inpainting, using a mask that distinguishes unpainted, previously painted and poorly-viewed regions. The result is back-projected to UV space. A view selection step then chooses the next camera, to cover remaining holes, with a final refinement pass that revisits low-quality areas. The incremental process avoids contradictory views but accumulates errors from earlier choices. The mask logic matters: pixels already painted from a good angle are frozen, pixels seen at grazing angles are allowed to be regenerated from a better camera, and unpainted pixels are filled in. That is what limits, but does not eliminate, the visible seams between views. ## When to use it Choose it for text-driven texturing of existing meshes when you accept minutes of runtime and can tolerate seams. Prefer [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md) or [TexFusion](https://texelatlas.vercel.app/t/texfusion.md) for synchronised multi-view sampling that reduces seam problems, [Paint3D](https://texelatlas.vercel.app/t/paint3d.md) for lighting-free output, and [Hunyuan3D-Paint](https://texelatlas.vercel.app/t/hunyuan3d-paint.md) when an image reference exists. ## Cost offline — Many sequential diffusion calls, minutes per asset. ## Failure modes - First-view bias: later views must match early errors - Visible seams and colour shifts where views meet - Baked-in lighting and shadows from the image model - Occluded and concave regions stay noisy - Repository metadata shows no clear licence (NOASSERTION) ## Dataflow - Inputs: mesh, text-prompt - Outputs: texture, uv-atlas - Platforms: cuda, python ## Sources 1. [primary] Dave Zhenyu Chen, Yawar Siddiqui, Hsin-Ying Lee, Sergey Tulyakov, Matthias Nießner (2023) Text2Tex: Text-driven Texture Synthesis via Diffusion Models. arXiv preprint (cs.CV). https://arxiv.org/abs/2303.11396 (verified via arxiv on 2026-11-29) 2. [primary] Dave Zhenyu Chen, Yawar Siddiqui, Hsin-Ying Lee, Sergey Tulyakov, Matthias Nießner (2023) Text2Tex: Text-driven Texture Synthesis via Diffusion Models. 2023 IEEE/CVF International Conference on Computer Vision (ICCV). https://doi.org/10.1109/iccv51070.2023.01701 (verified via crossref on 2026-11-29) 3. [implementation] daveredrum (2023) daveredrum/Text2Tex. https://github.com/daveredrum/Text2Tex License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Text2Tex." https://texelatlas.vercel.app/t/text2tex/ (accessed 2026-12-01). --- id: "thermal-erosion" title: "Thermal (Talus) Erosion" aliases: [thermal weathering, talus relaxation] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, houdini, unity, unreal, godot, python] year_introduced: 1989 inputs: [heightfield] outputs: [heightfield] style: "both" dynamic: "static" cost: "cheap" authority: "Musgrave et al., 1989" url: "https://texelatlas.vercel.app/t/thermal-erosion/" sources_verified_at: "2026-11-29" --- # Thermal (Talus) Erosion (Musgrave et al., 1989) > Iteratively moves material from a cell to lower neighbours wherever the slope exceeds an angle of repose, softening steep noise-generated cliffs into talus slopes and aprons. ## Reach for it when - noise terrain has spiky steep cliffs - need scree slopes under cliffs - want a cheap finishing pass to soften peaks - slopes steeper than angle of repose look fake ## How it works For every cell of a heightfield, compare its height with each of its 4 or 8 neighbours. If the drop to a neighbour exceeds the talus threshold (tan of the repose angle times cell spacing), a fraction of the excess is moved to that neighbour, split among all lower neighbours in proportion to their drop. Repeating the pass lets slopes relax toward the threshold angle. It is local, deterministic and embarrassingly parallel, which makes it a GPU-friendly ping-pong pass. Variants add a hardness map so rock layers resist erosion, or move material only when the slope is under a maximum so cliffs are preserved. Musgrave's 1989 paper introduced it alongside hydraulic erosion on fractal terrain. ## When to use it Choose it as a cheap finishing pass to knock the spikes off [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) terrain and to build scree slopes under cliffs. Prefer [Interactive Hydraulic Erosion on Heightfields](https://texelatlas.vercel.app/t/hydraulic-erosion-stava.md) or [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md) when you need river valleys and sediment deposition, and [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) for large-scale drainage-driven mountain shapes. ## Cost cheap — One neighbourhood pass per iteration; dozens to hundreds of iterations are typical for convincing talus, so total cost scales with iteration count. Measured GPU Weight: 511.23× baseline (extreme) — 16.8195 ms median / 17.145 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 432.01× baseline (extreme) — 6.869 ms median (2.45× faster on L4). Ampere A100 scaling: 367.91× baseline (extreme) — 10.5958 ms median (1.59× faster on A100). ## Failure modes - Few iterations leave the original noise visible; many iterations over-smooth the entire terrain into a blob - Grid-aligned diamond or square slope artifacts with 4-neighbour variants - Without a hardness mask all rock behaves like sand, so crisp cliff bands vanish - Mass is only conserved if transfers are symmetric; naive in-place updates leak or create height ## Engine support - unity: official — `Package Manager > Terrain Tools > Erosion > Thermal` (evidence: https://docs.unity3d.com/Packages/com.unity.terrain-tools@5.2/manual/erosion.html, checked 2026-12-01) — Official Terrain Tools package. - unreal: builtin — `Landscape Mode > Sculpt > Erosion tool` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/landscape-erosion-tool-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: heightfield - Outputs: heightfield - Platforms: webgl2, webgpu, desktop-gpu, cpu, houdini, unity, unreal, godot, python ## Presets ### Thermal (Talus) Erosion — steep unstable cliffs > talus angle (left) vs relaxed scree aprons (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_TALUS_SLOPE": 0.65, "P_RELAX_AMT": 0.85, "P_CAM_ORBIT": 0.38, "P_SPLIT": 0.48 } ``` ```glsl const float P_TALUS_SLOPE = 0.65; // P Critical Talus [0.25, 1.2, 0.04] const float P_RELAX_AMT = 0.85; // P Thermal Slump [0.1, 1.0, 0.02] const float P_CAM_ORBIT = 0.38; // P Orbit Speed [0.0, 2.0, 0.05] const float P_SPLIT = 0.48; // P Steep / Talus Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y ); } // Raw steep mesa / jagged butte formation with vertical cliff walls exceeding talus angle float rawButte(vec2 p) { float r1 = length(p - vec2(-0.35, -0.10)); float r2 = length(p - vec2(0.45, 0.18)); float jagged = vnoise(p * 2.4) * 0.26 + vnoise(p * 5.6) * 0.10; // Steep sheer cliffs float m1 = smoothstep(0.95, 0.42, r1 + jagged * 0.55) * 0.92; float m2 = smoothstep(0.78, 0.34, r2 + jagged * 0.45) * 0.72; return max(m1, m2) + jagged * 0.35 - 0.36; } // Thermal-erosion talus relaxation: material slumps downslope to form smooth constant-slope scree cones! vec2 talusButte(vec2 p, float talusTan, float relaxAmt) { float hRaw = rawButte(p); // 9-tap neighborhood slope-limited relaxation simulating iterative talus diffusion float hSmooth = 0.0; float hMax = hRaw; float rad = 0.24 * relaxAmt / max(talusTan, 0.25); for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { vec2 off = vec2(float(dx), float(dy)) * rad; float hn = rawButte(p + off); float dist = length(off); // Cone-of-repose lower bound: material from higher neighbor slides down at angle tan(alpha) float talusBound = hn - dist * talusTan * 0.85; hMax = max(hMax, talusBound); hSmooth += hn; } } hSmooth /= 9.0; float hRelax = mix(hRaw, max(hSmooth * 0.65 + hRaw * 0.35, hMax), relaxAmt); float screeMask = clamp((hRelax - hRaw) * 7.5, 0.0, 1.0); return vec2(hRelax, screeMask); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isThermal = screenX >= split; float talus = clamp(P_TALUS_SLOPE, 0.2, 1.4); float relax = clamp(P_RELAX_AMT, 0.05, 1.0); float spin = iTime * max(P_CAM_ORBIT, 0.0) * 0.35; vec3 ro = vec3(0.0, 1.18, 2.48); vec3 rd = normalize(vec3(uv.x, uv.y - 0.34, -1.35)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 sky = mix(vec3(0.92, 0.68, 0.48), vec3(0.20, 0.38, 0.68), smoothstep(-0.08, 0.52, rd.y)); vec3 col = sky; float t = 0.2; bool hit = false; for (int i = 0; i < 64; i++) { vec3 p = ro + rd * t; float h = isThermal ? talusButte(p.xz, talus, relax).x : rawButte(p.xz); float d = p.y - h; if (d < 0.008) { hit = true; break; } t += max(d * 0.42, 0.025); if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; float e = 0.016; vec2 val = isThermal ? talusButte(p.xz, talus, relax) : vec2(rawButte(p.xz), 0.0); float hx = isThermal ? talusButte(p.xz + vec2(e, 0.0), talus, relax).x : rawButte(p.xz + vec2(e, 0.0)); float hz = isThermal ? talusButte(p.xz + vec2(0.0, e), talus, relax).x : rawButte(p.xz + vec2(0.0, e)); vec3 n = normalize(vec3((val.x - hx) / e, 1.0, (val.x - hz) / e)); vec3 sunDir = normalize(vec3(0.68, 0.55, 0.48)); float diff = max(dot(n, sunDir), 0.0); // Tangent of local terrain slope = |grad h| = sqrt(1 - n.y^2) / n.y float tanSlope = length(n.xz) / max(n.y, 0.05); float overTalus = smoothstep(talus * 0.85, talus * 1.45, tanSlope); // Desert sandstone strata on bedrock vs loose pale gravel scree on talus aprons float strata = 0.5 + 0.5 * sin(val.x * 36.0 + vnoise(p.xz * 4.0) * 2.0); vec3 bedrock = mix(vec3(0.58, 0.30, 0.20), vec3(0.78, 0.48, 0.30), strata); vec3 scree = mix(vec3(0.62, 0.54, 0.44), vec3(0.76, 0.68, 0.56), vnoise(p.xz * 18.0)); vec3 floorSand = vec3(0.74, 0.58, 0.42); vec3 alb = mix(floorSand, bedrock, smoothstep(-0.22, 0.12, val.x)); if (isThermal) { alb = mix(alb, scree, clamp(val.y * 0.92, 0.0, 0.95)); } else { // On left side, highlight unstable cliffs exceeding critical talus angle in warning red-orange! alb = mix(alb, vec3(0.98, 0.24, 0.16), overTalus * 0.62); } vec3 lit = alb * (0.25 + 0.90 * diff) + vec3(0.24, 0.34, 0.52) * 0.18 * (0.5 + 0.5 * n.y); col = mix(lit, sky, 1.0 - exp(-t * 0.075)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md) ## Combines with - [GPU Pipe-Model Hydraulic Erosion](https://texelatlas.vercel.app/t/gpu-pipe-model-erosion.md): Thermal relaxation runs after the hydraulic step to stabilise steep banks the water pass carves. ## Sources 1. [primary] F. K. Musgrave, C. E. Kolb, R. S. Mace (1989) The synthesis and rendering of eroded fractal terrains. ACM SIGGRAPH Computer Graphics. https://doi.org/10.1145/74334.74337 (verified via crossref on 2026-11-29) 2. [implementation] dandrino (2018) dandrino/terrain-erosion-3-ways. https://github.com/dandrino/terrain-erosion-3-ways License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Thermal (Talus) Erosion." https://texelatlas.vercel.app/t/thermal-erosion/ (accessed 2026-12-01). --- id: "thin-film-iridescence" title: "Thin-film iridescence" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2017 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Belcour & Barla, 2017" url: "https://texelatlas.vercel.app/t/thin-film-iridescence/" sources_verified_at: "2026-11-29" --- # Thin-film iridescence (Belcour & Barla, 2017) > Models soap-bubble and oil-slick colours by evaluating interference of light reflected from the top and bottom of a thin dielectric film, folded into the Fresnel term of a microfacet BRDF. Belcour and Barla give a fast, closed-form spectral approximation. ## Reach for it when - soap bubble or oil slick colours look wrong - beetle shell or anodised metal needs rainbow sheen - colour shifts with viewing angle on coated surfaces - need interference colours in a pbr shader - titanium or coated lens tint ## How it works Light striking a thin film of thickness d and index n reflects off both interfaces; the two waves differ by an optical path delay of 2 n d cos(theta_t) and interfere, strengthening or cancelling wavelengths depending on angle and thickness. Belcour and Barla treat the film as a replacement Fresnel F(theta, d, eta1, eta2, eta3, kappa3) inside a microfacet model, computing it per wavelength via the Airy summation, then compress the result into a Fourier-domain sensitivity-curve approximation that avoids per-wavelength loops: only a few terms per RGB channel are evaluated. The film thickness can be a texture, giving swirled colours, and the base can be dielectric or conductor. Three.js exposes iridescence, IOR and thickness range in MeshPhysicalMaterial, and glTF has KHR_materials_iridescence. ## When to use it Choose it for soap bubbles, oil on water, beetle shells, anodised metal, titanium oxide and coated lenses. Prefer baked colour ramps for stylised iridescence ([Toon / cel shading with lighting ramps](https://texelatlas.vercel.app/t/toon-shading.md)-style looks) where physical accuracy is not required. Prefer [Clearcoat layer](https://texelatlas.vercel.app/t/clearcoat-layer.md) for colourless coatings and [OpenPBR Surface](https://texelatlas.vercel.app/t/openpbr-surface.md) thin-film layer for interchange. ## Cost cheap — About two extra Fresnel evaluations with a few trig operations per pixel. Measured GPU Weight: 2.47× baseline (light) — 0.0814 ms median / 0.0838 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.16× baseline (light) — 0.0344 ms median (2.37× faster on L4). Ampere A100 scaling: 1.48× baseline (feather) — 0.0426 ms median (1.91× faster on A100). ## Failure modes - Hue shifts from RGB-only approximation fail to match spectral renderers for thick films - Thickness texture mip filtering averages interference colours, producing muddy greys at distance - Interaction with IBL is approximate; pre-filtered probes need an iridescence-aware Fresnel or reflections look wrong - Rapid angular variation aliases without specular antialiasing ## Engine support - babylonjs: builtin — `pbrMaterial.iridescence.isEnabled = true (PBRIridescenceConfiguration)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/PBR/pbrIridescenceConfiguration.ts, checked 2026-12-01) - blender: builtin — `Principled BSDF > Thin Film (Thickness, IOR)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/principled.html, checked 2026-12-01) — Cycles only. - threejs: builtin — `material.iridescence = 1 (MeshPhysicalMaterial)` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshPhysicalMaterial.js, checked 2026-12-01) - unity: builtin — `HDRP Lit > Material Type = Iridescence` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/snippets/shader-properties/surface-options/iridescence.md, checked 2026-12-01) — HDRP only (Lit Iridescence and StackLit). - unreal: builtin — `Substrate Slab > Thin Film / Substrate Thin-Film material function` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/overview-of-substrate-materials-in-unreal-engine, checked 2026-12-01) — Substrate materials only. ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Soap-bubble style iridescence (three-material; rendered 2026-11-29) ```json { "color": "#ffffff", "roughness": 0.05, "metalness": 0, "iridescence": 1, "iridescenceIOR": 1.3, "transmission": 0.9, "thickness": 0.5 } ``` Attribution: written for this index; sensible defaults, not measured ## Combination ideas - [Chladni-vibrated iridescent soap film](https://texelatlas.vercel.app/ideas/chladni-driven-iridescent-soap-film/) ## Sources 1. [primary] Laurent Belcour, Pascal Barla (2017) A practical extension to microfacet theory for the modeling of varying iridescence. ACM Transactions on Graphics. https://doi.org/10.1145/3072959.3073620 (verified via crossref on 2026-11-29) 2. [implementation] mrdoob (2010) mrdoob/three.js. https://github.com/mrdoob/three.js License: MIT. (verified via github on 2026-11-29) 3. [implementation] Gökay Aydoğan (2026) gokayfem/glsl-studies. https://github.com/gokayfem/glsl-studies License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Thin-film iridescence." https://texelatlas.vercel.app/t/thin-film-iridescence/ (accessed 2026-12-01). --- id: "three-mesh-bvh" title: "three-mesh-bvh" aliases: [BVH, three-mesh-bvh, three-mesh-bvh (BVH for three.js)] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [webgl2, webgpu, cpu] year_introduced: 2019 inputs: [mesh] outputs: [depth, normals] style: "both" dynamic: "both" cost: "cheap" authority: "gkjohnson, 2018" url: "https://texelatlas.vercel.app/t/three-mesh-bvh/" sources_verified_at: "2026-11-29" --- # three-mesh-bvh (gkjohnson, 2018) > A bounding volume hierarchy for three.js geometries: fast raycasts, closest-point and shape queries and GPU-side traversal, with a web worker builder. The practical way to run geometric queries on meshes in the browser. ## Reach for it when - raycasting against large meshes in three.js is slow - picking and collisions on dense models lag - need fast spatial queries for browser 3d - mouse hover on high poly meshes drops the frame rate ## How it works Triangles are recursively partitioned by a splitting strategy such as centre, average or surface-area heuristic until leaf buckets are small, storing bounds in flat typed arrays for cache-friendly traversal. Queries walk the tree and skip subtrees whose boxes miss: raycast, first-hit, closest point to a point, intersection with another geometry or shape, and bounds-tree-versus-bounds-tree tests. The library patches Mesh raycasting in three.js so existing code gets faster. It can build in a worker, serialise the tree, refit it for skinned or deformed geometry, and expose the data as textures for shaders to traverse, enabling GPU path tracing. It also supports geometry with indexed or non-indexed attributes. ## When to use it Choose it for picking, painting, sculpt brushes, collision of characters against level geometry, signed-distance baking and path tracing in three.js. Prefer [Manifold Mesh Booleans](https://texelatlas.vercel.app/t/mesh-boolean-manifold.md) when you need to modify geometry, and a bespoke SDF [Exact Euclidean Distance Transform](https://texelatlas.vercel.app/t/exact-euclidean-distance-transform.md) grid for repeated inside/outside tests on a fixed mesh. ## Cost cheap — Build time grows with n log n; queries are logarithmic, so a raycast on millions of triangles takes microseconds to milliseconds. ## Failure modes - Build cost on very large meshes can stall the main thread without the worker path - Deforming meshes need refit; heavy deformation degrades tree quality - Memory overhead of tree buffers on top of geometry - Inside/outside tests require closed meshes; open meshes give wrong parity ## Engine support - threejs: plugin — `npm i three-mesh-bvh` (evidence: https://github.com/gkjohnson/three-mesh-bvh, checked 2026-12-01) ## Dataflow - Inputs: mesh - Outputs: depth, normals - Platforms: webgl2, webgpu, cpu ## Combines with - [Isotropic Remeshing](https://texelatlas.vercel.app/t/isotropic-remeshing.md): Fast closest-point queries reproject remeshed vertices onto the source. - [Exact Euclidean Distance Transform](https://texelatlas.vercel.app/t/exact-euclidean-distance-transform.md): Bake a distance volume from the mesh by querying the BVH at each grid point. ## Sources 1. [primary] gkjohnson (2018) gkjohnson/three-mesh-bvh. https://github.com/gkjohnson/three-mesh-bvh License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "three-mesh-bvh." https://texelatlas.vercel.app/t/three-mesh-bvh/ (accessed 2026-12-01). --- id: "tiled-deferred-shading" title: "Tiled deferred shading" aliases: [tiled shading, tile-based light culling] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2009 inputs: [gbuffer, depth] outputs: [radiance] style: "both" dynamic: "both" cost: "medium" authority: "Olsson & Assarsson, 2011" url: "https://texelatlas.vercel.app/t/tiled-deferred-shading/" sources_verified_at: "2026-11-29" --- # Tiled deferred shading (Olsson & Assarsson, 2011) > Cut the screen into small tiles, find each tile's depth range and the lights touching it, then shade the G-buffer pixels with just that tile's light list. ## Reach for it when - too many small lights tank deferred performance - each pixel shades every light unnecessarily - need a light list per screen region - scene with hundreds of point lights on opaque geometry ## How it works After the G-buffer pass, a compute shader processes one tile per workgroup. Threads reduce the tile's min and max depth, build its frustum, and cooperatively test all lights against it, appending hits to a list in shared memory. Then each thread shades its pixel by looping that list, reading material data from the G-buffer. Because lighting is done once per pixel and light lists are small, many hundreds of lights become affordable, though G-buffer bandwidth and material variety are limited. ## When to use it Choose it with a deferred renderer and many small lights. Prefer [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md) when you need MSAA, transparency, or wide depth ranges inside tiles. Prefer plain forward rendering with few lights on mobile. ## Cost medium — Scales with light count per tile and G-buffer width. Measured GPU Weight: 14.72× baseline (moderate) — 0.4842 ms median / 0.5053 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 12.92× baseline (moderate) — 0.2055 ms median (2.36× faster on L4). Ampere A100 scaling: 9.23× baseline (moderate) — 0.2657 ms median (1.82× faster on A100). ## Failure modes - Tiles with a large depth range, such as at silhouettes, get excess lights - Transparent surfaces do not fit the G-buffer - MSAA multiplies G-buffer cost - Only one material model per G-buffer layout ## Engine support - metal: builtin — `MTLTileRenderPipelineDescriptor + imageblock (on-chip Apple Silicon TBDR tile memory deferred pass)` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtltilerenderpipelinedescriptor.json, checked 2026-12-01) - unity: builtin — `URP Renderer > Rendering Path = Deferred; HDRP Camera > Lit Shader Mode = Deferred` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/Forward-And-Deferred-Rendering.md, checked 2026-12-01) — URP Deferred and HDRP Deferred. ## Dataflow - Inputs: gbuffer, depth - Outputs: radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Toy 2D tile light-culling heat map for animated point lights (glsl-fragment; rendered 2026-11-29) ```json { "LIGHTS": 24, "TILE": 32 } ``` ```glsl // Toy 2D light-culling view: screen split into 32px tiles, heat colour = number of lights whose radius overlaps the tile. const int LIGHTS = 24; const float TILE = 32.0; void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 tileMin = floor(fragCoord / TILE) * TILE, tileMax = tileMin + TILE; int cnt = 0; float lit = 0.0, ring = 1e9, cdist = 1e9; for (int i = 0; i < LIGHTS; i++) { float f = float(i); vec2 c = (vec2(0.5) + 0.42 * vec2(sin(f * 2.3 + iTime * 0.4 + f * f * 0.05), cos(f * 1.7 + iTime * 0.3))) * iResolution.xy; float r = 40.0 + 55.0 * fract(sin(f * 12.9) * 4375.0); vec2 q = clamp(c, tileMin, tileMax); if (distance(q, c) < r) cnt++; float d = distance(fragCoord, c); lit += smoothstep(r, 0.0, d) * smoothstep(r, 0.0, d); ring = min(ring, abs(d - r)); cdist = min(cdist, d); } float x = float(cnt) / 6.0; vec3 heat = clamp(vec3(1.5 * x, 1.5 - abs(3.0 * x - 1.5), 1.5 - 1.5 * x), 0.0, 1.0); vec3 col = mix(vec3(0.04, 0.05, 0.08), heat * 0.55, cnt > 0 ? 1.0 : 0.0); col += vec3(1.0, 0.9, 0.7) * lit * 0.12; vec2 g = fract(fragCoord / TILE); col = mix(col, vec3(0.0), (g.x < 0.04 || g.y < 0.04) ? 0.55 : 0.0); col = mix(col, vec3(1.0), smoothstep(1.2, 0.5, ring) * 0.7); col = mix(col, vec3(1.0), smoothstep(4.0, 2.5, cdist)); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Deferred shading (G-buffer)](https://texelatlas.vercel.app/t/deferred-shading.md) - extended by [Clustered forward shading](https://texelatlas.vercel.app/t/clustered-forward-shading.md) ## Combines with - [Hierarchical-Z occlusion culling](https://texelatlas.vercel.app/t/hierarchical-z-occlusion-culling.md): The depth pre-pass gives per-tile min and max depth for light culling and the pyramid for object culling. ## Sources 1. [primary] Ola Olsson, Ulf Assarsson (2011) Tiled Shading. Journal of Graphics, GPU, and Game Tools. https://doi.org/10.1080/2151237x.2011.621761 (verified via crossref on 2026-11-29) 2. [primary] Ola Olsson, Markus Billeter, Ulf Assarsson (2012) Tiled and clustered forward shading. ACM SIGGRAPH 2012 Posters on - SIGGRAPH '12. https://doi.org/10.1145/2343045.2343095 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Tiled deferred shading." https://texelatlas.vercel.app/t/tiled-deferred-shading/ (accessed 2026-12-01). --- id: "toksvig-mipmapping" title: "Toksvig normal-map filtering" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2005 inputs: [normals, texture] outputs: [texture, material-params] style: "both" dynamic: "both" cost: "cheap" authority: "Toksvig, 2005" url: "https://texelatlas.vercel.app/t/toksvig-mipmapping/" sources_verified_at: "2026-11-29" --- # Toksvig normal-map filtering (Toksvig, 2005) > Mipmapping a normal map shortens the averaged normal; Toksvig turns that shortening into extra roughness so minified bumpy surfaces blur their highlight instead of shimmering. ## Reach for it when - normal-mapped highlights shimmer in the distance - mip levels lose roughness from averaged normals - specular sparkle on minified bump maps - cheap baked fix for specular aliasing - bumpy surfaces should blur out far away ## How it works Averaging unit normals over a texel footprint produces a vector of length less than 1, and the shorter it is, the more the underlying normals disagree. Toksvig observes that for a Gaussian-like spread of normals the length encodes variance, and that the Blinn-Phong highlight over that distribution equals a broader lobe. So he adjusts the specular exponent by a factor ft = |Na| / (|Na| + s (1 - |Na|)) where s is the exponent. Modern variants apply the same idea to GGX by adding variance to roughness squared. The correction is either baked into per-mip roughness (or gloss) maps at texture-authoring time, or computed from the fetched normal's length when normal maps are stored unnormalised. ## When to use it Choose it as a cheap baseline for stopping specular shimmering on normal-mapped surfaces under minification. Prefer [Normal distribution filtering for specular antialiasing](https://texelatlas.vercel.app/t/normal-distribution-filtering.md) or [LEADR mapping](https://texelatlas.vercel.app/t/leadr-mapping.md) when you also need correct handling of the visible-slope distribution (LEADR) or per-pixel variance filtering with screen-space derivatives. Needed whenever [Normal mapping with MikkTSpace](https://texelatlas.vercel.app/t/normal-mapping-mikktspace.md) is used with glossy materials. ## Cost cheap — Baked into mip chain, or one length computation per pixel. Measured GPU Weight: 12.88× baseline (moderate) — 0.4236 ms median / 0.4287 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 9.36× baseline (moderate) — 0.1489 ms median (2.84× faster on L4). Ampere A100 scaling: 7.72× baseline (moderate) — 0.2222 ms median (1.91× faster on A100). ## Failure modes - Needs unnormalised normals in mips; normalised DXT/BC5 normals lose the length information - Assumes isotropic Gaussian normal spread, so directional grooves lose their stretched highlight - Only affects specular, not diffuse brightness changes with scale - Roughness bake must be redone if texture is retiled or rescaled ## Engine support - unreal: builtin — `Texture Editor > Composite Texture > CompositeTextureMode = CTM_NORMAL_ROUGHNESS_TO_ALPHA (converts normal-map mip variance into roughness)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/python-api/class/CompositeTextureMode, checked 2026-12-01) ## Dataflow - Inputs: normals, texture - Outputs: texture, material-params - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Toksvig filtering of a sub-pixel bump normal field: aliased (left) vs filtered (right) (glsl-fragment; rendered 2026-11-29) ```json { "SHININESS": 90, "BUMP_FREQ": 420, "BUMP_AMP": 0.55 } ``` ```glsl // Toksvig specular antialiasing. A sphere with a very high-frequency bump normal field (sub-pixel period). // Left: Blinn-Phong on the single pixel-centre normal: highlights sparkle/alias. // Right: the 4x4 footprint average normal (what a mip would store) is shorter than 1; Toksvig // ft = |N| / (|N| + s (1 - |N|)) shrinks the exponent so the highlight blurs instead of sparkling. const float SHININESS = 90.0; const float BUMP_FREQ = 420.0; const float BUMP_AMP = 0.55; vec3 bumpNormal(vec2 fc, out bool hit) { vec2 uv = (fc - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -2.4)); float b = dot(ro, rd); float h = b * b - dot(ro, ro) + 0.64; hit = h > 0.0; if (!hit) return vec3(0.0, 0.0, 1.0); vec3 p = ro + rd * (-b - sqrt(h)); vec3 n = normalize(p); vec3 t1 = normalize(cross(n, vec3(0.0, 1.0, 0.2))), t2 = cross(n, t1); return normalize(n + BUMP_AMP * (sin(BUMP_FREQ * p.x + 3.0 * p.y) * t1 + sin(BUMP_FREQ * 1.3 * p.y - 2.0 * p.x) * t2)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec3 v = vec3(0.0, 0.0, 1.0); vec3 l = normalize(vec3(-0.4, 0.5, 0.8)); vec3 hv = normalize(l + v); bool hit; vec3 n0 = bumpNormal(fragCoord, hit); vec3 col = vec3(0.03) + 0.04 * (fragCoord.y / iResolution.y); if (hit) { vec3 avg = vec3(0.0); for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++) { bool hh; avg += bumpNormal(fragCoord + (vec2(float(i), float(j)) - 1.5) * 0.25 * 4.0 / 1.0 * 0.5, hh); } avg /= 16.0; float len = length(avg); bool left = fragCoord.x < 0.5 * iResolution.x; vec3 n = left ? n0 : normalize(avg); float s = left ? SHININESS : SHININESS * len / (len + SHININESS * (1.0 - len)); float norm = (s + 8.0) / 25.13; float nl = max(dot(n, l), 0.0); col = vec3(0.35, 0.12, 0.1) * nl + vec3(1.0) * norm * pow(max(dot(n, hv), 0.0), s) * nl * 0.9; } if (abs(fragCoord.x - 0.5 * iResolution.x) < 1.0) col = vec3(1.0); col = col / (1.0 + col); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [LEADR mapping](https://texelatlas.vercel.app/t/leadr-mapping.md) - extended by [Normal distribution filtering for specular antialiasing](https://texelatlas.vercel.app/t/normal-distribution-filtering.md) ## Combination ideas - [Toon highlights that do not sparkle](https://texelatlas.vercel.app/ideas/variance-aware-toon-bands/) ## Sources 1. [primary] Michael Toksvig (2005) Mipmapping Normal Maps. Journal of Graphics Tools. https://doi.org/10.1080/2151237x.2005.10129203 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Toksvig normal-map filtering." https://texelatlas.vercel.app/t/toksvig-mipmapping/ (accessed 2026-12-01). --- id: "tonal-art-maps" title: "Real-time hatching with tonal art maps" aliases: [TAM, hatching] domain: "npr" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal] year_introduced: 2001 inputs: [mesh, uv-atlas, normals, texture] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Praun et al., 2001" url: "https://texelatlas.vercel.app/t/tonal-art-maps/" sources_verified_at: "2026-11-29" --- # Real-time hatching with tonal art maps (Praun et al., 2001) > Pre-draws a stack of hatch textures in which each darker tone only adds strokes to the lighter ones, then blends between two levels per fragment so tone changes without strokes popping. ## Reach for it when - hatching shading looks inconsistent as objects move - stroke density jumps when zooming in real time - pencil sketch rendering with temporal coherence - hand drawn shading that scales with distance ## How it works A tonal art map is a set of mip-mapped images, one per tone level and per resolution. Strokes are added going darker, so level k contains all strokes of level k−1 plus new ones, and the same holds across mip levels, which keeps stroke density roughly constant on screen. At runtime, the shader computes a lighting intensity and uses it to blend the two nearest tone textures; hardware mip-mapping chooses the resolution. Surfaces are parameterised so hatch direction follows the geometry (lapped textures or a UV atlas with direction fields). Because strokes are only ever added or removed across levels, there is minimal flicker as tone and distance change. ## When to use it Choose it when you want pen-and-ink or engraving-style shading on meshes with temporally coherent strokes. Prefer [Procedural cross-hatching shader](https://texelatlas.vercel.app/t/procedural-cross-hatching.md) for a quick screen-space shader without special parameterisation, and [Fine tone control in hardware hatching](https://texelatlas.vercel.app/t/hardware-hatching-tone-control.md) when you need finer tone gradation from fewer maps. ## Cost cheap — A few texture samples and a blend per fragment; cheap, plus authoring of the map stack. Measured GPU Weight: 3.68× baseline (light) — 0.121 ms median / 0.1242 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.91× baseline (light) — 0.0462 ms median (2.62× faster on L4). Ampere A100 scaling: 2.1× baseline (light) — 0.0604 ms median (2× faster on A100). ## Failure modes - Strokes follow the UV parameterisation, so poor UVs give strokes of wrong direction or density - Blending two levels can leave a faint grey cross-fade rather than crisp lines - Strong magnification or minification still thickens or fades strokes - Does not produce silhouettes; needs a separate outline pass ## Dataflow - Inputs: mesh, uv-atlas, normals, texture - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal ## Presets ### Left: lit frame. Right: nested hatch strokes, darker tone only adds strokes, second family enters in the shadows (glsl-fragment; rendered 2026-11-29) ```json { "SPC": 6, "ANG": 0.7854 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float SPC=6.0; // P const float ANG=0.7854; // P float fam(vec2 p,float a,float d,float seed){ float c=cos(a),s=sin(a),u=(p.x*c+p.y*s)/SPC,t=(-p.x*s+p.y*c)/SPC; float i=floor(u),w=abs(fract(u)-.5)*2.; float on=step(hash(vec2(i,seed)),d); float dash=step(hash(vec2(i+seed,floor(t/5.))),.55+.45*d); float wid=mix(.12,.45,d); return on*dash*smoothstep(wid+.12,wid-.04,w);} void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 col=shadeBasic(uv); if(R){float d=1.-pow(clamp(lum(col)*1.15,0.,1.),1./2.2); float h=max(fam(fragCoord,ANG,clamp(d*2.4,0.,1.),1.),fam(fragCoord,-ANG,clamp((d-.45)*2.6,0.,1.),7.)); col=mix(vec3(.96,.94,.88),vec3(.1,.1,.16),h);col=pow(col,vec3(2.2));} if(abs(u0.x)<.0015)col=vec3(1.); fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extended by [Fine tone control in hardware hatching](https://texelatlas.vercel.app/t/hardware-hatching-tone-control.md) ## Combines with - [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md): Hatching supplies tone; hull outline supplies contour lines. ## Combination ideas - [Hatching that deepens in the creases](https://texelatlas.vercel.app/ideas/occlusion-driven-hatching/) ## Sources 1. [primary] Emil Praun, Hugues Hoppe, Matthew Webb, Adam Finkelstein (2001) Real-time hatching. Proceedings of the 28th annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/383259.383328 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Real-time hatching with tonal art maps." https://texelatlas.vercel.app/t/tonal-art-maps/ (accessed 2026-12-01). --- id: "toon-shading" title: "Toon / cel shading with lighting ramps" aliases: [cel shading, toon ramp, Toon Shading, Cartoon Shading] domain: "npr" stage: "lighting" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] inputs: [normals, material-params] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "cheap" authority: "Gooch et al., 1998" url: "https://texelatlas.vercel.app/t/toon-shading/" sources_verified_at: "2026-11-29" --- # Toon / cel shading with lighting ramps (Gooch et al., 1998) > Quantizes diffuse lighting into a few flat tonal bands, usually via a 1D ramp texture or step functions, so a 3D surface reads as hand-inked cartoon colour. ## Reach for it when - want flat cartoon colour that reacts to light - lighting gradients look too realistic for my stylised game - need banded cel-shaded look - 3d character should look hand-inked ## How it works The shader computes a scalar lighting term, typically N·L (often remapped as half-Lambert so the terminator is softer), and uses it to look up a ramp instead of feeding it straight to the output. The ramp is either a small 1D texture an artist can paint, or a handful of `step`/`smoothstep` thresholds blending between a shadow colour, a base colour and a highlight colour. Choosing hue-shifted shadow colours (cool and saturated rather than just darker) is what gives the look its character. Specular is usually a hard-edged blob from thresholding N·H, and a rim term from 1 − N·V adds a graphic edge light. Anti-aliasing the thresholds with `fwidth` prevents shimmering on the band borders. Outlines are a separate pass (see the outline entries). ## When to use it Choose it when you want a flat-colour animated or comic look that still responds to a light direction. Prefer [Gooch tone shading](https://texelatlas.vercel.app/t/gooch-shading.md) when the goal is legible technical or CAD-style depiction with warm-to-cool tone rather than banding. Prefer [Guilty Gear Xrd anime-style 3D shading](https://texelatlas.vercel.app/t/guilty-gear-xrd-shading.md) when you need a hand-authored, animator-controlled look where artists sculpt shadow shapes through vertex data rather than letting the light decide. Prefer [Posterization](https://texelatlas.vercel.app/t/posterization.md) for a purely image-space version. ## Cost cheap — Qualitatively a few ALU ops per pixel plus one tiny ramp lookup; negligible next to any physically based shading pass. Measured GPU Weight: 8.88× baseline (moderate) — 0.2921 ms median / 0.3031 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.72× baseline (moderate) — 0.1068 ms median (2.74× faster on L4). Ampere A100 scaling: 5.01× baseline (light) — 0.1443 ms median (2.02× faster on A100). ## Failure modes - Band borders crawl and alias on curved surfaces unless thresholds are filtered with screen-space derivatives - Low-poly normals make the terminator follow facets; smooth or bake custom normals - Self-shadowing and cast shadows must be thresholded too, or soft shadow gradients break the flat look - A single N·L ramp cannot give artist-controlled shadow shapes on faces; shadows look noisy on small features ## Engine support - babylonjs: official — `new BABYLON.CellMaterial('m', scene) from @babylonjs/materials` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/materials/src/cell/cellMaterial.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Shader > Toon BSDF (or Shader to RGB + Color Ramp in EEVEE)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/shader/toon.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.diffuse_mode = DIFFUSE_TOON; specular_mode = SPECULAR_TOON` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) — Single hard cutoff, no custom ramp texture without a shader. - threejs: builtin — `new THREE.MeshToonMaterial({ gradientMap })` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/materials/MeshToonMaterial.js, checked 2026-12-01) - unity: official — `Package Manager > Unity Toon Shader (com.unity.toonshader) > Universal Render Pipeline/Toon` (evidence: https://github.com/Unity-Technologies/com.unity.toonshader, checked 2026-12-01) — Official Unity Toon Shader package (UTS3); URP and HDRP. ## Dataflow - Inputs: normals, material-params - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Three-band toon ramp on an SDF sphere (glsl-fragment; rendered 2026-11-29) ```json { "bands": 3, "t1": 0.45, "t2": 0.75 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style: toon ramp on a raymarched SDF sphere const vec3 LIGHT_DIR = vec3(0.6, 0.7, -0.4); const vec3 SHADOW_COL = vec3(0.35, 0.18, 0.45); const vec3 MID_COL = vec3(0.95, 0.45, 0.30); const vec3 LIT_COL = vec3(1.00, 0.85, 0.55); const float T1 = 0.45; // shadow / mid threshold on half-Lambert const float T2 = 0.75; // mid / lit threshold const float RIM_POWER = 3.0; float sdScene(vec3 p){ float s = length(p - vec3(0.0, 0.1, 0.0)) - 1.0; float f = p.y + 1.0; return min(s, f); } vec3 calcN(vec3 p){ vec2 e = vec2(0.001, 0.0); return normalize(vec3(sdScene(p+e.xyy)-sdScene(p-e.xyy), sdScene(p+e.yxy)-sdScene(p-e.yxy), sdScene(p+e.yyx)-sdScene(p-e.yyx))); } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = (fragCoord - 0.5*iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.3, -3.5); vec3 rd = normalize(vec3(uv, 1.7)); float t = 0.0; bool hit = false; for(int i=0;i<80;i++){ float d = sdScene(ro + rd*t); if(d < 0.001){ hit = true; break; } t += d; if(t > 20.0) break; } vec3 bg = mix(vec3(0.97,0.90,0.78), vec3(0.62,0.78,0.92), uv.y + 0.5); vec3 col = bg; if(hit){ vec3 p = ro + rd*t; vec3 n = calcN(p); vec3 l = normalize(vec3(LIGHT_DIR.x*cos(iTime*0.3), LIGHT_DIR.y, LIGHT_DIR.z)); float ndl = dot(n, l) * 0.5 + 0.5; float w = max(fwidth(ndl), 0.002); // antialias the ramp steps float b1 = smoothstep(T1 - w, T1 + w, ndl); float b2 = smoothstep(T2 - w, T2 + w, ndl); vec3 base = (p.y < -0.99) ? vec3(0.75,0.85,0.70) : MID_COL; vec3 ramp = mix(SHADOW_COL, base, b1); ramp = mix(ramp, LIT_COL, b2 * step(-0.99, p.y)); float rim = pow(1.0 - max(dot(n, -rd), 0.0), RIM_POWER); ramp += step(0.6, rim) * 0.25 * step(-0.99, p.y); col = ramp; } fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Combines with - [Inverted-hull outlines](https://texelatlas.vercel.app/t/inverted-hull-outline.md): Hull pass supplies the ink line; toon pass supplies the flat colour bands on the mesh itself. - [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md): Edge pass draws creases and silhouettes over the toon-shaded colour buffer. ## Combination ideas - [Toon highlights that do not sparkle](https://texelatlas.vercel.app/ideas/variance-aware-toon-bands/) ## Sources 1. [primary] Amy Gooch, Bruce Gooch, Peter Shirley, Elaine Cohen (1998) A non-photorealistic lighting model for automatic technical illustration. Proceedings of the 25th annual conference on Computer graphics and interactive techniques - SIGGRAPH '98. https://doi.org/10.1145/280814.280950 (verified via crossref on 2026-11-29) 2. [tutorial] Wikipedia Cel shading (outline section). en.wikipedia.org. https://en.wikipedia.org/wiki/Cel_shading (verified via http on 2026-11-29) ## Cite this entry Texel. "Toon / cel shading with lighting ramps." https://texelatlas.vercel.app/t/toon-shading/ (accessed 2026-12-01). --- id: "trellis-2" title: "TRELLIS.2 (O-Voxel structured latents)" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [ldr-image] outputs: [mesh, material-params] style: "both" dynamic: "static" cost: "heavy" authority: "Xiang et al., 2025" url: "https://texelatlas.vercel.app/t/trellis-2/" sources_verified_at: "2026-11-29" --- # TRELLIS.2 (O-Voxel structured latents) (Xiang et al., 2025) > Successor to TRELLIS that represents assets as sparse O-Voxels carrying geometry and PBR attributes, compresses them with a high-ratio sparse VAE and generates them with large flow-matching transformers. ## Reach for it when - image-to-3d loses thin structures and open surfaces - generated assets need pbr channels - cloth or leaves come out as closed blobs - need high-quality sparse 3d generation on a big gpu - assets with geometry and material attributes together ## How it works Instead of lifting 2D foundation features onto voxels, the model learns directly from native 3D data. The O-Voxel is a sparse voxel structure that stores both geometry (without requiring a watertight iso-surface) and surface attributes such as base colour, roughness, metallic and opacity. A Sparse Compression VAE reduces spatial resolution by a large factor to give a compact latent, and flow-matching transformers generate that latent from an image. Because the representation is not an iso-surface field, open surfaces, non-manifold and internal structure survive the round trip, and conversions between mesh and O-Voxel are described as rendering-free. ## When to use it Choose it when image-to-3D must keep open surfaces (cloth, leaves), thin structure or PBR channels, and you have a large GPU. Prefer [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) for the lighter first-generation model with Gaussian output, [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) for another PBR-capable pipeline, and [TripoSR](https://texelatlas.vercel.app/t/triposr.md) when only a quick shape is needed. ## Cost heavy — The repo gives timings by output resolution on an H100; consult it rather than relying on a figure here. ## Failure modes - Very large model and memory use restrict it to high-end GPUs - Generated PBR maps can bake in lighting from the input photo - Cannot hallucinate unseen sides faithfully; they are plausible rather than correct - Alpha / opacity handling can leave jagged cut-outs on foliage ## Dataflow - Inputs: ldr-image - Outputs: mesh, material-params - Platforms: cuda, python ## Lineage - extends [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) ## Sources 1. [primary] Jianfeng Xiang, Xiaoxue Chen, Sicheng Xu, Ruicheng Wang, Zelong Lv, Yu Deng, Hongyuan Zhu, Yue Dong, Hao Zhao, Nicholas Jing Yuan, Jiaolong Yang (2025) Native and Compact Structured Latents for 3D Generation. arXiv preprint (cs.CV). https://arxiv.org/abs/2512.14692 (verified via arxiv on 2026-11-29) 2. [implementation] microsoft (2025) microsoft/TRELLIS.2. https://github.com/microsoft/TRELLIS.2 License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "TRELLIS.2 (O-Voxel structured latents)." https://texelatlas.vercel.app/t/trellis-2/ (accessed 2026-12-01). --- id: "trellis" title: "TRELLIS (Structured 3D Latents)" aliases: [SLAT] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [text-prompt, ldr-image] outputs: [gaussians, radiance-field, mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Xiang et al., 2024" url: "https://texelatlas.vercel.app/t/trellis/" sources_verified_at: "2026-11-29" --- # TRELLIS (Structured 3D Latents) (Xiang et al., 2024) > Encodes an asset as features attached to active cells of a sparse voxel grid, then generates it with two rectified-flow transformers (structure, then features) and decodes to Gaussians, radiance fields or a mesh. ## Reach for it when - generate high quality 3d assets from text or image - need output in multiple formats like mesh or gaussians - structured latent for 3d generation - ai 3d models with good geometry and appearance ## How it works A 3D asset is rendered from many views, features from a pretrained vision model are aggregated onto the voxels that intersect the surface, and a sparse VAE compresses them into a structured latent (SLAT): a list of occupied voxel positions plus a latent vector per voxel. Generation is two-stage. A first flow transformer predicts which voxels are occupied (the coarse structure); a second, sparse-aware transformer fills in the latent vector at each of those voxels. Separate decoders turn the same SLAT into 3D Gaussians, a radiance field or a mesh, so one model serves several output formats. Text or image conditioning enters through cross-attention. ## When to use it Choose it for MIT-licensed image- or text-to-3D when you want Gaussian or mesh output with decent textures and can run a CUDA GPU with a large memory budget. Prefer [TRELLIS.2 (O-Voxel structured latents)](https://texelatlas.vercel.app/t/trellis-2.md) when you need PBR channels and arbitrary topology, [Hunyuan3D 2.1](https://texelatlas.vercel.app/t/hunyuan3d-2-1.md) for PBR-textured meshes, and [TripoSR](https://texelatlas.vercel.app/t/triposr.md) for the fastest throw-away result. ## Cost heavy — Seconds to tens of seconds per asset on a datacentre GPU; consult the repo for hardware requirements. Measured GPU Weight: 11.84× baseline (moderate) — 0.3896 ms median / 0.4209 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 9.57× baseline (moderate) — 0.1521 ms median (2.56× faster on L4). Ampere A100 scaling: 7.38× baseline (moderate) — 0.2125 ms median (1.83× faster on A100). ## Failure modes - Voxel-grid structure stage limits thin surfaces and sub-voxel detail - Mesh decoding from the SLAT can show holes or bumpy surfaces on complex objects - Texture is baked appearance without separate PBR maps - Weak on scenes or multi-object layouts, which are outside the training distribution - Heavy install: custom sparse-convolution and attention backends ## Dataflow - Inputs: text-prompt, ldr-image - Outputs: gaussians, radiance-field, mesh - Platforms: cuda, python ## Presets ### TRELLIS image-to-3D, repo defaults (json-params; parameter preset) ```json { "seed": 1, "sparse_structure_sampler_params": { "steps": 12, "cfg_strength": 7.5 }, "slat_sampler_params": { "steps": 12, "cfg_strength": 3 }, "glb_simplify": 0.95, "glb_texture_size": 1024 } ``` Attribution: Values taken from the example script in microsoft/TRELLIS (MIT licence).; basis: 2 ### TRELLIS (SLAT) — sparse active surface voxel latents (left) vs decoded 3D asset (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_VOXEL_RES": 12, "P_LATENT_GLOW": 0.95, "P_ROT_SPEED": 0.58, "P_SPLIT": 0.48 } ``` ```glsl const float P_VOXEL_RES = 12.0; // P Sparse Grid Res [6.0, 20.0, 1.0] const float P_LATENT_GLOW = 0.95; // P SLAT Feature Glow [0.1, 1.6, 0.05] const float P_ROT_SPEED = 0.58; // P Orbit Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P SLAT / Decoded [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Sculpted intertwined double-arch / knot object float mapTarget(vec3 q) { float t1 = length(vec2(length(q.xz) - 0.46, q.y)) - 0.20; float t2 = length(vec2(length(q.xy) - 0.46, q.z)) - 0.18; float h = clamp(0.5 + 0.5 * (t2 - t1) / 0.14, 0.0, 1.0); return (mix(t2, t1, h) - 0.14 * h * (1.0 - h)) * 0.85; } vec3 calcNormal(vec3 q) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapTarget(q + e.xyy) - mapTarget(q - e.xyy), mapTarget(q + e.yxy) - mapTarget(q - e.yxy), mapTarget(q + e.yyx) - mapTarget(q - e.yyx) )); } // Sparse voxel box distance around active surface voxels (TRELLIS SLAT) float mapSparseVoxels(vec3 q, float voxRes, out vec3 cellId) { float s = 1.0 / voxRes; cellId = floor(q * voxRes + 0.5); vec3 vc = cellId * s; float dCenter = mapTarget(vc); if (abs(dCenter) < s * 0.82) { vec3 local = abs(q - vc) - vec3(s * 0.44); return length(max(local, 0.0)) + min(max(local.x, max(local.y, local.z)), 0.0); } return max(abs(dCenter) - s * 0.72, s * 0.35); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float voxRes = clamp(floor(P_VOXEL_RES + 0.5), 6.0, 22.0); float glow = clamp(P_LATENT_GLOW, 0.05, 1.8); float spin = iTime * max(P_ROT_SPEED, 0.0) * 0.52; vec3 ro = vec3(0.0, 0.16, 2.35); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.03), -1.55)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; ro.yz = rot2(0.28) * ro.yz; rd.yz = rot2(0.28) * rd.yz; vec3 col = mix(vec3(0.020, 0.028, 0.048), vec3(0.056, 0.076, 0.124), smoothstep(-0.55, 0.55, uv.y)); vec3 lDir = normalize(vec3(0.55, 0.82, 0.48)); if (screenX < split) { // Left: Sparse active 3D voxel shell (SLAT) colored by latent feature embeddings float t = 0.0; bool hit = false; vec3 cid = vec3(0.0); for (int i = 0; i < 64; i++) { float d = mapSparseVoxels(ro + rd * t, voxRes, cid); if (d < 0.003) { hit = true; break; } t += max(d * 0.72, 0.008); if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 vc = cid / voxRes; vec3 local = (p - vc) * voxRes; vec3 an = abs(local); vec3 fn = (an.x > an.y && an.x > an.z) ? vec3(sign(local.x), 0.0, 0.0) : (an.y > an.z ? vec3(0.0, sign(local.y), 0.0) : vec3(0.0, 0.0, sign(local.z))); float diff = max(dot(fn, lDir), 0.0); // Latent feature RGB vector attached to each active voxel vec3 featCol = 0.5 + 0.5 * sin(cid * vec3(0.55, 0.72, 0.48) + vec3(0.0, 2.1, 4.2)); float edge = smoothstep(0.36, 0.43, max(an.x, max(an.y, an.z))); col = featCol * (0.32 + 0.75 * diff) * (0.75 + 0.35 * glow) + vec3(0.95) * edge * 0.28; } } else { // Right: Decoded high-resolution smooth 3D PBR asset float t = 0.0; bool hit = false; for (int i = 0; i < 56; i++) { float d = mapTarget(ro + rd * t); if (d < 0.0025) { hit = true; break; } t += d; if (t > 5.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 48.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = mix(vec3(0.14, 0.68, 0.86), vec3(0.96, 0.48, 0.24), smoothstep(-0.45, 0.45, p.y)); col = alb * (0.28 + 0.82 * diff) + vec3(1.0, 0.96, 0.90) * spec * 0.52 + vec3(0.28, 0.88, 0.98) * fres * 0.38; } } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extended by [TRELLIS.2 (O-Voxel structured latents)](https://texelatlas.vercel.app/t/trellis-2.md) ## Combines with - [Hunyuan3D-Paint](https://texelatlas.vercel.app/t/hunyuan3d-paint.md): TRELLIS produces a mesh; a separate texturing model can re-paint it with PBR-ready maps. ## Sources 1. [primary] Jianfeng Xiang, Zelong Lv, Sicheng Xu, Yu Deng, Ruicheng Wang, Bowen Zhang, Dong Chen, Xin Tong, Jiaolong Yang (2024) Structured 3D Latents for Scalable and Versatile 3D Generation. arXiv preprint (cs.CV). https://arxiv.org/abs/2412.01506 (verified via arxiv on 2026-11-29) 2. [primary] Jianfeng Xiang, Zelong Lv, Sicheng Xu, Yu Deng, Ruicheng Wang, Bowen Zhang, Dong Chen, Xin Tong, Jiaolong Yang (2025) Structured 3D Latents for Scalable and Versatile 3D Generation. 2025 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/cvpr52734.2025.02000 (verified via crossref on 2026-11-29) 3. [implementation] microsoft (2024) microsoft/TRELLIS. https://github.com/microsoft/TRELLIS License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "TRELLIS (Structured 3D Latents)." https://texelatlas.vercel.app/t/trellis/ (accessed 2026-12-01). --- id: "triplanar-mapping" title: "Triplanar mapping" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender] year_introduced: 2007 inputs: [texture, normals, mesh] outputs: [texture, material-params] style: "both" dynamic: "both" cost: "cheap" authority: "Geiss" url: "https://texelatlas.vercel.app/t/triplanar-mapping/" sources_verified_at: "2026-11-29" --- # Triplanar mapping (Geiss) > Texturing without UVs: sample a texture along the three world axes and blend by the surface normal. The standard fix for terrain cliffs, procedural meshes and anything where UV stretching is unavoidable. ## Reach for it when - textures stretch on cliffs and steep terrain - procedural meshes have no uvs - need to texture rocks without unwrapping - uv stretching ruins terrain slopes ## How it works Project the world position onto the three axis-aligned planes (yz, xz, xy) to form three UV sets and fetch the texture three times. Blend weights come from the absolute normal raised to a sharpness power and renormalised, w = |n|^k / sum |n|^k, so each projection dominates where it faces the surface. Normal maps need care: each projection's tangent-space normal has to be swizzled into world space (the whiteout or reoriented normal blend methods handle this properly) before blending. Vertex or splat-weighted material masks can pick different textures per layer. Because there are no UVs, the technique works on SDF-meshed, voxel and heightfield terrain, and the cost is three fetches per texture rather than one. ## When to use it Choose it for terrain, rocks, procedurally generated meshes and any mesh without good UVs. Prefer UV mapping with an atlas when UVs exist and detail must be authored. Use [Histogram-preserving blending (stochastic texturing)](https://texelatlas.vercel.app/t/histogram-preserving-blending.md) or [Hex-tiling](https://texelatlas.vercel.app/t/hex-tiling.md) on top to break repetition visible on large triplanar surfaces. Use [Surface gradient based bump mapping framework](https://texelatlas.vercel.app/t/surface-gradient-bump-mapping.md) to blend normals robustly. ## Cost cheap — Three texture fetches per map instead of one; bandwidth multiplies with layer count. Measured GPU Weight: 1.29× baseline (feather) — 0.0423 ms median / 0.0439 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.19× baseline (feather) — 0.0189 ms median (2.24× faster on L4). Ampere A100 scaling: 1.03× baseline (feather) — 0.0297 ms median (1.42× faster on A100). ## Failure modes - Visible blending seams and doubled detail where two projections overlap on 45-degree slopes - Naive normal blending produces wrong lighting; swizzle or use reoriented normal mapping - Texture repeats visibly over large areas without anti-tiling - Texture scale follows world space, so scaled objects show stretched or varying texel density ## Engine support - babylonjs: official — `new BABYLON.TriPlanarMaterial('m', scene) from @babylonjs/materials` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/materials/src/triPlanar/triPlanarMaterial.ts, checked 2026-12-01) — Also TriPlanarBlock in Node Material. - blender: builtin — `Image Texture node > Projection = Box (with Blend)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/image.html, checked 2026-12-01) - godot: builtin — `BaseMaterial3D.uv1_triplanar = true` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/BaseMaterial3D.xml, checked 2026-12-01) - threejs: builtin — `import { triplanarTexture } from 'three/tsl'` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/utils/TriplanarTextures.js, checked 2026-12-01) — TSL / WebGPURenderer. - unity: builtin — `Shader Graph > Triplanar Node` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.shadergraph/Documentation~/Triplanar-Node.md, checked 2026-12-01) — Shader Graph node, URP and HDRP. - unreal: builtin — `Material function WorldAlignedTexture (Texturing material functions)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/texturing-material-functions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: texture, normals, mesh - Outputs: texture, material-params - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, blender ## Presets ### Planar projection (left) vs triplanar projection (right) (glsl-fragment; rendered 2026-11-29) ```json { "SCALE": 3, "SHARPNESS": 4 } ``` ```glsl // Texturing without UVs. Left sphere: a single planar projection along z stretches the texture toward the // silhouette. Right sphere: triplanar projection blends three axis-aligned lookups by |normal|^4. const float SCALE = 3.0; const float SHARPNESS = 4.0; vec3 tex(vec2 uv) { vec2 f = fract(uv); vec3 c = mix(vec3(0.9, 0.55, 0.2), vec3(0.2, 0.3, 0.55), mod(floor(uv.x) + floor(uv.y), 2.0)); return mix(c, vec3(1.0), smoothstep(0.03, 0.0, abs(length(f - 0.5) - 0.3))); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 4.0), rd = normalize(vec3(uv, -2.3)); vec3 col = vec3(0.08) + 0.06 * uv.y; mat3 rot = mat3(0.87, 0.0, -0.5, 0.0, 1.0, 0.0, 0.5, 0.0, 0.87); for (int i = 0; i < 2; i++) { vec3 c = vec3(i == 0 ? -0.5 : 0.5, 0.0, 0.0); vec3 oc = ro - c; float b = dot(oc, rd); float h = b * b - dot(oc, oc) + 0.46 * 0.46; if (h < 0.0) continue; vec3 n = normalize(ro + rd * (-b - sqrt(h)) - c); vec3 q = rot * n * 0.46; vec3 alb; if (i == 0) alb = tex(q.xy * SCALE * 2.2); else { vec3 w = pow(abs(rot * n), vec3(SHARPNESS)); w /= w.x + w.y + w.z; alb = tex(q.yz * SCALE * 2.2) * w.x + tex(q.zx * SCALE * 2.2) * w.y + tex(q.xy * SCALE * 2.2) * w.z; } col = alb * (0.2 + 0.9 * max(dot(n, normalize(vec3(0.5, 0.6, 0.7))), 0.0)); } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Hex-tiling](https://texelatlas.vercel.app/t/hex-tiling.md): Hex-tiling breaks the repetition of each triplanar projection. ## Sources 1. [primary] Ryan Geiss Generating Complex Procedural Terrains Using the GPU. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-1-generating-complex-procedural-terrains-using-gpu (verified via http on 2026-11-29) ## Cite this entry Texel. "Triplanar mapping." https://texelatlas.vercel.app/t/triplanar-mapping/ (accessed 2026-12-01). --- id: "triposr" title: "TripoSR" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2024 inputs: [ldr-image] outputs: [mesh] style: "both" dynamic: "static" cost: "heavy" authority: "Tochilkin et al., 2024" url: "https://texelatlas.vercel.app/t/triposr/" sources_verified_at: "2026-11-29" --- # TripoSR (Tochilkin et al., 2024) > An open, MIT-licensed LRM-style transformer that turns one background-removed image into a triplane-based mesh in well under a second on a high-end GPU. ## Reach for it when - need a mesh from a single image in under a second - quick prototyping of props from photos - permissively licensed single image to 3d - fast single-view reconstruction for tools - background-removed picture to 3d model instantly ## How it works It follows the LRM recipe: image tokens from a vision transformer feed a transformer that outputs a triplane, which is decoded into a density and colour field. The authors changed the data curation, rendering and training choices and the geometry-supervision losses relative to the original LRM. Inference removes the background, runs one forward pass and extracts a mesh with marching cubes at a chosen resolution; the repo can also bake a UV texture instead of vertex colours. Output is a single closed shape without separate parts or materials. ## When to use it Choose it for fast, permissively licensed single-image meshes in tools and games prototyping. Prefer [InstantMesh](https://texelatlas.vercel.app/t/instantmesh.md) when you want sharper results through multi-view generation, [TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md) or [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md) when texture and geometry quality matter more than latency, and [Large Reconstruction Model (LRM)](https://texelatlas.vercel.app/t/large-reconstruction-model.md) for the underlying method. ## Cost heavy — Authors report sub-second inference on an A100-class GPU; treat as qualitative on other hardware. ## Failure modes - Back side is guessed and often too smooth - Thin structures and holes close up under marching cubes - Vertex-colour output lacks material channels such as roughness or metallic - Needs a clean, centred, background-removed object photo ## Dataflow - Inputs: ldr-image - Outputs: mesh - Platforms: cuda, python ## Sources 1. [primary] Dmitry Tochilkin, David Pankratz, Zexiang Liu, Zixuan Huang, Adam Letts, Yangguang Li, Ding Liang, Christian Laforte, Varun Jampani, Yan-Pei Cao (2024) TripoSR: Fast 3D Object Reconstruction from a Single Image. arXiv preprint (cs.CV). https://arxiv.org/abs/2403.02151 (verified via arxiv on 2026-11-29) 2. [implementation] VAST-AI-Research (2024) VAST-AI-Research/TripoSR. https://github.com/VAST-AI-Research/TripoSR License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "TripoSR." https://texelatlas.vercel.app/t/triposr/ (accessed 2026-12-01). --- id: "tufted-laplacian" title: "Tufted Cover Laplacian" domain: "geometry" stage: "geometry" realtime: "interactive" platforms: [cpu, python] year_introduced: 2020 inputs: [mesh, point-cloud] outputs: [mesh] style: "both" dynamic: "static" cost: "interactive" authority: "Sharp & Crane, 2020" url: "https://texelatlas.vercel.app/t/tufted-laplacian/" sources_verified_at: "2026-11-29" --- # Tufted Cover Laplacian (Sharp & Crane, 2020) > A Laplacian for non-manifold, non-orientable or disconnected triangle meshes. It builds a locally manifold tufted cover and applies intrinsic Delaunay to get a well-behaved cotan operator on messy geometry. ## Reach for it when - geometry processing fails on non-manifold meshes - mesh with duplicate vertices breaks laplacian - open boundaries and broken topology in a mesh solver - need robust cotan laplacian for dirty meshes ## How it works Real-world meshes often have non-manifold edges, duplicate vertices or open boundaries that break standard discrete Laplacians. The tufted cover replaces each triangle with a pair of oppositely oriented copies, and glues the copies together so that the result is a manifold, oriented surface for any input. Adjacent triangles are connected through edges even when the original was non-manifold. A small mass-matrix correction keeps the operator well-defined. On top of that, the intrinsic Delaunay flips are applied to give non-negative weights, and the resulting operator can drive heat-method distance, diffusion, smoothing and spectral algorithms. The operator reduces to the standard cotan Laplacian on clean manifold meshes. ## When to use it Choose it when you need Laplacian-based tools on triangle soups, polygon-soup scans or meshes you cannot repair. Prefer cleaning the mesh and the standard [Intrinsic Delaunay Triangulation](https://texelatlas.vercel.app/t/intrinsic-delaunay-triangulation.md) pipeline when the mesh is already manifold, and [Screened Poisson Surface Reconstruction](https://texelatlas.vercel.app/t/screened-poisson-surface-reconstruction.md) when you need a watertight replacement rather than an operator. ## Cost interactive — Same as a regular cotan Laplacian solve plus a linear-time construction. ## Failure modes - Results on strongly non-manifold input depend on how the tufting duplicates triangles, which can surprise - Spectral quantities relate to the doubled cover, not the original surface - Vertex coincidences without shared indices (unwelded soups) must be merged first - Not a repair tool: output geometry is unchanged ## Dataflow - Inputs: mesh, point-cloud - Outputs: mesh - Platforms: cpu, python ## Combines with - [Heat Method for Geodesic Distance](https://texelatlas.vercel.app/t/heat-method-geodesics.md): Run geodesic distance on meshes that are not manifold. - [Taubin Smoothing](https://texelatlas.vercel.app/t/taubin-smoothing.md): Use the tufted Laplacian in the smoothing operator for messy input. ## Sources 1. [primary] Nicholas Sharp, Keenan Crane (2020) A Laplacian for Nonmanifold Triangle Meshes. Computer Graphics Forum. https://doi.org/10.1111/cgf.14069 (verified via crossref on 2026-11-29) 2. [implementation] nmwsharp (2020) nmwsharp/nonmanifold-laplacian. https://github.com/nmwsharp/nonmanifold-laplacian License: MIT. (verified via github on 2026-11-29) 3. [implementation] nmwsharp (2017) nmwsharp/geometry-central. https://github.com/nmwsharp/geometry-central License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Tufted Cover Laplacian." https://texelatlas.vercel.app/t/tufted-laplacian/ (accessed 2026-12-01). --- id: "unified-particle-physics" title: "Unified particle physics" aliases: [FleX] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cuda, desktop-gpu] year_introduced: 2014 inputs: [particles] outputs: [particles, mesh] style: "both" dynamic: "dynamic" cost: "medium" authority: "Macklin et al., 2014" url: "https://texelatlas.vercel.app/t/unified-particle-physics/" sources_verified_at: "2026-11-29" --- # Unified particle physics (Macklin et al., 2014) > Single GPU particle framework that simulates rigid bodies, cloth, soft bodies, fluids and gases together using PBD-style constraints and two-way coupling. ## Reach for it when - want fluids, cloth and rigid bodies interacting in one solver - two-way coupling between liquid and solids - separate simulators don't interact properly - mixed-material gpu simulation in real time ## How it works Every object is a set of particles. Rigid bodies and soft bodies use shape-matching clusters, cloth uses distance and bending constraints, fluids use position-based density constraints, and gases use a variant with an expansion term. All constraint types are solved in the same Jacobi-style loop on the GPU, with a shared uniform-grid neighbour search for collisions, so different phases (cloth versus fluid, rigid versus gas) interact through ordinary contact constraints with mass-ratio scaling. Averaging constraint corrections per particle and applying a relaxation factor keeps the Jacobi iteration stable. This design is the basis of the NVIDIA FleX library. ## When to use it Choose it for scenes mixing liquids, cloth and solids with two-way coupling in one GPU solver. Prefer [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) for a single-material solver with calibrated stiffness, [Position Based Fluids](https://texelatlas.vercel.app/t/position-based-fluids.md) for fluids alone, and [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) for large rigid-body piles needing accurate stacking. ## Cost medium — GPU-bound by particle and contact count. ## Failure modes - Rigid bodies built of particles stack poorly and show surface bumpiness - Jacobi iteration with large mass ratios converges slowly - Fluids and gases have visibly artificial viscosity - Particles must be sized uniformly for the neighbour grid, limiting detail ## Dataflow - Inputs: particles - Outputs: particles, mesh - Platforms: cuda, desktop-gpu ## Sources 1. [primary] Miles Macklin, Matthias Müller, Nuttapong Chentanez, Tae-Yong Kim (2014) Unified particle physics for real-time applications. ACM Transactions on Graphics. https://doi.org/10.1145/2601097.2601152 (verified via crossref on 2026-11-29) 2. [implementation] NVIDIAGameWorks (2017) NVIDIAGameWorks/FleX. https://github.com/NVIDIAGameWorks/FleX License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Unified particle physics." https://texelatlas.vercel.app/t/unified-particle-physics/ (accessed 2026-12-01). --- id: "universal-photometric-stereo" title: "Universal Photometric Stereo (SDM-UniPS)" aliases: [SDM-UniPS, UniPS] domain: "capture" stage: "capture" realtime: "offline" platforms: [cuda, python] year_introduced: 2023 inputs: [photos] outputs: [normals] style: "photoreal" dynamic: "static" cost: "offline" authority: "Ikehata, 2023" url: "https://texelatlas.vercel.app/t/universal-photometric-stereo/" sources_verified_at: "2026-11-29" --- # Universal Photometric Stereo (SDM-UniPS) (Ikehata, 2023) > A neural network that predicts high-resolution surface normals from multi-light photos with unknown, arbitrary illumination and no object mask, including highly specular materials. ## Reach for it when - don't know my light positions for multi-light capture - glossy objects break normal recovery from photos - lighting is mixed or from the environment - need high-res normals without a mask or calibration - classic normal estimation fails on shiny material ## How it works Instead of calibrating light directions, the network encodes global lighting context across all input images with a transformer-style aggregation, so each pixel can reason about illumination implicitly. A scale-invariant spatial-and-directional design lets it process high-resolution images by working on sampled patches and recombining them, which keeps fine detail without a mask. Training uses synthetic renders with diverse shapes, SVBRDFs and lighting including near and environment lights. At inference you feed N images taken with fixed camera and varying lighting and obtain a normal map. It trades the physical guarantees of classic least squares for robustness to unknown light and complex materials. ## When to use it Choose it when lighting is unknown, mixed or environment-based, or the material is glossy and classic [Photometric Stereo](https://texelatlas.vercel.app/t/photometric-stereo.md) fails. Prefer [Photometric Stereo](https://texelatlas.vercel.app/t/photometric-stereo.md) when you control calibrated lights and want a transparent, reproducible solve. Run [Bilateral Normal Integration](https://texelatlas.vercel.app/t/bilateral-normal-integration.md) afterwards if you need a height field. ## Cost offline — Network inference on GPU; seconds to minutes per scene depending on resolution. ## Failure modes - Out-of-distribution materials or lighting can yield plausible but wrong normals without any uncertainty signal - Image sets with too little lighting variation leave normals ambiguous (bas-relief style ambiguity) - Needs a very still camera and object; any motion corrupts the per-pixel observations - Training-data licence and weights restrictions apply, check the repo ## Dataflow - Inputs: photos - Outputs: normals - Platforms: cuda, python ## Lineage - extends [Photometric Stereo](https://texelatlas.vercel.app/t/photometric-stereo.md) ## Combination ideas - [Drawings to relief via generated relighting](https://texelatlas.vercel.app/ideas/relit-drawings-to-relief/) ## Sources 1. [primary] Satoshi Ikehata (2023) Scalable, Detailed and Mask-Free Universal Photometric Stereo. 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/cvpr52729.2023.01268 (verified via crossref on 2026-11-29) 2. [primary] Satoshi Ikehata (2023) Scalable, Detailed and Mask-Free Universal Photometric Stereo. arXiv preprint (cs.CV). https://arxiv.org/abs/2303.15724 (verified via arxiv on 2026-11-29) 3. [implementation] satoshi-ikehata (2023) satoshi-ikehata/SDM-UniPS-CVPR2023. https://github.com/satoshi-ikehata/SDM-UniPS-CVPR2023 License: NOASSERTION. (verified via github on 2026-11-29) ## Cite this entry Texel. "Universal Photometric Stereo (SDM-UniPS)." https://texelatlas.vercel.app/t/universal-photometric-stereo/ (accessed 2026-12-01). --- id: "variance-shadow-maps" title: "Variance Shadow Maps" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2006 inputs: [depth] outputs: [visibility-mask] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Donnelly & Lauritzen, 2006" url: "https://texelatlas.vercel.app/t/variance-shadow-maps/" sources_verified_at: "2026-11-29" --- # Variance Shadow Maps (Donnelly & Lauritzen, 2006) > Stores depth and depth squared per texel so the shadow map can be blurred and mipmapped, then bounds visibility with Chebyshev's inequality instead of a binary test. ## Reach for it when - shadow map edges are aliased and can't be blurred - want soft shadows using ordinary gpu filtering - blurring depth maps gives wrong results - cheap soft shadows from a pre-blurred map ## How it works A VSM texture holds the first two moments of the depth distribution (E[z] and E[z^2]). Because these are linear quantities, the map can be filtered with separable blurs, mipmaps or anisotropic hardware sampling, which yields large soft kernels at constant cost. At shade time the mean and variance give an upper bound on the fraction of the filter footprint lying beyond the receiver depth via Chebyshev's one-sided inequality, and that bound is used as visibility. Fully lit regions return exactly one, so the technique is cheap, but the bound is loose when several occluders overlap in the footprint. ## When to use it Choose it when you need cheap, large, antialiased soft shadows from a prefilterable map and can tolerate tuning. Prefer [Exponential Variance Shadow Maps](https://texelatlas.vercel.app/t/exponential-variance-shadow-maps.md) or [Moment Shadow Maps](https://texelatlas.vercel.app/t/moment-shadow-maps.md) when light bleeding is visible, [Percentage-Closer Filtering](https://texelatlas.vercel.app/t/percentage-closer-filtering.md) for robustness without a special format, and [Percentage-Closer Soft Shadows](https://texelatlas.vercel.app/t/percentage-closer-soft-shadows.md) for distance-dependent penumbrae. ## Cost cheap — Needs a two-channel float or half-float target and a blur pass; sampling is a single filtered fetch. Measured GPU Weight: 12.7× baseline (moderate) — 0.4178 ms median / 0.4206 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 9.52× baseline (moderate) — 0.1513 ms median (2.76× faster on L4). Ampere A100 scaling: 8.05× baseline (moderate) — 0.2318 ms median (1.8× faster on A100). ## Failure modes - Light bleeding where occluders overlap at different depths - Precision loss with 16-bit moments on large depth ranges - Higher memory per cascade than a plain depth map - Needs a light-bleeding clamp that darkens real penumbrae ## Engine support - threejs: builtin — `renderer.shadowMap.type = THREE.VSMShadowMap` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/constants.js, checked 2026-12-01) ## Dataflow - Inputs: depth - Outputs: visibility-mask - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Left: hard depth comparison on a 64x64 map. Right: variance shadow map, pre-filtered moments and a Chebyshev bound (glsl-fragment; rendered 2026-11-29) ```json { "RES": 64, "BIAS": 0.1, "K": 2, "MINVAR": 0.0004 } ``` ```glsl float hash(vec2 c){uvec2 u=uvec2(ivec2(floor(c)));uint h=u.x*1597334673u^u.y*3812015801u;h^=h>>15;h*=2246822519u;h^=h>>13;h*=3266489917u;h^=h>>16;return float(h)*(1./4294967296.);} float lum(vec3 c){return dot(c,vec3(.2126,.7152,.0722));} vec3 gam(vec3 c){return pow(clamp(c,0.,1.),vec3(1./2.2));} const vec3 RO=vec3(0.,0.15,-5.0); const vec2 SH=vec2(0.,.17); vec2 proj(vec3 v){return v.xy/v.z*1.7+SH;} vec3 unproj(vec2 u,float z){return RO+vec3((u-SH)*z/1.7,z);} const vec3 LD=vec3(-0.75,0.55,0.37); const vec4 SP[3]=vec4[3](vec4(-0.32,-0.25,0.3,0.45),vec4(0.38,-0.47,-0.15,0.23),vec4(0.02,0.38,0.75,0.17)); float sdf(vec3 p){float d=p.y+0.7;for(int i=0;i<3;i++)d=min(d,length(p-SP[i].xyz)-SP[i].w);return d;} float isect(vec3 ro,vec3 rd,out vec3 n){ float t=1e9;n=vec3(0.); if(rd.y<-1e-4){float tp=(-0.7-ro.y)/rd.y;if(tp>1e-4){t=tp;n=vec3(0.,1.,0.);}} for(int i=0;i<3;i++){vec3 oc=ro-SP[i].xyz;float b=dot(oc,rd),c=dot(oc,oc)-SP[i].w*SP[i].w,h=b*b-c; if(h>0.){float ts=-b-sqrt(h);if(ts>1e-4&&ts1e8?1e9:t*rd.z;} vec3 lit(vec3 P,vec3 N){vec3 q;float sh=isect(P+N*2e-3,LD,q)>1e8?1.:0.; return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*sh*1.25);} vec3 shadeBasic(vec2 uv){vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);if(t>1e8)return sky(rd); return mix(lit(RO+rd*t,n),sky(rd),smoothstep(6.,25.,t));} const float EXT=3.2; vec3 lU(){return normalize(cross(vec3(0.,1.,0.),LD));} vec3 lV(){return cross(LD,lU());} vec2 toL(vec3 P){return vec2(dot(P,lU()),dot(P,lV()));} float recv(vec3 P){return 10.-dot(P,LD);} float smTex(vec2 st,float res){float tx=2.*EXT/res;vec2 c=(floor(st/tx)+.5)*tx;vec3 n; return isect(LD*10.+lU()*c.x+lV()*c.y,-LD,n);} float vis1(vec3 P,vec3 N,vec2 st,vec2 o,float res,float b){float tx=2.*EXT/res;vec2 cc=(floor((st+o)/tx)+.5)*tx;vec3 q; float d=isect(LD*10.+lU()*cc.x+lV()*cc.y,-LD,q);vec2 e=cc-st; float zr=recv(P)+(e.x*dot(N,lU())+e.y*dot(N,lV()))/max(dot(N,LD),.15); return zr-b>d?0.:1.;} vec3 shadeV(vec3 P,vec3 N,float vis){return alb(P)*(vec3(.55,.62,.75)*(.45+.35*N.y-.25*N.z)*.45+vec3(1.,.95,.85)*max(dot(N,LD),0.)*vis*1.3);} const float RES=64.0; // P const float BIAS=0.1; // P const int K=2; // P const float MINVAR=0.0004; // P void mainImage(out vec4 fragColor,in vec2 fragCoord){ vec2 u0=(fragCoord-.5*iResolution.xy)/iResolution.y;bool R=u0.x>0.;vec2 uv=vec2(u0.x+(R?-.25:.25),u0.y); vec3 rd=rayDir(uv),n;float t=isect(RO,rd,n);vec3 col=sky(rd); if(t<1e8){ vec3 P=RO+rd*t;float zr=recv(P);vec2 st=toL(P);float vis; if(!R) vis=zr-BIAS>smTex(st,RES)?0.:1.; else{ float tx=2.*EXT/RES;vec2 m=vec2(0.); for(int j=-K;j<=K;j++)for(int i=-K;i<=K;i++){float d=(smTex(st+vec2(float(i),float(j))*tx,RES)-7.)/6.;m+=vec2(d,d*d);} m/=float((2*K+1)*(2*K+1)); float tt=(zr-BIAS*.5-7.)/6.,v=max(m.y-m.x*m.x,MINVAR); vis=tt<=m.x?1.:v/(v+(tt-m.x)*(tt-m.x)); } col=mix(shadeV(P,n,vis),sky(rd),smoothstep(6.,25.,t)); } if(abs(u0.x)<.0015)col=vec3(1.);fragColor=vec4(gam(col),1.); } ``` Attribution: written for this index ## Lineage - extended by [Exponential Variance Shadow Maps](https://texelatlas.vercel.app/t/exponential-variance-shadow-maps.md) - extended by [Moment Shadow Maps](https://texelatlas.vercel.app/t/moment-shadow-maps.md) ## Sources 1. [primary] William Donnelly, Andrew Lauritzen (2006) Variance shadow maps. Proceedings of the 2006 symposium on Interactive 3D graphics and games - SI3D '06. https://doi.org/10.1145/1111411.1111440 (verified via crossref on 2026-11-29) 2. [tutorial] Andrew Lauritzen Summed-Area Variance Shadow Maps. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-8-summed-area-variance-shadow-maps (verified via http on 2026-11-29) ## Cite this entry Texel. "Variance Shadow Maps." https://texelatlas.vercel.app/t/variance-shadow-maps/ (accessed 2026-12-01). --- id: "verlet-integration-constraints" title: "Verlet integration with relaxation constraints" aliases: [Jakobsen method] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 2001 inputs: [particles] outputs: [particles, skeleton] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Jakobsen" url: "https://texelatlas.vercel.app/t/verlet-integration-constraints/" sources_verified_at: "2026-11-29" --- # Verlet integration with relaxation constraints (Jakobsen) > Stores current and previous positions instead of velocity and enforces constraints by repeatedly projecting positions, giving robust ropes, cloth and ragdolls in a few dozen lines. ## Reach for it when - need quick rope, cloth or cape in a few lines - ragdoll simulation explodes with velocity integration - want stable constraints that are easy to tune - creative coding physics with simple code ## How it works Positional Verlet updates `x_next = x + (x - x_prev) + a*dt^2`, so velocity is implicit. Constraints (fixed distance between particles, planes, pins) are satisfied by iterating over them several times per frame and moving the particles directly to satisfy each one, split by inverse mass. Because velocity is derived from the position change, projecting a particle out of a collider also removes the velocity into it, so collisions behave plausibly with no explicit impulse. Rigid bodies and ragdolls are built from particles linked by distance constraints into stiff tetrahedra or sticks. ## When to use it Choose it for quick, stable, easily-tuned rope, cloth, cape or ragdoll effects in games and creative coding. Prefer [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) or [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) when you need volume, bending, or time-step-independent stiffness, and [Sequential impulses (rigid bodies)](https://texelatlas.vercel.app/t/sequential-impulses.md) when rigid bodies must stack and have accurate friction and restitution. ## Cost cheap — Very cheap: linear in particles and constraints. Measured GPU Weight: 13.67× baseline (moderate) — 0.4238 ms median / 0.4419 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.81× baseline (moderate) — 0.1718 ms median (2.47× faster on L4). Ampere A100 scaling: 9.08× baseline (moderate) — 0.2616 ms median (1.62× faster on A100). ## Failure modes - Stiffness depends on iteration count: long chains stretch - Friction and restitution are crude; stacking stability is poor - Angular momentum is not conserved for rigid shapes built from particles - Fixed time step is assumed; variable dt changes the implicit velocity ## Engine support - godot: builtin — `SoftBody3D under GodotPhysics3D (GodotSoftBody3D::solve_constraints iteratively relaxes link constraints and updates velocity from position delta)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/godot_physics_3d/godot_soft_body_3d.cpp, checked 2026-12-01) - threejs: official — `examples/webgpu_compute_cloth.html` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/webgpu_compute_cloth.html, checked 2026-12-01) — Official WebGPU compute cloth example; not a library. ## Dataflow - Inputs: particles - Outputs: particles, skeleton - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Verlet Integration & Constraints — 2 relaxation sweeps (left) vs 16 Gauss-Seidel iterations (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_RELAX_ITERS": 14, "P_WIND_FORCE": 0.95, "P_WIRE_VIS": 0.85, "P_SPLIT": 0.48 } ``` ```glsl const float P_RELAX_ITERS = 14.0; // P Relaxation Iters [2.0, 24.0, 1.0] const float P_WIND_FORCE = 0.95; // P Wind Gust [0.0, 2.0, 0.05] const float P_WIRE_VIS = 0.85; // P Constraint Mesh [0.0, 1.5, 0.05] const float P_SPLIT = 0.48; // P Low / High Iter Split [0.0, 1.0, 0.02] // Analytic Verlet cloth surface height & sag modeled from Gauss-Seidel convergence rate (1 - c)^N vec3 clothSurface(vec2 q, float iters, float wind, float t) { // q.x in [-1, 1], q.y in [0, 1] (top pinned at y=1, hanging down to y=0) float drop = 1.0 - q.y; // Few iterations leave distance constraints stretched; high iterations converge to inextensible drape float stretchFactor = 0.34 / (1.0 + 0.32 * iters); float pinDip = (1.0 - abs(sin(q.x * 3.1415926 * 1.5))) * 0.06 * (1.0 + 2.4 * stretchFactor); float y = q.y * 1.05 - 0.50 - drop * drop * stretchFactor * 0.85 - pinDip * drop; float x = q.x * 0.82 * (1.0 - 0.06 * drop * (1.0 - stretchFactor)); // Travelling wind ripple obeying Verlet inertia x_new = 2x - x_prev + a*dt^2 float wave1 = sin(q.x * 4.2 - t * 2.6 + drop * 2.1) * 0.11; float wave2 = sin(q.x * 8.6 + t * 3.7 - drop * 3.8) * 0.042; float z = (wave1 + wave2) * wind * smoothstep(0.0, 0.35, drop) + 0.05 * drop * drop * wind; return vec3(x, y, z); } // Signed distance to hanging cloth sheet float mapCloth(vec3 p, float iters, float wind, float t, out vec2 uvCloth) { float drop = clamp((0.55 - p.y) / 1.05, 0.0, 1.0); float stretchFactor = 0.34 / (1.0 + 0.32 * iters); float effH = 1.05 + stretchFactor * 0.85; vec2 q = vec2(clamp(p.x / 0.82, -1.0, 1.0), clamp(1.0 - (0.55 - p.y) / effH, 0.0, 1.0)); uvCloth = q; vec3 surf = clothSurface(q, iters, wind, t); vec2 outBound = vec2(max(abs(p.x) - 0.82, 0.0), max(max(p.y - 0.55, surf.y - p.y - 0.01), 0.0)); float bottomY = clothSurface(vec2(q.x, 0.0), iters, wind, t).y; float dY = max(p.y - 0.55, bottomY - p.y); float dX = abs(p.x) - 0.82; float dSheet = abs(p.z - surf.z) - 0.016; return max(dSheet, max(dX, dY)); } vec3 calcNormal(vec3 p, float iters, float wind, float t) { vec2 e = vec2(0.004, 0.0); vec2 tmp; return normalize(vec3( mapCloth(p + e.xyy, iters, wind, t, tmp) - mapCloth(p - e.xyy, iters, wind, t, tmp), mapCloth(p + e.yxy, iters, wind, t, tmp) - mapCloth(p - e.yxy, iters, wind, t, tmp), mapCloth(p + e.yyx, iters, wind, t, tmp) - mapCloth(p - e.yyx, iters, wind, t, tmp) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isHigh = screenX >= split; float iters = isHigh ? clamp(P_RELAX_ITERS, 2.0, 24.0) : 2.0; float wind = max(P_WIND_FORCE, 0.0); float wireVis = clamp(P_WIRE_VIS, 0.0, 1.5); float t = iTime; vec3 ro = vec3(0.0, 0.02, 2.25); vec3 rd = normalize(vec3(uv, -1.55)); vec3 col = mix(vec3(0.028, 0.036, 0.056), vec3(0.075, 0.095, 0.142), smoothstep(-0.5, 0.55, uv.y)); // Top hanging rod (cylinder along x at y=0.56) float tRod = (0.0 - ro.z) / rd.z; vec3 pRod = ro + rd * tRod; if (abs(pRod.y - 0.56) < 0.026 && abs(pRod.x) < 0.92) { float cy = (pRod.y - 0.56) / 0.026; float shading = 0.35 + 0.65 * sqrt(max(1.0 - cy * cy, 0.0)); col = vec3(0.45, 0.52, 0.64) * shading; } float tHit = 0.0; bool hit = false; vec2 cUV = vec2(0.0); for (int i = 0; i < 64; i++) { vec3 p = ro + rd * tHit; float d = mapCloth(p, iters, wind, t, cUV); if (d < 0.0025) { hit = true; break; } tHit += d * 0.65; if (tHit > 6.0) break; } if (hit) { vec3 p = ro + rd * tHit; vec3 n = calcNormal(p, iters, wind, t); if (dot(n, rd) > 0.0) n = -n; vec3 l1 = normalize(vec3(0.55, 0.72, 0.65)); vec3 l2 = normalize(vec3(-0.65, -0.25, 0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float sheen = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); // Structural & shear Verlet distance constraint grid vec2 g = cUV * vec2(12.0, 9.0); vec2 gf = abs(fract(g - 0.5) - 0.5); float structWire = smoothstep(0.065, 0.015, min(gf.x, gf.y)); float shearWire = smoothstep(0.055, 0.012, min(abs(fract(g.x + g.y) - 0.5), abs(fract(g.x - g.y) - 0.5))); float nodeDot = smoothstep(0.14, 0.05, length(fract(g + 0.5) - 0.5)); // Strain coloring: left side stretches red/orange under gravity; right side holds crisp teal float stretchAmt = (1.0 - cUV.y) * (isHigh ? 0.14 : 0.92); vec3 fabricCol = isHigh ? mix(vec3(0.14, 0.64, 0.76), vec3(0.24, 0.84, 0.72), cUV.y) : mix(vec3(0.86, 0.34, 0.22), vec3(0.92, 0.64, 0.28), cUV.y); col = fabricCol * (0.28 + 0.82 * diff1 + 0.24 * diff2) + vec3(0.55, 0.78, 0.98) * sheen * 0.35; col = mix(col, vec3(0.05, 0.10, 0.16), structWire * 0.55 * min(wireVis, 1.0)); col = mix(col, vec3(0.95, 0.88, 0.45), shearWire * 0.22 * min(wireVis, 1.0)); col = mix(col, vec3(0.96, 0.98, 1.0), nodeDot * 0.55 * min(wireVis, 1.0)); col += vec3(0.25, 0.05, 0.02) * stretchAmt * 0.25; } // Split divider float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Thomas Jakobsen Advanced Character Physics. cs.cmu.edu. https://www.cs.cmu.edu/afs/cs/academic/class/15462-s13/www/lec_slides/Jakobsen.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Verlet integration with relaxation constraints." https://texelatlas.vercel.app/t/verlet-integration-constraints/ (accessed 2026-12-01). --- id: "vertex-animation-textures" title: "Vertex animation textures (VAT) and GPU crowds" aliases: [VAT, baked vertex animation, animation textures] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, houdini] year_introduced: 2007 inputs: [animation, mesh] outputs: [texture, animation] style: "both" dynamic: "dynamic" cost: "cheap" authority: "sideeffects, 2016" url: "https://texelatlas.vercel.app/t/vertex-animation-textures/" sources_verified_at: "2026-11-29" --- # Vertex animation textures (VAT) and GPU crowds (sideeffects, 2016) > Bake per-frame vertex positions (and normals) or bone matrices into a texture, then replay them in the vertex shader so thousands of instances animate with no CPU skinning. ## Reach for it when - too many skinned characters tank the cpu in a crowd - need to replay baked cloth or fluid cache on mobile - want destruction debris animation without runtime physics - thousands of instanced animated meshes need varied phase offsets ## How it works Offline, an animation is sampled at fixed time steps. For vertex-position VAT, each texel stores the position of one vertex at one frame, so the texture is vertices wide and frames tall; normals go in a second texture or are packed. Fluid, cloth and fracture caches that change topology are stored the same way, often with rigid-fragment variants storing pivot and rotation per piece. For crowds, the common variant bakes skinning matrices or animation frames of a skeleton instead. At runtime a shader uses the vertex index and a time value, optionally per-instance offset and speed, to fetch texels and interpolate between two frames. Because the data is just a texture lookup, GPU instancing draws thousands of characters or debris pieces in a few draw calls with varied phase and clip selection. Precision is the main design decision: bounding-box-normalised 16-bit half floats or 8-bit fixed-point trade size against jitter. ## When to use it Choose it when many copies of the same baked motion must play cheaply: crowds in a stadium, swarms, destruction, cached cloth or liquid surfaces on mobile and web. Prefer [Linear blend skinning](https://texelatlas.vercel.app/t/linear-blend-skinning.md) or [Dual quaternion skinning](https://texelatlas.vercel.app/t/dual-quaternion-skinning.md) when characters need blending, IK or runtime-driven poses; prefer [Blend shapes / morph targets and pose-space deformation](https://texelatlas.vercel.app/t/blend-shapes-morph-targets.md) for runtime-weighted facial shapes. Prefer [Motion matching](https://texelatlas.vercel.app/t/motion-matching.md) when motion must react to gameplay. VAT is the right answer for cached simulation from [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) or [FLIP/PIC fluids](https://texelatlas.vercel.app/t/flip-pic-fluids.md) that you want to replay unchanged. ## Cost cheap — One or two texture fetches per vertex per frame; memory is vertices times frames times channels. ## Failure modes - Texture memory grows quickly with vertex count times frame count, forcing frame-rate or mesh LOD cuts - Quantised positions shimmer or wobble on small details when the bounds are too large - Linear interpolation between baked frames smooths fast motion and breaks silhouettes at low sample rates - No runtime blending or retargeting: transitions between clips need cross-fading two lookups - Mip-mapping or filtering on the animation texture corrupts values; it must be point-sampled ## Engine support - babylonjs: builtin — `new VertexAnimationBaker(scene, mesh); mesh.bakedVertexAnimationManager` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/BakedVertexAnimation/bakedVertexAnimationManager.ts, checked 2026-12-01) - unreal: official — `Vertex Animation Tool (3ds Max script) exports animation to textures for a material` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/vertex-animation-tool-in-unreal-engine, checked 2026-12-01) — Epic-provided 3ds Max tool set. ## Dataflow - Inputs: animation, mesh - Outputs: texture, animation - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot, houdini ## Combines with - [Boids flocking](https://texelatlas.vercel.app/t/boids.md): Boid agents choose a baked clip and phase per instance, so a flock flaps with stored vertex animation instead of skinned rigs. - [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md): Cloth or soft-body output from an offline XPBD run is baked into the texture and replayed on many instances. ## Sources 1. [primary] sideeffects (2016) sideeffects/GameDevelopmentToolset. https://github.com/sideeffects/GameDevelopmentToolset License: NOASSERTION. (verified via github on 2026-11-29) 2. [tutorial] Dudash GPU Gems 3, Chapter 2: Animated Crowd Rendering. developer.nvidia.com. https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-2-animated-crowd-rendering (verified via http on 2026-11-29) ## Cite this entry Texel. "Vertex animation textures (VAT) and GPU crowds." https://texelatlas.vercel.app/t/vertex-animation-textures/ (accessed 2026-12-01). --- id: "vertex-block-descent" title: "Vertex Block Descent" aliases: [VBD] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [cuda, desktop-gpu, cpu] year_introduced: 2024 inputs: [mesh] outputs: [mesh] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Chen et al., 2024" url: "https://texelatlas.vercel.app/t/vertex-block-descent/" sources_verified_at: "2026-11-29" --- # Vertex Block Descent (Chen et al., 2024) > GPU-friendly implicit-integration solver that minimises variational energy by solving a small 3x3 system per vertex with graph colouring, converging quickly on stiff cloth and soft bodies. ## Reach for it when - cloth stretches too much on the gpu - stiff soft bodies are unstable with position-based solvers - heavy objects on light cloth cause problems - need fast implicit-style integration on gpu - high mass ratio simulations explode ## How it works The implicit Euler step is a minimisation problem. VBD performs block coordinate descent: for each vertex it fixes its neighbours, assembles the local gradient and Hessian of the energy (inertia plus elastic and collision terms), and solves a 3x3 system for the vertex update. Vertices are grouped by graph colouring so each colour can be updated in parallel without race conditions. The Hessian is approximated to remain positive definite. Compared with PBD, it handles stiff materials and high mass ratios with unconditional stability and faster convergence per iteration, and the formulation covers general materials, frictional contact and self-collision. ## When to use it Choose it for GPU-based stiff cloth, soft bodies and high mass-ratio scenes where PBD stretches. Prefer [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) for the simplest and cheapest real-time option, [Implicit cloth integration (Baraff-Witkin)](https://texelatlas.vercel.app/t/implicit-cloth-integration.md) for CPU-based classical cloth, and [Shape matching (meshless deformation)](https://texelatlas.vercel.app/t/shape-matching-deformation.md) for cheap jelly-like deformation. ## Cost medium — Per-vertex 3x3 solves, parallel by colour; heavier than PBD but converges in fewer iterations. ## Failure modes - Convergence is not exact in a fixed iteration count: stiff scenes may still sag - Requires a graph colouring of the mesh, which must be recomputed on topology change - Collision handling still relies on discrete detection and can tunnel - Hessian approximations trade accuracy for stability ## Dataflow - Inputs: mesh - Outputs: mesh - Platforms: cuda, desktop-gpu, cpu ## Lineage - extends [Extended Position-Based Dynamics](https://texelatlas.vercel.app/t/xpbd.md) ## Sources 1. [primary] Anka He Chen, Ziheng Liu, Yin Yang, Cem Yuksel (2024) Vertex Block Descent. ACM Transactions on Graphics. https://doi.org/10.1145/3658179 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Vertex Block Descent." https://texelatlas.vercel.app/t/vertex-block-descent/ (accessed 2026-12-01). --- id: "vertex-connection-and-merging" title: "Vertex Connection and Merging" aliases: [VCM, UPS] domain: "gi" stage: "lighting" realtime: "offline" platforms: [cpu, cuda] year_introduced: 2012 inputs: [mesh, material-params] outputs: [radiance] style: "photoreal" dynamic: "static" cost: "offline" authority: "Georgiev et al., 2012" url: "https://texelatlas.vercel.app/t/vertex-connection-and-merging/" sources_verified_at: "2026-11-29" --- # Vertex Connection and Merging (Georgiev et al., 2012) > Combines bidirectional path tracing's vertex connections with photon-mapping-style vertex merging inside one MIS framework, so both diffuse paths and specular caustic paths converge well. ## Reach for it when - path tracing noise with glass and mirrors - bidirectional tracing fails on caustics - want one robust method for diffuse and specular light transport - difficult light paths converge slowly in renderer ## How it works BDPT and photon mapping each fail where the other succeeds. BDPT is strong for diffuse-heavy paths but cannot connect through specular vertices; photon mapping handles specular-diffuse-specular caustics but is biased and wasteful on easy paths. VCM treats **merging** (accepting a light vertex that lies within a radius of an eye vertex) as an additional path sampling technique, interpreting it as an unbiased-in-the-limit path sampling strategy with a computable pdf. With that interpretation, connection and merging strategies of a given path length can be weighted together using multiple importance sampling. The merge pdf is proportional to the number of light vertices times the area of the merge disk, so the weights depend on a single radius. As in [progressive-photon-mapping](progressive-photon-mapping), the radius shrinks over iterations, which makes the estimator consistent. In practice you run one light subpath per pixel, store all light vertices in a grid, then trace the eye path, adding connection and merge contributions with their MIS weights at each vertex. ## When to use it Choose it as a robust offline integrator for scenes mixing diffuse interreflection and caustic-heavy specular transport, such as jewelry, glassware or pool scenes with indirect lighting. Prefer [path-tracing](path-tracing) when scenes are simple, since VCM's bookkeeping and memory are significant. Prefer [bidirectional-path-tracing](bidirectional-path-tracing) when there are no relevant caustics. Prefer [path-guiding](path-guiding) when the problem is general noise rather than specular transport. ## Cost offline — Costs more than BDPT per iteration because of a light-vertex grid and merge lookups; benefits show on caustic-heavy scenes. Measured GPU Weight: 3.36× baseline (light) — 0.1107 ms median / 0.1109 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 2.9× baseline (light) — 0.0461 ms median (2.4× faster on L4). Ampere A100 scaling: 2.08× baseline (light) — 0.0598 ms median (1.85× faster on A100). ## Failure modes - Bias from merging (blur) at early iterations, only vanishing as the radius shrinks - Radius parameter needs tuning: too large smears caustics, too small raises noise - Substantial implementation complexity in the MIS weight recurrence, with tricky reverse-pdf bookkeeping - Memory for the light vertex store grows with image resolution ## Dataflow - Inputs: mesh, material-params - Outputs: radiance - Platforms: cpu, cuda ## Presets ### Vertex Connection & Merging (VCM) — BDPT connection-only missing caustics (left) vs MIS photon-merged caustics (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_MERGE_RADIUS": 0.42, "P_CAUSTIC_GAIN": 1.4, "P_IOR": 1.52, "P_SPLIT": 0.48 } ``` ```glsl const float P_MERGE_RADIUS = 0.42; // P Merge Radius [0.15, 0.95, 0.05] const float P_CAUSTIC_GAIN = 1.40; // P Caustic Energy [0.4, 2.6, 0.1] const float P_IOR = 1.52; // P Glass IOR [1.2, 1.85, 0.04] const float P_SPLIT = 0.48; // P BDPT / VCM Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // Evaluate concentrated dispersive refractive caustic focused through the glass sphere onto the Cornell box floor vec3 evalGlassCaustic(vec3 p, vec3 sphC, float sphR, vec3 lightPos, float ior, float radius) { vec3 lDir = normalize(sphC - lightPos); // Intersection of central light axis through sphere with floor y = -0.68 float tFocus = (-0.68 - sphC.y) / min(lDir.y, -0.05); vec3 focusCenter = sphC + lDir * tFocus; vec2 d = p.xz - focusCenter.xz; float r = length(d); float focalTight = mix(0.28, 0.11, clamp((ior - 1.15) / 0.75, 0.0, 1.0)); float sig = max(focalTight * (0.55 + 0.65 * radius), 0.04); // Spectral dispersion rings (R/G/B slightly shifted focal radii) + bright central caustic core float cR = exp(-pow(r / (sig * 1.06), 2.0)) + 0.55 * exp(-pow((r - sig * 1.18) / (sig * 0.28), 2.0)); float cG = exp(-pow(r / (sig * 1.00), 2.0)) + 0.55 * exp(-pow((r - sig * 1.05) / (sig * 0.25), 2.0)); float cB = exp(-pow(r / (sig * 0.94), 2.0)) + 0.55 * exp(-pow((r - sig * 0.92) / (sig * 0.22), 2.0)); // Fine caustic filament wave structure float ang = atan(d.y, d.x); float fil = 0.82 + 0.18 * cos(ang * 5.0 + iTime * 0.7) * sin(r * 18.0); return vec3(cR, cG, cB) * fil; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool useVCM = sx >= split; float mergeR = clamp(P_MERGE_RADIUS, 0.1, 1.0); float cGain = clamp(P_CAUSTIC_GAIN, 0.2, 3.0); float ior = clamp(P_IOR, 1.15, 2.0); vec3 ro = vec3(0.0, 0.06, 1.88); vec3 rd = normalize(vec3(uv, -1.35)); vec3 col = vec3(0.03, 0.03, 0.04); vec3 lightPos = vec3(0.28 * sin(iTime * 0.65), 0.76, -0.35); vec3 sphC = vec3(0.0, -0.18, -0.45); float sphR = 0.36; // Intersect Cornell box walls (floor y=-0.68, ceil y=0.78, back z=-1.35, left x=-0.95, right x=0.95) float tHit = 1e5; vec3 hitN = vec3(0.0, 1.0, 0.0); int hitId = 0; if (rd.y < -1e-4) { float t = (-0.68 - ro.y) / rd.y; if (t > 0.05 && t < tHit) { tHit = t; hitN = vec3(0.0, 1.0, 0.0); hitId = 1; } } if (rd.y > 1e-4) { float t = (0.78 - ro.y) / rd.y; if (t > 0.05 && t < tHit) { tHit = t; hitN = vec3(0.0, -1.0, 0.0); hitId = 2; } } if (rd.z < -1e-4) { float t = (-1.35 - ro.z) / rd.z; if (t > 0.05 && t < tHit) { tHit = t; hitN = vec3(0.0, 0.0, 1.0); hitId = 3; } } if (rd.x < -1e-4) { float t = (-0.95 - ro.x) / rd.x; if (t > 0.05 && t < tHit) { tHit = t; hitN = vec3(1.0, 0.0, 0.0); hitId = 4; } } if (rd.x > 1e-4) { float t = (0.95 - ro.x) / rd.x; if (t > 0.05 && t < tHit) { tHit = t; hitN = vec3(-1.0, 0.0, 0.0); hitId = 5; } } // Intersect glass crystal sphere vec3 oc = ro - sphC; float b = dot(oc, rd); float c = dot(oc, oc) - sphR * sphR; float disc = b * b - c; bool hitGlass = false; if (disc > 0.0) { float tS = -b - sqrt(disc); if (tS > 0.05 && tS < tHit) { tHit = tS; hitN = normalize((ro + rd * tS) - sphC); hitGlass = true; hitId = 6; } } if (hitId > 0) { vec3 p = ro + rd * tHit; if (hitGlass) { // Refractive + reflective crystal sphere vec3 v = -rd; float ndv = max(dot(hitN, v), 0.0); float f0 = pow((ior - 1.0) / (ior + 1.0), 2.0); float F = f0 + (1.0 - f0) * pow(1.0 - ndv, 5.0); vec3 refr = refract(rd, hitN, 1.0 / ior); vec3 refl = reflect(rd, hitN); // Sample refracted Cornell box interior (crimson left, emerald right, bright floor caustic!) vec3 refrCol = mix(vec3(0.76, 0.72, 0.66), vec3(0.88, 0.22, 0.16), smoothstep(0.15, -0.55, refr.x)); refrCol = mix(refrCol, vec3(0.16, 0.74, 0.36), smoothstep(-0.15, 0.55, refr.x)); vec3 reflCol = mix(vec3(0.25, 0.28, 0.36), vec3(2.8, 2.5, 2.0), pow(max(dot(refl, normalize(lightPos - p)), 0.0), 32.0)); col = mix(refrCol * 0.92, reflCol, clamp(F + 0.15, 0.0, 0.92)); // Spectral rim col += vec3(0.45, 0.75, 1.0) * pow(1.0 - ndv, 3.5) * 0.45; } else { // Ceiling area emitter lamp if (hitId == 2 && length(p.xz - lightPos.xz) < 0.24) { col = vec3(3.6, 3.2, 2.6); } else { vec3 alb = vec3(0.76, 0.74, 0.70); if (hitId == 4) alb = vec3(0.86, 0.20, 0.16); // red left wall else if (hitId == 5) alb = vec3(0.16, 0.74, 0.34); // green right wall vec3 toL = lightPos - p; float dist2 = max(dot(toL, toL), 0.12); vec3 L = toL / sqrt(dist2); float ndl = max(dot(hitN, L), 0.0); // Glass sphere direct shadow test vec3 soc = p - sphC; float sb = dot(soc, L); float sc = dot(soc, soc) - sphR * sphR; float sDisc = sb * sb - sc; float sh = (sDisc > 0.0 && (-sb - sqrt(sDisc)) > 0.01 && (-sb - sqrt(sDisc)) < sqrt(dist2)) ? 0.18 : 1.0; // Diffuse Cornell box GI (both BDPT and VCM converge diffuse paths cleanly!) vec3 bounceRed = vec3(0.86, 0.20, 0.16) * max(dot(hitN, vec3(-1.0, 0.1, 0.0)), 0.0) / (0.85 + pow(p.x + 0.95, 2.0)); vec3 bounceGrn = vec3(0.16, 0.74, 0.34) * max(dot(hitN, vec3(1.0, 0.1, 0.0)), 0.0) / (0.85 + pow(0.95 - p.x, 2.0)); vec3 direct = alb * vec3(1.65, 1.48, 1.24) * (ndl * sh / dist2) * 0.75; vec3 indirect = alb * (bounceRed * 0.28 + bounceGrn * 0.28 + vec3(0.12, 0.12, 0.14)); col = direct + indirect; // Refractive SDS caustic on the floor beneath the crystal sphere if (hitId == 1) { vec3 caust = evalGlassCaustic(p, sphC, sphR, lightPos, ior, mergeR) * cGain; if (useVCM) { // Right (VCM): Photon vertex merging smoothly resolves the bright dispersive caustic with MIS! col += alb * caust * 1.85; } else { // Left (BDPT connections only): Fails to connect specular-diffuse-specular paths -> dark shadow with sparse fireflies! float rnd = hash21(floor(fragCoord * 0.65) + floor(iTime * 8.0) * 0.31); float firefly = step(0.972, rnd) * 5.5; col += alb * caust * firefly; } } } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Bidirectional Path Tracing](https://texelatlas.vercel.app/t/bidirectional-path-tracing.md) ## Sources 1. [primary] Iliyan Georgiev, Jaroslav Křivánek, Tomáš Davidovič, Philipp Slusallek (2012) Light transport simulation with vertex connection and merging. ACM Transactions on Graphics. https://doi.org/10.1145/2366145.2366211 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Vertex Connection and Merging." https://texelatlas.vercel.app/t/vertex-connection-and-merging/ (accessed 2026-12-01). --- id: "vggt" title: "VGGT (Visual Geometry Grounded Transformer)" aliases: [VGGT] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [photos] outputs: [camera-poses, depth, point-cloud] style: "photoreal" dynamic: "static" cost: "medium" authority: "Wang et al., 2025" url: "https://texelatlas.vercel.app/t/vggt/" sources_verified_at: "2026-11-29" --- # VGGT (Visual Geometry Grounded Transformer) (Wang et al., 2025) > A feed-forward transformer that takes one to hundreds of images and predicts, in a single pass, camera intrinsics and extrinsics, depth maps, pointmaps and point tracks. ## Reach for it when - need camera poses without running a full sfm - want depth and tracks from many images fast - need initialisation for splat training quickly - pose estimation from unordered photos in one pass ## How it works Images are patchified and embedded, and a camera token is added per view. A large transformer alternates frame-wise self-attention (within each image) with global self-attention (across all images), letting every view exchange geometric information with the others. Separate heads read the camera tokens to predict intrinsics and pose, and dense DPT-style heads decode depth, pointmaps and tracking features from image tokens. It is trained on many 3D-annotated datasets with direct regression losses, with no test-time optimisation. Results are produced in one forward pass, in a reference frame set by the first image, so there is no pairwise graph or global alignment step. The outputs can seed bundle adjustment or splat training. ## When to use it Choose it for fast pose and depth estimation from many views with no SfM run, as a splat initialiser. Prefer [Structure-from-Motion (COLMAP)](https://texelatlas.vercel.app/t/structure-from-motion-colmap.md) for final accuracy on large well-textured captures, [DUSt3R](https://texelatlas.vercel.app/t/dust3r.md) or [MASt3R](https://texelatlas.vercel.app/t/mast3r.md) when you need their pairwise matching, and [Depth Anything V2](https://texelatlas.vercel.app/t/depth-anything-v2.md) when you only need single-image relative depth. ## Cost medium — One forward pass; memory grows with number of views, with the reference paper reporting hundreds of images per pass on a high-end GPU. ## Failure modes - Accuracy degrades on very large view counts or long trajectories without refinement - Dynamic objects and extreme lighting changes break cross-view consistency - Memory limits the number of frames per pass - Weights come with research-focused licence terms, check the repo ## Dataflow - Inputs: photos - Outputs: camera-poses, depth, point-cloud - Platforms: cuda, python ## Combines with - [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md): Predicted poses, depth and points initialise Gaussians without running COLMAP. ## Combination ideas - [Freeze a generated world into splats](https://texelatlas.vercel.app/ideas/world-model-walkthrough-to-splats/) ## Sources 1. [primary] Jianyuan Wang, Minghao Chen, Nikita Karaev, Andrea Vedaldi, Christian Rupprecht, David Novotny (2025) VGGT: Visual Geometry Grounded Transformer. arXiv preprint (cs.CV). https://arxiv.org/abs/2503.11651 (verified via arxiv on 2026-11-29) 2. [implementation] facebookresearch (2025) facebookresearch/vggt. https://github.com/facebookresearch/vggt License: NOASSERTION. (verified via github on 2026-11-29) 3. [tutorial] Visual Geometry Group, University of Oxford, Meta AI VGGT project page. vgg-t.github.io. https://vgg-t.github.io/ (verified via http on 2026-11-29) ## Cite this entry Texel. "VGGT (Visual Geometry Grounded Transformer)." https://texelatlas.vercel.app/t/vggt/ (accessed 2026-12-01). --- id: "view-projected-texture-painting" title: "View-projected AI texture painting" aliases: [trompe, blockout texturing] domain: "genai" stage: "generation" realtime: "offline" platforms: [webgl2, webgpu, python] year_introduced: 2026 inputs: [mesh, text-prompt] outputs: [texture, uv-atlas] style: "photoreal" dynamic: "static" cost: "offline" authority: "patch-gg, 2026" url: "https://texelatlas.vercel.app/t/view-projected-texture-painting/" sources_verified_at: "2026-11-29" --- # View-projected AI texture painting (patch-gg, 2026) > Textures a whole level from grey geometry by planning cameras where a player can stand, having an image model paint each view, projecting the paintings back onto the mesh and baking one texture atlas. ## Reach for it when - need to texture a whole blockout level quickly - large scene mesh is grey and needs realistic look - paint environment from player-view camera positions - project ai images back onto level geometry - bake one atlas for a big scene from generated views ## How it works A camera planner picks views covering the surfaces a player can see. For each view an image model paints the depth-conditioned grey render under a flat, overcast lighting prompt so the result approximates albedo. Each painting is projected onto the mesh with visibility tests and blended into a shared UV atlas, and the final atlas is baked so the engine lights it with real shadows. Trompe runs planning, projection and baking in the browser on the GPU and calls hosted image models; the potemkin3D extension adds view-aware atlas density, geometry checks and surface relief for close-up walkthroughs. ## When to use it Choose it to dress an existing blockout level or large scene mesh quickly in a realistic style, viewed from a few metres or more. Prefer [SyncMVD](https://texelatlas.vercel.app/t/syncmvd.md), [Text2Tex](https://texelatlas.vercel.app/t/text2tex.md) or [Paint3D](https://texelatlas.vercel.app/t/paint3d.md) for single-object texturing, [Hunyuan3D-Paint](https://texelatlas.vercel.app/t/hunyuan3d-paint.md) for image-referenced single assets, and hand-authored tiling materials when the style must be stylised or close-up detail matters. ## Cost offline — Per-view image-model calls dominate; the trompe README quotes cost per view and minutes per level, qualitative here. ## Failure modes - One shared atlas for the level blurs texture at first-person ground distance - Seams and colour shifts where different painted views meet - Image model adds grime and uneven colour; stylised looks are hard to achieve - Named objects in the prompt get painted onto walls - Depends on hosted image-model APIs ## Dataflow - Inputs: mesh, text-prompt - Outputs: texture, uv-atlas - Platforms: webgl2, webgpu, python ## Sources 1. [primary] patch-gg (2026) patch-gg/trompe. https://github.com/patch-gg/trompe License: Apache-2.0. (verified via github on 2026-11-29) 2. [implementation] wrong-nebula (2026) wrong-nebula/potemkin3D. https://github.com/wrong-nebula/potemkin3D License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "View-projected AI texture painting." https://texelatlas.vercel.app/t/view-projected-texture-painting/ (accessed 2026-12-01). --- id: "virtual-shadow-maps" title: "Virtual Shadow Maps" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [desktop-gpu, unreal] year_introduced: 2021 inputs: [mesh, depth] outputs: [visibility-mask] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Games" url: "https://texelatlas.vercel.app/t/virtual-shadow-maps/" sources_verified_at: "2026-11-29" --- # Virtual Shadow Maps (Games) > A very high-resolution, sparsely allocated shadow map per light, where only pages the camera actually samples are rendered and cached, pairing with virtualised geometry. ## Reach for it when - shadow resolution too low for big detailed scenes - need film quality shadows on every light - cascades flicker and waste memory - shadows blurry near the camera in open worlds ## How it works Each light owns a virtual depth texture many thousands of texels wide, divided into pages. A pass analyses the depth buffer to mark which pages are needed at the required resolution (a clipmap for directional lights, mip-style levels for local lights), allocates physical pages, and renders only geometry overlapping them, with Nanite-style culling. Pages whose content did not change are cached between frames and invalidated by moving casters, so static scenes cost almost nothing per frame. Filtering is built from a small number of taps against the fine map and often combined with a screen-space or ray-traced term for contact detail. This is documented as an Unreal Engine 5 feature rather than a published paper. ## When to use it Choose it when geometry is extremely dense and you need consistent sharp shadows from near to far without hand-tuned cascades, in an engine with virtualised geometry. Prefer [Cascaded Shadow Maps](https://texelatlas.vercel.app/t/cascaded-shadow-maps.md) on mobile, WebGL or lower-end GPUs, and [Ray-Traced Shadows](https://texelatlas.vercel.app/t/ray-traced-shadows.md) when physically soft penumbrae are required. ## Cost heavy — Depends on cache hit rate and page count; static scenes are cheap, large dynamic casters invalidate many pages. Measured GPU Weight: 40.43× baseline (heavy) — 1.33 ms median / 1.4198 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 42.92× baseline (heavy) — 0.6824 ms median (1.95× faster on L4). Ampere A100 scaling: 25.28× baseline (heavy) — 0.7281 ms median (1.83× faster on A100). ## Failure modes - Page invalidation spikes from fast-moving or large dynamic casters - Large memory pool for the physical page cache - Needs a depth-buffer analysis pass and GPU-driven rendering infrastructure - Alpha-tested or deforming geometry can force costly re-rendering ## Engine support - blender: builtin — `Light Properties > Shadow (EEVEE uses Virtual Shadow Mapping)` (evidence: https://docs.blender.org/manual/en/5.2/render/eevee/light_settings.html, checked 2026-12-01) - unreal: builtin — `Project Settings > Rendering > Shadows > Shadow Map Method = Virtual Shadow Maps` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/virtual-shadow-maps-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, depth - Outputs: visibility-mask - Platforms: desktop-gpu, unreal ## Presets ### Virtual Shadow Maps (VSM) — sparse physical page table & dirty-page invalidation (left) vs 1:1 texel-crisp virtual shadows (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PAGE_GRID": 10, "P_CLIPMAP_VIS": 0.65, "P_MOVER_SPEED": 0.6, "P_SPLIT": 0.48 } ``` ```glsl const float P_PAGE_GRID = 10.00; // P Virtual Page Grid [5.0, 16.0, 1.0] const float P_CLIPMAP_VIS = 0.65; // P Page State Overlay [0.1, 1.0, 0.05] const float P_MOVER_SPEED = 0.60; // P Dynamic Caster Speed [0.0, 1.8, 0.05] const float P_SPLIT = 0.48; // P Page Table / VSM [0.0, 1.0, 0.02] 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); } // Courtyard with static fine architectural railing + a dynamic orbiting occluder that invalidates VSM pages! vec2 mapVSMScene(vec3 p, vec3 moverPos) { float dFloor = p.y + 0.52; vec2 res = vec2(dFloor, 1.0); // Static architectural fence/railing slats (demonstrates crisp 1:1 virtual shadow resolution!) for (int i = 0; i < 5; i++) { float x = -0.72 + float(i) * 0.22; float dPost = sdBox(p - vec3(x, -0.18, -0.35), vec3(0.032, 0.34, 0.032)); if (dPost < res.x) res = vec2(dPost, 2.0); } float dRail = sdBox(p - vec3(-0.28, 0.08, -0.35), vec3(0.50, 0.03, 0.04)); if (dRail < res.x) res = vec2(dRail, 2.0); // Dynamic moving sphere occluder (causes VSM dirty-page invalidation on tiles its shadow touches!) float dMov = length(p - moverPos) - 0.22; if (dMov < res.x) res = vec2(dMov, 3.0); return res; } vec3 calcNormal(vec3 p, vec3 moverPos) { vec2 e = vec2(0.0022, 0.0); return normalize(vec3( mapVSMScene(p + e.xyy, moverPos).x - mapVSMScene(p - e.xyy, moverPos).x, mapVSMScene(p + e.yxy, moverPos).x - mapVSMScene(p - e.yxy, moverPos).x, mapVSMScene(p + e.yyx, moverPos).x - mapVSMScene(p - e.yyx, moverPos).x )); } float traceVSMShadow(vec3 p, vec3 sunDir, vec3 moverPos) { float sh = 1.0; float t = 0.025; for (int i = 0; i < 24; i++) { float h = mapVSMScene(p + sunDir * t, moverPos).x; if (h < 0.002) return 0.0; sh = min(sh, 18.0 * h / t); t += max(h, 0.02); if (t > 4.0) break; } return clamp(sh, 0.0, 1.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float pageGrid = clamp(floor(P_PAGE_GRID + 0.5), 4.0, 18.0); float vis = clamp(P_CLIPMAP_VIS, 0.05, 1.0); float t = iTime * max(P_MOVER_SPEED, 0.0); vec3 moverPos = vec3(0.38 + 0.28 * cos(t * 0.95), -0.14 + 0.12 * sin(t * 1.4), 0.08 + 0.26 * sin(t * 0.95)); vec3 ro = vec3(0.0, 0.55, 2.25); vec3 rd = normalize(vec3(uv.x, uv.y - 0.22, -1.45)); vec3 sunDir = normalize(vec3(0.42, 0.78, 0.46)); vec3 sky = mix(vec3(0.70, 0.80, 0.92), vec3(0.18, 0.42, 0.78), smoothstep(-0.1, 0.5, rd.y)); vec3 col = sky; float dist = 0.05; vec2 hit = vec2(12.0, 0.0); for (int i = 0; i < 64; i++) { vec2 h = mapVSMScene(ro + rd * dist, moverPos); if (h.x < 0.0025) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 10.0) break; } if (hit.y > 0.5) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p, moverPos); float sh = traceVSMShadow(p + n * 0.008, sunDir, moverPos); vec3 alb = vec3(0.76, 0.74, 0.70); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.32, 0.36, 0.44); else if (hit.y > 2.5) alb = vec3(0.94, 0.52, 0.20); float ndl = max(dot(n, sunDir), 0.0); vec3 lit = alb * (vec3(0.20, 0.28, 0.42) + vec3(1.32, 1.20, 1.00) * ndl * sh); if (screenX < split) { // Left: Sparse Virtual Shadow Map clipmap page-table overlay! // Light-space virtual coordinates projected onto physical pages: vec3 lRight = normalize(cross(vec3(0.0, 1.0, 0.0), sunDir)); vec3 lUp = cross(sunDir, lRight); // Clipmap LOD level halves page frequency with camera distance float clipScale = (hit.x > 3.2) ? (pageGrid * 0.5) : pageGrid; vec2 vCoord = vec2(dot(p, lRight), dot(p, lUp)) * clipScale * 0.35; vec2 pageId = floor(vCoord); vec2 pf = fract(vCoord); float tileEdge = smoothstep(0.07, 0.015, min(min(pf.x, 1.0 - pf.x), min(pf.y, 1.0 - pf.y))); // Check if this virtual page overlaps the moving caster's shadow footprint -> INVALIDATED (amber/red) vs CACHED (cyan/emerald)! vec2 moverShadowCoord = vec2(dot(moverPos, lRight), dot(moverPos, lUp)) * clipScale * 0.35; bool dirtyPage = length(pageId + 0.5 - moverShadowCoord) < 1.35; vec3 pageTint = dirtyPage ? vec3(1.0, 0.42, 0.16) : ((hit.x > 3.2) ? vec3(0.22, 0.62, 0.98) : vec3(0.16, 0.90, 0.68)); col = mix(lit, lit * 0.55 + pageTint * 0.65, vis * 0.55); col = mix(col, pageTint * 1.4, tileEdge * vis * 0.72); } else { col = lit; } if (hit.y < 1.5) col = mix(sky, col, exp(-hit.x * 0.08)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.98, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Shadow Mapping](https://texelatlas.vercel.app/t/shadow-mapping.md) ## Sources 1. [primary] Epic Games Virtual Shadow Maps in Unreal Engine. dev.epicgames.com. https://dev.epicgames.com/documentation/en-us/unreal-engine/virtual-shadow-maps-in-unreal-engine (verified via http on 2026-11-29) ## Cite this entry Texel. "Virtual Shadow Maps." https://texelatlas.vercel.app/t/virtual-shadow-maps/ (accessed 2026-12-01). --- id: "virtual-texturing" title: "Sparse virtual texturing" aliases: [virtual textures, megatexture, SVT] domain: "performance" stage: "performance" realtime: "realtime" platforms: [desktop-gpu, unity, unreal, webgpu] year_introduced: 2008 inputs: [texture, uv-atlas] outputs: [texture] style: "both" dynamic: "both" cost: "medium" authority: "Waveren" url: "https://texelatlas.vercel.app/t/virtual-texturing/" sources_verified_at: "2026-11-29" --- # Sparse virtual texturing (Waveren) > Treat a huge texture address space as virtual memory: only the tiles the camera actually samples are streamed into a small physical cache, found through a page table or indirection texture. ## Reach for it when - textures too big to fit in gpu memory - unique texture detail across a huge terrain - too many texture bindings for large worlds - texture streaming causes visible pop-in - need per-pixel unique painted surface at world scale ## How it works Surfaces sample from a single enormous virtual texture, split into fixed-size pages (e.g. 128x128 texels) per mip level. A small physical texture or atlas holds the resident pages, and an indirection (page table) texture maps virtual page coordinates and mip to a location in that cache. To know which pages are needed, a feedback pass renders the scene at low resolution writing each pixel's virtual page and mip into a target. The CPU or a compute pass reads it back, requests missing pages, loads and decodes them (often transcoding to a block compressed format), and updates the page table with an LRU eviction policy. The shader samples the page table, computes the physical UV including border or padding handling, and falls back to a coarser resident mip while a requested page is still loading. ## When to use it Choose it for terrain, large worlds or unique-texel assets (decals, painted surfaces, baked lightmaps) that exceed GPU memory or would need hundreds of texture bindings. Prefer ordinary mipmapped textures with streaming of whole mip chains for modest scenes. Combine with [Block texture compression (BC7 / ASTC)](https://texelatlas.vercel.app/t/block-texture-compression.md) or [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md) for page payloads; [Virtual Shadow Maps](https://texelatlas.vercel.app/t/virtual-shadow-maps.md) applies the same paging idea to shadow depth. ## Cost medium — Extra indirection fetch per sample plus a feedback pass and CPU/IO streaming work; qualitative. Measured GPU Weight: 3.73× baseline (light) — 0.1157 ms median / 0.1179 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 3.09× baseline (light) — 0.0491 ms median (2.36× faster on L4). Ampere A100 scaling: 2.22× baseline (light) — 0.0638 ms median (1.81× faster on A100). ## Failure modes - Texture pop-in or blurry surfaces while pages stream in, especially on fast camera cuts - Anisotropic and trilinear filtering across page borders need padding or manual filtering, otherwise visible seams - Feedback buffer latency of a few frames lets fast motion outrun the cache - Cache thrash when the working set exceeds the physical pool causes constant reloads - Page-table lookup breaks hardware derivative-based mip selection if gradients are not passed carefully ## Engine support - metal: builtin — `MTLSparseTextureMappingMode via MTLResourceStateCommandEncoder.updateTextureMapping; sparse heaps` (evidence: https://developer.apple.com/tutorials/data/documentation/metal/mtlsparsetexturemappingmode.json, checked 2026-12-01) — Sparse residency is an API primitive; page table, feedback pass and streaming are yours. - unity: builtin — `HDRP Asset > Streaming Virtual Texturing; Shader Graph Sample Virtual Texture node` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md, checked 2026-12-01) — HDRP. - unreal: builtin — `Project Settings > Engine > Rendering > Virtual Textures; Streaming (SVT) and Runtime (RVT) virtual textures` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/virtual-texturing-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: texture, uv-atlas - Outputs: texture - Platforms: desktop-gpu, unity, unreal, webgpu ## Presets ### Sparse Virtual Texturing — mip feedback & resident page-table cache (left) vs streamed megatexture (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_PAGE_DENS": 6, "P_MIP_BIAS": 0, "P_CACHE_HUD": 1, "P_SPLIT": 0.5 } ``` ```glsl const float P_PAGE_DENS = 6.0; // P Virtual Pages [3.0, 12.0, 1.0] const float P_MIP_BIAS = 0.0; // P Mip LOD Bias [-1.0, 1.5, 0.1] const float P_CACHE_HUD = 1.0; // P Page Table HUD [0.0, 1.0, 0.05] const float P_SPLIT = 0.50; // P Feedback / Stream [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // High-detail procedural megatexture (unique non-repeating terrain + architectural decals) vec3 megatexture(vec2 uv, float lod) { float scale = 1.0 / pow(2.0, clamp(lod, 0.0, 4.0)); vec2 q = uv * 8.0; float n1 = sin(q.x * 1.4 + sin(q.y * 1.1)) * 0.5 + 0.5; float n2 = sin(q.x * 5.2 * scale + q.y * 4.8 * scale) * 0.5 + 0.5; float masonry = smoothstep(0.06, 0.12, min(abs(fract(q.x * 2.0 * scale) - 0.5), abs(fract(q.y * 2.0 * scale) - 0.5))); vec3 stone = mix(vec3(0.32, 0.28, 0.24), vec3(0.68, 0.62, 0.52), n1); vec3 moss = vec3(0.18, 0.44, 0.24); vec3 base = mix(stone, moss, smoothstep(0.55, 0.85, sin(uv.x * 3.1 - uv.y * 2.3) * 0.5 + 0.5)); return base * (0.72 + 0.28 * masonry) * (0.85 + 0.15 * n2); } vec3 mipColor(float m) { if (m < 0.5) return vec3(0.95, 0.24, 0.22); // Mip 0 highest detail if (m < 1.5) return vec3(0.98, 0.68, 0.18); // Mip 1 if (m < 2.5) return vec3(0.18, 0.88, 0.56); // Mip 2 if (m < 3.5) return vec3(0.20, 0.64, 0.98); // Mip 3 return vec3(0.62, 0.34, 0.92); // Mip 4+ coarse fallback } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 uv01 = fragCoord / max(iResolution.xy, vec2(1.0)); float screenX = uv01.x; float split = clamp(P_SPLIT, 0.0, 1.0); bool isStream = screenX >= split; float pageDens = clamp(floor(P_PAGE_DENS + 0.5), 3.0, 14.0); float mipBias = clamp(P_MIP_BIAS, -1.0, 1.8); float hudVis = clamp(P_CACHE_HUD, 0.0, 1.0); vec3 ro = vec3(0.25 * sin(iTime * 0.4), 1.15, 2.2 - iTime * 0.55); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.14), -1.35)); vec3 sky = mix(vec3(0.08, 0.12, 0.20), vec3(0.20, 0.30, 0.48), smoothstep(-0.1, 0.5, uv.y)); vec3 col = sky; // Perspective textured ground plane + side walls forming an infinite virtual-textured canyon if (rd.y < -0.01) { float t = -ro.y / rd.y; if (t > 0.0 && t < 38.0) { vec3 p = ro + rd * t; vec2 vUV = p.xz * 0.25; // Analytical screen-space mip level from ray distance & grazing angle (feedback pass) float footprint = t / max(abs(rd.y) * 2.2, 0.12); float mipFloat = clamp(log2(max(footprint * 0.45, 0.25)) + mipBias, 0.0, 4.2); float mipIdx = floor(mipFloat); // Virtual page coordinates at this mip level float pagesAtMip = max(pageDens / pow(2.0, mipIdx * 0.5), 1.5); vec2 pageCoord = floor(vUV * pagesAtMip); vec2 pageFrac = fract(vUV * pagesAtMip); // Simulate sparse physical page cache residency (a few newly visible tiles streaming in!) float pageHash = hash21(pageCoord + mipIdx * 13.7); float resident = step(0.14, fract(pageHash + floor(iTime * 0.8) * 0.07)); float effectiveMip = (resident > 0.5) ? mipIdx : min(mipIdx + 2.0, 4.0); vec3 texCol = megatexture(vUV, effectiveMip); float diff = 0.72 + 0.28 * sin(p.x * 0.8) * cos(p.z * 0.8); // Page border grid vec2 pf = abs(pageFrac - 0.5); float pEdge = smoothstep(0.45, 0.495, max(pf.x, pf.y)); if (!isStream) { // Left: GPU feedback buffer showing requested (pageX, pageY, mip) + sparse cache miss indicators vec3 fbCol = mipColor(mipIdx); col = mix(texCol * 0.35, fbCol * 0.92, 0.72); // Highlight streaming-miss tiles flashing white-cyan while falling back to coarser mip if (resident < 0.5) { col = mix(col, vec3(0.95, 0.98, 1.0), 0.55); } col = mix(col, vec3(0.04, 0.06, 0.10), pEdge * 0.82); } else { // Right: final megatexture sampled via indirection page table -> physical cache atlas col = texCol * diff; if (resident < 0.5) { // Subtle coarser fallback blur tint on newly streamed tile col = mix(col, megatexture(vUV, 3.5) * diff, 0.65); } col = mix(col, vec3(0.15, 0.25, 0.38), pEdge * 0.16); } float fog = 1.0 - exp(-t * t * 0.0028); col = mix(col, sky, clamp(fog, 0.0, 0.92)); } } // Bottom-left physical page-cache atlas inset showing packed resident 8x8 tiles vec2 hudMin = vec2(0.03, 0.05); vec2 hudSize = vec2(0.24, 0.30); vec2 hUV = (uv01 - hudMin) / hudSize; if (hudVis > 0.05 && hUV.x > 0.0 && hUV.x < 1.0 && hUV.y > 0.0 && hUV.y < 1.0) { vec2 tileId = floor(hUV * 6.0); vec2 tileF = fract(hUV * 6.0); float hVal = hash21(tileId + floor(iTime * 0.7) * 0.11); float slotMip = floor(hVal * 4.5); float isUsed = step(0.18, hash21(tileId * 3.7 + 2.1)); vec3 slotCol = (isUsed > 0.5) ? mix(mipColor(slotMip), megatexture(tileF + tileId * 0.3, slotMip), 0.45) : vec3(0.06, 0.08, 0.12); float tBorder = smoothstep(0.44, 0.49, max(abs(tileF.x - 0.5), abs(tileF.y - 0.5))); slotCol = mix(slotCol, vec3(0.03, 0.04, 0.07), tBorder); float outerB = min(min(hUV.x, 1.0 - hUV.x), min(hUV.y, 1.0 - hUV.y)); slotCol = mix(slotCol, vec3(0.75, 0.88, 1.0), smoothstep(0.03, 0.008, outerB)); col = mix(col, slotCol, 0.92 * hudVis); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Basis Universal / KTX2 supercompression](https://texelatlas.vercel.app/t/basis-universal-ktx2.md): Pages are stored in a supercompressed form and transcoded to the GPU format as they are streamed into the cache. ## Combination ideas - [Block-compressed tile streaming inside a hardware-filtered virtual texture cache](https://texelatlas.vercel.app/ideas/block-compressed-virtual-texture-cache/) ## Sources 1. [primary] J.M.P. van Waveren Software Virtual Textures. mrelusive.com. https://mrelusive.com/publications/papers/Software-Virtual-Textures.pdf (verified via http on 2026-11-29) 2. [tutorial] Sean Barrett Sparse Virtual Textures. silverspaceship.com. https://silverspaceship.com/src/svt (verified via http on 2026-11-29) ## Cite this entry Texel. "Sparse virtual texturing." https://texelatlas.vercel.app/t/virtual-texturing/ (accessed 2026-12-01). --- id: "visibility-bitmask-ssao" title: "Visibility Bitmask Ambient Occlusion" domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2022 inputs: [depth, normals] outputs: [visibility-mask, radiance] style: "photoreal" dynamic: "dynamic" cost: "medium" authority: "Therrien et al., 2022" url: "https://texelatlas.vercel.app/t/visibility-bitmask-ssao/" sources_verified_at: "2026-11-29" --- # Visibility Bitmask Ambient Occlusion (Therrien et al., 2022) > Records occluded sectors of the hemisphere as bits in an integer mask instead of a single horizon angle, so thin occluders can be handled and indirect light can be gathered. ## Reach for it when - fences and foliage get over-darkened by screen-space occlusion - thin occluders are treated as solid walls - want cheap indirect light together with occlusion - horizon-based darkening fails on thin geometry ## How it works Instead of keeping a max horizon per direction, each depth sample marks the angular interval it occupies, determined with an assumed thickness, as set bits in a 32-bit mask. The union of all occupied intervals gives the visible fraction (popcount) and the unset bits indicate directions from which light can arrive, which can be weighted by the radiance sampled at those pixels to give a screen-space one-bounce indirect term. This handles gaps between thin occluders and avoids the infinite thickness assumption of horizon-based methods. Cost is similar to horizon AO with a few bit operations per sample. ## When to use it Choose it when thin geometry (fences, foliage, railings) makes [Ground-Truth Ambient Occlusion](https://texelatlas.vercel.app/t/ground-truth-ambient-occlusion.md) or [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) over-darken, or when you want AO and a cheap screen-space indirect term together. Prefer [Ray-Traced Ambient Occlusion](https://texelatlas.vercel.app/t/ray-traced-ambient-occlusion.md) for full accuracy and [Screen-Space Ambient Occlusion](https://texelatlas.vercel.app/t/ssao.md) when 32-bit integer ops are not available. ## Cost medium — A couple of ms at 1080p depending on slice and sample count; similar to GTAO plus bit work. Measured GPU Weight: 146.4× baseline (extreme) — 4.8166 ms median / 4.9604 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 126.04× baseline (extreme) — 2.004 ms median (2.4× faster on L4). Ampere A100 scaling: 93.28× baseline (extreme) — 2.6865 ms median (1.79× faster on A100). ## Failure modes - Needs a thickness heuristic that must be tuned per scene - Screen-space limit: off-screen light and occluders are missing - Noise and temporal artefacts when only a few slices are used - Indirect term is limited to what the previous frame shows ## Dataflow - Inputs: depth, normals - Outputs: visibility-mask, radiance - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Visibility bitmask SSAO — sector-based horizon visibility vs lit geometry split (glsl-fragment; rendered 2026-11-30) ```json { "P_AO_RADIUS": 0.85, "P_THICKNESS": 0.32, "P_AO_POWER": 1.35, "P_SPLIT": 0.48 } ``` ```glsl const float P_AO_RADIUS = 0.85; // P Gather Radius [0.25, 1.8, 0.05] const float P_THICKNESS = 0.32; // P Occluder Thick [0.08, 0.8, 0.02] const float P_AO_POWER = 1.35; // P AO Contrast [0.4, 2.5, 0.05] const float P_SPLIT = 0.48; // P AO/Lit Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } // Multi-depth architectural atrium with thin hovering bars & recessed niches // (specifically illustrates how Visibility Bitmask AO avoids over-occlusion behind thin objects!) vec2 mapScene(vec3 p) { vec2 res = vec2(p.y + 0.85, 1.0); // floor float backD = p.z + 1.35; if (backD < res.x) res = vec2(backD, 1.0); // Recessed fluted arcade alcoves along rear wall vec3 ap = p - vec3(0.0, 0.0, -1.22); ap.x = mod(ap.x + 0.55, 1.1) - 0.55; float dPillar = sdBox(ap, vec3(0.14, 1.2, 0.24)) - 0.02; if (dPillar < res.x) res = vec2(dPillar, 2.0); // Thin floating sculptural ring & hovering bar (classic VBAO thickness test) vec3 q = p - vec3(0.0, -0.05, -0.25); q.xz = rot2(iTime * 0.32) * q.xz; q.xy = rot2(0.52) * q.xy; float dRing = sdTorus(q, vec2(0.58, 0.11)); if (dRing < res.x) res = vec2(dRing, 3.0); // Resting matte spheres on floor forming tight contact crevices float dS1 = length(p - vec3(-0.62, -0.53, -0.15)) - 0.32; float dS2 = length(p - vec3(0.64, -0.57, -0.28)) - 0.28; float dS3 = length(p - vec3(0.0, -0.55, -0.25)) - 0.30; float dSph = min(dS1, min(dS2, dS3)); if (dSph < res.x) res = vec2(dSph, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Emulate Visibility Bitmask AO (12 discrete elevation bins per slice, float-safe for GLSL ES 1.00) // Each horizon sample covers only its angular interval [thetaBack, thetaFront] using finite occluder thickness! float evalVisibilityBitmaskAO(vec3 p, vec3 n, float radius, float thickness, float jitter) { vec3 tanV = normalize(abs(n.y) < 0.9 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0))); vec3 bitV = cross(n, tanV); float occTotal = 0.0; // 4 azimuthal slices around tangent plane for (int slice = 0; slice < 4; slice++) { float phi = (float(slice) + jitter * 0.5) * 1.570796; vec3 dir = cos(phi) * tanV + sin(phi) * bitV; // 5+5 discrete cosine-weighted angular elevation sectors across [-pi/2, +pi/2] float secPos[5]; float secNeg[5]; for (int b = 0; b < 5; b++) { secPos[b] = 0.0; secNeg[b] = 0.0; } // Sample both positive (+dir) and negative (-dir) horizon directions along the slice for (int side = 0; side < 2; side++) { vec3 sDir = (side == 0) ? dir : -dir; for (int st = 1; st <= 4; st++) { float dist = radius * (float(st) / 4.0); vec3 sp = p + sDir * dist; float sdf = mapScene(sp).x; if (sdf < 0.22) { float hFront = clamp(0.18 - sdf, 0.0, radius); float hBack = hFront - thickness; float angFront = atan(hFront, dist); float angBack = atan(hBack, dist); float falloff = smoothstep(radius * 1.15, radius * 0.15, dist); for (int k = 0; k < 5; k++) { float binAng = (float(k) + 0.5) * (1.570796 / 5.0); float inInterval = smoothstep(angBack - 0.12, angBack + 0.08, binAng) * smoothstep(angFront + 0.12, angFront - 0.08, binAng); if (side == 0) secPos[k] = max(secPos[k], inInterval * falloff); else secNeg[k] = max(secNeg[k], inInterval * falloff); } } } } // Count occupied bitmask sectors with cosine hemisphere weighting (popcount analog) float sliceOcc = 0.0; for (int b = 0; b < 5; b++) { float elev = (float(b) + 0.5) * (1.570796 / 5.0); float cosW = cos(elev); sliceOcc += (secPos[b] + secNeg[b]) * cosW; } occTotal += sliceOcc / 6.2; } return clamp(1.0 - occTotal * 0.25, 0.02, 1.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 screenUV = fragCoord / iResolution.xy; vec3 ro = vec3(0.0, 0.28, 2.55); vec3 ta = vec3(0.0, -0.22, -0.35); vec3 ww = normalize(ta - ro); vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); vec3 vv = cross(uu, ww); vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.5 * ww); float rad = clamp(P_AO_RADIUS, 0.2, 2.0); float thick = clamp(P_THICKNESS, 0.06, 0.9); float aoPow = clamp(P_AO_POWER, 0.3, 3.0); float splitX = clamp(P_SPLIT, 0.0, 1.0); vec3 col = mix(vec3(0.06, 0.075, 0.10), vec3(0.16, 0.20, 0.28), smoothstep(-0.5, 0.6, uv.y)); float t = 0.0; float matId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 10.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); float jitter = fract(52.9829189 * fract(dot(fragCoord, vec2(0.06711056, 0.00583715)))); float vbao = pow(evalVisibilityBitmaskAO(p + n * 0.015, n, rad, thick, jitter), aoPow); if (screenUV.x < splitX) { // Left side: pure Visibility Bitmask Ambient Occlusion buffer (cool archival clay display) col = mix(vec3(0.04, 0.055, 0.085), vec3(0.94, 0.96, 0.99), vbao); } else { // Right side: lit PBR architectural scene shaded with VBAO indirect occlusion vec3 alb = vec3(0.76, 0.75, 0.72); if (matId > 1.5 && matId < 2.5) alb = vec3(0.68, 0.66, 0.64); else if (matId > 2.5 && matId < 3.5) alb = vec3(0.86, 0.54, 0.24); else if (matId > 3.5) alb = vec3(0.56, 0.72, 0.84); vec3 lDir = normalize(vec3(0.55 * cos(iTime * 0.35) + 0.3, 0.82, 0.58)); float ndl = max(dot(n, lDir), 0.0); vec3 hVec = normalize(lDir - rd); float spec = pow(max(dot(n, hVec), 0.0), 42.0) * 0.42; vec3 skyAmb = mix(vec3(0.18, 0.22, 0.30), vec3(0.42, 0.54, 0.72), n.y * 0.5 + 0.5); col = alb * (vec3(1.55, 1.42, 1.24) * ndl * (0.35 + 0.65 * vbao) + skyAmb * vbao) + vec3(1.0, 0.94, 0.86) * spec * vbao; col = aces(col); } } if (splitX > 0.01 && splitX < 0.99 && abs(screenUV.x - splitX) < 0.004) { col = vec3(0.28, 0.88, 1.0); } fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Horizon-Based Ambient Occlusion](https://texelatlas.vercel.app/t/hbao.md) ## Combination ideas - [A thin-occluder cascade zero](https://texelatlas.vercel.app/ideas/bitmask-near-field-cascades/) ## Sources 1. [primary] Olivier Therrien, Yannick Levesque, Guillaume Gilet (2022) Screen space indirect lighting with visibility bitmask. The Visual Computer. https://doi.org/10.1007/s00371-022-02703-y (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Visibility Bitmask Ambient Occlusion." https://texelatlas.vercel.app/t/visibility-bitmask-ssao/ (accessed 2026-12-01). --- id: "visibility-buffer" title: "Visibility buffer rendering" aliases: [V-buffer, visibility buffer] domain: "performance" stage: "performance" realtime: "realtime" platforms: [webgpu, desktop-gpu, unreal] year_introduced: 2013 inputs: [mesh, material-params, texture] outputs: [gbuffer, radiance] style: "both" dynamic: "dynamic" cost: "medium" authority: "" url: "https://texelatlas.vercel.app/t/visibility-buffer/" sources_verified_at: "2026-11-29" --- # Visibility buffer rendering > Rasterize only a triangle and instance id per pixel, then fetch vertices and evaluate materials in a later compute or full-screen pass, trading G-buffer bandwidth for shader-side attribute interpolation. ## Reach for it when - g-buffer bandwidth is my bottleneck - small triangles waste shading work in forward rendering - want msaa without a huge g-buffer - many materials cause too many draw calls - pixel quads shade tiny triangles inefficiently ## How it works The geometry pass writes a single 32-bit value per pixel: an instance or draw id plus a primitive id. Nothing else is stored, so the pass is cheap and bandwidth-light, and hardware MSAA stays affordable. A shading pass then, per pixel, looks up the triangle's three vertices from bindless or unified vertex and index buffers, reconstructs the barycentrics by intersecting the camera ray with the triangle analytically, interpolates attributes itself, and computes UV derivatives from the same math so mipmapping works. It then evaluates the material and lighting. Because pixels are grouped by material (via tile classification or a material-id depth trick), each material runs coherently over a screen region instead of being scattered across draws, and many materials can be shaded without many draw calls. ## When to use it Choose it with GPU-driven pipelines, dense small triangles, many materials, or when MSAA matters and a fat G-buffer is too heavy. Prefer [Deferred shading (G-buffer)](https://texelatlas.vercel.app/t/deferred-shading.md) when engine tooling, decals and legacy post-effects all assume a classic G-buffer, or on hardware without bindless access. It is the shading model behind [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md); pair with [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md) and [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md) for the full pipeline. ## Cost medium — Cheap geometry pass, heavier shading pass because of vertex fetch and manual interpolation; wins grow with triangle density. Qualitative. Measured GPU Weight: 27.03× baseline (heavy) — 0.8487 ms median / 0.8971 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 24.5× baseline (heavy) — 0.3871 ms median (2.19× faster on L4). Ampere A100 scaling: 18.05× baseline (moderate) — 0.5199 ms median (1.63× faster on A100). ## Failure modes - Texture sampling needs analytically derived UV gradients; getting them wrong gives over-blurred or aliased textures at silhouettes - Alpha-tested and transparent geometry cannot be resolved from a single id, so they need a separate path or per-pixel discard in the id pass - Shading pass reads scattered vertex data, causing cache pressure and divergent shaders if materials are not binned - Needs bindless/unified buffers, which limits older or WebGL-class targets - Vertex-shader features such as skinning and morphs must be done before the id pass or replayed in shading ## Engine support - unreal: builtin — `Nanite rasterizes cluster and triangle IDs to a Visibility Buffer and shades materials in a subsequent pass` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/nanite-virtualized-geometry-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: mesh, material-params, texture - Outputs: gbuffer, radiance - Platforms: webgpu, desktop-gpu, unreal ## Presets ### Visibility buffer rendering — compact triangle/instance ID buffer vs decoupled material pass (glsl-fragment; rendered 2026-11-30) ```json { "P_TRI_DENSITY": 10, "P_SPLIT": 0.45, "P_WIRE_OVERLAY": 0.65, "P_ROT_SPEED": 1 } ``` ```glsl const float P_TRI_DENSITY = 10.0; // P Triangle Scale [4.0, 20.0, 0.5] const float P_SPLIT = 0.45; // P VisBuf / Shaded [0.0, 1.0, 0.02] const float P_WIRE_OVERLAY = 0.65; // P Barycentric Wire [0.0, 1.5, 0.05] const float P_ROT_SPEED = 1.0; // P Spin Speed [0.0, 2.5, 0.05] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } vec3 hash31(float x) { vec3 p = fract(vec3(x) * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yzx + 33.33); return fract((p.xxy + p.yzz) * p.zyx); } float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; } 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); } // Returns vec2(distance, instanceID) vec2 mapScene(vec3 p, float spin) { vec2 res = vec2(p.y + 0.85, 1.0); // Instance 1: floor vec3 q1 = p - vec3(-0.55, 0.05, -0.15); q1.xz = rot2(spin * 0.5) * q1.xz; q1.xy = rot2(0.52) * q1.xy; float d1 = sdTorus(q1, vec2(0.48, 0.19)); if (d1 < res.x) res = vec2(d1, 2.0); // Instance 2: brushed brass torus vec3 q2 = p - vec3(0.62, -0.18, -0.25); q2.xz = rot2(-spin * 0.42) * q2.xz; float d2 = length(q2) - 0.42; if (d2 < res.x) res = vec2(d2, 3.0); // Instance 3: ceramic sphere vec3 q3 = p - vec3(0.05, -0.35, -1.15); q3.xz = rot2(spin * 0.25) * q3.xz; float d3 = sdBox(q3, vec3(0.32, 0.50, 0.32)) - 0.03; if (d3 < res.x) res = vec2(d3, 4.0); // Instance 4: monolith return res; } vec3 calcNormal(vec3 p, float spin) { vec2 e = vec2(0.002, 0.0); return normalize(vec3( mapScene(p + e.xyy, spin).x - mapScene(p - e.xyy, spin).x, mapScene(p + e.yxy, spin).x - mapScene(p - e.yxy, spin).x, mapScene(p + e.yyx, spin).x - mapScene(p - e.yyx, spin).x )); } // Compute surface parametric UV per instance for deterministic triangle IDs & barycentrics vec2 instanceUV(vec3 p, float instId, float spin) { if (instId < 1.5) return p.xz * 0.5; if (instId < 2.5) { vec3 q = p - vec3(-0.55, 0.05, -0.15); q.xz = rot2(spin * 0.5) * q.xz; q.xy = rot2(0.52) * q.xy; return vec2(atan(q.z, q.x) * 0.5, atan(q.y, length(q.xz) - 0.48) * 0.35); } if (instId < 3.5) { vec3 q = p - vec3(0.62, -0.18, -0.25); q.xz = rot2(-spin * 0.42) * q.xz; return vec2(atan(q.z, q.x) * 0.45, asin(clamp(q.y / 0.42, -0.99, 0.99)) * 0.45); } vec3 q = p - vec3(0.05, -0.35, -1.15); q.xz = rot2(spin * 0.25) * q.xz; return vec2(q.x + q.z, q.y) * 0.9; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float triDens = clamp(P_TRI_DENSITY, 3.0, 22.0); float wireAmt = clamp(P_WIRE_OVERLAY, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.45, 2.55); vec3 rd = normalize(vec3(uv.x, uv.y - 0.14, -1.48)); vec3 col = mix(vec3(0.035, 0.045, 0.065), vec3(0.09, 0.11, 0.16), smoothstep(-0.5, 0.6, uv.y)); float t = 0.0; float instId = 0.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t, spin); if (h.x < 0.002) { hit = true; instId = h.y; break; } t += h.x; if (t > 12.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, spin); vec2 suv = instanceUV(p, instId, spin) * triDens; // Split each quad cell into two triangles -> exact (triID, barycentric coords) vec2 cell = floor(suv); vec2 f = fract(suv); float upper = step(f.x, f.y); vec3 bary = (upper > 0.5) ? vec3(1.0 - f.y, f.x, f.y - f.x) : vec3(1.0 - f.x, f.y, f.x - f.y); float triId = hash21(cell * 1.31 + vec2(upper * 19.7, instId * 37.3)); // Stage 1: Compact Visibility Buffer (InstanceID + PrimitiveID packed into 32 bits) vec3 instTint = hash31(instId * 7.13 + 2.4); vec3 triTint = hash31(triId * 91.7 + instId * 13.0); vec3 visBufCol = mix(instTint, triTint, 0.62); float baryMin = min(bary.x, min(bary.y, bary.z)); float triEdge = smoothstep(0.075, 0.015, baryMin); visBufCol = mix(visBufCol, vec3(0.04, 0.06, 0.09), triEdge * 0.65 * min(wireAmt, 1.2)); // Encode subtle barycentric RGB tint in bottom strip of left side if (uv.y < -0.26 && screenX < split) { visBufCol = mix(visBufCol, bary, 0.72); } // Stage 2: Decoupled full-screen material pass reconstructing attributes from triangle ID vec3 l1 = normalize(vec3(0.62, 0.85, 0.52)); vec3 l2 = normalize(vec3(-0.72, 0.30, 0.45)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); vec3 hVec = normalize(l1 - rd); vec3 alb; float specPow = 28.0; float specGain = 0.35; if (instId < 1.5) { float chk = mod(floor(p.x * 2.0) + floor(p.z * 2.0), 2.0); alb = mix(vec3(0.16, 0.19, 0.24), vec3(0.26, 0.30, 0.36), chk); } else if (instId < 2.5) { alb = vec3(0.86, 0.64, 0.24); specPow = 54.0; specGain = 0.78; } else if (instId < 3.5) { float stripes = smoothstep(-0.2, 0.2, sin(suv.y * 2.2)); alb = mix(vec3(0.16, 0.54, 0.78), vec3(0.88, 0.91, 0.94), stripes * 0.45); specPow = 40.0; specGain = 0.52; } else { alb = vec3(0.78, 0.26, 0.32); specPow = 22.0; specGain = 0.30; } float spec = pow(max(dot(n, hVec), 0.0), specPow) * specGain; float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0) * 0.25; vec3 shaded = alb * (0.20 + 0.88 * diff1 + 0.25 * diff2) + vec3(spec) + vec3(0.45, 0.68, 1.0) * rim; // Subtle reconstructed triangle wireframe hint when wire slider > 0 shaded = mix(shaded, shaded + vec3(0.14, 0.22, 0.32), triEdge * 0.25 * wireAmt); float fog = exp(-max(t - 3.0, 0.0) * 0.14); col = (screenX < split) ? visBufCol : mix(vec3(0.05, 0.07, 0.10), shaded, fog); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Deferred shading (G-buffer)](https://texelatlas.vercel.app/t/deferred-shading.md) - extended by [Nanite virtualized geometry](https://texelatlas.vercel.app/t/nanite-virtualized-geometry.md) ## Combines with - [GPU-driven rendering](https://texelatlas.vercel.app/t/gpu-driven-rendering.md): GPU culling emits the visible instance and triangle ids that the visibility pass writes. - [Meshlets (cluster rendering)](https://texelatlas.vercel.app/t/meshlets.md): Cluster ids give compact primitive ids so the id target stays small and vertex fetch is coherent. ## Sources 1. [primary] The Visibility Buffer: A Cache-Friendly Approach to Deferred Shading. jcgt.org. https://jcgt.org/published/0002/02/04 (verified via http on 2026-11-29) 2. [talk] Ulrich Haar, Sebastian Aaltonen GPU-Driven Rendering Pipelines. SIGGRAPH 2015 Advances in Real-Time Rendering. https://advances.realtimerendering.com/s2015/aaltonenhaar_siggraph2015_combined_final_footer_220dpi.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Visibility buffer rendering." https://texelatlas.vercel.app/t/visibility-buffer/ (accessed 2026-12-01). --- id: "visual-hull" title: "Visual Hull (Shape from Silhouette)" aliases: [shape-from-silhouette, space carving (silhouette)] domain: "capture" stage: "capture" realtime: "interactive" platforms: [cpu, cuda] year_introduced: 1994 inputs: [photos, camera-poses] outputs: [voxels, mesh] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Laurentini, 1994" url: "https://texelatlas.vercel.app/t/visual-hull/" sources_verified_at: "2026-11-29" --- # Visual Hull (Shape from Silhouette) (Laurentini, 1994) > Reconstructs a conservative 3D shape as the intersection of the viewing cones back-projected from silhouettes in several calibrated views. ## Reach for it when - need coarse shape from turntable photos with masks - calibrated multi-camera rig should yield a quick 3d volume - initialise a mesh from silhouettes - bound a neural field with a robust rough shape - shape from outlines in several views ## How it works Segment the object in each calibrated image to get a binary silhouette. Every silhouette defines a cone from the camera centre through the object's outline, and the object must lie inside all of them. Voxel carving tests each voxel by projecting it into every view and discarding it if it falls outside any silhouette; polyhedral methods intersect the cones exactly. The result is the visual hull, the largest shape consistent with all silhouettes. It always contains the true object and cannot represent concavities invisible in silhouettes. More views tighten the hull. It runs in real time for multi-camera rigs, which is why it was used for live performance capture, and often serves as initialisation for photo-consistency refinement. ## When to use it Choose it for fast, robust coarse shape from calibrated multi-camera rigs or turntable captures with clean masks, e.g. initialising a mesh or bounding a neural field. Prefer [Multi-View Stereo (PatchMatch, COLMAP)](https://texelatlas.vercel.app/t/multi-view-stereo-patchmatch.md) or [NeuS](https://texelatlas.vercel.app/t/neus.md) when concavities and surface detail matter. Use [Segment Anything (SAM)](https://texelatlas.vercel.app/t/segment-anything.md) or [SAM 2](https://texelatlas.vercel.app/t/sam2.md) to produce the masks it needs. ## Cost cheap — Voxel projection tests are embarrassingly parallel and cheap on GPU; dominated by segmentation quality, not compute. Measured GPU Weight: 64.42× baseline (extreme) — 1.9969 ms median / 2.0548 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 45.65× baseline (heavy) — 0.7258 ms median (2.75× faster on L4). Ampere A100 scaling: 39.32× baseline (heavy) — 1.1323 ms median (1.76× faster on A100). ## Failure modes - Concavities (bowls, eye sockets) are filled in because silhouettes cannot see them - Few views leave phantom volumes (ghost blobs) outside the true shape - A single bad mask carves a hole through the whole model since intersection is unforgiving - Calibration error shaves thin parts such as limbs and fingers ## Dataflow - Inputs: photos, camera-poses - Outputs: voxels, mesh - Platforms: cpu, cuda ## Presets ### Visual Hull (Shape from Silhouette) — 3-camera coarse intersection (left) vs N-camera carved hull (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_CAM_COUNT": 12, "P_CONE_VIS": 0.75, "P_ROT_SPEED": 0.65, "P_SPLIT": 0.48 } ``` ```glsl const float P_CAM_COUNT = 12.0; // P Camera Count N [3.0, 18.0, 1.0] const float P_CONE_VIS = 0.75; // P Camera Ring Vis [0.0, 1.5, 0.05] const float P_ROT_SPEED = 0.65; // P Spin Speed [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P 3-Cam / N-Cam Split [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // 2D projected silhouette SDF of a sculpted trophy/chalice seen from camera azimuth angle phi // Back-projecting each camera's silhouette creates a 3D generalized cylinder (viewing cone)! // Intersecting N viewing cones = max_k(sdSilhouette_k(p)) = EXACT Visual Hull! float silhouetteCone(vec3 q, float phi) { // Project 3D point q into camera k's image plane (x_cam, y_cam) float xCam = q.x * cos(phi) + q.z * sin(phi); float yCam = q.y; // True object silhouette profile: wide flared bowl at top, narrow stem, wide pedestal foot float profileR = 0.24 + 0.24 * exp(-pow((yCam - 0.34) / 0.22, 2.0)) + 0.22 * exp(-pow((yCam + 0.44) / 0.14, 2.0)) - 0.11 * exp(-pow((yCam + 0.04) / 0.18, 2.0)); // Subtle non-axisymmetric handles protruding at phi=0 and phi=pi float handleProj = abs(cos(phi)) * 0.18 * exp(-pow((yCam - 0.28) / 0.16, 2.0)); float halfW = profileR + handleProj; float dX = abs(xCam) - halfW; float dY = abs(yCam) - 0.56; return max(dX, dY); } // Exact Visual Hull = intersection (max) of N back-projected viewing cones around the equator! float mapVisualHull(vec3 p, int nCams, float spin) { vec3 q = p; q.xz = rot2(spin * 0.55) * q.xz; q.yz = rot2(0.32) * q.yz; float dHull = -1e5; for (int k = 0; k < 18; k++) { if (k >= nCams) break; float phi = float(k) / float(nCams) * 3.1415926; dHull = max(dHull, silhouetteCone(q, phi)); } return dHull * 0.85; } vec3 calcNormal(vec3 p, int nCams, float spin) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapVisualHull(p + e.xyy, nCams, spin) - mapVisualHull(p - e.xyy, nCams, spin), mapVisualHull(p + e.yxy, nCams, spin) - mapVisualHull(p - e.yxy, nCams, spin), mapVisualHull(p + e.yyx, nCams, spin) - mapVisualHull(p - e.yyx, nCams, spin) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isMany = screenX >= split; int nCams = isMany ? int(clamp(floor(P_CAM_COUNT + 0.5), 3.0, 18.0)) : 3; float coneVis = clamp(P_CONE_VIS, 0.0, 1.5); float spin = iTime * max(P_ROT_SPEED, 0.0); vec3 ro = vec3(0.0, 0.36, 2.48); vec3 ta = vec3(0.0, -0.02, 0.0); vec3 fwd = normalize(ta - ro); vec3 right = normalize(cross(fwd, vec3(0.0, 1.0, 0.0))); vec3 up = cross(right, fwd); vec3 rd = normalize(fwd * 1.52 + right * uv.x + up * uv.y); vec3 col = mix(vec3(0.024, 0.034, 0.056), vec3(0.068, 0.088, 0.140), smoothstep(-0.55, 0.55, uv.y)); // Draw the calibrated multi-camera capture ring on floor plane y = -0.58 if (rd.y < -0.01) { float tFlr = (-0.58 - ro.y) / rd.y; if (tFlr > 0.0 && tFlr < 12.0) { vec3 pf = ro + rd * tFlr; float rFlr = length(pf.xz); float ringLine = smoothstep(0.026, 0.006, abs(rFlr - 1.15)); col += vec3(0.24, 0.56, 0.88) * ringLine * 0.65 * min(coneVis, 1.2); // Camera frustum markers around the capture ring (3 on left, N on right!) vec3 qf = pf; qf.xz = rot2(spin * 0.55) * qf.xz; for (int k = 0; k < 18; k++) { if (k >= nCams) break; float phi = float(k) / float(nCams) * 6.2831853; vec2 cPos = vec2(cos(phi), sin(phi)) * 1.15; float dCam = length(qf.xz - cPos); col += vec3(1.0, 0.84, 0.30) * smoothstep(0.065, 0.022, dCam) * 0.90 * min(coneVis, 1.2); // Sightline ray from camera toward hull center float proj = clamp(dot(qf.xz, cPos) / (1.15 * 1.15), 0.0, 1.0); float dRay = length(qf.xz - cPos * proj); col += vec3(0.20, 0.78, 0.94) * smoothstep(0.014, 0.003, dRay) * 0.25 * min(coneVis, 1.2); } } } // Raymarch the carved Visual Hull intersection of N silhouette cones float t = 0.0; bool hit = false; for (int i = 0; i < 68; i++) { float d = mapVisualHull(ro + rd * t, nCams, spin); if (d < 0.002) { hit = true; break; } t += d; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, nCams, spin); // Highlight polyhedral facet seams where different camera viewing cones intersect vec3 nA = calcNormal(p + vec3(0.014, 0.0, 0.0), nCams, spin); vec3 nB = calcNormal(p + vec3(0.0, 0.0, 0.014), nCams, spin); float facetEdge = smoothstep(0.14, 0.48, (1.0 - dot(n, nA)) + (1.0 - dot(n, nB))); vec3 l1 = normalize(vec3(0.58, 0.84, 0.52)); vec3 l2 = normalize(vec3(-0.70, -0.22, 0.50)); float diff = max(dot(n, l1), 0.0) * 0.85 + max(dot(n, l2), 0.0) * 0.26; float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 42.0); vec3 alb = isMany ? vec3(0.20, 0.78, 0.74) : vec3(0.88, 0.54, 0.28); col = alb * (0.28 + 0.82 * diff) + vec3(0.95) * spec * 0.45; col = mix(col, vec3(1.0, 0.92, 0.45), facetEdge * 0.72); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Segment Anything (SAM)](https://texelatlas.vercel.app/t/segment-anything.md): SAM supplies per-view silhouettes that the hull intersects. ## Combination ideas - [Depth-feathered soft-particle smoke wrapping live visual-hull silhouettes](https://texelatlas.vercel.app/ideas/visual-hull-soft-particle-shroud/) ## Sources 1. [primary] A. Laurentini (1994) The visual hull concept for silhouette-based image understanding. IEEE Transactions on Pattern Analysis and Machine Intelligence. https://doi.org/10.1109/34.273735 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Visual Hull (Shape from Silhouette)." https://texelatlas.vercel.app/t/visual-hull/ (accessed 2026-12-01). --- id: "vndf-sampling" title: "Visible normal distribution sampling (GGX VNDF)" domain: "materials" stage: "material" realtime: "realtime" platforms: [webgpu, desktop-gpu, cuda, cpu, blender] year_introduced: 2018 inputs: [material-params, normals] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "cheap" authority: "Heitz" url: "https://texelatlas.vercel.app/t/vndf-sampling/" sources_verified_at: "2026-11-29" --- # Visible normal distribution sampling (GGX VNDF) (Heitz) > Sample only the microfacet normals visible from the viewer, rather than the whole distribution, for lower variance and no wasted samples below the horizon. Heitz's ellipsoid-stretch derivation gives a compact exact sampler for GGX. ## Reach for it when - noise at grazing angles in glossy sampling - wasted samples on backfacing microfacets - importance sampling ggx has high variance - monte carlo specular rendering converges slowly ## How it works Naively importance-sampling D(h)*(n.h) produces half-vectors that may be backfacing or masked, wasting samples and creating variance at grazing angles. The visible normal distribution D_v(h) = G1(v) max(0, v.h) D(h) / (n.v) is the distribution of normals a viewer actually sees. Heitz shows that for GGX it is the projection of a hemisphere of an ellipsoid, so one can transform the view vector by the roughness, sample a disk-based hemisphere in the stretched space, and transform back, avoiding any rejection. The resulting reflected direction's pdf is D_v(h)/(4 v.h), which cancels the Fresnel-masking factors and leaves weights near F*G2/G1. Later variants (spherical caps, bounded VNDF) reduce cost further and avoid below-horizon directions. ## When to use it Choose it for Monte Carlo evaluation of GGX in path tracers, ReSTIR-style integrators, and pre-filtering of specular IBL on the GPU. Prefer plain D(h) sampling only when matching legacy implementations. Pair with [Smith masking-shadowing function](https://texelatlas.vercel.app/t/smith-masking-shadowing.md) and [GGX / Trowbridge-Reitz normal distribution](https://texelatlas.vercel.app/t/ggx-trowbridge-reitz.md) since the sampler assumes Smith masking. ## Cost cheap — A handful of arithmetic ops, one sqrt and one trigonometric pair per sample. Measured GPU Weight: 12.81× baseline (moderate) — 0.4213 ms median / 0.4407 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 10.26× baseline (moderate) — 0.1631 ms median (2.58× faster on L4). Ampere A100 scaling: 7.88× baseline (moderate) — 0.227 ms median (1.86× faster on A100). ## Failure modes - Assumes Smith masking, so any other G invalidates the pdf - Numerical precision near zero roughness causes degenerate half-vectors; clamp alpha - Backfacing shading normals need the unbiased variant - Samples reflected below the horizon still occur, so a visibility check is needed ## Engine support - unity: builtin — `HDRP path tracing and SSR sample visible normals internally` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl, checked 2026-12-01) — Shader library function; not a user setting. ## Dataflow - Inputs: material-params, normals - Outputs: radiance - Platforms: webgpu, desktop-gpu, cuda, cpu, blender ## Presets ### GGX VNDF Sampling — standard NDF high-variance grazing noise (left) vs low-variance visible-normal sampling (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ROUGHNESS": 0.42, "P_NOISE_SCALE": 1, "P_LIGHT_SPIN": 0.55, "P_SPLIT": 0.48 } ``` ```glsl const float P_ROUGHNESS = 0.42; // P GGX Roughness [0.12, 0.85, 0.02] const float P_NOISE_SCALE = 1.0; // P MC Variance Vis [0.2, 1.8, 0.05] const float P_LIGHT_SPIN = 0.55; // P Env Spin [0.0, 2.2, 0.05] const float P_SPLIT = 0.48; // P NDF / VNDF Split [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } // High-contrast studio environment for Monte Carlo GGX reflection comparison vec3 evalEnv(vec3 d, float spin) { float ang = atan(d.z, d.x) + spin * 0.45; vec3 sky = mix(vec3(0.04, 0.06, 0.11), vec3(0.18, 0.28, 0.45), smoothstep(-0.2, 0.7, d.y)); // Bright overhead softboxes & studio horizon strips float box1 = smoothstep(0.26, 0.16, abs(sin(ang * 2.0))) * smoothstep(0.18, 0.52, d.y); float sun = pow(max(dot(d, normalize(vec3(cos(spin * 0.45), 0.62, sin(spin * 0.45)))), 0.0), 32.0); float rimStrip = exp(-abs(d.y - 0.08) * 18.0) * (0.4 + 0.6 * cos(ang * 3.0)); return sky + vec3(2.4, 2.2, 1.9) * box1 + vec3(3.2, 2.6, 1.8) * sun + vec3(0.4, 0.85, 1.0) * rimStrip * 0.7; } // Orthonormal tangent basis from surface normal n void buildBasis(vec3 n, out vec3 t, out vec3 b) { vec3 up = (abs(n.y) < 0.99) ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0); t = normalize(cross(up, n)); b = cross(n, t); } // Heitz 2018 exact GGX VNDF microfacet normal sampler in local tangent space (n = +Z) vec3 sampleGGX_VNDF(vec3 Ve, float alpha, vec2 u) { vec3 Vh = normalize(vec3(alpha * Ve.x, alpha * Ve.y, max(Ve.z, 1e-4))); float lensq = Vh.x * Vh.x + Vh.y * Vh.y; vec3 T1 = (lensq > 1e-6) ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); vec3 T2 = cross(Vh, T1); float r = sqrt(clamp(u.x, 0.0, 0.9999)); float phi = 6.2831853 * u.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + Vh.z); t2 = (1.0 - s) * sqrt(max(1.0 - t1 * t1, 0.0)) + s * t2; vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } // Standard GGX NDF sampler (ignores view direction -> samples backfacing/masked microfacets at grazing angles!) vec3 sampleGGX_NDF(float alpha, vec2 u) { float phi = 6.2831853 * u.y; float cosT = sqrt(max((1.0 - u.x) / max(1.0 + (alpha * alpha - 1.0) * u.x, 1e-5), 0.0)); float sinT = sqrt(max(1.0 - cosT * cosT, 0.0)); return vec3(sinT * cos(phi), sinT * sin(phi), cosT); } float smithG1(float ndx, float alpha) { float a2 = alpha * alpha; return 2.0 * ndx / max(ndx + sqrt(a2 + (1.0 - a2) * ndx * ndx), 1e-4); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isVNDF = screenX >= split; float rough = clamp(P_ROUGHNESS, 0.10, 0.90); float alpha = rough * rough; float nGain = clamp(P_NOISE_SCALE, 0.1, 2.0); float spin = iTime * max(P_LIGHT_SPIN, 0.0); vec3 ro = vec3(0.0, 0.42, 2.25); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.08), -1.48)); vec3 col = evalEnv(rd, spin) * 0.35; // Intersect matte-gold metallic sphere (R=0.58) and grazing metallic ground plane (y=-0.58) float b = dot(ro, rd); float c = dot(ro, ro) - 0.58 * 0.58; float disc = b * b - c; float tSph = (disc > 0.0 && (-b - sqrt(disc)) > 0.05) ? (-b - sqrt(disc)) : 1e5; float tPl = (rd.y < -0.01) ? ((-0.58 - ro.y) / rd.y) : 1e5; if (tPl < 0.05 || tPl > 14.0) tPl = 1e5; float tHit = min(tSph, tPl); if (tHit < 1e4) { vec3 p = ro + rd * tHit; vec3 n = (tSph < tPl) ? normalize(p) : vec3(0.0, 1.0, 0.0); vec3 v = -rd; vec3 T, B; buildBasis(n, T, B); vec3 Ve = normalize(vec3(dot(v, T), dot(v, B), max(dot(v, n), 0.005))); // 4-sample Monte Carlo estimator per pixel: NDF suffers massive grazing fireflies/rejections; VNDF stays crisp! vec3 acc = vec3(0.0); vec3 f0 = (tSph < tPl) ? vec3(0.95, 0.76, 0.42) : vec3(0.55, 0.64, 0.78); vec2 pixSeed = floor(fragCoord * mix(1.0, 0.65, clamp(nGain - 0.5, 0.0, 0.7))); float frameJit = floor(iTime * 12.0) * 0.037; for (int s = 0; s < 4; s++) { float fs = float(s); vec2 u = vec2( hash21(pixSeed + vec2(fs * 17.3, frameJit * 11.1)), hash21(pixSeed * 1.37 + vec2(frameJit * 7.3, fs * 29.7)) ); u = clamp(u, 0.002, 0.998); vec3 hLocal = isVNDF ? sampleGGX_VNDF(Ve, alpha, u) : sampleGGX_NDF(alpha, u); vec3 hWorld = normalize(T * hLocal.x + B * hLocal.y + n * hLocal.z); vec3 lWorld = reflect(-v, hWorld); float ndl = dot(n, lWorld); float ndv = max(dot(n, v), 0.005); float ndh = max(dot(n, hWorld), 0.005); float vdh = max(dot(v, hWorld), 0.005); if (ndl > 0.002) { vec3 F = f0 + (1.0 - f0) * pow(1.0 - vdh, 5.0); vec3 env = evalEnv(lWorld, spin); if (isVNDF) { // VNDF weight reduces cleanly to G1(L) * F -- bounded in [0, 1], zero grazing weight explosion! float w = smithG1(ndl, alpha); acc += env * F * w; } else { // Classic NDF weight G2 * (V.H) / (N.V * N.H) explodes at grazing N.V -> 0! float G2 = smithG1(ndl, alpha) * smithG1(ndv, alpha); float w = clamp((G2 * vdh) / max(ndv * ndh, 0.015), 0.0, 4.5 * nGain); acc += env * F * w; } } } col = acc * 0.25; if (tPl < tSph) col = mix(col, evalEnv(rd, spin) * 0.35, 1.0 - exp(-tPl * 0.14)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Smith masking-shadowing function](https://texelatlas.vercel.app/t/smith-masking-shadowing.md) ## Sources 1. [primary] Eric Heitz Sampling the GGX Distribution of Visible Normals. JCGT 2018. https://jcgt.org/published/0007/04/01 (verified via http on 2026-11-29) ## Cite this entry Texel. "Visible normal distribution sampling (GGX VNDF)." https://texelatlas.vercel.app/t/vndf-sampling/ (accessed 2026-12-01). --- id: "volume-ray-marching" title: "Ray-marched Participating Media" aliases: [volume ray marching, single-scattering volume rendering] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu] year_introduced: 1984 inputs: [volume-density, camera-poses] outputs: [radiance, ldr-image] style: "both" dynamic: "both" cost: "medium" authority: "Novák et al., 2018" url: "https://texelatlas.vercel.app/t/volume-ray-marching/" sources_verified_at: "2026-11-29" --- # Ray-marched Participating Media (Novák et al., 2018) > Step along each view ray through a density field, accumulating emitted and in-scattered light weighted by transmittance; the general-purpose way to draw smoke, fog, clouds and fire. ## Reach for it when - need to draw smoke, fog or fire from a density field - want procedural clouds in a shader - visualise medical or simulation volume data - light should scatter through participating media ## How it works At each step of length dt the ray gains radiance equal to the in-scattered light times local density, attenuated by the transmittance accumulated so far; the transmittance then decays by exp(-sigma_t dt). The in-scattered light at a point is the light's radiance reduced by a secondary march toward the light (or a shadow map or cached shadow volume), times a phase function. Choose step size from density and distance, add per-pixel jitter (blue noise) to turn banding into noise, and stop early when transmittance falls under a threshold. For a density that comes from a 3D texture you can skip empty space with a coarse occupancy or min/max grid. Emission is added for fire. Because density is sampled along a ray this is a Riemann-sum solution of the radiative transfer equation and is biased by step size, unlike unbiased delta tracking. ## When to use it Choose it for any dynamic volume you can sample cheaply: procedural clouds, smoke from a fluid sim, shadertoy-style fog, or volumetric medical data. Prefer [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md) when the volume is a global fog with many lights. Prefer [Delta (Woodcock) Tracking](https://texelatlas.vercel.app/t/delta-tracking.md) when you need unbiased results and heterogeneous media offline. Prefer [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md) for sky-scale clouds with an authored pipeline. Prefer [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md) or [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md) for sparse simulation data. ## Cost medium — Scales with steps per pixel times light samples; empty-space skipping and early termination are the key savers. Measured GPU Weight: 390.5× baseline (extreme) — 12.8474 ms median / 13.0307 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 328.42× baseline (extreme) — 5.2219 ms median (2.46× faster on L4). Ampere A100 scaling: 273.19× baseline (extreme) — 7.8679 ms median (1.63× faster on A100). ## Failure modes - Banding stripes from regular step spacing when jitter is missing - Missed thin features when step size exceeds the feature width - Lighting that is only single-scatter, so thick media look too dark - Cost explosion in dense media because secondary light marches multiply the step count - Inconsistent results when step size varies with distance and density is not integrated analytically per step ## Engine support - blender: builtin — `Properties > Render > Volumes > Biased (enable), then Step Rate / Max Steps (Cycles)` (evidence: https://docs.blender.org/manual/en/5.2/render/cycles/render_settings/volumes.html, checked 2026-12-01) - godot: builtin — `Environment.volumetric_fog_enabled = true with FogVolume and FogMaterial (density, density_texture, albedo)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/FogVolume.xml, checked 2026-12-01) - threejs: official — `import { VolumeShader } from 'three/addons/shaders/VolumeShader.js'; TSL: RaymarchingBox from tsl/utils/Raymarching.js` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/shaders/VolumeShader.js, checked 2026-12-01) - unity: builtin — `HDRP Volume > Add Override > Fog > Volumetric Fog (VolumetricLighting.compute integrates density and scattering along jittered view rays)` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute, checked 2026-12-01) — HDRP only. - unreal: builtin — `Heterogeneous Volume component (volumetric material ray marched); also Volumetric Cloud` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/heterogeneous-volumes-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: volume-density, camera-poses - Outputs: radiance, ldr-image - Platforms: webgl2, webgpu, desktop-gpu, cpu ## Presets ### Emission-absorption volume ray marching of a noisy fireball (glsl-fragment; rendered 2026-11-29) ```json { "STEPS": 64, "SIGMA_T": 5 } ``` ```glsl // Emission-absorption volume ray marching: front-to-back accumulation with Beer-Lambert transmittance, // 64 fixed steps through a noise-modulated density ball with a hot emissive core. const int STEPS = 64; const float SIGMA_T = 5.0; float h31(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); } float vn(vec3 x) { vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f); return mix(mix(mix(h31(i), h31(i + vec3(1, 0, 0)), f.x), mix(h31(i + vec3(0, 1, 0)), h31(i + vec3(1, 1, 0)), f.x), f.y), mix(mix(h31(i + vec3(0, 0, 1)), h31(i + vec3(1, 0, 1)), f.x), mix(h31(i + vec3(0, 1, 1)), h31(i + vec3(1, 1, 1)), f.x), f.y), f.z); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.0, 3.5), rd = normalize(vec3(uv, -1.8)); vec3 bg = mix(vec3(0.02, 0.02, 0.04), vec3(0.08, 0.1, 0.16), uv.y + 0.5); float b = dot(ro, rd); float hh = b * b - dot(ro, ro) + 1.44; vec3 col = bg; if (hh > 0.0) { float t0 = -b - sqrt(hh), t1 = -b + sqrt(hh); float ds = (t1 - t0) / float(STEPS); float T = 1.0; vec3 L = vec3(0.0); for (int i = 0; i < STEPS; i++) { vec3 p = ro + rd * (t0 + (float(i) + 0.5) * ds); float r = length(p); vec3 q = p * 2.2 + vec3(0.0, -iTime * 0.6, 0.0); float n = 0.55 * vn(q) + 0.3 * vn(q * 2.1) + 0.15 * vn(q * 4.3); float d = clamp((1.0 - r / 1.2) * 1.6 + (n - 0.5) * 1.2, 0.0, 1.0) * SIGMA_T; float heat = clamp(1.0 - r / 0.8, 0.0, 1.0) * n * 2.0; vec3 em = mix(vec3(0.15, 0.1, 0.09), vec3(2.2, 0.9, 0.25), heat) * d; L += T * em * ds; T *= exp(-d * ds); } col = bg * T + L; } col = 1.0 - exp(-col * 1.6); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md) - extended by [Nubis-style Ray-marched Volumetric Clouds](https://texelatlas.vercel.app/t/nubis-volumetric-clouds.md) - extended by [Ray-marched Rayleigh/Mie Single Scattering](https://texelatlas.vercel.app/t/rayleigh-mie-single-scattering.md) - extended by [Schwarzschild Null-Geodesic Gravitational Lensing and Relativistic Accretion Disk](https://texelatlas.vercel.app/t/schwarzschild-null-geodesic-lensing.md) ## Combines with - [OpenVDB](https://texelatlas.vercel.app/t/openvdb.md): Reads density from sparse grids with ray-grid traversal that skips inactive space. - [Henyey-Greenstein Phase Function](https://texelatlas.vercel.app/t/henyey-greenstein-phase-function.md): Weights the in-scattered light at each step. ## Sources 1. [primary] Jan Novák, Iliyan Georgiev, Johannes Hanika, Wojciech Jarosz (2018) Monte Carlo Methods for Volumetric Light Transport Simulation. Computer Graphics Forum. https://doi.org/10.1111/cgf.13383 (verified via crossref on 2026-11-29) 2. [tutorial] Matt Pharr, Wenzel Jakob, Greg Humphreys Media (Physically Based Rendering, 4th ed.). pbr-book.org. https://www.pbr-book.org/4ed/Volume_Scattering/Media (verified via http on 2026-11-29) 3. [implementation] Gökay Aydoğan (2026) gokayfem/glsl-studies. https://github.com/gokayfem/glsl-studies License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Ray-marched Participating Media." https://texelatlas.vercel.app/t/volume-ray-marching/ (accessed 2026-12-01). --- id: "volumetric-light-scattering-god-rays" title: "Screen-space Volumetric Light Scattering (God Rays)" aliases: [crepuscular rays, light shafts, radial blur god rays] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2008 inputs: [depth, ldr-image] outputs: [ldr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Mitchell" url: "https://texelatlas.vercel.app/t/volumetric-light-scattering-god-rays/" sources_verified_at: "2026-11-29" --- # Screen-space Volumetric Light Scattering (God Rays) (Mitchell) > Fake sun shafts by blurring an occluder mask radially away from the sun's screen position and adding it over the frame. ## Reach for it when - want sun shafts on mobile or web cheaply - light beams through trees or clouds - stylised glow around the sun behind occluders - volumetric rays without raymarching a volume - cheap radial light streaks ## How it works Render a mask in which the sky and sun are bright and every occluder is black (the depth buffer or a separate pass can supply this). In a post pass, for each pixel, take N samples along the line toward the sun's screen-space position, accumulating the mask with a decay that falls as the sample moves away from the pixel, and a weight and exposure controls. The sum approximates integrating scattered sunlight along the view ray through the medium as if the medium had uniform density and the mask were the visibility to the sun. The result is added to the scene colour, usually only when the sun is in front of the camera and faded out by the dot product of view and sun direction. Resolution can be quarter size with a bilateral upsample. ## When to use it Choose it as a very cheap sun-shaft effect on mobile, web and older hardware, or as an art-directed stylised rim of light. Prefer [Froxel Volumetric Fog](https://texelatlas.vercel.app/t/froxel-volumetric-fog.md) for physically shadowed shafts from many lights and for shafts that persist when the sun is off-screen. Prefer [Exponential Height Fog](https://texelatlas.vercel.app/t/exponential-height-fog.md) when you only need haze. Use [Scalable Production Sky and Atmosphere (Hillaire)](https://texelatlas.vercel.app/t/hillaire-sky-atmosphere.md) for the sun colour. ## Cost cheap — Fixed N texture samples per pixel (often 32 to 100) in a post pass; run at reduced resolution to cut cost. Measured GPU Weight: 43.37× baseline (heavy) — 1.4269 ms median / 1.4553 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 37.84× baseline (heavy) — 0.6017 ms median (2.37× faster on L4). Ampere A100 scaling: 25.08× baseline (heavy) — 0.7223 ms median (1.98× faster on A100). ## Failure modes - Effect disappears abruptly when the sun leaves the screen, since it needs the sun position on screen - Banding or repeated ghost rays with too few samples along the blur direction - Bright foreground objects (not the sun) bloom radial streaks if the mask is thresholded poorly - Shafts do not show through translucent occluders or reflect the actual scattering medium density - Rays appear in front of objects if the sky-only mask ignores depth of transparent surfaces ## Engine support - babylonjs: builtin — `new BABYLON.VolumetricLightScatteringPostProcess('vls', 1.0, camera, mesh, 100, ..., engine)` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/PostProcesses/volumetricLightScatteringPostProcess.ts, checked 2026-12-01) - blender: builtin — `Compositor > Add > Filter > Glare, Glare Type = Sun Beams` (evidence: https://docs.blender.org/manual/en/5.2/compositing/types/filter/glare.html, checked 2026-12-01) — Screen-space crepuscular rays in the compositor. - threejs: official — `import { godrays } from 'three/addons/tsl/display/GodraysNode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/GodraysNode.js, checked 2026-12-01) - unreal: builtin — `Directional Light > Light Shafts > Light Shaft Bloom / Light Shaft Occlusion` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/using-light-shafts-in-unreal-engine, checked 2026-12-01) — Screen-space light shafts; Volumetric Fog also gives true volumetric scattering. ## Dataflow - Inputs: depth, ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Ray-marched fog light shafts through a slotted wall (glsl-fragment; rendered 2026-11-29) ```json { "STEPS": 72, "SIGMA": 0.45 } ``` ```glsl // Light shafts by ray-marching homogeneous fog: at each sample a shadow test against a slotted wall decides // whether the point-light behind it is visible. In-scattering is weighted by the Henyey-Greenstein phase // and view transmittance. The shafts also land on the floor. const int STEPS = 72; const float SIGMA = 0.45; const float WALL_Z = -1.0; const vec3 LIGHT_POS = vec3(1.2, 2.2, -7.0); bool slit(vec3 q) { return abs(fract(q.x * 0.7 + 0.5) - 0.5) < 0.08 && q.y < 2.6 && q.y > -1.0; } float vis(vec3 p) { vec3 d = LIGHT_POS - p; float t = (WALL_Z - p.z) / d.z; if (t < 0.0) return 1.0; return slit(p + d * t) ? 1.0 : 0.0; } float hg(float c, float g) { float g2 = g * g; return (1.0 - g2) / (12.566 * pow(1.0 + g2 - 2.0 * g * c, 1.5)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.8, 4.0), rd = normalize(vec3(uv.x, uv.y - 0.06, -1.2)); float tw = (WALL_Z - ro.z) / rd.z; float tf = rd.y < 0.0 ? (-1.0 - ro.y) / rd.y : 1e5; float tend = min(tw, tf); vec3 pe = ro + rd * tend; vec3 col = vec3(0.01, 0.012, 0.018); if (tend == tw && slit(pe)) col = vec3(1.0, 0.9, 0.7) * 3.0; if (tend == tf) col = vec3(0.03, 0.03, 0.035) + vec3(1.0, 0.9, 0.7) * 0.7 * vis(pe) * exp(-0.05 * tend); float dither = fract(sin(dot(fragCoord, vec2(12.9898, 78.233))) * 43758.5453); float ds = tend / float(STEPS); vec3 sc = vec3(0.0); for (int i = 0; i < STEPS; i++) { float t = (float(i) + dither) * ds; vec3 p = ro + rd * t; float v = vis(p); if (v < 0.5) continue; vec3 Ld = normalize(LIGHT_POS - p); sc += vec3(1.0, 0.92, 0.75) * v * SIGMA * ds * exp(-SIGMA * t) * hg(dot(Ld, rd), 0.55) * 22.0; } col = col * exp(-SIGMA * tend) + sc; col = 1.0 - exp(-col * 1.3); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Exponential Height Fog](https://texelatlas.vercel.app/t/exponential-height-fog.md): Fog makes the ground haze receive the shaft; the shaft pass adds directional brightness. ## Combination ideas - [Light shafts for any photo](https://texelatlas.vercel.app/ideas/photo-depth-god-rays/) ## Sources 1. [primary] Kenny Mitchell Volumetric Light Scattering as a Post-Process. GPU Gems 3, 2007. https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-13-volumetric-light-scattering-post-process (verified via http on 2026-11-29) ## Cite this entry Texel. "Screen-space Volumetric Light Scattering (God Rays)." https://texelatlas.vercel.app/t/volumetric-light-scattering-god-rays/ (accessed 2026-12-01). --- id: "voronoi-island-map-generation" title: "Polygon Map Generation (Voronoi Islands)" aliases: [mapgen2, Voronoi island generation] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, webgl2] year_introduced: 2010 inputs: [point-cloud] outputs: [graph, heightfield, layout] style: "stylized" dynamic: "static" cost: "cheap" authority: "Patel" url: "https://texelatlas.vercel.app/t/voronoi-island-map-generation/" sources_verified_at: "2026-11-29" --- # Polygon Map Generation (Voronoi Islands) (Patel) > Build fantasy-style island maps on a relaxed Voronoi graph: noise or radial shape sets land versus water, elevation grows from the coast, rivers follow downhill edges and moisture picks biomes. ## Reach for it when - generate fantasy world maps with islands - need game map with biomes and rivers - polygon based terrain for strategy games - noise maps look unnatural for coastlines ## How it works Place seed points (Poisson or relaxed random), compute the Voronoi/Delaunay graph, and treat each polygon as a map cell. A shape function (radial or noise-based) marks cells as land or water; ocean is flood-filled from the border so lakes remain distinct. Elevation increases with distance from the coast, rivers are traced down steepest edges and accumulate flow, moisture comes from distance to rivers and lakes, and a biome table maps elevation and moisture to colour. The graph is explicit, so cells carry data for gameplay, and the result can be turned into a heightmap or mesh. ## When to use it Choose it for game worlds, board-game maps and stylised overworld terrain where graph data (provinces, rivers) matters. Prefer [Fractal Brownian Motion and Multifractals](https://texelatlas.vercel.app/t/fractal-brownian-motion.md) or [Stream-Power Erosion (Fluvial Terrain Uplift)](https://texelatlas.vercel.app/t/stream-power-erosion.md) for realistic heightfields, [Terrain from Hydrology (River-First Terrain Synthesis)](https://texelatlas.vercel.app/t/hydrology-terrain-synthesis.md) when river structure should shape terrain, and [Procedural City Generation (L-system Road Networks)](https://texelatlas.vercel.app/t/procedural-city-roads.md) to lay out settlements. ## Cost cheap — Graph construction and a few linear passes; seconds even for large cell counts. Measured GPU Weight: 18.39× baseline (moderate) — 0.6051 ms median / 0.6312 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 18.39× baseline (moderate) — 0.2924 ms median (2.07× faster on L4). Ampere A100 scaling: 12.33× baseline (moderate) — 0.3552 ms median (1.7× faster on A100). ## Failure modes - Voronoi cell edges leave visibly polygonal coastlines unless smoothed or noise-perturbed - River courses are constrained to cell edges, producing zigzag rivers - Elevation from distance-to-coast gives uniform island-like shapes with little variety - Biome tables overfit to Earth-like climates, giving odd maps on non-island layouts ## Dataflow - Inputs: point-cloud - Outputs: graph, heightfield, layout - Platforms: cpu, webgl2 ## Presets ### Voronoi polygon island map with elevation-based biomes (glsl-fragment; rendered 2026-11-29) ```json { "CELLS": 12, "SEA_LEVEL": 0.32 } ``` ```glsl // Polygon island map: Voronoi cells from jittered sites get elevation (noise minus radial falloff) and biome by height. const float CELLS = 12.0; const float SEA_LEVEL = 0.32; vec2 hash2(vec2 p) { return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); } float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p), u = f * f * (3.0 - 2.0 * f); float a = hash2(i).x, b = hash2(i + vec2(1, 0)).x, c = hash2(i + vec2(0, 1)).x, d = hash2(i + 1.0).x; return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); } float elev(vec2 s) { float n = 0.55 * vnoise(s * 4.0) + 0.3 * vnoise(s * 9.0 + 3.0) + 0.15 * vnoise(s * 19.0 + 9.0); float r = length(s - 0.5) * 2.0; return n * 1.1 - r * r * 0.8 + 0.18; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec2 p = uv * CELLS, ip = floor(p); float d1 = 1e9, d2 = 1e9; vec2 best = vec2(0), second = vec2(0); for (int j = -2; j <= 2; j++) for (int i = -2; i <= 2; i++) { vec2 c = ip + vec2(i, j); vec2 s = c + 0.15 + 0.7 * hash2(c); float d = distance(p, s); if (d < d1) { d2 = d1; second = best; d1 = d; best = s; } else if (d < d2) { d2 = d; second = s; } } float e = elev(best / CELLS); vec3 col; if (e < SEA_LEVEL) col = mix(vec3(0.05, 0.12, 0.3), vec3(0.15, 0.35, 0.55), smoothstep(-0.3, SEA_LEVEL, e)); else if (e < SEA_LEVEL + 0.04) col = vec3(0.85, 0.78, 0.55); else if (e < 0.55) col = mix(vec3(0.3, 0.55, 0.25), vec3(0.15, 0.4, 0.2), (e - SEA_LEVEL) / 0.25); else if (e < 0.7) col = mix(vec3(0.45, 0.4, 0.33), vec3(0.6, 0.57, 0.52), (e - 0.55) / 0.15); else col = vec3(0.95); float edge = (d2 - d1); col *= 0.78 + 0.22 * smoothstep(0.0, 0.14, edge); float es = elev(second / CELLS); if ((e >= SEA_LEVEL) != (es >= SEA_LEVEL)) col = mix(col, vec3(0.1, 0.08, 0.05), smoothstep(0.1, 0.0, edge) * 0.8); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Voronoi Diagrams and Lloyd Relaxation](https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation.md) ## Sources 1. [primary] Amit Patel Mapgen2 Procedural Island Map Generator. redblobgames.com. https://www.redblobgames.com/maps/mapgen2 (verified via http on 2026-11-29) 2. [implementation] redblobgames (2017) redblobgames/mapgen2. https://github.com/redblobgames/mapgen2 License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "Polygon Map Generation (Voronoi Islands)." https://texelatlas.vercel.app/t/voronoi-island-map-generation/ (accessed 2026-12-01). --- id: "voronoi-lloyd-relaxation" title: "Voronoi Diagrams and Lloyd Relaxation" aliases: [centroidal Voronoi tessellation, CVT, Lloyd's algorithm] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, python, webgl2, houdini, blender, unity, unreal, godot] year_introduced: 1982 inputs: [point-cloud] outputs: [mesh, graph, layout] style: "both" dynamic: "static" cost: "cheap" authority: "Lloyd, 1982" url: "https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation/" sources_verified_at: "2026-11-29" --- # Voronoi Diagrams and Lloyd Relaxation (Lloyd, 1982) > Partition space by nearest seed (Voronoi), then repeatedly move each seed to the centroid of its cell. The cells become evenly sized and well-shaped, ideal for regions, provinces and tessellations. ## Reach for it when - voronoi cells are wildly uneven in size - need evenly shaped map regions or provinces - crack or fragment patterns look too irregular - relax random seeds into regular looking cells ## How it works Given seeds, the Voronoi diagram gives each seed the region of points closer to it than to any other; its dual is the Delaunay triangulation, computable in O(n log n) with Fortune's sweep or incremental Delaunay. Lloyd's iteration computes each cell's centroid (area-weighted, optionally with a density function) and moves the seed there, then recomputes the diagram. Each step reduces a quantisation energy and the process converges to a centroidal Voronoi tessellation (CVT) with hexagon-like cells in 2D. A few iterations (2 to 5) suffice for visually even cells without losing all randomness. Clipping the diagram to a boundary needs care at the border. ## When to use it Choose it for map regions, cracks and fragment shapes, cell-based terrain and mesh point distributions where regular but irregular-looking cells are wanted. Prefer [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md) when you only need points, [Worley (Cellular) Noise](https://texelatlas.vercel.app/t/worley-noise.md) for a per-pixel Voronoi texture with no explicit mesh, and [Wang Tiles (Aperiodic Tile Synthesis)](https://texelatlas.vercel.app/t/wang-tiles.md) for aperiodic tilings with stored tiles. ## Cost cheap — One diagram construction per iteration; n log n each. Measured GPU Weight: 702.95× baseline (extreme) — 23.1271 ms median / 23.4629 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 738.38× baseline (extreme) — 11.7402 ms median (1.97× faster on L4). Ampere A100 scaling: 503.2× baseline (extreme) — 14.4922 ms median (1.6× faster on A100). ## Failure modes - Too many iterations converge to a uniform hex grid that looks artificial; stop early - Cells at domain boundaries are unbounded or clipped asymmetrically, so seeds drift outward - Degenerate configurations (co-circular points) create zero-length edges and numerical instabilities - Density-weighted CVT needs numeric integration, which is slow and noisy for sharp density changes ## Dataflow - Inputs: point-cloud - Outputs: mesh, graph, layout - Platforms: cpu, python, webgl2, houdini, blender, unity, unreal, godot ## Presets ### Voronoi cells of random sites (left) vs one Lloyd relaxation step (right) (glsl-fragment; rendered 2026-11-29) ```json { "CELLS": 7, "SAMP": 6 } ``` ```glsl // Voronoi of jittered sites: left = raw random sites, right = after one Lloyd step (sites moved to their cell centroids, sampled). const float CELLS = 7.0; const int SAMP = 6; vec2 hash2(vec2 p) { return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); } vec2 site0(vec2 c) { return c + 0.08 + 0.84 * hash2(c); } vec2 relaxed(vec2 c) { vec2 s = site0(c), sum = vec2(0.0); float n = 0.0; for (int j = 0; j < SAMP; j++) for (int i = 0; i < SAMP; i++) { vec2 q = s + (vec2(float(i), float(j)) + 0.5) / float(SAMP) * 2.4 - 1.2; vec2 qc = floor(q); float bd = 1e9; vec2 bs = vec2(0); for (int b = -1; b <= 1; b++) for (int a = -1; a <= 1; a++) { vec2 sc = site0(qc + vec2(a, b)); float d = distance(q, sc); if (d < bd) { bd = d; bs = sc; } } if (distance(bs, s) < 1e-4) { sum += q; n += 1.0; } } return n > 0.0 ? sum / n : s; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; bool R = uv.x > 0.5; vec2 p = uv * CELLS, ip = floor(p); float d1 = 1e9, d2 = 1e9; vec2 best = vec2(0); vec2 bc = vec2(0); for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { vec2 c = ip + vec2(i, j); vec2 s = R ? relaxed(c) : site0(c); float d = distance(p, s); if (d < d1) { d2 = d1; d1 = d; best = s; bc = c; } else if (d < d2) d2 = d; } vec3 col = 0.45 + 0.4 * cos(6.2831 * (hash2(bc).x + vec3(0.0, 0.33, 0.67))); col *= 0.8 + 0.2 * smoothstep(0.0, 0.1, d2 - d1); col = mix(col, vec3(0.05), smoothstep(0.05, 0.0, d2 - d1) * 0.8); col = mix(col, vec3(0.05), smoothstep(0.1, 0.07, d1)); col = mix(col, vec3(1.0), smoothstep(0.004, 0.0, abs(uv.x - 0.5))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Lineage - extended by [Polygon Map Generation (Voronoi Islands)](https://texelatlas.vercel.app/t/voronoi-island-map-generation.md) ## Sources 1. [primary] S. Lloyd (1982) Least squares quantization in PCM. IEEE Transactions on Information Theory. https://doi.org/10.1109/tit.1982.1056489 (verified via crossref on 2026-11-29) 2. [primary] Qiang Du, Vance Faber, Max Gunzburger (1999) Centroidal Voronoi Tessellations: Applications and Algorithms. SIAM Review. https://doi.org/10.1137/s0036144599352836 (verified via crossref on 2026-11-29) 3. [implementation] d3 (2018) d3/d3-delaunay. https://github.com/d3/d3-delaunay License: ISC. (verified via github on 2026-11-29) ## Cite this entry Texel. "Voronoi Diagrams and Lloyd Relaxation." https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation/ (accessed 2026-12-01). --- id: "voxel-cone-tracing" title: "Voxel Cone Tracing" aliases: [VXGI, SVOGI, voxel GI] domain: "gi" stage: "lighting" realtime: "realtime" platforms: [desktop-gpu, webgl2, webgpu] year_introduced: 2011 inputs: [mesh, voxels, gbuffer] outputs: [radiance] style: "photoreal" dynamic: "dynamic" cost: "heavy" authority: "Crassin et al., 2011" url: "https://texelatlas.vercel.app/t/voxel-cone-tracing/" sources_verified_at: "2026-11-29" --- # Voxel Cone Tracing (Crassin et al., 2011) > Voxelizes the lit scene into a mip-mapped 3D texture and approximates diffuse and glossy indirect light by marching a handful of wide cones through the mip chain, instead of tracing many thin rays. ## Reach for it when - need dynamic gi and glossy reflections without ray tracing hardware - indirect lighting that updates as lights and objects move - bounce light for fully dynamic scenes on older gpus - few wide samples instead of many noisy rays - diffuse and specular indirect from a voxel scene ## How it works Each frame (or when geometry changes) the scene is **voxelized**: triangles are rasterized into a 3D grid, usually with conservative rasterization, storing albedo, normal and emissive. A light-injection pass computes direct lighting (with shadow maps) for each occupied voxel, giving outgoing radiance plus an anisotropic **opacity** per voxel. The grid is mip-mapped, with an **anisotropic** variant storing directional values in each of six faces so that averaging does not blur thin walls into translucent fog. At a shading point, a small set of cones (about five to nine) is traced over the hemisphere. A cone steps along its axis; at distance `d` the radius is `d * tan(half-angle)`, so the sample is taken from the mip level whose voxel size matches the footprint. Radiance is accumulated front-to-back using the sampled opacity, as in volume rendering. A narrow cone gives specular reflections; a wide cone gives soft occlusion for AO. A few wide cones replace the hundreds of rays of path tracing, trading exactness for stable, noise-free results. ## When to use it Choose it for fully dynamic GI and glossy reflections on GPUs without hardware ray tracing, in bounded scenes where a voxel volume around the camera is enough. Prefer [ddgi](ddgi) when you have ray tracing and want a clean grid of probes and fewer leaks. Prefer [lumen-gi](lumen-gi) for large production scenes with software and hardware ray tracing fallbacks. Prefer [light-propagation-volumes](light-propagation-volumes) for a cheaper, lower quality approximation. Prefer [lightmap-baking](lightmap-baking) when the scene is static and quality matters more than dynamism. ## Cost heavy — Voxelization and mip generation are the main fixed costs; cone tracing cost scales with the cone count. The original paper reports interactive frame rates on 2011 GPUs for its scenes. Measured GPU Weight: 119.27× baseline (extreme) — 3.9239 ms median / 4.0347 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 102.53× baseline (extreme) — 1.6302 ms median (2.41× faster on L4). Ampere A100 scaling: 69.24× baseline (extreme) — 1.9942 ms median (1.97× faster on A100). ## Failure modes - Light leaking and over-darkening through thin walls because voxels average geometry (partially mitigated by anisotropic voxels) - Aliasing and temporal flicker when the camera moves and the voxel grid snaps - Specular reflections are blurry and miss anything outside the voxelized volume - Voxelization cost and memory (hundreds of MB for large volumes) limit scene size, so clipmaps are needed ## Engine support - godot: builtin — `Add a VoxelGI node and bake it (VoxelGI.bake())` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/VoxelGI.xml, checked 2026-12-01) — Forward+ and Mobile. - threejs: official — `import { vxgi } from 'three/addons/lighting/vxgi/VXGINode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/lighting/vxgi/VXGINode.js, checked 2026-12-01) — WebGPURenderer with WebGPU backend only. ## Dataflow - Inputs: mesh, voxels, gbuffer - Outputs: radiance - Platforms: desktop-gpu, webgl2, webgpu ## Presets ### Voxel cone tracing — hierarchical mip-voxel indirect bounce & glossy cone aperture (glsl-fragment; rendered 2026-11-30) ```json { "P_CONE_APERTURE": 0.55, "P_GI_BOUNCE": 1.3, "P_VOXEL_RES": 12, "P_GLOSSINESS": 0.72 } ``` ```glsl const float P_CONE_APERTURE = 0.55; // P Cone Aperture [0.15, 1.1, 0.03] const float P_GI_BOUNCE = 1.3; // P Indirect GI [0.0, 2.5, 0.05] const float P_VOXEL_RES = 12.0; // P Voxel Grid [6.0, 24.0, 1.0] const float P_GLOSSINESS = 0.72; // P Glossy Spec [0.0, 1.4, 0.04] 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); } // Analytical scene SDF (Cornell room + glossy sphere + matte monolith) vec2 mapScene(vec3 p) { vec2 res = vec2(1.0 + p.y, 1.0); // floor float ceilD = 1.0 - p.y; if (ceilD < res.x) res = vec2(ceilD, 1.0); float backD = 1.4 + p.z; if (backD < res.x) res = vec2(backD, 1.0); float leftD = 1.4 + p.x; if (leftD < res.x) res = vec2(leftD, 2.0); // orange-red emitter wall float rightD = 1.4 - p.x; if (rightD < res.x) res = vec2(rightD, 3.0); // cobalt-cyan wall float dBox = sdBox(p - vec3(-0.48, -0.45, -0.45), vec3(0.35, 0.55, 0.35)); if (dBox < res.x) res = vec2(dBox, 4.0); vec3 sPos = vec3(0.45, -0.52 + 0.12 * sin(iTime * 0.9), -0.15); float dSph = length(p - sPos) - 0.38; if (dSph < res.x) res = vec2(dSph, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapScene(p + e.xyy).x - mapScene(p - e.xyy).x, mapScene(p + e.yxy).x - mapScene(p - e.yxy).x, mapScene(p + e.yyx).x - mapScene(p - e.yyx).x )); } // Sample quantized voxel radiance volume at mip level corresponding to cone diameter vec4 sampleVoxelMip(vec3 p, float coneDiameter, float voxRes, vec3 emPos) { float mipScale = max(voxRes / max(1.0, coneDiameter * voxRes * 0.65), 2.0); vec3 vp = (floor(p * mipScale) + 0.5) / mipScale; vec2 h = mapScene(vp); float voxelSize = 1.0 / mipScale; float occ = smoothstep(voxelSize * 0.85, -voxelSize * 0.25, h.x); vec3 rad = vec3(0.0); if (occ > 0.01) { if (h.y < 1.5) rad = vec3(0.42, 0.43, 0.46); else if (h.y < 2.5) rad = vec3(1.45, 0.32, 0.14); else if (h.y < 3.5) rad = vec3(0.14, 0.68, 1.35); else rad = vec3(0.72, 0.72, 0.74); // Modulate voxel radiance by proximity to moving glowing emitter bar float lDist = length(vp - emPos); rad *= (0.45 + 1.85 / (0.35 + lDist * lDist)); } // Glowing emissive voxel strip float dEm = length(vp - emPos) - 0.24; float emOcc = smoothstep(voxelSize * 0.9, -voxelSize * 0.2, dEm); if (emOcc > 0.01) { rad = mix(rad, vec3(3.2, 2.4, 1.4), emOcc); occ = max(occ, emOcc); } return vec4(rad, occ); } // Trace a single VCT cone with front-to-back alpha accumulation: c += (1 - a) * c_i; a += (1 - a) * a_i vec4 traceCone(vec3 ro, vec3 rd, float aperture, float voxRes, vec3 emPos) { vec3 accum = vec3(0.0); float alpha = 0.0; float t = 0.12; for (int i = 0; i < 8; i++) { float diam = max(0.08, 2.0 * t * aperture); vec4 vox = sampleVoxelMip(ro + rd * t, diam, voxRes, emPos); float a = clamp(vox.a * 0.72, 0.0, 1.0); accum += (1.0 - alpha) * vox.rgb * a; alpha += (1.0 - alpha) * a; if (alpha > 0.94 || t > 3.2) break; t += diam * 0.62; } return vec4(accum, alpha); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec3 ro = vec3(0.0, 0.04, 2.38); vec3 rd = normalize(vec3(uv, -1.35)); float voxRes = clamp(P_VOXEL_RES, 5.0, 28.0); float aperture = clamp(P_CONE_APERTURE, 0.12, 1.2); float giGain = max(P_GI_BOUNCE, 0.0); float gloss = max(P_GLOSSINESS, 0.0); vec3 emPos = vec3(0.55 * sin(iTime * 0.65), 0.72, -0.35 + 0.35 * cos(iTime * 0.65)); float t = 0.0; float matId = 1.0; bool hit = false; for (int i = 0; i < 64; i++) { vec2 h = mapScene(ro + rd * t); if (h.x < 0.002) { matId = h.y; hit = true; break; } t += h.x; if (t > 9.0) break; } vec3 col = vec3(0.02); if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); vec3 alb = vec3(0.76, 0.76, 0.78); if (matId > 1.5 && matId < 2.5) alb = vec3(0.88, 0.24, 0.12); else if (matId > 2.5 && matId < 3.5) alb = vec3(0.14, 0.54, 0.88); else if (matId > 4.5) alb = vec3(0.90, 0.92, 0.95); // Subtle voxel lattice visualization etched on room walls vec3 vg = abs(fract(p * voxRes * 0.5 - 0.5) - 0.5); float grid = smoothstep(0.055, 0.01, min(min(vg.x, vg.y), vg.z)); alb *= (1.0 - 0.12 * grid * step(matId, 3.5)); // Direct light from moving orb vec3 toL = emPos - p; float lDist = length(toL) + 1e-4; vec3 lDir = toL / lDist; float ndl = max(dot(n, lDir), 0.0); float sh = 1.0; float ts = 0.05; for (int s = 0; s < 16; s++) { float dh = mapScene(p + n * 0.02 + lDir * ts).x; sh = min(sh, clamp(5.0 * dh / ts, 0.0, 1.0)); ts += max(dh, 0.06); if (ts > lDist - 0.1) break; } vec3 direct = alb * vec3(2.4, 1.95, 1.45) * ndl * sh / (0.45 + lDist * lDist); // Diffuse VCT: 5 wide hemisphere cones (1 normal + 4 tilted) vec3 tanV = normalize(abs(n.y) < 0.9 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0))); vec3 bitV = cross(n, tanV); vec4 c0 = traceCone(p + n * 0.06, n, aperture, voxRes, emPos); vec4 c1 = traceCone(p + n * 0.06, normalize(n * 0.65 + tanV * 0.76), aperture, voxRes, emPos); vec4 c2 = traceCone(p + n * 0.06, normalize(n * 0.65 - tanV * 0.76), aperture, voxRes, emPos); vec4 c3 = traceCone(p + n * 0.06, normalize(n * 0.65 + bitV * 0.76), aperture, voxRes, emPos); vec4 c4 = traceCone(p + n * 0.06, normalize(n * 0.65 - bitV * 0.76), aperture, voxRes, emPos); vec3 diffGI = (c0.rgb * 0.28 + (c1.rgb + c2.rgb + c3.rgb + c4.rgb) * 0.18) * giGain; float voxAO = 1.0 - 0.55 * (c0.a * 0.28 + (c1.a + c2.a + c3.a + c4.a) * 0.18); // Glossy specular VCT cone along reflection vector (tighter aperture on sphere & floor) vec3 rDir = reflect(rd, n); float specAp = (matId > 4.5) ? max(0.09, aperture * 0.25) : max(0.22, aperture * 0.5); vec4 cSpec = traceCone(p + n * 0.06, rDir, specAp, voxRes, emPos); float fres = 0.06 + 0.94 * pow(1.0 - max(dot(n, -rd), 0.0), 5.0); float specAmt = (matId > 4.5) ? (0.45 + 0.55 * fres) : (0.18 * fres); col = direct + alb * (diffGI + vec3(0.04, 0.045, 0.055) * voxAO) + cSpec.rgb * specAmt * gloss; } // Visible glowing light orb in scene vec3 toEm = emPos - ro; float proj = dot(toEm, rd); if (proj > 0.0 && (!hit || proj < t)) { float dPerp = length(toEm - rd * proj); col += vec3(3.2, 2.3, 1.2) * exp(-dPerp * 14.0); col += vec3(4.0, 3.6, 2.8) * smoothstep(0.11, 0.05, dPerp); } fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Combines with - [Screen-Space Global Illumination](https://texelatlas.vercel.app/t/screen-space-gi.md): Screen-space gathers fill in the contact-scale detail that voxel resolution misses. ## Combination ideas - [Generated levels with free voxel GI](https://texelatlas.vercel.app/ideas/wfc-voxels-as-gi-volume/) ## Sources 1. [primary] Cyril Crassin, Fabrice Neyret, Miguel Sainz, Simon Green, Elmar Eisemann (2011) Interactive Indirect Illumination Using Voxel Cone Tracing. Computer Graphics Forum. https://doi.org/10.1111/j.1467-8659.2011.02063.x (verified via crossref on 2026-11-30) ## Cite this entry Texel. "Voxel Cone Tracing." https://texelatlas.vercel.app/t/voxel-cone-tracing/ (accessed 2026-12-01). --- id: "voxel-grid-dda-traversal" title: "Voxel grid DDA ray traversal (Amanatides–Woo)" aliases: [DDA grid traversal, 3D DDA, Amanatides-Woo] domain: "geometry" stage: "geometry" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, cuda] year_introduced: 1987 inputs: [voxels] outputs: [depth, normals] style: "both" dynamic: "dynamic" cost: "cheap" authority: "Amanatides & Woo" url: "https://texelatlas.vercel.app/t/voxel-grid-dda-traversal/" sources_verified_at: "2026-11-29" --- # Voxel grid DDA ray traversal (Amanatides–Woo) (Amanatides & Woo) > Walks a ray through a regular grid one cell at a time in strict order using two vectors, the distance to the next boundary on each axis and the distance between boundaries, so no cell is missed or visited twice. ## Reach for it when - ray marching through voxel grid skips cells at corners - need to pick a block with the mouse in a voxel world - fast line of sight test through a grid - cast rays against a voxel chunk in a shader ## How it works Convert the ray origin to its starting cell and find, for each axis, the step direction (±1) and `tMax`, the ray parameter at which it crosses the first cell boundary on that axis. Also compute `tDelta`, the ray parameter needed to cross one whole cell on each axis. Each iteration tests the current cell, then advances along the axis with the smallest `tMax`: bump that component of the cell index by its step and add its `tDelta` to `tMax`. The axis you just stepped across gives the face normal, and the smaller `tMax` before stepping gives the hit distance. Everything is integer indexing plus min comparisons, making it ideal for shaders. It also works for voxel picking, line-of-sight, light propagation and traversing hierarchical grids (octrees) if you step at the right level. ## When to use it Choose it for ray casting through dense or sparse voxel grids, volume marching with an occupancy test, and block picking. Prefer [Sphere Tracing](https://texelatlas.vercel.app/t/sphere-tracing.md) when the data is a distance field and you can skip empty space in big jumps, [Greedy meshing for voxel worlds](https://texelatlas.vercel.app/t/greedy-voxel-meshing.md) when you want a rasterised mesh instead, [Ray-marched Participating Media](https://texelatlas.vercel.app/t/volume-ray-marching.md) for density integration, and [three-mesh-bvh](https://texelatlas.vercel.app/t/three-mesh-bvh.md) when the primitives are triangles. ## Cost cheap — A few ALU ops per cell; total cost scales with the number of cells traversed, so large empty spaces need a hierarchy or distance-field skipping. Measured GPU Weight: 18.83× baseline (moderate) — 0.6194 ms median / 0.6541 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 16.63× baseline (moderate) — 0.2644 ms median (2.34× faster on L4). Ampere A100 scaling: 13.73× baseline (moderate) — 0.3954 ms median (1.57× faster on A100). ## Failure modes - Division by zero or NaN tMax when a ray direction component is exactly 0, unless guarded by a small epsilon or an infinity convention - Rays that start exactly on a cell boundary or at the grid edge can pick the wrong first cell - Long empty stretches cost one step per cell, so large sparse worlds stall without a two-level grid or octree - Floating-point drift over very long rays can skip a cell at corners; rebase the origin per chunk ## Dataflow - Inputs: voxels - Outputs: depth, normals - Platforms: cpu, webgl2, webgpu, desktop-gpu, cuda ## Presets ### DDA traversal of a procedural voxel heightfield (glsl-fragment; rendered 2026-11-29) ```json { "max_steps": 96, "half_extent": 9 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Amanatides-Woo voxel traversal through a procedural heightfield grid. const int MAX_STEPS = 96; const float HALF = 9.0; bool solid(ivec3 c) { if (abs(float(c.x)) > HALF || abs(float(c.z)) > HALF || c.y < 0) return false; float x = float(c.x), z = float(c.z); float h = 2.0 + 1.5 * sin(x * 0.55) * cos(z * 0.45) + 0.08 * (x * x + z * z) * 0.25; return float(c.y) < h; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float a = 0.3 * iTime; vec3 ro = vec3(14.0 * sin(a), 9.0, 14.0 * cos(a)); vec3 fw = normalize(vec3(0.0, 1.5, 0.0) - ro); vec3 rt = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(rt, fw); vec3 rd = normalize(fw * 1.4 + rt * p.x + up * p.y); rd += vec3(1e-5); // avoid exact zeros in 1/rd ivec3 cell = ivec3(floor(ro)); vec3 stp = sign(rd); vec3 tDelta = abs(1.0 / rd); vec3 tMax = (vec3(cell) + step(0.0, rd) - ro) / rd; vec3 mask = vec3(0.0); bool hit = false; for (int i = 0; i < MAX_STEPS; i++) { if (solid(cell)) { hit = true; break; } mask = vec3(lessThanEqual(tMax.xyz, min(tMax.yzx, tMax.zxy))); tMax += mask * tDelta; cell += ivec3(mask * stp); } vec3 col = mix(vec3(0.55, 0.7, 0.9), vec3(0.15, 0.2, 0.35), clamp(p.y + 0.6, 0.0, 1.0)); if (hit) { vec3 n = -mask * stp; float hgt = float(cell.y) / 5.0; vec3 base = mix(vec3(0.25, 0.5, 0.2), vec3(0.75, 0.7, 0.6), hgt); float lit = 0.35 + 0.65 * max(dot(n, normalize(vec3(0.4, 0.9, 0.3))), 0.0); float chk = mod(float(cell.x + cell.y + cell.z), 2.0); col = base * lit * (0.88 + 0.12 * chk); } fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [NanoVDB](https://texelatlas.vercel.app/t/nanovdb.md): A hierarchical DDA over NanoVDB's tree skips empty space while using the same cell-stepping logic. ## Combination ideas - [Overhang-capable voxel erosion with pipe-model water](https://texelatlas.vercel.app/ideas/margolus-voxel-erosion-pipe-water/) ## Sources 1. [primary] John Amanatides, Andrew Woo A Fast Voxel Traversal Algorithm for Ray Tracing. cse.yorku.ca. http://www.cse.yorku.ca/~amana/research/grid.pdf (verified via http on 2026-11-29) ## Cite this entry Texel. "Voxel grid DDA ray traversal (Amanatides–Woo)." https://texelatlas.vercel.app/t/voxel-grid-dda-traversal/ (accessed 2026-12-01). --- id: "wang-tiles" title: "Wang Tiles (Aperiodic Tile Synthesis)" aliases: [stochastic tiling with Wang tiles] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [cpu, webgl2, webgpu, desktop-gpu, unity, unreal, godot] year_introduced: 2003 inputs: [texture] outputs: [texture, layout] style: "both" dynamic: "static" cost: "cheap" authority: "Cohen et al., 2003" url: "https://texelatlas.vercel.app/t/wang-tiles/" sources_verified_at: "2026-11-29" --- # Wang Tiles (Aperiodic Tile Synthesis) (Cohen et al., 2003) > A small set of square tiles with coloured edges is assembled so adjacent edge colours match, producing non-repeating textures or distributions from a compact atlas that can be looked up per pixel. ## Reach for it when - texture tiling visibly repeats across large surfaces - non-periodic patterns from a small set of tiles - tile floors and terrain without obvious seams - cheap infinite texture without repetition ## How it works Each tile carries a colour on each edge, and a tile set with all edge-colour combinations (for two colours per axis, 16 tiles; a reduced 8-tile set suffices for a scanline order) can tile the plane so every neighbouring pair of edges agrees. Tiles are generated from source patches so content crossing a shared edge colour is identical: for textures, patches are quilted together; for point sets, a stored Poisson disk set per tile makes a precomputed blue-noise distribution. At runtime a pseudo-random choice (or a hash of cell coordinates) picks, for each cell, a tile consistent with its left and top neighbours. This gives non-periodic coverage with a small atlas and constant-time per-pixel evaluation. ## When to use it Choose it for large non-repeating ground textures, blue-noise scattering on the fly (e.g. foliage on a huge terrain) and sampling patterns. Prefer [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md) for one-time point generation, [Wave Function Collapse](https://texelatlas.vercel.app/t/wave-function-collapse.md) for richer adjacency rules and level layouts, and [Worley (Cellular) Noise](https://texelatlas.vercel.app/t/worley-noise.md) for a procedural cell pattern with no stored tiles. ## Cost cheap — One hash and an atlas lookup per cell; the cost is in precomputing tile content. Measured GPU Weight: 2.45× baseline (light) — 0.0805 ms median / 0.0832 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.94× baseline (feather) — 0.0308 ms median (2.61× faster on L4). Ampere A100 scaling: 1.57× baseline (feather) — 0.0452 ms median (1.78× faster on A100). ## Failure modes - Seams visible if edge colours are matched but the interior features differ in structure - Few tile colours show repetition: the same motif recurs along rows or columns - Tile-based blue noise has visible tile boundaries in the power spectrum - Tile content must be authored per texture; oriented or anisotropic textures need extra care ## Dataflow - Inputs: texture - Outputs: texture, layout - Platforms: cpu, webgl2, webgpu, desktop-gpu, unity, unreal, godot ## Presets ### Two-colour Wang tiles with automatically matching edges forming paths (glsl-fragment; rendered 2026-11-29) ```json { "TILES": 6 } ``` ```glsl // Wang tiles with 2 edge colours: each tile's edge colours come from a hash of the shared edge, so matching is automatic. const float TILES = 6.0; float eh(vec2 e, float k) { return step(0.5, fract(sin(dot(e, vec2(12.9898, 78.233)) + k * 31.7) * 43758.5453)); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy * TILES; vec2 id = floor(uv), f = fract(uv) - 0.5; float N = eh(id + vec2(0, 1), 1.0), S = eh(id, 1.0), E = eh(id + vec2(1, 0), 2.0), W = eh(id, 2.0); // quadrant triangles tinted by the edge colour on that side float side; if (abs(f.x) > abs(f.y)) side = f.x > 0.0 ? E : W; else side = f.y > 0.0 ? N : S; vec3 c0 = vec3(0.16, 0.2, 0.35), c1 = vec3(0.95, 0.6, 0.25); vec3 col = mix(c0, c1, side) * (0.7 + 0.3 * (1.0 - 2.0 * max(abs(f.x), abs(f.y)))); // coloured edges continue as paths through the tile centre, so matching edges form continuous lines float d = 1e9; if (N > 0.5) d = min(d, abs(f.x) + step(f.y, 0.0) * 9.0); if (S > 0.5) d = min(d, abs(f.x) + step(0.0, f.y) * 9.0); if (E > 0.5) d = min(d, abs(f.y) + step(f.x, 0.0) * 9.0); if (W > 0.5) d = min(d, abs(f.y) + step(0.0, f.x) * 9.0); col = mix(col, vec3(0.97, 0.93, 0.8), smoothstep(0.07, 0.055, d)); vec2 g = abs(f); col = mix(col, vec3(0.03), smoothstep(0.012, 0.0, 0.5 - max(g.x, g.y))); fragColor = vec4(pow(col, vec3(0.8)), 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Michael F. Cohen, Jonathan Shade, Stefan Hiller, Oliver Deussen (2003) Wang Tiles for image and texture generation. ACM Transactions on Graphics. https://doi.org/10.1145/882262.882265 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Wang Tiles (Aperiodic Tile Synthesis)." https://texelatlas.vercel.app/t/wang-tiles/ (accessed 2026-12-01). --- id: "water-caustics-realtime" title: "Real-time Water Caustics" aliases: [image-space caustics, caustic mapping] domain: "volumes" stage: "volume" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu] year_introduced: 2006 inputs: [normals, heightfield, depth] outputs: [texture, irradiance-probes] style: "both" dynamic: "dynamic" cost: "medium" authority: "Wyman & Davis, 2006" url: "https://texelatlas.vercel.app/t/water-caustics-realtime/" sources_verified_at: "2026-11-29" --- # Real-time Water Caustics (Wyman & Davis, 2006) > Approximate the bright, moving light patterns on a pool floor by refracting light through the water surface and splatting where each ray lands, or by scattering and tracing a cheap procedural pattern. ## Reach for it when - pool floor lacks dancing light patterns - underwater scenes need moving bright ripples - need cheap plausible caustics for water - light through waves should focus on seabed ## How it works Render the water surface from the light's point of view as a normal map and refract the light direction at each texel (Snell's law). Each refracted ray is intersected with the receiving geometry, either by marching a depth/height texture of the floor, or analytically for a flat floor. Rays are splatted as small additive quads or points into a caustic texture; where rays converge the sum gets brighter, and the texture is then projected onto the scene. A cheaper version, popular in WebGL demos, compares the area of each refracted cell before and after refraction using screen-space derivatives of the refracted position, which gives intensity as the ratio of areas and avoids splatting. Temporal blur and a small blur kernel suppress noise. The caustic texture is multiplied into the lighting of floors, hulls and shadowed regions. ## When to use it Choose it for pools, shallow seas and fountains when you can trade accuracy for a plausible, animated light pattern at low cost. Prefer procedural approximations in the material (e.g. layered Voronoi noise) when the surface is not simulated and only the visual matters. Prefer path tracing with photon mapping offline for exact results. Use alongside [FFT Ocean (Tessendorf)](https://texelatlas.vercel.app/t/fft-ocean.md), [Gerstner (Trochoidal) Waves](https://texelatlas.vercel.app/t/gerstner-waves.md) or [Shallow Water Equations (Height-field Water)](https://texelatlas.vercel.app/t/shallow-water-equations.md) as the source of surface normals. ## Cost medium — Splatting costs rise with surface resolution and overdraw; derivative-based methods are cheap. Measured GPU Weight: 9.32× baseline (moderate) — 0.3065 ms median / 0.3274 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 7.96× baseline (moderate) — 0.1266 ms median (2.42× faster on L4). Ampere A100 scaling: 5.26× baseline (light) — 0.1516 ms median (2.02× faster on A100). ## Failure modes - Noisy, speckled caustics when splat density is too low - Missing caustics shadowing: objects in the water do not occlude the caustic light unless added - Wrong pattern focus depth if the floor distance used is a constant and the real floor is deep or sloped - Flicker as the surface moves because caustic intensity is computed per frame without temporal filtering - Only the first refraction is handled: reflective caustics and caustics from submerged objects are missing ## Engine support - threejs: official — `examples/webgpu_caustics.html` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/webgpu_caustics.html, checked 2026-12-01) — Official example, not a setting. - unity: builtin — `Water Surface > Caustics` (evidence: https://github.com/Unity-Technologies/Graphics/blob/557f6ac22b948284f57ffae6a789751fd1f63620/Packages/com.unity.render-pipelines.high-definition/Documentation~/water-caustics-in-the-water-system.md, checked 2026-12-01) — HDRP only. ## Dataflow - Inputs: normals, heightfield, depth - Outputs: texture, irradiance-probes - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu ## Presets ### Analytic refraction caustics on a pool floor from an animated wave field (glsl-fragment; rendered 2026-11-29) ```json { "DEPTH": 2, "AMP": 0.05 } ``` ```glsl // Analytic water caustics on a pool floor. Rays refract through an animated wave height field // (Snell, eta=1/1.33); the floor point P is mapped back to its surface source by fixed-point iteration, and // intensity = 1 / |det(d landing / d surface)|: focusing where neighbouring rays converge. const float DEPTH = 2.0; const float AMP = 0.05; vec2 slope(vec2 p) { vec2 g = vec2(0.0); g += AMP * 6.0 * cos(dot(vec2(0.8, 0.6), p) * 6.0 + iTime * 1.3) * vec2(0.8, 0.6); g += AMP * 8.0 * cos(dot(vec2(-0.5, 0.86), p) * 8.0 - iTime * 1.7) * vec2(-0.5, 0.86); g += AMP * 11.0 * cos(dot(vec2(0.2, -0.98), p) * 11.0 + iTime * 2.1) * vec2(0.2, -0.98); g += AMP * 14.0 * 0.6 * cos(dot(vec2(-0.9, -0.43), p) * 14.0 - iTime * 2.6) * vec2(-0.9, -0.43); return g; } vec2 land(vec2 p) { vec2 g = slope(p); vec3 d = refract(vec3(0.0, -1.0, 0.0), normalize(vec3(-g.x, 1.0, -g.y)), 1.0 / 1.33); return p + d.xz / (-d.y) * DEPTH; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 P = uv * 3.0; vec2 x = P; for (int i = 0; i < 4; i++) x = P - (land(x) - x); float e = 0.004; vec2 fx = (land(x + vec2(e, 0.0)) - land(x - vec2(e, 0.0))) / (2.0 * e); vec2 fy = (land(x + vec2(0.0, e)) - land(x - vec2(0.0, e))) / (2.0 * e); float I = clamp(1.0 / max(abs(fx.x * fy.y - fx.y * fy.x), 0.12), 0.0, 6.0); vec2 tile = fract(P * 0.8); vec3 floorc = mix(vec3(0.08, 0.3, 0.38), vec3(0.1, 0.38, 0.45), step(0.5, fract(floor(P.x * 0.8) * 0.5 + floor(P.y * 0.8) * 0.5) * 2.0)); if (min(tile.x, tile.y) < 0.03) floorc *= 0.6; vec3 col = floorc * (0.25 + 0.55 * I) + vec3(0.6, 0.95, 1.0) * pow(I / 6.0, 2.0) * 1.5; col = col / (1.0 + 0.5 * col); fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0); } ``` Attribution: written for this index ## Combines with - [Shallow Water Equations (Height-field Water)](https://texelatlas.vercel.app/t/shallow-water-equations.md): Height field normals feed the caustic refraction pass in an interactive pool. ## Combination ideas - [Bathymetry-refracted coastal ocean with shore caustics](https://texelatlas.vercel.app/ideas/eikonal-refracted-fft-shore-caustics/) - [Meshlet kelp forests through underwater PSF scattering](https://texelatlas.vercel.app/ideas/meshlet-kelp-small-angle-underwater-psf/) ## Sources 1. [primary] Chris Wyman, Scott Davis (2006) Interactive image-space techniques for approximating caustics. Proceedings of the 2006 symposium on Interactive 3D graphics and games - SI3D '06. https://doi.org/10.1145/1111411.1111439 (verified via crossref on 2026-11-29) 2. [primary] Musawir A. Shah, Jaakko Konttinen, Sumanta Pattanaik (2007) Caustics Mapping: An Image-Space Technique for Real-Time Caustics. IEEE Transactions on Visualization and Computer Graphics. https://doi.org/10.1109/tvcg.2007.32 (verified via crossref on 2026-11-29) 3. [implementation] evanw (2015) evanw/webgl-water. https://github.com/evanw/webgl-water (verified via github on 2026-11-29) 4. [implementation] Gökay Aydoğan (2026) gokayfem/glsl-studies. https://github.com/gokayfem/glsl-studies License: MIT. (verified via github on 2026-11-30) ## Cite this entry Texel. "Real-time Water Caustics." https://texelatlas.vercel.app/t/water-caustics-realtime/ (accessed 2026-12-01). --- id: "watercolor-bousseau-realtime" title: "Interactive watercolor rendering with temporal coherence" domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu] year_introduced: 2006 inputs: [ldr-image, depth, normals] outputs: [ldr-image] style: "stylized" dynamic: "dynamic" cost: "medium" authority: "Bousseau et al., 2006" url: "https://texelatlas.vercel.app/t/watercolor-bousseau-realtime/" sources_verified_at: "2026-11-29" --- # Interactive watercolor rendering with temporal coherence (Bousseau et al., 2006) > A real-time pipeline that turns rendered 3D animation into watercolour imagery (abstraction, edge darkening, pigment variation, paper) while limiting flicker and swimming. ## Reach for it when - want a watercolour look on animated 3d scenes - paint effect flickers or swims across frames - pigment, paper and edge darkening in real time - per-object control of abstraction in stylised render - watercolour stylisation for interactive 3d ## How it works The method stacks several post-processing steps on a rendered frame: colour simplification via smoothing of the rendered image, a pigment-dispersion effect through procedural noise perturbation, edge darkening where gradient magnitude is large, and a paper texture layered via a multiply. The key concern is temporal coherence: effects like pigment noise and paper must not swim or flicker as the camera or objects move, so they are handled with scene-aware coherence rather than being re-generated each frame. Abstraction and pigment parameters are controlled per object with masks, which lets artists pick which parts remain detailed. ## When to use it Choose it for a watercolour look on animated 3D scenes with controllable abstraction per object. Prefer [Computer-generated watercolor (fluid simulation)](https://texelatlas.vercel.app/t/watercolor-rendering-curtis.md) for physically simulated paint on 2D canvases, and [Kuwahara filter](https://texelatlas.vercel.app/t/kuwahara-filter.md) or [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) for a cheap generic painterly look with no paper-texture coherence. ## Cost medium — Several full-screen passes; interactive to real-time on a modern GPU. Measured GPU Weight: 87.2× baseline (extreme) — 2.8689 ms median / 3.0414 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 78.35× baseline (extreme) — 1.2457 ms median (2.3× faster on L4). Ampere A100 scaling: 57.09× baseline (heavy) — 1.6443 ms median (1.74× faster on A100). ## Failure modes - Image-space smoothing blurs fine details such as faces - Coherence can fail at occlusions and fast motion - Paper texture can show a shower-door effect if it is tied only to the screen - Edge darkening halos on noisy renders ## Dataflow - Inputs: ldr-image, depth, normals - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu ## Presets ### Interactive Watercolor (Bousseau et al.) — dry 3D shaded render (left) vs abstraction, capillary edge darkening, granulation & paper grain (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_EDGE_DARK": 0.8, "P_GRANULATION": 0.65, "P_PAPER_GRAIN": 0.7, "P_SPLIT": 0.44 } ``` ```glsl const float P_EDGE_DARK = 0.80; // P Capillary Edge Dark [0.0, 1.3, 0.05] const float P_GRANULATION = 0.65; // P Pigment Granulation [0.0, 1.2, 0.05] const float P_PAPER_GRAIN = 0.70; // P Cold-Press Paper [0.0, 1.0, 0.05] const float P_SPLIT = 0.44; // P Dry 3D / Watercolor [0.0, 1.0, 0.02] float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y ); } float fbm(vec2 p) { float a = 0.5; float s = 0.0; for (int i = 0; i < 4; i++) { s += a * vnoise(p); p = p * 2.03 + vec2(13.7, 29.1); a *= 0.5; } return s; } 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); } // Sunlit Mediterranean stone archway, cypress spheres & reflective canal (classic Bousseau watercolor subject) vec2 mapBridge(vec3 p) { float dWater = p.y + 0.52; vec2 res = vec2(dWater, 1.0); // Stone bridge arch spanning across canal float dWall = sdBox(p - vec3(0.0, -0.10, -0.35), vec3(1.15, 0.44, 0.26)); float dArchHole = length(vec2(p.x, p.y + 0.48)) - 0.42; float dBridge = max(dWall, -dArchHole); if (dBridge < res.x) res = vec2(dBridge, 2.0); // Terracotta villa dome behind bridge float dDome = length(p - vec3(0.46, 0.24, -0.78)) - 0.34; if (dDome < res.x) res = vec2(dDome, 3.0); // Sunlit foliage spheres on left bank float dTree1 = length(p - vec3(-0.62, 0.22, -0.58)) - 0.32; float dTree2 = length(p - vec3(-0.34, 0.16, -0.70)) - 0.24; float dTree = min(dTree1, dTree2); if (dTree < res.x) res = vec2(dTree, 4.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapBridge(p + e.xyy).x - mapBridge(p - e.xyy).x, mapBridge(p + e.yxy).x - mapBridge(p - e.yxy).x, mapBridge(p + e.yyx).x - mapBridge(p - e.yyx).x )); } // Render dry scene color + object-space anchor coordinates (prevents shower-door swimming during camera motion!) void evalDryScene(vec2 uv, float t, out vec3 col, out float dep, out vec2 objAnchor) { vec3 ro = vec3(0.22 * sin(t * 0.42), 0.14, 2.15); vec3 rd = normalize(vec3(uv.x, uv.y - 0.04, -1.48)); vec3 sunDir = normalize(vec3(0.62, 0.72, 0.46)); col = mix(vec3(0.95, 0.89, 0.78), vec3(0.44, 0.68, 0.90), smoothstep(-0.08, 0.52, rd.y)); dep = 10.0; objAnchor = uv * 4.5 + vec2(0.22 * sin(t * 0.42) * 0.5, 0.0); float dist = 0.05; vec2 hit = vec2(10.0, 0.0); for (int i = 0; i < 60; i++) { vec2 h = mapBridge(ro + rd * dist); if (h.x < 0.0025) { hit = vec2(dist, h.y); break; } dist += h.x; if (dist > 8.5) break; } if (hit.y > 0.5) { dep = hit.x; vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); objAnchor = (hit.y < 1.5) ? (p.xz * 2.4) : (p.xy * 2.8 + p.z * 0.9); float ndl = max(dot(n, sunDir), 0.0); if (hit.y < 1.5) { // Shimmering turquoise canal water vec3 wAlb = mix(vec3(0.20, 0.54, 0.68), vec3(0.54, 0.78, 0.84), 0.5 + 0.5 * sin(p.z * 7.0 + p.x * 3.0)); float archSh = smoothstep(0.18, 0.55, abs(p.z + 0.35)); col = wAlb * (0.45 + 0.55 * archSh); } else if (hit.y < 2.5) { // Warm sandstone bridge vec3 sAlb = vec3(0.88, 0.78, 0.62); col = sAlb * (0.32 + 0.82 * ndl) + vec3(0.18, 0.28, 0.44) * (1.0 - ndl) * 0.30; } else if (hit.y < 3.5) { // Terracotta roof dome col = vec3(0.90, 0.44, 0.28) * (0.30 + 0.85 * ndl) + vec3(0.20, 0.24, 0.42) * (1.0 - ndl) * 0.26; } else { // Olive-emerald foliage col = vec3(0.26, 0.62, 0.36) * (0.30 + 0.85 * ndl) + vec3(0.14, 0.28, 0.38) * (1.0 - ndl) * 0.25; } } } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float edgeDark = clamp(P_EDGE_DARK, 0.0, 1.4); float granAmt = clamp(P_GRANULATION, 0.0, 1.4); float paperAmt = clamp(P_PAPER_GRAIN, 0.0, 1.0); vec3 dryCol; float cDep; vec2 objAnchor; evalDryScene(uv, iTime, dryCol, cDep, objAnchor); vec3 col = dryCol; if (screenX >= split) { // Right: Bousseau real-time watercolor pipeline (wobble -> abstraction -> pigment granulation -> edge darkening -> paper!) // 1. Object-anchored pigment wobble (temporally coherent as camera glides!) vec2 wob = (vec2(fbm(objAnchor * 1.4), fbm(objAnchor * 1.4 + vec2(7.3, 19.1))) - 0.5) * 0.016 * granAmt; vec2 wUv = uv + wob; // 2. Color simplification / wet-on-wet 5-tap abstraction smoothing vec3 c0, cL, cR, cD, cU; float d0, dL, dR, dD, dU; vec2 a0, aTmp; float eps = 0.008; evalDryScene(wUv, iTime, c0, d0, a0); evalDryScene(wUv + vec2(-eps, 0.0), iTime, cL, dL, aTmp); evalDryScene(wUv + vec2(eps, 0.0), iTime, cR, dR, aTmp); evalDryScene(wUv + vec2(0.0, -eps), iTime, cD, dD, aTmp); evalDryScene(wUv + vec2(0.0, eps), iTime, cU, dU, aTmp); vec3 wash = (c0 * 2.0 + cL + cR + cD + cU) / 6.0; // Slight vibrant watercolor glaze lift (translucent bright paper showing through pigment) wash = mix(wash, pow(clamp(wash, 0.0, 1.0), vec3(0.88)), 0.35); // 3. Pigment dispersion / granulation using temporally coherent object-space fBM float gran = fbm(a0 * 2.6 + vec2(3.1, 8.7)); float granMod = 1.0 + (gran - 0.5) * 0.42 * granAmt; // Kubelka-Munk-like pigment concentration power curve (pigment pools saturate & darken!) vec3 pigmented = pow(clamp(wash, 0.02, 1.0), vec3(granMod)); // 4. Capillary edge darkening (wet pigment migrates to stroke boundaries where color/depth gradient spikes!) float gradCol = length(cR - cL) + length(cU - cD); float gradDep = (abs(dR - dL) + abs(dU - dD)) * 0.14; float edgeMask = smoothstep(0.06, 0.34, gradCol + gradDep); // Darken & slightly saturate boundary edges like dried watercolor backruns vec3 edgePigment = pow(clamp(pigmented, 0.02, 1.0), vec3(1.0 + 1.35 * edgeDark * edgeMask)); edgePigment *= (1.0 - 0.28 * edgeDark * edgeMask); // 5. Cold-press cotton watercolor paper texture (multiplied in screen space) float paperFine = fbm(fragCoord * 0.16); float paperCoarse = fbm(fragCoord * 0.045 + vec2(17.1, 4.3)); float paperH = mix(paperCoarse, paperFine, 0.55); vec3 paperTint = vec3(0.99, 0.97, 0.93) * (0.88 + 0.18 * paperH); // Granulation settles extra pigment into paper valleys col = edgePigment * mix(vec3(1.0), paperTint, paperAmt); col = mix(col, col * (0.86 + 0.24 * paperH), paperAmt * 0.55); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.22, 0.24, 0.30), sep); fragColor = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Computer-generated watercolor (fluid simulation)](https://texelatlas.vercel.app/t/watercolor-rendering-curtis.md) ## Combines with - [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md): Kuwahara abstraction provides the colour flattening before paper and edge-darkening layers. ## Sources 1. [primary] Adrien Bousseau, Matt Kaplan, Joëlle Thollot, François X. Sillion (2006) Interactive watercolor rendering with temporal coherence and abstraction. Proceedings of the 4th international symposium on Non-photorealistic animation and rendering. https://doi.org/10.1145/1124728.1124751 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Interactive watercolor rendering with temporal coherence." https://texelatlas.vercel.app/t/watercolor-bousseau-realtime/ (accessed 2026-12-01). --- id: "watercolor-rendering-curtis" title: "Computer-generated watercolor (fluid simulation)" domain: "npr" stage: "material" realtime: "offline" platforms: [cpu, python] year_introduced: 1997 inputs: [ldr-image, texture] outputs: [ldr-image] style: "stylized" dynamic: "static" cost: "offline" authority: "Curtis et al., 1997" url: "https://texelatlas.vercel.app/t/watercolor-rendering-curtis/" sources_verified_at: "2026-11-29" --- # Computer-generated watercolor (fluid simulation) (Curtis et al., 1997) > Simulates pigment advection and deposition in a shallow water layer over paper, a physical model that reproduces wet-in-wet blooms, edge darkening and granulation. ## Reach for it when - make rendering look like a watercolor painting - pigment bleeding and paper texture effects - stylize images with layered translucent washes - physically inspired artistic paint simulation ## How it works The model treats a painting as layers of glazes. For each layer, a shallow fluid simulation moves water over a paper height field, while pigment is carried by the water velocity, deposited onto the paper and lifted back off depending on pigment properties. Capillary action spreads water into dry paper and creates feathery backruns. Paper texture affects flow and granulation, and edge darkening arises because pigment accumulates at the boundary of wet regions. Pigments have per-colour optical properties combined with a Kubelka-Munk style composition between layers. Because it is a simulation, it handles strokes drawn interactively and automatic conversion of photographs. ## When to use it Choose it when physical plausibility of paint behaviour matters and runtime is acceptable offline or in an interactive paint tool. Prefer [Interactive watercolor rendering with temporal coherence](https://texelatlas.vercel.app/t/watercolor-bousseau-realtime.md) for filtering 3D renders at real-time rates, and [Anisotropic Kuwahara filter](https://texelatlas.vercel.app/t/anisotropic-kuwahara.md) for a cheap generic painterly look. ## Cost offline — Iterative fluid simulation per layer; offline or interactive on small canvases. Measured GPU Weight: 56.33× baseline (heavy) — 1.8534 ms median / 2.1882 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 49.17× baseline (heavy) — 0.7818 ms median (2.37× faster on L4). Ampere A100 scaling: 37.74× baseline (heavy) — 1.087 ms median (1.71× faster on A100). ## Failure modes - Needs many tuned parameters per pigment and paper type - Simulation state is hard to keep coherent in animation - Compositing many glazes is slow - Reproduces 2D paintings, not 3D scenes, without extra work ## Dataflow - Inputs: ldr-image, texture - Outputs: ldr-image - Platforms: cpu, python ## Presets ### Curtis watercolor pigment model — wet-edge darkening, paper valley granulation and glazing (glsl-fragment; rendered 2026-11-30) ```json { "EDGE_DARKEN": 0.78, "GRANULATION": 0.58, "PAPER_GRAIN": 0.48, "WET_BLEED": 0.34 } ``` ```glsl const float EDGE_DARKEN = 0.78; // P const float GRANULATION = 0.58; // P const float PAPER_GRAIN = 0.48; // P const float WET_BLEED = 0.34; // P float hash(vec2 p) { vec3 q = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); } float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y ); } float fbm(vec2 p) { float v = 0.0, a = 0.5; mat2 m = mat2(0.8, 0.6, -0.6, 0.8); for (int i = 0; i < 4; i++) { v += a * vnoise(p); p = m * p * 2.03; a *= 0.5; } return v; } // Cold-press cotton paper heightfield (valleys trap heavier pigment particles) float paperHeight(vec2 uv) { float coarse = fbm(uv * 28.0); float fine = vnoise(uv * 115.0); float tooth = 0.5 + 0.5 * sin(uv.x * 160.0 + coarse * 5.0) * cos(uv.y * 160.0 + fine * 4.0); return clamp(0.55 * coarse + 0.30 * fine + 0.15 * tooth, 0.0, 1.0); } // Curtis et al. (1997) subtractive glaze: pigment density + capillary wet-edge rim + valley granulation vec3 applyGlaze(vec3 canvas, float sdf, vec3 absorbRGB, float baseConc, float paperH, vec2 uv) { float bleed = max(WET_BLEED, 0.02); float feather = fbm(uv * 9.5 + vec2(3.1, 1.7)) - 0.5; float d = sdf + feather * bleed * 0.22; float inside = smoothstep(0.012, -0.018, d); if (inside < 0.001) return canvas; // Capillary backrun concentrates pigment right along the dry boundary float edgeDist = abs(d); float rimPeak = exp(-edgeDist * edgeDist / max(0.00055 * (1.0 + bleed * 1.4), 1e-5)); float edgeTerm = 1.0 + max(EDGE_DARKEN, 0.0) * 1.45 * rimPeak; // Granulation: heavy pigments settle into low paper valleys float gran = mix(1.0, 1.55 - 1.15 * paperH, clamp(GRANULATION, 0.0, 1.5)); // Soft internal wet-in-wet flow mottling float flow = 0.72 + 0.56 * fbm(uv * 5.5 + vec2(0.0, iTime * 0.08)); float thickness = baseConc * inside * edgeTerm * gran * flow; // Kubelka-Munk / Beer-Lambert optical absorption glaze over previous layers vec3 transmittance = exp(-absorbRGB * thickness * 2.2); return canvas * transmittance; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; vec2 drift = vec2(0.025 * cos(iTime * 0.35), 0.02 * sin(iTime * 0.28)); if (iMouse.z > 0.5 || length(iMouse.xy) > 1.0) { drift = ((iMouse.xy - 0.5 * iResolution.xy) / iResolution.y) * 0.18; } float paperH = paperHeight(uv); // Warm textured rag paper substrate vec3 paper = vec3(0.965, 0.945, 0.895) * (1.0 - max(PAPER_GRAIN, 0.0) * 0.14 * (1.0 - paperH)); vec3 col = paper; // Glaze 1: Prussian blue sky/mountain wash float dBlue = length((uv - vec2(-0.16, 0.14) - drift * 0.5) * vec2(0.85, 1.15)) - 0.30; col = applyGlaze(col, dBlue, vec3(1.45, 0.62, 0.18), 0.68, paperH, uv + vec2(1.2, 0.4)); // Glaze 2: Warm burnt sienna / cadmium ochre sun wash overlapping the blue float dOchre = length((uv - vec2(0.18, 0.12) + drift * 0.6) * vec2(1.05, 0.92)) - 0.26; col = applyGlaze(col, dOchre, vec3(0.14, 0.68, 1.55), 0.64, paperH, uv + vec2(-2.4, 1.8)); // Glaze 3: Viridian botanical wash across the lower foreground vec2 gUv = uv - vec2(-0.04, -0.20) + drift * 0.3; float dGreen = length(gUv * vec2(0.68, 1.38)) - 0.26; col = applyGlaze(col, dGreen, vec3(1.28, 0.28, 0.72), 0.62, paperH, uv + vec2(4.1, -3.2)); // Glaze 4: Deep alizarin crimson petal accent with crisp wet-edge backrun float dCrim = length((uv - vec2(0.12, -0.10) - drift * 0.4) * vec2(1.15, 0.85)) - 0.18; col = applyGlaze(col, dCrim, vec3(0.18, 1.38, 1.05), 0.75, paperH, uv + vec2(-1.7, -2.5)); // Subtle warm paper lighting relief float dx = paperHeight(uv + vec2(0.003, 0.0)) - paperH; col *= 1.0 + dx * max(PAPER_GRAIN, 0.0) * 0.35; fragColor = vec4(clamp(col, 0.0, 1.0), 1.0); } ``` Attribution: MIT — written for this index ## Lineage - extended by [Interactive watercolor rendering with temporal coherence](https://texelatlas.vercel.app/t/watercolor-bousseau-realtime.md) ## Sources 1. [primary] Cassidy J. Curtis, Sean E. Anderson, Joshua E. Seims, Kurt W. Fleischer, David H. Salesin (1997) Computer-generated watercolor. Proceedings of the 24th annual conference on Computer graphics and interactive techniques - SIGGRAPH '97. https://doi.org/10.1145/258734.258896 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Computer-generated watercolor (fluid simulation)." https://texelatlas.vercel.app/t/watercolor-rendering-curtis/ (accessed 2026-12-01). --- id: "wave-function-collapse" title: "Wave Function Collapse" aliases: [WFC, overlapping-model WFC, tiled-model WFC] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, python, unity, unreal, godot, webgl2] year_introduced: 2016 inputs: [texture, layout] outputs: [texture, voxels, layout] style: "both" dynamic: "static" cost: "offline" authority: "mxgmn, 2016" url: "https://texelatlas.vercel.app/t/wave-function-collapse/" sources_verified_at: "2026-11-29" --- # Wave Function Collapse (mxgmn, 2016) > Constraint-solving generator that fills a grid with tiles or pixels so all local neighbourhoods match an example. Each cell keeps a set of possible states and repeatedly collapses the lowest-entropy cell, then propagates the consequences. ## Reach for it when - want a level or town generated from an example - tile placement must obey neighbour rules - need procedural voxel structures that stay coherent - texture synthesis that matches local patterns ## How it works Starting from an example bitmap or a tile set with adjacency rules, the algorithm extracts which patterns may sit next to each other (overlapping model: all NxN patterns of the sample; tiled model: explicit adjacency). Every output cell starts as a superposition of all patterns. A loop picks the cell with the lowest Shannon entropy among those not yet determined, collapses it to one pattern with weighted random choice, then propagates constraints (arc consistency) to its neighbours, pruning impossible patterns. If any cell loses all options, the run has hit a contradiction and is restarted or backtracked. Output is local-consistency only, so global structure comes from the input; designers add fixed tiles, border conditions or non-local constraints to steer it. ## When to use it Choose it for tile-based levels, towns, voxel structures and texture synthesis where local adjacency rules are easy to specify or learn from an example. Prefer [Model Synthesis](https://texelatlas.vercel.app/t/model-synthesis.md) when you want the earlier chunked, non-backtracking formulation for large 3D scenes, [MarkovJunior (Rewrite-Rule Generation)](https://texelatlas.vercel.app/t/markov-junior-rewrite-rules.md) for sequential rule rewriting with explicit goals, and [BSP Dungeon Generation](https://texelatlas.vercel.app/t/bsp-dungeon-generation.md) for structured room layouts with guaranteed connectivity. ## Cost offline — Cost grows with grid cells times tile count; contradictions force restarts, so large outputs usually use chunking. Measured GPU Weight: 7.18× baseline (moderate) — 0.2362 ms median / 0.2408 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.05× baseline (moderate) — 0.0962 ms median (2.46× faster on L4). Ampere A100 scaling: 4.67× baseline (light) — 0.1345 ms median (1.76× faster on A100). ## Failure modes - Contradictions: a grid can become unsolvable, requiring restarts or backtracking and making runtime unbounded - Only local correctness: no guarantee of global connectivity, reachability or coherent large-scale structure - Overlapping model with large N memorises the input; with small N yields incoherent noise - Tile weights and symmetry settings dramatically change output, so poorly tuned tile sets over-represent a common tile - Large grids are slow without chunked or windowed solving ## Dataflow - Inputs: texture, layout - Outputs: texture, voxels, layout - Platforms: cpu, python, unity, unreal, godot, webgl2 ## Presets ### Wave function collapse — propagating edge-constraint tile resolution & entropy glow (glsl-fragment; rendered 2026-11-30) ```json { "P_GRID_SIZE": 9, "P_WAVE_SPEED": 0.85, "P_TRACE_WIDTH": 0.24, "P_ENTROPY_GLOW": 1 } ``` ```glsl const float P_GRID_SIZE = 9.0; // P Grid Cells [4.0, 16.0, 1.0] const float P_WAVE_SPEED = 0.85; // P Collapse Speed [0.0, 2.5, 0.05] const float P_TRACE_WIDTH = 0.24; // P Conduit Width [0.1, 0.42, 0.01] const float P_ENTROPY_GLOW = 1.0; // P Frontier Glow [0.0, 2.0, 0.05] float hash21(vec2 p) { p = fract(p * vec2(234.34, 435.345)); p += dot(p, p + 34.23); return fract(p.x * p.y); } // Shared edge-socket oracle guaranteeing 100% Wang adjacency compatibility across N/E/S/W boundaries float hEdge(vec2 cell) { // Horizontal edge between (cell.x, cell.y) and (cell.x, cell.y+1) return step(0.46, hash21(cell * 1.37 + vec2(11.3, 27.9))); } float vEdge(vec2 cell) { // Vertical edge between (cell.x, cell.y) and (cell.x+1, cell.y) return step(0.46, hash21(cell * 1.71 + vec2(53.1, 19.7))); } float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / (dot(ba, ba) + 1e-5), 0.0, 1.0); return length(pa - ba * h); } // Render one of the 16 edge-matched WFC architectural/circuit tiles given its 4 sockets (N, E, S, W) vec2 evalTileSDF(vec2 f, float N, float E, float S, float W, float seed) { // f in [-0.5, 0.5]^2 float d = 1.0; float count = N + E + S + W; if (count < 0.5) { // Empty courtyard tile with recessed square emblem d = max(abs(f.x), abs(f.y)) - 0.16; } else if (count < 1.5) { // Terminal node cap if (N > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(0.0, 0.5))); if (S > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(0.0, -0.5))); if (E > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(0.5, 0.0))); if (W > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(-0.5, 0.0))); d = min(d, length(f) - 0.16); } else if (count < 2.5 && ((N > 0.5 && E > 0.5) || (E > 0.5 && S > 0.5) || (S > 0.5 && W > 0.5) || (W > 0.5 && N > 0.5))) { // Smooth 90-degree quarter-arc corner conduit vec2 corner = vec2((E > 0.5 ? 0.5 : -0.5), (N > 0.5 ? 0.5 : -0.5)); d = abs(length(f - corner) - 0.5); } else { // Straight, T-junction, or 4-way cross hub if (N > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(0.0, 0.5))); if (S > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(0.0, -0.5))); if (E > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(0.5, 0.0))); if (W > 0.5) d = min(d, sdSegment(f, vec2(0.0, 0.0), vec2(-0.5, 0.0))); if (count > 2.5) d = min(d, length(f) - (0.12 + 0.05 * seed)); } return vec2(d, count); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / iResolution.y; float gridN = floor(clamp(P_GRID_SIZE, 4.0, 18.0) + 0.5); float spd = max(P_WAVE_SPEED, 0.0); float traceW = clamp(P_TRACE_WIDTH, 0.08, 0.45) * 0.42; vec2 gp = uv * gridN; vec2 cell = floor(gp); vec2 f = fract(gp) - 0.5; // Cycle wave propagation across the grid so viewer sees live collapse frontier resolving states float cycle = fract(iTime * 0.18 * spd + 0.35); float waveFront = cycle * (gridN * 1.45) - gridN * 0.55; // Manhattan + radial heuristic mimics lowest-entropy propagation front float cellDist = length(cell + 0.5) + 0.45 * hash21(cell * 3.1); float collapseProgress = smoothstep(waveFront + 1.35, waveFront - 0.25, cellDist); float frontier = smoothstep(1.4, 0.0, abs(cellDist - waveFront)); // Query shared sockets for this cell float N = hEdge(cell); float S = hEdge(cell - vec2(0.0, 1.0)); float E = vEdge(cell); float W = vEdge(cell - vec2(1.0, 0.0)); float seed = hash21(cell * 7.3 + 1.9); vec2 tile = evalTileSDF(f, N, E, S, W, seed); float dTrace = tile.x - traceW; // Superposed uncollapsed candidate ghost patterns (blurred blend of alternative states) vec2 ghost1 = evalTileSDF(f, 1.0 - N, E, 1.0 - S, W, 0.5); vec2 ghost2 = evalTileSDF(f, N, 1.0 - E, S, 1.0 - W, 0.5); float ghostMask = 0.5 * smoothstep(traceW + 0.04, traceW - 0.04, ghost1.x) + 0.5 * smoothstep(traceW + 0.04, traceW - 0.04, ghost2.x); // Tile substrate palette (deep indigo ceramic PCB / architectural stone) vec3 tileBg = mix(vec3(0.055, 0.072, 0.115), vec3(0.085, 0.105, 0.16), 0.5 + 0.5 * seed); vec2 borderD = abs(f); float cellFrame = smoothstep(0.455, 0.49, max(borderD.x, borderD.y)); tileBg = mix(tileBg, vec3(0.025, 0.032, 0.05), cellFrame * 0.7); // Collapsed conduit shading: metallic bevel + luminous gold/cyan signal trace float aa = gridN * px * 1.4; float outerFill = smoothstep(aa, -aa, dTrace); float innerTrack = smoothstep(aa, -aa, tile.x - traceW * 0.42); float edgeRim = smoothstep(0.045, 0.0, abs(dTrace)); vec3 conduitBase = mix(vec3(0.16, 0.34, 0.48), vec3(0.24, 0.56, 0.68), smoothstep(0.0, 4.0, tile.y)); vec3 coreCol = mix(vec3(0.32, 0.92, 1.0), vec3(1.05, 0.78, 0.32), step(2.5, tile.y)); float signalPulse = 0.72 + 0.28 * sin((uv.x + uv.y) * 14.0 - iTime * 3.5); vec3 collapsedCol = tileBg; collapsedCol = mix(collapsedCol, conduitBase, outerFill); collapsedCol = mix(collapsedCol, coreCol * signalPulse, innerTrack); collapsedCol += vec3(0.85, 0.95, 1.0) * edgeRim * 0.35; // Uncollapsed quantum-superposition cell appearance (translucent shimmering possibilities) float shimmer = 0.5 + 0.5 * sin(iTime * 6.0 + cell.x * 2.1 + cell.y * 3.7); vec3 superCol = tileBg * 0.85 + vec3(0.18, 0.42, 0.68) * ghostMask * (0.45 + 0.35 * shimmer); // Entropy indicator bars inside uncollapsed tiles float entropyDots = smoothstep(0.06, 0.02, length(f - vec2(0.0, 0.0))) * (0.4 + 0.6 * shimmer); superCol += vec3(0.42, 0.72, 1.0) * entropyDots * 0.45; vec3 col = mix(superCol, collapsedCol, collapseProgress); // Bright amber-cyan wave-collapse frontier highlight float glowAmt = clamp(P_ENTROPY_GLOW, 0.0, 2.2); col += vec3(1.1, 0.72, 0.25) * frontier * (0.28 + 0.75 * cellFrame) * glowAmt; col += vec3(0.35, 0.92, 1.0) * frontier * innerTrack * 0.6 * glowAmt; fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: Original interactive WebGL2 fragment shader written for Texel Atlas (MIT). ## Lineage - extends [Model Synthesis](https://texelatlas.vercel.app/t/model-synthesis.md) - extended by [MarkovJunior (Rewrite-Rule Generation)](https://texelatlas.vercel.app/t/markov-junior-rewrite-rules.md) ## Combines with - [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md): Poisson points place fixed anchor tiles or landmarks that WFC then fills around. ## Combination ideas - [Generated levels with free voxel GI](https://texelatlas.vercel.app/ideas/wfc-voxels-as-gi-volume/) ## Sources 1. [primary] mxgmn (2016) mxgmn/WaveFunctionCollapse. https://github.com/mxgmn/WaveFunctionCollapse License: NOASSERTION. (verified via github on 2026-11-29) 2. [implementation] mxgmn (2016) mxgmn/WaveFunctionCollapse. https://github.com/mxgmn/WaveFunctionCollapse License: NOASSERTION. (verified via github on 2026-11-29) 3. [implementation] BorisTheBrave (2018) BorisTheBrave/DeBroglie. https://github.com/BorisTheBrave/DeBroglie License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Wave Function Collapse." https://texelatlas.vercel.app/t/wave-function-collapse/ (accessed 2026-12-01). --- id: "wavelet-all-frequency-relighting" title: "All-Frequency Shadows via Wavelet Lighting" aliases: [wavelet relighting, all-frequency PRT] domain: "gi" stage: "lighting" realtime: "interactive" platforms: [cpu, desktop-gpu] year_introduced: 2003 inputs: [mesh, hdr-image] outputs: [radiance] style: "photoreal" dynamic: "both" cost: "medium" authority: "Ng et al., 2003" url: "https://texelatlas.vercel.app/t/wavelet-all-frequency-relighting/" sources_verified_at: "2026-11-29" --- # All-Frequency Shadows via Wavelet Lighting (Ng et al., 2003) > Stores precomputed visibility per vertex as Haar wavelets of a cubemap and keeps only the largest coefficients of both the light and the visibility, so sharp shadows from high-frequency environment maps are relit in real time. ## Reach for it when - sunny hdr sky shadows look too soft - relight rigid objects with detailed environment maps - all-frequency lighting and shadows in real time - precomputed shadows that stay sharp under studio lights - need sharp and soft lighting from the same environment ## How it works [precomputed-radiance-transfer](precomputed-radiance-transfer) with spherical harmonics blurs shadows because low bands cannot represent hard edges. This method swaps SH for **Haar wavelets** on each cubemap face, which are localized in space and so can represent a sharp shadow edge with a few coefficients. Offline, for each vertex, the visibility times cosine function over the cube map is transformed into the wavelet basis. Only the largest coefficients (a few tens to hundreds out of tens of thousands) are kept; the rest are zeroed. At runtime, the lighting environment is transformed to the same wavelet basis, and a **non-linear approximation** keeps its largest coefficients too. Because wavelets are orthonormal, the lit value of a vertex is the dot product of the two coefficient sets, which only needs the entries that are non-zero in *both*. Non-linear selection adapts to the data per vertex and per environment, which is why a handful of coefficients captures both a bright small light and its shadows. Diffuse transfer is a vector; glossy transfer uses a matrix expressed in the same basis. ## When to use it Choose it for rigid objects relit by high-frequency environment maps (HDR skies with a sun, studio lights) when hard shadows matter and low-order SH looks too soft. Prefer [precomputed-radiance-transfer](precomputed-radiance-transfer) with SH for compact, cheap, smooth results. Prefer [spherical-harmonics-lighting](spherical-harmonics-lighting) for ambient-only lighting. Prefer [lightmap-baking](lightmap-baking) when the lighting never changes. Prefer [restir-di](restir-di) or ray traced shadows for modern dynamic scenes. ## Cost medium — Per-vertex cost depends on the number of retained coefficients; precomputation is heavy and storage is large for dense meshes. Measured GPU Weight: 27.88× baseline (heavy) — 0.9171 ms median / 0.945 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 22.16× baseline (heavy) — 0.3524 ms median (2.6× faster on L4). Ampere A100 scaling: 15.95× baseline (moderate) — 0.4593 ms median (2× faster on A100). ## Failure modes - Large precomputed data per vertex, and sparse coefficient lists are awkward to evaluate on GPUs - Rigid-only: moving or deforming geometry invalidates the transfer - Truncation artifacts: dropping coefficients leaves visible blockiness in the shadow edges for high compression ratios - Per-vertex sampling limits shadow quality to the mesh density unless stored in textures ## Dataflow - Inputs: mesh, hdr-image - Outputs: radiance - Platforms: cpu, desktop-gpu ## Presets ### Wavelet All-Frequency Relighting — low-order SH blurry shadows (left) vs sparse Haar wavelet sharp shadows (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_ENV_ROT": 0.55, "P_WAVELET_K": 0.92, "P_SPEC_GLOSS": 0.75, "P_SPLIT": 0.48 } ``` ```glsl const float P_ENV_ROT = 0.55; // P Env Rotation [0.0, 2.2, 0.05] const float P_WAVELET_K = 0.92; // P Wavelet Terms [0.1, 1.0, 0.02] const float P_SPEC_GLOSS = 0.75; // P Specular Gloss [0.1, 1.0, 0.02] const float P_SPLIT = 0.48; // P Low-SH / Wavelet [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } // Sculpted relief bust / multi-lobe architectural knot with deep self-occluding crevices! float mapSculpt(vec3 p) { // Pedestal floor at y = -0.58 float dFloor = p.y + 0.58; // Twin interlocking sculptural rings + central sphere (casts crisp all-frequency self-shadows!) vec3 q1 = p - vec3(0.0, 0.05, 0.0); float dRing1 = length(vec2(length(q1.xz) - 0.54, q1.y)) - 0.13; vec3 q2 = q1; q2.xy = rot2(1.05) * q2.xy; float dRing2 = length(vec2(length(q2.xz) - 0.54, q2.y)) - 0.12; float dCore = length(q1) - 0.28; return min(dFloor, min(dCore, min(dRing1, dRing2))); } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapSculpt(p + e.xyy) - mapSculpt(p - e.xyy), mapSculpt(p + e.yxy) - mapSculpt(p - e.yxy), mapSculpt(p + e.yyx) - mapSculpt(p - e.yyx) )); } // Soft raymarched directional visibility V(p, w) with selectable angular blur k float marchVis(vec3 p, vec3 lDir, float kSoft) { float vis = 1.0; float t = 0.04; for (int i = 0; i < 24; i++) { float d = mapSculpt(p + lDir * t); if (d < 0.002) return 0.0; vis = min(vis, kSoft * d / max(t, 0.04)); t += clamp(d, 0.025, 0.25); if (t > 2.6) break; } return clamp(vis, 0.0, 1.0); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isWavelet = screenX >= split; float rotT = iTime * max(P_ENV_ROT, 0.0); float wavK = clamp(P_WAVELET_K, 0.08, 1.0); float gloss = clamp(P_SPEC_GLOSS, 0.05, 1.0); vec3 ro = vec3(0.0, 0.52, 2.28); vec3 rd = normalize(vec3(uv.x, uv.y - 0.18, -1.48)); // Rotating high-contrast HDR environment with 2 sharp studio key lights + cool dome vec3 lKey1 = normalize(vec3(cos(rotT * 0.65) * 0.78, 0.62, sin(rotT * 0.65) * 0.78)); vec3 lKey2 = normalize(vec3(-cos(rotT * 0.65 + 0.7) * 0.72, 0.58, -sin(rotT * 0.65 + 0.7) * 0.72)); vec3 bg = mix(vec3(0.025, 0.032, 0.055), vec3(0.085, 0.125, 0.210), smoothstep(-0.3, 0.6, rd.y)); // Show rotating bright HDR environment light lobes in background bg += vec3(1.8, 1.25, 0.65) * pow(max(dot(rd, lKey1), 0.0), 48.0); bg += vec3(0.55, 1.15, 1.85) * pow(max(dot(rd, lKey2), 0.0), 48.0); vec3 col = bg; float t = 0.05; bool hit = false; for (int i = 0; i < 64; i++) { float d = mapSculpt(ro + rd * t); if (d < 0.0025) { hit = true; break; } t += d; if (t > 8.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p); bool isFloor = (p.y < -0.56); vec3 alb = isFloor ? vec3(0.58, 0.60, 0.64) : vec3(0.84, 0.80, 0.74); if (!isWavelet) { // Left: Order-2 Spherical Harmonics (9 coeffs) heavily band-limits visibility & glossy BRDF -> washed-out blurry shadows! float vis1 = mix(0.45, 0.92, marchVis(p, lKey1, 2.2)); float vis2 = mix(0.45, 0.92, marchVis(p, lKey2, 2.2)); float shDiff1 = max(dot(n, lKey1) * 0.62 + 0.38, 0.0); float shDiff2 = max(dot(n, lKey2) * 0.62 + 0.38, 0.0); // Low-order SH cannot represent sharp specular highlights float shSpec1 = pow(max(dot(n, normalize(lKey1 - rd)), 0.0), 5.0) * 0.24 * gloss; vec3 shEnv = vec3(0.16, 0.22, 0.32) * (0.5 + 0.5 * n.y); col = alb * (vec3(1.15, 0.84, 0.56) * shDiff1 * vis1 * 0.72 + vec3(0.42, 0.74, 1.15) * shDiff2 * vis2 * 0.58 + shEnv) + vec3(1.0, 0.92, 0.82) * shSpec1; } else { // Right: Non-linear Haar Wavelet PRT preserves top-K sparse wavelets -> razor-sharp all-frequency shadows & glossy highlights! float sharpK = mix(4.0, 26.0, wavK); float vis1 = marchVis(p, lKey1, sharpK); float vis2 = marchVis(p, lKey2, sharpK); float diff1 = max(dot(n, lKey1), 0.0) * vis1; float diff2 = max(dot(n, lKey2), 0.0) * vis2; float specExp = mix(14.0, 88.0, gloss * wavK); float spec1 = pow(max(dot(n, normalize(lKey1 - rd)), 0.0), specExp) * vis1 * (0.45 + 0.85 * gloss); float spec2 = pow(max(dot(n, normalize(lKey2 - rd)), 0.0), specExp) * vis2 * (0.35 + 0.65 * gloss); float ao = clamp(0.35 + 0.65 * mapSculpt(p + n * 0.14) / 0.14, 0.2, 1.0); vec3 amb = vec3(0.10, 0.15, 0.24) * (0.4 + 0.6 * n.y) * ao; col = alb * (vec3(1.45, 0.98, 0.56) * diff1 + vec3(0.45, 0.85, 1.40) * diff2 + amb) + vec3(1.0, 0.92, 0.78) * spec1 * (isFloor ? 0.32 : 0.92) + vec3(0.68, 0.88, 1.0) * spec2 * (isFloor ? 0.24 : 0.72); } if (isFloor) col = mix(col, bg, 1.0 - exp(-t * 0.10)); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Precomputed Radiance Transfer](https://texelatlas.vercel.app/t/precomputed-radiance-transfer.md) ## Sources 1. [primary] Ren Ng, Ravi Ramamoorthi, Pat Hanrahan (2003) All-frequency shadows using non-linear wavelet lighting approximation. ACM Transactions on Graphics. https://doi.org/10.1145/882262.882280 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "All-Frequency Shadows via Wavelet Lighting." https://texelatlas.vercel.app/t/wavelet-all-frequency-relighting/ (accessed 2026-12-01). --- id: "weathering-simulation" title: "Weathering simulation (weathered stone)" domain: "materials" stage: "material" realtime: "offline" platforms: [cpu, houdini, blender, python] year_introduced: 1999 inputs: [mesh, texture] outputs: [texture, material-params] style: "photoreal" dynamic: "static" cost: "offline" authority: "Dorsey et al., 1999" url: "https://texelatlas.vercel.app/t/weathering-simulation/" sources_verified_at: "2026-11-29" --- # Weathering simulation (weathered stone) (Dorsey et al., 1999) > Physically motivated ageing of surfaces: water flow, dust and salt deposition and erosion are simulated on the mesh to produce stains, crusts and wear that follow geometry and exposure rather than random noise. ## Reach for it when - stone surfaces look too clean and new - need realistic aging and water stains on buildings - procedural dirt and erosion on materials - make models look weathered over time ## How it works Dorsey et al. model stone as a slab of layers with a water-transport simulation. Rainwater flows over the surface following gravity and exposure; where water seeps in it dissolves and transports minerals and, depending on the wetness and the saturation, deposits them in layers or erodes material. Surface and subsurface moisture are tracked on a volumetric grid (slab) beneath each surface point, and weathering creates stains, crusts (gypsum), erosion and discolouration. Appearance is rendered with subsurface-scattering since weathered stone is translucent and layered. Later work (gamma-ton tracing, Chen et al. 2005) replaces the fluid simulation with particle tracing, a stochastic transport of weathering agents across the surface, which handles dust, rust, moss and peeling paint in much less time. ## When to use it Choose it when weathering must respond to geometry, orientation and exposure: ruins, monuments, rusting machinery. Prefer curvature- and AO-driven procedural masks in material shaders when you need a fast approximation in real-time. Prefer [Procedural noise for texturing](https://texelatlas.vercel.app/t/procedural-noise-texturing.md) for unstructured variation, and [Image quilting](https://texelatlas.vercel.app/t/image-quilting.md) to extend a scanned weathered exemplar. ## Cost offline — Simulation runs offline on a mesh or voxel grid; results are baked to textures. Measured GPU Weight: 100.14× baseline (extreme) — 3.2947 ms median / 3.5439 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 87.77× baseline (extreme) — 1.3955 ms median (2.36× faster on L4). Ampere A100 scaling: 70.93× baseline (extreme) — 2.0429 ms median (1.61× faster on A100). ## Failure modes - Needs a watertight, well-tessellated mesh and parameter tuning per material - Simulation time and memory scale with grid resolution - Results look plausible but are not predictive of real ageing - Artist control is indirect; fixing one stain requires re-running the simulation ## Dataflow - Inputs: mesh, texture - Outputs: texture, material-params - Platforms: cpu, houdini, blender, python ## Presets ### Stone Weathering Simulation — fresh carved limestone (left) vs moss, rain streaks & edge erosion (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_AGE_YEARS": 0.78, "P_MOSS_WET": 0.82, "P_RAIN_STREAK": 0.85, "P_SPLIT": 0.46 } ``` ```glsl const float P_AGE_YEARS = 0.78; // P Weathering Age [0.05, 1.0, 0.02] const float P_MOSS_WET = 0.82; // P Moss & Moisture [0.0, 1.4, 0.04] const float P_RAIN_STREAK = 0.85; // P Rain Wash Streaks [0.0, 1.5, 0.05] const float P_SPLIT = 0.46; // P Fresh / Weathered [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } float hash21(vec2 p) { p = fract(p * vec2(127.1, 311.7)); p += dot(p, p + 34.5); return fract(p.x * p.y); } float vnoise(vec2 p) { vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix( mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x), mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y ); } float fbm(vec2 p) { float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++) { s += a * vnoise(p); p = p * 2.04 + vec2(13.7, 7.3); a *= 0.5; } return s; } 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); } // Architectural stone balustrade / temple shrine plinth float mapStone(vec3 p, float erodeAmt) { float base = sdBox(p - vec3(0.0, -0.52, 0.0), vec3(0.76, 0.16, 0.52)) - 0.02; float colL = sdBox(p - vec3(-0.44, 0.02, 0.0), vec3(0.18, 0.42, 0.24)) - 0.02; float colR = sdBox(p - vec3(0.44, 0.02, 0.0), vec3(0.18, 0.42, 0.24)) - 0.02; float lintel = sdBox(p - vec3(0.0, 0.52, 0.0), vec3(0.72, 0.14, 0.34)) - 0.02; float d = min(min(base, lintel), min(colL, colR)); // Subtle physical stone chipping & surface pitting increases with age float pit = (fbm(p.xy * 7.5 + p.z * 3.1) - 0.5) * 0.028 * erodeAmt; return (d + pit) * 0.85; } vec3 calcNormal(vec3 p, float erodeAmt) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapStone(p + e.xyy, erodeAmt) - mapStone(p - e.xyy, erodeAmt), mapStone(p + e.yxy, erodeAmt) - mapStone(p - e.yxy, erodeAmt), mapStone(p + e.yyx, erodeAmt) - mapStone(p - e.yyx, erodeAmt) )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool isWeathered = screenX >= split; float age = clamp(P_AGE_YEARS, 0.05, 1.0); float mossGain = clamp(P_MOSS_WET, 0.0, 1.5); float streakGain = clamp(P_RAIN_STREAK, 0.0, 1.6); float spin = sin(iTime * 0.38) * 0.42; vec3 ro = vec3(0.0, 0.16, 2.38); vec3 rd = normalize(vec3(uv - vec2(0.0, 0.03), -1.48)); ro.xz = rot2(spin) * ro.xz; rd.xz = rot2(spin) * rd.xz; vec3 col = mix(vec3(0.030, 0.036, 0.052), vec3(0.075, 0.092, 0.128), smoothstep(-0.55, 0.55, uv.y)); float erodeAmt = isWeathered ? age : 0.05; float t = 0.0; bool hit = false; for (int i = 0; i < 60; i++) { float d = mapStone(ro + rd * t, erodeAmt); if (d < 0.0025) { hit = true; break; } t += d; if (t > 6.0) break; } if (hit) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, erodeAmt); vec3 lDir = normalize(vec3(0.62, 0.78, 0.52)); float diff = max(dot(n, lDir), 0.0); float spec = pow(max(dot(n, normalize(lDir - rd)), 0.0), 22.0); // Multi-scale ambient occlusion / crevice accessibility & convex edge curvature float dNear = mapStone(p + n * 0.08, erodeAmt); float dMid = mapStone(p + n * 0.22, erodeAmt); float ao = clamp(0.32 + 0.68 * (dNear / 0.08 * 0.5 + dMid / 0.22 * 0.5), 0.18, 1.0); float crevice = clamp(1.0 - ao, 0.0, 1.0); float edgeWear = clamp((dNear - 0.078) * 18.0, 0.0, 1.0); // Base fresh warm limestone float grain = fbm(p.xy * 12.0 + p.z * 5.0); vec3 stoneAlb = mix(vec3(0.76, 0.72, 0.64), vec3(0.88, 0.84, 0.76), grain); if (isWeathered) { // 1) Gravity-driven vertical rain-runoff stains & calcium carbonate leaching streaks under lintel! float streakNoise = fbm(vec2(p.x * 16.0 + p.z * 9.0, p.y * 2.2)); float underLintel = smoothstep(0.55, 0.32, p.y) * smoothstep(-0.55, 0.35, p.y) * (1.0 - abs(n.y)); float streaks = smoothstep(0.42, 0.72, streakNoise) * underLintel * streakGain * age; // 2) Upward-facing & damp-crevice biological moss colonization float mossNoise = fbm(p.xz * 9.0 + p.y * 4.0); float mossMask = smoothstep(0.38, 0.72, n.y * 0.65 + crevice * 0.75 + mossNoise * 0.45 - 0.32) * mossGain * age; mossMask = clamp(mossMask, 0.0, 1.0); // 3) Soot/dirt darkening inside recessed crevices + pale leached limestone on exposed convex edges stoneAlb = mix(stoneAlb, vec3(0.24, 0.22, 0.20), clamp(crevice * 0.85 * age + streaks * 0.62, 0.0, 0.85)); stoneAlb = mix(stoneAlb, vec3(0.92, 0.90, 0.84), edgeWear * 0.55 * age); vec3 mossCol = mix(vec3(0.14, 0.34, 0.12), vec3(0.34, 0.54, 0.16), mossNoise); stoneAlb = mix(stoneAlb, mossCol, mossMask); // Damp glossy sheen along rain runoff channels spec *= (0.65 + 1.45 * streaks); } col = stoneAlb * (0.24 + 0.84 * diff) * ao + vec3(0.96, 0.94, 0.90) * spec * 0.22; } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combination ideas - [Weathering that creeps along the surface](https://texelatlas.vercel.app/ideas/geodesic-weathering-sources/) ## Sources 1. [primary] Julie Dorsey, Alan Edelman, Henrik Wann Jensen, Justin Legakis, Hans Køhling Pedersen (1999) Modeling and rendering of weathered stone. Proceedings of the 26th annual conference on Computer graphics and interactive techniques - SIGGRAPH '99. https://doi.org/10.1145/311535.311560 (verified via crossref on 2026-11-29) 2. [primary] Yanyun Chen, Lin Xia, Tien-Tsin Wong, Xin Tong, Hujun Bao, Baining Guo, Heung-Yeung Shum (2005) Visual simulation of weathering by γ-ton tracing. ACM Transactions on Graphics. https://doi.org/10.1145/1073204.1073321 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Weathering simulation (weathered stone)." https://texelatlas.vercel.app/t/weathering-simulation/ (accessed 2026-12-01). --- id: "web-gaussian-splat-viewers" title: "Web Gaussian Splat Renderers (three.js)" aliases: [GaussianSplats3D, Spark] domain: "capture" stage: "capture" realtime: "realtime" platforms: [webgl2, webgpu, mobile-gpu, desktop-gpu] year_introduced: 2023 inputs: [gaussians, camera-poses] outputs: [ldr-image] style: "photoreal" dynamic: "static" cost: "medium" authority: "contributors" url: "https://texelatlas.vercel.app/t/web-gaussian-splat-viewers/" sources_verified_at: "2026-11-29" --- # Web Gaussian Splat Renderers (three.js) (contributors) > Browser libraries that load trained splat files and rasterise them as depth-sorted instanced quads in WebGL2, often integrated into three.js scenes. ## Reach for it when - need to show a splat capture on a web page - mix gaussian splats with three.js meshes - no native app, must run in browser webgl2 - embed a photoreal capture in a site ## How it works A trained scene is converted to a compact format (PLY, SPLAT, SPZ or KSPLAT). In the browser, each Gaussian becomes an instanced screen-space quad: a vertex shader projects the 3D covariance to a 2D ellipse and the fragment shader evaluates the Gaussian falloff and blends with premultiplied alpha. Because blending is order dependent, splats are sorted back to front by view-space depth, usually in a Web Worker with a counting sort on quantised depths, and the index buffer is updated asynchronously. Spherical-harmonic colour is evaluated up to a configured degree, with streaming and level-of-detail schemes for large scenes. Spark exposes splats as three.js objects so they composite with meshes. ## When to use it Choose these to ship splat captures in a web page or mix them with polygonal geometry in three.js. Prefer native [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md) or [gsplat](https://texelatlas.vercel.app/t/gsplat.md) viewers when you need the exact reference rasteriser, and [StopThePop (Sorted Gaussian Splatting)](https://texelatlas.vercel.app/t/stopthepop.md) for popping-free native rendering. ## Cost medium — Dominated by splat count and sorting; million-splat scenes run on desktop and recent phones, larger ones need LOD or streaming. ## Failure modes - Approximate per-frame sorting causes popping during fast camera motion - Large files and memory pressure on mobile, so splats are quantised or dropped - Order-dependent blending makes correct mixing with transparent meshes difficult - SH degree is usually reduced, flattening view-dependent effects ## Engine support - babylonjs: builtin — `new BABYLON.GaussianSplattingMesh(name, url, scene) loads and renders depth-sorted 3D Gaussian splats in WebGL2/WebGPU` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Meshes/GaussianSplatting/gaussianSplattingMesh.pure.ts, checked 2026-12-01) - threejs: official — `import { GaussianSplat } from 'three/addons/objects/GaussianSplat.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/objects/GaussianSplat.js, checked 2026-12-01) — Third-party: GaussianSplats3D, Spark. ## Dataflow - Inputs: gaussians, camera-poses - Outputs: ldr-image - Platforms: webgl2, webgpu, mobile-gpu, desktop-gpu ## Combines with - [3D Gaussian Splatting](https://texelatlas.vercel.app/t/gaussian-splatting-3dgs.md): Trained 3DGS scenes are exported to splat formats that these viewers load. ## Combination ideas - [Liquids drawn by a splat renderer](https://texelatlas.vercel.app/ideas/fluids-through-splat-renderer/) ## Sources 1. [implementation] mkkellogg (2023) mkkellogg/GaussianSplats3D. https://github.com/mkkellogg/GaussianSplats3D License: MIT. (verified via github on 2026-11-29) 2. [implementation] sparkjsdev (2025) sparkjsdev/spark. https://github.com/sparkjsdev/spark License: MIT. (verified via github on 2026-11-29) 3. [primary] Spark contributors Spark documentation. sparkjs.dev. https://sparkjs.dev/ (verified via http on 2026-11-29) ## Cite this entry Texel. "Web Gaussian Splat Renderers (three.js)." https://texelatlas.vercel.app/t/web-gaussian-splat-viewers/ (accessed 2026-12-01). --- id: "weber-penn-tree-generation" title: "Weber and Penn parametric tree generation" aliases: [Weber-Penn, Sapling tree generator] domain: "procgen" stage: "procedural" realtime: "interactive" platforms: [cpu, blender, python, unity, unreal, godot] year_introduced: 1995 outputs: [curves, mesh] style: "photoreal" dynamic: "static" cost: "cheap" authority: "Weber & Penn, 1995" url: "https://texelatlas.vercel.app/t/weber-penn-tree-generation/" sources_verified_at: "2026-11-29" --- # Weber and Penn parametric tree generation (Weber & Penn, 1995) > Grows a tree from a few dozen species parameters that control trunk taper, branch splitting, curvature, and recursion over several levels, then skins the stems and adds leaves. ## Reach for it when - need many varied tree species from sliders - generate a realistic tree mesh from parameters - blender sapling style procedural trees - want branching with taper curvature and splits ## How it works A tree is described by up to four recursion levels: trunk, branches, sub-branches, twigs. Each level has parameters for length, radius ratio, number of children, their spacing along the parent, downward and rotational angles, curvature, and random variation. The generator walks the stem as a sequence of segments, bending each by the level's curve parameters, and places children at positions along the parent derived from the child count and spacing, with each child's angle relative to the parent and a spiral phase. Clones at the segment level can split stems into forks. Trunk flare and radius taper follow a profile function. Leaves attach at the last level. Output is a skeleton of curves with radii that you skin into a mesh and instance leaves onto; species presets are simply parameter sets, which is why it is so easy to ship with a UI. ## When to use it Choose it when you want controllable, species-like trees from a small parameter set, or a classic baseline with a known preset library. Prefer [L-Systems](https://texelatlas.vercel.app/t/l-systems.md) for grammar-driven plants where topology rules matter more than botany sliders, [Space Colonization Tree Modeling](https://texelatlas.vercel.app/t/space-colonization-trees.md) when branches should fill a given crown envelope or react to obstacles, and [Interactive Climbing Plant Modeling](https://texelatlas.vercel.app/t/climbing-plants-simulation.md) for plants that interact with surfaces. ## Cost cheap — Tree generation is milliseconds to seconds on CPU depending on branch count; rendering cost is the resulting mesh and alpha-tested leaves. Measured GPU Weight: 642.54× baseline (extreme) — 21.1395 ms median / 21.6719 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 563.3× baseline (extreme) — 8.9564 ms median (2.36× faster on L4). Ampere A100 scaling: 446.63× baseline (extreme) — 12.863 ms median (1.64× faster on A100). ## Failure modes - Parameters interact non-intuitively, so tuning a new species by hand takes many iterations - Branches ignore each other and light, so crowns interpenetrate and look uniformly dense unlike real, light-seeking trees - Branch-to-trunk joins show seams or pinching unless the skinning blends radii at junctions - Random variation makes results non-reproducible unless the seed is stored with the parameters ## Engine support - blender: official — `Install Sapling Tree Gen from extensions.blender.org` (evidence: https://extensions.blender.org/add-ons/sapling-tree-gen/, checked 2026-12-01) — Extension; no longer bundled with Blender. ## Dataflow - Inputs: — - Outputs: curves, mesh - Platforms: cpu, blender, python, unity, unreal, godot ## Presets ### Weber & Penn Tree Generation — multi-level parametric branch skeleton (left) vs skinned bark & backlit foliage canopy (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_SPLIT_ANGLE": 0.52, "P_CURVATURE": 0.38, "P_CANOPY_DENS": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_SPLIT_ANGLE = 0.52; // P Branch Split Angle [0.22, 0.85, 0.03] const float P_CURVATURE = 0.38; // P Phototropism Curve [0.05, 0.75, 0.03] const float P_CANOPY_DENS = 1.00; // P Canopy Fullness [0.4, 1.5, 0.05] const float P_SPLIT = 0.48; // P Skeleton / Tree Split [0.0, 1.0, 0.02] float hash31(vec3 p) { p = fract(p * vec3(127.1, 311.7, 74.7)); p += dot(p, p.yzx + 19.19); return fract((p.x + p.y) * p.z); } float noise3(vec3 p) { vec3 i = floor(p); vec3 f = fract(p); f = f * f * (3.0 - 2.0 * f); return mix( mix(mix(hash31(i), hash31(i + vec3(1.0, 0.0, 0.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 0.0)), hash31(i + vec3(1.0, 1.0, 0.0)), f.x), f.y), mix(mix(hash31(i + vec3(0.0, 0.0, 1.0)), hash31(i + vec3(1.0, 0.0, 1.0)), f.x), mix(hash31(i + vec3(0.0, 1.0, 1.0)), hash31(i + vec3(1.0, 1.0, 1.0)), f.x), f.y), f.z ); } // Tapered capsule segment from a (radius ra) to b (radius rb) float sdTaperCapsule(vec3 p, vec3 a, vec3 b, float ra, float rb) { vec3 ba = b - a; vec3 pa = p - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h) - mix(ra, rb, h); } // Evaluate Weber-Penn 3-level recursive tree SDF: returns vec2(distance, matId) // matId: 1 = L0 Trunk, 2 = L1 Primary Limbs, 3 = L2 Secondary Boughs, 4 = Leaf Canopy, 5 = Ground vec2 mapTree(vec3 p, float splitAng, float curveK, float canDens, bool includeLeaves) { float dGround = p.y + 0.68 - 0.06 * cos(length(p.xz) * 1.4); vec2 res = vec2(dGround, 5.0); // Level 0: Tapered slightly curved main trunk with buttress flare at base vec3 t0 = vec3(0.0, -0.70, 0.0); vec3 t1 = vec3(0.04 * curveK, -0.05, 0.0); vec3 t2 = vec3(-0.03 * curveK, 0.42, 0.02 * curveK); float dL0 = min( sdTaperCapsule(p, t0, t1, 0.115, 0.072), sdTaperCapsule(p, t1, t2, 0.072, 0.040) ); if (dL0 < res.x) res = vec2(dL0, 1.0); // Level 1 (5 primary limbs) + Level 2 (2 secondary boughs each = 10 twigs) + Leaf clusters at tips float dL1 = 1e5; float dL2 = 1e5; float dLeaf = 1e5; for (int i = 0; i < 5; i++) { float fi = float(i); float az = fi * 1.256637 + 0.35; float hStart = -0.06 + fi * 0.105; vec3 bStart = mix(t1, t2, clamp((hStart + 0.05) / 0.47, 0.0, 1.0)); // Weber-Penn down-angle + upward phototropism bend float elev = 1.15 - splitAng * 0.72 + curveK * 0.35; vec3 dir1 = normalize(vec3(cos(az) * sin(elev), cos(elev) + 0.35 + curveK * 0.35, sin(az) * sin(elev))); float len1 = (0.58 - fi * 0.045) * (0.85 + 0.25 * splitAng); vec3 bMid = bStart + dir1 * (len1 * 0.55); vec3 bEnd = bMid + normalize(dir1 + vec3(0.0, curveK * 0.95, 0.0)) * (len1 * 0.52); float r1 = 0.042 - fi * 0.004; dL1 = min(dL1, sdTaperCapsule(p, bStart, bMid, r1, r1 * 0.68)); dL1 = min(dL1, sdTaperCapsule(p, bMid, bEnd, r1 * 0.68, r1 * 0.36)); // Two Level-2 secondary boughs splitting off each primary limb for (int j = 0; j < 2; j++) { float side = (j == 0) ? -1.0 : 1.0; float az2 = az + side * (0.55 + splitAng * 0.45); vec3 dir2 = normalize(vec3(cos(az2), 0.58 + curveK * 0.65, sin(az2))); vec3 sStart = mix(bMid, bEnd, float(j) * 0.45 + 0.25); vec3 sEnd = sStart + dir2 * (0.34 - fi * 0.02); dL2 = min(dL2, sdTaperCapsule(p, sStart, sEnd, r1 * 0.42, 0.010)); if (includeLeaves) { float clR = (0.24 + 0.04 * sin(fi * 2.1 + side)) * canDens; float dC = length(p - sEnd) - clR; if (dC < 0.12) { float leafN = noise3(p * 11.0 + vec3(iTime * 0.35, 0.0, 0.0)) - 0.5; dC += leafN * 0.095; } dLeaf = min(dLeaf, dC); } } if (includeLeaves) { float tipR = 0.25 * canDens; float dTip = length(p - bEnd) - tipR; if (dTip < 0.12) { dTip += (noise3(p * 11.0 + vec3(iTime * 0.35, 1.7, 0.0)) - 0.5) * 0.095; } dLeaf = min(dLeaf, dTip); } } // Crown apex cluster if (includeLeaves) { vec3 apex = t2 + vec3(0.0, 0.28 + curveK * 0.14, 0.0); float dApex = length(p - apex) - 0.27 * canDens; if (dApex < 0.12) dApex += (noise3(p * 11.0 + vec3(iTime * 0.35, 3.1, 0.0)) - 0.5) * 0.095; dLeaf = min(dLeaf, dApex); } if (dL1 < res.x) res = vec2(dL1, 2.0); if (dL2 < res.x) res = vec2(dL2, 3.0); if (includeLeaves && dLeaf < res.x) res = vec2(dLeaf, 4.0); return res; } vec3 calcNormal(vec3 p, float splitAng, float curveK, float canDens, bool includeLeaves) { vec2 e = vec2(0.003, 0.0); return normalize(vec3( mapTree(p + e.xyy, splitAng, curveK, canDens, includeLeaves).x - mapTree(p - e.xyy, splitAng, curveK, canDens, includeLeaves).x, mapTree(p + e.yxy, splitAng, curveK, canDens, includeLeaves).x - mapTree(p - e.yxy, splitAng, curveK, canDens, includeLeaves).x, mapTree(p + e.yyx, splitAng, curveK, canDens, includeLeaves).x - mapTree(p - e.yyx, splitAng, curveK, canDens, includeLeaves).x )); } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float sx = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); bool showFoliage = sx >= split; float splitAng = clamp(P_SPLIT_ANGLE, 0.15, 0.95); float curveK = clamp(P_CURVATURE, 0.0, 0.85); float canDens = clamp(P_CANOPY_DENS, 0.3, 1.6); float orb = iTime * 0.28 + 0.4; vec3 ro = vec3(2.45 * sin(orb), 0.34, 2.45 * cos(orb)); vec3 ta = vec3(0.0, 0.10, 0.0); vec3 fw = normalize(ta - ro); vec3 ri = normalize(cross(fw, vec3(0.0, 1.0, 0.0))); vec3 up = cross(ri, fw); vec3 rd = normalize(fw * 1.44 + ri * uv.x + up * uv.y); vec3 sunDir = normalize(vec3(0.62, 0.76, 0.48)); vec3 sky = mix(vec3(0.76, 0.84, 0.94), vec3(0.18, 0.40, 0.76), smoothstep(-0.08, 0.58, rd.y)); vec3 col = showFoliage ? sky : mix(vec3(0.05, 0.07, 0.11), vec3(0.12, 0.16, 0.24), smoothstep(-0.2, 0.6, rd.y)); float t = 0.08; float hitId = 0.0; for (int i = 0; i < 64; i++) { vec2 h = mapTree(ro + rd * t, splitAng, curveK, canDens, showFoliage); if (h.x < 0.0028) { hitId = h.y; break; } t += h.x * 0.82; if (t > 9.0) break; } if (hitId > 0.5) { vec3 p = ro + rd * t; vec3 n = calcNormal(p, splitAng, curveK, canDens, showFoliage); float ndl = max(dot(n, sunDir), 0.0); // Quick soft canopy shadow float sh = 1.0; float ts = 0.06; for (int s = 0; s < 14; s++) { float ds = mapTree(p + sunDir * ts, splitAng, curveK, canDens, showFoliage).x; if (ds < 0.004) { sh = 0.18; break; } sh = min(sh, 5.0 * ds / max(ts, 1e-4) + 0.18); ts += max(ds, 0.05); if (ts > 2.4) break; } sh = clamp(sh, 0.18, 1.0); if (!showFoliage) { // Left: Color-coded Weber-Penn parametric recursion hierarchy (L0 Trunk, L1 Primary, L2 Secondary, Blueprint Ground) if (hitId > 4.5) { vec2 g = abs(fract(p.xz * 2.5) - 0.5); float gl = smoothstep(0.04, 0.01, min(0.5 - g.x, 0.5 - g.y)); col = mix(vec3(0.07, 0.09, 0.13), vec3(0.22, 0.42, 0.58), gl * 0.65) * (0.55 + 0.45 * sh); } else { vec3 lvlCol = vec3(0.95, 0.55, 0.22); // L0 Trunk if (hitId > 1.5 && hitId < 2.5) lvlCol = vec3(0.22, 0.88, 0.98); // L1 Primary limbs else if (hitId > 2.5) lvlCol = vec3(0.32, 0.96, 0.48); // L2 Secondary twigs col = lvlCol * (0.35 + 0.85 * ndl) + vec3(0.9) * pow(max(dot(n, normalize(sunDir - rd)), 0.0), 24.0) * 0.25; } } else { // Right: Full skinned bark & backlit translucent green foliage canopy! vec3 skyAmb = mix(vec3(0.16, 0.22, 0.18), vec3(0.34, 0.48, 0.72), 0.5 + 0.5 * n.y); if (hitId > 4.5) { vec3 grass = mix(vec3(0.18, 0.34, 0.14), vec3(0.28, 0.44, 0.18), noise3(p * 3.5)); col = grass * (vec3(1.32, 1.22, 0.98) * ndl * sh + skyAmb * 0.52); col = mix(col, sky, 1.0 - exp(-t * 0.09)); } else if (hitId < 3.5) { float bark = 0.75 + 0.25 * sin(atan(p.z, p.x) * 18.0 + p.y * 12.0); vec3 barkAlb = vec3(0.28, 0.20, 0.13) * bark; col = barkAlb * (vec3(1.25, 1.12, 0.92) * ndl * sh + skyAmb * 0.48); } else { // Lush sunlit leaves with warm yellow-green subsurface translucency float leafVar = noise3(p * 14.0); vec3 leafAlb = mix(vec3(0.10, 0.32, 0.10), vec3(0.26, 0.52, 0.14), leafVar); float sss = pow(max(dot(rd, sunDir), 0.0), 3.0) * 0.55 + 0.25 * max(dot(-n, sunDir), 0.0); col = leafAlb * (vec3(1.42, 1.28, 0.96) * ndl * sh + skyAmb * 0.58) + vec3(0.58, 0.82, 0.18) * sss * (0.4 + 0.6 * sh); } } } float sep = smoothstep(0.0035, 0.0008, abs(sx - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Combines with - [Space Colonization Tree Modeling](https://texelatlas.vercel.app/t/space-colonization-trees.md): A Weber–Penn trunk and main branches can seed the crown, and space colonization then fills twig-level detail inside it. ## Sources 1. [primary] Jason Weber, Joseph Penn (1995) Creation and rendering of realistic trees. Proceedings of the 22nd annual conference on Computer graphics and interactive techniques - SIGGRAPH '95. https://doi.org/10.1145/218380.218427 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "Weber and Penn parametric tree generation." https://texelatlas.vercel.app/t/weber-penn-tree-generation/ (accessed 2026-12-01). --- id: "weighted-blended-oit" title: "Weighted blended order-independent transparency" aliases: [WBOIT, weighted blended OIT] domain: "visibility" stage: "visibility" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot] year_introduced: 2013 inputs: [mesh, depth] outputs: [hdr-image] style: "both" dynamic: "dynamic" cost: "cheap" authority: "McGuire & Bavoil" url: "https://texelatlas.vercel.app/t/weighted-blended-oit/" sources_verified_at: "2026-11-29" --- # Weighted blended order-independent transparency (McGuire & Bavoil) > Draws all transparent surfaces in any order into two cheap accumulation targets and resolves them in one pass with a depth-dependent weight, trading exact ordering for single-pass speed. ## Reach for it when - many overlapping transparent particles render in the wrong order - need transparency without sorting triangles every frame - smoke and glass layers pop when camera moves - transparent foliage cards need cheap blending on webgl2 - sorting transparent objects is too slow with thousands of quads ## How it works Transparent geometry is rendered after the opaque pass with depth writes off. Each fragment contributes to two render targets using additive/multiplicative blending: an RGBA16F target accumulating premultiplied colour times a weight, plus the weight itself in alpha, and an R8/R16F target accumulating the product of (1 - alpha), which is the final revealage (how much background still shows). The weight is a hand-designed function that grows with alpha and falls steeply with view depth, so nearer layers dominate the average the way they would after sorting. A fullscreen composite then divides accumulated colour by accumulated weight to get an average transparent colour and blends it over the opaque image using one minus revealage. Because accumulation is commutative, no sorting, per-pixel lists or multiple depth peels are needed. Variants add a colour-dependent transmittance target, or tune the weight to the scene's depth range. ## When to use it Choose it for particles, smoke, foliage cards, glass-like clutter and any case where many low-to-moderate alpha layers overlap and approximate ordering is acceptable, especially on WebGL2 and mobile where linked lists are unavailable. Prefer [Hashed alpha testing / alpha-to-coverage for foliage](https://texelatlas.vercel.app/t/hashed-alpha-testing.md) when the surfaces can be stochastic cutouts resolved by [Temporal Anti-Aliasing](https://texelatlas.vercel.app/t/temporal-anti-aliasing.md), and exact sorted or per-pixel-list OIT when a few high-alpha layers (stacked windows, jewellery) must layer correctly. Keep opaque and refractive-glass objects in their own passes. ## Cost cheap — One geometry pass with blending into two small targets plus a fullscreen composite; cost is dominated by overdraw bandwidth, not sorting. Measured GPU Weight: 2.2× baseline (light) — 0.0723 ms median / 0.0757 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 1.77× baseline (feather) — 0.0281 ms median (2.57× faster on L4). Ampere A100 scaling: 1.29× baseline (feather) — 0.0372 ms median (1.94× faster on A100). ## Failure modes - Ordering errors with high-alpha layers: a distant opaque-looking surface can bleed over a near one - The depth weight needs tuning per scene; too flat gives order-dependent mush, too steep makes far layers vanish - Colour tints from averaging, since colours blend by weight rather than by true transmittance - Float target precision limits with huge weights or very many layers (overflow in RGBA16F) - Needs a separate pass and care to avoid double-blending with fog or bloom inputs ## Engine support - threejs: official — `import { oitPass } from 'three/addons/tsl/display/OITPassNode.js'` (evidence: https://github.com/mrdoob/three.js/blob/r187/examples/jsm/tsl/display/OITPassNode.js, checked 2026-12-01) ## Dataflow - Inputs: mesh, depth - Outputs: hdr-image - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, unity, unreal, godot ## Presets ### Unsorted over vs WBOIT vs sorted, four overlapping discs (glsl-fragment; rendered 2026-11-29) ```json { "alpha": 0.55, "depths": [ 1, 2, 3, 4 ] } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Left: unsorted "over" blending. Middle: weighted blended OIT. Right: sorted reference. const float ALPHA = 0.55; const vec4 Z = vec4(1.0, 2.0, 3.0, 4.0); // view depth per layer (index 0 is farthest) vec3 layerColor(int i) { if (i == 0) return vec3(0.95, 0.25, 0.20); if (i == 1) return vec3(0.95, 0.80, 0.15); if (i == 2) return vec3(0.15, 0.75, 0.35); return vec3(0.20, 0.35, 0.95); } vec2 layerCenter(int i, float t) { float a = t * 0.6 + float(i) * 1.57; return vec2(0.13 * cos(a), 0.13 * sin(a)) + vec2(-0.08 + 0.055 * float(i), 0.0); } float coverage(int i, vec2 p, float t) { return step(length(p - layerCenter(i, t)), 0.20); } float weightFn(float z, float a) { return a * clamp(10.0 / (1e-5 + pow(z / 5.0, 3.0) + pow(z / 200.0, 6.0)), 1e-2, 3e3); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; float panel = floor(uv.x * 3.0); vec2 p = vec2(fract(uv.x * 3.0) - 0.5, uv.y - 0.5); vec3 bg = mix(vec3(0.92), vec3(0.55, 0.60, 0.70), uv.y); vec3 col = bg; float t = iTime; if (panel < 0.5) { int order[4] = int[4](2, 0, 3, 1); // arbitrary submission order, no sorting for (int k = 0; k < 4; k++) { int i = order[k]; float c = coverage(i, p, t) * ALPHA; col = mix(col, layerColor(i), c); } } else if (panel < 1.5) { vec3 accum = vec3(0.0); float aw = 0.0; float reveal = 1.0; for (int i = 0; i < 4; i++) { float cov = coverage(i, p, t); float w = weightFn(Z[i], ALPHA) * cov; accum += layerColor(i) * w; aw += w; reveal *= 1.0 - cov * ALPHA; } vec3 avg = accum / max(aw, 1e-5); col = mix(bg, avg, 1.0 - reveal); } else { for (int i = 0; i < 4; i++) { // back to front col = mix(col, layerColor(i), coverage(i, p, t) * ALPHA); } } if (abs(fract(uv.x * 3.0) - 0.5) > 0.495) col = vec3(1.0); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index; weight function follows the formula family in the cited paper; basis: 0 ## Combines with - [Hashed alpha testing / alpha-to-coverage for foliage](https://texelatlas.vercel.app/t/hashed-alpha-testing.md): Hashed cutouts handle opaque-ish foliage while WBOIT handles the genuinely translucent layers in the same frame. ## Sources 1. [primary] Morgan McGuire, Louis Bavoil Weighted Blended Order-Independent Transparency. jcgt.org. https://jcgt.org/published/0002/02/09 (verified via http on 2026-11-29) 2. [implementation] stevinz (2022) stevinz/three-wboit. https://github.com/stevinz/three-wboit License: MIT. (verified via github on 2026-11-29) 3. [implementation] mhalber (2019) mhalber/Weighted-Blended-OIT. https://github.com/mhalber/Weighted-Blended-OIT License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Weighted blended order-independent transparency." https://texelatlas.vercel.app/t/weighted-blended-oit/ (accessed 2026-12-01). --- id: "worldgen" title: "WorldGen (text/image to 3D scene)" domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2025 inputs: [text-prompt, ldr-image] outputs: [gaussians, mesh] style: "both" dynamic: "static" cost: "heavy" authority: "ZiYang-xie, 2025" url: "https://texelatlas.vercel.app/t/worldgen/" sources_verified_at: "2026-11-29" --- # WorldGen (text/image to 3D scene) (ZiYang-xie, 2025) > An open-source pipeline that generates an explorable 3D scene (indoor or outdoor) from a text prompt or image, intended for games, simulation and robotics. ## Reach for it when - need a quick explorable 3d scene from a prompt - open-source text or image to environment - prototype backdrop for simulation or robotics - generate indoor or outdoor levels without modelling - permissively licensed scene generator for games ## How it works The repository exposes a single call that takes a prompt or image and returns a scene. From the README, the pipeline produces a 360-degree consistent environment with loop closure and lets the user render from arbitrary cameras and trajectories. Internally such scene-generation pipelines typically produce a panoramic or multi-view image prior, estimate depth, and lift the result into a Gaussian or mesh representation; I could not verify WorldGen's exact internal stages, since it has no paper, so treat this entry as describing the interface only. ## When to use it Choose it to get a quick explorable environment for prototypes and simulation backdrops with an Apache-2.0 codebase. Prefer [Marble (World Labs multimodal world model)](https://texelatlas.vercel.app/t/marble-world-model.md) for a hosted, higher-fidelity world model with export, [Genie 2 and Genie 3 (interactive world models)](https://texelatlas.vercel.app/t/genie-world-models.md) for interactive but non-exportable worlds, and object-level generators ([TRELLIS (Structured 3D Latents)](https://texelatlas.vercel.app/t/trellis.md), [Hunyuan3D 2.0](https://texelatlas.vercel.app/t/hunyuan3d-2.md)) when you need individual assets. ## Cost heavy — README claims seconds per scene; not independently verified. ## Failure modes - Only reliable within a limited range around the generation viewpoint; far views reveal stretched or missing geometry - Panoramic seams and distortion near poles - Scene geometry is approximate, with poor collision usefulness - No paper to define methodology or evaluation ## Dataflow - Inputs: text-prompt, ldr-image - Outputs: gaussians, mesh - Platforms: cuda, python ## Sources 1. [primary] ZiYang-xie (2025) ZiYang-xie/WorldGen. https://github.com/ZiYang-xie/WorldGen License: Apache-2.0. (verified via github on 2026-11-29) ## Cite this entry Texel. "WorldGen (text/image to 3D scene)." https://texelatlas.vercel.app/t/worldgen/ (accessed 2026-12-01). --- id: "worley-noise" title: "Worley (Cellular) Noise" aliases: [cellular noise, Voronoi noise, F1/F2 noise] domain: "procgen" stage: "procedural" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, houdini, unity, unreal, godot, python] year_introduced: 1996 outputs: [texture, heightfield] style: "both" dynamic: "both" cost: "cheap" authority: "Worley, 1996" url: "https://texelatlas.vercel.app/t/worley-noise/" sources_verified_at: "2026-11-29" --- # Worley (Cellular) Noise (Worley, 1996) > A procedural texture basis built from distances to the nearest scattered feature points. F1 gives cells, F2-F1 gives cell borders, and combinations give stone, cracks, scales and caustics. ## Reach for it when - need cellular or cracked pattern texture - make stone, scales or water caustics procedurally - pattern with distinct cells and distances to points - organic cell structure looks different from perlin noise ## How it works Space is split into a grid and each cell holds a few jittered feature points, generated by hashing the cell index so the pattern is infinite and seedable. At a shading point you search the point's own cell and its neighbours (3x3 in 2D, 3x3x3 in 3D, sometimes more for several points per cell) and record the sorted distances F1, F2, F3 to the closest features. Any function of these distances is a texture: F1 looks like pebbles or bubbles, F2-F1 produces thin crack-like borders along Voronoi edges, F2 squashed gives scales. Switching the metric from Euclidean to Manhattan or Chebyshev changes cell shapes. The cell id of the nearest feature can also be used to give each cell a random colour or height. ## When to use it Choose it for stone, tiles, cracked mud, cell membranes, scales or any texture with explicit cell structure, and as a source of cell ids for per-cell variation. Prefer [Perlin Noise (gradient lattice noise)](https://texelatlas.vercel.app/t/perlin-noise.md) family when you want smooth blobby fields, [Voronoi Diagrams and Lloyd Relaxation](https://texelatlas.vercel.app/t/voronoi-lloyd-relaxation.md) when you need an explicit mesh of cells rather than a per-pixel function, and [Poisson Disk Sampling (Bridson)](https://texelatlas.vercel.app/t/poisson-disk-sampling.md) when point spacing must be guaranteed. ## Cost cheap — Fixed neighbourhood search per pixel (9 or 27 cells); cost grows with points per cell and with 3D. Measured GPU Weight: 7.6× baseline (moderate) — 0.2502 ms median / 0.2579 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 6.68× baseline (moderate) — 0.1062 ms median (2.36× faster on L4). Ampere A100 scaling: 4.82× baseline (light) — 0.1387 ms median (1.8× faster on A100). ## Failure modes - Searching only the 3x3 neighbourhood misses the true nearest point when jitter is large, producing straight-edged discontinuities in F1 - F1 has gradient discontinuities along cell borders, which show as sharp creases in bump mapped surfaces - Unbounded jitter plus low point density yields very large cells and visible lattice alignment - Hash correlation between neighbouring cells creates repeating motifs ## Engine support - babylonjs: builtin — `WorleyNoise3DBlock in Node Material Editor` (evidence: https://github.com/BabylonJS/Babylon.js/blob/9.38.0/packages/dev/core/src/Materials/Node/Blocks/worleyNoise3DBlock.ts, checked 2026-12-01) - blender: builtin — `Shader Editor > Add > Texture > Voronoi Texture (F1, F2, Smooth F1)` (evidence: https://docs.blender.org/manual/en/5.2/render/shader_nodes/textures/voronoi.html, checked 2026-12-01) - godot: builtin — `FastNoiseLite > noise_type = FastNoiseLite.TYPE_CELLULAR (Voronoi / Worley cellular noise)` (evidence: https://github.com/godotengine/godot/blob/4.4-stable/modules/noise/fastnoise_lite.cpp, checked 2026-12-01) - threejs: builtin — `import { mx_worley_noise_float } from 'three/tsl'` (evidence: https://github.com/mrdoob/three.js/blob/r187/src/nodes/materialx/MaterialXNodes.js, checked 2026-12-01) — TSL node. - unity: official — `Package Manager > Mathematics > noise.cellular` (evidence: https://github.com/Unity-Technologies/Unity.Mathematics/blob/master/src/Unity.Mathematics/Noise/cellular3D.cs, checked 2026-12-01) — Unity.Mathematics cellular noise; Shader Graph also has a Voronoi node. - unreal: builtin — `Material Noise expression > Function = Voronoi (Worley/cellular)` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/utility-material-expressions-in-unreal-engine, checked 2026-12-01) ## Dataflow - Inputs: — - Outputs: texture, heightfield - Platforms: webgl2, webgpu, desktop-gpu, mobile-gpu, cpu, blender, houdini, unity, unreal, godot, python ## Presets ### Worley F1 cells with F2-F1 borders (glsl-fragment; rendered 2026-11-29) ```json { "scale": 7, "jitter": 1 } ``` ```glsl // GLSL ES 3.0, Shadertoy-style. Worley F1/F2 cells with animated feature points. const float SCALE = 7.0; // cells across the screen height const float JITTER = 1.0; // 0 = regular grid, 1 = fully random points vec2 hash22(vec2 p){ vec3 q = fract(vec3(p.xyx) * vec3(.1031, .1030, .0973)); q += dot(q, q.yzx + 33.33); return fract((q.xx + q.yz) * q.zy); } void mainImage(out vec4 fragColor, in vec2 fragCoord){ vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y * SCALE; vec2 ip = floor(uv); vec2 fp = fract(uv); float f1 = 8.0, f2 = 8.0; vec2 id = vec2(0.0); for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { vec2 g = vec2(float(i), float(j)); vec2 h = hash22(ip + g); vec2 o = 0.5 + 0.5 * sin(iTime * 0.8 + 6.2831 * h); vec2 pt = g + mix(vec2(0.5), o, JITTER); float d = length(pt - fp); if (d < f1) { f2 = f1; f1 = d; id = ip + g; } else if (d < f2) { f2 = d; } } } vec3 cellCol = 0.5 + 0.5 * cos(6.2831 * (hash22(id).x + vec3(0.0, 0.33, 0.67))); float edge = smoothstep(0.0, 0.08, f2 - f1); vec3 col = cellCol * (0.55 + 0.45 * (1.0 - f1)); col = mix(vec3(0.03), col, edge); fragColor = vec4(col, 1.0); } ``` Attribution: written for this index ## Sources 1. [primary] Steven Worley (1996) A cellular texture basis function. Proceedings of the 23rd annual conference on Computer graphics and interactive techniques. https://doi.org/10.1145/237170.237267 (verified via crossref on 2026-11-29) 2. [tutorial] Inigo Quilez Voronoise. iquilezles.org. https://iquilezles.org/articles/voronoise (verified via http on 2026-11-29) 3. [tutorial] Inigo Quilez Voronoi Edges. iquilezles.org. https://iquilezles.org/articles/voronoilines (verified via http on 2026-11-29) ## Cite this entry Texel. "Worley (Cellular) Noise." https://texelatlas.vercel.app/t/worley-noise/ (accessed 2026-12-01). --- id: "xatlas" title: "xatlas" domain: "geometry" stage: "geometry" realtime: "offline" platforms: [cpu, blender, unity, unreal, webgl2] year_introduced: 2018 inputs: [mesh] outputs: [uv-atlas] style: "both" dynamic: "static" cost: "offline" authority: "jpcy, 2018" url: "https://texelatlas.vercel.app/t/xatlas/" sources_verified_at: "2026-11-29" --- # xatlas (jpcy, 2018) > A small C++ library that segments a triangle mesh into charts, parameterizes each, and packs them into a lightmap atlas without user seams. Widely used for automatic lightmap UVs. ## Reach for it when - need lightmap uvs for an arbitrary mesh - automatic unwrapping without manual seams - baked ao or probe textures need packed charts - meshes have no secondary uv set for lightmaps ## How it works The mesh is first split into charts by growing regions from seed triangles while checking normal deviation, roundness and the cost of the shared boundary, and merging when beneficial. Each chart is flattened by a least-squares conformal or similar projection, with iterative fixes for overlap and flip. Then the charts are packed using a rasterised approach: each chart is rendered into a bitmap, and a brute-force or block-based placer finds a position and rotation that fits with a chosen padding. The pack is repeated to find a resolution or texel density. The API can return a remapped vertex list so you can keep the original vertex data, and it supports multi-mesh atlases and a user-supplied UV set for reuse. ## When to use it Choose it to generate secondary UVs for baked lightmaps, AO or probe textures on arbitrary meshes in an engine or tool. Prefer [Least Squares Conformal Maps](https://texelatlas.vercel.app/t/lscm-uv-unwrapping.md) on a single artist-seamed chart, [Geometry Images](https://texelatlas.vercel.app/t/geometry-images.md) for single-chart remeshing, and an artist-made UV when texture painting quality matters. ## Cost offline — Seconds for hundreds of thousands of triangles; packing resolution dominates. ## Failure modes - Many small charts and seams produce visible lighting or filtering seams when sampled with bilinear texels - Charts of very different stretch cause uneven texel density - Rejects or produces overlapping charts for non-manifold or degenerate input - Packing efficiency depends on resolution; low settings waste space ## Engine support - godot: builtin — `ArrayMesh.lightmap_unwrap(); scene import option Meshes > Light Baking = Static Lightmaps` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/doc/classes/ArrayMesh.xml, checked 2026-12-01) — Godot bundles xatlas for lightmap UV unwrapping. - unreal: official — `Geometry Script plugin: Auto Generate X Atlas Mesh UVs` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/geometry-scripting-reference-in-unreal-engine, checked 2026-12-01) — Geometry Script is an engine plugin. ## Dataflow - Inputs: mesh - Outputs: uv-atlas - Platforms: cpu, blender, unity, unreal, webgl2 ## Combines with - [Least Squares Conformal Maps](https://texelatlas.vercel.app/t/lscm-uv-unwrapping.md): LSCM is the typical per-chart flattening step inside atlas builders. ## Combination ideas - [Neural-compressed directional lightmaps](https://texelatlas.vercel.app/ideas/neural-compressed-lightmaps/) ## Sources 1. [primary] jpcy (2018) jpcy/xatlas. https://github.com/jpcy/xatlas License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "xatlas." https://texelatlas.vercel.app/t/xatlas/ (accessed 2026-12-01). --- id: "xdog-stylization" title: "XDoG edge and stylization filter" aliases: [extended difference of Gaussians, XDoG, eXtended DoG] domain: "npr" stage: "post" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, unity, unreal, python] year_introduced: 2012 inputs: [ldr-image] outputs: [ldr-image] style: "stylized" dynamic: "both" cost: "cheap" authority: "Winnemöller et al., 2012" url: "https://texelatlas.vercel.app/t/xdog-stylization/" sources_verified_at: "2026-11-29" --- # XDoG edge and stylization filter (Winnemöller et al., 2012) > A tunable difference-of-Gaussians filter with sharpening and a soft threshold. Depending on its parameters it gives pencil lines, ink drawings, tone-separated posterised shapes or hatched looks from any image. ## Reach for it when - want pencil sketch or ink lines from a rendered frame - comic book line art filter that is tunable - need soft thresholded edges from an image - turn a photo into a stylized drawing in one pass ## How it works A difference of Gaussians subtracts two blurs of the image at different scales, which acts as an edge and band-pass detector. XDoG makes it expressive by adding two controls. A sharpening weight `p` amplifies the narrower blur, `D = (1 + p) * G(sigma) - p * G(k * sigma)`, so the response is stronger and more contrasty. A thresholding function then maps D to output: values above an epsilon go to white, values below fall off smoothly with `1 + tanh(phi * (D - eps))`, with `phi` controlling how hard the transition is. Parameters change the character. A large `p` with a low `phi` makes bold pen lines; a large `eps` removes thin detail leaving blobs; a higher sigma gives thick brush-like lines; setting `eps` near zero gives a flat-colour stylisation with outlines. Thresholding can be replaced by a ramp for multi-tone results, as in [posterization](posterization). It runs as two or three separable blur passes plus a pointwise combine. Applying it to luminance, depth or normals gives different line sets. ## When to use it Choose it as a one-pass sketch, ink or comic filter on a rendered frame or photo with tunable thickness and softness. Prefer [screen-space-edge-outline](screen-space-edge-outline) or [jump-flood-outline](jump-flood-outline) for clean silhouette lines driven by depth, normals or object IDs. Prefer [kuwahara-filter](kuwahara-filter) or [anisotropic-kuwahara](anisotropic-kuwahara) for painterly smoothing instead of line art. Prefer [halftone-screen](halftone-screen) or [procedural-cross-hatching](procedural-cross-hatching) for shading-based tonal patterns. Prefer [toon-shading](toon-shading) when stylisation should come from the lighting rather than a post filter. ## Cost cheap — Two separable Gaussian blurs and a combine at screen resolution; larger sigmas cost more taps. Measured GPU Weight: 105.88× baseline (extreme) — 3.4836 ms median / 3.6046 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 83.45× baseline (extreme) — 1.3268 ms median (2.63× faster on L4). Ampere A100 scaling: 79.97× baseline (extreme) — 2.303 ms median (1.51× faster on A100). ## Failure modes - Noise and texture in the source become speckled lines; the image must be smoothed or run on a low-detail channel - Temporal flicker on moving content because thresholds flip pixels between frames - Line width changes with image resolution and scale unless sigma is expressed in resolution-independent units - Thin features vanish when `eps` is high, and flat areas turn pure white or black with extreme `p` - Lines on shading gradients follow lighting rather than geometry, producing contours across smooth surfaces - Colour images need a luminance conversion first; applying it per channel gives rainbow fringes ## Dataflow - Inputs: ldr-image - Outputs: ldr-image - Platforms: webgl2, webgpu, desktop-gpu, unity, unreal, python ## Presets ### XDoG ink look on shaded spheres (glsl-fragment; rendered 2026-11-29) ```json { "sigma": 1.2, "k": 1.6, "p": 20, "eps": 0.3, "phi": 3 } ``` ```glsl // XDoG on a procedural luminance image: sharpened difference of Gaussians, then a soft threshold. const float SIGMA = 1.2; // pixels const float K = 1.6; const float P = 20.0; // sharpening const float EPS = 0.3; // threshold const float PHI = 3.0; // threshold softness float lum(vec2 q) { // q in pixels; shaded spheres on a gradient vec2 uv = q / iResolution.xy; float v = 0.55 + 0.25 * uv.y; vec2 cs[3] = vec2[3](vec2(0.3, 0.45), vec2(0.62, 0.55), vec2(0.5, 0.2)); float rs[3] = float[3](0.2, 0.15, 0.1); for (int i = 0; i < 3; i++) { vec2 d = (uv - cs[i]) / rs[i]; float r2 = dot(d, d); if (r2 < 1.0) { vec3 n = vec3(d, sqrt(1.0 - r2)); v = 0.08 + 0.9 * max(dot(n, normalize(vec3(-0.5, 0.6, 0.6))), 0.0); } } return v; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { float g1 = 0.0, g2 = 0.0, w1 = 0.0, w2 = 0.0; float s1 = SIGMA, s2 = SIGMA * K; for (int j = -5; j <= 5; j++) for (int i = -5; i <= 5; i++) { vec2 o = vec2(float(i), float(j)); float l = lum(fragCoord + o), d2 = dot(o, o); float a = exp(-d2 / (2.0 * s1 * s1)), b = exp(-d2 / (2.0 * s2 * s2)); g1 += a * l; w1 += a; g2 += b * l; w2 += b; } float D = (1.0 + P) * (g1 / w1) - P * (g2 / w2); float T = D >= EPS ? 1.0 : 1.0 + tanh(PHI * (D - EPS)); fragColor = vec4(vec3(T), 1.0); } ``` Attribution: written for this index ## Lineage - extends [Depth/normal Sobel edge outlines](https://texelatlas.vercel.app/t/screen-space-edge-outline.md) ## Combines with - [Kuwahara filter](https://texelatlas.vercel.app/t/kuwahara-filter.md): Smooth the image painterly first, then run XDoG on the result to get clean ink lines over flat regions. - [Posterization](https://texelatlas.vercel.app/t/posterization.md): The soft XDoG threshold can be replaced by tonal quantisation levels for a multi-tone cut-out look. - [Halftone screens](https://texelatlas.vercel.app/t/halftone-screen.md): XDoG line art multiplied with a halftone dot layer gives a comic-print look. ## Sources 1. [primary] Holger Winnemöller, Jan Eric Kyprianidis, Sven C. Olsen (2012) XDoG: An eXtended difference-of-Gaussians compendium including advanced image stylization. Computers & Graphics. https://doi.org/10.1016/j.cag.2012.03.004 (verified via crossref on 2026-11-29) ## Cite this entry Texel. "XDoG edge and stylization filter." https://texelatlas.vercel.app/t/xdog-stylization/ (accessed 2026-12-01). --- id: "xpbd" title: "Extended Position-Based Dynamics" aliases: [Extended PBD] domain: "simulation" stage: "simulation" realtime: "realtime" platforms: [webgl2, webgpu, desktop-gpu, cpu, unity, unreal] year_introduced: 2016 inputs: [particles] outputs: [particles, mesh] style: "both" dynamic: "dynamic" cost: "medium" authority: "Macklin et al., 2016" url: "https://texelatlas.vercel.app/t/xpbd/" sources_verified_at: "2026-11-29" --- # Extended Position-Based Dynamics (Macklin et al., 2016) > Adds a compliance term to position-based constraint solving so stiffness is a real material parameter independent of time step and iteration count, while keeping PBD's stability. ## Reach for it when - cloth stiffness changes with frame rate or iterations - need position-based solver with real material stiffness - want breakable constraints and motors with force readout - position-based dynamics feels time-step dependent - stable soft-body or rope simulation with consistent behaviour ## How it works XPBD derives from implicit Euler with a constraint energy `1/2 C^T alpha^{-1} C`, where `alpha` is inverse stiffness (compliance). It keeps a Lagrange multiplier per constraint across iterations of the same step. Each iteration computes a multiplier increment `dlambda = (-C - alpha~ * lambda) / (grad C M^-1 grad C^T + alpha~)` with `alpha~ = alpha/dt^2`, then applies the position change along the gradient. When compliance is zero it reduces to plain PBD; when it is positive the constraint behaves like a spring whose force converges to the true implicit solution as iterations increase. Since the multiplier is also the constraint force (times dt^2), it can be used to read out forces for e.g. breakable joints. Combined with substepping it is the common modern realtime solver. ## When to use it Choose it when you want PBD's robustness but need consistent stiffness across frame rates, or need constraint forces (breaking, motors). Prefer [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) only for the very simplest cases where one scalar is enough, [Soft Step solver / substepping](https://texelatlas.vercel.app/t/soft-step-solver.md) / substepping for rigid-body-dominant scenes, and [Vertex Block Descent](https://texelatlas.vercel.app/t/vertex-block-descent.md) when you need guaranteed convergence on stiff, high-ratio cloth. ## Cost medium — Same order as PBD plus one multiplier per constraint; usually run with many substeps rather than many iterations. Measured GPU Weight: 145.23× baseline (extreme) — 4.5021 ms median / 4.7383 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 129.82× baseline (extreme) — 2.0641 ms median (2.18× faster on L4). Ampere A100 scaling: 101.55× baseline (extreme) — 2.9245 ms median (1.54× faster on A100). ## Failure modes - Still not exact: very stiff constraints with few iterations remain soft - Large mass ratios converge slowly even with compliance - Damping must be added as a separate constraint-space term or motion looks overly dissipative - Multiplier history makes constraint add/remove mid-step (contacts) slightly fiddly ## Engine support - blender: builtin — `Geometry Nodes > Simulation > XPBD Solver` (evidence: https://docs.blender.org/manual/en/5.2/modeling/geometry_nodes/simulation/xpbd_solver.html, checked 2026-12-01) — For hair, cloth and particles. - godot: builtin — `SoftBody3D with JoltPhysics3D solves soft bodies via Extended Position-Based Dynamics (Jolt SoftBodyMotionProperties)` (evidence: https://github.com/godotengine/godot/blob/4.7.2-stable/modules/jolt_physics/objects/jolt_soft_body_3d.cpp, checked 2026-12-01) - unreal: builtin — `Cloth Panel Node Editor: add XPBD constraints to a Chaos Cloth asset` (evidence: https://dev.epicgames.com/documentation/en-us/unreal-engine/panel-cloth-editor-overview, checked 2026-12-01) — Chaos Cloth; optional XPBD constraint types in the panel cloth editor. ## Dataflow - Inputs: particles - Outputs: particles, mesh - Platforms: webgl2, webgpu, desktop-gpu, cpu, unity, unreal ## Presets ### XPBD — stiff PBD alpha=0 (left) vs compliant XPBD elastic chain & strain heatmap (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_COMPLIANCE": 0.42, "P_GRAVITY": 1, "P_SPEED": 1, "P_SPLIT": 0.48 } ``` ```glsl const float P_COMPLIANCE = 0.42; // P Compliance Alpha [0.0, 1.5, 0.02] const float P_GRAVITY = 1.0; // P Gravity Load [0.2, 2.2, 0.05] const float P_SPEED = 1.0; // P Osc Speed [0.0, 2.5, 0.05] const float P_SPLIT = 0.48; // P PBD / XPBD Split [0.0, 1.0, 0.02] float sdSeg(vec2 p, vec2 a, vec2 b, out float h) { vec2 pa = p - a; vec2 ba = b - a; h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-5), 0.0, 1.0); return length(pa - ba * h); } vec3 strainRamp(float s) { float t = clamp(s, 0.0, 1.0); vec3 c0 = vec3(0.14, 0.62, 0.92); vec3 c1 = vec3(0.18, 0.88, 0.62); vec3 c2 = vec3(0.98, 0.72, 0.16); vec3 c3 = vec3(0.96, 0.24, 0.22); if (t < 0.33) return mix(c0, c1, t * 3.0); if (t < 0.66) return mix(c1, c2, (t - 0.33) * 3.0); return mix(c2, c3, (t - 0.66) * 3.0); } // Compute node position of a 7-node elastic XPBD chain with compliance alpha vec2 xpbdNode(int idx, float alpha, float grav, float t, float xOff) { float fi = float(idx); float restL = 0.105; vec2 anchor = vec2(xOff, 0.36); if (idx == 0) return anchor; // Iterative XPBD equilibrium: dLambda = (-C - alphaTilde * lam) / (wSum + alphaTilde) // Static stretch scales with alphaTilde * loadBelow; dynamic swing scales with compliance float dt = 0.016; float alphaTilde = alpha * 0.0018 / (dt * dt + 1e-5); float wSum = 2.0; float kComp = alphaTilde / (wSum + alphaTilde + 1e-5); float swayPhase = t * (2.15 - 0.55 * kComp); float wind = 0.11 * sin(swayPhase) + 0.045 * sin(swayPhase * 2.3 + 0.8); vec2 pos = anchor; for (int k = 1; k <= 7; k++) { if (k > idx) break; float fk = float(k); float loadBelow = (8.0 - fk) * grav; // XPBD analytical steady-state compliance elongation per link float stretch = restL * (0.018 + 0.24 * kComp * loadBelow * 0.28); float L = restL + stretch; float ang = wind * (0.55 + 0.34 * fk) * (1.0 + 0.65 * kComp) + 0.08 * sin(swayPhase * 1.4 - fk * 0.52) * (0.4 + kComp); pos += vec2(sin(ang), -cos(ang)) * L; } return pos; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float px = 1.0 / max(iResolution.y, 1.0); float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float alphaRight = max(P_COMPLIANCE, 0.0); float grav = clamp(P_GRAVITY, 0.2, 2.5); float t = iTime * max(P_SPEED, 0.0); // Dark engineering blueprint grid vec3 col = mix(vec3(0.028, 0.038, 0.058), vec3(0.055, 0.074, 0.112), smoothstep(-0.5, 0.5, uv.y)); vec2 g1 = abs(fract(uv * 10.0 - 0.5) - 0.5); vec2 g2 = abs(fract(uv * 2.0 - 0.5) - 0.5); col += vec3(0.016, 0.024, 0.038) * smoothstep(0.035, 0.008, min(g1.x, g1.y)); col += vec3(0.028, 0.042, 0.068) * smoothstep(0.014, 0.003, min(g2.x, g2.y)); // Top ceiling beam float dBeam = abs(uv.y - 0.385) - 0.025; col = mix(col, vec3(0.16, 0.20, 0.27), smoothstep(px * 2.0, 0.0, dBeam)); float hatch = smoothstep(0.45, 0.55, sin((uv.x + uv.y) * 90.0)); col = mix(col, vec3(0.24, 0.30, 0.39), smoothstep(px * 2.0, 0.0, dBeam) * hatch * 0.45); // Draw two chains on each side (stiff left alpha=0, compliant right alpha=P_COMPLIANCE) float restL = 0.105; for (int side = 0; side < 2; side++) { bool isRight = (side == 1); float alpha = isRight ? alphaRight : 0.0; float xBase = isRight ? 0.34 : -0.34; float sideMask = isRight ? smoothstep(split - 0.004, split + 0.004, screenX) : smoothstep(split + 0.004, split - 0.004, screenX); // Draw two coupled strands forming a narrow compliant ladder/ribbon for (int strand = 0; strand < 2; strand++) { float dx = (strand == 0) ? -0.095 : 0.095; vec2 prevP = xpbdNode(0, alpha, grav, t + float(strand) * 0.18, xBase + dx); vec2 prevRest = vec2(xBase + dx, 0.36); for (int i = 1; i <= 7; i++) { vec2 curP = xpbdNode(i, alpha, grav, t + float(strand) * 0.18, xBase + dx); vec2 curRest = vec2(xBase + dx, 0.36 - float(i) * restL); // Rest-length ghost guide float hGhost; float dGhost = sdSeg(uv, prevRest, curRest, hGhost); float dash = step(0.5, fract(hGhost * 4.0)); col += vec3(0.16, 0.22, 0.32) * smoothstep(px * 2.2, px * 0.5, dGhost) * dash * 0.45 * sideMask; // Elastic constraint spring segment float hSeg; float dSeg = sdSeg(uv, prevP, curP, hSeg); float segLen = length(curP - prevP); float strain = clamp((segLen - restL) / (restL * 0.38), 0.0, 1.0); vec3 sCol = strainRamp(strain); // Coiled spring wave modulation along the segment vec2 dir = (curP - prevP) / max(segLen, 1e-5); vec2 perp = vec2(-dir.y, dir.x); float coils = sin(hSeg * 6.2831853 * 6.0) * (0.011 - 0.004 * strain); vec2 springPt = mix(prevP, curP, hSeg) + perp * coils * smoothstep(0.0, 0.12, hSeg) * smoothstep(1.0, 0.88, hSeg); float dSpring = length(uv - springPt); float linkCore = smoothstep(0.0085, 0.003, dSeg); float coilGlow = smoothstep(0.007, 0.002, dSpring); col = mix(col, sCol * 1.15, max(linkCore * 0.72, coilGlow * 0.92) * sideMask); // Horizontal shear rung between the two strands if (strand == 1) { vec2 leftP = xpbdNode(i, alpha, grav, t, xBase - 0.095); float hRung; float dRung = sdSeg(uv, leftP, curP, hRung); float rungStrain = clamp(abs(length(curP - leftP) - 0.19) / 0.08, 0.0, 1.0); col = mix(col, strainRamp(rungStrain) * 0.85, smoothstep(0.006, 0.002, dRung) * 0.75 * sideMask); } // Mass node sphere + compliance energy halo float rNode = (i == 7) ? 0.028 : 0.019; float dNode = length(uv - curP); if (dNode < rNode) { vec2 local = (uv - curP) / rNode; float z = sqrt(max(1.0 - dot(local, local), 0.0)); vec3 n = normalize(vec3(local, z)); float diff = max(dot(n, normalize(vec3(0.45, 0.7, 0.6))), 0.0); float spec = pow(max(dot(n, normalize(vec3(0.3, 0.5, 1.0))), 0.0), 32.0); vec3 nodeCol = mix(vec3(0.75, 0.84, 0.96), sCol, 0.45) * (0.35 + 0.75 * diff) + vec3(0.95) * spec * 0.7; col = mix(col, nodeCol, sideMask); } float halo = smoothstep(rNode + 0.016, rNode, dNode) * smoothstep(rNode - 0.002, rNode + 0.004, dNode); col += sCol * halo * (0.35 + 0.65 * strain) * sideMask; prevP = curP; prevRest = curRest; } // Anchor pin float dPin = length(uv - vec2(xBase + dx, 0.36)); col = mix(col, vec3(0.95, 0.82, 0.36), smoothstep(0.018, 0.011, dPin) * sideMask); } } // Split divider line float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.94, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Lineage - extends [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) - supersedes [Position Based Dynamics](https://texelatlas.vercel.app/t/position-based-dynamics.md) - extended by [Vertex Block Descent](https://texelatlas.vercel.app/t/vertex-block-descent.md) ## Combination ideas - [Deformable XPBD soft bodies carved straight from NeuS captures](https://texelatlas.vercel.app/ideas/neus-captured-xpbd-soft-bodies/) ## Sources 1. [primary] Miles Macklin, Matthias Müller, Nuttapong Chentanez (2016) XPBD. Proceedings of the 9th International Conference on Motion in Games. https://doi.org/10.1145/2994258.2994272 (verified via crossref on 2026-11-29) 2. [primary] Miles Macklin, Kier Storey, Michelle Lu, Pierre Terdiman, Nuttapong Chentanez, Stefan Jeschke, Matthias Müller (2019) Small steps in physics simulation. Proceedings of the 18th annual ACM SIGGRAPH/Eurographics Symposium on Computer Animation. https://doi.org/10.1145/3309486.3340247 (verified via crossref on 2026-11-29) 3. [implementation] InteractiveComputerGraphics (2015) InteractiveComputerGraphics/PositionBasedDynamics. https://github.com/InteractiveComputerGraphics/PositionBasedDynamics License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Extended Position-Based Dynamics." https://texelatlas.vercel.app/t/xpbd/ (accessed 2026-12-01). --- id: "zero-1-to-3" title: "Zero-1-to-3" aliases: [Zero123] domain: "genai" stage: "generation" realtime: "interactive" platforms: [cuda, python] year_introduced: 2023 inputs: [ldr-image, camera-poses] outputs: [ldr-image] style: "both" dynamic: "static" cost: "offline" authority: "Liu et al., 2023" url: "https://texelatlas.vercel.app/t/zero-1-to-3/" sources_verified_at: "2026-11-29" --- # Zero-1-to-3 (Liu et al., 2023) > Fine-tunes a large image diffusion model to render an object from a new camera pose given one photo and the relative rotation, giving a 3D-aware prior for single-image reconstruction. ## Reach for it when - see an object from new angles given one image - single photo to novel viewpoint synthesis - need multi-view images for a 3d reconstruction from one view - generate rotated views with camera control ## How it works A pretrained latent diffusion model is fine-tuned on renders of a large synthetic object collection. Its conditioning is the input view plus a relative camera transform (change in polar angle, azimuth, radius), so at inference you ask for "the same object seen from 40 degrees to the left" and receive an image. A single call gives one novel view; to get 3D you either feed the model into a score-distillation loop (optimising a NeRF or SDF so every render agrees with the view-conditioned prior) or run it repeatedly for a ring of cameras and fit a reconstruction. The key idea is that geometry knowledge hidden in web-scale 2D models can be unlocked by explicit camera conditioning. ## When to use it Choose it as a view-conditioned prior when you have exactly one object image and want either a few extra views or an SDS gradient. Prefer [InstantMesh](https://texelatlas.vercel.app/t/instantmesh.md) or [TripoSR](https://texelatlas.vercel.app/t/triposr.md) when you want a mesh in seconds without per-asset optimisation, and [Score Distillation Sampling (DreamFusion)](https://texelatlas.vercel.app/t/score-distillation-sampling.md) with a text prompt when no image exists. ## Cost offline — One diffusion sampling pass per view; full image-to-3D via distillation takes many minutes on a single GPU. Measured GPU Weight: 16.16× baseline (moderate) — 0.5318 ms median / 0.5811 ms p95 on Tesla T4/PCIe/SSE2 @ 1920x1080 (opengl-timer-query). Ada L4 scaling: 15.15× baseline (moderate) — 0.2409 ms median (2.21× faster on L4). Ampere A100 scaling: 10.39× baseline (moderate) — 0.2992 ms median (1.78× faster on A100). ## Failure modes - Views generated independently are not guaranteed multi-view consistent, so fused geometry has seams or flat, blobby shapes - Backs of objects are hallucinated and often generic - Weak on non-centred, cluttered or heavily foreshortened inputs because training renders are centred objects - Identity drift in fine texture and text between views ## Dataflow - Inputs: ldr-image, camera-poses - Outputs: ldr-image - Platforms: cuda, python ## Presets ### Zero-1-to-3 — canonical input view (left) vs pose-conditioned novel view (R,T) synthesis (right) (glsl-fragment; rendered 2026-11-30) ```json { "P_AZIMUTH": 1.15, "P_ELEVATION": 0.35, "P_ORBIT_AUTO": 0.55, "P_SPLIT": 0.46 } ``` ```glsl const float P_AZIMUTH = 1.15; // P Delta Azimuth [0.0, 6.28, 0.05] const float P_ELEVATION = 0.35; // P Delta Elev [-0.6, 0.9, 0.03] const float P_ORBIT_AUTO = 0.55; // P Auto Orbit [0.0, 2.0, 0.05] const float P_SPLIT = 0.46; // P Input / Novel View [0.0, 1.0, 0.02] mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); } 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); } // Asymmetric multi-colored 3D totem/camera-target so novel pose parallax is unmistakably clear! vec2 mapTotem(vec3 p) { vec2 res = vec2(length(p - vec3(0.0, -0.05, 0.0)) - 0.44, 1.0); // main body float nose = sdBox(p - vec3(0.0, 0.02, 0.40), vec3(0.14, 0.12, 0.20)) - 0.03; // front lens/beak if (nose < res.x) res = vec2(nose, 2.0); float wingL = sdBox(p - vec3(-0.46, 0.0, -0.05), vec3(0.14, 0.28, 0.16)) - 0.03; // left cyan fin if (wingL < res.x) res = vec2(wingL, 3.0); float wingR = sdBox(p - vec3(0.46, 0.0, -0.05), vec3(0.14, 0.28, 0.16)) - 0.03; // right amber fin if (wingR < res.x) res = vec2(wingR, 4.0); float crown = length(vec2(length(p.xz) - 0.28, p.y - 0.42)) - 0.09; // top gold ring if (crown < res.x) res = vec2(crown, 5.0); return res; } vec3 calcNormal(vec3 p) { vec2 e = vec2(0.0025, 0.0); return normalize(vec3( mapTotem(p + e.xyy).x - mapTotem(p - e.xyy).x, mapTotem(p + e.yxy).x - mapTotem(p - e.yxy).x, mapTotem(p + e.yyx).x - mapTotem(p - e.yyx).x )); } vec3 renderView(vec2 uv, float az, float el) { vec3 ro = vec3(0.0, 0.0, 2.35); vec3 rd = normalize(vec3(uv, -1.55)); ro.yz = rot2(el) * ro.yz; rd.yz = rot2(el) * rd.yz; ro.xz = rot2(az) * ro.xz; rd.xz = rot2(az) * rd.xz; vec3 bg = mix(vec3(0.032, 0.038, 0.062), vec3(0.075, 0.092, 0.142), smoothstep(-0.55, 0.55, uv.y)); // Subtle equatorial pose-conditioning coordinate ring on y = -0.58 if (rd.y < -0.02) { float tPl = (-0.58 - ro.y) / rd.y; if (tPl > 0.1 && tPl < 6.0) { vec3 hp = ro + rd * tPl; float r = length(hp.xz); float ring = exp(-abs(r - 0.82) * 36.0); float tick = smoothstep(0.06, 0.015, abs(sin(atan(hp.z, hp.x) * 6.0))) * smoothstep(0.10, 0.02, abs(r - 0.82)); bg += vec3(0.24, 0.72, 0.96) * (ring * 0.45 + tick * 0.40); } } float t = 0.0; vec2 hit = vec2(1e5, 0.0); for (int i = 0; i < 52; i++) { vec2 h = mapTotem(ro + rd * t); if (h.x < 0.0025) { hit = vec2(t, h.y); break; } t += h.x; if (t > 5.0) break; } if (hit.x < 1e4) { vec3 p = ro + rd * hit.x; vec3 n = calcNormal(p); vec3 l1 = normalize(vec3(0.55, 0.82, 0.50)); vec3 l2 = normalize(vec3(-0.65, 0.15, -0.55)); float diff1 = max(dot(n, l1), 0.0); float diff2 = max(dot(n, l2), 0.0); float spec = pow(max(dot(n, normalize(l1 - rd)), 0.0), 38.0); float fres = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); vec3 alb = vec3(0.84, 0.86, 0.92); if (hit.y > 1.5 && hit.y < 2.5) alb = vec3(0.95, 0.28, 0.34); else if (hit.y > 2.5 && hit.y < 3.5) alb = vec3(0.14, 0.78, 0.94); else if (hit.y > 3.5 && hit.y < 4.5) alb = vec3(0.98, 0.62, 0.16); else if (hit.y > 4.5) alb = vec3(0.96, 0.84, 0.28); return alb * (0.28 + 0.82 * diff1 + 0.26 * diff2) + vec3(1.0) * spec * 0.45 + vec3(0.32, 0.72, 1.0) * fres * 0.32; } return bg; } vec3 aces(vec3 x) { x = max(x, 0.0); return (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; float screenX = fragCoord.x / max(iResolution.x, 1.0); float split = clamp(P_SPLIT, 0.0, 1.0); float az = P_AZIMUTH + iTime * max(P_ORBIT_AUTO, 0.0) * 0.65; float el = clamp(P_ELEVATION, -0.7, 0.95); vec3 col; if (screenX < split) { // Left: Fixed single canonical input view (az=0, el=0.12) vec2 uvL = uv + vec2(0.24, 0.0); col = renderView(uvL, 0.0, 0.12); } else { // Right: Pose-conditioned novel view synthesized at (R(az, el), T) vec2 uvR = uv - vec2(0.24, 0.0); col = renderView(uvR, az, el); } float sep = smoothstep(0.0035, 0.0008, abs(screenX - split)); col = mix(col, vec3(0.95, 0.97, 1.0), sep); fragColor = vec4(pow(clamp(aces(col), 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); } ``` Attribution: MIT — written for this index. ## Sources 1. [primary] Ruoshi Liu, Rundi Wu, Basile Van Hoorick, Pavel Tokmakov, Sergey Zakharov, Carl Vondrick (2023) Zero-1-to-3: Zero-shot One Image to 3D Object. arXiv preprint (cs.CV). https://arxiv.org/abs/2303.11328 (verified via arxiv on 2026-11-29) 2. [primary] Ruoshi Liu, Rundi Wu, Basile Van Hoorick, Pavel Tokmakov, Sergey Zakharov, Carl Vondrick (2023) Zero-1-to-3: Zero-shot One Image to 3D Object. 2023 IEEE/CVF International Conference on Computer Vision (ICCV). https://doi.org/10.1109/iccv51070.2023.00853 (verified via crossref on 2026-11-29) 3. [implementation] cvlab-columbia (2023) cvlab-columbia/zero123. https://github.com/cvlab-columbia/zero123 License: MIT. (verified via github on 2026-11-29) ## Cite this entry Texel. "Zero-1-to-3." https://texelatlas.vercel.app/t/zero-1-to-3/ (accessed 2026-12-01).