Ellipse.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Math/Float2.h>
  5. JPH_NAMESPACE_BEGIN
  6. /// Ellipse centered around the origin
  7. /// @see https://en.wikipedia.org/wiki/Ellipse
  8. class Ellipse
  9. {
  10. public:
  11. JPH_OVERRIDE_NEW_DELETE
  12. /// Construct ellipse with radius A along the X-axis and B along the Y-axis
  13. Ellipse(float inA, float inB) : mA(inA), mB(inB) { JPH_ASSERT(inA > 0.0f); JPH_ASSERT(inB > 0.0f); }
  14. /// Check if inPoint is inside the ellipsse
  15. bool IsInside(const Float2 &inPoint) const
  16. {
  17. return Square(inPoint.x / mA) + Square(inPoint.y / mB) <= 1.0f;
  18. }
  19. /// Get the closest point on the ellipse to inPoint
  20. /// Assumes inPoint is outside the ellipse
  21. /// @see Rotation Joint Limits in Quaterion Space by Gino van den Bergen, section 10.1 in Game Engine Gems 3.
  22. Float2 GetClosestPoint(const Float2 &inPoint) const
  23. {
  24. float a_sq = Square(mA);
  25. float b_sq = Square(mB);
  26. // Equation of ellipse: f(x, y) = (x/a)^2 + (y/b)^2 - 1 = 0 [1]
  27. // Normal on surface: (df/dx, df/dy) = (2 x / a^2, 2 y / b^2)
  28. // Closest point (x', y') on ellipse to point (x, y): (x', y') + t (x / a^2, y / b^2) = (x, y)
  29. // <=> (x', y') = (a^2 x / (t + a^2), b^2 y / (t + b^2))
  30. // Requiring point to be on ellipse (substituting into [1]): g(t) = (a x / (t + a^2))^2 + (b y / (t + b^2))^2 - 1 = 0
  31. // Newton raphson iteration, starting at t = 0
  32. float t = 0.0f;
  33. for (;;)
  34. {
  35. // Calculate g(t)
  36. float t_plus_a_sq = t + a_sq;
  37. float t_plus_b_sq = t + b_sq;
  38. float gt = Square(mA * inPoint.x / t_plus_a_sq) + Square(mB * inPoint.y / t_plus_b_sq) - 1.0f;
  39. // Check if g(t) it is close enough to zero
  40. if (abs(gt) < 1.0e-6f)
  41. return Float2(a_sq * inPoint.x / t_plus_a_sq, b_sq * inPoint.y / t_plus_b_sq);
  42. // Get derivative dg/dt = g'(t) = -2 (b^2 y^2 / (t + b^2)^3 + a^2 x^2 / (t + a^2)^3)
  43. float gt_accent = -2.0f *
  44. (a_sq * Square(inPoint.x) / Cubed(t_plus_a_sq)
  45. + b_sq * Square(inPoint.y) / Cubed(t_plus_b_sq));
  46. // Calculate t for next iteration: tn+1 = tn - g(t) / g'(t)
  47. float tn = t - gt / gt_accent;
  48. t = tn;
  49. }
  50. }
  51. /// Get normal at point inPoint (non-normalized vector)
  52. Float2 GetNormal(const Float2 &inPoint) const
  53. {
  54. // Calculated by [d/dx f(x, y), d/dy f(x, y)], where f(x, y) is the ellipse equation from above
  55. return Float2(inPoint.x / Square(mA), inPoint.y / Square(mB));
  56. }
  57. private:
  58. float mA; ///< Radius along X-axis
  59. float mB; ///< Radius along Y-axis
  60. };
  61. JPH_NAMESPACE_END