diff options
Diffstat (limited to 'src/common/math_util.h')
-rw-r--r-- | src/common/math_util.h | 50 |
1 files changed, 45 insertions, 5 deletions
diff --git a/src/common/math_util.h b/src/common/math_util.h index 510c4e56d..54485bf53 100644 --- a/src/common/math_util.h +++ b/src/common/math_util.h @@ -4,6 +4,7 @@ #pragma once +#include <algorithm> #include <cstdlib> #include <type_traits> @@ -20,10 +21,32 @@ struct Rectangle { constexpr Rectangle() = default; + constexpr Rectangle(T width, T height) : right(width), bottom(height) {} + constexpr Rectangle(T left_, T top_, T right_, T bottom_) : left(left_), top(top_), right(right_), bottom(bottom_) {} - [[nodiscard]] T GetWidth() const { + [[nodiscard]] constexpr T Left() const { + return left; + } + + [[nodiscard]] constexpr T Top() const { + return top; + } + + [[nodiscard]] constexpr T Right() const { + return right; + } + + [[nodiscard]] constexpr T Bottom() const { + return bottom; + } + + [[nodiscard]] constexpr bool IsEmpty() const { + return (GetWidth() <= 0) || (GetHeight() <= 0); + } + + [[nodiscard]] constexpr T GetWidth() const { if constexpr (std::is_floating_point_v<T>) { return std::abs(right - left); } else { @@ -31,7 +54,7 @@ struct Rectangle { } } - [[nodiscard]] T GetHeight() const { + [[nodiscard]] constexpr T GetHeight() const { if constexpr (std::is_floating_point_v<T>) { return std::abs(bottom - top); } else { @@ -39,18 +62,35 @@ struct Rectangle { } } - [[nodiscard]] Rectangle<T> TranslateX(const T x) const { + [[nodiscard]] constexpr Rectangle<T> TranslateX(const T x) const { return Rectangle{left + x, top, right + x, bottom}; } - [[nodiscard]] Rectangle<T> TranslateY(const T y) const { + [[nodiscard]] constexpr Rectangle<T> TranslateY(const T y) const { return Rectangle{left, top + y, right, bottom + y}; } - [[nodiscard]] Rectangle<T> Scale(const float s) const { + [[nodiscard]] constexpr Rectangle<T> Scale(const float s) const { return Rectangle{left, top, static_cast<T>(static_cast<float>(left + GetWidth()) * s), static_cast<T>(static_cast<float>(top + GetHeight()) * s)}; } + + [[nodiscard]] constexpr bool operator==(const Rectangle<T>& rhs) const { + return (left == rhs.left) && (top == rhs.top) && (right == rhs.right) && + (bottom == rhs.bottom); + } + + [[nodiscard]] constexpr bool operator!=(const Rectangle<T>& rhs) const { + return !operator==(rhs); + } + + [[nodiscard]] constexpr bool Intersect(const Rectangle<T>& with, Rectangle<T>* result) const { + result->left = std::max(left, with.left); + result->top = std::max(top, with.top); + result->right = std::min(right, with.right); + result->bottom = std::min(bottom, with.bottom); + return !result->IsEmpty(); + } }; template <typename T> |