1 #ifndef BOX_HXX
  2 #define BOX_HXX
  3 
  4 #include "Ray.hxx"
  5 
  6 class Box
  7 {
  8 public:
  9 	// Bottom left and top right corner
 10 	Vec3f min,max;
 11 
 12 	Box() 
 13 	{ 
 14 		Clear();
 15 	};
 16 
 17 	inline void Extend(Vec3f a)
 18 	{
 19 		min.SetMin(a);
 20 		max.SetMax(a);
 21 	}
 22 
 23 	inline void Extend(Box box)
 24 	{
 25 		Extend(box.min);
 26 		Extend(box.max);
 27 	}
 28 
 29 	inline void Clear()
 30 	{
 31 		min = Vec3f(Infinity);
 32 		max = Vec3f(-Infinity);
 33 	}
 34 
 35 	// Returns volume of the box
 36 	inline float Volume()
 37 	{
 38 		return (max.x - min.x) * (max.y - min.y) * (max.z - min.z);
 39 	}
 40 
 41 	// Ray box intersection
 42 	std::pair<float, float> Intersect(const Ray &ray)
 43 	{
 44 		float low  = Epsilon,
 45 		      high = Infinity,
 46 		      t1,t2,
 47 		      invRayDir;
 48 
 49 		// Doing the slabs algorithm...
 50 		// ... for x
 51 		invRayDir = 1 / ray.dir.x;
 52 		t1        = (min.x - ray.org.x) * invRayDir;
 53 		t2        = (max.x - ray.org.x) * invRayDir;
 54 		if (invRayDir > 0)
 55 		{
 56 		  if (t1 > low) low   = t1;
 57 		  if (t2 < high) high = t2;
 58 		}
 59 		else 
 60 		{
 61 		  if (t2 > low) low   = t2;
 62 		  if (t1 < high) high = t1;
 63 		}
 64 
 65 		// ... for y
 66 		invRayDir = 1 / ray.dir.y;
 67 		t1        = (min.y - ray.org.y) * invRayDir;
 68 		t2        = (max.y - ray.org.y) * invRayDir;
 69 		if (invRayDir > 0)
 70 		{
 71 		  if (t1 > low) low   = t1;
 72 		  if (t2 < high) high = t2;
 73 		}
 74 		else
 75 		{
 76 		  if (t2 > low) low   = t2;
 77 		  if (t1 < high) high = t1;
 78 		}
 79 
 80 		// ... and for z
 81 		invRayDir = 1 / ray.dir.z;
 82 		t1        = (min.z - ray.org.z) * invRayDir;
 83 		t2        = (max.z - ray.org.z) * invRayDir;
 84 		if (invRayDir > 0)
 85 		{
 86 		  if (t1 > low) low   = t1;
 87 		  if (t2 < high) high = t2;
 88 		}
 89 		else
 90 		{
 91 		  if (t2 > low) low   = t2;
 92 		  if (t1 < high) high = t1;
 93 		}
 94 
 95 		if (low > high)
 96 			return std::make_pair(FLT_MAX, -FLT_MAX);
 97 		else
 98 			return std::make_pair(low,     high);
 99 	}
100 };
101 
102 #endif


syntax highlighted by Code2HTML, v. 0.9.1