Buku ini belum tersedia dalam Bahasa Indonesia. Edisi: English.
University Computer Science — Year 3 · Sarjana Tahun 3
31Computer Graphics: From Triangles to Pixels
A picture on a screen is a grid of pixels, and a three-dimensional scene is a list of triangles in space. Computer graphics turns the second into the first. Each triangle is moved into place, seen through a camera, projected onto the screen and broken into the pixels it covers; where two triangles cover the same pixel, the nearer one wins; each pixel then receives a colour from the light that falls on the surface. The chapter writes every step in a few dozen lines of C, with no graphics library, and writes its images to files: a cube’s corners through the whole chain of matrices, a rasteriser in exact integers whose fill rule draws every pixel of a mesh exactly once, a depth buffer, two kinds of shading, and a small scene traced ray by ray.
You already know
Vectors, the dot and cross products, matrices and their products, and the composition of linear maps come from the mathematics volumes, as do barycentres and barycentric coordinates: a point of a triangle is with , and the coordinates are ratios of signed areas. An image is a grid of pixels, each with a red, a green and a blue intensity (grade 10 volume). Floating-point numbers round, and two computations of the same value can differ in their last bits (grade 10 volume). Structures, fixed-size arrays and integers in C come from the Year 1 and Year 2 volumes.
31.1 Coordinates and transformations
A cube of side 2 centred at the origin has the eight corners . To show it, the program must turn it, place it in front of a camera, and find where each corner lands on a screen of pixels. Turning is a linear map, a matrix; placing is a translation, which is not linear, since it moves the origin. One more coordinate makes both of them matrices.
Definition 31.1 (Homogeneous coordinates)
The homogeneous coordinates of a point of space are , and those of a direction are . More generally, with stands for the point : all non-zero multiples of a 4-vector stand for the same point.
In homogeneous coordinates the translation by and the rotation by an angle about the axis are
adds times : it moves a point, whose is 1, and leaves a direction, whose is 0, as it was, which is right, since a direction has no position to move. A scaling by the factors is the diagonal matrix of entries . A product of such matrices applies the right-hand factor first: turns a point, then moves it, and the order matters, since moves it first and then turns it about the origin, with the translation turned too (Exercise 31.5).
Definition 31.2 (Model transform, view transform, projection matrix)
The model transform of an object is the matrix that takes the coordinates in which the object was modelled to the coordinates of the scene. The view transform takes scene coordinates to camera coordinates, in which the camera sits at the origin and looks down the negative axis, with up. The projection matrix takes camera coordinates to clip coordinates, a 4-vector whose division by its last coordinate gives the position on the screen and a depth.
The chain is the same for every vertex of every object; only changes from object to object, and when the camera moves. Interactive computer graphics goes back to Sketchpad, the drawing program that Ivan Sutherland wrote in 1963.
Perspective
In camera coordinates, a point at height and distance in front of the camera is seen in the direction of slope : twice as far, it must be twice as high to be seen in the same direction. This division by the distance is perspective.
Definition 31.3 (Perspective projection, view frustum, perspective division)
A perspective projection maps a point of camera coordinates at distance in front of the camera to the screen position , scaled so that the edges of the field of view map to . The view frustum is the truncated pyramid of points that the camera shows: inside the field of view, between a near plane and a far plane . The projection matrix leaves the division undone: it puts into the fourth coordinate , and the perspective division divides by it, giving the normalised device coordinates (NDC), each in inside the frustum.
With the vertical field of view , the aspect ratio (width over height) and , the projection matrix is
An orthographic projection, for technical drawings, skips the division: it scales and directly, so that parallel lines stay parallel and far objects keep their size; its last row is . The perspective matrix’s last row puts . Its first two rows scale and so that, after the division, the top of the field of view, where , lands at . Its third row gives the depth after the division: on the near plane, on the far plane, and growing with in between, which is all a depth test needs. The listing writes it in C, with the entry of row and column .
// Perspective projection: camera at the origin looking down -z, vertical field of view
// fovy, z = -near and z = -far mapped to depths -1 and +1 after division by w = -z.
static inline mat4 perspective(double fovy, double aspect, double near, double far) {
double f = 1.0 / tan(fovy / 2);
mat4 r = {{{0}}};
r.m[0][0] = f / aspect;
r.m[1][1] = f;
r.m[2][2] = (far + near) / (near - far);
r.m[2][3] = 2 * far * near / (near - far);
r.m[3][2] = -1;
return r;
}
vec.h, all a few lines long, are the vector operations, the product of matrices and the translation and rotation matrices. code/bachelor-3/31-computer-graphics/listings/vec.hThe program below sends the eight corners through the whole chain. The cube is turned by about , then by about , then pushed 6 units in front of the camera; the camera has a field of view of , the aspect ratio , and the planes and . The viewport, the last step, maps to and to , since rows of pixels are counted from the top.
int main(void) {
mat4 model = matmul(translate(0, 0, -6), matmul(rotate_y(PI / 6), rotate_x(PI / 9)));
mat4 view = identity(); // the camera stays at the origin, looking down -z
mat4 proj = perspective(PI / 3, 4.0 / 3.0, 1, 20);
mat4 mvp = matmul(proj, matmul(view, model));
printf("corner clip (x, y, z, w) NDC (x, y, z) pixel\n");
for (int i = 0; i < 8; i++) {
vec4 p = {i & 1 ? 1 : -1, i & 2 ? 1 : -1, i & 4 ? 1 : -1, 1};
vec4 c = apply(mvp, p);
double nx = c.x / c.w, ny = c.y / c.w, nz = c.z / c.w; // perspective division
double px = (nx + 1) / 2 * 320, py = (1 - ny) / 2 * 240; // viewport: y down
printf("(%2.0f,%2.0f,%2.0f) (%6.3f,%6.3f,%6.3f,%6.3f) (%6.3f,%6.3f,%6.3f) (%5.1f,%5.1f)\n",
p.x, p.y, p.z, c.x, c.y, c.z, c.w, nx, ny, nz, px, py);
}
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o transform transform.c -lm && ./transform
corner clip (x, y, z, w) NDC (x, y, z) pixel
(-1,-1,-1) (-1.957,-1.035, 5.201, 6.610) (-0.296,-0.157, 0.787) (112.6,138.8)
( 1,-1,-1) ( 0.293,-1.035, 6.306, 7.610) ( 0.038,-0.136, 0.829) (166.1,136.3)
(-1, 1,-1) (-1.513, 2.220, 4.546, 6.018) (-0.251, 0.369, 0.755) (119.8, 75.7)
( 1, 1,-1) ( 0.737, 2.220, 5.651, 7.018) ( 0.105, 0.316, 0.805) (176.8, 82.0)
(-1,-1, 1) (-0.737,-2.220, 3.402, 4.982) (-0.148,-0.446, 0.683) (136.3,173.5)
( 1,-1, 1) ( 1.513,-2.220, 4.507, 5.982) ( 0.253,-0.371, 0.753) (200.5,164.5)
(-1, 1, 1) (-0.293, 1.035, 2.747, 4.390) (-0.067, 0.236, 0.626) (149.3, 91.7)
( 1, 1, 1) ( 1.957, 1.035, 3.852, 5.390) ( 0.363, 0.192, 0.715) (218.1, 97.0)
The first corner checks by hand: its is its distance, 6.610, and its depth is . The four corners with in the cube’s own coordinates have from 4.39 to 5.98, against 6.02 to 7.61 for the other four, and their pixels spread over 82 columns, against 64 for the far face: perspective makes the near face look bigger.
31.2 Rasterisation
Once its three corners are pixels, a triangle must be broken into the pixels it covers. The test for one pixel uses three signed areas.
Definition 31.4 (Rasterisation, edge function, top-left rule)
Rasterisation is the computation of the set of pixels that a shape covers; a pixel is covered by a triangle when its centre is inside the triangle. The edge function of the directed edge from to is
twice the signed area of the triangle ; it is zero on the line and has opposite signs on its two sides. The top-left rule decides the centres that lie exactly on an edge: such a centre is drawn only if the edge is a top edge, horizontal with the triangle below it, or a left edge, with the triangle to its right.
With pointing down the screen and a triangle listed clockwise, the three edge functions , and are all positive inside the triangle, and their sum at any point is , twice the area: divided by it, they are the barycentric coordinates of the point. Juan Pineda described rasterisation by edge functions in 1988, as a test that every pixel can run at the same time; the older line-drawing algorithm of Bresenham, from 1965, was written for a digital plotter.
The rasteriser below works in exact integers: coordinates are counted in sixteenths of a pixel, so that the centre of pixel is , and an edge function is a product of integers, exactly zero when a centre is on an edge. With floating-point numbers, the same centre could fall on one side of an edge for one triangle and on the other side for its neighbour.
// Twice the signed area of (a, b, p): positive when p is to the right of a -> b on a
// screen whose y points down, that is inside a triangle listed clockwise.
static inline long edge(pt a, pt b, pt p) {
return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
}
// For a clockwise triangle: a top edge is horizontal with the inside below it (it runs
// to the right); a left edge runs up the screen.
static inline bool top_left(pt a, pt b) {
return (a.y == b.y && b.x > a.x) || b.y < a.y;
}
// Is p drawn as part of the triangle (a, b, c), already put in clockwise order?
// rule 1: the top-left rule; rule 0: the naive test, every point with w >= 0.
static inline bool inside(pt a, pt b, pt c, pt p, int rule) {
long w[3] = {edge(a, b, p), edge(b, c, p), edge(c, a, p)};
pt from[3] = {a, b, c}, to[3] = {b, c, a};
for (int k = 0; k < 3; k++) {
if (w[k] < 0) return false;
if (w[k] == 0 && rule == 1 && !top_left(from[k], to[k])) return false;
}
return true;
}
The programs of this chapter test every pixel of the image, which keeps them short; a rasteriser tests only the pixels of the triangle’s bounding box, the smallest rectangle of pixels around its three corners. For a clockwise triangle on a screen whose points down, an edge running up the screen has the inside on its right, which is the triangle’s left edge; a horizontal edge running to the right has the inside below it, which is its top edge. That is all top_left tests. raster.c draws one triangle, of corners , and , on a grid of pixels, as text. The corners are rounded to sixteenths of a pixel first, to , and , and the area it prints is that of the rounded triangle, 225.74 against 225.615 for the corners as given.
$ gcc -std=c17 -O2 -Wall -Wextra -o raster raster.c -lm && ./raster
................................
................................
................................
....###.........................
....#######.....................
....###########.................
....###############.............
.....#################..........
.....#####################......
.....#######################....
......#####################.....
......###################.......
......##################........
.......###############..........
.......##############...........
.......############.............
........#########...............
........########................
........######..................
.........####...................
.........##.....................
.........#......................
................................
................................
226 pixels drawn, triangle area 225.74 pixels
#, when its centre is inside. The count of pixels is close to the area, without being equal to it.The edge between two triangles of a mesh is where the rule matters. shared_edge.c splits a square, whose corners are pixel centres, along its diagonal, and marks each pixel with the triangle that drew it: 1, 2, or X for both.
$ gcc -std=c17 -O2 -Wall -Wextra -o shared_edge shared_edge.c -lm && ./shared_edge
naive test, w >= 0:
............
.X111111111.
.2211111111.
.222X111111.
.2222211111.
.222222X111.
.2222222211.
.222222222X.
............
drawn twice: 4, square pixels missed: 0
top-left rule:
............
.111111111..
.221111111..
.222111111..
.222221111..
.222222111..
.222222221..
............
............
drawn twice: 0, square pixels missed: 0
The rule draws each centre on a shared edge once because the two triangles run along it in opposite directions: an edge that runs up the screen for one runs down for the other, so it is a left edge for exactly one of them; a horizontal edge has the inside below it for exactly one of them. Exercise 31.10 proves it, and the weekend problem counts the pixels of whole meshes.
31.3 Visibility
Where two triangles cover the same pixel, the pixel shows the nearer one. Sorting the triangles from far to near and drawing them in that order, the painter’s way, fails when two triangles cross: each is in front of the other in part of the image. The depth buffer decides pixel by pixel.
Definition 31.5 (Depth buffer, back-face culling)
A depth buffer, or z-buffer, holds one depth per pixel, initialised to the far plane; a triangle’s pixel is drawn only if its depth at that pixel is smaller than the one stored, which it then replaces. Back-face culling drops, before rasterisation, every triangle of a closed surface that faces away from the camera; with the triangles of every surface listed in the same order seen from outside, it is the triangles whose screen order is reversed.
The z-buffer was first described in 1974 by Wolfgang Straßer, in his doctoral thesis, and the same year by Edwin Catmull, to whom it is most often attributed. The depth of a pixel inside a triangle is interpolated from the depths of its corners with the pixel’s barycentric coordinates, the edge functions divided by twice the area. In NDC the depth is an affine function of the screen position over a flat triangle, so the interpolation is exact (Exercise 31.11).
static void draw(int id, vertex v[3], const double colour[3]) {
vertex u[3] = {v[0], v[1], v[2]};
pt a = fixed(u[0].x, u[0].y), b = fixed(u[1].x, u[1].y), c = fixed(u[2].x, u[2].y);
if (edge(a, b, c) < 0) { // clockwise order; each depth stays with its vertex
pt t = b;
b = c, c = t;
vertex s = u[1];
u[1] = u[2], u[2] = s;
}
double area = (double)edge(a, b, c);
for (int j = 0; j < H; j++)
for (int i = 0; i < W; i++) {
pt p = centre(i, j);
if (!inside(a, b, c, p, 1)) continue;
double l0 = edge(b, c, p) / area, l1 = edge(c, a, p) / area, l2 = 1 - l0 - l1;
double z = l0 * u[0].z + l1 * u[1].z + l2 * u[2].z; // barycentric depth
covers[j][i] |= id;
if (z < depth[j][i]) { // nearer than what is there: draw it
depth[j][i] = z, front[j][i] = id;
for (int k = 0; k < 3; k++) image[j][i][k] = colour[k] * (1.1 - z);
}
}
}
zbuffer.c draws two triangles that cross: a red one whose depth goes from 0.2 on its left to 0.8 on the right, and a blue one going the other way.
$ gcc -std=c17 -O2 -Wall -Wextra -o zbuffer zbuffer.c -lm && ./zbuffer
pixels covered by red only 2784, blue only 2236, both 3486, neither 10694
where both cover a pixel: red in front at 1830, blue at 1656
zbuffer.c writes: the two triangles cross along the line where their depths are equal, and each is darker where it is farther. No order of drawing the two whole triangles would give this picture.Back-face culling halves the work for a closed object: a cube shows at most three faces, and its other three are hidden by the first ones, so they need not be rasterised at all (Exercise 31.6). It does not replace the depth buffer, which must still order the faces that remain, and the faces of other objects.
31.4 Shading
The colour of a pixel depends on the light that leaves the surface towards the eye. Three terms give a usable picture: a constant ambient term for light coming from everywhere; a diffuse term for a matt surface, which scatters light equally in all directions; and a specular term for a shiny one, which sends it mainly in the mirror direction. For a surface of unit normal , lit from the unit direction and seen from the unit direction , the diffuse term is proportional to , the cosine of the angle of incidence, and the specular term to , where is the mirror image of about the normal and the shininess narrows the highlight as it grows. Bui Tuong Phong published this reflection model in 1975.
// The light leaving a point of normal n towards the viewer at +z: ambient, diffuse
// (Lambert: proportional to the cosine n.L) and specular (Phong: the reflected light
// direction r against the view direction, raised to a shininess).
static vec3 light(vec3 n) {
vec3 l = unit(v3(-1, 1, 1)), view = v3(0, 0, 1), base = v3(0.9, 0.55, 0.2);
double diffuse = dot(n, l) > 0 ? dot(n, l) : 0;
vec3 r = sub(mul(n, 2 * dot(n, l)), l);
double specular = diffuse > 0 && dot(r, view) > 0 ? pow(dot(r, view), 40) : 0;
return add(mul(base, 0.08 + 0.75 * diffuse), mul(v3(1, 1, 1), 0.6 * specular));
}
n: an ambient term 0.08, a diffuse term of weight 0.75, and a white specular term of weight 0.6 with the shininess 40. The light comes from the upper left, the viewer looks down . code/bachelor-3/31-computer-graphics/listings/shade.cDefinition 31.6 (Lambertian shading, Gouraud shading, Phong shading)
Lambertian shading colours a point in proportion to , as a matt surface that scatters light equally in every direction. Gouraud shading computes the light at the vertices of each triangle, with the vertex normals, and interpolates the colours across the triangle. Phong shading interpolates the normals instead, renormalises them, and computes the light at every pixel.
Henri Gouraud published his interpolation in 1971. shade.c lights the front half of a sphere both ways. On the left, the half-sphere is a mesh of cells of two triangles each, lit at its vertices and interpolated; on the right, each pixel takes the sphere’s exact normal, which is what Phong shading approaches as it interpolates the vertex normals of a fine enough mesh. The brightest point should be where , that is where the normal is the unit vector halfway between and .
$ gcc -std=c17 -O2 -Wall -Wextra -o shade shade.c -lm && ./shade
Gouraud: brightest pixel ( 55, 53), green 0.806
per pixel: brightest pixel (217, 57), green 1.008
highlight expected where n = (L + V)/|L + V|: pixel (216.7, 56.7)
shade.c. On the left, the highlight falls between vertices and is smeared over a few triangles, whose edges show in the shading; on the right, it is a small bright spot.The left half shows the weakness of Gouraud shading: a highlight narrower than a triangle is lost if no vertex sees it, and drawn too wide if one does. The cost is the reason it was used: the light is computed once per vertex instead of once per pixel.
In practice
The images of this chapter are written by the C programs themselves, as binary PPM files: the two characters P6, the width, the height and the maximum value 255 in ASCII decimal, then three bytes per pixel, row by row. A Python script of under 60 lines then writes each one as a PNG file, which is what the book prints: the 8-byte signature, then chunks, each with its length, its four-letter type, its data and a CRC computed over the type and the data, from the header chunk IHDR to the end chunk IEND, with the pixels compressed by zlib in between. A test decodes every PNG back and compares it with the PPM, pixel for pixel. Before storing, ppm.h raises each intensity to the power , a gamma encoding, and rounds to a byte.
31.5 Ray tracing
Rasterisation starts from the triangles and asks which pixels they cover. Ray tracing starts from the pixels and asks what each one sees.
Definition 31.7 (Ray tracing, primary ray, shadow ray)
Ray tracing computes the colour of each pixel by following rays of light backwards, from the eye into the scene. The primary ray of a pixel starts at the eye and passes through the pixel; its colour is that of the nearest surface it meets. A shadow ray starts at a point of a surface and goes towards a light: if it meets a surface before the light, the point is in shadow.
A ray is , with origin , unit direction and . It meets the sphere of centre and radius where ; with and , that is the quadratic , whose roots are . A negative discriminant means a miss; otherwise the smaller positive root is the visible hit. A ray meets the floor plane at .
The scene of rt.h has three spheres over a checkered floor and one point light. trace finds the nearest hit, sends a shadow ray from just off the surface, and lights the point by Lambert’s term if the light is not blocked; its last lines trace a reflected ray when a depth budget remains, which Exercise 31.12 uses.
static vec3 trace(vec3 o, vec3 d, int depth, counts *n) {
int what;
double t = nearest(o, d, &what);
n->ends[what + 1]++;
if (t < 0) return v3(0.75, 0.85, 1.0); // the sky
vec3 p = add(o, mul(d, t)), normal, colour;
double mirror;
if (what == 3) {
normal = v3(0, 1, 0), mirror = 0;
int check = ((long)floor(p.x) + (long)floor(p.z)) & 1;
colour = check ? v3(0.85, 0.85, 0.85) : v3(0.35, 0.35, 0.35);
} else {
normal = unit(sub(p, scene[what].centre));
colour = scene[what].colour, mirror = scene[what].mirror;
}
vec3 to_light = sub(LIGHT, p);
double dist = sqrt(dot(to_light, to_light));
vec3 l = mul(to_light, 1 / dist);
vec3 start = add(p, mul(normal, 1e-6)); // just off the surface
int blocker;
n->shadow++;
double tb = nearest(start, l, &blocker);
int lit = !(tb > 0 && tb < dist && blocker != 3);
double diffuse = lit && dot(normal, l) > 0 ? dot(normal, l) : 0;
vec3 c = mul(colour, 0.1 + 0.9 * diffuse);
if (depth > 0 && mirror > 0) {
n->reflected++;
vec3 r = sub(d, mul(normal, 2 * dot(d, normal)));
c = add(mul(c, 1 - mirror), mul(trace(start, r, depth - 1, n), mirror));
}
return c;
}
hit_sphere solves the quadratic above. code/bachelor-3/31-computer-graphics/listings/rt.hraytrace.c sends one primary ray through the centre of each pixel of a image, from a camera at the origin with the same field of view of as before, and with no reflection.
$ gcc -std=c17 -O2 -Wall -Wextra -o raytrace raytrace.c -lm && ./raytrace
primary rays 76800, shadow rays 45170, reflected rays 0
rays ending: sky 31630, red 3686, green 2661, blue 6074, floor 32749
raytrace.c writes. Shadows on the floor and on the spheres come from the shadow rays; the light is to the upper left.Turner Whitted showed in 1980 how to trace recursive rays for mirror reflection and refraction, which is what the last lines of trace do for reflection. The cost of ray tracing is in the search for the nearest hit: each ray here tests three spheres and a plane, but a scene of many thousands of triangles keeps them in a tree of bounding boxes, so that a ray tests only the few triangles near its path. Rasterisation pays per triangle, ray tracing per pixel and per ray; shadows and reflections, which a rasteriser must fake, come to a ray tracer from the same function called once more.
31.6 Exercises
Exercise 31.1 ★
Compute applied to the point and to the direction , in homogeneous coordinates, and applied to the point . Which way does turn the axis, seen from above?
Solution
Solution of Exercise 31.1.
: the point moves by 2 along . : the last column is multiplied by , and the direction is unchanged. : the axis turns to the axis, which, seen from above with towards the viewer, is a quarter turn counterclockwise. A test checks the three products.
Exercise 31.2 ★
With the camera of transform.c, find the NDC height of the points and of camera coordinates, and the row of pixels on which they land. Why must they land on the same pixel?
Solution
Solution of Exercise 31.2.
With , . Both points have , so for both, and the viewport puts them on the row , inside row 16. They lie on the same line of sight from the camera, the second twice as far and twice as high: the camera cannot tell them apart, only the depth can, and it is for the first and for the second. A test checks both NDC heights.
Exercise 31.3 ★
Take , and on a screen whose points down. Is clockwise? Compute , and at , their sum, and the barycentric coordinates of . Show that the sum of the three edge functions is the same at every point.
Solution
Solution of Exercise 31.3.
: clockwise on a screen whose points down. At : , , . The sum is . Each edge function, divided by 64, is the barycentric coordinate of the vertex opposite its edge: , , , and indeed . Each is affine in ; in the sum, the coefficient of is , and that of is 0 the same way, so the sum is a constant, its value at , where two of the terms vanish: . A test checks the four values.
Exercise 31.4 ★
Rasterise by hand, with the top-left rule, the triangle , , on a grid of pixels. How many pixels are drawn, against which area? One pixel centre lies exactly on an edge: which, and is it drawn?
Solution
Solution of Exercise 31.4.
: the triangle is clockwise, with area 14.5. Testing the 56 centres gives
........ .###.... .#####.. .####... ..##.... ..#..... ........
15 pixels for an area of 14.5. The centre of pixel is on the edge from to , at its middle. That edge runs up the screen, so it is a left edge, and the centre is drawn. A test checks the count, the area and the decision.
Exercise 31.5 ★★
A spinning cube is drawn with the model matrix instead of . Where is its centre for ? Describe what the viewer sees, and write the rule for the order of the factors.
Solution
Solution of Exercise 31.5.
moves the cube 6 units away first, then turns it about the camera’s vertical axis. Its centre becomes : at , at , at , level with the camera, and at , behind it. The viewer sees the cube swing off to the left and disappear, coming back a turn later. With the centre stays at and the cube spins in place. The rule: the factor written last acts first, so an object is turned about its own centre, then placed, . exercises/ex5_drift.c prints both centres for five angles, and a test checks the one at .
Exercise 31.6 ★★
Add back-face culling to the cube of transform.c: list its 12 triangles counterclockwise seen from outside, project them, and keep those whose screen order shows their front. How many are kept? Why is culling enough to draw one convex object correctly with no depth buffer, and not two?
Solution
Solution of Exercise 31.6.
exercises/ex6_cull.c lists the six faces by their corners, splits each into two triangles, and keeps a triangle when its projected edge function is negative. A face turned towards the camera is seen from outside, counterclockwise, which on a screen whose points down gives ; a back face is seen from inside, clockwise. Of the 12 triangles, 6 are kept: three faces. A test checks, for 24 orientations of the cube, that the kept triangles are exactly those of the faces whose outward normal points towards the camera. For one convex object culling is enough: a line of sight from the eye enters a convex body once, through one front face, so the front faces never cover each other and can be drawn in any order. With two objects, a front face of the nearer one can hide a front face of the other, and the order matters again: the depth buffer is still needed. It is also needed for one object that is not convex, such as a torus, whose front faces can hide each other.
Exercise 31.7 ★★
With and , compute the NDC depth at the distances . What part of the depth range is left to the far half of the frustum, ? A depth buffer stores the depth with a fixed number of bits: where does it tell near surfaces apart best, and how does moving the near plane closer change it?
Solution
Solution of Exercise 31.7.
With and the NDC depth is : at , at , at and at . The far half of the frustum keeps only of the range of length 2, that is , while the distances from 1 to 2 use more than half of it. The depth changes at the rate , so a buffer with a fixed number of levels separates surfaces finely near the camera and coarsely far away: one unit of distance at moves the depth 100 times less than at , and two surfaces close together far away can round to the same stored depth and flicker in front of each other. The rate is proportional to for small against : bringing the near plane from 1 to 0.1 divides the precision near the far plane by about ten. The near plane should be as far as the scene allows. A test checks the four depths.
Exercise 31.8 ★★
Find by hand the pixel where the highlight of the right half of shade.c should be: the sphere has radius 70 pixels and centre , is the unit vector of , . Why is the highlight where is halfway between and ? Why does the Gouraud half miss it?
Solution
Solution of Exercise 31.8.
Facts used: , the specular term is largest when . If then , so is the unit vector of : the normal must bisect the light and the view. Here , of length 1.776, and . On a sphere of radius 70 centred at the point of normal is at and , with downwards; a pixel’s centre is its index plus , so the pixel is , which the program prints rounded as , and its brightest pixel is . The Gouraud half computes the light only at its vertices, at multiples of of longitude and latitude, while is at about of longitude and of latitude: no vertex is at the highlight, and with the shininess 40 the specular term falls fast away from it, so the interpolated colours stay lower, 0.806 at best, and the peak is spread along the triangles’ edges. A test checks and the pixel.
Exercise 31.9 ★★
Derive the quadratic of the ray–sphere test. Compute for the ray from along against the sphere of centre and radius 1, and for a ray from that sphere’s centre along . At which angle from the axis do rays from the origin stop meeting the sphere?
Solution
Solution of Exercise 31.9.
Facts used: . , with ; equal to , this is . For the first ray, , , , and or 6: the ray enters at , the front of the sphere, and leaves at 6. From the centre, , , and : the only positive root, 1, is where the ray leaves the sphere, which is why hit_sphere tries the larger root when the smaller is not positive. A ray from the origin at the angle from the axis passes at the distance from the centre; it stops meeting the sphere when that distance exceeds the radius, at , . A test checks the two roots and that rays just inside and just outside that angle hit and miss.
Exercise 31.10 ★★★
Two clockwise triangles share the edge , on opposite sides of it. Prove that a pixel centre lying on strictly between and is drawn by exactly one of them under the top-left rule.
Solution
Solution of Exercise 31.10.
Facts used: ; a triangle is clockwise when ; top_left holds when and , or when .
Let the triangles be and with and on opposite sides of the line , . The first is clockwise as written. For the second, , so it is clockwise as : the two triangles run along the shared edge in opposite directions. Let be a centre on strictly between and . Then . The two other edges of the first triangle meet the line only at and at , so their edge functions are not zero at ; since is on the closed triangle, they are positive. The same holds for the second triangle. So the first triangle draws exactly when top_left, and the second exactly when top_left. If , exactly one of and holds, and the horizontal clause is false for both. If , the clause is false for both, and exactly one of and holds, since . In every case exactly one of the two tests is true, and is drawn exactly once. ∎
Exercise 31.11 ★★★
Show that the NDC depth of the points of a flat triangle is an affine function of their NDC position , so that interpolating the corners’ depths with screen-space barycentric coordinates is exact. Show that the distance is not affine in , but is. What does this mean for a texture or a colour interpolated across a triangle seen at a slant?
Solution
Solution of Exercise 31.11.
Facts used: perspective projection gives and with ; the NDC depth is with constants , .
A flat triangle lies in a plane of camera coordinates; if the plane does not pass through the eye, . Dividing by and writing , , gives
so is an affine function of the screen position over the triangle. The NDC depth is then affine in too, and an affine function is reproduced exactly by barycentric interpolation of its values at the corners: the depth buffer of zbuffer.c, which interpolates in screen space, computes the exact depth. The distance is not affine unless the affine function is constant, that is unless the triangle faces the camera squarely (). A colour or a texture coordinate given at the corners varies linearly in camera space, so like it is not affine on the screen: interpolated there it bends a slanted checkerboard. The fix is to interpolate and , both affine on the screen, and divide one by the other at each pixel, which is called perspective-correct interpolation. In shade.c the mesh is projected straight, without perspective, so its interpolation is exact.
Exercise 31.12 ★★★
Make the three spheres of rt.h partial mirrors and trace the image with a depth limit of 0 to 4. Count the primary, reflected and shadow rays for each limit. Explain the number of reflected rays at limit 1, why the counts stop growing quickly, and why a limit is needed at all.
Solution
Solution of Exercise 31.12.
exercises/ex12_reflect.c traces the scene with each depth limit, and a test checks every count:
| limit | primary | reflected | shadow | total |
|---|---|---|---|---|
| 0 | 76,800 | 0 | 45,170 | 121,970 |
| 1 | 76,800 | 12,421 | 50,881 | 140,102 |
| 2 | 76,800 | 13,333 | 51,343 | 141,476 |
| 3 | 76,800 | 13,478 | 51,422 | 141,700 |
| 4 | 76,800 | 13,498 | 51,435 | 141,733 |
At limit 1 every primary ray that ends on a sphere is reflected once: , the floor being no mirror. Of these reflected rays, meet a surface and send a shadow ray; the other 6,710 go to the sky. Each further level adds only the rays that meet a sphere again: 912, then 145, then 20. Three spheres apart from each other face each other over small solid angles, so a reflected ray rarely meets another one. Each bounce also weighs its colour by the mirror factor 0.3, so the fourth level changes a pixel by at most . A limit is needed because nothing else stops the recursion: two mirrors facing each other send a ray along the line through their centres back and forth for ever.
31.7 Weekend problem
Problem 31.1
Weekend problem — How many pixels does a triangle cover?
A triangle of area 225.74 pixels, once its corners are rounded to sixteenths, covered 226 pixels. The problem asks how close the count of pixels is to the area, when it is exact, and why the top-left rule makes it exact for a whole mesh. mesh.c draws six random triangles whose corners are pixel centres, so that Pick’s theorem applies, then five meshes that cover an image of pixels, each with both rules. Pick’s theorem, from 1899, says that a polygon whose corners have integer coordinates has the area , where counts the integer points strictly inside it and those on its boundary.
$ gcc -std=c17 -O2 -Wall -Wextra -o mesh mesh.c -lm && ./mesh
lattice triangle area interior boundary Pick naive top-left
(23, 8) (17, 9) (11, 1) 27.0 26 4 27.0 30 27
(12,10) (22,13) ( 3,13) 28.5 18 23 28.5 41 20
( 8, 2) (10,15) ( 3, 9) 39.5 39 3 39.5 42 40
(23, 6) (18,16) ( 1,16) 85.0 74 24 85.0 98 75
( 0,11) (17, 8) (16,15) 58.0 56 6 58.0 62 60
(13,16) (11,17) (19, 8) 5.0 4 4 5.0 8 4
mesh cells triangles rule drawn overlap never
1 20 40 top-left 3072 0 0
1 20 40 w >= 0 3159 66 0
2 30 60 top-left 3072 0 0
2 30 60 w >= 0 3139 44 0
3 42 84 top-left 3072 0 0
3 42 84 w >= 0 3139 32 0
4 56 112 top-left 3072 0 0
4 56 112 w >= 0 3173 56 0
5 72 144 top-left 3072 0 0
5 72 144 w >= 0 3270 112 0
Part I — One triangle, one square.
- Why does the count of drawn pixels of
raster.cdiffer from the area, and by how much can it differ for a triangle of that size? - Why does the rasteriser count in sixteenths of a pixel with integers? What could go wrong with floating-point coordinates on a shared edge?
- In the naive grid of
shared_edge.c, which four pixels are drawn twice, and why exactly those? - Which pixels does the naive test draw outside the square’s 54, and which neighbouring square of a mesh would draw them too?
- Name each edge of the two triangles of the square as top, left, or neither, and check the top-left grid against it.
- Check Pick’s theorem on the square, whose corners are pixel centres.
Part II — Lattice triangles.
- Check Pick’s formula on the first triangle of the table.
- Why is the naive count always ? Check it on the fourth row.
- The second triangle has an area of 28.5 and the top-left rule draws only 20 pixels. Where are its 23 boundary points, and which of them does the rule keep?
- For a lattice triangle, show that the top-left count lies between and , and that it can be above or below the area.
- The third triangle has no boundary points but its corners. What does Pick’s theorem give for it, and why is its top-left count then within one pixel of the area?
- Why does no single triangle’s count tell whether a rule is right?
Part III — Meshes.
- How are the meshes made, and why are a third of the inner vertices put on pixel centres?
- Why does the top-left rule draw exactly 3,072 pixels for every mesh?
- For the first mesh, the naive rule draws 3,159 pixels, with 66 drawn more than once. Why is larger than 66?
- Why does the naive rule never leave a pixel undrawn?
- A rule that drew only centres with all three : what would it leave in a mesh, and how would it show?
- Why does a pixel drawn twice matter for a half-transparent surface, even though the depth buffer hides it for an opaque one?
Part IV — Exactly once.
- Prove that a centre on a shared edge, strictly between its ends, is drawn by exactly one of the two triangles (Exercise 31.10 may be quoted).
- Show that a centre strictly inside one triangle of a mesh is drawn by that triangle alone.
- The proof leaves out centres exactly on a vertex. What does the table say about them, given that the meshes put many vertices on centres?
- Explain the rule in one dimension: a segment of pixels split at points, each piece drawing the half-open interval .
- Why must the rule depend only on the edge, and not on which triangle is drawn first?
- Sum up: how many pixels does a single triangle cover compared with its area, and how many does a mesh covering the image draw under each rule?
Solution
Solution of Problem 31.1.
1. A pixel is drawn when its centre is in the triangle; the centres form a grid with one point per unit of area, so the count is the area plus an error from the pixels that the boundary cuts, each wrong by less than one pixel. For this triangle, whose perimeter is about 70 pixels, the error can reach the order of the perimeter in the worst case, but errors of opposite signs along the boundary cancel, and here the count, 226, is within 0.26 of the area.
2. So that every edge function is computed exactly: a centre is then exactly on an edge, or exactly on one side. With floating-point numbers, the two triangles of a shared edge compute the edge function with their vertices in another order, and rounding can put a centre on the edge inside both, or inside neither, which leaves a doubled pixel or a hole.
3. The diagonal runs from centre to centre , a step of : it passes through the centres of pixels , , and , and through no other. The naive test draws a centre with in both triangles.
4. The column and the row : 7 plus 9, 16 pixels, since the naive test draws the square’s right and bottom edges, which go through centres. In a mesh of such squares, the square to the right draws the column again on its left edge, and the square below draws the row on its top edge.
5. With , , , in pixel centres and down, both triangles and are clockwise, with . In the first, runs right, horizontal: top; runs down: neither; runs up: left. In the second, runs down: neither; runs left, horizontal: neither; runs up: left. So the diagonal belongs to triangle 1, as the grid shows at and ; the top row and the left column are drawn, the bottom row and the right column are not.
6. centres strictly inside, on the boundary, and . A test checks it.
7. , the area.
8. The naive test draws the centres of the closed triangle: the inside and the on the boundary. Fourth row: .
9. The triangle , , is clockwise. Its bottom edge, from to , carries 20 centres, its two ends included; its edge from to , a step of , carries 2 more strictly between its ends; the corner is the 23rd. The bottom edge runs left: it is not a top edge, and its 20 centres are refused. The edge from up to is a left edge, and its 2 inner centres are kept. The corner is also on the edge to , which runs down, and is refused. So . A test checks the split.
10. The top-left rule draws every centre strictly inside, all with , and some of those on the boundary, so its count is between and . The area is between them as well, and the count can fall on either side: the third and fifth rows are above, 40 against 39.5 and 60 against 58; the second, fourth and sixth are below.
11. gives : 39.5. A corner is drawn only if both edges through it are top or left, and at most one corner of a triangle is, the one where its two top-left edges meet; so the count is or , here 40, half a pixel from the area.
12. A single triangle may legitimately draw anything between and ; what makes a rule right is a property of a mesh: every pixel of the covered region drawn exactly once. Only the count over a mesh, compared with the region, tests that.
13. A grid of cells for the seed , whose outer vertices lie on the image’s border; each inner vertex is either moved by up to 2.5 pixels in each direction or, one time in three, put exactly on a pixel centre; each cell is cut along one of its two diagonals at random. The vertices on centres make many edges pass exactly through centres, and some centres be vertices, the cases where a rule can fail: random vertices alone would almost never put a centre on an edge.
14. The triangles cover the rectangle without overlapping, and no centre lies on the outer border, which runs along pixel boundaries. By Questions 19 to 21, each of the 3,072 centres is drawn by exactly one triangle.
15. A centre on a shared edge is drawn twice, but a centre on a vertex is drawn by every triangle that has that vertex as a corner, often four to six. The extra draws are pixels drawn twice or more, plus more draws on pixels drawn three times or more.
16. The closed triangles cover the whole rectangle, and the naive test draws every centre of its closed triangle: each centre is in at least one.
17. Such a rule draws no centre on an edge: every centre on a shared edge or a vertex would be drawn by nobody, leaving lines of background pixels along the edges that pass through centres, cracks in the surface.
18. With blending, the colour of a half-transparent surface is mixed with what is behind it once per draw. A pixel drawn twice is mixed twice, and shows as a darker or more opaque seam along the edges. An opaque surface drawn twice at the same depth gives the same colour twice, and the error does not show.
19. This is Exercise 31.10: the two triangles run along the edge in opposite directions, and top_left is true for exactly one direction. The other two edge functions of each triangle are positive there.
20. A centre strictly inside a triangle has its three edge functions positive, and draws it. Another triangle of the mesh cannot contain it even in its closure: a small disc around the centre lies inside , and if the centre were in the closed , the disc would contain inner points of , so the two triangles would overlap.
21. The table shows no pixel drawn twice and none missed in five meshes where a third of the inner vertices are centres: the rule works at vertices too. A proof: the test of inside is the same as asking whether the point moved by , for a small enough , is strictly inside. On an edge with , the move changes by ; if , the first-order term decides, and it is positive when , a left edge; if , it is positive when , a top edge. The moved point lies on none of the finitely many edges, so it is strictly inside exactly one triangle, the one that draws the centre.
22. On a line, cut the pixels at the points : the piece takes its left end and not its right one, and the next piece takes . Every point belongs to exactly one piece. The top-left rule is the same choice in the plane: each triangle owns its top and left boundary, and leaves its bottom and right boundary to its neighbours.
23. So that the result does not depend on the order of drawing: each pixel is decided by its own centre and the triangle’s edges only, so the triangles can be drawn in any order, and the pixels tested all at once, as Pineda’s parallel test does.
24. One triangle covers its centres strictly inside and part of its boundary: between and , close to the area but off by up to the boundary’s share, 20 against 28.5 in the worst row. A mesh that covers the image draws exactly the pixels of the image under the top-left rule, with no overlap and no gap, in all five meshes; the naive rule never leaves a gap but makes from 3,139 to 3,270 draws, with 32 to 112 pixels drawn more than once.