TExcelTAD
Home › Math for Games › Mini Project: ASCII Ray Picker

Mini Project: ASCII Ray Picker

In this project you will build a tiny 3D renderer and a mouse-picking system that prints to the terminal. It uses almost every section of the course: vectors and the cross product for the camera basis, spaces and projection for turning pixels into rays, ray–sphere and ray–plane tests for hits, the dot product for lighting and shadows, and the reverse projection to put a point back on the screen.

What we are building: a scene with three spheres on a ground plane, seen through a camera. Every character of a 60×22 "screen" shoots a ray into the scene. Then a "click" at a character position picks the object under it, reports the hit point and normal, and marks it on the image.

Step New concepts
1. Scene and camera Vec3, look-at basis with cross products, orthonormal checks
2. One ray per character pixel → NDC → ray direction, ray–sphere, ray–plane, closest hit
3. Light and shadow Lambert (max(0, n̂ · l̂)), shadow rays, ASCII brightness ramp
4. Picking screen → world ray, hit report, world → screen round trip
5. Orbit and pick again rotating the camera around the target, re-picking

Note: Terminal characters are about twice as tall as they are wide, so the camera's aspect ratio uses width * 0.5 / height. Without it, spheres come out as tall ellipses.

Step 1: The scene and the camera

Start with the data: a Vec3, spheres, a ground plane at y = 0, and a camera defined by an eye position, a target and a vertical field of view. The camera's basis comes from two cross products (the Look Rotation lesson). Print it and check that the axes are perpendicular unit vectors before building anything on top of them.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <vector>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
double length(Vec3 v) { return std::sqrt(dot(v, v)); }
Vec3 normalize(Vec3 v) { return v * (1 / length(v)); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }

struct Sphere { std::string name; char id; Vec3 center; double radius; };

struct Camera {
    Vec3 eye, forward, right, up;
    double tanHalf, aspect;
    Camera(Vec3 eyePos, Vec3 target, double fovDeg, double aspectRatio) : eye(eyePos), aspect(aspectRatio) {
        forward = normalize(target - eye);
        right = normalize(cross(forward, {0, 1, 0}));
        up = cross(right, forward);
        tanHalf = std::tan(fovDeg * 3.141592653589793 / 360);
    }
};

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::vector<Sphere> spheres = {
        {"red ball", 'A', {-1.6, 0.8, 0}, 0.8},
        {"blue ball", 'B', {0.7, 0.6, -1.2}, 0.6},
        {"gold ball", 'C', {1.6, 0.5, 1.0}, 0.5},
    };
    const int W = 60, H = 22;
    Camera cam({0, 2.6, 5.2}, {0, 0.4, 0}, 50, W * 0.5 / H);

    std::cout << "camera forward " << cam.forward << "\n";
    std::cout << "camera right   " << cam.right << "\n";
    std::cout << "camera up      " << cam.up << "\n";
    std::cout << "checks: |f|=" << length(cam.forward) << " |r|=" << length(cam.right) << " |u|=" << length(cam.up)
              << "  f.r=" << z0(dot(cam.forward, cam.right)) << " f.u=" << z0(dot(cam.forward, cam.up))
              << " r.u=" << z0(dot(cam.right, cam.up)) << "\n";
    for (const auto& s : spheres)
        std::cout << s.id << " " << s.name << " at " << s.center << " r=" << s.radius
                  << ", distance from eye " << length(s.center - cam.eye) << "\n";
}
camera forward (0.000, -0.390, -0.921)
camera right   (1.000, 0.000, 0.000)
camera up      (0.000, 0.921, -0.390)
checks: |f|=1.000 |r|=1.000 |u|=1.000  f.r=0.000 f.u=0.000 r.u=0.000
A red ball at (-1.600, 0.800, 0.000) r=0.800, distance from eye 5.731
B blue ball at (0.700, 0.600, -1.200) r=0.600, distance from eye 6.742
C gold ball at (1.600, 0.500, 1.000) r=0.500, distance from eye 4.961

All lengths are 1 and all dot products 0, so the basis is orthonormal. The gold ball is the closest to the camera, which will matter when we pick.

Step 2: One ray per character

