Преглед изворни кода

Fixed possible divide by zero issues.

Fixed several areas in the point class that could have a divide by zero
issue.
Nathan Bowhay пре 10 година
родитељ
комит
c7e0d83587
1 измењених фајлова са 28 додато и 1 уклоњено
  1. 28 1
      Engine/source/math/mPoint3.h

+ 28 - 1
Engine/source/math/mPoint3.h

@@ -233,11 +233,13 @@ class Point3D
    bool  isZero() const;
    F64 len()    const;
    F64 lenSquared() const;
+   F64 magnitudeSafe() const;
 
    //-------------------------------------- Mathematical mutators
   public:
    void neg();
    void normalize();
+   void normalizeSafe();
    void normalize(F64 val);
    void convolve(const Point3D&);
    void convolveInverse(const Point3D&);
@@ -728,11 +730,13 @@ inline Point3F& Point3F::operator*=(const Point3F &_vec)
 
 inline Point3F Point3F::operator/(const Point3F &_vec) const
 {
+   AssertFatal(_vec.x != 0.0f && _vec.y != 0.0f && _vec.z != 0.0f, "Error, div by zero attempted");
    return Point3F(x / _vec.x, y / _vec.y, z / _vec.z);
 }
 
 inline Point3F& Point3F::operator/=(const Point3F &_vec)
 {
+   AssertFatal(_vec.x != 0.0f && _vec.y != 0.0f && _vec.z != 0.0f, "Error, div by zero attempted");
    x /= _vec.x;
    y /= _vec.y;
    z /= _vec.z;
@@ -855,7 +859,8 @@ inline F64 Point3D::lenSquared() const
 
 inline F64 Point3D::len() const
 {
-   return mSqrtD(x*x + y*y + z*z);
+	F64 temp = x*x + y*y + z*z;
+	return (temp > 0.0) ? mSqrtD(x*x + y*y + z*z) : 0.0;
 }
 
 inline void Point3D::normalize()
@@ -863,6 +868,28 @@ inline void Point3D::normalize()
    m_point3D_normalize(*this);
 }
 
+inline F64 Point3D::magnitudeSafe() const
+{
+   if( isZero() )
+   {
+      return 0.0;
+   }
+   else
+   {
+      return len();
+   }
+}
+
+inline void Point3D::normalizeSafe()
+{
+   F64 vmag = magnitudeSafe();
+
+   if( vmag > POINT_EPSILON )
+   {
+      *this *= F64(1.0 / vmag);
+   }
+}
+
 inline void Point3D::normalize(F64 val)
 {
    m_point3D_normalize_f(*this, val);