math_util.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <algorithm>
  6. #include <cstdlib>
  7. #include <type_traits>
  8. namespace MathUtil {
  9. static constexpr float PI = 3.14159265f;
  10. inline bool IntervalsIntersect(unsigned start0, unsigned length0, unsigned start1,
  11. unsigned length1) {
  12. return (std::max(start0, start1) < std::min(start0 + length0, start1 + length1));
  13. }
  14. template <typename T>
  15. inline T Clamp(const T val, const T& min, const T& max) {
  16. return std::max(min, std::min(max, val));
  17. }
  18. template <class T>
  19. struct Rectangle {
  20. T left;
  21. T top;
  22. T right;
  23. T bottom;
  24. Rectangle() {}
  25. Rectangle(T left, T top, T right, T bottom)
  26. : left(left), top(top), right(right), bottom(bottom) {}
  27. T GetWidth() const {
  28. return std::abs(static_cast<typename std::make_signed<T>::type>(right - left));
  29. }
  30. T GetHeight() const {
  31. return std::abs(static_cast<typename std::make_signed<T>::type>(bottom - top));
  32. }
  33. Rectangle<T> TranslateX(const T x) const {
  34. return Rectangle{left + x, top, right + x, bottom};
  35. }
  36. Rectangle<T> TranslateY(const T y) const {
  37. return Rectangle{left, top + y, right, bottom + y};
  38. }
  39. Rectangle<T> Scale(const float s) const {
  40. return Rectangle{left, top, static_cast<T>(left + GetWidth() * s),
  41. static_cast<T>(top + GetHeight() * s)};
  42. }
  43. };
  44. } // namespace MathUtil