Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/jolt_physics/Jolt/Geometry/Ellipse.h
9913 views
1
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3
// SPDX-License-Identifier: MIT
4
5
#pragma once
6
7
#include <Jolt/Math/Float2.h>
8
9
JPH_NAMESPACE_BEGIN
10
11
/// Ellipse centered around the origin
12
/// @see https://en.wikipedia.org/wiki/Ellipse
13
class Ellipse
14
{
15
public:
16
JPH_OVERRIDE_NEW_DELETE
17
18
/// Construct ellipse with radius A along the X-axis and B along the Y-axis
19
Ellipse(float inA, float inB) : mA(inA), mB(inB) { JPH_ASSERT(inA > 0.0f); JPH_ASSERT(inB > 0.0f); }
20
21
/// Check if inPoint is inside the ellipse
22
bool IsInside(const Float2 &inPoint) const
23
{
24
return Square(inPoint.x / mA) + Square(inPoint.y / mB) <= 1.0f;
25
}
26
27
/// Get the closest point on the ellipse to inPoint
28
/// Assumes inPoint is outside the ellipse
29
/// @see Rotation Joint Limits in Quaternion Space by Gino van den Bergen, section 10.1 in Game Engine Gems 3.
30
Float2 GetClosestPoint(const Float2 &inPoint) const
31
{
32
float a_sq = Square(mA);
33
float b_sq = Square(mB);
34
35
// Equation of ellipse: f(x, y) = (x/a)^2 + (y/b)^2 - 1 = 0 [1]
36
// Normal on surface: (df/dx, df/dy) = (2 x / a^2, 2 y / b^2)
37
// Closest point (x', y') on ellipse to point (x, y): (x', y') + t (x / a^2, y / b^2) = (x, y)
38
// <=> (x', y') = (a^2 x / (t + a^2), b^2 y / (t + b^2))
39
// 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
40
41
// Newton Raphson iteration, starting at t = 0
42
float t = 0.0f;
43
for (;;)
44
{
45
// Calculate g(t)
46
float t_plus_a_sq = t + a_sq;
47
float t_plus_b_sq = t + b_sq;
48
float gt = Square(mA * inPoint.x / t_plus_a_sq) + Square(mB * inPoint.y / t_plus_b_sq) - 1.0f;
49
50
// Check if g(t) it is close enough to zero
51
if (abs(gt) < 1.0e-6f)
52
return Float2(a_sq * inPoint.x / t_plus_a_sq, b_sq * inPoint.y / t_plus_b_sq);
53
54
// Get derivative dg/dt = g'(t) = -2 (b^2 y^2 / (t + b^2)^3 + a^2 x^2 / (t + a^2)^3)
55
float gt_accent = -2.0f *
56
(a_sq * Square(inPoint.x) / Cubed(t_plus_a_sq)
57
+ b_sq * Square(inPoint.y) / Cubed(t_plus_b_sq));
58
59
// Calculate t for next iteration: tn+1 = tn - g(t) / g'(t)
60
float tn = t - gt / gt_accent;
61
t = tn;
62
}
63
}
64
65
/// Get normal at point inPoint (non-normalized vector)
66
Float2 GetNormal(const Float2 &inPoint) const
67
{
68
// Calculated by [d/dx f(x, y), d/dy f(x, y)], where f(x, y) is the ellipse equation from above
69
return Float2(inPoint.x / Square(mA), inPoint.y / Square(mB));
70
}
71
72
private:
73
float mA; ///< Radius along X-axis
74
float mB; ///< Radius along Y-axis
75
};
76
77
JPH_NAMESPACE_END
78
79