Introduction
Raymarching is an advanced rendering technique used to create procedural surfaces, fractals, and volumetric effects. Unlike traditional ray tracing, which calculates ray intersections with polygons, raymarching steps through space using a mathematical function known as a Signed Distance Field (SDF) to determine the closest surface.
This article explains how to implement raymarching in Three.js using GLSL shaders.
What is Raymarching?
Instead of directly calculating intersections, raymarching:
- Casts a ray from the camera into the scene.
- Steps forward along the ray using the SDF value.
- If the distance is small enough, the ray has hit a surface.
- If no object is found, the ray continues marching until a maximum distance is reached.
What Are Signed Distance Fields (SDFs)?
An SDF function defines a shape implicitly by returning the shortest distance from any point in space to the nearest surface.
For example, the SDF of a sphere at (0,0,0) with radius r is:
- distance=x2+y2+z2−rtext{distance} = sqrt{x^2 + y^2 + z^2} – rIf
distance < 0, the point is inside the object. - If
distance = 0, the point is on the surface. - If
distance > 0, the point is outside the object.
Common SDFs
// Sphere SDF
float sphereSDF(vec3 p, float r) {
return length(p) - r;
}
// Box SDF
float boxSDF(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);
}
// Torus SDF
float torusSDF(vec3 p, vec2 t) {
vec2 q = vec2(length(p.xz) - t.x, p.y);
return length(q) - t.y;
}