TaperedCapsuleShape.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/Collision/Shape/TaperedCapsuleShape.h>
  5. #include <Physics/Collision/Shape/SphereShape.h>
  6. #include <Physics/Collision/Shape/RotatedTranslatedShape.h>
  7. #include <Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Physics/Collision/TransformedShape.h>
  9. #include <Geometry/RayCapsule.h>
  10. #include <ObjectStream/TypeDeclarations.h>
  11. #include <Core/StreamIn.h>
  12. #include <Core/StreamOut.h>
  13. #ifdef JPH_DEBUG_RENDERER
  14. #include <Renderer/DebugRenderer.h>
  15. #endif // JPH_DEBUG_RENDERER
  16. namespace JPH {
  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(Vec3Arg inDirection, Vec3Arg inScale, SupportingFace &outVertices) const
  182. {
  183. JPH_ASSERT(IsValidScale(inScale));
  184. // Check zero vector
  185. float len = inDirection.Length();
  186. if (len == 0.0f)
  187. return;
  188. // Get scaled tapered capsule
  189. Vec3 abs_scale = inScale.Abs();
  190. float scale_xz = abs_scale.GetX();
  191. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  192. Vec3 scaled_top_center = Vec3(0, scale_y * mTopCenter, 0);
  193. Vec3 scaled_bottom_center = Vec3(0, scale_y * mBottomCenter, 0);
  194. float scaled_top_radius = scale_xz * mTopRadius;
  195. float scaled_bottom_radius = scale_xz * mBottomRadius;
  196. // Get support point for top and bottom sphere in the opposite of inDirection (including convex radius)
  197. Vec3 support_top = scaled_top_center - (scaled_top_radius / len) * inDirection;
  198. Vec3 support_bottom = scaled_bottom_center - (scaled_bottom_radius / len) * inDirection;
  199. // Get projection on inDirection
  200. float proj_top = support_top.Dot(inDirection);
  201. float proj_bottom = support_bottom.Dot(inDirection);
  202. // If projection is roughly equal then return line, otherwise we return nothing as there's only 1 point
  203. if (abs(proj_top - proj_bottom) < cCapsuleProjectionSlop * len)
  204. {
  205. outVertices.push_back(support_top);
  206. outVertices.push_back(support_bottom);
  207. }
  208. }
  209. MassProperties TaperedCapsuleShape::GetMassProperties() const
  210. {
  211. AABox box = GetInertiaApproximation();
  212. MassProperties p;
  213. p.SetMassAndInertiaOfSolidBox(box.GetSize(), GetDensity());
  214. return p;
  215. }
  216. Vec3 TaperedCapsuleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  217. {
  218. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  219. // See: TaperedCapsuleShape.gliffy
  220. // We need to calculate ty and by in order to see if the position is on the top or bottom sphere
  221. // sin(alpha) = by / br = ty / tr
  222. // => by = sin(alpha) * br, ty = sin(alpha) * tr
  223. if (inLocalSurfacePosition.GetY() > mTopCenter + mSinAlpha * mTopRadius)
  224. return (inLocalSurfacePosition - Vec3(0, mTopCenter, 0)).Normalized();
  225. else if (inLocalSurfacePosition.GetY() < mBottomCenter + mSinAlpha * mBottomRadius)
  226. return (inLocalSurfacePosition - Vec3(0, mBottomCenter, 0)).Normalized();
  227. else
  228. {
  229. // Get perpendicular vector to the surface in the xz plane
  230. Vec3 perpendicular = Vec3(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ()).Normalized();
  231. // 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
  232. perpendicular.SetY(mTanAlpha);
  233. return perpendicular.Normalized();
  234. }
  235. }
  236. AABox TaperedCapsuleShape::GetLocalBounds() const
  237. {
  238. float max_radius = max(mTopRadius, mBottomRadius);
  239. return AABox(Vec3(-max_radius, mBottomCenter - mBottomRadius, -max_radius), Vec3(max_radius, mTopCenter + mTopRadius, max_radius));
  240. }
  241. AABox TaperedCapsuleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  242. {
  243. JPH_ASSERT(IsValidScale(inScale));
  244. Vec3 abs_scale = inScale.Abs();
  245. float scale_xz = abs_scale.GetX();
  246. float scale_y = inScale.GetY(); // The sign of y is important as it flips the tapered capsule
  247. Vec3 bottom_extent = Vec3::sReplicate(scale_xz * mBottomRadius);
  248. Vec3 bottom_center = inCenterOfMassTransform * Vec3(0, scale_y * mBottomCenter, 0);
  249. Vec3 top_extent = Vec3::sReplicate(scale_xz * mTopRadius);
  250. Vec3 top_center = inCenterOfMassTransform * Vec3(0, scale_y * mTopCenter, 0);
  251. Vec3 p1 = Vec3::sMin(top_center - top_extent, bottom_center - bottom_extent);
  252. Vec3 p2 = Vec3::sMax(top_center + top_extent, bottom_center + bottom_extent);
  253. return AABox(p1, p2);
  254. }
  255. #ifdef JPH_DEBUG_RENDERER
  256. void TaperedCapsuleShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  257. {
  258. if (mGeometry == nullptr)
  259. {
  260. SupportBuffer buffer;
  261. const Support *support = GetSupportFunction(ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  262. mGeometry = inRenderer->CreateTriangleGeometryForConvex([support](Vec3Arg inDirection) { return support->GetSupport(inDirection); });
  263. }
  264. // Preserve flip along y axis but make sure we're not inside out
  265. Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? Vec3(-1, 1, 1) * inScale : inScale;
  266. Mat44 world_transform = inCenterOfMassTransform * Mat44::sScale(scale);
  267. AABox bounds = GetWorldSpaceBounds(inCenterOfMassTransform, inScale);
  268. float lod_scale_sq = Square(max(mTopRadius, mBottomRadius));
  269. Color color = inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor;
  270. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  271. inRenderer->DrawGeometry(world_transform, bounds, lod_scale_sq, color, mGeometry, DebugRenderer::ECullMode::CullBackFace, DebugRenderer::ECastShadow::On, draw_mode);
  272. }
  273. #endif // JPH_DEBUG_RENDERER
  274. AABox TaperedCapsuleShape::GetInertiaApproximation() const
  275. {
  276. // TODO: For now the mass and inertia is that of a box
  277. float avg_radius = 0.5f * (mTopRadius + mBottomRadius);
  278. return AABox(Vec3(-avg_radius, mBottomCenter - mBottomRadius, -avg_radius), Vec3(avg_radius, mTopCenter + mTopRadius, avg_radius));
  279. }
  280. void TaperedCapsuleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  281. {
  282. Vec3 scale;
  283. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  284. TransformedShape ts(transform.GetTranslation(), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  285. ts.SetShapeScale(scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()));
  286. ioCollector.AddHit(ts);
  287. }
  288. void TaperedCapsuleShape::SaveBinaryState(StreamOut &inStream) const
  289. {
  290. ConvexShape::SaveBinaryState(inStream);
  291. inStream.Write(mCenterOfMass);
  292. inStream.Write(mTopRadius);
  293. inStream.Write(mBottomRadius);
  294. inStream.Write(mTopCenter);
  295. inStream.Write(mBottomCenter);
  296. inStream.Write(mConvexRadius);
  297. inStream.Write(mSinAlpha);
  298. inStream.Write(mTanAlpha);
  299. }
  300. void TaperedCapsuleShape::RestoreBinaryState(StreamIn &inStream)
  301. {
  302. ConvexShape::RestoreBinaryState(inStream);
  303. inStream.Read(mCenterOfMass);
  304. inStream.Read(mTopRadius);
  305. inStream.Read(mBottomRadius);
  306. inStream.Read(mTopCenter);
  307. inStream.Read(mBottomCenter);
  308. inStream.Read(mConvexRadius);
  309. inStream.Read(mSinAlpha);
  310. inStream.Read(mTanAlpha);
  311. }
  312. bool TaperedCapsuleShape::IsValidScale(Vec3Arg inScale) const
  313. {
  314. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScale(inScale.Abs());
  315. }
  316. void TaperedCapsuleShape::sRegister()
  317. {
  318. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::TaperedCapsule);
  319. f.mConstruct = []() -> Shape * { return new TaperedCapsuleShape; };
  320. f.mColor = Color::sGreen;
  321. }
  322. } // JPH