BoxShape.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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/Geometry/RayAABox.h>
  13. #include <Jolt/ObjectStream/TypeDeclarations.h>
  14. #include <Jolt/Core/StreamIn.h>
  15. #include <Jolt/Core/StreamOut.h>
  16. #ifdef JPH_DEBUG_RENDERER
  17. #include <Jolt/Renderer/DebugRenderer.h>
  18. #endif // JPH_DEBUG_RENDERER
  19. JPH_NAMESPACE_BEGIN
  20. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(BoxShapeSettings)
  21. {
  22. JPH_ADD_BASE_CLASS(BoxShapeSettings, ConvexShapeSettings)
  23. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mHalfExtent)
  24. JPH_ADD_ATTRIBUTE(BoxShapeSettings, mConvexRadius)
  25. }
  26. static const Vec3 sUnitBoxTriangles[] = {
  27. Vec3(-1, 1, -1), Vec3(-1, 1, 1), Vec3(1, 1, 1),
  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. };
  40. ShapeSettings::ShapeResult BoxShapeSettings::Create() const
  41. {
  42. if (mCachedResult.IsEmpty())
  43. Ref<Shape> shape = new BoxShape(*this, mCachedResult);
  44. return mCachedResult;
  45. }
  46. BoxShape::BoxShape(const BoxShapeSettings &inSettings, ShapeResult &outResult) :
  47. ConvexShape(EShapeSubType::Box, inSettings, outResult),
  48. mHalfExtent(inSettings.mHalfExtent),
  49. mConvexRadius(inSettings.mConvexRadius)
  50. {
  51. // Check convex radius
  52. if (inSettings.mConvexRadius < 0.0f
  53. || inSettings.mHalfExtent.ReduceMin() <= inSettings.mConvexRadius)
  54. {
  55. outResult.SetError("Invalid convex radius");
  56. return;
  57. }
  58. // Result is valid
  59. outResult.Set(this);
  60. }
  61. class BoxShape::Box final : public Support
  62. {
  63. public:
  64. Box(const AABox &inBox, float inConvexRadius) :
  65. mBox(inBox),
  66. mConvexRadius(inConvexRadius)
  67. {
  68. static_assert(sizeof(Box) <= sizeof(SupportBuffer), "Buffer size too small");
  69. JPH_ASSERT(IsAligned(this, alignof(Box)));
  70. }
  71. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  72. {
  73. return mBox.GetSupport(inDirection);
  74. }
  75. virtual float GetConvexRadius() const override
  76. {
  77. return mConvexRadius;
  78. }
  79. private:
  80. AABox mBox;
  81. float mConvexRadius;
  82. };
  83. const ConvexShape::Support *BoxShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  84. {
  85. // Scale our half extents
  86. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  87. switch (inMode)
  88. {
  89. case ESupportMode::IncludeConvexRadius:
  90. {
  91. // Make box out of our half extents
  92. AABox box = AABox(-scaled_half_extent, scaled_half_extent);
  93. JPH_ASSERT(box.IsValid());
  94. return new (&inBuffer) Box(box, 0.0f);
  95. }
  96. case ESupportMode::ExcludeConvexRadius:
  97. {
  98. // Reduce the box by our convex radius
  99. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  100. Vec3 convex_radius3 = Vec3::sReplicate(convex_radius);
  101. Vec3 reduced_half_extent = scaled_half_extent - convex_radius3;
  102. AABox box = AABox(-reduced_half_extent, reduced_half_extent);
  103. JPH_ASSERT(box.IsValid());
  104. return new (&inBuffer) Box(box, convex_radius);
  105. }
  106. }
  107. JPH_ASSERT(false);
  108. return nullptr;
  109. }
  110. void BoxShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  111. {
  112. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  113. Vec3 scaled_half_extent = inScale.Abs() * mHalfExtent;
  114. AABox box(-scaled_half_extent, scaled_half_extent);
  115. box.GetSupportingFace(inDirection, outVertices);
  116. // Transform to world space
  117. for (Vec3 &v : outVertices)
  118. v = inCenterOfMassTransform * v;
  119. }
  120. MassProperties BoxShape::GetMassProperties() const
  121. {
  122. MassProperties p;
  123. p.SetMassAndInertiaOfSolidBox(2.0f * mHalfExtent, GetDensity());
  124. return p;
  125. }
  126. Vec3 BoxShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  127. {
  128. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  129. // Get component that is closest to the surface of the box
  130. int index = (inLocalSurfacePosition.Abs() - mHalfExtent).Abs().GetLowestComponentIndex();
  131. // Calculate normal
  132. Vec3 normal = Vec3::sZero();
  133. normal.SetComponent(index, inLocalSurfacePosition[index] > 0.0f? 1.0f : -1.0f);
  134. return normal;
  135. }
  136. #ifdef JPH_DEBUG_RENDERER
  137. void BoxShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  138. {
  139. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  140. inRenderer->DrawBox(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), GetLocalBounds(), inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  141. }
  142. #endif // JPH_DEBUG_RENDERER
  143. bool BoxShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  144. {
  145. // Test hit against box
  146. float fraction = max(RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent), 0.0f);
  147. if (fraction < ioHit.mFraction)
  148. {
  149. ioHit.mFraction = fraction;
  150. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  151. return true;
  152. }
  153. return false;
  154. }
  155. void BoxShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  156. {
  157. // Test shape filter
  158. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  159. return;
  160. float min_fraction, max_fraction;
  161. RayAABox(inRay.mOrigin, RayInvDirection(inRay.mDirection), -mHalfExtent, mHalfExtent, min_fraction, max_fraction);
  162. if (min_fraction <= max_fraction // Ray should intersect
  163. && max_fraction >= 0.0f // End of ray should be inside box
  164. && min_fraction < ioCollector.GetEarlyOutFraction()) // Start of ray should be before early out fraction
  165. {
  166. // Better hit than the current hit
  167. RayCastResult hit;
  168. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  169. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  170. // Check front side
  171. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  172. {
  173. hit.mFraction = max(0.0f, min_fraction);
  174. ioCollector.AddHit(hit);
  175. }
  176. // Check back side hit
  177. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  178. && max_fraction < ioCollector.GetEarlyOutFraction())
  179. {
  180. hit.mFraction = max_fraction;
  181. ioCollector.AddHit(hit);
  182. }
  183. }
  184. }
  185. void BoxShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  186. {
  187. // Test shape filter
  188. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  189. return;
  190. if (Vec3::sLessOrEqual(inPoint.Abs(), mHalfExtent).TestAllXYZTrue())
  191. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  192. }
  193. void BoxShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  194. {
  195. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, Mat44::sScale(mHalfExtent), sUnitBoxTriangles, sizeof(sUnitBoxTriangles) / sizeof(Vec3), GetMaterial());
  196. }
  197. int BoxShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  198. {
  199. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  200. }
  201. void BoxShape::SaveBinaryState(StreamOut &inStream) const
  202. {
  203. ConvexShape::SaveBinaryState(inStream);
  204. inStream.Write(mHalfExtent);
  205. inStream.Write(mConvexRadius);
  206. }
  207. void BoxShape::RestoreBinaryState(StreamIn &inStream)
  208. {
  209. ConvexShape::RestoreBinaryState(inStream);
  210. inStream.Read(mHalfExtent);
  211. inStream.Read(mConvexRadius);
  212. }
  213. void BoxShape::sRegister()
  214. {
  215. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Box);
  216. f.mConstruct = []() -> Shape * { return new BoxShape; };
  217. f.mColor = Color::sGreen;
  218. }
  219. JPH_NAMESPACE_END