Halloween Ray Tracer Part 3 Making It Glow

Where we left off

At the end of Part 2, the jack-o’-lantern had a lit body and a carved face, but the face looked painted on. A real candle-lit pumpkin glows: light spills out of the eyes and mouth and over the edges around them.

In games this effect is called bloom. Unity and Unreal give it to you as a post-process checkbox. Here we’ll build it by hand in three steps:

  1. Mark what glows. Render a second image that contains only the light-emitting pixels.
  2. Blur it. Spread that light out with a Gaussian blur.
  3. Add it back. Add the blurred light on top of the normal image.

As before, vec3.h, ray.h, and display.h don’t change. All the work is in main.cpp.

Step 1: Two images instead of one

So far, ray_color() has returned one colour per pixel. For bloom, each pixel needs to answer two questions:

  • What does the camera see here? This is the normal image.
  • How much light does this point give off? For most pixels the answer is none.

A small struct holds both answers:

struct Shade {
	vec3 color;
	vec3 glow;
};

Here’s where the zeroing constructor from Part 1 pays off: vec3() is black, so “no glow” is just vec3().

In ray_color(), the face returns its colour as both what we see and what it emits. Every other return passes vec3() for glow:

    if (face) {
        vec3 candle(1.0f, 0.92f, 0.35f);
        return { candle, candle };            // seen AND emitted
    }
    // ...lighting...
    return { brightness * pumpkin, vec3() };  // body: no glow

main() now fills two buffers of the same size:

    std::vector<vec3> image(width * height);
    std::vector<vec3> glow(width * height);

    // inside the pixel loop:
    Shade s = ray_color(r);
    image[y * width + x] = s.color;
    glow[y * width + x]  = s.glow;

This is the payoff of the decision in Part 1 to render into a buffer first. Because the whole image exists in memory before it’s shown, we can process it afterwards, just like a post-process pass in an engine.

Why not just pick the bright pixels?

Unity and Unreal choose which pixels bloom using a threshold: anything brighter than a set value glows. That works because engines render in HDR, where a light can be 10 or 50 times brighter than a white wall. Our colours all stay between 0 and 1, so a threshold low enough to catch the face would also catch the brightly lit side of the body. Marking the emissive pixels by hand gives exact control.

Step 2: The Gaussian blur

What the blur does

Each output pixel is a weighted average of the pixels around it. Close neighbours get a high weight and distant ones get a low weight. The weights follow a bell curve, the Gaussian:

weight(d) = exp(−d² / (2σ²))

Here d is the distance in pixels and σ (sigma) controls how wide the bell is. A bigger sigma means a softer, wider glow. Past about 3σ the weights are almost zero, so we stop sampling there. With σ = 12, that’s 36 pixels in each direction.

The trick: blur in two passes

A direct 2D blur with a radius of 36 reads a 73 × 73 square of pixels for every output pixel. That’s 5,329 reads per pixel.

The Gaussian has a useful property: a 2D Gaussian is exactly a horizontal 1D Gaussian multiplied by a vertical one.

exp(−(dx² + dy²) / 2σ²)  =  exp(−dx² / 2σ²) · exp(−dy² / 2σ²)

So we can blur every row first, then blur every column of that result, and get the same image. That’s 73 + 73 = 146 reads per pixel, about 36× less work. This is called a separable blur. Unity’s and Unreal’s bloom use the same trick, combined with another one: they blur several downsampled copies of the image, which makes wide glows much cheaper.

Measuring it

Measuring it

I timed both versions with std::chrono::steady_clock, and also wrote a direct 2D blur to compare against:

DebugRelease
Separable (2 passes)2,701 ms116 ms
Direct 2D92,842 ms5,045 ms
Ratio34×43×

Both versions produced the same image: the largest pixel difference was 0.0000024, which is just floating-point rounding. Theory predicted 36.5×, but Release measured 43×. Each 2D read does a little more work (an extra multiply and more bounds checks), so counting operations doesn’t tell the whole story.

Weights, computed once

The weights depend only on the distance, not on the pixel, so we compute them once up front. The curve is symmetric (the weight at −5 equals the weight at +5), so we store only one side:

