00001 #ifndef PHX_RECTANGLE_H
00002 #define PHX_RECTANGLE_H
00003
00004 #include <math.h>
00005 #include <algorithm>
00006
00013 namespace Phx {
00014
00035 template <typename T = double>
00036 class Rectangle {
00037 public:
00038 Rectangle() : mX0(0), mY0(0), mX1(0), mY1(0) {}
00039 Rectangle(T x0, T y0, T x1, T y1) :
00040 mX0(x0), mY0(y0), mX1(x1), mY1(y1) {}
00041
00042 T x0(void) const { return mX0; }
00043 T y0(void) const { return mY0; }
00044 T x1(void) const { return mX1; }
00045 T y1(void) const { return mY1; }
00046
00047 T left(void) const { return std::min(mX0, mX1); }
00048 T right(void) const { return std::max(mX0, mX1); }
00049 T top(void) const { return std::max(mY0, mY1); }
00050 T bottom(void) const { return std::min(mY0, mY1); }
00051
00052 T width(void) const { return fabs(mX0-mX1); }
00053 T height(void) const { return fabs(mY0-mY1); }
00054
00055 void x0(T x0) { mX0 = x0; }
00056 void y0(T y0) { mY0 = y0; }
00057 void x1(T x1) { mX1 = x1; }
00058 void y1(T y1) { mY1 = y1; }
00059
00065 T area(void) const { return width()*height(); }
00066
00072 T perimeter(void) const { return (width()+height())*2; }
00073
00081 bool empty(void) const { return (width() == 0) || (height() == 0); }
00082
00101 Rectangle intersection(const Rectangle& R) const {
00102 T l = std::max(left(), R.left());
00103 T r = std::min(right(), R.right());
00104 T t = std::min(top(), R.top());
00105 T b = std::max(bottom(), R.bottom());
00106 if (b < t) { t = b = (t - b) / 2; }
00107 if (r < l) { l = r = (l - r) / 2; }
00108
00109 return Rectangle(l, t, r, b);
00110 }
00111
00127 Rectangle cover(const Rectangle& R) const {
00128 T l = std::min(left(), R.left());
00129 T r = std::max(right(), R.right());
00130 T t = std::max(top(), R.top());
00131 T b = std::min(bottom(), R.bottom());
00132 return Rectangle(l, t, r, b);
00133 }
00134
00135
00136
00146 bool operator==(const Rectangle& r) {
00147 return (r.x0()==x0() && r.x1()==x1() &&
00148 r.y0()==y0() && r.y1()==y1());
00149 }
00150
00151 private:
00152 T mX0, mY0, mX1, mY1;
00153 };
00154
00155 };
00156
00157 #endif