Solutions to all three questions of the paper dated 8 June 2015. Products of transformation matrices act on column vectors, with the rightmost factor acting first; the order issue in iii is discussed explicitly.[ref]
Computer Graphics examination paper by the University of Oxford (2015). Cover and printed pp. 2–6, A10403W1
Three advantages of integer arithmetic for raster graphics are:
- Cheap, fast operations. Historically, integer addition, subtraction and shifts needed much less hardware and execution time than floating-point arithmetic, especially on machines without a floating-point unit. An incremental Bresenham's line algorithm needs only a few additions and a decision per pixel.
- Exact decisions. Provided integer overflow is excluded, the scaled midpoint line decision is exact. There is no accumulated rounding error that can move a decision across a half-pixel boundary; equality has a reproducible tie rule.
- Simple storage and hardware. Integer coordinates already identify pixels. An implementation can keep coordinates and decision variables in ordinary registers and use a small add/compare datapath, avoiding conversion between floating-point numbers and integer screen addresses.
These are historical and structural advantages, not a claim that every modern processor executes every integer operation faster. An integer implementation still needs sufficient width for its intermediate results. The compact answer is
By exchanging axes, reversing endpoint order and reflecting coordinate signs where necessary, reduce a general line segment to the first octant:The vertical case is handled by exchanging axes. In this octant, increasing by one requires increasing by either zero or one. Thus, from the currently plotted pixel the candidates are and .
Use the implicit equation of the lineAt a fixed , means that lies below the exact line. The midpoint line decision evaluates , halfway between the two candidate pixel centres. If , the exact line lies below , so choose ; if , choose . At equality either candidate is equally near, but a fixed tie rule is essential. We choose on a tie throughout these solutions:This chooses the closest vertical-grid pixel centre in each column, with ties rounded upward. Since , the result has one pixel per column and consecutive pixels share an edge or a corner.
Multiply the midpoint line decision by two to remove the fraction. At the current pixel , maintainAt the initial endpoint this is . If is chosen, the next decision midpoint is displaced by and increases by . If is chosen, its displacement is and increases by . Both increments are constant, so the per-pixel work uses only integer arithmetic:The completed code, using the tie rule of part (b), is:
void midpointLine(int x0, int y0, int x1, int y1)
{
int dx, dy, incrE, incrNE, d, x, y;
x = x0; y = y0;
dx = x1 - x0;
dy = y1 - y0;
incrE = 2 * dy;
incrNE = 2 * (dy - dx);
d = 2 * dy - dx;
drawPoint(x, y);
while (x < x1) {
if (d < 0) {
d += incrE;
} else {
d += incrNE;
y++;
}
x++;
drawPoint(x, y);
}
return;
}Thus
guard1 is x < x1, and guard2 is d < 0. Multiplication by two is the only multiplication. Signed decision variables are convenient because and incrNE can be negative; this remains an integer arithmetic algorithm. A strictly unsigned hardware representation would need an equivalent biased or separated-sign encoding. As with the printed int skeleton, assume all intermediate values fit the chosen type; integer overflow would invalidate the mathematical decisions.To verify the geometry, write . The chosen ordinate isThe midpoint line decision selects exactly this nearest integer, rounding halves upward. Its increment between successive columns is zero or one. At and , it gives exactly and , respectively, so both endpoints are included and the line segment has precisely distinct pixels.
For the illustrated endpoints and , the ordinates are . In particular the exact ordinate at is , and the chosen pixel is .
The verifier can check the final geometric criterion directly, independently of the incremental decision variable. Set , , and define the scaled vertical residualThe exact line ordinate is , so . Nearest-integer selection with upward ties is preciselyThe strictness matters: at a half-integer ordinate the upper pixel has and passes, whereas the lower pixel has and fails. Each column has exactly one accepted integer ordinate.
With
reject() terminating verification unsuccessfully, suitable outline code is:void checkPoint(int x, int y)
{
Wide a = Wide(x) - x0;
if (a < 0) reject(); // inequality 1
Wide b = Wide(x1) - x;
if (b < 0) reject(); // inequality 2
Wide dx = Wide(x1) - x0;
Wide dy = Wide(y1) - y0;
Wide e = 2 * dy * a - 2 * dx * (Wide(y) - y0);
Wide lower = e + dx;
if (lower < 0) reject(); // inequality 3
Wide upper = dx - e;
if (upper <= 0) reject(); // inequality 4
counter[x]++;
}Wide denotes a signed integer type large enough for the products and differences, with conversion before subtraction. These are exactly four inequalities against zero, all applied to named integer variables. The arithmetic restriction on the drawing loop in part (c) does not restrict multiplication in this verifier. The screen endpoints are assumed valid, with and valid endpoint ordinates, so indexing is safe after the first two checks. These endpoint and screen preconditions belong in initialization if they are not guaranteed by the caller.No separate -range tests are needed: for between the endpoints, lies in , and its nearest integer lies in the same interval because both bounds are integers. The counters defer detection of omissions and repetitions to part (e). As for every finite counter, use adequate capacity or a sticky failure on overflow; saturating each counter at two also suffices because only zero, one, and “more than one” matter.
After every proposed pixel has passed part (d), insist on exactly one call in every column of the closed endpoint interval:
void final()
{
for (int x = x0; x <= x1; x++) {
if (counter[x] != 1) reject();
}
accept();
}Part (d) already rejected every out-of-range column and every incorrect ordinate. A zero counter now detects an omitted column; a counter greater than one detects a repeated call in that column. Because the residual interval in part (d) allows exactly one integer ordinate in each column, accepted calls in a repeated column must address the same pixel. Conversely, a counter of one in every column forces the complete set of nearest pixels, including both endpoints. Consecutive correct columns differ in ordinate by at most one, which proves that there are no gaps in the resulting thin line segment.
The verifier certifies the final plotted set; it need not require calls to arrive in increasing order. Its final condition is simply
| Matrix | Geometric action and parameters |
|---|---|
| A proper rotation about the -axis: . The angle is in radians, with the usual right-hand sense. | |
| A translation by : . | |
| Uniform scaling by : . Positive gives a uniform dilation; collapses the object to the origin; negative additionally reverses its direction through the origin. | |
| Perspective projection from the origin onto the plane , where is the focal length in the chosen coordinate units. |
The last operation produces . It requires a perspective divide: divide the first three components by the last. For ,This is why the last component of homogeneous coordinates cannot simply be discarded. Points with have no finite projected position, and a visible scene normally uses under this forward-axis convention. The first three transformations leave the last component equal to one and need no nontrivial divide. The displayed retains no depth variation after division; it describes projection onto the image plane, rather than a complete depth-buffer mapping.
Interpret the given focal point as the centre of perspective projection, . First translate it to the origin with . The direction from to the world origin is then , of length 10. Choose the rotation matrix so that this direction becomes :Indeed, the transformed component is , and the transformed component is . Thus the required mapping, followed by the perspective divide, isFor a world point , its camera coordinates and projected device coordinates areThe world origin projects to and lies at camera depth 10. A point five units along the unit viewing direction from has camera coordinates , so it lies on the central image plane as expected. Here device coordinates are image-plane coordinates centred on the optical axis; an actual pixel viewport would require its own specified scale and offset.
Only rotations about the -axis are available. Consequently the camera's horizontal axis stays parallel to the world -axis; the viewing direction lies in the world plane. The available orientation has pitch but no independent yaw or roll. Translations move the camera and the projected origin but cannot supply the missing orientation degrees of freedom.
In the solid-modelling convention used here, a rigid-body transformation is an orientation-preserving rigid transformation, represented by a proper rotation and a translation. The proposed upper-left block is orthogonal but hasIt is a reflection in the plane . It preserves distances, but reverses handedness, so it cannot describe continuous motion of a rigid solid through proper rotations and translations. Some mathematical uses of rigid transformation include this orientation-reversing case; the determinant is the distinction relevant to the warning.
In a solid modeller, triangle winding and outward normal vectors must agree. A reflection reverses the winding: for edge vectors ,Simply transforming stored normal vectors by while retaining the original vertex order therefore makes the geometric and stored normals disagree. Back-face culling, inside/outside tests and Phong reflection model calculations can then use the wrong side. Code assuming a positive oriented volume can likewise interpret the reflected solid incorrectly. A modeller can support reflections if it deliberately corrects these orientation conventions.
A suitable alternative rotates by about and then translates upward by
height. Writing ,Its rotation matrix has determinant . The source bounds , , become , , , where . A horizontal stripe becomes the vertical stripe , so even the stripe positions from the left edge are preserved. The face's normal vector is also preserved.The call constructs dimensions along the old axes. To obtain target dimensions and make an old layer become a new layer , use the cyclic permutationThe new coordinate ranges are immediately , , . Its spatial block is orthogonal with determinant , since a three-cycle is an even permutation. Hence this is a proper rotation, through about the axis in direction under the right-hand convention. No translation is required.
The multiplication order needs care. Use the standard right-hand rotation matrices, consistent with the printed and the stated positive rotation. For column vectors, direct multiplication of the two products in the order printed givesBoth permute the dimensions into , rather than the required . Therefore, with ordinary column-vector matrix multiplication, neither printed product is the permutation in part (ii). A translation can correct the position of a cuboid, but cannot correct these permuted side lengths for general . This order mismatch is present in the original printed question.[ref]
The apparent intended comparison is obtained if “chain” means apply the rotation first, then the rotation. Under that interpretation the actual column-vector products have the reverse order:Thus the negative-angle sequence is correct when read as operations performed from left to right. The positive-angle sequence givesIt occupies . Apply the world-space translationThis puts the cuboid in and still maps to . The distinction is purely the action order: ordinary products act rightmost first, while a library may describe an ordered sequence of operations in application order. Giving the coordinate maps makes either convention explicit. If one merely wanted to place the literal printed negative product in the positive octant, its translation would instead be , producing dimensions and still failing the requested general bounds.
At a surface point , let be the outward unit normal vector, the unit vector from toward the viewer, and the unit vector from toward the light. The incoming propagation direction is therefore . The specular reflection direction points away from the surface along the ideal reflected ray.
Resolve into its normal and tangential components:Reflection of the incoming direction preserves its tangential component and reverses its normal component. Equivalently, the outgoing direction has the same normal component as and the opposite tangential component, givingThe dot product identity shows when .
In the Phong reflection model, ambient lighting approximates unmodelled indirect illumination and is independent of these directions. The diffuse term models Lambertian reflectance and varies as . The specular term models a highlight around and varies as , where controls its sharpness. For a visible front surface, a convenient per-colour-channel equation iswhere is ambient illumination, is the source strength at the surface including any chosen attenuation, are material weights, and is one when and zero otherwise. The weights can be colour-dependent. An idealized point source's incident strength decreases as inverse distance squared; the empirical equation can also use a prescribed attenuation law.
In degenerate geometric cases the effective weights switch off. A light behind or tangent to the surface contributes neither direct diffuse nor specular illumination. If , the specular term is zero. A viewpoint on the back side is rejected by back-face culling for a one-sided surface. A material with no highlight has ; with no diffuse response, ; without ambient illumination the ambient term vanishes. These zeros do not require renormalizing the other weights, and the empirical Phong reflection model does not impose a universal condition . At coincident light/surface or eye/surface positions a direction cannot be normalized; such singular configurations require a separate convention, rather than substituting an undefined unit vector into the formula.
A bidirectional reflectance distribution function, or BRDF, describes how a surface scatters incident illumination into each outgoing direction. At a fixed surface point and wavelength, its inputs are two directions above the surface, toward the incident source and toward the observer; equivalently these are two pairs of angular coordinates. Its output is the ratio of differential reflected radiance to differential incident irradiance:Position and wavelength may be additional arguments when material properties vary. A colour implementation can return one value per colour channel. The BRDF is a material response, not the final outgoing light value: it must be combined with the incident illumination and the projected-angle factor.[ref]
Physically Based Rendering: From Theory to Implementation (4th edition) by Matt Pharr and others. §4.3.1, definition of the BRDF as differential outgoing radiance divided by differential incident irradiance
For incident radiance , the reflection part of the rendering equation isEmission is added separately if the surface itself emits. This integral explains how a BRDF replaces the assumed material response of a local lighting model. For Lambertian reflectance, , so the cosine factor yields the diffuse term from part (a). A directional specular lobe supplies a highlight. The empirical Phong reflection model is an approximate angular-response model of this kind; its original direct specular term is not automatically a normalized, energy-conserving BRDF. The ambient term approximates missing illumination and is not itself a third direction-independent material scattering mechanism. More general BRDFs can reproduce measured surface behaviour, while illumination from other surfaces supplies indirect light in the rendering equation.
Let the oriented vertices be , in an order such that points out of the front face. The given nondegeneracy guarantees . A ray with nonzero direction approaches the front face only ifReject . This combines back-face culling with rejection of parallel rays, including the coplanar case for this ordinary surface-hit test. The ray-plane intersection parameter isReject ; for rays launched from existing surfaces use a positive lower cutoff to avoid counting the launch surface. Form .
Finally determine whether lies inside the triangle. For , , , computeThese solve . The barycentric coordinates are , so the complete acceptance criterion isThe inequalities include the edges and vertices. A renderer sharing edges between triangles should use a consistent numerical edge convention; small floating-point arithmetic errors near a shared boundary should not create cracks. Normalizing is unnecessary for this intersection calculation because its scale cancels.
For single-shot ray tracing, construct one primary ray per pixel, normally through its centre on the image plane, with the camera centre as origin for perspective projection. Transform the ray into the scene's coordinates, or consistently transform all the scene geometry into camera coordinates.
Intersect that primary ray with the scene's triangles, using part (c), and retain the accepted hit with the smallest nonnegative parameter . This nearest-hit selection supplies visibility: farther surfaces cannot show through the first opaque surface. If there is no hit, write the background colour. At a hit , obtain its material colour and front unit normal vector and set toward the camera.
For each point light at , form , calculate the specular reflection direction, and evaluate its diffuse and specular contributions using the Phong reflection model. Sum the contributions and add ambient illumination once:The coloured surface can supply colour-dependent diffuse weights, and each source can have its own colour. Convert the result into the output image's colour encoding and range. Single-shot here means direct local shading after one primary visibility ray; no reflected or transmitted secondary viewing rays are followed. Part (e) adds secondary visibility queries for the lights.
At each primary hit , send a shadow ray toward each point light. An especially clear parameterization isIf an opaque scene surface intersects this open segment, the source is hidden. The finite interval is essential: an object beyond the light must not cast a shadow at . Exclude the launch surface with a small geometrically appropriate origin offset or positive minimum parameter, so floating-point arithmetic does not create a false self-intersection.
Introduce a visibility factor equal to zero when blocked and one otherwise. The modified equation isA blocked light loses both its diffuse and specular contributions. The simple ambient approximation remains. Opaque point lights produce hard shadow boundaries. Use a consistent sidedness policy for occluders: an opaque closed solid blocks from either crossing side, so a two-sided blocker test is appropriate even when primary visibility uses back-face culling. An any-hit query can stop as soon as it finds one blocker before the light.
A bounding volume hierarchy is a tree whose leaves contain geometric primitives, here triangles, and whose internal nodes store cheap-to-test bounding volumes containing all descendant geometry. A bounding volume may be an axis-aligned bounding box or a sphere. The key containment guarantee isTraverse from the root. Reject a whole subtree when its bounding volume is missed; otherwise visit its children and perform the full ray-triangle intersection test only at surviving leaves. Hitting a bounding volume is only permission to investigate, not evidence of hitting an enclosed triangle.
For nearest-hit queries, visit the nearer child first and keep the current nearest parameter. A second child whose volume begins farther away than this parameter can be pruned. For a shadow ray, restrict the traversal to the segment before the source and terminate at any blocker.
A flat list of triangles needs up to detailed tests per primary ray or shadow ray. A well-built bounding volume hierarchy can reject large groups with a few cheap tests and substantially reduce the average work. A balanced, well-separated scene often gives traversal resembling a short root-to-leaf search, but balance alone does not guarantee logarithmic query time: extensive overlap or an unfortunate ray can force examination of most or all leaves. Its advantage is spatial rejection, not a universal worst-case bound.
Path tracing estimates the rendering equation by a Monte Carlo method. Launch camera rays; at each surface hit sample an outgoing continuation direction according to a chosen probability density function, trace to the next hit, and continue through successive reflections. Accumulate emitted light or environment light with the product of scattering, cosine and inverse-density factors along the path. A bounce sampled with density updates the path weight byAverage many independently sampled paths per pixel. Multiple bounces account for indirect illumination, including colour bleeding between surfaces, instead of approximating all of it by one ambient constant. Termination can use Russian roulette: continue with probability and divide surviving weights by , preserving the expected contribution. A fixed bounce cutoff is simpler but truncates transport.
The elementary strategy that obtains illumination only when a randomly continued path hits an emitter fails for ideal point lights. From a surface point, an ideal point source occupies zero solid angle; sampling a direction from an ordinary continuous probability density function hits that one direction with probability zero. Thus this strategy almost surely never discovers the light, regardless of the number of samples. An area emitter occupies nonzero solid angle and can be hit.
The qualification matters: practical path tracing can use point lights by explicitly sampling a source and connecting the current surface to it with a shadow ray, a technique called next-event estimation. For a point source the connection direction is known exactly, rather than discovered by a random hemisphere hit. Thus the restriction applies to naive emitter-hit path tracing, not to all path tracing algorithms.[ref]
Physically Based Rendering: From Theory to Implementation (4th edition) by Matt Pharr and others. §12.2: point lights have delta-position emission and deterministic incident directions; §13.4: direct-light sampling is combined with scattering-direction sampling
Articles by others on the same topic
There are currently no matching articles.
