Ray tracing is known for producing stunning reflections, we can achieve the same effect using ray
marching. In this post, we’ll walk through a classic two-sphere reflective scene, but instead of traditional ray
tracing, we’ll ray march our way to stunning reflections.
The first step is defining a scene with two spheres and a ground plane. In ray marching, objects are defined using
signed distance functions (SDFs). Our scene SDF is just a combination of smaller SDFs.
SDFs
The SDF for a sphere gives us the distance from any point to the surface of the sphere:
The SDF for a ground plane:
Finally, we combine the objects into a scene SDF:
Raymarching
Now we trace a ray through our scene using ray marching.
Surface Normals
For lighting and reflections, we need surface normals. These are estimated using small offsets in each direction:
Reflections
Reflections are computed using the reflect function:
\[R = I - 2 (N \cdot I) N\]
where:
\(I\) is the incoming ray direction,
\(N\) is the surface normal,
\(R\) is the reflected ray.
In GLSL, this is done using:
Now, we ray march again along the reflected direction:
Full Shader
Running this shader, you should see two very reflective spheres reflecting each other.
Conclusion
With just a few functions, we’ve recreated a classic ray tracing scene using ray marching. This technique allows
us to:
Render reflective surfaces without traditional ray tracing
Generate soft shadows using SDF normals
Extend the method for refraction and more complex materials