🎨 Ray Marching — SDF Scene Rendering

CPU ray marching · SDF primitives · Smooth-min blending · Phong shading · Soft shadows · AO

Preset

Scene

Lighting

Soft shadows
Ambient occlusion

Stats

Render time
Avg ray steps
Buffer160×120 → 640×480

Drag canvas to orbit camera. Rendering runs on CPU in a 160×120 offscreen buffer.

🎨 Ray Marching & Signed Distance Functions

Ray marching is a rendering technique where camera rays advance step by step through a scene described entirely by mathematical distance functions — no polygons, no meshes. Each step size equals the minimum distance to any surface, guaranteeing safety. When that distance drops below a threshold the ray has hit a surface. This implementation runs entirely on the CPU, writing pixels into a 160×120 ImageData buffer that is scaled 4× to 640×480 — making real-time CPU ray marching feasible at 15–20 FPS.

Physics & Math

Ray march: advance t += SDF(origin + t⋅dir) until SDF < 0.001. Sphere SDF = |p| − r. Box SDF uses the sdBox formula. Torus: |vec2(length(p.xz) − R, p.y)| − r. smin(a,b,k) produces the smooth union. Normals are estimated via finite differences of the SDF gradient. Phong shading: ambient + diffuse⋅max(0, n⋅L) + specular⋅(R⋅V)^n. Soft shadows march toward the light accumulating a penumbra factor from SDF clearance.

How to Use

Drag the canvas to orbit the camera. Choose a preset to load a different scene composition. Adjust FOV (30–90°), sphere radius, smooth-min blend factor k, and light direction X. Toggle soft shadows and ambient occlusion on or off. Enable Normals view to visualise the normal map directly. Stats show per-frame CPU render time and average ray steps per pixel.

Did You Know?

Smooth-min (smin) was popularised by Inigo Quilez as a way to blend SDF primitives into organic, continuous shapes — the boundary between two objects dissolves into a soft fillet. By tuning the blend factor k you control how wide the merge zone is: k=0 is a hard union, large k creates a broad mushroom-cap blend. The same primitive combination used here — sphere, box and torus — appears in nearly every introductory ray marching tutorial because it covers the full range of basic SDF maths.