# CS488 - Introduction to Computer Graphics - Lecture 21

## Ray Tracing

The idea is simple:

for each pixel
calculate the eye/pixel ray
project the ray into the scene
find the first intersection
apply illumination and shading calculations
colour the pixel with the result

E + t*(P - E)

#### Object in scene

Set of points {Q} satisfying

• f(Q) = 0
• This is the surface of an object. (How do you know?)
• Why don't we care about inside points?

Solve the equation

• f(E + t*(P-E)) = 0 for t.
• For example, all points, Q, on the surface of a sphere, centred at C, of radius r, satisfies |Q-C| = r
• Thus, we solve | E - C + t*(P-E) | = r
• which amounts to (E - C + t*(P-E)).(E - C + t*(P-E)) = r^2
• This is the quadratic equation
• t^2 | P-E |^2 + 2t (E-C).(P-E) + | E-C |^2 - r^2 = 0

which has zero, one or two solutions.

• Most of the time there is no solution

The surface might be defined by an algorithm, then use a root-finding method

• For example, float f(E + t*(P - E)) returns distance of point from surface
• Submit the function to your favourite root-finder

#### Object is planar, e.g. a triangle

Equation of the plane is \sum_i ai*xi = b. Where do the parameters come from?

• Normal vector is n = (a0, a1, a2, 0)
• Take the cross product of any two edges n = (Vn - Vn+1) x (Vm - Vm+1). Now we know the ai.
• Substitute and vertex Vn = (v0, v1, v2)
• b = \sum ai*vi

Substitute eye ray into the plane equation and solve for t

• This point is on the plane: is it inside the polygon?
• Triangle: calculate barycentric coordinates; if < 0 outside.
• Convex polygon: do n half-plane tests
• Either: determine coordinates of the intersection point(s) in the plane of the polygon
• Clip the point against the polygon edges

#### Another idea: intersect in object coordinates

• In object coordinates each point is given by the object definition.
• In world coordinates each point in object coordinates is Q = MQ', where Q' is the point in object coordinates
• M is an affine transformation, therefore invertible

f'(Q') is the object definition in object coordinates

• Use invM to transform E,P to E',P', then solve the equation for t
• Find intersection point in world coordinates as E + t*(P-E)

### Shading for Ray Tracing

When we have found the intersection point we need to calculate a colour.

We know

1. The eye ray, V
2. Surface properties
3. The normal vector
• from a planar primitive
• by interpolation from vertex normals
• by calculation from equation of surface

For each light

1. Calculate illumination: RGB, l

Accumulate outgoing light