ray-marching-sdf-shaders.md
Ray Marching and Signed Distance Fields
Render infinite geometry on a fullscreen triangle SDFs, sphere tracing, and the shader loop that replaced polygon soup.
- Shaders
- WebGL
- Graphics
Polygon rasterization won the real-time race for decades. But in shader land, a fullscreen quad and a for loop can render infinite detail no meshes, no UV unwrapping, no LOD chains.
The setup
Cast a ray from the camera through each pixel. Step along the ray until you hit a surface. That's ray marching but naive stepping is slow.
Sphere tracing uses signed distance functions (SDFs): at any point in space, the SDF returns the distance to the nearest surface. You can safely advance by that distance without overshooting.
float map(vec3 p) {
float sphere = length(p) - 1.0;
float box = sdBox(p - vec3(2,0,0), vec3(0.5));
return min(sphere, box);
}
float rayMarch(vec3 ro, vec3 rd) {
float t = 0.0;
for (int i = 0; i < 128; i++) {
vec3 p = ro + rd * t;
float d = map(p);
if (d < 0.001) return t;
t += d;
if (t > 100.0) break;
}
return -1.0;
}Primitive SDFs
| Shape | SDF |
|---|---|
| Sphere | length(p) - r |
| Box | length(max(abs(p)-b, 0)) |
| Torus | complex but closed-form |
CSG operations combine shapes with min (union), max (intersection), and smooth variants.
Normals and lighting
No vertex normals exist estimate via gradient:
vec3 calcNormal(vec3 p) {
vec2 e = vec2(0.001, 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)
));
}Then standard Phong/Blinn lighting applies.
Where it shines
- Demoscene and ShaderToy art
- Procedural planets and terrain
- UI effects and transitions
- Teaching 3D math without engine overhead
The tradeoff
Ray marching is CPU/GPU brute force. Modern games hybridize SDFs for volumetrics, meshes for characters. But understanding SDFs unlocks a different way to think about geometry entirely.
Related
Continue reading
More notes on similar topics.
How Ken Perlin's gradient noise creates infinite terrain, clouds, and fire and why Simplex improved it thirty years later.
- Graphics
- Algorithms
The horse is doing the running. You're still the one who has to stay balanced, read the terrain, and not fall off. That's the whole difference between vibe coding and actually directing the thing.
- AI Engineering
- Vibe Coding
The Day the Facility Guy Shipped a Feature to My App
July 29, 2026
I taught our building's maintenance guy how to vibe code for fun. Twenty minutes later he'd chatted his way into a working feature inside one of my real apps. Here's what actually happened, and why it didn't disprove anything I've written in this series.
- AI Engineering
- Vibe Coding