File indexing completed on 2024-12-15 04:01:13

0001 /*
0002  * SPDX-FileCopyrightText: 2019-2023 Mattia Basaglia <dev@dragon.best>
0003  *
0004  * SPDX-License-Identifier: GPL-3.0-or-later
0005  */
0006 
0007 #pragma once
0008 
0009 #include <cmath>
0010 #include <QtMath>
0011 #include <QtGlobal>
0012 
0013 namespace glaxnimate::math {
0014 
0015 constexpr const qreal pi = 3.14159265358979323846;
0016 constexpr const qreal tau = pi*2;
0017 constexpr const qreal sqrt_2 = M_SQRT2;
0018 constexpr const qreal ellipse_bezier = 0.5519;
0019 
0020 using std::sqrt;
0021 using std::sin;
0022 using std::cos;
0023 using std::tan;
0024 using std::acos;
0025 using std::asin;
0026 using std::atan;
0027 using std::atan2;
0028 using std::pow;
0029 
0030 template<class Numeric>
0031 constexpr Numeric sign(Numeric x) noexcept
0032 {
0033     return x < 0 ? -1 : 1;
0034 }
0035 
0036 constexpr qreal rad2deg(qreal rad) noexcept
0037 {
0038     return rad / pi * 180;
0039 }
0040 
0041 constexpr qreal deg2rad(qreal rad) noexcept
0042 {
0043     return rad * pi / 180;
0044 }
0045 
0046 template<class Numeric>
0047 Numeric fmod(Numeric x, Numeric y)
0048 {
0049     return x < 0 ?
0050         std::fmod(std::fmod(x, y) + y, y) :
0051         std::fmod(x, y)
0052     ;
0053 }
0054 
0055 
0056 template <typename T>
0057 constexpr inline const T & min(const T &a, const T &b) noexcept { return (a < b) ? a : b; }
0058 template <typename T>
0059 constexpr inline const T & max(const T &a, const T &b) noexcept { return (a < b) ? b : a; }
0060 template <typename T>
0061 constexpr  inline const T &bound(const T &vmin, const T &val, const T &vmax) noexcept
0062 { return max(vmin, min(vmax, val)); }
0063 
0064 template<class T> constexpr inline T abs(T t) noexcept { return t < 0 ? -t : t; }
0065 
0066 /**
0067  * \brief Reverses linear interpolation
0068  * \param a First value interpolated from
0069  * \param b Second value interpolated from
0070  * \param c Interpolation result
0071  * \pre a < b && a <= c <= b
0072  * \returns Factor \p f so that lerp(a, b, f) == c
0073  */
0074 template<class T> constexpr qreal unlerp(const T& a, const T& b, const T& c)
0075 {
0076     return qreal(c-a) / qreal(b-a);
0077 }
0078 
0079 
0080 template<class T>
0081 constexpr T lerp(const T& a, const T& b, double factor)
0082 {
0083     return a * (1-factor) + b * factor;
0084 }
0085 
0086 inline qreal sum_squared() { return 0; }
0087 
0088 template<class H, class... T>
0089 inline qreal sum_squared(H head, T... args)
0090 {
0091     return qreal(head) * head + sum_squared(args...);
0092 }
0093 
0094 template<class... T>
0095 inline qreal hypot(T... args)
0096 {
0097     return sqrt(sum_squared(args...));
0098 }
0099 
0100 } // namespace glaxnimate::math