1//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
2//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
3#include "Math/BsRect2.h"
4#include "Math/BsVector2.h"
5#include "Math/BsMatrix4.h"
6#include "Math/BsMath.h"
7
8namespace bs
9{
10 const Rect2 Rect2::EMPTY;
11
12 bool Rect2::contains(const Vector2& point) const
13 {
14 if(point.x >= x && point.x <= (x + width))
15 {
16 if(point.y >= y && point.y <= (y + height))
17 return true;
18 }
19
20 return false;
21 }
22
23 bool Rect2::overlaps(const Rect2& other) const
24 {
25 float otherRight = other.x + other.width;
26 float myRight = x + width;
27
28 float otherBottom = other.y + other.height;
29 float myBottom = y + height;
30
31 if(x < otherRight && myRight > other.x &&
32 y < otherBottom && myBottom > other.y)
33 return true;
34
35 return false;
36 }
37
38 void Rect2::encapsulate(const Rect2& other)
39 {
40 float myRight = x + width;
41 float myBottom = y + height;
42 float otherRight = other.x + other.width;
43 float otherBottom = other.y + other.height;
44
45 if(other.x < x)
46 x = other.x;
47
48 if(other.y < y)
49 y = other.y;
50
51 if(otherRight > myRight)
52 width = otherRight - x;
53 else
54 width = myRight - x;
55
56 if(otherBottom > myBottom)
57 height = otherBottom - y;
58 else
59 height = myBottom - y;
60 }
61
62 void Rect2::clip(const Rect2& clipRect)
63 {
64 float newLeft = std::max(x, clipRect.x);
65 float newTop = std::max(y, clipRect.y);
66
67 float newRight = std::min(x + width, clipRect.x + clipRect.width);
68 float newBottom = std::min(y + height, clipRect.y + clipRect.height);
69
70 x = newLeft;
71 y = newTop;
72 width = newRight - newLeft;
73 height = newBottom - newTop;
74 }
75
76 void Rect2::transform(const Matrix4& matrix)
77 {
78 Vector4 verts[4];
79 verts[0] = Vector4(x, y, 0.0f, 1.0f);
80 verts[1] = Vector4(x + width, y, 0.0f, 1.0f);
81 verts[2] = Vector4(x, y + height, 0.0f, 1.0f);
82 verts[3] = Vector4(x + width, y + height, 0.0f, 1.0f);
83
84 for(UINT32 i = 0; i < 4; i++)
85 verts[i] = matrix.multiply(verts[i]);
86
87 float minX = std::numeric_limits<float>::max();
88 float maxX = std::numeric_limits<float>::min();
89 float minY = std::numeric_limits<float>::max();
90 float maxY = std::numeric_limits<float>::min();
91
92 for(UINT32 i = 0; i < 4; i++)
93 {
94 if(verts[i].x < minX)
95 minX = verts[i].x;
96
97 if(verts[i].y < minY)
98 minY = verts[i].y;
99
100 if(verts[i].x > maxX)
101 maxX = verts[i].x;
102
103 if(verts[i].y > maxY)
104 maxY = verts[i].y;
105 }
106
107 x = minX;
108 y = minY;
109 width = maxX - x;
110 height = maxY - y;
111 }
112
113 Vector2 Rect2::getCenter() const
114 {
115 return Vector2(x + width * 0.5f, y + height * 0.5f);
116 }
117
118 Vector2 Rect2::getHalfSize() const
119 {
120 return Vector2(width, height) * 0.5f;
121 }
122}
123