# Ray-Sphere Intersection¶

Implementation of ray-sphere intersection algorithm.

## Primitives¶

The first thing is to define the ray origin $O$ and direction $\large ê$, where the unit vector $\large ê = \frac{\vec{e}}{\parallel \vec{e} \parallel}$. Next step is to define the sphere/circle center $C_s$ and radius $\large r$. ## Intersection¶

To find the ray intersection, the next step is define the oriented segment $\overline{OC} = Cs - O$. Next step, we need to find the parameter $\large t$ which will parametrize the ray segment and find the intersections from the origin. The value $\large t$ can be found by projecting the vetor $\vec{OC}$ on the versor $\large ê$. The projection of a vector $\large \vec{a}$ on a $\large \vec{b}$ can be defined as the geometric representation of dot product:

$$\large a_1 = \parallel a \parallel \cos{\theta} = a \cdot \hat{b} = a \cdot \frac{\vec{b}}{\parallel \vec{b} \parallel}$$ Having the parameter $\large t$, we can finally define the segment which will give us the point $P_e$ projected from center of the sphere on the ray direction. Applying the concept of parametrized line, we can define:

$$\large P_e = O + t \cdot \hat{e}$$

Having this point, we can find the distance between $C_s$ and $P_e$ with ${\parallel P_e - C_s \parallel}_2$. Notice that now we have the distance $\large d$ so we can make some assumptions:

• If $d > r$ then there is no intersections;
• If $d = r$ then there is 1 intersection (tangent);
• if $d < r$ there are 2 intersections. Now we have all the necessary to calculate the intersection positions using the pythagorean theorem se we can have the value $\large i$ and define the positions based on the parametrized line from origin.

\large \begin{aligned} P_s^1 & = O + \hat{e} \cdot (t - i) \\ P_s^2 & = O + \hat{e} \cdot (t + i) \end{aligned} ## 3D Intersection¶

Apply same model for each pixel of an image plane as the origin and the ray direction is based on the perspective camera model: 