TaperedCapsuleShape.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h>
  5. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  6. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  7. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Jolt/Physics/Collision/TransformedShape.h>
  9. #include <Jolt/Geometry/RayCapsule.h>
  10. #include <Jolt/ObjectStream/TypeDeclarations.h>
  11. #include <Jolt/Core/StreamIn.h>
  12. #include <Jolt/Core/StreamOut.h>
  13. #ifdef JPH_DEBUG_RENDERER
  14. #include <Jolt/Renderer/DebugRenderer.h>
  15. #endif // JPH_DEBUG_RENDERER
  16. JPH_NAMESPACE_BEGIN
  17. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TaperedCapsuleShapeSettings)
  18. {
  19. JPH_ADD_BASE_CLASS(TaperedCapsuleShapeSettings, ConvexShapeSettings)
  20. JPH_ADD_ATTRIBUTE(TaperedCapsuleShapeSettings, mHalfHeightOfTaperedCylinder)
  21. JPH_ADD_ATTRIBUTE(TaperedCapsuleShapeSettings, mTopRadius)
  22. JPH_ADD_ATTRIBUTE(TaperedCapsuleShapeSettings, mBottomRadius)
  23. }
  24. bool TaperedCapsuleShapeSettings::IsSphere() const
  25. {
  26. return max(mTopRadius, mBottomRadius) >= 2.0f * mHalfHeightOfTaperedCylinder + min(mTopRadius, mBottomRadius);
  27. }
  28. ShapeSettings::ShapeResult TaperedCapsuleShapeSettings::Create() const
  29. {
  30. if (mCachedResult.IsEmpty())
  31. {
  32. Ref<Shape> shape;
  33. if (IsValid() && IsSphere())
  34. {
  35. // Determine sphere center and radius
  36. float radius, center;
  37. if (mTopRadius > mBottomRadius)
  38. {
  39. radius = mTopRadius;
  40. center = mHalfHeightOfTaperedCylinder;
  41. }
  42. else
  43. {
  44. radius = mBottomRadius;
  45. center = -mHalfHeightOfTaperedCylinder;
  46. }
  47. // Create sphere
  48. shape = new SphereShape(radius, mMaterial);
  49. // Offset sphere if needed
  50. if (abs(center) > 1.0e-6f)
  51. {
  52. RotatedTranslatedShapeSettings rot_trans(Vec3(0, center, 0), Quat::sIdentity(), shape);
  53. mCachedResult = rot_trans.Create();
  54. }
  55. else
  56. mCachedResult.Set(shape);
  57. }
  58. else
  59. {
  60. // Normal tapered capsule shape
  61. shape = new TaperedCapsuleShape(*this, mCachedResult);
  62. }
  63. }
  64. return mCachedResult;
  65. }
  66. TaperedCapsuleShapeSettings::TaperedCapsuleShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, const PhysicsMaterial *inMaterial) :
  67. ConvexShapeSettings(inMaterial),
  68. mHalfHeightOfTaperedCylinder(inHalfHeightOfTaperedCylinder),
  69. mTopRadius(inTopRadius),
  70. mBottomRadius(inBottomRadius)
  71. {
  72. }
  73. TaperedCapsuleShape::TaperedCapsuleShape(const TaperedCapsuleShapeSettings &inSettings, ShapeResult &outResult) :
  74. ConvexShape(EShapeSubType::TaperedCapsule, inSettings, outResult),
  75. mTopRadius(inSettings.mTopRadius),
  76. mBottomRadius(inSettings.mBottomRadius)
  77. {
  78. if (mTopRadius <= 0.0f)
  79. {
  80. outResult.SetError("Invalid top radius");
  81. return;
  82. }
  83. if (mBottomRadius <= 0.0f)
  84. {
  85. outResult.SetError("Invalid bottom radius");
  86. return;
  87. }
  88. if (inSettings.mHalfHeightOfTaperedCylinder <= 0.0f)
  89. {
  90. outResult.SetError("Invalid height");
  91. return;
  92. }
  93. // If this goes off one of the sphere ends falls totally inside the other and you should use a sphere instead
  94. if (inSettings.IsSphere())
  95. {
  96. outResult.SetError("One sphere embedded in other sphere, please use sphere shape instead");
  97. return;
  98. }
  99. // Approximation: The center of mass is exactly half way between the top and bottom cap of the tapered capsule
  100. mTopCenter = inSettings.mHalfHeightOfTaperedCylinder + 0.5f * (mBottomRadius - mTopRadius);
  101. mBottomCenter = -inSettings.mHalfHeightOfTaperedCylinder + 0.5f * (mBottomRadius - mTopRadius);
  102. // Calculate center of mass
  103. mCenterOfMass = Vec3(0, inSettings.mHalfHeightOfTaperedCylinder - mTopCenter, 0);
  104. // Calculate convex radius
  105. mConvexRadius = min(mTopRadius, mBottomRadius);
  106. JPH_ASSERT(mConvexRadius > 0.0f);
  107. // Calculate the sin and tan of the angle that the cone surface makes with the Y axis
  108. // See: TaperedCapsuleShape.gliffy
  109. mSinAlpha = (mBottomRadius - mTopRadius) / (mTopCenter - mBottomCenter);
  110. JPH_ASSERT(mSinAlpha >= -1.0f && mSinAlpha <= 1.0f);
  111. mTanAlpha = Tan(ASin(mSinAlpha));
  112. outResult.Set(this);
  113. }
  114. class TaperedCapsuleShape::TaperedCapsule final : public Support
  115. {
  116. public:
  117. TaperedCapsule(Vec3Arg inTopCenter, Vec3Arg inBottomCenter, float inTopRadius, float inBottomRadius, float inConvexRadius) :
  118. mTopCenter(inTopCenter),
  119. mBottomCenter(inBottomCenter),
  120. mTopRadius(inTopRadius),
  121. mBottomRadius(inBottomRadius),
  122. mConvexRadius(inConvexRadius)
  123. {
  124. static_assert(sizeof(TaperedCapsule) <= sizeof(SupportBuffer), "Buffer size too small");
  125. JPH_ASSERT(IsAligned(this, alignof(TaperedCapsule)));
  126. }
  127. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  128. {
  129. // Check zero vector
  130. float len = inDirection.Length();
  131. if (len == 0.0f)
  132. return mTopCenter + Vec3(0, mTopRadius, 0); // Return top
  133. // Check if the support of the top sphere or bottom sphere is bigger
  134. Vec3 support_top = mTopCenter + (mTopRadius / len) * inDirection;
  135. Vec3 support_bottom = mBottomCenter + (mBottomRadius / len) * inDirection;
  136. if (support_top.Dot(inDirection) > support_bottom.Dot(inDirection))
  137. return support_top;
  138. else
  139. return support_bottom;
  140. }
  141. virtual float GetConvexRadius() const override
  142. {
  143. return mConvexRadius;
  144. }
  145. private:
  146. Vec3 mTopCenter;
  147. Vec3 mBottomCenter;
  148. float mTopRadius;
  149. float mBottomRadius;
  150. float mConvexRadius;
  151. };
  152. const ConvexShape::Support *TaperedCapsuleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  153. {
  154. JPH_ASSERT(IsValidScale(inScale));
  155. // Get scaled tapered capsule
  156. Vec3 abs_scale = inScale.Abs();
  157. float scale_xz = abs_scale.GetX();
  158. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  159. Vec3 scaled_top_center = Vec3(0, scale_y * mTopCenter, 0);
  160. Vec3 scaled_bottom_center = Vec3(0, scale_y * mBottomCenter, 0);
  161. float scaled_top_radius = scale_xz * mTopRadius;
  162. float scaled_bottom_radius = scale_xz * mBottomRadius;
  163. float scaled_convex_radius = scale_xz * mConvexRadius;
  164. switch (inMode)
  165. {
  166. case ESupportMode::IncludeConvexRadius:
  167. return new (&inBuffer) TaperedCapsule(scaled_top_center, scaled_bottom_center, scaled_top_radius, scaled_bottom_radius, 0.0f);
  168. case ESupportMode::ExcludeConvexRadius:
  169. {
  170. // Get radii reduced by convex radius
  171. float tr = scaled_top_radius - scaled_convex_radius;
  172. float br = scaled_bottom_radius - scaled_convex_radius;
  173. JPH_ASSERT(tr >= 0.0f && br >= 0.0f);
  174. JPH_ASSERT(tr == 0.0f || br == 0.0f, "Convex radius should be that of the smallest sphere");
  175. return new (&inBuffer) TaperedCapsule(scaled_top_center, scaled_bottom_center, tr, br, scaled_convex_radius);
  176. }
  177. }
  178. JPH_ASSERT(false);
  179. return nullptr;
  180. }
  181. void TaperedCapsuleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  182. {
  183. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  184. JPH_ASSERT(IsValidScale(inScale));
  185. // Check zero vector
  186. float len = inDirection.Length();
  187. if (len == 0.0f)
  188. return;
  189. // Get scaled tapered capsule
  190. Vec3 abs_scale = inScale.Abs();
  191. float scale_xz = abs_scale.GetX();
  192. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  193. Vec3 scaled_top_center = Vec3(0, scale_y * mTopCenter, 0);
  194. Vec3 scaled_bottom_center = Vec3(0, scale_y * mBottomCenter, 0);
  195. float scaled_top_radius = scale_xz * mTopRadius;
  196. float scaled_bottom_radius = scale_xz * mBottomRadius;
  197. // Get support point for top and bottom sphere in the opposite of inDirection (including convex radius)
  198. Vec3 support_top = scaled_top_center - (scaled_top_radius / len) * inDirection;
  199. Vec3 support_bottom = scaled_bottom_center - (scaled_bottom_radius / len) * inDirection;
  200. // Get projection on inDirection
  201. float proj_top = support_top.Dot(inDirection);
  202. float proj_bottom = support_bottom.Dot(inDirection);
  203. // If projection is roughly equal then return line, otherwise we return nothing as there's only 1 point
  204. if (abs(proj_top - proj_bottom) < cCapsuleProjectionSlop * len)
  205. {
  206. outVertices.push_back(inCenterOfMassTransform * support_top);
  207. outVertices.push_back(inCenterOfMassTransform * support_bottom);
  208. }
  209. }
  210. MassProperties TaperedCapsuleShape::GetMassProperties() const
  211. {
  212. AABox box = GetInertiaApproximation();
  213. MassProperties p;
  214. p.SetMassAndInertiaOfSolidBox(box.GetSize(), GetDensity());
  215. return p;
  216. }
  217. Vec3 TaperedCapsuleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  218. {
  219. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  220. // See: TaperedCapsuleShape.gliffy
  221. // We need to calculate ty and by in order to see if the position is on the top or bottom sphere
  222. // sin(alpha) = by / br = ty / tr
  223. // => by = sin(alpha) * br, ty = sin(alpha) * tr
  224. if (inLocalSurfacePosition.GetY() > mTopCenter + mSinAlpha * mTopRadius)
  225. return (inLocalSurfacePosition - Vec3(0, mTopCenter, 0)).Normalized();
  226. else if (inLocalSurfacePosition.GetY() < mBottomCenter + mSinAlpha * mBottomRadius)
  227. return (inLocalSurfacePosition - Vec3(0, mBottomCenter, 0)).Normalized();
  228. else
  229. {
  230. // Get perpendicular vector to the surface in the xz plane
  231. Vec3 perpendicular = Vec3(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ()).NormalizedOr(Vec3::sAxisX());
  232. // We know that the perpendicular has length 1 and that it needs a y component where tan(alpha) = y / 1 in order to align it to the surface
  233. perpendicular.SetY(mTanAlpha);
  234. return perpendicular.Normalized();
  235. }
  236. }
  237. AABox TaperedCapsuleShape::GetLocalBounds() const
  238. {
  239. float max_radius = max(mTopRadius, mBottomRadius);
  240. return AABox(Vec3(-max_radius, mBottomCenter - mBottomRadius, -max_radius), Vec3(max_radius, mTopCenter + mTopRadius, max_radius));
  241. }
  242. AABox TaperedCapsuleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  243. {
  244. JPH_ASSERT(IsValidScale(inScale));
  245. Vec3 abs_scale = inScale.Abs();
  246. float scale_xz = abs_scale.GetX();
  247. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  248. Vec3 bottom_extent = Vec3::sReplicate(scale_xz * mBottomRadius);
  249. Vec3 bottom_center = inCenterOfMassTransform * Vec3(0, scale_y * mBottomCenter, 0);
  250. Vec3 top_extent = Vec3::sReplicate(scale_xz * mTopRadius);
  251. Vec3 top_center = inCenterOfMassTransform * Vec3(0, scale_y * mTopCenter, 0);
  252. Vec3 p1 = Vec3::sMin(top_center - top_extent, bottom_center - bottom_extent);
  253. Vec3 p2 = Vec3::sMax(top_center + top_extent, bottom_center + bottom_extent);
  254. return AABox(p1, p2);
  255. }
  256. #ifdef JPH_DEBUG_RENDERER
  257. void TaperedCapsuleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  258. {
  259. if (mGeometry == nullptr)
  260. {
  261. SupportBuffer buffer;
  262. const Support *support = GetSupportFunction(ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  263. mGeometry = inRenderer->CreateTriangleGeometryForConvex([support](Vec3Arg inDirection) { return support->GetSupport(inDirection); });
  264. }
  265. // Preserve flip along y axis but make sure we're not inside out
  266. Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? Vec3(-1, 1, 1) * inScale : inScale;
  267. RMat44 world_transform = inCenterOfMassTransform * Mat44::sScale(scale);
  268. AABox bounds = Shape::GetWorldSpaceBounds(inCenterOfMassTransform, inScale);
  269. float lod_scale_sq = Square(max(mTopRadius, mBottomRadius));
  270. Color color = inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor;
  271. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  272. inRenderer->DrawGeometry(world_transform, bounds, lod_scale_sq, color, mGeometry, DebugRenderer::ECullMode::CullBackFace, DebugRenderer::ECastShadow::On, draw_mode);
  273. }
  274. #endif // JPH_DEBUG_RENDERER
  275. AABox TaperedCapsuleShape::GetInertiaApproximation() const
  276. {
  277. // TODO: For now the mass and inertia is that of a box
  278. float avg_radius = 0.5f * (mTopRadius + mBottomRadius);
  279. return AABox(Vec3(-avg_radius, mBottomCenter - mBottomRadius, -avg_radius), Vec3(avg_radius, mTopCenter + mTopRadius, avg_radius));
  280. }
  281. void TaperedCapsuleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  282. {
  283. Vec3 scale;
  284. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  285. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  286. ts.SetShapeScale(scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()));
  287. ioCollector.AddHit(ts);
  288. }
  289. void TaperedCapsuleShape::SaveBinaryState(StreamOut &inStream) const
  290. {
  291. ConvexShape::SaveBinaryState(inStream);
  292. inStream.Write(mCenterOfMass);
  293. inStream.Write(mTopRadius);
  294. inStream.Write(mBottomRadius);
  295. inStream.Write(mTopCenter);
  296. inStream.Write(mBottomCenter);
  297. inStream.Write(mConvexRadius);
  298. inStream.Write(mSinAlpha);
  299. inStream.Write(mTanAlpha);
  300. }
  301. void TaperedCapsuleShape::RestoreBinaryState(StreamIn &inStream)
  302. {
  303. ConvexShape::RestoreBinaryState(inStream);
  304. inStream.Read(mCenterOfMass);
  305. inStream.Read(mTopRadius);
  306. inStream.Read(mBottomRadius);
  307. inStream.Read(mTopCenter);
  308. inStream.Read(mBottomCenter);
  309. inStream.Read(mConvexRadius);
  310. inStream.Read(mSinAlpha);
  311. inStream.Read(mTanAlpha);
  312. }
  313. bool TaperedCapsuleShape::IsValidScale(Vec3Arg inScale) const
  314. {
  315. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs());
  316. }
  317. void TaperedCapsuleShape::sRegister()
  318. {
  319. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::TaperedCapsule);
  320. f.mConstruct = []() -> Shape * { return new TaperedCapsuleShape; };
  321. f.mColor = Color::sGreen;
  322. }
  323. JPH_NAMESPACE_END