For each character cell, compute its center in NDC (-1..1), turn that into a direction with the camera basis (the Screen-to-World lesson's "cheaper way"), and find the closest hit among the spheres and the ground plane. Print each sphere's letter, _ for the ground and a space for the sky. This is an object-ID buffer: exactly what some engines render offscreen to make picking pixel-perfect.

cpp · try it yourself
#include <iostream>
#include <cmath>
#include <string>
#include <vector>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
Vec3 normalize(Vec3 v) { return v * (1 / std::sqrt(dot(v, v))); }

struct Sphere { std::string name; char id; Vec3 center; double radius; };
struct Camera {
    Vec3 eye, forward, right, up;
    double tanHalf, aspect;
    Camera(Vec3 e, Vec3 target, double fovDeg, double a) : eye(e), aspect(a) {
        forward = normalize(target - eye);
        right = normalize(cross(forward, {0, 1, 0}));
        up = cross(right, forward);
        tanHalf = std::tan(fovDeg * 3.141592653589793 / 360);
    }
    Vec3 rayDir(double ndcX, double ndcY) const {
        return normalize(forward + right * (ndcX * tanHalf * aspect) + up * (ndcY * tanHalf));
    }
};

double raySphere(Vec3 o, Vec3 d, const Sphere& s) {          // -1 = miss
    Vec3 oc = o - s.center;
    double b = dot(oc, d), c = dot(oc, oc) - s.radius * s.radius;
    double disc = b * b - c;
    if (disc < 0) return -1;
    double t = -b - std::sqrt(disc);
    return t > 1e-6 ? t : -1;
}
double rayGround(Vec3 o, Vec3 d) {                            // plane y = 0
    if (d.y > -1e-9) return -1;
    return -o.y / d.y;
}

struct Hit { double t = 1e30; char id = ' '; };
Hit trace(const std::vector<Sphere>& spheres, Vec3 o, Vec3 d) {
    Hit h;
    for (const auto& s : spheres) {
        double t = raySphere(o, d, s);
        if (t > 0 && t < h.t) { h.t = t; h.id = s.id; }
    }
    double tg = rayGround(o, d);
    if (tg > 0 && tg < h.t) { h.t = tg; h.id = '_'; }
    return h;
}

int main() {
    std::vector<Sphere> spheres = {
        {"red ball", 'A', {-1.6, 0.8, 0}, 0.8},
        {"blue ball", 'B', {0.7, 0.6, -1.2}, 0.6},
        {"gold ball", 'C', {1.6, 0.5, 1.0}, 0.5},
    };
    const int W = 60, H = 22;
    Camera cam({0, 2.6, 5.2}, {0, 0.4, 0}, 50, W * 0.5 / H);
    for (int row = 0; row < H; row++) {
        std::string line;
        for (int col = 0; col < W; col++) {
            double ndcX = (col + 0.5) / W * 2 - 1, ndcY = 1 - (row + 0.5) / H * 2;
            line += trace(spheres, cam.eye, cam.rayDir(ndcX, ndcY)).id;
        }
        std::cout << "|" << line << "|\n";
    }
}
|                                                            |
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________AAAAAAAA________________________________________|
|__________AAAAAAAAAAAA_________BBBBBBBB_____________________|
|_________AAAAAAAAAAAAAA________BBBBBBBB_____________________|
|_________AAAAAAAAAAAAAA________BBBBBBBB_____________________|
|_________AAAAAAAAAAAAAA__________BBBB______CCCCCC___________|
|__________AAAAAAAAAAAA___________________CCCCCCCCCC_________|
|_____________AAAAAA______________________CCCCCCCCCCC________|
|_________________________________________CCCCCCCCCC_________|
|___________________________________________CCCCCCC__________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|

The sky is the top row, the ground fills the rest, and each ball covers the ground behind it. Try moving C to (0.5, 0.5, -0.5) and watch it cover part of B: keeping only the closest hit does the depth sorting, with no z-buffer needed.

Step 3: Light and shadow

Replace the letters with brightness. At each hit, compute the surface normal ((p - center) / r for spheres, (0, 1, 0) for the ground) and the Lambert term max(0, n̂ · l̂) for a directional light. Then cast a shadow ray from the hit point toward the light: if it hits a sphere, the point only gets ambient light. Map the final brightness onto a character ramp.

cpp · try it yourself
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
Vec3 normalize(Vec3 v) { return v * (1 / std::sqrt(dot(v, v))); }

struct Sphere { std::string name; char id; Vec3 center; double radius; };
struct Camera {
    Vec3 eye, forward, right, up;
    double tanHalf, aspect;
    Camera(Vec3 e, Vec3 target, double fovDeg, double a) : eye(e), aspect(a) {
        forward = normalize(target - eye);
        right = normalize(cross(forward, {0, 1, 0}));
        up = cross(right, forward);
        tanHalf = std::tan(fovDeg * 3.141592653589793 / 360);
    }
    Vec3 rayDir(double ndcX, double ndcY) const {
        return normalize(forward + right * (ndcX * tanHalf * aspect) + up * (ndcY * tanHalf));
    }
};
double raySphere(Vec3 o, Vec3 d, const Sphere& s) {
    Vec3 oc = o - s.center;
    double b = dot(oc, d), c = dot(oc, oc) - s.radius * s.radius, disc = b * b - c;
    if (disc < 0) return -1;
    double t = -b - std::sqrt(disc);
    return t > 1e-6 ? t : -1;
}
double rayGround(Vec3 o, Vec3 d) { return d.y < -1e-9 ? -o.y / d.y : -1; }

struct Hit { double t = 1e30; int sphere = -1; bool ground = false; };
Hit trace(const std::vector<Sphere>& spheres, Vec3 o, Vec3 d) {
    Hit h;
    for (size_t i = 0; i < spheres.size(); i++) {
        double t = raySphere(o, d, spheres[i]);
        if (t > 0 && t < h.t) { h.t = t; h.sphere = int(i); }
    }
    double tg = rayGround(o, d);
    if (tg > 0 && tg < h.t) { h.t = tg; h.sphere = -1; h.ground = true; }
    return h;
}

char shade(const std::vector<Sphere>& spheres, Vec3 o, Vec3 d, Vec3 toLight) {
    static const std::string ramp = ".:-=+*#%@";            // dark -> bright
    Hit h = trace(spheres, o, d);
    if (h.sphere < 0 && !h.ground) return ' ';             // sky
    Vec3 p = o + d * h.t;
    Vec3 n = h.ground ? Vec3{0, 1, 0} : (p - spheres[h.sphere].center) * (1 / spheres[h.sphere].radius);
    double light = std::max(0.0, dot(n, toLight));
    Hit shadow = trace(spheres, p + n * 1e-4, toLight);    // nudge off the surface to avoid self-hits
    if (shadow.sphere >= 0) light = 0;
    double albedo = h.ground ? 0.45 : 1.0;                 // the floor is darker than the balls
    double brightness = 0.12 + 0.88 * light * albedo;      // ambient + diffuse
    int idx = std::clamp(int(brightness * ramp.size()), 0, int(ramp.size()) - 1);
    return ramp[idx];
}

int main() {
    std::vector<Sphere> spheres = {
        {"red ball", 'A', {-1.6, 0.8, 0}, 0.8},
        {"blue ball", 'B', {0.7, 0.6, -1.2}, 0.6},
        {"gold ball", 'C', {1.6, 0.5, 1.0}, 0.5},
    };
    const int W = 60, H = 22;
    Camera cam({0, 2.6, 5.2}, {0, 0.4, 0}, 50, W * 0.5 / H);
    Vec3 toLight = normalize({-1, 1.5, 0.8});              // light from the upper left, slightly in front
    for (int row = 0; row < H; row++) {
        std::string line;
        for (int col = 0; col < W; col++) {
            double ndcX = (col + 0.5) / W * 2 - 1, ndcY = 1 - (row + 0.5) / H * 2;
            line += shade(spheres, cam.eye, cam.rayDir(ndcX, ndcY), toLight);
        }
        std::cout << "|" << line << "|\n";
    }
}
|                                                            |
|============================================================|
|============================================================|
|============================================================|
|============================================================|
|============================================================|
|============@@%%##*=========================================|
|==========@@@@%##*+=-:=========%@@@%#*-=====================|
|=========@@@%%##*++=-::========%%%%#*=-=====================|
|=========%%%##**+==-:::========+**+=-::=====================|
|=========****++==-:::::=:========:::::::::=%@@@%#===========|
|==============--:::::::::::::============#@@@@@%%#+=========|
|=============::::::::::::::==============#%%%%%##*=:========|
|==========================================**#***+=::========|
|===========================================:---::::::=======|
|============================================================|
|============================================================|
|============================================================|
|============================================================|
|============================================================|
|============================================================|
|============================================================|

The spheres are bright on the upper-left side facing the light and fall off toward their unlit side, and each one casts a shadow (:) onto the ground to its right. The p + n * 1e-4 nudge matters: without it, rounding puts some shadow rays slightly inside the surface they start from, they hit their own sphere, and you get speckled "shadow acne", a bug real renderers fight with the same trick (a depth or normal bias).

Step 4: Picking

Now the interactive part. A "click" is a character position (col, row). Build the same ray as the renderer uses for that cell, trace it, and report what was hit, how far away, where, and the surface normal there. Then go the other way: project the hit point back to the screen with the camera basis (the Clip Space lesson) and check that it lands in the cell that was clicked.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <vector>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
Vec3 normalize(Vec3 v) { return v * (1 / std::sqrt(dot(v, v))); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }

struct Sphere { std::string name; char id; Vec3 center; double radius; };
struct Camera {
    Vec3 eye, forward, right, up;
    double tanHalf, aspect;
    int W, H;
    Camera(Vec3 e, Vec3 target, double fovDeg, int w, int h) : eye(e), aspect(w * 0.5 / h), W(w), H(h) {
        forward = normalize(target - eye);
        right = normalize(cross(forward, {0, 1, 0}));
        up = cross(right, forward);
        tanHalf = std::tan(fovDeg * 3.141592653589793 / 360);
    }
    Vec3 rayDirForCell(int col, int row) const {                   // screen -> world
        double ndcX = (col + 0.5) / W * 2 - 1, ndcY = 1 - (row + 0.5) / H * 2;
        return normalize(forward + right * (ndcX * tanHalf * aspect) + up * (ndcY * tanHalf));
    }
    bool worldToCell(Vec3 p, int& col, int& row) const {           // world -> screen
        Vec3 v = p - eye;
        double depth = dot(v, forward);
        if (depth <= 1e-6) return false;                           // behind the camera
        double ndcX = dot(v, right) / (depth * tanHalf * aspect);
        double ndcY = dot(v, up) / (depth * tanHalf);
        col = int(std::floor((ndcX + 1) / 2 * W));
        row = int(std::floor((1 - ndcY) / 2 * H));
        return col >= 0 && col < W && row >= 0 && row < H;
    }
};
double raySphere(Vec3 o, Vec3 d, const Sphere& s) {
    Vec3 oc = o - s.center;
    double b = dot(oc, d), c = dot(oc, oc) - s.radius * s.radius, disc = b * b - c;
    if (disc < 0) return -1;
    double t = -b - std::sqrt(disc);
    return t > 1e-6 ? t : -1;
}
double rayGround(Vec3 o, Vec3 d) { return d.y < -1e-9 ? -o.y / d.y : -1; }

void pick(const Camera& cam, const std::vector<Sphere>& spheres, int col, int row) {
    Vec3 d = cam.rayDirForCell(col, row);
    double best = 1e30;
    int which = -1;
    bool ground = false;
    for (size_t i = 0; i < spheres.size(); i++) {
        double t = raySphere(cam.eye, d, spheres[i]);
        if (t > 0 && t < best) { best = t; which = int(i); }
    }
    double tg = rayGround(cam.eye, d);
    if (tg > 0 && tg < best) { best = tg; which = -1; ground = true; }

    std::cout << "click (" << col << ", " << row << "): ";
    if (which < 0 && !ground) { std::cout << "sky, nothing selected\n"; return; }
    Vec3 p = cam.eye + d * best;
    Vec3 n = ground ? Vec3{0, 1, 0} : (p - spheres[which].center) * (1 / spheres[which].radius);
    std::cout << (ground ? std::string("ground") : spheres[which].name) << " at distance " << best
              << "\n    hit point " << p << " normal " << n;
    int c2, r2;
    if (cam.worldToCell(p, c2, r2))
        std::cout << "\n    projected back to cell (" << c2 << ", " << r2 << ")" << (c2 == col && r2 == row ? " OK" : " MISMATCH");
    std::cout << "\n";
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::vector<Sphere> spheres = {
        {"red ball", 'A', {-1.6, 0.8, 0}, 0.8},
        {"blue ball", 'B', {0.7, 0.6, -1.2}, 0.6},
        {"gold ball", 'C', {1.6, 0.5, 1.0}, 0.5},
    };
    Camera cam({0, 2.6, 5.2}, {0, 0.4, 0}, 50, 60, 22);
    pick(cam, spheres, 15, 9);       // on the red ball
    pick(cam, spheres, 45, 12);      // on the gold ball
    pick(cam, spheres, 34, 8);       // on the blue ball
    pick(cam, spheres, 30, 18);      // the floor in front
    pick(cam, spheres, 5, 0);        // top-left corner: sky
}
click (15, 9): red ball at distance 4.935
    hit point (-1.447, 1.041, 0.747) normal (0.191, 0.302, 0.934)
    projected back to cell (15, 9) OK
click (45, 12): gold ball at distance 4.464
    hit point (1.391, 0.703, 1.406) normal (-0.419, 0.405, 0.813)
    projected back to cell (45, 12) OK
click (34, 8): blue ball at distance 6.147
    hit point (0.580, 0.823, -0.656) normal (-0.199, 0.371, 0.907)
    projected back to cell (34, 8) OK
click (30, 18): ground at distance 3.998
    hit point (0.040, 0.000, 2.163) normal (0.000, 1.000, 0.000)
    projected back to cell (30, 18) OK
click (5, 0): sky, nothing selected

Every pick projects back into the cell it came from: screen → world and world → screen are exact inverses of each other. The normal on the red ball points mostly toward the camera (+z), a little up, and a little to the right (+x): the camera sits to the right of the red ball, so the face we see is turned that way. An engine uses the same normal to orient a selection ring or a bullet-hole decal.

Step 5: Orbit and pick again

Finally, move the camera. An orbit camera rotates its eye around the target: take the offset eye - target, rotate it around the world up axis (Rodrigues' formula from the Axis-Angle lesson, which for the Y axis is just the 2D rotation of x and z), and add the target back. The look-at basis is rebuilt from the new eye. Then render the ID buffer with a + at the clicked cell and pick through the same cell again: a different object is under the cursor now.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <vector>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
Vec3 normalize(Vec3 v) { return v * (1 / std::sqrt(dot(v, v))); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }

struct Sphere { std::string name; char id; Vec3 center; double radius; };
struct Camera {
    Vec3 eye, forward, right, up;
    double tanHalf, aspect;
    int W, H;
    Camera(Vec3 e, Vec3 target, double fovDeg, int w, int h) : eye(e), aspect(w * 0.5 / h), W(w), H(h) {
        forward = normalize(target - eye);
        right = normalize(cross(forward, {0, 1, 0}));
        up = cross(right, forward);
        tanHalf = std::tan(fovDeg * 3.141592653589793 / 360);
    }
    Vec3 rayDirForCell(int col, int row) const {
        double ndcX = (col + 0.5) / W * 2 - 1, ndcY = 1 - (row + 0.5) / H * 2;
        return normalize(forward + right * (ndcX * tanHalf * aspect) + up * (ndcY * tanHalf));
    }
};
double raySphere(Vec3 o, Vec3 d, const Sphere& s) {
    Vec3 oc = o - s.center;
    double b = dot(oc, d), c = dot(oc, oc) - s.radius * s.radius, disc = b * b - c;
    if (disc < 0) return -1;
    double t = -b - std::sqrt(disc);
    return t > 1e-6 ? t : -1;
}
double rayGround(Vec3 o, Vec3 d) { return d.y < -1e-9 ? -o.y / d.y : -1; }

struct Hit { double t = 1e30; int sphere = -1; bool ground = false; };
Hit trace(const std::vector<Sphere>& spheres, Vec3 o, Vec3 d) {
    Hit h;
    for (size_t i = 0; i < spheres.size(); i++) {
        double t = raySphere(o, d, spheres[i]);
        if (t > 0 && t < h.t) { h.t = t; h.sphere = int(i); }
    }
    double tg = rayGround(o, d);
    if (tg > 0 && tg < h.t) { h.t = tg; h.sphere = -1; h.ground = true; }
    return h;
}

// Rotate `p` around the vertical axis through `pivot` (positive = counter-clockwise seen from above).
Vec3 orbitY(Vec3 p, Vec3 pivot, double degrees) {
    double a = degrees * 3.141592653589793 / 180, c = std::cos(a), s = std::sin(a);
    Vec3 v = p - pivot;
    return pivot + Vec3{v.x * c + v.z * s, v.y, -v.x * s + v.z * c};
}

void frame(const std::vector<Sphere>& spheres, const Camera& cam, int clickCol, int clickRow) {
    for (int row = 0; row < cam.H; row++) {
        std::string line;
        for (int col = 0; col < cam.W; col++) {
            if (col == clickCol && row == clickRow) { line += '+'; continue; }
            Hit h = trace(spheres, cam.eye, cam.rayDirForCell(col, row));
            line += h.sphere >= 0 ? spheres[h.sphere].id : (h.ground ? '_' : ' ');
        }
        std::cout << "|" << line << "|\n";
    }
    Hit h = trace(spheres, cam.eye, cam.rayDirForCell(clickCol, clickRow));
    std::cout << "eye " << cam.eye << " -> selected: "
              << (h.sphere >= 0 ? spheres[h.sphere].name : h.ground ? "ground" : "nothing") << "\n";
}

int main() {
    std::cout << std::fixed << std::setprecision(2);
    std::vector<Sphere> spheres = {
        {"red ball", 'A', {-1.6, 0.8, 0}, 0.8},
        {"blue ball", 'B', {0.7, 0.6, -1.2}, 0.6},
        {"gold ball", 'C', {1.6, 0.5, 1.0}, 0.5},
    };
    const Vec3 target{0, 0.4, 0}, startEye{0, 2.6, 5.2};
    const int clickCol = 39, clickRow = 9;
    for (double yaw : {0.0, 40.0}) {
        Camera cam(orbitY(startEye, target, yaw), target, 50, 60, 18);
        std::cout << "orbit " << yaw << " deg\n";
        frame(spheres, cam, clickCol, clickRow);
    }
}
orbit 0.00 deg
|                                                            |
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|_______________AAAAAAA___________BBB________________________|
|_____________AAAAAAAAAAA_______BBBBBB_______________________|
|_____________AAAAAAAAAAA_______BBBBBB_______________________|
|_____________AAAAAAAAAAA________BBBB_____CCCCC______________|
|______________AAAAAAAAA________________+CCCCCCC_____________|
|__________________A____________________CCCCCCCCC____________|
|________________________________________CCCCCCC_____________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
eye (0.00, 2.60, 5.20) -> selected: gold ball
orbit 40.00 deg
|                                                            |
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________AAAAA___________________________________|
|__________________AAAAAAAAA_________________________________|
|__________________AAAAAAAAA_________BBBBB___________________|
|__________________AAAAAAAAA________BBBBBBB__________________|
|___________________AAAAAAA_________BBBBBBB__________________|
|_____________________________________BB+____________________|
|________________________________CCCCCCCC____________________|
|_______________________________CCCCCCCCCC___________________|
|_______________________________CCCCCCCCCC___________________|
|________________________________CCCCCCCC____________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
|____________________________________________________________|
eye (3.34, 2.60, 3.98) -> selected: blue ball

At 0° the cursor rests on the gold ball. After orbiting 40° counter-clockwise (seen from above), the camera looks at the scene from the right-front, the balls slide across the screen, and the same cell now selects the blue ball. Nothing in the picking code changed: it only depends on the camera basis, which is the whole point of separating "where is the camera" from "how do I turn a pixel into a ray".

Where to go from here

  • Color: give each object its own brightness ramp, or print ANSI colors.
  • Add a box: an AABB ray test (the slab method) gives you crates and walls.
  • Use matrices: build view and projection with the lookAt and perspective functions from the Spaces section and unproject with the inverse, as GPUs do. The output should be identical.
  • Animate: orbit the camera a few degrees per frame and print several frames; add damping so it eases to a stop.
  • In an engine, this whole project is Physics.Raycast(Camera.main.ScreenPointToRay(...)) in Unity, GetHitResultUnderCursor in Unreal, or PhysicsRayQueryParameters3D in Godot. Now you know what they do inside.

Test yourself

Why does the renderer multiply the aspect ratio by 0.5 for terminal output?

  1. To render twice as fast
  2. Terminal characters are about twice as tall as they are wide
  3. Because the FOV is 50°
  4. To flip the y axis

Why is the shadow ray started at p + n * 1e-4 instead of exactly at p?

  1. To make shadows softer
  2. Rounding could place the start inside the surface, so the ray would hit its own sphere (shadow acne)
  3. Because the light is far away
  4. To skip the ground plane

What does the round trip in Step 4 (cell → ray → hit → projected cell) verify?

  1. That the lighting is correct
  2. That screen-to-world and world-to-screen use consistent, inverse math
  3. That the spheres don't overlap
  4. That the camera is orthographic