ray_sphere_intersect.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "ray_sphere_intersect.h"
  2. template <
  3. typename Derivedo,
  4. typename Derivedd,
  5. typename Derivedc,
  6. typename r_type,
  7. typename t_type>
  8. IGL_INLINE int igl::ray_sphere_intersect(
  9. const Eigen::PlainObjectBase<Derivedo> & ao,
  10. const Eigen::PlainObjectBase<Derivedd> & d,
  11. const Eigen::PlainObjectBase<Derivedc> & ac,
  12. r_type r,
  13. t_type & t0,
  14. t_type & t1)
  15. {
  16. Eigen::Vector3d o = ao-ac;
  17. // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
  18. //Compute A, B and C coefficients
  19. double a = d.dot(d);
  20. double b = 2 * d.dot(o);
  21. double c = o.dot(o) - (r * r);
  22. //Find discriminant
  23. double disc = b * b - 4 * a * c;
  24. // if discriminant is negative there are no real roots, so return
  25. // false as ray misses sphere
  26. if (disc < 0)
  27. {
  28. return 0;
  29. }
  30. // compute q as described above
  31. double distSqrt = sqrt(disc);
  32. double q;
  33. if (b < 0)
  34. {
  35. q = (-b - distSqrt)/2.0;
  36. } else
  37. {
  38. q = (-b + distSqrt)/2.0;
  39. }
  40. // compute t0 and t1
  41. t0 = q / a;
  42. double _t1 = c/q;
  43. if(_t1 == t0)
  44. {
  45. return 1;
  46. }
  47. t1 = _t1;
  48. // make sure t0 is smaller than t1
  49. if (t0 > t1)
  50. {
  51. // if t0 is bigger than t1 swap them around
  52. double temp = t0;
  53. t0 = t1;
  54. t1 = temp;
  55. }
  56. return 2;
  57. }
  58. #ifndef IGL_HEADER_ONLY
  59. // Explicit template instanciation
  60. template int igl::ray_sphere_intersect<Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, 3, 1, 0, 3, 1>, double, double>(Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&, double, double&, double&);
  61. #endif