LJYC

Ray Tracer2022

A CPU path tracer written with reference to the first two books of Ray Tracing in One Weekend.

When I started learning computer graphics in 2022, I wrote this CPU path tracer in C++ with reference to the first two books of Ray Tracing in One Weekend, reorganizing the structure as I went. Once the basic scenes were running, I ran into two concrete problems while trying to build scenes of my own: when a ray is trapped inside a glass sphere, cutting it off at a fixed 50 bounces wastes a good deal of computation; and when I put in a fairly bright light of my own, pixel values computed above 255 smear into a patch of pure white in the final image.

Around these two problems I made two changes: Russian roulette in place of the fixed bounce limit, and ACES tone mapping for over-bright highlights. Along the way I looked at how image quality and cost actually changed afterwards.

Small colored spheres all over the ground, with three large spheres side by side in the middle: a blue-violet diffuse sphere, a glass sphere and a metal sphere; the sky is a very pale blue

Rendered by this program: 1080 × 720, 1000 samples per pixel.

Chapter 1

Real-time path tracing and how sampling converges

The basic process of path tracing is to shoot rays from the camera through each pixel; when a ray hits a surface it scatters randomly according to the material, until it reaches the sky or a light, and the color attenuation along the way is then multiplied back. A single ray is only one random estimate with a large error; the more rays a pixel shoots and averages, the more the noise in the image fades. The cover image at the top of the page is the result of 1000 samples per pixel.

This is a precomputed image. Once you click, it is computed from scratch, live, on your computer.

Not started

Scene

Russian roulette

When off, a ray stops after 50 bounces. When on, every bounce has a one-in-ten chance of ending the path; the survivors make up the lost brightness, and there is also a cap on the number of bounces.

Rays that hit something bounced … times on average

ACES

When a light is too bright, pixel values overshoot the displayable range. ACES pulls the overly bright parts back, so the highlights keep their gradations.

Noise remaining

The horizontal axis is the number of samples per pixel and the vertical axis is the noise left in the image, both on log scales. The dashed line shows noise falling in inverse proportion to the square root of the sample count.

The solid line is measured in your browser; the dashed line is where four times the samples halves the noise.

Click the canvas above and it computes in real time from scratch in your browser; the curve on the right takes the difference between the average of the odd samples and the average of the even samples, as a live measure of the noise left in the image. By the Monte Carlo convergence rule, noise is inversely proportional to the square root of the number of samples: four times the samples roughly halves the noise. You can switch between the three scenes and flip the Russian roulette and ACES switches to compare directly with what the next two chapters describe.

Chapter 2

Russian roulette and firefly noise

The original tutorial cuts off at a fixed depth: a ray stops recursing after 50 bounces. I changed this step to Russian roulette: each time the ray hits an object, the path is ended early with probability 1 − p; if the path survives, the returned color is divided by the survival probability p, to make up for the energy of the paths that were cut off early and keep the overall brightness unbiased.

To keep a very small number of paths from bouncing too deep, I also computed a recursion cap, ⌈ln 0.001 / ln p⌉, from the rule that “the probability of a path surviving n bounces in a row has just dropped below 0.1%” (implemented in Camera::calculateColor, with the cap stored as rr_recursion_upper). The first version uses p = 0.9, giving a cap of 66 bounces; the second uses p = 0.95, giving 135.

The horizontal axis is the number of bounces; the vertical axis is the probability that a path trapped in the scene, never reaching the sky, is still alive. The gray line is the fixed cutoff: alive for the first 50 bounces, all stopped at the 50th. The blue line is the roulette: multiplied by p at each bounce, up to the cap.

The first version of the code uses 0.9 and the second 0.95.

Cap
66 bouncesFixed cutoff: 50 bounces
Trapped path, on average
9.0 bouncesFixed cutoff: 50 bounces
Weight boost at the cap
1047 timesFixed cutoff: no boost
Drawn from the formula in the code; drag p to see how the cap and the cost change. Because the cap is set at 0.1%, a path that survives to the cap is scaled up roughly a thousandfold, whatever p is.
Three spheres on yellow-green ground: a glass sphere on the left covered in tiny bright specks, a blue diffuse sphere in the middle and a fuzzy gold metal sphere on the right
Three spheres, rendered by this program with p = 0.9 and enlarged three times in raw pixels.

With the roulette, paths trapped in the scene drop from a fixed 50 bounces to about 9 on average at p = 0.9, a clear reduction in computation. The cost that comes with it is higher variance: every extra bounce a path survives divides its weight by p once more, and a path that lives to the 66-bounce cap has its weight scaled up about 1047 times. Among the three enlarged spheres on the left, the glass material absorbs almost no energy, so paths survive inside it for a long time, and the accumulated weight produces 198 over-bright pixels above 255, reaching 620: the familiar firefly noise. Switch back to “Three spheres” in the demo above to see the trade-off between bounce count and noise for yourself.

Chapter 3

Highlight overflow and ACES tone mapping

Black background, a sphere on a whitish marble floor, with the glowing numbers 20 and 22 on the left and right
zen as rendered by this program, with no tone mapping.

The physical brightness path tracing computes has no upper limit, while a display can only express the range 0 to 1 (0 to 255 when written into an 8-bit image). Converting high-dynamic-range brightness into the displayable range is what tone mapping is.

