Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Body/Body.cpp

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #include <Jolt/Jolt.h>
6
7 #include <Jolt/Physics/Body/Body.h>
8 #include <Jolt/Physics/Body/BodyCreationSettings.h>
9 #include <Jolt/Physics/SoftBody/SoftBodyCreationSettings.h>
10 #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>
11 #include <Jolt/Physics/PhysicsSettings.h>
12 #include <Jolt/Physics/StateRecorder.h>
13 #include <Jolt/Physics/Collision/Shape/EmptyShape.h>
14 #include <Jolt/Core/StringTools.h>
15 #include <Jolt/Core/Profiler.h>
16 #ifdef JPH_DEBUG_RENDERER
17 #include <Jolt/Renderer/DebugRenderer.h>
18 #endif // JPH_DEBUG_RENDERER
19
20 JPH_NAMESPACE_BEGIN
21
22 static const EmptyShape sFixedToWorldShape;
23 Body Body::sFixedToWorld(false);
24
25 Body::Body(bool) :
26 mPosition(Vec3::sZero()),
27 mRotation(Quat::sIdentity()),
28 mShape(&sFixedToWorldShape), // Dummy shape
29 mFriction(0.0f),
30 mRestitution(0.0f),
31 mObjectLayer(cObjectLayerInvalid),
32 mMotionType(EMotionType::Static)
33 {
34 sFixedToWorldShape.SetEmbedded();
35 }
36
37 void Body::SetMotionType(EMotionType inMotionType)
38 {
39 if (mMotionType == inMotionType)
40 return;
41
42 JPH_ASSERT(inMotionType == EMotionType::Static || mMotionProperties != nullptr, "Body needs to be created with mAllowDynamicOrKinematic set to true");
43 JPH_ASSERT(inMotionType != EMotionType::Static || !IsActive(), "Deactivate body first");
44 JPH_ASSERT(inMotionType == EMotionType::Dynamic || !IsSoftBody(), "Soft bodies can only be dynamic, you can make individual vertices kinematic by setting their inverse mass to 0");
45
46 // Store new motion type
47 mMotionType = inMotionType;
48
49 if (mMotionProperties != nullptr)
50 {
51 // Update cache
52 JPH_IF_ENABLE_ASSERTS(mMotionProperties->mCachedMotionType = inMotionType;)
53
54 switch (inMotionType)
55 {
56 case EMotionType::Static:
57 // Stop the object
58 mMotionProperties->mLinearVelocity = Vec3::sZero();
59 mMotionProperties->mAngularVelocity = Vec3::sZero();
60 [[fallthrough]];
61
62 case EMotionType::Kinematic:
63 // Cancel forces
64 mMotionProperties->ResetForce();
65 mMotionProperties->ResetTorque();
66 break;
67
68 case EMotionType::Dynamic:
69 break;
70 }
71 }
72 }
73
74 void Body::SetAllowSleeping(bool inAllow)
75 {
76 mMotionProperties->mAllowSleeping = inAllow;
77 if (inAllow)
78 ResetSleepTimer();
79 }
80
81 void Body::MoveKinematic(RVec3Arg inTargetPosition, QuatArg inTargetRotation, float inDeltaTime)
82 {
83 JPH_ASSERT(IsRigidBody()); // Only valid for rigid bodies
84 JPH_ASSERT(!IsStatic());
85 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess(), BodyAccess::EAccess::Read));
86
87 // Calculate center of mass at end situation
88 RVec3 new_com = inTargetPosition + inTargetRotation * mShape->GetCenterOfMass();
89
90 // Calculate delta position and rotation
91 Vec3 delta_pos = Vec3(new_com - mPosition);
92 Quat delta_rotation = inTargetRotation * mRotation.Conjugated();
93
94 mMotionProperties->MoveKinematic(delta_pos, delta_rotation, inDeltaTime);
95 }
96
97 void Body::CalculateWorldSpaceBoundsInternal()
98 {
99 mBounds = mShape->GetWorldSpaceBounds(GetCenterOfMassTransform(), Vec3::sOne());
100 }
101
102 void Body::SetPositionAndRotationInternal(RVec3Arg inPosition, QuatArg inRotation, bool inResetSleepTimer)
103 {
104 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess(), BodyAccess::EAccess::ReadWrite));
105
106 mPosition = inPosition + inRotation * mShape->GetCenterOfMass();
107 mRotation = inRotation;
108
109 // Initialize bounding box
110 CalculateWorldSpaceBoundsInternal();
111
112 // Reset sleeping test
113 if (inResetSleepTimer && mMotionProperties != nullptr)
114 ResetSleepTimer();
115 }
116
117 void Body::UpdateCenterOfMassInternal(Vec3Arg inPreviousCenterOfMass, bool inUpdateMassProperties)
118 {
119 // Update center of mass position so the world position for this body stays the same
120 mPosition += mRotation * (mShape->GetCenterOfMass() - inPreviousCenterOfMass);
121
122 // Recalculate mass and inertia if requested
123 if (inUpdateMassProperties && mMotionProperties != nullptr)
124 mMotionProperties->SetMassProperties(mMotionProperties->GetAllowedDOFs(), mShape->GetMassProperties());
125 }
126
127 void Body::SetShapeInternal(const Shape *inShape, bool inUpdateMassProperties)
128 {
129 JPH_ASSERT(IsRigidBody()); // Only valid for rigid bodies
130 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess(), BodyAccess::EAccess::ReadWrite));
131
132 // Get the old center of mass
133 Vec3 old_com = mShape->GetCenterOfMass();
134
135 // Update the shape
136 mShape = inShape;
137
138 // Update center of mass
139 UpdateCenterOfMassInternal(old_com, inUpdateMassProperties);
140
141 // Recalculate bounding box
142 CalculateWorldSpaceBoundsInternal();
143 }
144
145 ECanSleep Body::UpdateSleepStateInternal(float inDeltaTime, float inMaxMovement, float inTimeBeforeSleep)
146 {
147 // Check override & sensors will never go to sleep (they would stop detecting collisions with sleeping bodies)
148 if (!mMotionProperties->mAllowSleeping || IsSensor())
149 return ECanSleep::CannotSleep;
150
151 // Get the points to test
152 RVec3 points[3];
153 GetSleepTestPoints(points);
154
155 #ifdef JPH_DOUBLE_PRECISION
156 // Get base offset for spheres
157 DVec3 offset = mMotionProperties->GetSleepTestOffset();
158 #endif // JPH_DOUBLE_PRECISION
159
160 for (int i = 0; i < 3; ++i)
161 {
162 Sphere &sphere = mMotionProperties->mSleepTestSpheres[i];
163
164 // Make point relative to base offset
165 #ifdef JPH_DOUBLE_PRECISION
166 Vec3 p = Vec3(points[i] - offset);
167 #else
168 Vec3 p = points[i];
169 #endif // JPH_DOUBLE_PRECISION
170
171 // Encapsulate the point in a sphere
172 sphere.EncapsulatePoint(p);
173
174 // Test if it exceeded the max movement
175 if (sphere.GetRadius() > inMaxMovement)
176 {
177 // Body is not sleeping, reset test
178 mMotionProperties->ResetSleepTestSpheres(points);
179 return ECanSleep::CannotSleep;
180 }
181 }
182
183 return mMotionProperties->AccumulateSleepTime(inDeltaTime, inTimeBeforeSleep);
184 }
185
186 void Body::GetSubmergedVolume(RVec3Arg inSurfacePosition, Vec3Arg inSurfaceNormal, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outRelativeCenterOfBuoyancy) const
187 {
188 // For GetSubmergedVolume we transform the surface relative to the body position for increased precision
189 Mat44 rotation = Mat44::sRotation(mRotation);
190 Plane surface_relative_to_body = Plane::sFromPointAndNormal(inSurfacePosition - mPosition, inSurfaceNormal);
191
192 // Calculate amount of volume that is submerged and what the center of buoyancy is
193 mShape->GetSubmergedVolume(rotation, Vec3::sOne(), surface_relative_to_body, outTotalVolume, outSubmergedVolume, outRelativeCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, mPosition));
194 }
195
196 bool Body::ApplyBuoyancyImpulse(float inTotalVolume, float inSubmergedVolume, Vec3Arg inRelativeCenterOfBuoyancy, float inBuoyancy, float inLinearDrag, float inAngularDrag, Vec3Arg inFluidVelocity, Vec3Arg inGravity, float inDeltaTime)
197 {
198 JPH_ASSERT(IsRigidBody()); // Only implemented for rigid bodies currently
199
200 // We follow the approach from 'Game Programming Gems 6' 2.5 Exact Buoyancy for Polyhedra
201 // All quantities below are in world space
202
203 // If we're not submerged, there's no point in doing the rest of the calculations
204 if (inSubmergedVolume > 0.0f)
205 {
206 #ifdef JPH_DEBUG_RENDERER
207 // Draw submerged volume properties
208 if (Shape::sDrawSubmergedVolumes)
209 {
210 RVec3 center_of_buoyancy = mPosition + inRelativeCenterOfBuoyancy;
211 DebugRenderer::sInstance->DrawMarker(center_of_buoyancy, Color::sWhite, 2.0f);
212 DebugRenderer::sInstance->DrawText3D(center_of_buoyancy, StringFormat("%.3f / %.3f", (double)inSubmergedVolume, (double)inTotalVolume));
213 }
214 #endif // JPH_DEBUG_RENDERER
215
216 // When buoyancy is 1 we want neutral buoyancy, this means that the density of the liquid is the same as the density of the body at that point.
217 // Buoyancy > 1 should make the object float, < 1 should make it sink.
218 float inverse_mass = mMotionProperties->GetInverseMass();
219 float fluid_density = inBuoyancy / (inTotalVolume * inverse_mass);
220
221 // Buoyancy force = Density of Fluid * Submerged volume * Magnitude of gravity * Up direction (eq 2.5.1)
222 // Impulse = Force * Delta time
223 // We should apply this at the center of buoyancy (= center of mass of submerged volume)
224 Vec3 buoyancy_impulse = -fluid_density * inSubmergedVolume * mMotionProperties->GetGravityFactor() * inGravity * inDeltaTime;
225
226 // Calculate the velocity of the center of buoyancy relative to the fluid
227 Vec3 linear_velocity = mMotionProperties->GetLinearVelocity();
228 Vec3 angular_velocity = mMotionProperties->GetAngularVelocity();
229 Vec3 center_of_buoyancy_velocity = linear_velocity + angular_velocity.Cross(inRelativeCenterOfBuoyancy);
230 Vec3 relative_center_of_buoyancy_velocity = inFluidVelocity - center_of_buoyancy_velocity;
231
232 // Here we deviate from the article, instead of eq 2.5.14 we use a quadratic drag formula: https://en.wikipedia.org/wiki/Drag_%28physics%29
233 // Drag force = 0.5 * Fluid Density * (Velocity of fluid - Velocity of center of buoyancy)^2 * Linear Drag * Area Facing the Relative Fluid Velocity
234 // Again Impulse = Force * Delta Time
235 // We should apply this at the center of buoyancy (= center of mass for submerged volume with no center of mass offset)
236
237 // Get size of local bounding box
238 Vec3 size = mShape->GetLocalBounds().GetSize();
239
240 // Determine area of the local space bounding box in the direction of the relative velocity between the fluid and the center of buoyancy
241 float area = 0.0f;
242 float relative_center_of_buoyancy_velocity_len_sq = relative_center_of_buoyancy_velocity.LengthSq();
243 if (relative_center_of_buoyancy_velocity_len_sq > 1.0e-12f)
244 {
245 Vec3 local_relative_center_of_buoyancy_velocity = GetRotation().InverseRotate(relative_center_of_buoyancy_velocity);
246 area = local_relative_center_of_buoyancy_velocity.Abs().Dot(size.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * size.Swizzle<SWIZZLE_Z, SWIZZLE_X, SWIZZLE_Y>()) / sqrt(relative_center_of_buoyancy_velocity_len_sq);
247 }
248
249 // Calculate the impulse
250 Vec3 drag_impulse = (0.5f * fluid_density * inLinearDrag * area * inDeltaTime) * relative_center_of_buoyancy_velocity * relative_center_of_buoyancy_velocity.Length();
251
252 // Clamp magnitude against current linear velocity to prevent overshoot
253 float linear_velocity_len_sq = linear_velocity.LengthSq();
254 float drag_delta_linear_velocity_len_sq = (drag_impulse * inverse_mass).LengthSq();
255 if (drag_delta_linear_velocity_len_sq > linear_velocity_len_sq)
256 drag_impulse *= sqrt(linear_velocity_len_sq / drag_delta_linear_velocity_len_sq);
257
258 // Calculate the resulting delta linear velocity due to buoyancy and drag
259 Vec3 delta_linear_velocity = (drag_impulse + buoyancy_impulse) * inverse_mass;
260 mMotionProperties->AddLinearVelocityStep(delta_linear_velocity);
261
262 // Determine average width of the body (across the three axis)
263 float l = (size.GetX() + size.GetY() + size.GetZ()) / 3.0f;
264
265 // Drag torque = -Angular Drag * Mass * Submerged volume / Total volume * (Average width of body)^2 * Angular velocity (eq 2.5.15)
266 Vec3 drag_angular_impulse = (-inAngularDrag * inSubmergedVolume / inTotalVolume * inDeltaTime * Square(l) / inverse_mass) * angular_velocity;
267 Mat44 inv_inertia = GetInverseInertia();
268 Vec3 drag_delta_angular_velocity = inv_inertia * drag_angular_impulse;
269
270 // Clamp magnitude against the current angular velocity to prevent overshoot
271 float angular_velocity_len_sq = angular_velocity.LengthSq();
272 float drag_delta_angular_velocity_len_sq = drag_delta_angular_velocity.LengthSq();
273 if (drag_delta_angular_velocity_len_sq > angular_velocity_len_sq)
274 drag_delta_angular_velocity *= sqrt(angular_velocity_len_sq / drag_delta_angular_velocity_len_sq);
275
276 // Calculate total delta angular velocity due to drag and buoyancy
277 Vec3 delta_angular_velocity = drag_delta_angular_velocity + inv_inertia * inRelativeCenterOfBuoyancy.Cross(buoyancy_impulse + drag_impulse);
278 mMotionProperties->AddAngularVelocityStep(delta_angular_velocity);
279 return true;
280 }
281
282 return false;
283 }
284
285 bool Body::ApplyBuoyancyImpulse(RVec3Arg inSurfacePosition, Vec3Arg inSurfaceNormal, float inBuoyancy, float inLinearDrag, float inAngularDrag, Vec3Arg inFluidVelocity, Vec3Arg inGravity, float inDeltaTime)
286 {
287 JPH_PROFILE_FUNCTION();
288
289 float total_volume, submerged_volume;
290 Vec3 relative_center_of_buoyancy;
291 GetSubmergedVolume(inSurfacePosition, inSurfaceNormal, total_volume, submerged_volume, relative_center_of_buoyancy);
292
293 return ApplyBuoyancyImpulse(total_volume, submerged_volume, relative_center_of_buoyancy, inBuoyancy, inLinearDrag, inAngularDrag, inFluidVelocity, inGravity, inDeltaTime);
294 }
295
296 void Body::SaveState(StateRecorder &inStream) const
297 {
298 // Only write properties that can change at runtime
299 inStream.Write(mPosition);
300 inStream.Write(mRotation);
301
302 if (mMotionProperties != nullptr)
303 {
304 if (IsSoftBody())
305 static_cast<const SoftBodyMotionProperties *>(mMotionProperties)->SaveState(inStream);
306 else
307 mMotionProperties->SaveState(inStream);
308 }
309 }
310
311 void Body::RestoreState(StateRecorder &inStream)
312 {
313 inStream.Read(mPosition);
314 inStream.Read(mRotation);
315
316 if (mMotionProperties != nullptr)
317 {
318 if (IsSoftBody())
319 static_cast<SoftBodyMotionProperties *>(mMotionProperties)->RestoreState(inStream);
320 else
321 mMotionProperties->RestoreState(inStream);
322
323 JPH_IF_ENABLE_ASSERTS(mMotionProperties->mCachedMotionType = mMotionType);
324 }
325
326 // Initialize bounding box
327 CalculateWorldSpaceBoundsInternal();
328 }
329
330 BodyCreationSettings Body::GetBodyCreationSettings() const
331 {
332 JPH_ASSERT(IsRigidBody());
333
334 BodyCreationSettings result;
335
336 result.mPosition = GetPosition();
337 result.mRotation = GetRotation();
338 result.mLinearVelocity = mMotionProperties != nullptr? mMotionProperties->GetLinearVelocity() : Vec3::sZero();
339 result.mAngularVelocity = mMotionProperties != nullptr? mMotionProperties->GetAngularVelocity() : Vec3::sZero();
340 result.mObjectLayer = GetObjectLayer();
341 result.mUserData = mUserData;
342 result.mCollisionGroup = GetCollisionGroup();
343 result.mMotionType = GetMotionType();
344 result.mAllowedDOFs = mMotionProperties != nullptr? mMotionProperties->GetAllowedDOFs() : EAllowedDOFs::All;
345 result.mAllowDynamicOrKinematic = mMotionProperties != nullptr;
346 result.mIsSensor = IsSensor();
347 result.mCollideKinematicVsNonDynamic = GetCollideKinematicVsNonDynamic();
348 result.mUseManifoldReduction = GetUseManifoldReduction();
349 result.mApplyGyroscopicForce = GetApplyGyroscopicForce();
350 result.mMotionQuality = mMotionProperties != nullptr? mMotionProperties->GetMotionQuality() : EMotionQuality::Discrete;
351 result.mEnhancedInternalEdgeRemoval = GetEnhancedInternalEdgeRemoval();
352 result.mAllowSleeping = mMotionProperties != nullptr? GetAllowSleeping() : true;
353 result.mFriction = GetFriction();
354 result.mRestitution = GetRestitution();
355 result.mLinearDamping = mMotionProperties != nullptr? mMotionProperties->GetLinearDamping() : 0.0f;
356 result.mAngularDamping = mMotionProperties != nullptr? mMotionProperties->GetAngularDamping() : 0.0f;
357 result.mMaxLinearVelocity = mMotionProperties != nullptr? mMotionProperties->GetMaxLinearVelocity() : 0.0f;
358 result.mMaxAngularVelocity = mMotionProperties != nullptr? mMotionProperties->GetMaxAngularVelocity() : 0.0f;
359 result.mGravityFactor = mMotionProperties != nullptr? mMotionProperties->GetGravityFactor() : 1.0f;
360 result.mNumVelocityStepsOverride = mMotionProperties != nullptr? mMotionProperties->GetNumVelocityStepsOverride() : 0;
361 result.mNumPositionStepsOverride = mMotionProperties != nullptr? mMotionProperties->GetNumPositionStepsOverride() : 0;
362 result.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
363
364 // Invert inertia and mass
365 if (mMotionProperties != nullptr)
366 {
367 float inv_mass = mMotionProperties->GetInverseMassUnchecked();
368 Mat44 inv_inertia = mMotionProperties->GetLocalSpaceInverseInertiaUnchecked();
369
370 // Get mass
371 result.mMassPropertiesOverride.mMass = inv_mass != 0.0f? 1.0f / inv_mass : FLT_MAX;
372
373 // Get inertia
374 Mat44 inertia;
375 if (inertia.SetInversed3x3(inv_inertia))
376 {
377 // Inertia was invertible, we can use it
378 result.mMassPropertiesOverride.mInertia = inertia;
379 }
380 else
381 {
382 // Prevent division by zero
383 Vec3 diagonal = Vec3::sMax(inv_inertia.GetDiagonal3(), Vec3::sReplicate(FLT_MIN));
384 result.mMassPropertiesOverride.mInertia = Mat44::sScale(diagonal.Reciprocal());
385 }
386 }
387 else
388 {
389 result.mMassPropertiesOverride.mMass = FLT_MAX;
390 result.mMassPropertiesOverride.mInertia = Mat44::sScale(Vec3::sReplicate(FLT_MAX));
391 }
392
393 result.SetShape(GetShape());
394
395 return result;
396 }
397
398 SoftBodyCreationSettings Body::GetSoftBodyCreationSettings() const
399 {
400 JPH_ASSERT(IsSoftBody());
401
402 SoftBodyCreationSettings result;
403
404 result.mPosition = GetPosition();
405 result.mRotation = GetRotation();
406 result.mUserData = mUserData;
407 result.mObjectLayer = GetObjectLayer();
408 result.mCollisionGroup = GetCollisionGroup();
409 result.mFriction = GetFriction();
410 result.mRestitution = GetRestitution();
411 const SoftBodyMotionProperties *mp = static_cast<const SoftBodyMotionProperties *>(mMotionProperties);
412 result.mNumIterations = mp->GetNumIterations();
413 result.mLinearDamping = mp->GetLinearDamping();
414 result.mMaxLinearVelocity = mp->GetMaxLinearVelocity();
415 result.mGravityFactor = mp->GetGravityFactor();
416 result.mPressure = mp->GetPressure();
417 result.mUpdatePosition = mp->GetUpdatePosition();
418 result.mVertexRadius = mp->GetVertexRadius();
419 result.mAllowSleeping = mp->GetAllowSleeping();
420 result.mFacesDoubleSided = mp->GetFacesDoubleSided();
421 result.mSettings = mp->GetSettings();
422
423 return result;
424 }
425
426 JPH_NAMESPACE_END