Game Development Community

Box3F::collideLine()

by asmaloney (Andy) · in Torque Game Engine · 01/19/2007 (11:47 am) · 0 replies

Here's a version of Box3F::collideLine() which - for my profiling runs on gcc/PPC - reduced the time from 1.6% to 1.3%. Simple changes - removed unecessary Point3F copying and use floats instead of ints to reduce type cast penalties.

bool Box3F::collideLine(const Point3F& start, const Point3F& end, F32* t, Point3F* n) const
{
   // Collide against bounding box. Need at least this for the editor.
   F32 st,et;
   F32 fst = 0.0f;
   F32 fet = 1.0f;
   const F32* bmin = &min.x;
   const F32* bmax = &max.x;
   const F32* si   = &start.x;
   const F32* ei   = &end.x;

   static const Point3F na[3] = { Point3F(1.0f, 0.0f, 0.0f), Point3F(0.0f, 1.0f, 0.0f), Point3F(0.0f, 0.0f, 1.0f) };
   Point3F finalNormal;

   for (int i = 0; i < 3; i++) {
	  bool	n_neg = false;
      if (si[i] < ei[i]) {
         if (si[i] > bmax[i] || ei[i] < bmin[i])
            return false;
         F32 di = ei[i] - si[i];
         st = (si[i] < bmin[i]) ? (bmin[i] - si[i]) / di : 0.0f;
         et = (ei[i] > bmax[i]) ? (bmax[i] - si[i]) / di : 1.0f;
	n_neg = true;
      }
      else {
         if (ei[i] > bmax[i] || si[i] < bmin[i])
            return false;
         F32 di = ei[i] - si[i];
         st = (si[i] > bmax[i]) ? (bmax[i] - si[i]) / di : 0.0f;
         et = (ei[i] < bmin[i]) ? (bmin[i] - si[i]) / di : 1.0f;
      }
      if (st > fst) {
         fst = st;
		 finalNormal = na[i];
		 if ( n_neg )
			finalNormal.neg();
      }
      if (et < fet)
         fet = et;

      if (fet < fst)
         return false;
   }

   *t = fst;
   *n = finalNormal;
   return true;
}