← All writing Doom 3 Path Tracing

Refactoring Doom 3's Path Tracer: CUDA, OpenCL, and Renderer Correctness

A renderer case study covering the CUDA-to-OpenCL port, tree construction, Doom 3 material stages, and a controlled denoiser comparison.

In the first version, Doom 3’s render backend handed its draw surfaces and lights directly to a CUDA renderer. That was enough to play the game, but the code that interpreted a Doom 3 material was tied to the code that uploaded it to the GPU. A second compute backend would either have to duplicate that interpretation or share it somewhere above the device code.

I used CUDA as the reference implementation: first get it running behind the new interface, then port the device pipeline to OpenCL without duplicating scene extraction. I handed the refactor itself to AI agents, which also did most of the work on material rendering. The first implementation was roughly 70% my effort and 30% AI; across the refactor and follow-up work, I’d reverse those numbers. Those are estimates of effort, not measurements.


Splitting Scene Extraction from GPU Execution

On pt-refactor, renderer_pt takes over the engine-facing work. It flattens draw surfaces into triangles, evaluates material stages and light parameters, and collects pending textures in idPathTracerScene. The idPathTracerBackend interface then separates scene data from the parameters used to render a view:

UploadScene(idPathTracerScene)   -> upload scene data and rebuild the linear BVH (LBVH)
Render(ptRenderParams_t)         -> trace, accumulate, optionally denoise, tone-map
ReadPixels(dest, width, height)  -> copy the finished RGBA8 image for presentation

The backend owns device buffers and two distinct kinds of history: the raw running mean and the denoiser’s reprojectable history. ResetAccumulation(false) clears the mean without discarding the latter. That distinction matters when the camera moves: old samples no longer belong in the same pixel’s running mean, but the denoiser can still try to find the corresponding surface in the previous view.

I got CUDA working behind this interface before starting the OpenCL 1.2 port. The second backend came together much faster than I expected: the agent had working CUDA kernels to compare against and didn’t have to touch the engine integration. Most of the pipeline carried over in the same order, but a few stages needed different implementations:

Stage CUDA OpenCL 1.2
Texture storage Device pointers to texels One texel pool with descriptors locating each texture
Morton-key sort CUB radix sort Stable least-significant-digit radix sort
BVH bounds __threadfence() before the atomic parent signal Publish bounds through atomics across work-groups

The OpenCL backend checks shared struct layouts at startup. The LBVH test checks the sort order against std::stable_sort, compares child indices with a CPU reference, and follows escape links to verify that each triangle is reachable exactly once. Those checks don’t establish image parity. On an Intel device, for example, tan(pi/4) returned the next representable float above 1.0, shifting SVGF reprojection off the expected pixel grid. For a 90° field of view, computing the half-angle tangent as tanpi(90 / 360.0) gives exactly 1.0.

Tracing Rays Through the BVH

For a shadow ray, an eligible opaque hit can terminate traversal immediately; there’s no need to find the closest triangle. An alpha-tested hit still has to sample the cutout before it can count as a blocker. The CUDA pass that introduced this also replaced per-pixel curand_init with PCG and moved Morton-key sorting from Thrust to CUB with persistent scratch storage.

Together, the changes nearly halved the time it took to render a frame: from 74 to 39 milliseconds in one alphalabs1 run at 320 × 240. That run doesn’t tell us how much of the gain came from shadow traversal alone.

A later pass removed traversal stacks. Each node gained an escape link to the next node outside its subtree. On a miss, the ray follows that link, skipping every descendant without having to push and pop pending nodes.

The LBVH bug was in tree construction, not traversal. The smallest example is a scene with three triangles. After sorting them by Morton code, the root should cover indices 0 through 2. The builder first doubles a search bound until it’s beyond the range, then works back down in powers of two to find the last index. Here the bound normally reaches 4, so the second search starts by trying a step of 2. An old safety clamp cut the bound back to 3, leaving the second search with only a step of 1. The third triangle never made it into the tree.

