f7179a9e703397ffb84f874c60b4e6c974eba43c
[supertux.git] / src / math / rect.hpp
1 #ifndef __RECT_H__
2 #define __RECT_H__
3
4 #include <assert.h>
5 #include "vector.hpp"
6
7 /** This class represents a rectangle.
8  * (Implementation Note) We're using upper left and lower right point instead of
9  * upper left and width/height here, because that makes the collision dectection
10  * a little bit efficienter.
11  */
12 class Rect
13 {
14 public:
15   Rect()
16   { }
17
18   Rect(const Vector& np1, const Vector& np2)
19     : p1(np1), p2(np2)
20   {
21   }
22
23   Rect(float x1, float y1, float x2, float y2)
24     : p1(x1, y1), p2(x2, y2)
25   {
26     assert(p1.x <= p2.x && p1.y <= p2.y);
27   }
28
29   float get_left() const
30   { return p1.x; }
31
32   float get_right() const
33   { return p2.x; }
34
35   float get_top() const
36   { return p1.y; }
37
38   float get_bottom() const
39   { return p2.y; }
40
41   float get_width() const
42   { return p2.x - p1.x; }
43
44   float get_height() const
45   { return p2.y - p1.y; }
46
47   Vector get_middle() const
48   { return Vector((p1.x+p2.x)/2, (p1.y+p2.y)/2); }
49
50   void set_pos(const Vector& v)
51   {
52     move(v-p1);
53   }
54
55   void set_height(float height)
56   {
57     p2.y = p1.y + height;
58   }
59   void set_width(float width)
60   {
61     p2.x = p1.x + width;
62   }
63   void set_size(float width, float height)
64   {
65     set_width(width);
66     set_height(height);
67   }                                         
68
69   void move(const Vector& v)
70   {
71     p1 += v;
72     p2 += v;
73   }
74
75   bool inside(const Vector& v) const
76   {
77     return v.x >= p1.x && v.y >= p1.y && v.x < p2.x && v.y < p2.y;
78   }
79   bool inside(const Rect& other) const
80   {
81     if(p1.x >= other.p2.x || other.p1.x >= p2.x)
82       return false;
83     if(p1.y >= other.p2.y || other.p1.y >= p2.y)
84       return false;
85
86     return true;
87   }
88    
89   // leave these 2 public to safe the headaches of set/get functions for such
90   // simple things :)
91
92   /// upper left edge
93   Vector p1;
94   /// lower right edge
95   Vector p2;
96 };
97
98 #endif
99