math_util.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. inline bool IntervalsIntersect(unsigned start0, unsigned length0, unsigned start1,
  10. unsigned length1) {
  11. return (std::max(start0, start1) < std::min(start0 + length0, start1 + length1));
  12. }
  13. template <typename T>
  14. inline T Clamp(const T val, const T& min, const T& max) {
  15. return std::max(min, std::min(max, val));
  16. }
  17. template <class T>
  18. struct Rectangle {
  19. T left;
  20. T top;
  21. T right;
  22. T bottom;
  23. Rectangle() {}
  24. Rectangle(T left, T top, T right, T bottom)
  25. : left(left), top(top), right(right), bottom(bottom) {}
  26. T GetWidth() const {
  27. return std::abs(static_cast<typename std::make_signed<T>::type>(right - left));
  28. }
  29. T GetHeight() const {
  30. return std::abs(static_cast<typename std::make_signed<T>::type>(bottom - top));
  31. }
  32. Rectangle<T> TranslateX(const T x) const {
  33. return Rectangle{left + x, top, right + x, bottom};
  34. }
  35. Rectangle<T> TranslateY(const T y) const {
  36. return Rectangle{left, top + y, right, bottom + y};
  37. }
  38. Rectangle<T> Scale(const float s) const {
  39. return Rectangle{left, top, static_cast<T>(left + GetWidth() * s),
  40. static_cast<T>(top + GetHeight() * s)};
  41. }
  42. };
  43. } // namespace MathUtil