home *** CD-ROM | disk | FTP | other *** search
/ BCI NET 2 / BCI NET 2.iso / archives / programming / source / graphicgems4.lha / GemsIV / vec_mat / ray / Sphere.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-06  |  1.6 KB  |  50 lines

  1. #include "Sphere.h"
  2. #include "solver.h"
  3.  
  4. /************************************************************************
  5. *                                    *
  6. * This method computes the intersection between a ray and the sphere.    *
  7. * It returns the distance between the origin of the ray and the closest *
  8. * point of intersection (or 0.0 if no intersection occurs).        *
  9. *                                    *
  10. ************************************************************************/
  11.  
  12. double Sphere::intersect(vec3& ray_org, vec3& ray_dir)
  13. {
  14. double    c[3],                // coefficients of the quadric equation.
  15.     s[2];                // solutions of the quadric equation
  16. vec3    d = ray_org - pos;        // vector from the center of the sphere to
  17.                     // the origin of the ray.
  18.  
  19. // compute the coefficients of the resolvent equation
  20. c[2] = 1.0;
  21. c[1] = 2.0 * ray_dir * d;
  22. c[0] = d * d - radius * radius;
  23.  
  24. // return the closest intersection point
  25. return closest_intersection(s, solveQuadric(c, s));
  26. }
  27.  
  28. /************************************************************************
  29. *                                    *
  30. * This method computes the normal vector to the sphere at the point of    *
  31. * intersection. (NB: normalization is "built-in" for the sphere).    *
  32. *                                    *
  33. ************************************************************************/
  34.  
  35. vec3 Sphere::normalAt(vec3& p)
  36. { return (p - pos) / radius; }
  37.  
  38. /************************************************************************
  39. *                                    *
  40. * Input from stream.                            *
  41. *                                    *
  42. ************************************************************************/
  43.  
  44. istream& operator >> (istream& s, Sphere& a)
  45. {
  46. s >> *((Primitive*) &a);
  47. s >> a.radius;
  48. return s;
  49. }
  50.