Path: blob/master/thirdparty/jolt_physics/Jolt/Geometry/Ellipse.h
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Math/Float2.h>78JPH_NAMESPACE_BEGIN910/// Ellipse centered around the origin11/// @see https://en.wikipedia.org/wiki/Ellipse12class Ellipse13{14public:15JPH_OVERRIDE_NEW_DELETE1617/// Construct ellipse with radius A along the X-axis and B along the Y-axis18Ellipse(float inA, float inB) : mA(inA), mB(inB) { JPH_ASSERT(inA > 0.0f); JPH_ASSERT(inB > 0.0f); }1920/// Check if inPoint is inside the ellipse21bool IsInside(const Float2 &inPoint) const22{23return Square(inPoint.x / mA) + Square(inPoint.y / mB) <= 1.0f;24}2526/// Get the closest point on the ellipse to inPoint27/// Assumes inPoint is outside the ellipse28/// @see Rotation Joint Limits in Quaternion Space by Gino van den Bergen, section 10.1 in Game Engine Gems 3.29Float2 GetClosestPoint(const Float2 &inPoint) const30{31float a_sq = Square(mA);32float b_sq = Square(mB);3334// Equation of ellipse: f(x, y) = (x/a)^2 + (y/b)^2 - 1 = 0 [1]35// Normal on surface: (df/dx, df/dy) = (2 x / a^2, 2 y / b^2)36// Closest point (x', y') on ellipse to point (x, y): (x', y') + t (x / a^2, y / b^2) = (x, y)37// <=> (x', y') = (a^2 x / (t + a^2), b^2 y / (t + b^2))38// Requiring point to be on ellipse (substituting into [1]): g(t) = (a x / (t + a^2))^2 + (b y / (t + b^2))^2 - 1 = 03940// Newton Raphson iteration, starting at t = 041float t = 0.0f;42for (;;)43{44// Calculate g(t)45float t_plus_a_sq = t + a_sq;46float t_plus_b_sq = t + b_sq;47float gt = Square(mA * inPoint.x / t_plus_a_sq) + Square(mB * inPoint.y / t_plus_b_sq) - 1.0f;4849// Check if g(t) it is close enough to zero50if (abs(gt) < 1.0e-6f)51return Float2(a_sq * inPoint.x / t_plus_a_sq, b_sq * inPoint.y / t_plus_b_sq);5253// Get derivative dg/dt = g'(t) = -2 (b^2 y^2 / (t + b^2)^3 + a^2 x^2 / (t + a^2)^3)54float gt_accent = -2.0f *55(a_sq * Square(inPoint.x) / Cubed(t_plus_a_sq)56+ b_sq * Square(inPoint.y) / Cubed(t_plus_b_sq));5758// Calculate t for next iteration: tn+1 = tn - g(t) / g'(t)59float tn = t - gt / gt_accent;60t = tn;61}62}6364/// Get normal at point inPoint (non-normalized vector)65Float2 GetNormal(const Float2 &inPoint) const66{67// Calculated by [d/dx f(x, y), d/dy f(x, y)], where f(x, y) is the ellipse equation from above68return Float2(inPoint.x / Square(mA), inPoint.y / Square(mB));69}7071private:72float mA; ///< Radius along X-axis73float mB; ///< Radius along Y-axis74};7576JPH_NAMESPACE_END777879