Brute Force Ray Sphere Intersection Illustrated

This notebook developes a 3D visualization to assist in understanding the brute force technique for intersecting a ray and a sphere.

Ross Beveridge, October 9, 2018

In [1]:
var('r, s');
Cv = vector(SR, 3, (5,5,5)); r = 3;
Lv = vector(SR, 3, (0,0,0));
Uv = vector(SR, 3, (1,2,2)); Uv = Uv / Uv.norm();
Pv = vector(SR, 3, var('x, y, z'));
Tv = vector(SR, 3, (Cv-Lv));
pretty_print("Sphere center: C = ", Cv);
pretty_print("Ray start:     L = ", Lv);
pretty_print("Ray direction: U = ", Uv);
pretty_print("Base to Center: T = ", Cv - Lv);

Following the approach and using the code from the previous notebook here we solve for the s-value where the ray enters and leaves the sphere, should they intersect.

In [2]:
eq1 = ((Pv - Cv)*(Pv - Cv) - r^2 == 0);
ray = Lv + s * Uv;
eq2 = (eq1.lhs()(x=ray[0],y=ray[1],z=ray[2]) == 0);
res = solve(eq2,s);
show(res[0]); show(res[1]);
In [3]:
bs     = 10.0;
Pt1    = Lv + res[0].rhs() * Uv; 
Pt2    = Lv + res[1].rhs() * Uv;
Ptfar  = Lv + sqrt(3 * (bs^2)) * Uv;
contents = [
  arrow3d(Lv, Lv+Uv, width=3),
  point(Pt1, color='green', size=16),
  point(Pt2, color='red',   size=16),
  sphere(Cv, size=r, color = Color('#F1C40F'), opacity=0.33),
  line3d([Lv, Ptfar], thickness=5, color=Color('#7D3C98')),
  line3d([(0,0,0),(bs, 0,  0)],thickness=5,color='red'),
  line3d([(0,0,0),(0, bs,  0)],thickness=5,color='green'),
  line3d([(0,0,0),(0,  0, bs)],thickness=5,color='blue')
  ];
show(sum(contents), aspect_ratio=(1,1,1));