BoxShape.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  8. #include <Jolt/Physics/Collision/RayCast.h>
  9. #include <Jolt/Physics/Collision/CastResult.h>
  10. #include <Jolt/Physics/Collision/CollidePointResult.h>
  11. #include <Jolt/Physics/Collision/TransformedShape.h>
  12. #include <Jolt/Physics/SoftBody/SoftBodyVertex.h>
  13. #include <Jolt/Geometry/RayAABox.h>
  14. #include <Jolt/ObjectStream/TypeDeclarations.h>
  15. #include <Jolt/Core/StreamIn.h>
  16. #include <Jolt/Core/StreamOut.h>
  17. #ifdef JPH_DEBUG_RENDERER
  18. #include <Jolt/Renderer/DebugRenderer.h>
  19. #endif // JPH_DEBUG_RENDERER
  20. JPH_NAMESPACE_BEGIN
  21. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(BoxShapeSettings)
  22. {
  23. JPH_ADD_BASE_CLASS(BoxShapeSettings, ConvexShapeSettings)
  24. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mHalfExtent)
  25. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mConvexRadius)
  26. }
  27. static const Vec3 sUnitBoxTriangles[] = {
  28. Vec3(-1, 1, -1), Vec3(-1, 1, 1), Vec3(1, 1, 1),
  29. Vec3(-1, 1, -1), Vec3(1, 1, 1), Vec3(1, 1, -1),
  30. Vec3(-1, -1, -1), Vec3(1, -1, -1), Vec3(1, -1, 1),
  31. Vec3(-1, -1, -1), Vec3(1, -1, 1), Vec3(-1, -1, 1),
  32. Vec3(-1, 1, -1), Vec3(-1, -1, -1), Vec3(-1, -1, 1),
  33. Vec3(-1, 1, -1), Vec3(-1, -1, 1), Vec3(-1, 1, 1),
  34. Vec3(1, 1, 1), Vec3(1, -1, 1), Vec3(1, -1, -1),
  35. Vec3(1, 1, 1), Vec3(1, -1, -1), Vec3(1, 1, -1),
  36. Vec3(-1, 1, 1), Vec3(-1, -1, 1), Vec3(1, -1, 1),
  37. Vec3(-1, 1, 1), Vec3(1, -1, 1), Vec3(1, 1, 1),
  38. Vec3(-1, 1, -1), Vec3(1, 1, -1), Vec3(1, -1, -1),
  39. Vec3(-1, 1, -1), Vec3(1, -1, -1), Vec3(-1, -1, -1)
  40. };
  41. ShapeSettings::ShapeResult BoxShapeSettings::Create() const
  42. {
  43. if (mCachedResult.IsEmpty())
  44. Ref<Shape> shape = new BoxShape(*this, mCachedResult);
  45. return mCachedResult;
  46. }
  47. BoxShape::BoxShape(const BoxShapeSettings &inSettings, ShapeResult &outResult) :
  48. ConvexShape(EShapeSubType::Box, inSettings, outResult),
  49. mHalfExtent(inSettings.mHalfExtent),
  50. mConvexRadius(inSettings.mConvexRadius)
  51. {
  52. // Check convex radius
  53. if (inSettings.mConvexRadius < 0.0f
  54. || inSettings.mHalfExtent.ReduceMin() <= inSettings.mConvexRadius)
  55. {
  56. outResult.SetError("Invalid convex radius");
  57. return;
  58. }
  59. // Result is valid
  60. outResult.Set(this);
  61. }
  62. class BoxShape::Box final : public Support
  63. {
  64. public:
  65. Box(const AABox &inBox, float inConvexRadius) :
  66. mBox(inBox),
  67. mConvexRadius(inConvexRadius)
  68. {
  69. static_assert(sizeof(Box) <= sizeof(SupportBuffer), "Buffer size too small");
  70. JPH_ASSERT(IsAligned(this, alignof(Box)));
  71. }
  72. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  73. {
  74. return mBox.GetSupport(inDirection);
  75. }
  76. virtual float GetConvexRadius() const override
  77. {
  78. return mConvexRadius;
  79. }
  80. private:
  81. AABox mBox;
  82. float mConvexRadius;
  83. };
  84. const ConvexShape::Support *BoxShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  85. {
  86. // Scale our half extents
  87. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  88. switch (inMode)
  89. {
  90. case ESupportMode::IncludeConvexRadius:
  91. case ESupportMode::Default:
  92. {
  93. // Make box out of our half extents
  94. AABox box = AABox(-scaled_half_extent, scaled_half_extent);
  95. JPH_ASSERT(box.IsValid());
  96. return new (&inBuffer) Box(box, 0.0f);
  97. }
  98. case ESupportMode::ExcludeConvexRadius:
  99. {
  100. // Reduce the box by our convex radius
  101. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  102. Vec3 convex_radius3 = Vec3::sReplicate(convex_radius);
  103. Vec3 reduced_half_extent = scaled_half_extent - convex_radius3;
  104. AABox box = AABox(-reduced_half_extent, reduced_half_extent);
  105. JPH_ASSERT(box.IsValid());
  106. return new (&inBuffer) Box(box, convex_radius);
  107. }
  108. }
  109. JPH_ASSERT(false);
  110. return nullptr;
  111. }
  112. void BoxShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  113. {
  114. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  115. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  116. AABox box(-scaled_half_extent, scaled_half_extent);
  117. box.GetSupportingFace(inDirection, outVertices);
  118. // Transform to world space
  119. for (Vec3 &v : outVertices)
  120. v = inCenterOfMassTransform * v;
  121. }
  122. MassProperties BoxShape::GetMassProperties() const
  123. {
  124. MassProperties p;
  125. p.SetMassAndInertiaOfSolidBox(2.0f * mHalfExtent, GetDensity());
  126. return p;
  127. }
  128. Vec3 BoxShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  129. {
  130. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  131. // Get component that is closest to the surface of the box
  132. int index = (inLocalSurfacePosition.Abs() - mHalfExtent).Abs().GetLowestComponentIndex();
  133. // Calculate normal
  134. Vec3 normal = Vec3::sZero();
  135. normal.SetComponent(index, inLocalSurfacePosition[index] > 0.0f? 1.0f : -1.0f);
  136. return normal;
  137. }
  138. #ifdef JPH_DEBUG_RENDERER
  139. void BoxShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  140. {
  141. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  142. inRenderer->DrawBox(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), GetLocalBounds(), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  143. }
  144. #endif // JPH_DEBUG_RENDERER
  145. bool BoxShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  146. {
  147. // Test hit against box
  148. float fraction = max(RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent), 0.0f);
  149. if (fraction < ioHit.mFraction)
  150. {
  151. ioHit.mFraction = fraction;
  152. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  153. return true;
  154. }
  155. return false;
  156. }
  157. void BoxShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  158. {
  159. // Test shape filter
  160. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  161. return;
  162. float min_fraction, max_fraction;
  163. RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent, min_fraction, max_fraction);
  164. if (min_fraction <= max_fraction // Ray should intersect
  165. && max_fraction >= 0.0f // End of ray should be inside box
  166. && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction
  167. {
  168. // Better hit than the current hit
  169. RayCastResult hit;
  170. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  171. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  172. // Check front side
  173. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  174. {
  175. hit.mFraction = max(0.0f, min_fraction);
  176. ioCollector.AddHit(hit);
  177. }
  178. // Check back side hit
  179. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  180. && max_fraction < ioCollector.GetEarlyOutFraction())
  181. {
  182. hit.mFraction = max_fraction;
  183. ioCollector.AddHit(hit);
  184. }
  185. }
  186. }
  187. void BoxShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  188. {
  189. // Test shape filter
  190. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  191. return;
  192. if (Vec3::sLessOrEqual(inPoint.Abs(), mHalfExtent).TestAllXYZTrue())
  193. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  194. }
  195. void BoxShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  196. {
  197. Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
  198. Vec3 half_extent = inScale.Abs() * mHalfExtent;
  199. for (SoftBodyVertex *v = ioVertices, *sbv_end = ioVertices + inNumVertices; v < sbv_end; ++v)
  200. if (v->mInvMass > 0.0f)
  201. {
  202. // Convert to local space
  203. Vec3 local_pos = inverse_transform * v->mPosition;
  204. // Clamp point to inside box
  205. Vec3 clamped_point = Vec3::sMax(Vec3::sMin(local_pos, half_extent), -half_extent);
  206. // Test if point was inside
  207. if (clamped_point == local_pos)
  208. {
  209. // Calculate closest distance to surface
  210. Vec3 delta = half_extent - local_pos.Abs();
  211. int index = delta.GetLowestComponentIndex();
  212. float penetration = delta[index];
  213. if (penetration > v->mLargestPenetration)
  214. {
  215. v->mLargestPenetration = penetration;
  216. // Calculate contact point and normal
  217. Vec3 possible_normals[] = { Vec3::sAxisX(), Vec3::sAxisY(), Vec3::sAxisZ() };
  218. Vec3 normal = local_pos.GetSign() * possible_normals[index];
  219. Vec3 point = normal * half_extent;
  220. // Store collision
  221. v->mCollisionPlane = Plane::sFromPointAndNormal(point, normal).GetTransformed(inCenterOfMassTransform);
  222. v->mCollidingShapeIndex = inCollidingShapeIndex;
  223. }
  224. }
  225. else
  226. {
  227. // Calculate normal
  228. Vec3 normal = local_pos - clamped_point;
  229. float normal_length = normal.Length();
  230. // Penetration will be negative since we're not penetrating
  231. float penetration = -normal_length;
  232. if (penetration > v->mLargestPenetration)
  233. {
  234. normal /= normal_length;
  235. v->mLargestPenetration = penetration;
  236. // Store collision
  237. v->mCollisionPlane = Plane::sFromPointAndNormal(clamped_point, normal).GetTransformed(inCenterOfMassTransform);
  238. v->mCollidingShapeIndex = inCollidingShapeIndex;
  239. }
  240. }
  241. }
  242. }
  243. void BoxShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  244. {
  245. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, Mat44::sScale(mHalfExtent), sUnitBoxTriangles, sizeof(sUnitBoxTriangles) / sizeof(Vec3), GetMaterial());
  246. }
  247. int BoxShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  248. {
  249. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  250. }
  251. void BoxShape::SaveBinaryState(StreamOut &inStream) const
  252. {
  253. ConvexShape::SaveBinaryState(inStream);
  254. inStream.Write(mHalfExtent);
  255. inStream.Write(mConvexRadius);
  256. }
  257. void BoxShape::RestoreBinaryState(StreamIn &inStream)
  258. {
  259. ConvexShape::RestoreBinaryState(inStream);
  260. inStream.Read(mHalfExtent);
  261. inStream.Read(mConvexRadius);
  262. }
  263. void BoxShape::sRegister()
  264. {
  265. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Box);
  266. f.mConstruct = []() -> Shape * { return new BoxShape; };
  267. f.mColor = Color::sGreen;
  268. }
  269. JPH_NAMESPACE_END