Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 50 ยท Ray Tracing and Rasterization Pipeline

Ray Tracing: Rays, Spheres and Planes

Build your first ray tracer: camera rays, the ray equation, ray-sphere and ray-plane intersection math, surface normals and simple shading, with live demos.

Everything you have drawn so far worked object by object: take a triangle, project it, fill the pixels it covers. Ray tracing turns the question around and works pixel by pixel. For each pixel, shoot a ray from the camera through that pixel into the scene, find the first object it hits, and compute the color from what you find there. Light really travels from lamps to the eye, but almost none of it reaches the camera, so we follow it backward and only trace the paths that matter.

The idea is simple enough to fit on one screen, and it produces effects that are hard for a rasterizer: accurate shadows, mirrors and glass. In this lesson you will write the core: generating camera rays, intersecting a ray with a sphere and a plane, and shading the nearest hit. The next lesson adds shadows, reflection and refraction on top of this foundation.

The ray equation

A ray has an origin O and a direction D. Every point on it is:

TEXT
P(t) = O + t * D          for t >= 0

The number t is the distance along the ray when D has length 1 (a unit vector). Intersecting the ray with an object means finding the values of t where P(t) lies on the object. If there is more than one, the smallest positive t is the visible one, because it is nearest to the camera. A negative t is behind the origin and must be ignored.

All vector math here uses the dot product a . b = ax*bx + ay*by + az*bz, which also gives squared length: a . a = |a|^2.

Camera rays

Put the camera at the origin looking down the negative z axis (the same convention as in the camera lesson). Imagine a rectangular image plane one unit in front of the camera. Pixel (i, j) of a W by H image maps to a point on that plane:

TEXT
aspect = W / H
u = (2 * (i + 0.5) / W - 1) * aspect * tan(fov / 2)
v = (1 - 2 * (j + 0.5) / H) * tan(fov / 2)
D = normalize( (u, v, -1) )

The + 0.5 aims at the pixel's center. The 1 - ... for v flips the screen's downward y axis into the world's upward one (see coordinate systems). The field of view fov is the vertical angle the image covers: a larger angle means a wider view and smaller-looking objects.

flowchart LR
  E["Eye (camera)"] --> P["Pixel on the<br/>image plane"]
  P --> S["Ray continues<br/>into the scene"]
  S --> H{"First hit?"}
  H -->|object| C["Shade the hit point"]
  H -->|nothing| B["Background color"]

One ray per pixel: the image is the answer to "what does this ray see first?"

Ray-sphere intersection

A sphere with center C and radius r is the set of points P with |P - C|^2 = r^2. Substitute the ray P = O + t*D and let L = O - C:

TEXT
|L + t*D|^2 = r^2
(D . D) t^2 + 2 (D . L) t + (L . L - r^2) = 0

That is a quadratic a t^2 + b t + c = 0 with a = D . D (equal to 1 for a unit direction), b = 2 (D . L) and c = L . L - r^2. The discriminant b^2 - 4ac tells the story:

  • Negative: the ray misses the sphere.
  • Zero: the ray just grazes it (one touching point).
  • Positive: two solutions t = (-b - sqrt(disc)) / (2a) and t = (-b + sqrt(disc)) / (2a): where the ray enters and where it leaves.

Take the smaller root first. If it is negative (the origin is inside the sphere, or the sphere is behind us), try the larger one. If both are negative, there is no hit.

At the hit point P, the surface normal of a sphere is just the direction from the center outward: N = (P - C) / r. The normal is what lighting needs. The first demo prints the numbers for a few rays so you can check the math by hand.

JS Ray-sphere intersection by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The straight-ahead ray hits at t = 4: the sphere's center is 5 units away and its radius is 1, so the near surface is 4 units away, and the normal points straight back at the camera, (0, 0, 1). The ray tilted by 0.2 per unit forward comes very close to the sphere's silhouette; the one at 0.5 misses.

Ray-plane intersection

A plane through point Q with unit normal N is the set of points with (P - Q) . N = 0. Putting in P = O + t*D and solving for t:

