00001 // 00002 // Point2D.cpp 00003 // A point in the 2-D plane. 00004 // 00005 00006 #include <cmath> 00007 #include "Point2D.hpp" 00008 #include "../BasicDatatypes.hpp" 00009 00010 namespace datatypes 00011 { 00012 00013 Point2D::value_type Point2D::dist( const Point2D & point ) const 00014 { 00015 return hypot(m_x - point.m_x, m_y - point.m_y); 00016 } 00017 00018 Point2D::value_type Point2D::distSquare( const Point2D & point ) const 00019 { 00020 const value_type x = getX() - point.getX(); 00021 const value_type y = getY() - point.getY(); 00022 return x * x + y * y; 00023 } 00024 00025 Point2D Point2D::fromPolar(value_type r, value_type angle) 00026 { 00027 Point2D p; 00028 p.setPolar(r, angle); 00029 return p; 00030 } 00031 00032 00033 void Point2D::rotate(value_type angle) 00034 { 00035 *this = rotated(angle); 00036 } 00037 00038 Point2D Point2D::rotated(value_type angle_rad) const 00039 { 00040 value_type dCos = cos(angle_rad); 00041 value_type dSin = sin(angle_rad); 00042 return Point2D(m_x * dCos - m_y * dSin, 00043 m_x * dSin + m_y * dCos); 00044 } 00045 00046 Point2D Point2D::normalized() const 00047 { 00048 Point2D result(*this); 00049 result.normalize(); 00050 return result; 00051 } 00052 00053 void Point2D::normalize() 00054 { 00055 if (isZero()) 00056 // Vector has zero length. Such a vector will be left unchanged. 00057 return; 00058 00059 // The division below will be done in float, not in double! Hence, 00060 // we must retrieve the length in float already as well. 00061 value_type len = dist(); 00062 00063 // If isZero() was false above, the distance cannot be zero 00064 // anyway, so checking for this would only result in unreachable 00065 // code. 00066 assert (!fuzzyCompare(len, value_type(0.0))); 00067 00068 *this /= len; 00069 } 00070 00075 std::string Point2D::toString(UINT16 digits) const 00076 { 00077 std::string text = "(" + ::toString(getX(), (int)digits) + ", " + ::toString(getY(), (int)digits) + ")"; 00078 return text; 00079 } 00080 00081 00082 } // namespace datatypes