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