LPCGame
A Simple 2d Game Engine
 All Classes Namespaces Functions Variables Enumerations Enumerator Pages
rect.h
1 #ifndef RECT_H
2 #define RECT_H
3 
4 #include <string>
5 #include <sstream>
6 #include <SDL.h>
7 #include "external/json/json.h"
8 #include "vectors.h"
9 
11 
15 template<class T>
16 class Rect {
17 public:
18  Rect() : pos(0, 0), w(0), h(0) {
19  }
27  Rect(T pX, T pY, T pW, T pH) : pos(pX, pY), w(pW), h(pH) {
28  }
35  Rect(Vector2<T> pPos, T pW, T pH){
36  Set(pPos, pW, pH);
37  }
43  Load(val);
44  }
49  void Set(const Rect<T> &r){
50  pos.x = r.pos.x;
51  pos.y = r.pos.y;
52  w = r.w;
53  h = r.h;
54  }
62  void Set(T pX, T pY, T pW, T pH){
63  pos.x = pX;
64  pos.y = pY;
65  w = pW;
66  h = pH;
67  }
74  void Set(Vector2<T> pPos, T pW, T pH){
75  pos = pPos;
76  w = pW;
77  h = pH;
78  }
84  void Set(T pX, T pY){
85  pos.x = pX;
86  pos.y = pY;
87  }
92  void Set(Vector2<T> pPos){
93  pos = pPos;
94  }
96  Vector2<T> Pos() const{
97  return pos;
98  }
100  T X() const{
101  return pos.x;
102  }
104  T Y() const{
105  return pos.y;
106  }
108  T W() const{
109  return w;
110  }
112  T H() const{
113  return h;
114  }
119  Json::Value Save() const {
120  Json::Value val;
121  val["x"] = pos.x;
122  val["y"] = pos.y;
123  val["w"] = w;
124  val["h"] = h;
125  return val;
126  }
131  void Load(Json::Value val){
132  Set(val["x"].asInt(), val["y"].asInt(),
133  val["w"].asInt(), val["h"].asInt());
134  }
136  bool operator == (Rect<T> r) const {
137  return (pos.x == r.X() && pos.y == r.Y()
138  && w == r.w && h == r.h);
139  }
140  Rect<T>& operator += (Vector2f vec){
141  this->pos += vec;
142  return *this;
143  }
144  Rect<T> operator + (const Vector2f v) const{
145  return Rect<T>(pos.x + v.x, pos.y + v.y, w, h);
146  }
147  Rect<T> operator - (const Vector2f v) const{
148  return Rect<T>(pos.x - v.x, pos.y - v.y, w, h);
149  }
151  operator SDL_Rect() const{
152  SDL_Rect rect;
153  rect.x = pos.x;
154  rect.y = pos.y;
155  rect.w = w;
156  rect.h = h;
157  return rect;
158  }
159  operator Rect<float>() const {
160  Rect<float> rect(pos, w, h);
161  return rect;
162  }
163  operator Rect<int>() const {
164  Rect<int> rect(pos, w, h);
165  return rect;
166  }
167  operator std::string() const {
168  std::stringstream s;
169  s << "Rect: (" << (std::string)pos
170  << ", w: " << w << ", h: " << h << ")";
171  return s.str();
172  }
173 
174 public:
175  Vector2<T> pos;
176  T w, h;
177 };
178 
179 typedef Rect<int> Recti;
180 typedef Rect<float> Rectf;
181 typedef Rect<double> Rectd;
182 
183 #endif