HalloweenRayTracerPart2

Where we left off

In Part 1, every ray flew off into a purple sky. In this part, some of those rays hit something: a pumpkin, half a unit wide, one unit in front of the camera.

We’ll build it up in four steps, and each step gives an image you can run and see:

  1. A flat orange disc. The ray either hits the sphere or misses.
  2. A rainbow ball. We find the surface normal where the ray hits and show it as a colour.
  3. A shaded pumpkin. Lambert lighting with a single directional light.
  4. A jack-o’-lantern. The eyes and mouth are carved using the normal.

vec3.h, ray.h, and display.h don’t change at all. Everything happens in main.cpp. And dot(), which I added to vec3 in Part 1 “for later”, turns out to do most of the work.

Step 1: Does the ray hit the sphere?

The math

A point P is on a sphere with centre C and radius r when its distance from C is exactly r. Written with a dot product (because a vector dotted with itself is its length squared):

(P − C) · (P − C) = r²

The points on our ray are P(t) = A + t·b. Substituting that in for P and expanding gives an equation with t² in it, which is a quadratic:

(b·b) t²  +  2 b·(A − C) t  +  (A − C)·(A − C) − r²  =  0
    a              b'                    c

That’s the familiar a t² + b t + c = 0 from school, solved with the quadratic formula:

t = (−b' ± √(b'² − 4ac)) / 2a

The part under the square root is the discriminant, and it tells us everything:

  • less than 0: no real solution. The ray misses.
  • equal to 0: one solution. The ray just grazes the edge.
  • greater than 0: two solutions. The ray enters the sphere at one t and leaves at the other.

When there are two hits, we want the closer one, which is the smaller t. That’s −b' − √…. We also ignore hits with t ≤ 0, because those are behind the camera.

The code

// Returns the distance t to the nearest hit, or -1 if the ray misses.
float hit_sphere(const vec3& center, float radius, const ray& r)
{
    vec3 oc = r.origin() - center;               // A - C

    float a = dot(r.direction(), r.direction());
    float b = 2.0f * dot(oc, r.direction());
    float c = dot(oc, oc) - radius * radius;

    float discriminant = b * b - 4.0f * a * c;
    if (discriminant < 0.0f)
        return -1.0f;                           // miss

    float sqrtD = std::sqrt(discriminant);
    float t1 = (-b - sqrtD) / (2.0f * a);        // near side
    float t2 = (-b + sqrtD) / (2.0f * a);        // far side

    if (t1 > 0.001f) return t1;
    if (t2 > 0.001f) return t2;                 // camera is inside the sphere
    return -1.0f;
}

Why 0.001f and not 0.0f? Floating-point maths is never exact, so a hit that should be at exactly 0 can come out as 0.0000001. Using a small margin avoids those false hits. It matters more once rays start bouncing off surfaces, in later chapters of the book.

Now a ray_color() function decides what each ray sees. If it hits the pumpkin, it returns orange. Otherwise it falls back to Part 1’s sky_color():

vec3 ray_color(const ray& r)
{
    vec3 center(0.0f, 0.0f, -1.0f);
    float radius = 0.5f;

    float t = hit_sphere(center, radius, r);
    if (t > 0.0f)
        return vec3(1.0f, 0.35f, 0.05f);        // pumpkin orange

    return sky_color(r);
}

In main(), change one line: sky_color(r) becomes ray_color(r).

It’s a sphere, but it looks like a flat circle, because every pixel that hits gets the same colour. To make it look 3D, we need to know which way the surface faces at each hit point.

Step 2: The surface normal

The normal is the direction a surface faces at a given point. For a sphere it’s easy to find: it points straight out from the centre through the hit point.

N = (P − C) / r

The vector P − C has length exactly r, because P is on the sphere. So dividing by r gives a unit vector without calling unit_vector() and its square root.

A good way to check normals is to show them as colours. Each component runs from −1 to 1, so we map it to 0 to 1:

 float t = hit_sphere(center, radius, r);
    if (t > 0.0f)
    {
        vec3 hitPoint = r.at(t);
        vec3 normal = (hitPoint - center) / radius;

        // Debug view: map -1..1 to 0..1
        return 0.5f * (normal + vec3(1.0f, 1.0f, 1.0f));
    }

Reading the colours:

  • The right side is red (x = +1).
  • The top is green (y = +1).
  • The centre facing you is blue (z = +1, pointing back at the camera).

This is the same view as the world-normal buffer in Unity or Unreal. A debug view like this is worth keeping: if the lighting ever looks wrong, check the normals first.

Step 3: Lighting the pumpkin

This is where the moon from Part 1 comes back. There, dot(dir, moonDir) measured how closely a ray pointed at the moon. Here, dot(normal, lightDir) measures how directly the surface faces the light:

  • 1: the surface faces the light head-on, so it’s fully lit.
  • 0: the light hits at a glancing angle, so the surface is dark.
  • below 0: the surface faces away from the light. We clamp this to 0.

