TExcelTAD
Home › Shaders & Graphics Programming › Normal Estimation

Normal Estimation

Every lighting model in the next lessons needs the surface normal: the unit vector pointing straight out of the surface at the point you hit. Triangle meshes store normals per vertex, and the rasterizer interpolates them. A raymarched SDF has no vertices, but it has something better: the SDF's gradient. Distance grows fastest in the direction pointing away from the surface, so the gradient of the SDF is the normal (after normalizing).

The gradient by central differences

We can't differentiate map symbolically inside a shader, so we sample it. Nudge the point a tiny e along each axis, both ways, and measure how the distance changes:

text
n.x = map(p + (e,0,0)) - map(p - (e,0,0))
n.y = map(p + (0,e,0)) - map(p - (0,e,0))
n.z = map(p + (0,0,e)) - map(p - (0,0,e))
normal = normalize(n)

That is 6 extra map calls per pixel. A sphere has a known normal (normalize(p - center)), so we can check the estimate in JavaScript, together with a cheaper variant that uses only 4 samples at the corners of a tetrahedron:

js · try it yourself
const center = [0, 1, 0];
const map = (p) => Math.hypot(p[0] - center[0], p[1] - center[1], p[2] - center[2]) - 1;
const norm = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
const add = (a, b, s = 1) => a.map((c, i) => c + b[i] * s);

function centralDiff(p, e) {
  return norm([
    map(add(p, [e, 0, 0])) - map(add(p, [-e, 0, 0])),
    map(add(p, [0, e, 0])) - map(add(p, [0, -e, 0])),
    map(add(p, [0, 0, e])) - map(add(p, [0, 0, -e])),
  ]);
}

function tetrahedron(p, e) {
  const ks = [[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]];
  let n = [0, 0, 0];
  for (const k of ks) n = add(n, k, map(add(p, k, e)));      // sum of k * map(p + k*e)
  return norm(n);
}

const p = norm([0.3, 0.8, -0.52]).map((c, i) => c + center[i]);   // a point on the sphere
const exact = norm(add(p, center, -1));
const fmt = (v) => v.map((c) => c.toFixed(5)).join(', ');
console.log('exact        ', fmt(exact));
console.log('central e=1e-3', fmt(centralDiff(p, 1e-3)));
console.log('tetra   e=1e-3', fmt(tetrahedron(p, 1e-3)));
console.log('central e=0.5 ', fmt(centralDiff(p, 0.5)));
exact         0.29994, 0.79984, -0.51990
central e=1e-3 0.29994, 0.79984, -0.51990
tetra   e=1e-3 0.30024, 0.79970, -0.51994
central e=0.5  0.28837, 0.81177, -0.50781

With a small e, central differences match the exact normal to five digits, and the tetrahedron is off by about 0.0003: slightly less accurate, invisible on screen, and a third cheaper. With a large e they blur: the normal starts to average over a region, which rounds sharp edges. That can be a feature (soft-looking edges) but usually you want e around 0.001 times your scene scale.

Normals in the shader

Here is the tetrahedron version in GLSL. The scene is shaded with its normal mapped to color, n * 0.5 + 0.5, the standard way to see normals: surfaces facing +X turn red, +Y green, +Z blue. The ground faces up, so it is light green everywhere.

glsl · try it yourself
float map(vec3 p) {
    float sphere = length(p - vec3(0.0, 1.0, 0.0)) - 1.0;
    vec3 q = abs(p - vec3(2.3, 0.7, 0.5)) - vec3(0.6);
    float box = length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);
    return min(min(sphere, box), p.y);
}

vec3 calcNormal(vec3 p) {
    const float e = 0.001;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(k.xyy * map(p + k.xyy * e) +
                     k.yyx * map(p + k.yyx * e) +
                     k.yxy * map(p + k.yxy * e) +
                     k.xxx * map(p + k.xxx * e));
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    vec3 ro = vec3(1.0 + sin(iTime * 0.5), 2.0, -4.5);
    vec3 rd = normalize(vec3(uv, 1.6) + vec3(0.0, -0.25, 0.0));

    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 > 40.0) break;
    }

    vec3 color = vec3(0.1);
    if (hit) {
        vec3 n = calcNormal(ro + rd * t);
        color = n * 0.5 + 0.5;                      // visualize: -1..1 -> 0..1
    }
    fragColor = vec4(color, 1.0);
}

The k.xyy, k.yyx … swizzles spell the four tetrahedron corners (1,-1,-1), (-1,-1,1), (-1,1,-1) and (1,1,1), exactly as in the JavaScript.

Seeing the cost

Normal estimation runs map 4 more times, but only once per pixel, after the march. The march itself may call map 50–100 times, so the normal adds a few percent. What does cost is calling calcNormal inside the loop by accident, or estimating normals for every light separately. Compute the normal once and reuse it.

When the normal is wrong

Shading artifacts in raymarched scenes usually come from one of three places, and the normal view above is the fastest way to tell them apart:

Symptom in the normal view Cause Fix
Speckled noise on surfaces the hit point is not on the surface (march stopped early at t > max or the iteration limit) treat those pixels as misses; raise the iteration limit
Black or flashing pixels normalize(vec3(0)): the gradient is zero, usually exactly on a crease or inside a shape add a tiny bias, or step back along the ray before sampling
Faceted, blocky edges e too large for the detail scale e with distance: e = 0.0005 * t
Banding on the ground near the horizon float precision at large t limit the march distance, add fog

Tip: For simple primitives you can return analytic normals (normalize(p - center) for a sphere, vec3(0, 1, 0) for the ground). They are exact and free, but you need to know which object was hit. The mini project returns a material id from map for exactly that reason.

Normals on meshes

For triangle meshes, normals come from the vertex buffer, and two rules from rasterization carry over:

  • Re-normalize in the fragment shader. Interpolating three unit vectors produces a shorter vector in the middle of the triangle; normalize(vNormal) fixes it.
  • Transform normals with the normal matrix, the inverse-transpose of the model matrix, not the model matrix itself. A non-uniform scale otherwise tilts them. Matrices in Shaders shows why.

Test yourself

Why is the gradient of an SDF the surface normal?

  1. Because SDFs store normals
  2. Distance increases fastest in the direction pointing straight away from the surface
  3. Because the gradient is always (0,1,0)
  4. It is only an approximation for spheres

How many extra map evaluations does the tetrahedron technique need?

  1. 2
  2. 4
  3. 6
  4. 8

What does the color n * 0.5 + 0.5 show for a surface whose normal is (0, 1, 0)?

  1. Black
  2. Pure green
  3. Light green (0.5, 1.0, 0.5)
  4. White