Rect.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /** @file Rect.h
  2. @author Jukka Jylänki
  3. This work is released to Public Domain, do whatever you want with it.
  4. */
  5. #pragma once
  6. #include <cassert>
  7. //#undef assert
  8. //#define assert(x) DEBUG_ASSERT(x, "rects")
  9. #if DEBUG
  10. #define debug_assert(x) assert(x)
  11. #else
  12. #define debug_assert(x)
  13. #endif
  14. struct RectSize
  15. {
  16. int width;
  17. int height;
  18. };
  19. struct RectSizeIndex : RectSize
  20. {
  21. int index;
  22. };
  23. struct Rect
  24. {
  25. int x;
  26. int y;
  27. int width;
  28. int height;
  29. };
  30. struct RectIndex : Rect
  31. {
  32. int index;
  33. };
  34. /// Performs a lexicographic compare on (rect short side, rect long side).
  35. /// @return -1 if the smaller side of a is shorter than the smaller side of b, 1 if the other way around.
  36. /// If they are equal, the larger side length is used as a tie-breaker.
  37. /// If the rectangles are of same size, returns 0.
  38. int CompareRectShortSide(const Rect &a, const Rect &b);
  39. /// Performs a lexicographic compare on (x, y, width, height).
  40. int NodeSortCmp(const Rect &a, const Rect &b);
  41. /// Returns true if a is contained in b.
  42. bool IsContainedIn(const Rect &a, const Rect &b);
  43. #if DEBUG
  44. class DisjointRectCollection
  45. {
  46. public:
  47. Memc<Rect> rects;
  48. bool Add(const Rect &r)
  49. {
  50. // Degenerate rectangles are ignored.
  51. if (r.width == 0 || r.height == 0)
  52. return true;
  53. if (!Disjoint(r))
  54. return false;
  55. rects.add(r);
  56. return true;
  57. }
  58. void Clear()
  59. {
  60. rects.clear();
  61. }
  62. bool Disjoint(const Rect &r) const
  63. {
  64. // Degenerate rectangles are ignored.
  65. if (r.width == 0 || r.height == 0)
  66. return true;
  67. FREPA(rects)
  68. if (!Disjoint(rects[i], r))
  69. return false;
  70. return true;
  71. }
  72. static bool Disjoint(const Rect &a, const Rect &b)
  73. {
  74. if (a.x + a.width <= b.x ||
  75. b.x + b.width <= a.x ||
  76. a.y + a.height <= b.y ||
  77. b.y + b.height <= a.y)
  78. return true;
  79. return false;
  80. }
  81. };
  82. #endif