GLSL Sphere Signed Distance Function SDF
This article provides a concise guide to the Signed Distance Function (SDF) for a sphere using the OpenGL Shading Language (GLSL). It covers the fundamental mathematical equation behind the sphere distance field, demonstrates standard GLSL implementations for centered and offset spheres, and explains how to interpret the resulting distance values in raymarching applications.
Mathematical Formulation
A Signed Distance Function returns the shortest distance from a given point in space to the surface of a shape. For a sphere centered at the origin with radius \(r\), the distance from an arbitrary point \(p\) to the sphere's surface is calculated as the Euclidean length of \(p\) minus the radius \(r\):
\[f(p) = |p| - r\]
The sign of the returned value indicates the spatial relationship of the point relative to the sphere:
- Negative (\(d < 0\)): The point is inside the sphere.
- Zero (\(d = 0\)): The point lies exactly on the surface of the sphere.
- Positive (\(d > 0\)): The point is outside the sphere.
GLSL Implementation
In GLSL, the Euclidean norm of a vector is calculated using the
built-in length() function.
Sphere Centered at the Origin
When the sphere is positioned at coordinate
(0.0, 0.0, 0.0), the function requires only the sample
point p and the radius r:
float sdSphere(vec3 p, float r) {
return length(p) - r;
}Sphere with an Arbitrary Center
To position the sphere anywhere in 3D space, subtract the sphere's
center position c from the sampling point p
before computing the vector length:
float sdSphere(vec3 p, vec3 c, float r) {
return length(p - c) - r;
}Alternatively, you can translate the coordinate space externally by
passing p - c directly into the origin-centered
function:
vec3 sphereCenter = vec3(0.0, 1.0, -3.0);
float sphereRadius = 1.0;
float distance = sdSphere(p - sphereCenter, sphereRadius);Performance and Usage in Raymarching
The sphere SDF is the computationally cheapest 3D distance estimator
in computer graphics, requiring only a dot product, square root
(contained inside length()), and subtraction. In a standard
sphere-tracing or raymarching loop, the returned distance dictates the
maximum step size the ray can safely advance along its direction vector
without intersecting or overshooting geometry.