# 1. Simple ray tracer ## 1.1. Description

A simple ray tracer written by me. So far it renders a scene consisting of a bunch of colorful spheres. Features supported so far include color, diffuse, shadows and reflections. A simple bounding volume hierarchy using bounding spheres is used to speed up ray-object intersection calculations. The only object shapes supported for now are spheres, due to simplicity of intersection and reflection calculations. Missing features include refraction, other object shapes and textures.

## 1.2. Download

raytrace: [raytrace.cc]

# 2. Theory

## 2.1. Ray-sphere intersection

We have a ray given by equation $$\boldsymbol{p}=\boldsymbol{a}t+\boldsymbol{b}$$ and a sphere of radius $$r$$ centered at $$\boldsymbol{c}$$. The distance between a point on the ray at $$t$$ and the center of the sphere is given by the formula:

$$d=\left(a_{x}t+b_{x}-c_{x}\right)^{2}+\left(a_{y}t+b_{y}-c_{y}\right)^{2}+\left(a_{z}t+b_{z}-c_{z}\right)^{2}$$

The minimum of this function is where the derivative is zero:

$$2\left(t\left(a_{x}^{2}+a_{y}^{2}+a_{z}^{2}\right)+a_{x}\left(b_{x}-c_{x}\right)+a_{y}\left(b_{y}-c_{y}\right)+a_{z}\left(b_{z}-c_{z}\right)\right)=0$$

By solving this equation for $$t$$ we get:

$$t_{o}=\frac{a_{x}(c_{x}-b_{x})+a_{y}(c_{y}-b_{y})+a_{z}(c_{z}-b_{z})}{a_{x}^{2}+a_{y}^{2}+a_{z}^{2}}$$

This gives us point closest to the center of the sphere. In order to check whether we actually have an intersection we need to check whether the distance between this point and the center of the sphere is smaller or equal to the radius of the sphere. The squared distance is:

$$d^{2}=\left(a_{x}t_{0}+b_{x}-c_{x}\right)^{2}+\left(a_{y}t_{0}+b_{y}-c_{y}\right)^{2}+\left(a_{z}t_{0}+b_{z}-c_{z}\right)^{2}$$

If $$d^{2}\leqslant r^{2}$$ then the ray intersects the sphere. In such case we may calculate intersection points — enty point and exit point. If $$d^{2}=r^{2}$$ then the entry point and the exit point are the same point. The formulas for the entry point and the exit point are:

$$t_{1}=t_{0}-\sqrt{r^{2}-d^{2}}$$
$$t_{2}=t_{0}+\sqrt{r^{2}+d^{2}}$$
Copyright © 2009, 2010, 2014 Janusz Kowalski
Powered by KrotCMS 2.0