Ellipsoidal sampling (offline)¶
This tutorial compares the three ways TimeGatedPathTracerInline connects a camera path to the
laser spot, at equal rendering time, on a narrow gate.
With direct sampling, every vertex \(x\) of the camera path is connected straight to the laser
spot. The length of that connection is whatever the geometry makes it, so with a narrow gate only
the few paths whose total length happens to fall inside the gate contribute, and the image is
noisy. ellipsoidal sampling instead inserts a new vertex \(y\) on the scene so that the path
\(x \to y \to\) laser spot has a length inside the gate: all such \(y\) lie on an ellipsoid with foci
\(x\) and the laser spot, and the pass samples \(y\) where that ellipsoid crosses a scene triangle.
Every path sampled this way fits the gate. ellipsoidal_direct_mis uses both techniques and
combines them with multiple importance sampling (balance heuristic). See
Connection sampling in the plugin reference.
The scene is the Cornell box with a diffuse dragon, lit by the same laser as the other tutorials:
download scene-v4-nolight.pbrt
and save it as cornell-box-dragon-diffuse/scene-v4-nolight.pbrt next to the script. The scene
also needs the dragon mesh, meshes/dragon.ply next to the .pbrt file, which is not included
here. (The Cornell box is by Benedikt Bitterli, released under
CC0.)
|
Frames |
Samples per pixel |
relMSE |
|---|---|---|---|
|
43 |
1,376 |
0.583 |
|
7 |
224 |
0.317 |
|
7 |
224 |
0.0510 |
Each image renders at 1024 x 1024 with 32 samples per pixel per frame and a 0.01-wide gate. The bottom row enlarges the dragon’s head. An ellipsoidal frame costs about six times a direct one, so it renders far fewer samples in the same time, but with MIS its error is 11 times lower. The error is the relative mean squared error against a path-traced reference with 262,144 samples per pixel. These numbers were measured on an NVIDIA GeForce RTX 3090 with Vulkan.
How the ellipsoidal vertex is sampled¶
The ellipsoidal connection follows Pediredla et al. (2019), with one change that makes it practical on a GPU: how the scene triangle that holds \(y\) is chosen. The original method tests the ellipsoid against the bounding boxes of a BVH and against the triangles in its leaves, and collects every triangle the ellipsoid crosses, then picks one from the list. On a GPU this list is the problem: for detailed meshes it can hold thousands of triangles per connection, far more than a thread can keep, which spills registers and memory.
TimeGatedPathTracerInline never builds the list. It samples the triangle by walking a BVH, the light BVH that
Falcor builds for emissive triangles, here built over all the scene’s triangles (ellipsoidTriangleSampler = LightBVH):
Length: the length of \(x \to y \to\) laser spot is drawn from the gate, and with \(x\) and the laser spot as foci it defines the ellipsoid.
Node: from the root, the walk goes into one of the two children at random, with a weight equal to the total area of the child’s triangles. The weight is zero, and the child is never visited, if its bounding box cannot hold a point of the ellipsoid’s surface: the box misses the ellipsoid’s bounding box, lies entirely outside the ellipsoid (its distances to the two foci add up to more than the length) or entirely inside it, or lies behind the surface at \(x\) or at the laser spot. The test uses only the box, so a box that passes can still hold triangles the ellipsoid does not cross.
Triangle: every leaf holds one triangle, which is taken without testing whether the ellipsoid crosses it.
Point: \(y\) is sampled on the curve where the ellipsoid crosses the triangle (an ellipse in the triangle’s plane, clipped to the triangle): in coordinates where the ellipsoid is the unit sphere, the curve is a circle, and \(y\) is uniform in angle over its arcs inside the triangle.
Visibility: a ray from \(x\) towards \(y\) must hit that triangle first; otherwise the sample is rejected.
The probability of every step is known, so the density of \(y\) is too, and it is recomputed for multiple importance sampling by walking the BVH again. The bounding-box test is conservative: a leaf can be reached whose triangle the ellipsoid misses, and that sample then fails instead of being drawn again. This keeps the cost of a connection to one walk down the tree, at the price of some failed samples.
Two more changes from the original method:
MIS with direct connections:
ellipsoidal_direct_miscombines the ellipsoidal technique with BSDF sampling followed by a direct connection, so that specular and glossy surfaces, where an ellipsoidal vertex has almost no BSDF value, are still sampled well.Connections to the light only: the ellipsoidal vertex is inserted only when the camera path connects to the laser spot (next-event estimation), not between subpaths as in bidirectional path tracing.
ellipsoidTriangleSampler = Uniform picks any scene triangle with the same probability, without looking at the
ellipsoid, as a baseline: most of its samples miss.
1. Load the scene¶
import time
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import falcorcomp as falcor
SIZE = 1024
testbed = falcor.Testbed(create_window=False)
testbed.load_scene("cornell-box-dragon-diffuse/scene-v4-nolight.pbrt")
testbed.resize_frame_buffer(SIZE, SIZE)
testbed.scene.camera.aspectRatio = 1.0
testbed.clock.pause()
SECONDS = 2.0 # rendering time for each method
REFERENCE = Path("reference.npy") # rendered below if missing
REFERENCE_SPP = 262144
TRACER = {"samplesPerPixel": 32, "maxBounces": 6,
"timeGateMode": "box", "timeGateWindow": 0.01, "timeCenter": 17.337084148727985}
METHODS = ["direct", "ellipsoidal", "ellipsoidal_direct_mis"]
2. Build the render graph¶
The graph is the one from Time-gated rendering (offline); only
samplingMethod changes between the three renders. The other ellipsoidal options keep their
defaults: the scene triangle is chosen with a light BVH over the scene’s triangles
(ellipsoidTriangleSampler), and with ellipsoidal only vertices rougher than
specularRoughnessThresholdEllipsoid (0.25) insert an ellipsoidal vertex.
def create_graph(sampling_method):
graph = testbed.create_render_graph(sampling_method)
graph.create_pass("VBuffer", "VBufferRT", {"samplePattern": "Center", "sampleCount": 1})
graph.create_pass("Laser", "LaserLight", {
"laserPosition": [0.0, 1.7, 6.8], "laserDirection": [0.0, 0.0, -1.0],
"laserPower": [170.0, 120.0, 40.0], "laserAngle": 0.0,
})
graph.create_pass("Tracer", "TimeGatedPathTracerInline",
{**TRACER, "samplingMethod": sampling_method})
graph.create_pass("Accumulate", "AccumulatePass", {"precisionMode": "SingleCompensated"})
graph.add_edge("VBuffer.vbuffer", "Tracer.vbuffer")
graph.add_edge("VBuffer.viewW", "Tracer.viewW")
graph.add_edge("Laser", "Tracer")
graph.add_edge("Tracer.color", "Accumulate.input")
graph.mark_output("Accumulate.output")
return graph
3. Render each method for the same time¶
As in the ReSTIR equal-time comparison, the timing waits for the GPU after every frame and leaves out a few warm-up frames, in which the shaders are compiled and the triangle sampler is built.
def render(graph, seconds):
testbed.render_graph = graph
for _ in range(10): # warm-up: shader compilation and the triangle sampler; not counted
testbed.frame()
graph.get_pass("Accumulate").reset()
testbed.device.wait()
frames, elapsed = 0, 0.0
while elapsed < seconds:
start = time.perf_counter()
testbed.frame()
testbed.device.wait() # include the frame's GPU time
elapsed += time.perf_counter() - start
frames += 1
return graph.get_output("Accumulate.output").to_numpy()[..., :3].copy(), frames
results = {}
for method in METHODS:
results[method] = render(create_graph(method), SECONDS)
4. Compare with the reference¶
If there is no reference.npy, the script first renders one with direct sampling and 262,144
samples per pixel, which takes about 7 minutes on an RTX 3090, and saves it for later runs.
if not REFERENCE.exists():
graph = create_graph("direct")
testbed.render_graph = graph
for _ in range(REFERENCE_SPP // TRACER["samplesPerPixel"]):
testbed.frame()
np.save(REFERENCE, graph.get_output("Accumulate.output").to_numpy()[..., :3])
reference = np.load(REFERENCE)
def relative_mse(image):
return float(np.mean((image - reference) ** 2) / np.mean(reference ** 2))
labels = []
for method, (image, frames) in results.items():
labels.append(f"{method}\n{frames} frames, relMSE {relative_mse(image):.4f}")
print(labels[-1].replace("\n", ": "))
5. Save the comparison¶
def to_display(image):
image = np.maximum(image, 0.0)
image = image / (1.0 + image) # Reinhard
image = np.where(image <= 0.0031308, 12.92 * image, 1.055 * image ** (1 / 2.4) - 0.055) # sRGB
return Image.fromarray((np.clip(image, 0, 1) * 255).astype(np.uint8))
images = [image for image, _ in results.values()] + [reference]
labels.append(f"Reference\n{REFERENCE_SPP} spp")
PANEL, CROP = 512, (180, 400, 500, 720) # crop box in the 1024 x 1024 image
font = ImageFont.load_default(size=26)
comparison = Image.new("RGB", (PANEL * len(images), 72 + 2 * PANEL), "white")
draw = ImageDraw.Draw(comparison)
for index, (image, label) in enumerate(zip(images, labels)):
display = to_display(image)
comparison.paste(display.resize((PANEL, PANEL), Image.LANCZOS), (index * PANEL, 72))
crop = display.crop(CROP).resize((PANEL, PANEL), Image.NEAREST)
comparison.paste(crop, (index * PANEL, 72 + PANEL))
draw.multiline_text((index * PANEL + 8, 6), label, fill="black", font=font)
comparison.save("time_gated_ellipsoidal_equal_time.png")
The full script:
time_gated_ellipsoidal_equal_time.py. With
the reference in place, it takes under a minute.