Ray Sphere Intersection

Introduction: Rendering Your First 3D Object

Welcome to the first lesson in our ray tracing journey! In this lesson, you'll learn how to render your first actual 3D object: a simple sphere. By the end of this lesson, you'll have a working ray tracer that displays a red sphere floating in front of a blue-to-white gradient background.

The key challenge we'll tackle is understanding ray-sphere intersection. When we shoot a ray from our camera through each pixel, we need to determine whether that ray hits our sphere, and if so, where. This is a fundamental problem in ray tracing, and solving it requires some geometry and algebra. Don't worry, though — we'll break down the mathematics step by step and show you exactly how it translates into working C++ code.

Our approach will be mathematical but practical. We'll use the implicit equation of a sphere and combine it with our ray equation to create a quadratic equation we can solve. This might sound complex, but you'll see that the code is actually quite straightforward once you understand what each piece is doing.

The Implicit Equation of a Sphere

Before we can determine if a ray hits a sphere, we need a mathematical way to describe what a sphere actually is. In geometry, we use something called an implicit equation. An implicit equation defines a surface by specifying a condition that all points on that surface must satisfy.

For a sphere, the condition is simple: every point on the sphere's surface is exactly the same distance (the radius) from the sphere's center. If we have a sphere centered at point c with radius r, and we want to know if some point p is on the sphere's surface, we check whether the distance from p to c equals r.

In mathematical notation, we write this as: |p - c|² = r²

The left side of this equation, |p - c|², represents the squared distance from point p to the center c. We use the squared distance because it's computationally cheaper to calculate (we avoid the square root operation), and it works just as well for our purposes. If this squared distance equals r², then point p is exactly on the sphere's surface.

In our C++ code, we can express this using the dot product. Remember that the squared length of a vector v is the same as the dot product of v with itself: |v|² = v · v. So our sphere equation becomes: (p - c) · (p - c) = r²

This formulation is perfect for ray tracing because we can easily compute dot products using our vec3 class. The equation tells us everything we need to know: given any point in 3D space, we can test whether it lies on our sphere's surface.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal