- More work on scripting interface
[supertux.git] / src / math / rectangle.h
1 #ifndef __RECTANGLE_H__
2 #define __RECTANGLE_H__
3
4 #include <assert.h>
5 #include "vector.h"
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 Rectangle
13 {
14 public:
15   Rectangle()
16   { }
17
18   Rectangle(const Vector& np1, const Vector& np2)
19     : p1(np1), p2(np2)
20   {
21   }
22
23   Rectangle(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_width() const
30   { return p2.x - p1.x; }
31
32   float get_height() const
33   { return p2.y - p1.y; }
34
35   Vector get_middle() const
36   { return Vector((p1.x+p2.x)/2, (p1.y+p2.y)/2); }
37
38   void set_pos(const Vector& v)
39   {
40     move(v-p1);
41   }
42
43   void set_height(float height)
44   {
45     p2.y = p1.y + height;
46   }
47   void set_width(float width)
48   {
49     p2.x = p1.x + width;
50   }
51   void set_size(float width, float height)
52   {
53     set_width(width);
54     set_height(height);
55   }                                         
56
57   void move(const Vector& v)
58   {
59     p1 += v;
60     p2 += v;
61   }
62
63   bool inside(const Vector& v) const
64   {
65     return v.x >= p1.x && v.y >= p1.y && v.x < p2.x && v.y < p2.y;
66   }
67   bool inside(const Rectangle& other) const
68   {
69     if(p1.x >= other.p2.x || other.p1.x >= p2.x)
70       return false;
71     if(p1.y >= other.p2.y || other.p1.y >= p2.y)
72       return false;
73
74     return true;
75   }
76    
77   // leave these 2 public to safe the headaches of set/get functions for such
78   // simple things :)
79
80   /// upper left edge
81   Vector p1;
82   /// lower right edge
83   Vector p2;
84 };
85
86 #endif
87