Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h
9912 views
1
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2
// SPDX-FileCopyrightText: 2024 Jorrit Rouwe
3
// SPDX-License-Identifier: MIT
4
5
#pragma once
6
7
#include <Jolt/Core/QuickSort.h>
8
#include <Jolt/Core/STLLocalAllocator.h>
9
#include <Jolt/Physics/Collision/CollisionDispatch.h>
10
11
//#define JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
12
13
#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
14
#include <Jolt/Renderer/DebugRenderer.h>
15
#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
16
17
JPH_NAMESPACE_BEGIN
18
19
/// Removes internal edges from collision results. Can be used to filter out 'ghost collisions'.
20
/// Based on: Contact generation for meshes - Pierre Terdiman (https://www.codercorner.com/MeshContacts.pdf)
21
///
22
/// Note that this class requires that CollideSettingsBase::mActiveEdgeMode == EActiveEdgeMode::CollideWithAll
23
/// and CollideSettingsBase::mCollectFacesMode == ECollectFacesMode::CollectFaces.
24
class InternalEdgeRemovingCollector : public CollideShapeCollector
25
{
26
static constexpr uint cMaxLocalDelayedResults = 32;
27
static constexpr uint cMaxLocalVoidedFeatures = 128;
28
29
/// Check if a vertex is voided
30
inline bool IsVoided(const SubShapeID &inSubShapeID, Vec3 inV) const
31
{
32
for (const Voided &vf : mVoidedFeatures)
33
if (vf.mSubShapeID == inSubShapeID
34
&& inV.IsClose(Vec3::sLoadFloat3Unsafe(vf.mFeature), 1.0e-8f))
35
return true;
36
return false;
37
}
38
39
/// Add all vertices of a face to the voided features
40
inline void VoidFeatures(const CollideShapeResult &inResult)
41
{
42
for (const Vec3 &v : inResult.mShape2Face)
43
if (!IsVoided(inResult.mSubShapeID1, v))
44
{
45
Voided vf;
46
v.StoreFloat3(&vf.mFeature);
47
vf.mSubShapeID = inResult.mSubShapeID1;
48
mVoidedFeatures.push_back(vf);
49
}
50
}
51
52
/// Call the chained collector
53
inline void Chain(const CollideShapeResult &inResult)
54
{
55
// Make sure the chained collector has the same context as we do
56
mChainedCollector.SetContext(GetContext());
57
58
// Forward the hit
59
mChainedCollector.AddHit(inResult);
60
61
// If our chained collector updated its early out fraction, we need to follow
62
UpdateEarlyOutFraction(mChainedCollector.GetEarlyOutFraction());
63
}
64
65
/// Call the chained collector and void all features of inResult
66
inline void ChainAndVoid(const CollideShapeResult &inResult)
67
{
68
Chain(inResult);
69
VoidFeatures(inResult);
70
71
#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
72
DebugRenderer::sInstance->DrawWirePolygon(RMat44::sIdentity(), inResult.mShape2Face, Color::sGreen);
73
DebugRenderer::sInstance->DrawArrow(RVec3(inResult.mContactPointOn2), RVec3(inResult.mContactPointOn2) + inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero()), Color::sGreen, 0.1f);
74
#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
75
}
76
77
public:
78
/// Constructor, configures a collector to be called with all the results that do not hit internal edges
79
explicit InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector) :
80
CollideShapeCollector(inChainedCollector),
81
mChainedCollector(inChainedCollector)
82
{
83
// Initialize arrays to full capacity to avoid needless reallocation calls
84
mVoidedFeatures.reserve(cMaxLocalVoidedFeatures);
85
mDelayedResults.reserve(cMaxLocalDelayedResults);
86
}
87
88
// See: CollideShapeCollector::Reset
89
virtual void Reset() override
90
{
91
CollideShapeCollector::Reset();
92
93
mChainedCollector.Reset();
94
95
mVoidedFeatures.clear();
96
mDelayedResults.clear();
97
}
98
99
// See: CollideShapeCollector::OnBody
100
virtual void OnBody(const Body &inBody) override
101
{
102
// Just forward the call to our chained collector
103
mChainedCollector.OnBody(inBody);
104
}
105
106
// See: CollideShapeCollector::AddHit
107
virtual void AddHit(const CollideShapeResult &inResult) override
108
{
109
// We only support welding when the shape is a triangle or has more vertices so that we can calculate a normal
110
if (inResult.mShape2Face.size() < 3)
111
return ChainAndVoid(inResult);
112
113
// Get the triangle normal of shape 2 face
114
Vec3 triangle_normal = (inResult.mShape2Face[1] - inResult.mShape2Face[0]).Cross(inResult.mShape2Face[2] - inResult.mShape2Face[0]);
115
float triangle_normal_len = triangle_normal.Length();
116
if (triangle_normal_len < 1e-6f)
117
return ChainAndVoid(inResult);
118
119
// If the triangle normal matches the contact normal within 1 degree, we can process the contact immediately
120
// We make the assumption here that if the contact normal and the triangle normal align that the we're dealing with a 'face contact'
121
Vec3 contact_normal = -inResult.mPenetrationAxis;
122
float contact_normal_len = inResult.mPenetrationAxis.Length();
123
if (triangle_normal.Dot(contact_normal) > 0.999848f * contact_normal_len * triangle_normal_len) // cos(1 degree)
124
return ChainAndVoid(inResult);
125
126
// Delayed processing
127
mDelayedResults.push_back(inResult);
128
}
129
130
/// After all hits have been added, call this function to process the delayed results
131
void Flush()
132
{
133
// Sort on biggest penetration depth first
134
Array<uint, STLLocalAllocator<uint, cMaxLocalDelayedResults>> sorted_indices;
135
sorted_indices.resize(mDelayedResults.size());
136
for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
137
sorted_indices[i] = i;
138
QuickSort(sorted_indices.begin(), sorted_indices.end(), [this](uint inLHS, uint inRHS) { return mDelayedResults[inLHS].mPenetrationDepth > mDelayedResults[inRHS].mPenetrationDepth; });
139
140
// Loop over all results
141
for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
142
{
143
const CollideShapeResult &r = mDelayedResults[sorted_indices[i]];
144
145
// Determine which vertex or which edge is the closest to the contact point
146
float best_dist_sq = FLT_MAX;
147
uint best_v1_idx = 0;
148
uint best_v2_idx = 0;
149
uint num_v = uint(r.mShape2Face.size());
150
uint v1_idx = num_v - 1;
151
Vec3 v1 = r.mShape2Face[v1_idx] - r.mContactPointOn2;
152
for (uint v2_idx = 0; v2_idx < num_v; ++v2_idx)
153
{
154
Vec3 v2 = r.mShape2Face[v2_idx] - r.mContactPointOn2;
155
Vec3 v1_v2 = v2 - v1;
156
float denominator = v1_v2.LengthSq();
157
if (denominator < Square(FLT_EPSILON))
158
{
159
// Degenerate, assume v1 is closest, v2 will be tested in a later iteration
160
float v1_len_sq = v1.LengthSq();
161
if (v1_len_sq < best_dist_sq)
162
{
163
best_dist_sq = v1_len_sq;
164
best_v1_idx = v1_idx;
165
best_v2_idx = v1_idx;
166
}
167
}
168
else
169
{
170
// Taken from ClosestPoint::GetBaryCentricCoordinates
171
float fraction = -v1.Dot(v1_v2) / denominator;
172
if (fraction < 1.0e-6f)
173
{
174
// Closest lies on v1
175
float v1_len_sq = v1.LengthSq();
176
if (v1_len_sq < best_dist_sq)
177
{
178
best_dist_sq = v1_len_sq;
179
best_v1_idx = v1_idx;
180
best_v2_idx = v1_idx;
181
}
182
}
183
else if (fraction < 1.0f - 1.0e-6f)
184
{
185
// Closest lies on the line segment v1, v2
186
Vec3 closest = v1 + fraction * v1_v2;
187
float closest_len_sq = closest.LengthSq();
188
if (closest_len_sq < best_dist_sq)
189
{
190
best_dist_sq = closest_len_sq;
191
best_v1_idx = v1_idx;
192
best_v2_idx = v2_idx;
193
}
194
}
195
// else closest is v2, but v2 will be tested in a later iteration
196
}
197
198
v1_idx = v2_idx;
199
v1 = v2;
200
}
201
202
// Check if this vertex/edge is voided
203
bool voided = IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])
204
&& (best_v1_idx == best_v2_idx || IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx]));
205
206
#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
207
Color color = voided? Color::sRed : Color::sYellow;
208
DebugRenderer::sInstance->DrawText3D(RVec3(r.mContactPointOn2), StringFormat("%d: %g", i, r.mPenetrationDepth), color, 0.1f);
209
DebugRenderer::sInstance->DrawWirePolygon(RMat44::sIdentity(), r.mShape2Face, color);
210
DebugRenderer::sInstance->DrawArrow(RVec3(r.mContactPointOn2), RVec3(r.mContactPointOn2) + r.mPenetrationAxis.NormalizedOr(Vec3::sZero()), color, 0.1f);
211
DebugRenderer::sInstance->DrawMarker(RVec3(r.mShape2Face[best_v1_idx]), IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])? Color::sRed : Color::sYellow, 0.1f);
212
DebugRenderer::sInstance->DrawMarker(RVec3(r.mShape2Face[best_v2_idx]), IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx])? Color::sRed : Color::sYellow, 0.1f);
213
#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
214
215
// No voided features, accept the contact
216
if (!voided)
217
Chain(r);
218
219
// Void the features of this face
220
VoidFeatures(r);
221
}
222
223
// All delayed results have been processed
224
mVoidedFeatures.clear();
225
mDelayedResults.clear();
226
}
227
228
// See: CollideShapeCollector::OnBodyEnd
229
virtual void OnBodyEnd() override
230
{
231
Flush();
232
mChainedCollector.OnBodyEnd();
233
}
234
235
/// Version of CollisionDispatch::sCollideShapeVsShape that removes internal edges
236
static void sCollideShapeVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { })
237
{
238
JPH_ASSERT(inCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideWithAll); // Won't work without colliding with all edges
239
JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces
240
241
InternalEdgeRemovingCollector wrapper(ioCollector);
242
CollisionDispatch::sCollideShapeVsShape(inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, wrapper, inShapeFilter);
243
wrapper.Flush();
244
}
245
246
private:
247
// This algorithm tests a convex shape (shape 1) against a set of polygons (shape 2).
248
// This assumption doesn't hold if the shape we're testing is a compound shape, so we must also
249
// store the sub shape ID and ignore voided features that belong to another sub shape ID.
250
struct Voided
251
{
252
Float3 mFeature; // Feature that is voided (of shape 2). Read with Vec3::sLoadFloat3Unsafe so must not be the last member.
253
SubShapeID mSubShapeID; // Sub shape ID of the shape that is colliding against the feature (of shape 1).
254
};
255
256
CollideShapeCollector & mChainedCollector;
257
Array<Voided, STLLocalAllocator<Voided, cMaxLocalVoidedFeatures>> mVoidedFeatures;
258
Array<CollideShapeResult, STLLocalAllocator<CollideShapeResult, cMaxLocalDelayedResults>> mDelayedResults;
259
};
260
261
JPH_NAMESPACE_END
262
263