I built a scene of my own called zen: a spherical light of brightness 4 above a black background, lighting a marble-textured sphere and ground. Without tone mapping, the program writes values above 255 straight into the plain-text PPM file; after the four glowing digits “20 22” were added, 3,721 pixels in the image exceeded 255, with a maximum of 511, and when converted to PNG a large area of the ground under the light was hard-clipped to pure white.

In the same commit I added Krzysztof Narkowicz’s ACES fit: brightness is first multiplied by 0.6, then mapped through a curve that gently approaches 1. The brighter the input, the more slowly the curve rises, and it still has not topped out at a brightness of 8, so the gradation from bright to dark on the ground under the light is preserved.

The horizontal axis is the computed brightness, from 0 to 8; the vertical axis is the value before it is written to the image, from 0 to 1. The gray line is plain clamping: everything past 1 becomes 1. The blue line is ACES, which approaches 1 more slowly the brighter the input.
Horizontal axis: the computed brightness; vertical axis: the value before it is written to the image. Plain clamping turns everything past 1 white; ACES still hasn’t reached 1 at 8.
Plain clamping: a large patch of pure white on the ground under the light Through ACES: the ground under the light still shades from bright to dark Clamp ACES
The same computed result is clamped on the left and passed through ACES on the right. Drag the center line to compare.

Chapter 4

The six steps of a single ray, debugging Perlin noise, and the renders

Six steps of a single ray

A camera, a column of pixels, the ground, a diffuse sphere and a glass sphere; a ray leaves the camera, bounces once off the ground and once off a sphere, then flies into the sky Bounding boxes: this ray misses them, so the spheres inside are skipped Pixel column Image plane, camera’s view This ray: row 3, cell 6 Three rays, one cell Camera The nearest hit is on the ground Normal + a random point in the unit sphere Stop: 1 − p chance Continue: result ÷ p Hits the sky: color = sky × ground albedo × sphere albedo ÷ p² Average N ACES √ (gamma 2) × 255.99 into PPM

In the diagram: the camera · one cell on the image plane · three rays through the same cell

In the diagram: the dashed boxes are bounding boxes, which this ray misses · the nearest hit is on the ground

In the diagram: the normal plus a random point in the unit sphere (dashed circle) gives the new direction

In the diagram: red dashed line, stop with probability 1 − p · blue line, continue with the result ÷ p

In the diagram: the ray hits the sky; the color it brings back = sky × ground albedo × sphere albedo ÷ p²

In the diagram: average N samples → ACES → square root (gamma 2) → × 255.99 into PPM

The camera shoots N rays per pixel, each offset a little at random within the pixel; averaged together, they leave no jagged edges on objects. The camera can be positioned and its field of view adjusted, and it has thin-lens depth of field.

The scene is first built into a BVH (bounding volume hierarchy): pick a random axis, split the objects in half by count, and pack them into bounding boxes level by level. A ray is tested against the boxes first, and every object inside a box it misses is skipped. The nearest hit is stored in the ray object, and later objects overwrite it only when their intersection is closer.

The material decides where the ray bounces. Diffuse picks a random point in the unit sphere and adds it to the normal as a vector; metal reflects like a mirror, plus a little fuzz; glass refracts by Snell’s law, and a probability from Schlick’s approximation decides between reflection and refraction.

Each time the ray hits something, the roulette spins once: the path ends here with probability 1 − p, and a surviving path divides its result by p. In the second version of the code, p is 0.95.

A path only gets light when it hits the sky or an emissive object; the attenuations along the way, multiplied together, are the color the ray brings back. For a diffuse surface the attenuation is its albedo, that is, how much light it reflects.

The N results for a pixel are averaged, passed through ACES, square-rooted for gamma 2, multiplied by 255.99, truncated to integers and written into an ASCII PPM.

The interactive diagram above breaks down, in the order of the code, how one ray becomes a pixel: the camera, with thin-lens depth of field and random jitter inside the pixel, shoots the ray; a BVH (bounding volume hierarchy) skips the regions the ray cannot hit to intersect it with the scene; a scatter direction is computed for diffuse, metal or glass (Snell refraction with the Schlick approximation); the roulette decides whether to continue or stop; on hitting the sky or an emitter, the albedos along the way are multiplied together to get light; finally the N samples are averaged, passed in turn through ACES, a square root for gamma 2 and a multiplication by 255.99 truncated to an integer, and written to an ASCII PPM image.

A Perlin noise debugging note

When implementing Perlin noise (a smooth random function whose output can be positive or negative), I at first left out the step that maps it into the [0, 1] range and used the raw return value directly. As a result, 8,971 of the twenty thousand pixels were written as −2147483648, most likely because negative values went into the gamma square root before output and became NaN, which then overflowed when converted to an integer. Only after I took the absolute value of the interpolated result did I get a proper marble texture, and I left a comment beside the code as a record of the mistake.

textbook:: return acc, however, my result shows some errors.

A broken Perlin noise render: a dark sphere and ground with large patches of pure black
The broken one Mark broken pixels
The fixed marble noise: gray-and-white marble veins on the sphere and the ground
The marble after the fix

Other features and renders

Beyond basic spheres and the sky, the program also implements five kinds of texture (solid color, 3D checker, marble, the uninterpolated block noise Bedrock, and image textures loaded with stb_image), rectangle lights, instance proxies for translating, rotating and flipping normals, and a volume material for constant-density smoke. The Cornell box, the smoke box and the pseudo Cornell box built from five large spheres in the gallery below were all rendered by this program.