CapsuleShape.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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/CapsuleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  7. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  9. #include <Jolt/Physics/Collision/RayCast.h>
  10. #include <Jolt/Physics/Collision/CastResult.h>
  11. #include <Jolt/Physics/Collision/CollidePointResult.h>
  12. #include <Jolt/Physics/Collision/TransformedShape.h>
  13. #include <Jolt/Geometry/RayCapsule.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(CapsuleShapeSettings)
  22. {
  23. JPH_ADD_BASE_CLASS(CapsuleShapeSettings, ConvexShapeSettings)
  24. JPH_ADD_ATTRIBUTE(CapsuleShapeSettings, mRadius)
  25. JPH_ADD_ATTRIBUTE(CapsuleShapeSettings, mHalfHeightOfCylinder)
  26. }
  27. static const int cCapsuleDetailLevel = 2;
  28. static const std::vector<Vec3> sCapsuleTopTriangles = []() {
  29. std::vector<Vec3> verts;
  30. GetTrianglesContextVertexList::sCreateHalfUnitSphereTop(verts, cCapsuleDetailLevel);
  31. return verts;
  32. }();
  33. static const std::vector<Vec3> sCapsuleMiddleTriangles = []() {
  34. std::vector<Vec3> verts;
  35. GetTrianglesContextVertexList::sCreateUnitOpenCylinder(verts, cCapsuleDetailLevel);
  36. return verts;
  37. }();
  38. static const std::vector<Vec3> sCapsuleBottomTriangles = []() {
  39. std::vector<Vec3> verts;
  40. GetTrianglesContextVertexList::sCreateHalfUnitSphereBottom(verts, cCapsuleDetailLevel);
  41. return verts;
  42. }();
  43. ShapeSettings::ShapeResult CapsuleShapeSettings::Create() const
  44. {
  45. if (mCachedResult.IsEmpty())
  46. {
  47. Ref<Shape> shape;
  48. if (IsValid() && IsSphere())
  49. {
  50. // If the capsule has no height, use a sphere instead
  51. shape = new SphereShape(mRadius, mMaterial);
  52. mCachedResult.Set(shape);
  53. }
  54. else
  55. shape = new CapsuleShape(*this, mCachedResult);
  56. }
  57. return mCachedResult;
  58. }
  59. CapsuleShape::CapsuleShape(const CapsuleShapeSettings &inSettings, ShapeResult &outResult) :
  60. ConvexShape(EShapeSubType::Capsule, inSettings, outResult),
  61. mRadius(inSettings.mRadius),
  62. mHalfHeightOfCylinder(inSettings.mHalfHeightOfCylinder)
  63. {
  64. if (inSettings.mHalfHeightOfCylinder <= 0.0f)
  65. {
  66. outResult.SetError("Invalid height");
  67. return;
  68. }
  69. if (inSettings.mRadius <= 0.0f)
  70. {
  71. outResult.SetError("Invalid radius");
  72. return;
  73. }
  74. outResult.Set(this);
  75. }
  76. class CapsuleShape::CapsuleNoConvex final : public Support
  77. {
  78. public:
  79. CapsuleNoConvex(Vec3Arg inHalfHeightOfCylinder, float inConvexRadius) :
  80. mHalfHeightOfCylinder(inHalfHeightOfCylinder),
  81. mConvexRadius(inConvexRadius)
  82. {
  83. static_assert(sizeof(CapsuleNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  84. JPH_ASSERT(IsAligned(this, alignof(CapsuleNoConvex)));
  85. }
  86. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  87. {
  88. if (inDirection.GetY() > 0)
  89. return mHalfHeightOfCylinder;
  90. else
  91. return -mHalfHeightOfCylinder;
  92. }
  93. virtual float GetConvexRadius() const override
  94. {
  95. return mConvexRadius;
  96. }
  97. private:
  98. Vec3 mHalfHeightOfCylinder;
  99. float mConvexRadius;
  100. };
  101. class CapsuleShape::CapsuleWithConvex final : public Support
  102. {
  103. public:
  104. CapsuleWithConvex(Vec3Arg inHalfHeightOfCylinder, float inRadius) :
  105. mHalfHeightOfCylinder(inHalfHeightOfCylinder),
  106. mRadius(inRadius)
  107. {
  108. static_assert(sizeof(CapsuleWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  109. JPH_ASSERT(IsAligned(this, alignof(CapsuleWithConvex)));
  110. }
  111. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  112. {
  113. float len = inDirection.Length();
  114. Vec3 radius = len > 0.0f? inDirection * (mRadius / len) : Vec3::sZero();
  115. if (inDirection.GetY() > 0)
  116. return radius + mHalfHeightOfCylinder;
  117. else
  118. return radius - mHalfHeightOfCylinder;
  119. }
  120. virtual float GetConvexRadius() const override
  121. {
  122. return 0.0f;
  123. }
  124. private:
  125. Vec3 mHalfHeightOfCylinder;
  126. float mRadius;
  127. };
  128. const ConvexShape::Support *CapsuleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  129. {
  130. JPH_ASSERT(IsValidScale(inScale));
  131. // Get scaled capsule
  132. Vec3 abs_scale = inScale.Abs();
  133. float scale = abs_scale.GetX();
  134. Vec3 scaled_half_height_of_cylinder = Vec3(0, scale * mHalfHeightOfCylinder, 0);
  135. float scaled_radius = scale * mRadius;
  136. switch (inMode)
  137. {
  138. case ESupportMode::IncludeConvexRadius:
  139. return new (&inBuffer) CapsuleWithConvex(scaled_half_height_of_cylinder, scaled_radius);
  140. case ESupportMode::ExcludeConvexRadius:
  141. return new (&inBuffer) CapsuleNoConvex(scaled_half_height_of_cylinder, scaled_radius);
  142. }
  143. JPH_ASSERT(false);
  144. return nullptr;
  145. }
  146. void CapsuleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  147. {
  148. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  149. JPH_ASSERT(IsValidScale(inScale));
  150. // Get direction in horizontal plane
  151. Vec3 direction = inDirection;
  152. direction.SetComponent(1, 0.0f);
  153. // Check zero vector, in this case we're hitting from top/bottom so there's no supporting face
  154. float len = direction.Length();
  155. if (len == 0.0f)
  156. return;
  157. // Get scaled capsule
  158. Vec3 abs_scale = inScale.Abs();
  159. float scale = abs_scale.GetX();
  160. Vec3 scaled_half_height_of_cylinder = Vec3(0, scale * mHalfHeightOfCylinder, 0);
  161. float scaled_radius = scale * mRadius;
  162. // Get support point for top and bottom sphere in the opposite of 'direction' (including convex radius)
  163. Vec3 support = (scaled_radius / len) * direction;
  164. Vec3 support_top = scaled_half_height_of_cylinder - support;
  165. Vec3 support_bottom = -scaled_half_height_of_cylinder - support;
  166. // Get projection on inDirection
  167. // Note that inDirection is not normalized, so we need to divide by inDirection.Length() to get the actual projection
  168. // We've multiplied both sides of the if below with inDirection.Length()
  169. float proj_top = support_top.Dot(inDirection);
  170. float proj_bottom = support_bottom.Dot(inDirection);
  171. // If projection is roughly equal then return line, otherwise we return nothing as there's only 1 point
  172. if (abs(proj_top - proj_bottom) < cCapsuleProjectionSlop * inDirection.Length())
  173. {
  174. outVertices.push_back(inCenterOfMassTransform * support_top);
  175. outVertices.push_back(inCenterOfMassTransform * support_bottom);
  176. }
  177. }
  178. MassProperties CapsuleShape::GetMassProperties() const
  179. {
  180. MassProperties p;
  181. float density = GetDensity();
  182. // Calculate inertia and mass according to:
  183. // https://www.gamedev.net/resources/_/technical/math-and-physics/capsule-inertia-tensor-r3856
  184. float radius_sq = mRadius * mRadius;
  185. float height = 2.0f * mHalfHeightOfCylinder;
  186. float cylinder_mass = JPH_PI * height * radius_sq * density;
  187. float hemisphere_mass = (2.0f * JPH_PI / 3.0f) * radius_sq * mRadius * density;
  188. // From cylinder
  189. float inertia_y = radius_sq * cylinder_mass * 0.5f;
  190. float inertia_x = inertia_y * 0.5f + cylinder_mass * height * height / 12.0f;
  191. float inertia_z = inertia_x;
  192. // From hemispheres
  193. float temp0 = hemisphere_mass * 2.0f * radius_sq / 5.0f;
  194. inertia_y += temp0 * 2.0f;
  195. float temp1 = mHalfHeightOfCylinder;
  196. float temp2 = temp0 + hemisphere_mass * (temp1 * temp1 + (3.0f / 8.0f) * height * mRadius);
  197. inertia_x += temp2 * 2.0f;
  198. inertia_z += temp2 * 2.0f;
  199. // Mass is cylinder + hemispheres
  200. p.mMass = cylinder_mass + hemisphere_mass * 2.0f;
  201. // Set inertia
  202. p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
  203. return p;
  204. }
  205. Vec3 CapsuleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  206. {
  207. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  208. if (inLocalSurfacePosition.GetY() > mHalfHeightOfCylinder)
  209. return (inLocalSurfacePosition - Vec3(0, mHalfHeightOfCylinder, 0)).Normalized();
  210. else if (inLocalSurfacePosition.GetY() < -mHalfHeightOfCylinder)
  211. return (inLocalSurfacePosition - Vec3(0, -mHalfHeightOfCylinder, 0)).Normalized();
  212. else
  213. return Vec3(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ()).NormalizedOr(Vec3::sAxisX());
  214. }
  215. AABox CapsuleShape::GetLocalBounds() const
  216. {
  217. Vec3 extent = Vec3::sReplicate(mRadius) + Vec3(0, mHalfHeightOfCylinder, 0);
  218. return AABox(-extent, extent);
  219. }
  220. AABox CapsuleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  221. {
  222. JPH_ASSERT(IsValidScale(inScale));
  223. Vec3 abs_scale = inScale.Abs();
  224. float scale = abs_scale.GetX();
  225. Vec3 extent = Vec3::sReplicate(scale * mRadius);
  226. Vec3 height = Vec3(0, scale * mHalfHeightOfCylinder, 0);
  227. Vec3 p1 = inCenterOfMassTransform * -height;
  228. Vec3 p2 = inCenterOfMassTransform * height;
  229. return AABox(Vec3::sMin(p1, p2) - extent, Vec3::sMax(p1, p2) + extent);
  230. }
  231. #ifdef JPH_DEBUG_RENDERER
  232. void CapsuleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  233. {
  234. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  235. inRenderer->DrawCapsule(inCenterOfMassTransform * Mat44::sScale(inScale.Abs().GetX()), mHalfHeightOfCylinder, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  236. }
  237. #endif // JPH_DEBUG_RENDERER
  238. bool CapsuleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  239. {
  240. // Test ray against capsule
  241. float fraction = RayCapsule(inRay.mOrigin, inRay.mDirection, mHalfHeightOfCylinder, mRadius);
  242. if (fraction < ioHit.mFraction)
  243. {
  244. ioHit.mFraction = fraction;
  245. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  246. return true;
  247. }
  248. return false;
  249. }
  250. void CapsuleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  251. {
  252. // Test shape filter
  253. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  254. return;
  255. float radius_sq = Square(mRadius);
  256. // Get vertical distance to the top/bottom sphere centers
  257. float delta_y = abs(inPoint.GetY()) - mHalfHeightOfCylinder;
  258. // Get distance in horizontal plane
  259. float xz_sq = Square(inPoint.GetX()) + Square(inPoint.GetZ());
  260. // Check if the point is in one of the two spheres
  261. bool in_sphere = xz_sq + Square(delta_y) <= radius_sq;
  262. // Check if the point is in the cylinder in the middle
  263. bool in_cylinder = delta_y <= 0.0f && xz_sq <= radius_sq;
  264. if (in_sphere || in_cylinder)
  265. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  266. }
  267. void CapsuleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  268. {
  269. Vec3 scale;
  270. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  271. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  272. ts.SetShapeScale(ScaleHelpers::MakeUniformScale(scale.Abs()));
  273. ioCollector.AddHit(ts);
  274. }
  275. void CapsuleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  276. {
  277. JPH_ASSERT(IsValidScale(inScale));
  278. Vec3 abs_scale = inScale.Abs();
  279. float scale = abs_scale.GetX();
  280. GetTrianglesContextMultiVertexList *context = new (&ioContext) GetTrianglesContextMultiVertexList(false, GetMaterial());
  281. Mat44 world_matrix = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(scale);
  282. Mat44 top_matrix = world_matrix * Mat44(Vec4(mRadius, 0, 0, 0), Vec4(0, mRadius, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, mHalfHeightOfCylinder, 0, 1));
  283. context->AddPart(top_matrix, sCapsuleTopTriangles.data(), sCapsuleTopTriangles.size());
  284. Mat44 middle_matrix = world_matrix * Mat44::sScale(Vec3(mRadius, mHalfHeightOfCylinder, mRadius));
  285. context->AddPart(middle_matrix, sCapsuleMiddleTriangles.data(), sCapsuleMiddleTriangles.size());
  286. Mat44 bottom_matrix = world_matrix * Mat44(Vec4(mRadius, 0, 0, 0), Vec4(0, mRadius, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, -mHalfHeightOfCylinder, 0, 1));
  287. context->AddPart(bottom_matrix, sCapsuleBottomTriangles.data(), sCapsuleBottomTriangles.size());
  288. }
  289. int CapsuleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  290. {
  291. return ((GetTrianglesContextMultiVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  292. }
  293. void CapsuleShape::SaveBinaryState(StreamOut &inStream) const
  294. {
  295. ConvexShape::SaveBinaryState(inStream);
  296. inStream.Write(mRadius);
  297. inStream.Write(mHalfHeightOfCylinder);
  298. }
  299. void CapsuleShape::RestoreBinaryState(StreamIn &inStream)
  300. {
  301. ConvexShape::RestoreBinaryState(inStream);
  302. inStream.Read(mRadius);
  303. inStream.Read(mHalfHeightOfCylinder);
  304. }
  305. bool CapsuleShape::IsValidScale(Vec3Arg inScale) const
  306. {
  307. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs());
  308. }
  309. void CapsuleShape::sRegister()
  310. {
  311. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Capsule);
  312. f.mConstruct = []() -> Shape * { return new CapsuleShape; };
  313. f.mColor = Color::sGreen;
  314. }
  315. JPH_NAMESPACE_END