home *** CD-ROM | disk | FTP | other *** search
/ Photo CD Demo 1 / Demo.bin / gems / graphics / raybox.c < prev    next >
C/C++ Source or Header  |  1992-04-09  |  2KB  |  75 lines

  1. /* 
  2. Fast Ray-Box Intersection
  3. by Andrew Woo
  4. from "Graphics Gems", Academic Press, 1990
  5. */
  6.  
  7. #include "GraphicsGems.h"
  8.  
  9. #define NUMDIM    3
  10. #define RIGHT    0
  11. #define LEFT    1
  12. #define MIDDLE    2
  13.  
  14. char HitBoundingBox(minB,maxB, origin, dir,coord)
  15. double minB[NUMDIM], maxB[NUMDIM];        /*box */
  16. double origin[NUMDIM], dir[NUMDIM];        /*ray */
  17. double coord[NUMDIM];                /* hit point */
  18. {
  19.     char inside = TRUE;
  20.     char quadrant[NUMDIM];
  21.     register int i;
  22.     int whichPlane;
  23.     double maxT[NUMDIM];
  24.     double candidatePlane[NUMDIM];
  25.  
  26.     /* Find candidate planes; this loop can be avoided if
  27.        rays cast all from the eye(assume perpsective view) */
  28.     for (i=0; i<NUMDIM; i++)
  29.         if(origin[i] < minB[i]) {
  30.             quadrant[i] = LEFT;
  31.             candidatePlane[i] = minB[i];
  32.             inside = FALSE;
  33.         }else if (origin[i] > maxB[i]) {
  34.             quadrant[i] = RIGHT;
  35.             candidatePlane[i] = maxB[i];
  36.             inside = FALSE;
  37.         }else    {
  38.             quadrant[i] = MIDDLE;
  39.         }
  40.  
  41.     /* Ray origin inside bounding box */
  42.     if(inside)    {
  43.         coord = origin;
  44.         return (TRUE);
  45.     }
  46.  
  47.  
  48.     /* Calculate T distances to candidate planes */
  49.     for (i = 0; i < NUMDIM; i++)
  50.         if (quadrant[i] != MIDDLE && dir[i] !=0.)
  51.             maxT[i] = (candidatePlane[i]-origin[i]) / dir[i];
  52.         else
  53.             maxT[i] = -1.;
  54.  
  55.     /* Get largest of the maxT's for final choice of intersection */
  56.     whichPlane = 0;
  57.     for (i = 1; i < NUMDIM; i++)
  58.         if (maxT[whichPlane] < maxT[i])
  59.             whichPlane = i;
  60.  
  61.     /* Check final candidate actually inside box */
  62.     if (maxT[whichPlane] < 0.) return (FALSE);
  63.     for (i = 0; i < NUMDIM; i++)
  64.         if (whichPlane != i) {
  65.             coord[i] = origin[i] + maxT[whichPlane] *dir[i];
  66.             if ((quadrant[i] == RIGHT && coord[i] < minB[i]) ||
  67.                (quadrant[i] == LEFT && coord[i] > maxB[i]))
  68.                return (FALSE);    /* outside box */
  69.             }else {
  70.                 coord[i] = candidatePlane[i];
  71.             }
  72.     return (TRUE);                /* ray hits box */
  73. }    
  74.  
  75.