home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 3 / RISC_DISC_3.iso / resources / etexts / gems / gemsii / intersect / intsph.c next >
C/C++ Source or Header  |  1991-09-22  |  2KB  |  61 lines

  1.  
  2. #include    <math.h>
  3. #include    "GraphicsGems.h"
  4.  
  5. /* ----    intsph - Intersect a ray with a sphere. -----------------------    */
  6. /*                                    */
  7. /*                                    */
  8. /*    Description:                            */
  9. /*        Intsph determines the intersection of a ray with a sphere.    */
  10. /*                                    */
  11. /*    On entry:                            */
  12. /*        raybase = The coordinate defining the base of the        */
  13. /*              intersecting ray.                    */
  14. /*        raycos  = The direction cosines of the above ray.        */
  15. /*        center  = The center location of the sphere.        */
  16. /*        radius  = The radius of the sphere.                */
  17. /*                                    */
  18. /*    On return:                            */
  19. /*        rin     = The entering distance of the intersection.    */
  20. /*        rout    = The leaving  distance of the intersection.    */
  21. /*                                    */
  22. /*    Returns:  True if the ray intersects the sphere.        */
  23. /*                                    */
  24. /* --------------------------------------------------------------------    */
  25.  
  26.  
  27. int    intsph    (raybase,raycos,center,radius,rin,rout)
  28.  
  29.     Point3    raybase;        /* Base of the intersection ray    */
  30.     Vector3    raycos;            /* Direction cosines of the ray    */
  31.     Point3    center;            /* Center of the sphere        */
  32.     double    radius;            /* Radius of the sphere        */
  33.     double    *rin;            /* Entering distance        */
  34.     double    *rout;            /* Leaving distance        */
  35.  
  36. {
  37.     int    hit;            /* True if ray intersects sphere*/
  38.     double    dx, dy, dz;        /* Ray base to sphere center    */
  39.     double    bsq, u, disc;
  40.     double    root;
  41.  
  42.  
  43.     dx   = raybase.x - center.x;
  44.     dy   = raybase.y - center.y;
  45.     dz   = raybase.z - center.z;
  46.     bsq  = dx*raycos.x + dy*raycos.y + dz*raycos.z; 
  47.     u    = dx*dx + dy*dy + dz*dz - radius*radius;
  48.     disc = bsq*bsq - u;
  49.   
  50.     hit  = (disc >= 0.0);
  51.  
  52.     if  (hit) {                 /* If ray hits sphere    */
  53.         root  =  sqrt(disc);
  54.         *rin  = -bsq - root;        /*    entering distance    */
  55.         *rout = -bsq + root;        /*    leaving distance    */
  56.     }
  57.   
  58.     return (hit);
  59. }
  60.  
  61.