TEXT
t = ((Q - O) . N) / (D . N)

When D . N is zero the ray runs parallel to the plane and there is no hit (or, in the unlikely case that it lies in the plane, infinitely many). Otherwise accept the hit only if t > 0. For a floor at y = -1 you can simplify: N = (0, 1, 0), so t = (-1 - O.y) / D.y.

A plane is infinite, so to make it readable give it a texture. A checkerboard is a one-liner: take the hit point's x and z, floor them, and test whether the sum is even or odd. The pattern is computed on demand and never stored, which is a common ray tracing trick.

Finding the nearest object

A scene is a list of objects. For each ray, test every object and keep the one with the smallest positive t:

TEXT
nearest = none
for each object in scene:
    t = intersect(ray, object)
    if t exists and (nearest is none or t < nearest.t):
        nearest = (object, t)

This brute-force loop costs pixels x objects intersection tests. Real renderers speed it up with bounding volume hierarchies, but the logic of the nearest hit stays the same. Notice that there is no depth buffer and no sorting: finding the smallest t solves visibility directly, and it handles intersecting objects correctly for free.

Your first ray tracer

Below is a complete tracer in about fifty lines. Three spheres hover above a checkerboard floor, a sky gradient fills the background, and one directional light shades the spheres with the Lambert rule from light and reflection: brightness is max(0, N . L). The Field of view slider changes the camera, and Normals switches to a debugging view that paints each surface point with its normal vector as a color, a very handy trick when something looks wrong.

A first ray tracer

Drag the field of view up and the spheres shrink while more of the floor appears; drag it down and you zoom in. Turn on the normal view: the left edge of each sphere has little red (its normal points toward negative x), the top is rich in green, and the part facing you looks bluish, because the color channels are simply the x, y and z of the normal remapped from -1..1 to 0..255.

Common problems

  • Self-intersection ("acne"). A ray that starts exactly on a surface may immediately hit that same surface because of rounding errors. The code ignores hits with t < 0.001; later you will offset new ray origins slightly along the normal.
  • Unnormalized directions. The formulas above assume |D| = 1. If you forget to normalize, t is no longer a distance and the a = D . D term must be kept.
  • Hits behind the camera. Always require t to be positive, otherwise spheres behind you will show up mirrored in front of you.
  • Aspect ratio. Forgetting to multiply u by W / H squashes the picture.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the ray equation P(t) = O + t * D, what does a negative t mean?

    t measures the distance along the ray from its origin. A negative t lies behind the origin, so it cannot be seen along this ray.
  2. 2. What does a negative discriminant in the ray-sphere quadratic tell you?

    A quadratic with a negative discriminant has no real solutions, so the ray never reaches the sphere's surface.
  3. 3. How is the surface normal of a sphere computed at a hit point P?

    The normal of a sphere points straight out from its center through the surface point. Dividing by the radius makes it a unit vector.
  4. 4. How does a ray tracer decide which of many objects is visible for a pixel?

    Each object reports where the ray hits it. The smallest positive t is the nearest surface, so no sorting or depth buffer is needed.
  5. 5. Why does the example ignore hits with t below 0.001?

    Floating point error can put a ray's start point slightly inside its own surface. A small minimum t prevents that false self-intersection.

Summary

  • Ray tracing works per pixel: shoot a ray through each pixel and find the first object it hits.
  • A ray is P(t) = O + t*D; the smallest positive t over all objects is the visible hit.
  • A camera ray for pixel (i, j) uses u = (2(i+0.5)/W - 1) * aspect * tan(fov/2) and v = (1 - 2(j+0.5)/H) * tan(fov/2), with direction normalize(u, v, -1).
  • Ray-sphere intersection solves a quadratic; its discriminant says miss, graze or hit. The normal is (P - C) / r.
  • Ray-plane intersection is t = ((Q - O) . N) / (D . N), and fails when the ray is parallel.
  • Beware self-intersection, unnormalized directions and hits behind the origin.

Next, make the picture look real with shadows, mirrors and glass in Shadows, Reflections and Refraction.