CmRect.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "CmRect.h"
  2. #include "CmInt2.h"
  3. #include "CmMatrix4.h"
  4. #include "CmMath.h"
  5. namespace CamelotFramework
  6. {
  7. Rect::Rect()
  8. :x(0), y(0), width(0), height(0)
  9. { }
  10. Rect::Rect(int _x, int _y, int _width, int _height)
  11. :x(_x), y(_y), width(_width), height(_height)
  12. { }
  13. bool Rect::contains(const Int2& point) const
  14. {
  15. if(point.x >= x && point.x <= (x + width))
  16. {
  17. if(point.y >= y && point.y <= (y + height))
  18. return true;
  19. }
  20. return false;
  21. }
  22. bool Rect::overlaps(const Rect& other) const
  23. {
  24. INT32 otherRight = other.x + other.width;
  25. INT32 myRight = x + width;
  26. INT32 otherBottom = other.y + other.height;
  27. INT32 myBottom = y + height;
  28. if(x < otherRight && myRight > other.x &&
  29. y < otherBottom && myBottom > other.y)
  30. return true;
  31. return false;
  32. }
  33. void Rect::encapsulate(const Rect& other)
  34. {
  35. int myRight = x + width;
  36. int myBottom = y + height;
  37. int otherRight = other.x + other.width;
  38. int otherBottom = other.y + other.height;
  39. if(other.x < x)
  40. x = other.x;
  41. if(other.y < y)
  42. y = other.y;
  43. if(otherRight > myRight)
  44. width = otherRight - x;
  45. else
  46. width = myRight - x;
  47. if(otherBottom > myBottom)
  48. height = otherBottom - y;
  49. else
  50. height = myBottom - y;
  51. }
  52. void Rect::transform(const Matrix4& matrix)
  53. {
  54. Vector4 verts[4];
  55. verts[0] = Vector4((float)x, (float)y, 0.0f, 1.0f);
  56. verts[1] = Vector4((float)x + width, (float)y, 0.0f, 1.0f);
  57. verts[2] = Vector4((float)x, (float)y + height, 0.0f, 1.0f);
  58. verts[3] = Vector4((float)x + width, (float)y + height, 0.0f, 1.0f);
  59. for(UINT32 i = 0; i < 4; i++)
  60. verts[i] = matrix * verts[i];
  61. float minX = std::numeric_limits<float>::max();
  62. float maxX = std::numeric_limits<float>::min();
  63. float minY = std::numeric_limits<float>::max();
  64. float maxY = std::numeric_limits<float>::min();
  65. for(UINT32 i = 0; i < 4; i++)
  66. {
  67. if(verts[i].x < minX)
  68. minX = verts[i].x;
  69. if(verts[i].y < minY)
  70. minY = verts[i].y;
  71. if(verts[i].x > maxX)
  72. maxX = verts[i].x;
  73. if(verts[i].y > maxY)
  74. maxY = verts[i].y;
  75. }
  76. x = Math::FloorToInt(minX);
  77. y = Math::FloorToInt(minY);
  78. width = Math::CeilToInt(maxX) - x;
  79. height = Math::CeilToInt(maxY) - y;
  80. }
  81. }