From c584b1a00593a07bfd572a3a7fea0cf4b0890093 Mon Sep 17 00:00:00 2001 From: Dmitry Marakasov Date: Tue, 30 Dec 2014 00:14:14 +0300 Subject: [PATCH] Add Rect intersection and union methods --- SDL2pp/Rect.cc | 27 +++++++++++++++++++++++++++ SDL2pp/Rect.hh | 30 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/SDL2pp/Rect.cc b/SDL2pp/Rect.cc index 05cfb78..b2bb830 100644 --- a/SDL2pp/Rect.cc +++ b/SDL2pp/Rect.cc @@ -19,6 +19,8 @@ 3. This notice may not be removed or altered from any source distribution. */ +#include + #include #include @@ -150,6 +152,31 @@ bool Rect::Contains(const Rect& rect) const { return rect.x >= x && rect.y >= y && rect.GetX2() <= GetX2() && rect.GetY2() <= GetY2(); } +bool Rect::Intersects(const Rect& rect) const { + return !(rect.GetX2() < x || rect.GetY2() < y || rect.x > GetX2() || rect.y > GetY2()); +} + +Rect Rect::GetUnion(const Rect& rect) const { + return Rect::FromCorners( + std::min(x, rect.x), + std::min(y, rect.y), + std::max(GetX2(), rect.GetX2()), + std::max(GetY2(), rect.GetY2()) + ); +} + +Optional Rect::GetIntersection(const Rect& rect) const { + if (!Intersects(rect)) + return NullOpt; + + return Rect::FromCorners( + std::max(x, rect.x), + std::max(y, rect.y), + std::min(GetX2(), rect.GetX2()), + std::min(GetY2(), rect.GetY2()) + ); +} + Rect Rect::operator+(const Point& offset) const { return Rect(x + offset.x, y + offset.y, w, h); } diff --git a/SDL2pp/Rect.hh b/SDL2pp/Rect.hh index bedf764..cbf54e9 100644 --- a/SDL2pp/Rect.hh +++ b/SDL2pp/Rect.hh @@ -301,6 +301,36 @@ public: //////////////////////////////////////////////////////////// bool Contains(const Rect& rect) const; + //////////////////////////////////////////////////////////// + /// \brief Check whether the rect intersects another rect + /// + /// \param rect Rect to check + /// + /// \returns True if the rects intersect + /// + //////////////////////////////////////////////////////////// + bool Intersects(const Rect& rect) const; + + //////////////////////////////////////////////////////////// + /// \brief Calculate union with another rect + /// + /// \param rect Rect to union with + /// + /// \returns Rect representing intersection area or NullOpt if there was no intersection + /// + //////////////////////////////////////////////////////////// + Rect GetUnion(const Rect& rect) const; + + //////////////////////////////////////////////////////////// + /// \brief Calculate intersection with another rect + /// + /// \param rect Rect to intersect with + /// + /// \returns Rect representing intersection area or NullOpt if there was no intersection + /// + //////////////////////////////////////////////////////////// + Optional GetIntersection(const Rect& rect) const; + //////////////////////////////////////////////////////////// /// \brief Get rectangle moved by a given offset ///