| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <utility> |
| 8 | #include <vector> |
| 9 | |
| 10 | namespace Utils::Math { |
| 11 | |
| 12 | /// Performs a linear normalization to a collection of values from an old range |
| 13 | /// to a new range. |
| 14 | /// |
| 15 | /// @note Only works with regular numeric types. |
| 16 | /// |
| 17 | /// @param values collection of values to normalize |
| 18 | /// @param oldRange old range of the values of the collection |
| 19 | /// @param newRange new range for the result of the normalization |
| 20 | template<typename T> |
| 21 | void linearNorm(std::vector<T> &values, std::pair<T, T> const &oldRange, |
| 22 | std::pair<T, T> const &newRange) |
| 23 | { |
| 24 | std::transform(values.cbegin(), values.cend(), values.begin(), [&](T value) { |
| 25 | return static_cast<T>( |
| 26 | (value - oldRange.first) * |
| 27 | (static_cast<double>(newRange.second - newRange.first) / |
| 28 | (oldRange.second - oldRange.first)) + |
| 29 | newRange.first); |
| 30 | }); |
| 31 | } |
| 32 | |
| 33 | /// Performs a lineal interpolation between two points resolving the y value at |
| 34 | /// the supplied x value. |
| 35 | /// |
| 36 | /// @note Only works with regular numeric types. |
| 37 | /// |
| 38 | /// @param value x value to be evaluated |
| 39 | /// @param p1 first point |
| 40 | /// @param p2 second point |
| 41 | /// @return resolved y value |
| 42 | template<typename X, typename Y> |
| 43 | Y lerpX(X value, std::pair<X, Y> const &p1, std::pair<X, Y> const &p2) |
| 44 | { |
| 45 | return static_cast<X>( |
| 46 | (static_cast<double>(p2.second - p1.second) / (p2.first - p1.first)) * |
| 47 | (value - p1.first) + |
| 48 | p1.second); |
| 49 | } |
| 50 | |
| 51 | /// Performs a lineal interpolation between two points resolving the x value at |
| 52 | /// the supplied y value. |
| 53 | /// |
| 54 | /// @note Only works with regular numeric types. |
| 55 | /// |
| 56 | /// @param value y value to be evaluated |
| 57 | /// @param p1 first point |
| 58 | /// @param p2 second point |
| 59 | /// @return resolved x value |
| 60 | template<typename X, typename Y> |
| 61 | X lerpY(Y value, std::pair<X, Y> const &p1, std::pair<X, Y> const &p2) |
| 62 | { |
| 63 | return static_cast<Y>( |
| 64 | (static_cast<double>(p2.first - p1.first) / (p2.second - p1.second)) * |
| 65 | (value - p1.second) + |
| 66 | p1.first); |
| 67 | } |
| 68 | |
| 69 | } // namespace Utils::Math |