1 module nudsfml.graphics.rect;
2 
3 import std.traits;
4 
5 import nudsfml.system.vector2;
6 
7 struct Rect(T)
8     if(isNumeric!(T))
9 {
10     T left = 0;
11     T top = 0;
12     T width = 0;;
13     T height = 0;
14 
15     this(T rectLeft, T rectTop, T rectWidth, T rectHeight){
16         left = rectLeft;
17         top = rectTop;
18         width = rectWidth;
19         height = rectHeight;
20     }
21 
22     this(Vector2!(T) position, Vector2!(T) size){
23         left = position.x;
24         top = position.y;
25         width = size.x;
26         height = size.y;
27     }
28 
29     bool contains(E)(E x, E y) const
30         if(isNumeric!(E))
31     {
32         return x >= left && x <= left + width && y >= top && y <= top + height;
33     }
34 
35     bool contains(E)(Vector2!(E) point) const
36         if(isNumeric!(E))
37     {
38         return contains(point.x, point.y);
39     }
40 
41     bool intersects(E)(Rect!(E) rectangle) const
42         if(isNumeric!(E)) 
43     {
44         Rect!(T) rect;
45         return intersects(rectangle, rect);
46 
47     }
48 
49     bool intersects(E)(Rect!(E) rectangle, out Rect!(E) intersection) const 
50         if(isNumeric!(E)) 
51     {
52         E interLeft = max(left, rectangle.left);
53         E interTop = max(top, rectangle.top);
54         E interRight = min(left + width, rectangle.left + rectangle.width);
55         E interBottom = min(top + height, rectangle.top + rectangle.height);
56 
57         if(interLeft < interRight && interTop < interBottom) {
58             intersection = Rect!(E)(interLeft, interTop, interRight - interLeft, interBottom - interTop);
59             return true;
60         } else {
61             intersection = Rect!(E)(0, 0, 0, 0);
62             return false;
63         }
64     }
65 
66     bool opEquals(E)(const Rect!(E) otherRect) const
67         if(isNumeric!(E)) 
68     {
69         return ((left == otherRect.left) && (top == otherRect.top) && 
70                 (width == otherRect.width) && (height == otherRect.height));
71     }
72 
73     string toString() const {
74         import std.conv;
75         return "Rect(" ~ text(left) ~ ", " ~ text(top) ~ ", " ~ text(width) ~ ", " ~ text(height) ~ ")";
76     }
77 
78     private T max(T a, T b) const {
79         return a > b ? a : b;
80     }
81 
82     private T min(T a, T b) const {
83         return a < b ? a : b;
84     }
85 }
86     
87 alias IntRect = Rect!(int);
88 alias FloatRect = Rect!(float);