Lighting a Ray-Marched SDF
A distance field supplies a scalar but lighting needs orientation. Sample on both sides of x/y/z to estimate its gradient, then normalize. An RGB normal view is an intermediate diagnostic; establish continuous orientations before tuning diffuse or specular lighting.
Fix the problem and environment
A distance field supplies a scalar but lighting needs orientation. Sample on both sides of x/y/z to estimate its gradient, then normalize. An RGB normal view is an intermediate diagnostic; establish continuous orientations before tuning diffuse or specular lighting.
The controlling code
vec3 normalAt(vec3 p){
vec2 e=vec2(0.002,0.0);
return normalize(vec3(
scene(p+e.xyy)-scene(p-e.xyy),
scene(p+e.yxy)-scene(p-e.yxy),
scene(p+e.yyx)-scene(p-e.yyx)));
}
vec3 n=normalAt(hitPoint);
float diffuse=max(dot(n,normalize(lightDirection)),0.0);
Verify in order
Compare the sphere normal view with its shaded view, then halve or double finite-difference epsilon. Differentiate the final combined field for CSG so carved walls receive the right normals.
Scope and common mistakes
Tiny epsilon amplifies floating-point error; large epsilon smooths small features. Normalize the gradient and evaluate it only at actual surface hits.