This is Lambert’s cosine law, the same diffuse term as in every basic shader. A directional light in Unity or Unreal works the same way. On its own it makes the shadowed side completely black, so we add a small constant ambient term:

brightness = ambient + (1 − ambient) · max(0, N · L)
        vec3 lightDir = unit_vector(vec3(-1.0f, 1.0f, 1.0f)); // upper left, in front

        float diffuse = std::max(0.0f, dot(normal, lightDir));
        float brightness = 0.20f + 0.80f * diffuse;

        vec3 pumpkin(1.0f, 0.35f, 0.05f);
        return brightness * pumpkin;

Add #include <algorithm> at the top for std::max. (display.h already includes it, but it’s better not to depend on that.)

A note for later: this is not how the book lights things. In the book, rays bounce randomly off surfaces, and the light comes from the sky itself. That approach is more physically correct, but it’s slower and noisy. A fixed light direction is a shortcut I took so the pumpkin would look good now. The book’s way comes later in the series.

Step 4: Carving the face

On the side facing the camera, the normal’s x and y components act like 2D coordinates on the pumpkin’s face. (0, 0) is the centre, x runs left to right, and y runs bottom to top, each from about −1 to 1. So drawing a face means writing rules in (x, y): “this region is an eye”, “this curve is the mouth”.

It’s the same idea as the moon. We never draw a shape. Each pixel checks whether its point falls inside a region, and the shape appears from all the answers.

Eyes: triangles

    float x = normal.x();
    float y = normal.y();

    // Width shrinks as y goes up -> a triangle pointing up.
    float eyeWidth = 0.45f * (0.45f - y);

    bool leftEye  = y > 0.10f && y < 0.45f && std::fabs(x + 0.35f) < eyeWidth;
    bool rightEye = y > 0.10f && y < 0.45f && std::fabs(x - 0.35f) < eyeWidth;
  • std::fabs(x + 0.35f) is the distance from x = −0.35, the centre of the left eye.
  • eyeWidth is about 0.16 at the bottom of the eye (y = 0.10) and shrinks to 0 at the top (y = 0.45). Because the allowed width shrinks steadily as y goes up, the shape is a triangle.

Mouth: a parabola

        // A U-shaped curve: lowest at x = 0, rising toward the corners.
        float smileCurve = -0.28f + 0.9f * x * x;

        bool mouth = std::fabs(x) < 0.42f &&
                     y > -0.35f && y < -0.05f &&
                     std::fabs(y - smileCurve) < 0.04f;

y = −0.28 + 0.9x² is a parabola, so it curves up into a smile. std::fabs(y - smileCurve) < 0.04f keeps only the points within 0.04 of that curve, which gives a band 0.08 thick.

Front side only

The back of the sphere has the same x and y values as the front. We need to check normal.z() > 0, which means facing the camera, so the face doesn’t also get drawn on the back.

        bool face = normal.z() > 0.0f && (leftEye || rightEye || mouth);
        if (face)
            return vec3(1.0f, 0.92f, 0.35f);    // candle yellow

The face colour skips the lighting completely. A jack-o’-lantern’s face doesn’t reflect light, because the candle inside makes it glow. That’s why it looks a bit flat for now. Making it actually glow is what Part 3 is about.

The full main.cpp

#include <vector>
#include "vec3.h"
#include "ray.h"
#include "display.h"
#include <algorithm>
#include <cmath>

// Return the distance t to the nearest hit or -1 if the ray misses.
float hit_sphere(const vec3& center, float radius, const ray& r)
{
vec3 oc = r.origin() - center; // A - C

float a = dot(r.direction(), r.direction());
float b = 2.0f * dot(oc, r.direction());
float c = dot(oc, oc) - radius * radius;

float discriminant = b * b - 4 * a * c;
if (discriminant < 0.0f)
{
return -1.0f;
}

float sqrtD = std::sqrt(discriminant);
float t1 = (-b - sqrtD) / (2.0f * a);
float t2 = (-b + sqrtD) / (2.0f * a);

if (t1 > 0.001f) return t1;
if (t2 > 0.001f) return t2;
return -1.0f;
}


vec3 sky_color(const ray& r)
{
vec3 dir = unit_vector(r.direction());

float t = 0.5f * (dir.y() + 1.0f);

vec3 horizon(0.60f, 0.15f, 0.48f); // magenta
vec3 night(0.09f, 0.03f, 0.22f); // deep violet

return (1.0f - t) * horizon + t * night;
}

