Guest User

Untitled

a guest
Jan 26th, 2017
144
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   /* Test the intersection of a ray and a sphere in three dimensional space.
  2.    * Returns 0, 1 or 2 intersection points. The first intersection point, if
  3.    * any, is written into #result and the sphere's surface normal into
  4.    * #normal.
  5.    *
  6.    * @param s - The origin of the ray.
  7.    * @param d - The direction of the line (a unit vector)
  8.    * @param c - The center of the sphere
  9.    * @param r - The radius of the sphere
  10.    * @param p1 - The first hitpoint on the sphere.
  11.    * @param p2 - The second hitpoint on the sphere.
  12.    * @return The number of intersections (0, 1 or 2).
  13.    *
  14.    * Thanks go out to http://gamedev.stackexchange.com/a/96469/9616
  15.    */
  16.   template <typename T>
  17.   inline int test_ray_sphere_intersection(
  18.     vector<3, T> const& s, vector<3, T> const& d, vector<3, T> const& c,
  19.     T r, vector<3, T>* p2, vector<3, T>* p1)
  20.   {
  21.     // Calculate ray start's offset from the sphere center
  22.     vector<3, T> p = s - c;
  23.  
  24.     T rSquared = r * r;
  25.     T p_d = p.dot(d);
  26.  
  27.     // The sphere is behind or surrounding the start point.
  28.     if (p_d > 0 || p.dot(p) < rSquared)
  29.       return 0;
  30.  
  31.     // Flatten p into the plane passing through c perpendicular to the ray.
  32.     // This gives the closest approach of the ray to the center.
  33.     vector<3, T> a = p - p_d * d;
  34.  
  35.     T aSquared = a.dot(a);
  36.  
  37.     // Closest approach is outside the sphere.
  38.     if (aSquared > rSquared)
  39.       return 0;
  40.  
  41.     // Calculate distance from plane where ray enters/exits the sphere.
  42.     T h = std::sqrt(rSquared - aSquared);
  43.  
  44.     // Calculate intersection point relative to sphere center, then
  45.     // derive the first and second hit point.
  46.  
  47.     if (p1) *p1 = c + (a + h * d);
  48.     if (aSquared == rSquared)
  49.       return 1;
  50.  
  51.     if (p2) *p2 = c + (a - h * d);
  52.     return 2;
  53.   };
RAW Paste Data