CylinderShape.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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/CylinderShape.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/Collision/CollideSoftBodyVertexIterator.h>
  13. #include <Jolt/Geometry/RayCylinder.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(CylinderShapeSettings)
  22. {
  23. JPH_ADD_BASE_CLASS(CylinderShapeSettings, ConvexShapeSettings)
  24. JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mHalfHeight)
  25. JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mRadius)
  26. JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mConvexRadius)
  27. }
  28. // Approximation of top face with 8 vertices
  29. static const Vec3 cCylinderTopFace[] =
  30. {
  31. Vec3(0.0f, 1.0f, 1.0f),
  32. Vec3(0.707106769f, 1.0f, 0.707106769f),
  33. Vec3(1.0f, 1.0f, 0.0f),
  34. Vec3(0.707106769f, 1.0f, -0.707106769f),
  35. Vec3(-0.0f, 1.0f, -1.0f),
  36. Vec3(-0.707106769f, 1.0f, -0.707106769f),
  37. Vec3(-1.0f, 1.0f, 0.0f),
  38. Vec3(-0.707106769f, 1.0f, 0.707106769f)
  39. };
  40. static const StaticArray<Vec3, 96> sUnitCylinderTriangles = []() {
  41. StaticArray<Vec3, 96> verts;
  42. const Vec3 bottom_offset(0.0f, -2.0f, 0.0f);
  43. int num_verts = sizeof(cCylinderTopFace) / sizeof(Vec3);
  44. for (int i = 0; i < num_verts; ++i)
  45. {
  46. Vec3 t1 = cCylinderTopFace[i];
  47. Vec3 t2 = cCylinderTopFace[(i + 1) % num_verts];
  48. Vec3 b1 = cCylinderTopFace[i] + bottom_offset;
  49. Vec3 b2 = cCylinderTopFace[(i + 1) % num_verts] + bottom_offset;
  50. // Top
  51. verts.emplace_back(0.0f, 1.0f, 0.0f);
  52. verts.push_back(t1);
  53. verts.push_back(t2);
  54. // Bottom
  55. verts.emplace_back(0.0f, -1.0f, 0.0f);
  56. verts.push_back(b2);
  57. verts.push_back(b1);
  58. // Side
  59. verts.push_back(t1);
  60. verts.push_back(b1);
  61. verts.push_back(t2);
  62. verts.push_back(t2);
  63. verts.push_back(b1);
  64. verts.push_back(b2);
  65. }
  66. return verts;
  67. }();
  68. ShapeSettings::ShapeResult CylinderShapeSettings::Create() const
  69. {
  70. if (mCachedResult.IsEmpty())
  71. Ref<Shape> shape = new CylinderShape(*this, mCachedResult);
  72. return mCachedResult;
  73. }
  74. CylinderShape::CylinderShape(const CylinderShapeSettings &inSettings, ShapeResult &outResult) :
  75. ConvexShape(EShapeSubType::Cylinder, inSettings, outResult),
  76. mHalfHeight(inSettings.mHalfHeight),
  77. mRadius(inSettings.mRadius),
  78. mConvexRadius(inSettings.mConvexRadius)
  79. {
  80. if (inSettings.mHalfHeight < inSettings.mConvexRadius)
  81. {
  82. outResult.SetError("Invalid height");
  83. return;
  84. }
  85. if (inSettings.mRadius < inSettings.mConvexRadius)
  86. {
  87. outResult.SetError("Invalid radius");
  88. return;
  89. }
  90. if (inSettings.mConvexRadius < 0.0f)
  91. {
  92. outResult.SetError("Invalid convex radius");
  93. return;
  94. }
  95. outResult.Set(this);
  96. }
  97. CylinderShape::CylinderShape(float inHalfHeight, float inRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) :
  98. ConvexShape(EShapeSubType::Cylinder, inMaterial),
  99. mHalfHeight(inHalfHeight),
  100. mRadius(inRadius),
  101. mConvexRadius(inConvexRadius)
  102. {
  103. JPH_ASSERT(inHalfHeight >= inConvexRadius);
  104. JPH_ASSERT(inRadius >= inConvexRadius);
  105. JPH_ASSERT(inConvexRadius >= 0.0f);
  106. }
  107. class CylinderShape::Cylinder final : public Support
  108. {
  109. public:
  110. Cylinder(float inHalfHeight, float inRadius, float inConvexRadius) :
  111. mHalfHeight(inHalfHeight),
  112. mRadius(inRadius),
  113. mConvexRadius(inConvexRadius)
  114. {
  115. static_assert(sizeof(Cylinder) <= sizeof(SupportBuffer), "Buffer size too small");
  116. JPH_ASSERT(IsAligned(this, alignof(Cylinder)));
  117. }
  118. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  119. {
  120. // Support mapping, taken from:
  121. // A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen
  122. // page 8
  123. float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
  124. float o = sqrt(Square(x) + Square(z));
  125. if (o > 0.0f)
  126. return Vec3((mRadius * x) / o, Sign(y) * mHalfHeight, (mRadius * z) / o);
  127. else
  128. return Vec3(0, Sign(y) * mHalfHeight, 0);
  129. }
  130. virtual float GetConvexRadius() const override
  131. {
  132. return mConvexRadius;
  133. }
  134. private:
  135. float mHalfHeight;
  136. float mRadius;
  137. float mConvexRadius;
  138. };
  139. const ConvexShape::Support *CylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  140. {
  141. JPH_ASSERT(IsValidScale(inScale));
  142. // Get scaled cylinder
  143. Vec3 abs_scale = inScale.Abs();
  144. float scale_xz = abs_scale.GetX();
  145. float scale_y = abs_scale.GetY();
  146. float scaled_half_height = scale_y * mHalfHeight;
  147. float scaled_radius = scale_xz * mRadius;
  148. float scaled_convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  149. switch (inMode)
  150. {
  151. case ESupportMode::IncludeConvexRadius:
  152. case ESupportMode::Default:
  153. return new (&inBuffer) Cylinder(scaled_half_height, scaled_radius, 0.0f);
  154. case ESupportMode::ExcludeConvexRadius:
  155. return new (&inBuffer) Cylinder(scaled_half_height - scaled_convex_radius, scaled_radius - scaled_convex_radius, scaled_convex_radius);
  156. }
  157. JPH_ASSERT(false);
  158. return nullptr;
  159. }
  160. void CylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  161. {
  162. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  163. JPH_ASSERT(IsValidScale(inScale));
  164. // Get scaled cylinder
  165. Vec3 abs_scale = inScale.Abs();
  166. float scale_xz = abs_scale.GetX();
  167. float scale_y = abs_scale.GetY();
  168. float scaled_half_height = scale_y * mHalfHeight;
  169. float scaled_radius = scale_xz * mRadius;
  170. float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
  171. float xz_sq = Square(x) + Square(z);
  172. float y_sq = Square(y);
  173. // Check which component is bigger
  174. if (xz_sq > y_sq)
  175. {
  176. // Hitting side
  177. float f = -scaled_radius / sqrt(xz_sq);
  178. float vx = x * f;
  179. float vz = z * f;
  180. outVertices.push_back(inCenterOfMassTransform * Vec3(vx, scaled_half_height, vz));
  181. outVertices.push_back(inCenterOfMassTransform * Vec3(vx, -scaled_half_height, vz));
  182. }
  183. else
  184. {
  185. // Hitting top or bottom
  186. // When the inDirection is more than 5 degrees from vertical, align the vertices so that 1 of the vertices
  187. // points towards inDirection in the XZ plane. This ensures that we always have a vertex towards max penetration depth.
  188. Mat44 transform = inCenterOfMassTransform;
  189. if (xz_sq > 0.00765427f * y_sq)
  190. {
  191. Vec4 base_x = Vec4(x, 0, z, 0) / sqrt(xz_sq);
  192. Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);
  193. transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));
  194. }
  195. // Adjust for scale and height
  196. Vec3 multiplier = y < 0.0f? Vec3(scaled_radius, scaled_half_height, scaled_radius) : Vec3(-scaled_radius, -scaled_half_height, scaled_radius);
  197. transform = transform.PreScaled(multiplier);
  198. for (const Vec3 &v : cCylinderTopFace)
  199. outVertices.push_back(transform * v);
  200. }
  201. }
  202. MassProperties CylinderShape::GetMassProperties() const
  203. {
  204. MassProperties p;
  205. // Mass is surface of circle * height
  206. float radius_sq = Square(mRadius);
  207. float height = 2.0f * mHalfHeight;
  208. p.mMass = JPH_PI * radius_sq * height * GetDensity();
  209. // Inertia according to https://en.wikipedia.org/wiki/List_of_moments_of_inertia:
  210. float inertia_y = radius_sq * p.mMass * 0.5f;
  211. float inertia_x = inertia_y * 0.5f + p.mMass * height * height / 12.0f;
  212. float inertia_z = inertia_x;
  213. // Set inertia
  214. p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
  215. return p;
  216. }
  217. Vec3 CylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  218. {
  219. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  220. // Calculate distance to infinite cylinder surface
  221. Vec3 local_surface_position_xz(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ());
  222. float local_surface_position_xz_len = local_surface_position_xz.Length();
  223. float distance_to_curved_surface = abs(local_surface_position_xz_len - mRadius);
  224. // Calculate distance to top or bottom plane
  225. float distance_to_top_or_bottom = abs(abs(inLocalSurfacePosition.GetY()) - mHalfHeight);
  226. // Return normal according to closest surface
  227. if (distance_to_curved_surface < distance_to_top_or_bottom)
  228. return local_surface_position_xz / local_surface_position_xz_len;
  229. else
  230. return inLocalSurfacePosition.GetY() > 0.0f? Vec3::sAxisY() : -Vec3::sAxisY();
  231. }
  232. AABox CylinderShape::GetLocalBounds() const
  233. {
  234. Vec3 extent = Vec3(mRadius, mHalfHeight, mRadius);
  235. return AABox(-extent, extent);
  236. }
  237. #ifdef JPH_DEBUG_RENDERER
  238. void CylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  239. {
  240. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  241. inRenderer->DrawCylinder(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), mHalfHeight, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  242. }
  243. #endif // JPH_DEBUG_RENDERER
  244. bool CylinderShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  245. {
  246. // Test ray against capsule
  247. float fraction = RayCylinder(inRay.mOrigin, inRay.mDirection, mHalfHeight, mRadius);
  248. if (fraction < ioHit.mFraction)
  249. {
  250. ioHit.mFraction = fraction;
  251. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  252. return true;
  253. }
  254. return false;
  255. }
  256. void CylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  257. {
  258. // Test shape filter
  259. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  260. return;
  261. // Check if the point is in the cylinder
  262. if (abs(inPoint.GetY()) <= mHalfHeight // Within the height
  263. && Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mRadius)) // Within the radius
  264. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  265. }
  266. void CylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
  267. {
  268. JPH_ASSERT(IsValidScale(inScale));
  269. Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
  270. // Get scaled cylinder
  271. Vec3 abs_scale = inScale.Abs();
  272. float half_height = abs_scale.GetY() * mHalfHeight;
  273. float radius = abs_scale.GetX() * mRadius;
  274. for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
  275. if (v.GetInvMass() > 0.0f)
  276. {
  277. Vec3 local_pos = inverse_transform * v.GetPosition();
  278. // Calculate penetration into side surface
  279. Vec3 side_normal = local_pos;
  280. side_normal.SetY(0.0f);
  281. float side_normal_length = side_normal.Length();
  282. float side_penetration = radius - side_normal_length;
  283. // Calculate penetration into top or bottom plane
  284. float top_penetration = half_height - abs(local_pos.GetY());
  285. Vec3 point, normal;
  286. if (side_penetration < 0.0f && top_penetration < 0.0f)
  287. {
  288. // We're outside the cylinder height and radius
  289. point = side_normal * (radius / side_normal_length) + Vec3(0, half_height * Sign(local_pos.GetY()), 0);
  290. normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());
  291. }
  292. else if (side_penetration < top_penetration)
  293. {
  294. // Side surface is closest
  295. normal = side_normal_length > 0.0f? side_normal / side_normal_length : Vec3::sAxisX();
  296. point = radius * normal;
  297. }
  298. else
  299. {
  300. // Top or bottom plane is closest
  301. normal = Vec3(0, Sign(local_pos.GetY()), 0);
  302. point = half_height * normal;
  303. }
  304. // Calculate penetration
  305. Plane plane = Plane::sFromPointAndNormal(point, normal);
  306. float penetration = -plane.SignedDistance(local_pos);
  307. if (v.UpdatePenetration(penetration))
  308. v.SetCollision(plane.GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);
  309. }
  310. }
  311. void CylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  312. {
  313. Mat44 unit_cylinder_transform(Vec4(mRadius, 0, 0, 0), Vec4(0, mHalfHeight, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, 0, 0, 1));
  314. new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, unit_cylinder_transform, sUnitCylinderTriangles.data(), sUnitCylinderTriangles.size(), GetMaterial());
  315. }
  316. int CylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  317. {
  318. return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials);
  319. }
  320. void CylinderShape::SaveBinaryState(StreamOut &inStream) const
  321. {
  322. ConvexShape::SaveBinaryState(inStream);
  323. inStream.Write(mHalfHeight);
  324. inStream.Write(mRadius);
  325. inStream.Write(mConvexRadius);
  326. }
  327. void CylinderShape::RestoreBinaryState(StreamIn &inStream)
  328. {
  329. ConvexShape::RestoreBinaryState(inStream);
  330. inStream.Read(mHalfHeight);
  331. inStream.Read(mRadius);
  332. inStream.Read(mConvexRadius);
  333. }
  334. bool CylinderShape::IsValidScale(Vec3Arg inScale) const
  335. {
  336. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScaleXZ(inScale.Abs());
  337. }
  338. Vec3 CylinderShape::MakeScaleValid(Vec3Arg inScale) const
  339. {
  340. Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
  341. return scale.GetSign() * ScaleHelpers::MakeUniformScaleXZ(scale.Abs());
  342. }
  343. void CylinderShape::sRegister()
  344. {
  345. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Cylinder);
  346. f.mConstruct = []() -> Shape * { return new CylinderShape; };
  347. f.mColor = Color::sGreen;
  348. }
  349. JPH_NAMESPACE_END