The fix was to remove the clamp. The lookup already returns -1 for any index outside the triangle array, so it can test offset 4 without reading past the end.

Translating a Draw, Not Just a Material Name

Doom 3 evaluates stage conditions, colors, and texture transforms using shader registers supplied for the draw. Two entities can point to the same idMaterial and still supply different values. Caching the converted material by declaration alone conflates those draws. The scene converter instead keeps separate evaluated slots where those values differ. The intersection code also has to agree with the shading code: if the camera path transforms the UVs of a cutout but the shadow path tests the original UVs, the holes in the surface and its shadow no longer line up.

The flashlight beam is a useful example of what those stages can do. In OpenGL, one pass writes the beam mask into the framebuffer’s alpha channel without touching RGB. The dust pass then blends with GL_DST_ALPHA, GL_ONE, multiplying its color by the mask that’s already there:

alpha_dst = mask
rgb_out   = rgb_dst + dust_rgb * alpha_dst

The path tracer had skipped the first pass because it didn’t write any color. That left the dust unmasked, making the outline of the beam mesh visible. The material converter now carries the preceding mask texture, evaluated alpha, and UV transform into the additive stage. If it can’t find a supported resident mask, it warns and omits the overlay rather than drawing the full beam.

Why Rejecting Surface History Also Disabled Fog Filtering

The SVGF implementation keeps separate diffuse and specular histories so a filter suited to diffuse lighting doesn’t smear reflections. Volumetric radiance is filtered separately too, but its eligibility originally depended on the surface depth guide. Transparent and mixed-material pixels could clear that depth to reject unreliable surface reprojection. The volume filter read that same zero as “do not filter,” even when the pixel still contained noisy fog.

Enpro frame 300 with noisy fog between two marines Denoiser coverage view of Enpro frame 300 highlighting the transparent region in red Figure 1. Enpro frame 300 at 8 samples per pixel (spp) and its coverage diagnostic, not a before-and-after pair. Red marks transparent pixels, including the noisy region between the marines. Yellow marks dynamic pixels eligible for spatial filtering only; green marks static coverage.

The coverage fix gave the volume pass its own volumeDepth, taken from the first visible layer. It also let compatible opaque mixtures use neighboring pixels without borrowing samples from previous frames.

The biggest improvement was in the transparent areas marked red in the diagnostic. Compared with the old filter, the new one cut the color error there by about 80%. Across the whole image, the error fell by about 25%.

For that comparison, I rendered the same frozen 800 × 600 view at 8 samples per pixel with each filter. I measured how far the pixel colors were from an unfiltered 128-sample reference using mean squared error, which gives larger differences more weight. With filtering turned off, both versions exported identical PNGs. The numbers tell us how closely the filters matched the reference on one frame, not how stable they were in motion.

In live gameplay, fresh spatial samples along mixed-material edges could shimmer without stable history. The final implementation leaves the sampling loop alone and gates the expanded coverage when it writes the guides: outside capture mode it clears volumeDepth and restores the accumulated fallback for mixed pixels. The same renderer can then use the broader filter for fixed-sample captures without imposing it on gameplay.

Doom 3’s demo1, Path-Traced

For the benchmark I started with demo1.demo, the same recording I’d use to test the stock OpenGL renderer with timedemo demo1. I wanted to see how the path tracer handled a sequence I already knew as a benchmark, rather than record a new run for it. For example, r_ptBenchmark demo1.demo 32 replays demo1 at 32 spp per recorded frame. That experiment became d3ptmark.

The recording is the same; the work measured isn’t. Stock timedemo measures how fast OpenGL can draw the sequence. r_ptBenchmark holds each recorded view until the path tracer reaches the sample target, then advances. That lets me compare CUDA and OpenCL with the same demo, resolution, shading mode, and sample budget without treating the result as a stock timedemo score.


References