Graphics Reference
In-Depth Information
Listing 15.22: Rasterizer implemented by simply inverting the nesting order of
the loops from the ray tracer, but adding a
DepthBuffer
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void
rasterize(
Image
& image,
const
Scene
& scene,
const
Camera
& camera){
const int
w = image.width(), h = image.height();
DepthBuffer depthBuffer(w, h, INFINITY);
// For each triangle
for
(
unsigned int
t = 0; t < scene.triangleArray.size(); ++t) {
const
Triangle
& T = scene.triangleArray[t];
// Very conservative bounds: the whole screen
const int
x0=0;
const int
x1=w;
const int
y0=0;
const int
y1=h;
// For each pixel
for
(
int
y = y0; y < y1; ++y) {
for
(
int
x = x0; x < x1; ++x) {
const
Ray
& R = computeEyeRay(x, y, w, h, camera);
Radiance3
L_o;
float
distance = depthBuffer.get(x, y);
if
(sampleRayTriangle(scene, x, y, R, T, L_o, distance)) {
image.set(x, y, L_o);
depthBuffer.set(x, y, distance);
}
}
}
}
}
The
DepthBuffer
class is similar to
Image
, but it stores a single float at
each pixel. Buffers over the image domain are common in computer graphics.
This is a good opportunity for code reuse through polymorphism. In C++, the
main polymorphic language feature is the template, which corresponds to tem-
plates in C# and generics in Java. One could design a templated
Buffer
class and
then instantiate it for
Radiance3
,
float
, or whatever per-pixel data was desired.
Since methods for saving to disk or gamma correction may not be appropriate
for all template parameters, those are best left to subclasses of a specific template
instance.
For the initial rasterizer implementation, this level of design is not required.
You may simply implement
DepthBuffer
by copying the
Image
class imple-
mentation, replacing
Radiance3
with
float
, and deleting the display and save
methods. We leave the implementation as an exercise.
Inline Exercise 15.8:
Implement
DepthBuffer
as described in the text.
After implementing Listing 15.22, we need to test the rasterizer. At this time,
we trust our ray tracer's results. So we run the rasterizer and ray tracer on the
same scene, for which they should generate identical pixel values. As before, if
the results are not identical, then the differences may give clues about the nature of
the bug.