' '

1. Mathematics

We want to find the intersections of

  • A ray starting at point \(O\) and having direction \(\vec\Delta\).

  • A sphere with radius \(R\) centered at \(C\).

A sphere is defined as the set of all points \(P\) that are at a distance \(R\) from a center \(C\). Put into formula, each \(P\) must satisfy the following equation:

\[\mathrm{dist}(P, C) = R\]

Making use of the dot product, the distance \(\mathrm{dist}(P, C)\) can be written as \(\sqrt{(P-C)\cdot(P-C)}\). The square root being rather bothersome, we square it away:

\[(P-C)\cdot(P-C) = R^2\]

We know that \(P\) must reside on the ray, i.e. \(P\) must also satisfy

\[P = O + \vec\Delta \cdot t\]

for some \(t\). Combining these two equations we get

\[(O + \vec\Delta \cdot t - C) \cdot (O + \vec\Delta \cdot t - C) = R^2\]

Expanding and rearranging terms gives

\[(\vec\Delta \cdot \vec\Delta) \cdot t^2 + ((O - C) \cdot \vec\Delta) \cdot t + (O - C) \cdot (O - C) - R^2 = 0\]

We simplify the equation replacing the larger subexpressions by letters:

\[\begin{array}{rcl} a & = & \vec\Delta \cdot \vec\Delta \\ b & = & (O - C) \cdot \vec\Delta \\ c & = & (O - C) \cdot (O - C) - R^2 \end{array}\]

Thus giving as new equation

\[a \cdot t^2 + b \cdot t + c = 0\]

This quadratic equation can be solved using standard techniques.

  1. Compute the discriminant:

    \[D = b^2 - 4 \cdot a \cdot c\]
  2. If \(D < 0\), there are no solutions. This means the ray does not intersect the sphere.

  3. If \(D \geq 0\), there are two solutions.

    \[t_1 = \frac{-b-\sqrt{D}}{2 \cdot a} \qquad t_2 = \frac{-b+\sqrt{D}}{2 \cdot a}\]

Both \(t\) values indicate where on the ray the intersections lie. If \(t > 0\), the intersection lies in front of the beginning of the ray, i.e. these are generally the intersections that matter to us.

The actual intersection positions can be found using

\[P_1 = O + \vec\Delta \cdot t_1 \qquad P_2 = O + \vec\Delta \cdot t_2\]

2. Summary

Given

  • A ray starting at point \(O\) and having direction \(\vec\Delta\).

  • A sphere with radius \(R\) centered at \(C\).

The intersections can be found using the following steps:

  1. Compute \(a = \vec\Delta \cdot \vec\Delta\).

  2. Compute \(b = (O - C) \cdot \vec\Delta\).

  3. Compute \(c = (O - C) \cdot (O - C) - R^2\).

  4. Compute \(D = b^2 - 4 \cdot a \cdot c\).

  5. If \(D < 0\), there are no intersections.

  6. If \(D \geq 0\), there are two intersections:

    \[t_1 = \frac{-b-\sqrt{D}}{2 \cdot a} \qquad t_2 = \frac{-b+\sqrt{D}}{2 \cdot a}\]
  7. The hit positions can be found using

    \[P_1 = O + \vec\Delta \cdot t_1 \qquad P_2 = O + \vec\Delta \cdot t_2\]
  8. The normals are

    \[\vec{N}_1 = \frac{P_1 - C}{R} \qquad \vec{N}_2 = \frac{P_2 - C}{R}\]