// weights[d] for d = 0..radius, where radius = 3 * sigma
std::vector<float> gaussian_weights(float sigma)
{
    int radius = int(std::ceil(3.0f * sigma));
    std::vector<float> w(radius + 1);
    for (int d = 0; d <= radius; d++)
        w[d] = std::exp(-(d * d) / (2.0f * sigma * sigma));
    return w;
}

My first version called std::exp() inside the innermost blur loop, so it ran around 70 million times per frame. This version calls it 37 times.

One pass

// One 1D blur pass: along rows (horizontal) or along columns.
std::vector<vec3> blur_pass(const std::vector<vec3>& src,
                            int width, int height,
                            const std::vector<float>& weights,
                            bool horizontal)
{
    const int radius = int(weights.size()) - 1;
    std::vector<vec3> dst(width * height);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            vec3 sum;
            float total = 0.0f;

            for (int d = -radius; d <= radius; d++) {
                int sx = horizontal ? x + d : x;
                int sy = horizontal ? y : y + d;
                if (sx < 0 || sx >= width || sy < 0 || sy >= height)
                    continue;                     // off the image: skip

                float w = weights[std::abs(d)];
                sum += src[sy * width + sx] * w;
                total += w;
            }
            dst[y * width + x] = sum / total;
        }
    }
    return dst;
}

Two details worth noticing:

  • Dividing by total. This makes the weights add up to 1, so the blur spreads light out without making the image brighter or darker overall.
  • Edges. Near the border, some neighbours are off the image. We skip them and divide only by the weights we actually used, so edge pixels don’t fade toward black.

The only vec3 operations used here are *, +=, and /, all of which we wrote in Part 1.

Step 3: Add the light back

Light adds up: two lamps pointing at a wall make it brighter than one. So the final step is plain addition:

    const float bloomStrength = 1.5f;
    for (int i = 0; i < width * height; i++)
        image[i] += blurred[i] * bloomStrength;

Some pixels near the face will now be brighter than 1.0. That’s fine, because to_byte() in display.h clamps every value to 0–1 before display. Engines handle this more gently with tone mapping, which compresses bright values instead of cutting them off. That’s a topic for a later season.

The full main.cpp

// main.cpp
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
#include "vec3.h"
#include "ray.h"
#include "display.h"

struct Shade {
    vec3 color;   // what the camera sees
    vec3 glow;    // light this point emits (zero for most pixels)
};

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;
}

// 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;

    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;

    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;
}

Shade 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 { sky_color(r), vec3() };

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

    // --- Face ---
    float x = normal.x();
    float y = normal.y();

    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;

    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) {
        vec3 candle(1.0f, 0.92f, 0.35f);
        return { candle, candle };            // seen AND emitted
    }

    // --- Body: Lambert lighting ---
    vec3 lightDir = unit_vector(vec3(-1.0f, 1.0f, 1.0f));
    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, vec3() };
}

// weights[d] for d = 0..radius, where radius = 3 * sigma
std::vector<float> gaussian_weights(float sigma)
{
    int radius = int(std::ceil(3.0f * sigma));
    std::vector<float> w(radius + 1);
    for (int d = 0; d <= radius; d++)
        w[d] = std::exp(-(d * d) / (2.0f * sigma * sigma));
    return w;
}

// One 1D blur pass: along rows (horizontal) or along columns.
std::vector<vec3> blur_pass(const std::vector<vec3>& src,
                            int width, int height,
                            const std::vector<float>& weights,
                            bool horizontal)
{
    const int radius = int(weights.size()) - 1;
    std::vector<vec3> dst(width * height);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            vec3 sum;
            float total = 0.0f;

            for (int d = -radius; d <= radius; d++) {
                int sx = horizontal ? x + d : x;
                int sy = horizontal ? y : y + d;
                if (sx < 0 || sx >= width || sy < 0 || sy >= height)
                    continue;

                float w = weights[std::abs(d)];
                sum += src[sy * width + sx] * w;
                total += w;
            }
            dst[y * width + x] = sum / total;
        }
    }
    return dst;
}

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

    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);

    // 1. Render: what we see, and what glows
    std::vector<vec3> image(width * height);
    std::vector<vec3> glow(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);

            Shade s = ray_color(r);
            image[y * width + x] = s.color;
            glow[y * width + x]  = s.glow;
        }
    }

    // 2. Blur the glow: rows first, then columns
    std::vector<float> weights = gaussian_weights(12.0f);
    std::vector<vec3> blurred = blur_pass(glow, width, height, weights, true);
    blurred = blur_pass(blurred, width, height, weights, false);

    // 3. Add the light back on top
    const float bloomStrength = 1.5f;
    for (int i = 0; i < width * height; i++)
        image[i] += blurred[i] * bloomStrength;

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

