From 4c219aee1f99226e7afad38509c2f0a7c8100779 Mon Sep 17 00:00:00 2001 From: Brandon DeRosier Date: Thu, 18 Aug 2022 14:54:59 -0700 Subject: [PATCH] Add Point::AngleTo (flutter/engine#35510) --- .../impeller/geometry/geometry_unittests.cc | 29 +++++++++++++++++++ engine/src/flutter/impeller/geometry/point.h | 4 +++ 2 files changed, 33 insertions(+) diff --git a/engine/src/flutter/impeller/geometry/geometry_unittests.cc b/engine/src/flutter/impeller/geometry/geometry_unittests.cc index 8ba3c6e9b7..84eec3be14 100644 --- a/engine/src/flutter/impeller/geometry/geometry_unittests.cc +++ b/engine/src/flutter/impeller/geometry/geometry_unittests.cc @@ -773,6 +773,35 @@ TEST(GeometryTest, PointAbs) { ASSERT_POINT_NEAR(a_abs, expected); } +TEST(GeometryTest, PointAngleTo) { + // Negative result in the CCW (with up = -Y) direction. + { + Point a(1, 1); + Point b(1, -1); + Radians actual = a.AngleTo(b); + Radians expected = Radians{-kPi / 2}; + ASSERT_FLOAT_EQ(actual.radians, expected.radians); + } + + // Check the other direction to ensure the result is signed correctly. + { + Point a(1, -1); + Point b(1, 1); + Radians actual = a.AngleTo(b); + Radians expected = Radians{kPi / 2}; + ASSERT_FLOAT_EQ(actual.radians, expected.radians); + } + + // Differences in magnitude should have no impact on the result. + { + Point a(100, -100); + Point b(0.01, 0.01); + Radians actual = a.AngleTo(b); + Radians expected = Radians{kPi / 2}; + ASSERT_FLOAT_EQ(actual.radians, expected.radians); + } +} + TEST(GeometryTest, CanUseVector3AssignmentOperators) { { Vector3 p(1, 2, 4); diff --git a/engine/src/flutter/impeller/geometry/point.h b/engine/src/flutter/impeller/geometry/point.h index 5fd01ea9a2..04b5461dbe 100644 --- a/engine/src/flutter/impeller/geometry/point.h +++ b/engine/src/flutter/impeller/geometry/point.h @@ -204,6 +204,10 @@ struct TPoint { return *this - axis * this->Dot(axis) * 2; } + constexpr Radians AngleTo(const TPoint& p) const { + return Radians{std::atan2(this->Cross(p), this->Dot(p))}; + } + constexpr bool IsZero() const { return x == 0 && y == 0; } };