James Kuszmaul | 0af658b | 2019-01-25 18:36:29 -0800 | [diff] [blame] | 1 | #ifndef AOS_UTIL_MATH_H_ |
| 2 | #define AOS_UTIL_MATH_H_ |
| 3 | |
| 4 | #include <cmath> |
| 5 | |
| 6 | #include "Eigen/Dense" |
| 7 | |
| 8 | namespace aos { |
| 9 | namespace math { |
| 10 | |
| 11 | // Normalizes an angle to be in (-M_PI, M_PI] |
| 12 | template <typename Scalar> |
| 13 | constexpr Scalar NormalizeAngle(Scalar theta) { |
| 14 | // First clause takes care of getting theta into |
| 15 | // (-3 * M_PI, M_PI) |
| 16 | const int n_pi_pos = (theta + M_PI) / 2.0 / M_PI; |
| 17 | theta -= n_pi_pos * 2.0 * M_PI; |
| 18 | // Next we fix it to cut off the bottom half of the above |
| 19 | // range and bring us into (-M_PI, M_PI] |
| 20 | const int n_pi_neg = (theta - M_PI) / 2.0 / M_PI; |
| 21 | theta -= n_pi_neg * 2.0 * M_PI; |
| 22 | return theta; |
| 23 | } |
| 24 | |
| 25 | // Calculate a - b and return the result in (-M_PI, M_PI] |
| 26 | template <typename Scalar> |
| 27 | constexpr Scalar DiffAngle(Scalar a, Scalar b) { |
| 28 | return NormalizeAngle(a - b); |
| 29 | } |
| 30 | |
| 31 | // Returns whether points A, B, C are arranged in a counter-clockwise manner on |
| 32 | // a 2-D plane. |
| 33 | // Collinear points of any sort will cause this to return false. |
| 34 | // Source: https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ |
| 35 | // Mathod: |
| 36 | // 3 points on a plane will form a triangle (unless they are collinear), e.g.: |
| 37 | // A-------------------C |
| 38 | // \ / |
| 39 | // \ / |
| 40 | // \ / |
| 41 | // \ / |
| 42 | // \ / |
| 43 | // \ / |
| 44 | // \ / |
| 45 | // \ / |
| 46 | // \ / |
| 47 | // B |
| 48 | // We are interested in whether A->B->C is the counter-clockwise direction |
| 49 | // around the triangle (it is in this picture). |
| 50 | // Essentially, we want to know whether the angle between A->B and A->C is |
| 51 | // positive or negative. |
| 52 | // For this, consider the cross-product, where we imagine a third z-axis |
| 53 | // coming out of the page. The cross-product AB x AC will be positive if ABC |
| 54 | // is counter-clockwise and negative if clockwise (and zero if collinear). |
| 55 | // The z-component (which is the only non-zero component) of the cross-product |
| 56 | // is AC.y * AB.x - AB.y * AC.x > 0, which turns into: |
| 57 | // AC.y * AB.x > AB.y * AC.x |
| 58 | // (C.y - A.y) * (B.x - A.x) > (B.y - A.y) * (C.x - A.x) |
| 59 | // which is exactly what we have below. |
| 60 | template <typename Scalar> |
| 61 | constexpr bool PointsAreCCW(const Eigen::Ref<Eigen::Matrix<Scalar, 2, 1>> &A, |
| 62 | const Eigen::Ref<Eigen::Matrix<Scalar, 2, 1>> &B, |
| 63 | const Eigen::Ref<Eigen::Matrix<Scalar, 2, 1>> &C) { |
| 64 | return (C.y() - A.y()) * (B.x() - A.x()) > (B.y() - A.y()) * (C.x() - A.x()); |
| 65 | } |
| 66 | |
| 67 | } // namespace math |
| 68 | } // namespace aos |
| 69 | |
| 70 | #endif // AOS_UTIL_MATH_H_ |