Evan Wallace

GLSL Path Tracing

Download for Mac OS X 10.6

How to use

This program allows you to edit simple 3D scenes that are realistically lit while you edit. But simple means really simple—you get twenty or so objects (depending on your graphics card) that can only be spheres and cubes. It's not meant to be useful, it's just an experiment with lighting and shaders.

The entire scene is dynamically compiled into a GLSL shader. Everything can be repositioned in real-time, but any geometry or material change means a recompilation. The compiler supports three material types: diffuse, reflective, and glossy.

To calculate a pixel color, a ray is shot into the scene and allowed to bounce around five times. At each bounce, the direct light incoming at that point (including shadows) is multiplied by all previous material colors and accumulated. Soft shadows are achieved by randomly jittering the light position per-pixel. The basic code looks like this:

vec3 ray = initialRay;
vec3 origin = intitialOrigin;

vec3 colorMask = vec3(1.0);
vec3 accumulatedColor = vec3(0.0);

for(int bounce = 0; bounce < 5; bounce++)
{
  float t = /* compute t from objects */;
  vec3 hit = origin + ray * t;

  vec3 materialColor = /* compute material color from hit */;
  float directLighting = /* compute direct lighting from hit */;

  // accumulate incoming light
  colorMask *= materialColor;
  accumulatedColor += colorMask * directLighting;

  ray = /* compute next ray */;
  origin = hit;
}

gl_FragColor = accumulatedColor;

This is known as path tracing because you are tracing possible paths that light followed through the scene to reach each pixel. The scene is continually rendered and averaged with previous results, so the longer you wait the more paths are followed and the less noisy the result gets.