The structure of main() is now the same as a frame in a game engine: render the scene, run a post-process pass, then present the result.

Result

※ The moon and lighting tweaks from the exercises are in the GitHub version.

That’s the whole series: a window and a sky, a sphere with a carved face, and light spilling out of it. Every pixel came from code I can read, from the first ray to the last blur pass.

Bonus

bloomStrength = 0 vs 1.5f vs 4 vs 10 At 4 the face starts losing its shape. At 10 it’s a white blob, because values far above 1.0 get clamped

gaussian_weights 4, 12, 24 4 looks like neon, 12 like candlelight, 24 like fog.

Hittable Object

We can display multiple spheres by describing the pumpkins as data as below:

struct Pumpkin {
	vec3 center;
	float radius;
};

const std::vector<Pumpkin> pumpkins = {
	{vec3(0.0f, 0.0f, -1.0f), 0.5f},
	{vec3(-1.2f, -0.3f, -1.8f), 0.35f},
	{vec3(1.1f, -0.35f, -1.5f), 0.3f},
	{vec3(0.55f, -0.4f, -0.75f), 0.12f},
};

In ray_color(), check every pumpkin and keep the nearest

Shade ray_color(const ray& r)
{
    // Find the closest pumpkin this ray hits.
    float closestT = 1e30f;      // "very far away"
    int hitIndex = -1;           // -1 = hit nothing

    for (int i = 0; i < (int)pumpkins.size(); i++)
    {
        float t = hit_sphere(pumpkins[i].center, pumpkins[i].radius, r);
        if (t > 0.0f && t < closestT)
        {
            closestT = t;
            hitIndex = i;
        }
    }

    if (hitIndex < 0)
    {
        // moon + sky code from before
    }

    const Pumpkin& p = pumpkins[hitIndex];
    vec3 hitPoint = r.at(closestT);
    vec3 normal = (hitPoint - p.center) / p.radius;

    // ...face + lighting code, unchanged...
}

Without t < closestT, the last pumpkin in the list wins instead of the nearest one, so the back pumpkins get drawn over the front.

Removing && t < closestT gives this:

What I learned this October

Engines aren’t magic. They’re passes. This was the biggest one. Rendering into a buffer, blurring it in a horizontal pass and a vertical pass, then adding it back is the same structure as the post-processing in Unity and Unreal. When I opened URP’s Bloom settings afterwards, I recognised almost every option. Threshold is my glow mask, Intensity is my bloomStrength, and Filter: Gaussian is the function I wrote. I’ve ticked that checkbox for years, and now I know what’s behind it.

The dot product does almost everything. One small function placed the moon, lit the pumpkin, and decided which way each surface faced. I had used dot in shaders many times, but seeing it do three completely different jobs in one file is when it finally clicked.

Shapes are questions, not drawings. I never drew a circle, a triangle, or a smile. Each pixel asks “am I inside this region?”, and the shape appears from all the answers. Once I saw it as distance plus an inequality, I stopped memorising formulas and started building shapes myself.

Measure, don’t guess. Theory said the separable blur would be about 36× faster. I measured 43×, because operation count isn’t the same as cost. Debug vs Release added another 20× on top. Together that’s roughly an 800× difference for the same image.

C++ is less forgiving than C#. A return inside a loop silently turned my blur off. A missing return compiled with only a warning. () and {} create completely different vectors. In Unity, the compiler would have caught most of these for me.

Debug views save time. Showing normals as colours, and brightening the blur buffer 5×, explained bugs that staring at the final image never would.

Going slowly was the right call. I rebuilt everything from an empty project instead of rushing ahead, and wrote these posts to make sure I could explain each step. Ray tracing is a field you could spend a whole career in. This month was just the first step, and I want to understand each step properly before taking the next.

Credits & Source

1 Comment

Leave a Comment