vec3 ray_color(const ray& r)
{
vec3 center(0.0f, 0.0f, -1.0f);
float radius = 0.5f;

float t = hit_sphere(center, radius, r);

if (t > 0.0f)
{


vec3 hitPoint = r.at(t);
vec3 normal = (hitPoint - center) / radius;

float x = normal.x();
float y = normal.y();

// Width shrinks as y goes up -> a triangle pointing up.
float eyeWidth = 0.45f * (0.45f - y);

bool leftEye = y > 0.10f && y < 0.45f && std::fabs(x + 0.35f) < eyeWidth;
bool rightEye = y > 0.10f && y < 0.45f && std::fabs(x - 0.35f) < eyeWidth;

// A U-shaped curve: lowest at x = 0, rising toward the corners.
float smileCurve = -0.28f + 0.9f * x * x;

bool mouth = std::fabs(x) < 0.42f &&
y > -0.35f && y < -0.05f &&
std::fabs(y - smileCurve) < 0.04f;

bool face = normal.z() > 0.0f && (leftEye || rightEye || mouth);
if (face)
return vec3(1.0f, 0.92f, 0.35f); // candle yellow

// light
vec3 lightDir = unit_vector(vec3(-1.0f, 1.0f, 1.0f)); // upper left, in front

float diffuse = std::max(0.0f, dot(normal, lightDir));
float brightness = 0.20f + 0.80f * diffuse;

vec3 pumpkin(1.0f, 0.35f, 0.05f);
return brightness * pumpkin;

}

return sky_color(r);
}

int main()
{
const int width = 800;
const int height = 600;

// Camera
vec3 origin (0.0f, 0.0f, 0.0f);
vec3 lower_left (-2.0f, -1.5f, -1.0f);
vec3 horizontal(4.0f, 0.0f, 0.0f);
vec3 vertical(0.0f, 3.0f, 0.0f);

// Render into a buffer first, show it afterwords
std::vector<vec3> image(width * height);

for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float u = float(x) / float(width - 1);
float v = float(height - 1 - y) / float(height - 1);

vec3 direction = lower_left + u * horizontal + v * vertical - origin;
ray r(origin, direction);

image[y * width + x] = ray_color(r);
}

show_image("Halloween Ray Tracer - Part2", image, width, height);
return 0;
}

Compared with Part 1, the only change inside main() is sky_color → ray_color. The camera loop stays the same: it decides which ray each pixel gets, and ray_color decides what that ray sees. That split stays in place for the rest of the book.

Result

The pumpkin is lit, and its face is carved using nothing but a dot product and a few inequalities. The face still looks painted on, though. In Part 3, we’ll make it glow.

Bonus: a scarier pumpkin


I didn’t plan this pumpkin. It came out of the exercises. Moving the light below the pumpkin lights its chin and leaves the top in shadow. It’s the same trick as holding a flashlight under your chin to tell a ghost story.

vec3 lightDir = unit_vector(vec3(0.0f, -1.0f, 1.0f)); // from below, in front

The teeth needed only one line. sin alternates between positive and negative, so keeping only the positive half cuts the mouth into stripes:

bool teeth = std::sin(x * 100.0f) > 0.0f;   // about 13 teeth across the mouth
mouth = mouth && teeth;

Nothing new was added here. It’s the same dot product and the same face coordinates, just different numbers. That’s what I’m enjoying about writing the renderer myself: every effect is a line of code I can read and change.

A Few Other Examples…

leftEye = std::fabs(x + 0.3)* std::fabs(x + 0.3) + (y – 0.25)* (y – 0.25) < 0.08;

rightEye = std::fabs(x – 0.3) * std::fabs(x – 0.3) + (y – 0.25) * (y – 0.25) < 0.08;

bool circles1 = (x – 0.35f) * (x – 0.35) + (y – 0.25f) * (y – 0.25f) < 0.08f;

bool circles2 = (x + 0.35f) * (x + 0.35) + (y – 0.15f) * (y – 0.15f) < 0.03f;

if (((circles1 || circles2) || mouth)

return vec3(1.0f, 1.0f, 1.0f);

bool circles1b = (x – 0.42f) * (x – 0.42) + (y – 0.23f) * (y – 0.23f) < 0.04f;

bool circles2b = (x + 0.4f) * (x + 0.4) + (y – 0.2f) * (y – 0.2f) < 0.01f;

if (circles1b || circles2b)) {return vec3(0.1f, 0.1f, 0.1f);}

brightness *= 0.8f + 0.2f * std::cos(x * 25.0f);

smileCurve = -0.20f + 0.05f * std::sin(x * 20.0f);

Credits & Source

  • Ray Tracing in One Weekend by Peter Shirley, Trevor David Black, and Steve Hollasch. The ray–sphere intersection and surface normal sections follow the book. The lighting and the face are my own additions.
  • SDL2 is used for the window.
  • Source code: celebrate-season-with-raytracer on GitHub, in the Halloween folder.

Next: Part 3, Making it glow. We’ll mark which pixels are emissive, blur only those with a separable Gaussian blur, and add the result back on top of the image. That’s bloom, built by hand.

1 Comment

Leave a Comment