Rect.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "Rect.h"
  2. #include <AK/StdLibExtras.h>
  3. void Rect::intersect(const Rect& other)
  4. {
  5. int l = max(left(), other.left());
  6. int r = min(right(), other.right());
  7. int t = max(top(), other.top());
  8. int b = min(bottom(), other.bottom());
  9. if (l > r || t > b) {
  10. m_location = { };
  11. m_size = { };
  12. return;
  13. }
  14. m_location.set_x(l);
  15. m_location.set_y(t);
  16. m_size.set_width((r - l) + 1);
  17. m_size.set_height((b - t) + 1);
  18. }
  19. Rect Rect::united(const Rect& other) const
  20. {
  21. if (is_null())
  22. return other;
  23. if (other.is_null())
  24. return *this;
  25. Rect rect;
  26. rect.set_left(min(left(), other.left()));
  27. rect.set_top(min(top(), other.top()));
  28. rect.set_right(max(right(), other.right()));
  29. rect.set_bottom(max(bottom(), other.bottom()));
  30. return rect;
  31. }
  32. Vector<Rect> Rect::shatter(const Rect& hammer) const
  33. {
  34. Vector<Rect> pieces;
  35. if (!intersects(hammer)) {
  36. pieces.append(*this);
  37. return pieces;
  38. }
  39. Rect top_shard {
  40. x(),
  41. y(),
  42. width(),
  43. hammer.y() - y()
  44. };
  45. Rect bottom_shard {
  46. x(),
  47. hammer.y() + hammer.height(),
  48. width(),
  49. (y() + height()) - (hammer.y() + hammer.height())
  50. };
  51. Rect left_shard {
  52. x(),
  53. max(hammer.y(), y()),
  54. hammer.x() - x(),
  55. min((hammer.y() + hammer.height()), (y() + height())) - max(hammer.y(), y())
  56. };
  57. Rect right_shard {
  58. hammer.x() + hammer.width(),
  59. max(hammer.y(), y()),
  60. right() - hammer.right(),
  61. min((hammer.y() + hammer.height()), (y() + height())) - max(hammer.y(), y())
  62. };
  63. if (intersects(top_shard))
  64. pieces.append(top_shard);
  65. if (intersects(bottom_shard))
  66. pieces.append(bottom_shard);
  67. if (intersects(left_shard))
  68. pieces.append(left_shard);
  69. if (intersects(right_shard))
  70. pieces.append(right_shard);
  71. return pieces;
  72. }