TaperedCylinderShape.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/Shape/TaperedCylinderShape.h>
  6. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  7. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Jolt/Physics/Collision/CollidePointResult.h>
  9. #include <Jolt/Physics/Collision/TransformedShape.h>
  10. #include <Jolt/Physics/Collision/CollideSoftBodyVertexIterator.h>
  11. #include <Jolt/ObjectStream/TypeDeclarations.h>
  12. #include <Jolt/Core/StreamIn.h>
  13. #include <Jolt/Core/StreamOut.h>
  14. #ifdef JPH_DEBUG_RENDERER
  15. #include <Jolt/Renderer/DebugRenderer.h>
  16. #endif // JPH_DEBUG_RENDERER
  17. JPH_NAMESPACE_BEGIN
  18. // Approximation of a face of the tapered cylinder
  19. static const Vec3 cTaperedCylinderFace[] =
  20. {
  21. Vec3(0.0f, 0.0f, 1.0f),
  22. Vec3(0.707106769f, 0.0f, 0.707106769f),
  23. Vec3(1.0f, 0.0f, 0.0f),
  24. Vec3(0.707106769f, 0.0f, -0.707106769f),
  25. Vec3(-0.0f, 0.0f, -1.0f),
  26. Vec3(-0.707106769f, 0.0f, -0.707106769f),
  27. Vec3(-1.0f, 0.0f, 0.0f),
  28. Vec3(-0.707106769f, 0.0f, 0.707106769f)
  29. };
  30. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TaperedCylinderShapeSettings)
  31. {
  32. JPH_ADD_BASE_CLASS(TaperedCylinderShapeSettings, ConvexShapeSettings)
  33. JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mHalfHeight)
  34. JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mTopRadius)
  35. JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mBottomRadius)
  36. JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mConvexRadius)
  37. }
  38. ShapeSettings::ShapeResult TaperedCylinderShapeSettings::Create() const
  39. {
  40. if (mCachedResult.IsEmpty())
  41. {
  42. Ref<Shape> shape;
  43. if (mTopRadius == mBottomRadius)
  44. {
  45. // Convert to regular cylinder
  46. CylinderShapeSettings settings;
  47. settings.mHalfHeight = mHalfHeight;
  48. settings.mRadius = mTopRadius;
  49. settings.mMaterial = mMaterial;
  50. settings.mConvexRadius = mConvexRadius;
  51. new CylinderShape(settings, mCachedResult);
  52. }
  53. else
  54. {
  55. // Normal tapered cylinder shape
  56. new TaperedCylinderShape(*this, mCachedResult);
  57. }
  58. }
  59. return mCachedResult;
  60. }
  61. TaperedCylinderShapeSettings::TaperedCylinderShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) :
  62. ConvexShapeSettings(inMaterial),
  63. mHalfHeight(inHalfHeightOfTaperedCylinder),
  64. mTopRadius(inTopRadius),
  65. mBottomRadius(inBottomRadius),
  66. mConvexRadius(inConvexRadius)
  67. {
  68. }
  69. TaperedCylinderShape::TaperedCylinderShape(const TaperedCylinderShapeSettings &inSettings, ShapeResult &outResult) :
  70. ConvexShape(EShapeSubType::TaperedCylinder, inSettings, outResult),
  71. mTopRadius(inSettings.mTopRadius),
  72. mBottomRadius(inSettings.mBottomRadius),
  73. mConvexRadius(inSettings.mConvexRadius)
  74. {
  75. if (mTopRadius < 0.0f)
  76. {
  77. outResult.SetError("Invalid top radius");
  78. return;
  79. }
  80. if (mBottomRadius < 0.0f)
  81. {
  82. outResult.SetError("Invalid bottom radius");
  83. return;
  84. }
  85. if (inSettings.mHalfHeight <= 0.0f)
  86. {
  87. outResult.SetError("Invalid height");
  88. return;
  89. }
  90. if (inSettings.mConvexRadius < 0.0f)
  91. {
  92. outResult.SetError("Invalid convex radius");
  93. return;
  94. }
  95. if (inSettings.mTopRadius < inSettings.mConvexRadius)
  96. {
  97. outResult.SetError("Convex radius must be smaller than convex radius");
  98. return;
  99. }
  100. if (inSettings.mBottomRadius < inSettings.mConvexRadius)
  101. {
  102. outResult.SetError("Convex radius must be smaller than bottom radius");
  103. return;
  104. }
  105. // Calculate the center of mass (using wxMaxima).
  106. // Radius of cross section for tapered cylinder from 0 to h:
  107. // r(x):=br+x*(tr-br)/h;
  108. // Area:
  109. // area(x):=%pi*r(x)^2;
  110. // Total volume of cylinder:
  111. // volume(h):=integrate(area(x),x,0,h);
  112. // Center of mass:
  113. // com(br,tr,h):=integrate(x*area(x),x,0,h)/volume(h);
  114. // Results:
  115. // ratsimp(com(br,tr,h),br,bt);
  116. // Non-tapered cylinder should have com = 0.5:
  117. // ratsimp(com(r,r,h));
  118. // Cone with tip at origin and height h should have com = 3/4 h
  119. // ratsimp(com(0,r,h));
  120. float h = 2.0f * inSettings.mHalfHeight;
  121. float tr = mTopRadius;
  122. float tr2 = Square(tr);
  123. float br = mBottomRadius;
  124. float br2 = Square(br);
  125. float com = h * (3 * tr2 + 2 * br * tr + br2) / (4.0f * (tr2 + br * tr + br2));
  126. mTop = h - com;
  127. mBottom = -com;
  128. outResult.Set(this);
  129. }
  130. class TaperedCylinderShape::TaperedCylinder final : public Support
  131. {
  132. public:
  133. TaperedCylinder(float inTop, float inBottom, float inTopRadius, float inBottomRadius, float inConvexRadius) :
  134. mTop(inTop),
  135. mBottom(inBottom),
  136. mTopRadius(inTopRadius),
  137. mBottomRadius(inBottomRadius),
  138. mConvexRadius(inConvexRadius)
  139. {
  140. static_assert(sizeof(TaperedCylinder) <= sizeof(SupportBuffer), "Buffer size too small");
  141. JPH_ASSERT(IsAligned(this, alignof(TaperedCylinder)));
  142. }
  143. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  144. {
  145. float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
  146. float o = sqrt(Square(x) + Square(z));
  147. if (o > 0.0f)
  148. {
  149. Vec3 top_support((mTopRadius * x) / o, mTop, (mTopRadius * z) / o);
  150. Vec3 bottom_support((mBottomRadius * x) / o, mBottom, (mBottomRadius * z) / o);
  151. return inDirection.Dot(top_support) > inDirection.Dot(bottom_support)? top_support : bottom_support;
  152. }
  153. else
  154. {
  155. if (y > 0.0f)
  156. return Vec3(0, mTop, 0);
  157. else
  158. return Vec3(0, mBottom, 0);
  159. }
  160. }
  161. virtual float GetConvexRadius() const override
  162. {
  163. return mConvexRadius;
  164. }
  165. private:
  166. float mTop;
  167. float mBottom;
  168. float mTopRadius;
  169. float mBottomRadius;
  170. float mConvexRadius;
  171. };
  172. JPH_INLINE void TaperedCylinderShape::GetScaled(Vec3Arg inScale, float &outTop, float &outBottom, float &outTopRadius, float &outBottomRadius, float &outConvexRadius) const
  173. {
  174. Vec3 abs_scale = inScale.Abs();
  175. float scale_xz = abs_scale.GetX();
  176. float scale_y = inScale.GetY();
  177. outTop = scale_y * mTop;
  178. outBottom = scale_y * mBottom;
  179. outTopRadius = scale_xz * mTopRadius;
  180. outBottomRadius = scale_xz * mBottomRadius;
  181. outConvexRadius = min(abs_scale.GetY(), scale_xz) * mConvexRadius;
  182. // Negative Y-scale flips the top and bottom
  183. if (outBottom > outTop)
  184. {
  185. std::swap(outTop, outBottom);
  186. std::swap(outTopRadius, outBottomRadius);
  187. }
  188. }
  189. const ConvexShape::Support *TaperedCylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  190. {
  191. JPH_ASSERT(IsValidScale(inScale));
  192. // Get scaled tapered cylinder
  193. float top, bottom, top_radius, bottom_radius, convex_radius;
  194. GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);
  195. switch (inMode)
  196. {
  197. case ESupportMode::IncludeConvexRadius:
  198. case ESupportMode::Default:
  199. return new (&inBuffer) TaperedCylinder(top, bottom, top_radius, bottom_radius, 0.0f);
  200. case ESupportMode::ExcludeConvexRadius:
  201. return new (&inBuffer) TaperedCylinder(top - convex_radius, bottom + convex_radius, top_radius - convex_radius, bottom_radius - convex_radius, convex_radius);
  202. }
  203. JPH_ASSERT(false);
  204. return nullptr;
  205. }
  206. JPH_INLINE static Vec3 sCalculateSideNormalXZ(Vec3Arg inSurfacePosition)
  207. {
  208. return (Vec3(1, 0, 1) * inSurfacePosition).NormalizedOr(Vec3::sAxisX());
  209. }
  210. JPH_INLINE static Vec3 sCalculateSideNormal(Vec3Arg inNormalXZ, float inTop, float inBottom, float inTopRadius, float inBottomRadius)
  211. {
  212. float tan_alpha = (inBottomRadius - inTopRadius) / (inTop - inBottom);
  213. return Vec3(inNormalXZ.GetX(), tan_alpha, inNormalXZ.GetZ()).Normalized();
  214. }
  215. void TaperedCylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  216. {
  217. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  218. JPH_ASSERT(IsValidScale(inScale));
  219. // Get scaled tapered cylinder
  220. float top, bottom, top_radius, bottom_radius, convex_radius;
  221. GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);
  222. // Get the normal of the side of the cylinder
  223. Vec3 normal_xz = sCalculateSideNormalXZ(-inDirection);
  224. Vec3 normal = sCalculateSideNormal(normal_xz, top, bottom, top_radius, bottom_radius);
  225. constexpr float cMinRadius = 1.0e-3f;
  226. // Check if the normal is closer to the side than to the top or bottom
  227. if (abs(normal.Dot(inDirection)) > abs(inDirection.GetY()))
  228. {
  229. // Return the side of the cylinder
  230. outVertices.push_back(inCenterOfMassTransform * (normal_xz * top_radius + Vec3(0, top, 0)));
  231. outVertices.push_back(inCenterOfMassTransform * (normal_xz * bottom_radius + Vec3(0, bottom, 0)));
  232. }
  233. else
  234. {
  235. // When the inDirection is more than 5 degrees from vertical, align the vertices so that 1 of the vertices
  236. // points towards inDirection in the XZ plane. This ensures that we always have a vertex towards max penetration depth.
  237. Mat44 transform = inCenterOfMassTransform;
  238. Vec4 base_x = Vec4(inDirection.GetX(), 0, inDirection.GetZ(), 0);
  239. float xz_sq = base_x.LengthSq();
  240. float y_sq = Square(inDirection.GetY());
  241. if (xz_sq > 0.00765427f * y_sq)
  242. {
  243. base_x /= sqrt(xz_sq);
  244. Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);
  245. transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));
  246. }
  247. if (inDirection.GetY() < 0.0f)
  248. {
  249. // Top of the cylinder
  250. if (top_radius > cMinRadius)
  251. {
  252. Vec3 top_3d(0, top, 0);
  253. for (Vec3 v : cTaperedCylinderFace)
  254. outVertices.push_back(transform * (top_radius * v + top_3d));
  255. }
  256. }
  257. else
  258. {
  259. // Bottom of the cylinder
  260. if (bottom_radius > cMinRadius)
  261. {
  262. Vec3 bottom_3d(0, bottom, 0);
  263. for (const Vec3 *v = cTaperedCylinderFace + std::size(cTaperedCylinderFace) - 1; v >= cTaperedCylinderFace; --v)
  264. outVertices.push_back(transform * (bottom_radius * *v + bottom_3d));
  265. }
  266. }
  267. }
  268. }
  269. MassProperties TaperedCylinderShape::GetMassProperties() const
  270. {
  271. MassProperties p;
  272. // Calculate mass
  273. float density = GetDensity();
  274. p.mMass = GetVolume() * density;
  275. // Calculate inertia of a tapered cylinder (using wxMaxima)
  276. // Radius:
  277. // r(x):=br+(x-b)*(tr-br)/(t-b);
  278. // Where t=top, b=bottom, tr=top radius, br=bottom radius
  279. // Area of the cross section of the cylinder at x:
  280. // area(x):=%pi*r(x)^2;
  281. // Inertia x slice at x (using inertia of a solid disc, see https://en.wikipedia.org/wiki/List_of_moments_of_inertia, note needs to be multiplied by density):
  282. // dix(x):=area(x)*r(x)^2/4;
  283. // Inertia y slice at y (note needs to be multiplied by density)
  284. // diy(x):=area(x)*r(x)^2/2;
  285. // Volume:
  286. // volume(b,t):=integrate(area(x),x,b,t);
  287. // The constant density (note that we have this through GetDensity() so we'll use that instead):
  288. // density(b,t):=m/volume(b,t);
  289. // Inertia tensor element xx, note that we use the parallel axis theorem to move the inertia: Ixx' = Ixx + m translation^2, also note we multiply by density here:
  290. // Ixx(br,tr,b,t):=integrate(dix(x)+area(x)*x^2,x,b,t)*density(b,t);
  291. // Inertia tensor element yy:
  292. // Iyy(br,tr,b,t):=integrate(diy(x),x,b,t)*density(b,t);
  293. // Note that we can simplify Ixx by using:
  294. // Ixx_delta(br,tr,b,t):=Ixx(br,tr,b,t)-Iyy(br,tr,b,t)/2;
  295. // For a cylinder this formula matches what is listed on the wiki:
  296. // factor(Ixx(r,r,-h/2,h/2));
  297. // factor(Iyy(r,r,-h/2,h/2));
  298. // For a cone with tip at origin too:
  299. // factor(Ixx(0,r,0,h));
  300. // factor(Iyy(0,r,0,h));
  301. // Now for the tapered cylinder:
  302. // rat(Ixx(br,tr,b,t),br,bt);
  303. // rat(Iyy(br,tr,b,t),br,bt);
  304. // rat(Ixx_delta(br,tr,b,t),br,bt);
  305. float t = mTop;
  306. float t2 = Square(t);
  307. float t3 = t * t2;
  308. float b = mBottom;
  309. float b2 = Square(b);
  310. float b3 = b * b2;
  311. float br = mBottomRadius;
  312. float br2 = Square(br);
  313. float br3 = br * br2;
  314. float br4 = Square(br2);
  315. float tr = mTopRadius;
  316. float tr2 = Square(tr);
  317. float tr3 = tr * tr2;
  318. float tr4 = Square(tr2);
  319. float inertia_y = (JPH_PI / 10.0f) * density * (t - b) * (br4 + tr * br3 + tr2 * br2 + tr3 * br + tr4);
  320. float inertia_x_delta = (JPH_PI / 30.0f) * density * ((t3 + 2 * b * t2 + 3 * b2 * t - 6 * b3) * br2 + (3 * t3 + b * t2 - b2 * t - 3 * b3) * tr * br + (6 * t3 - 3 * b * t2 - 2 * b2 * t - b3) * tr2);
  321. float inertia_x = inertia_x_delta + inertia_y / 2;
  322. float inertia_z = inertia_x;
  323. p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
  324. return p;
  325. }
  326. Vec3 TaperedCylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  327. {
  328. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  329. constexpr float cEpsilon = 1.0e-5f;
  330. if (inLocalSurfacePosition.GetY() > mTop - cEpsilon)
  331. return Vec3(0, 1, 0);
  332. else if (inLocalSurfacePosition.GetY() < mBottom + cEpsilon)
  333. return Vec3(0, -1, 0);
  334. else
  335. return sCalculateSideNormal(sCalculateSideNormalXZ(inLocalSurfacePosition), mTop, mBottom, mTopRadius, mBottomRadius);
  336. }
  337. AABox TaperedCylinderShape::GetLocalBounds() const
  338. {
  339. float max_radius = max(mTopRadius, mBottomRadius);
  340. return AABox(Vec3(-max_radius, mBottom, -max_radius), Vec3(max_radius, mTop, max_radius));
  341. }
  342. void TaperedCylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  343. {
  344. // Test shape filter
  345. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  346. return;
  347. // Check if the point is in the tapered cylinder
  348. if (inPoint.GetY() >= mBottom && inPoint.GetY() <= mTop // Within height
  349. && Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mBottomRadius + (inPoint.GetY() - mBottom) * (mTopRadius - mBottomRadius) / (mTop - mBottom))) // Within the radius
  350. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  351. }
  352. void TaperedCylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
  353. {
  354. JPH_ASSERT(IsValidScale(inScale));
  355. Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
  356. // Get scaled tapered cylinder
  357. float top, bottom, top_radius, bottom_radius, convex_radius;
  358. GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);
  359. Vec3 top_3d(0, top, 0);
  360. Vec3 bottom_3d(0, bottom, 0);
  361. for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
  362. if (v.GetInvMass() > 0.0f)
  363. {
  364. Vec3 local_pos = inverse_transform * v.GetPosition();
  365. // Calculate penetration into side surface
  366. Vec3 normal_xz = sCalculateSideNormalXZ(local_pos);
  367. Vec3 side_normal = sCalculateSideNormal(normal_xz, top, bottom, top_radius, bottom_radius);
  368. Vec3 side_support_top = normal_xz * top_radius + top_3d;
  369. float side_penetration = (side_support_top - local_pos).Dot(side_normal);
  370. // Calculate penetration into top and bottom plane
  371. float top_penetration = top - local_pos.GetY();
  372. float bottom_penetration = local_pos.GetY() - bottom;
  373. float min_top_bottom_penetration = min(top_penetration, bottom_penetration);
  374. Vec3 point, normal;
  375. if (side_penetration < 0.0f || min_top_bottom_penetration < 0.0f)
  376. {
  377. // We're outside the cylinder
  378. // Calculate the closest point on the line segment from bottom to top support point:
  379. // closest_point = bottom + fraction * (top - bottom) / |top - bottom|^2
  380. Vec3 side_support_bottom = normal_xz * bottom_radius + bottom_3d;
  381. Vec3 bottom_to_top = side_support_top - side_support_bottom;
  382. float fraction = (local_pos - side_support_bottom).Dot(bottom_to_top);
  383. // Calculate the distance to the axis of the cylinder
  384. float distance_to_axis = normal_xz.Dot(local_pos);
  385. bool inside_top_radius = distance_to_axis <= top_radius;
  386. bool inside_bottom_radius = distance_to_axis <= bottom_radius;
  387. /*
  388. Regions of tapered cylinder (side view):
  389. _ B | |
  390. --_ | A |
  391. t-------+
  392. C / \
  393. / tapered \
  394. _ / cylinder \
  395. --_ / \
  396. b-----------------+
  397. D | E |
  398. | |
  399. t = side_support_top, b = side_support_bottom
  400. Lines between B and C and C and D are at a 90 degree angle to the line between t and b
  401. */
  402. if (fraction >= bottom_to_top.LengthSq() // Region B: Above the line segment
  403. && !inside_top_radius) // Outside the top radius
  404. {
  405. // Top support point is closest
  406. point = side_support_top;
  407. normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());
  408. }
  409. else if (fraction < 0.0f // Region D: Below the line segment
  410. && !inside_bottom_radius) // Outside the bottom radius
  411. {
  412. // Bottom support point is closest
  413. point = side_support_bottom;
  414. normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());
  415. }
  416. else if (top_penetration < 0.0f // Region A: Above the top plane
  417. && inside_top_radius) // Inside the top radius
  418. {
  419. // Top plane is closest
  420. point = top_3d;
  421. normal = Vec3(0, 1, 0);
  422. }
  423. else if (bottom_penetration < 0.0f // Region E: Below the bottom plane
  424. && inside_bottom_radius) // Inside the bottom radius
  425. {
  426. // Bottom plane is closest
  427. point = bottom_3d;
  428. normal = Vec3(0, -1, 0);
  429. }
  430. else // Region C
  431. {
  432. // Side surface is closest
  433. point = side_support_top;
  434. normal = side_normal;
  435. }
  436. }
  437. else if (side_penetration < min_top_bottom_penetration)
  438. {
  439. // Side surface is closest
  440. point = side_support_top;
  441. normal = side_normal;
  442. }
  443. else if (top_penetration < bottom_penetration)
  444. {
  445. // Top plane is closest
  446. point = top_3d;
  447. normal = Vec3(0, 1, 0);
  448. }
  449. else
  450. {
  451. // Bottom plane is closest
  452. point = bottom_3d;
  453. normal = Vec3(0, -1, 0);
  454. }
  455. // Calculate penetration
  456. Plane plane = Plane::sFromPointAndNormal(point, normal);
  457. float penetration = -plane.SignedDistance(local_pos);
  458. if (v.UpdatePenetration(penetration))
  459. v.SetCollision(plane.GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);
  460. }
  461. }
  462. class TaperedCylinderShape::TCSGetTrianglesContext
  463. {
  464. public:
  465. explicit TCSGetTrianglesContext(Mat44Arg inTransform) : mTransform(inTransform) { }
  466. Mat44 mTransform;
  467. uint mProcessed = 0; // Which elements we processed, bit 0 = top, bit 1 = bottom, bit 2 = side
  468. };
  469. void TaperedCylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  470. {
  471. static_assert(sizeof(TCSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  472. JPH_ASSERT(IsAligned(&ioContext, alignof(TCSGetTrianglesContext)));
  473. // Make sure the scale is not inside out
  474. Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? inScale.FlipSign<-1, 1, 1>() : inScale;
  475. // Mark top and bottom processed if their radius is too small
  476. TCSGetTrianglesContext *context = new (&ioContext) TCSGetTrianglesContext(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(scale));
  477. constexpr float cMinRadius = 1.0e-3f;
  478. if (mTopRadius < cMinRadius)
  479. context->mProcessed |= 0b001;
  480. if (mBottomRadius < cMinRadius)
  481. context->mProcessed |= 0b010;
  482. }
  483. int TaperedCylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  484. {
  485. constexpr int cNumVertices = int(std::size(cTaperedCylinderFace));
  486. static_assert(cGetTrianglesMinTrianglesRequested >= 2 * cNumVertices);
  487. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  488. TCSGetTrianglesContext &context = (TCSGetTrianglesContext &)ioContext;
  489. int total_num_triangles = 0;
  490. // Top cap
  491. Vec3 top_3d(0, mTop, 0);
  492. if ((context.mProcessed & 0b001) == 0)
  493. {
  494. Vec3 v0 = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[0]);
  495. Vec3 v1 = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[1]);
  496. for (const Vec3 *v = cTaperedCylinderFace + 2, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)
  497. {
  498. Vec3 v2 = context.mTransform * (top_3d + mTopRadius * *v);
  499. v0.StoreFloat3(outTriangleVertices++);
  500. v1.StoreFloat3(outTriangleVertices++);
  501. v2.StoreFloat3(outTriangleVertices++);
  502. v1 = v2;
  503. }
  504. total_num_triangles = cNumVertices - 2;
  505. context.mProcessed |= 0b001;
  506. }
  507. // Bottom cap
  508. Vec3 bottom_3d(0, mBottom, 0);
  509. if ((context.mProcessed & 0b010) == 0
  510. && total_num_triangles + cNumVertices - 2 < inMaxTrianglesRequested)
  511. {
  512. Vec3 v0 = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[0]);
  513. Vec3 v1 = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[1]);
  514. for (const Vec3 *v = cTaperedCylinderFace + 2, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)
  515. {
  516. Vec3 v2 = context.mTransform * (bottom_3d + mBottomRadius * *v);
  517. v0.StoreFloat3(outTriangleVertices++);
  518. v2.StoreFloat3(outTriangleVertices++);
  519. v1.StoreFloat3(outTriangleVertices++);
  520. v1 = v2;
  521. }
  522. total_num_triangles += cNumVertices - 2;
  523. context.mProcessed |= 0b010;
  524. }
  525. // Side
  526. if ((context.mProcessed & 0b100) == 0
  527. && total_num_triangles + 2 * cNumVertices < inMaxTrianglesRequested)
  528. {
  529. Vec3 v0t = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[cNumVertices - 1]);
  530. Vec3 v0b = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[cNumVertices - 1]);
  531. for (const Vec3 *v = cTaperedCylinderFace, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)
  532. {
  533. Vec3 v1t = context.mTransform * (top_3d + mTopRadius * *v);
  534. v0t.StoreFloat3(outTriangleVertices++);
  535. v0b.StoreFloat3(outTriangleVertices++);
  536. v1t.StoreFloat3(outTriangleVertices++);
  537. Vec3 v1b = context.mTransform * (bottom_3d + mBottomRadius * *v);
  538. v1t.StoreFloat3(outTriangleVertices++);
  539. v0b.StoreFloat3(outTriangleVertices++);
  540. v1b.StoreFloat3(outTriangleVertices++);
  541. v0t = v1t;
  542. v0b = v1b;
  543. }
  544. total_num_triangles += 2 * cNumVertices;
  545. context.mProcessed |= 0b100;
  546. }
  547. // Store materials
  548. if (outMaterials != nullptr)
  549. {
  550. const PhysicsMaterial *material = GetMaterial();
  551. for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
  552. *m = material;
  553. }
  554. return total_num_triangles;
  555. }
  556. #ifdef JPH_DEBUG_RENDERER
  557. void TaperedCylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  558. {
  559. // Preserve flip along y axis but make sure we're not inside out
  560. Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? inScale.FlipSign<-1, 1, 1>() : inScale;
  561. RMat44 world_transform = inCenterOfMassTransform * Mat44::sScale(scale);
  562. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  563. inRenderer->DrawTaperedCylinder(world_transform, mTop, mBottom, mTopRadius, mBottomRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
  564. }
  565. #endif // JPH_DEBUG_RENDERER
  566. void TaperedCylinderShape::SaveBinaryState(StreamOut &inStream) const
  567. {
  568. ConvexShape::SaveBinaryState(inStream);
  569. inStream.Write(mTop);
  570. inStream.Write(mBottom);
  571. inStream.Write(mTopRadius);
  572. inStream.Write(mBottomRadius);
  573. inStream.Write(mConvexRadius);
  574. }
  575. void TaperedCylinderShape::RestoreBinaryState(StreamIn &inStream)
  576. {
  577. ConvexShape::RestoreBinaryState(inStream);
  578. inStream.Read(mTop);
  579. inStream.Read(mBottom);
  580. inStream.Read(mTopRadius);
  581. inStream.Read(mBottomRadius);
  582. inStream.Read(mConvexRadius);
  583. }
  584. float TaperedCylinderShape::GetVolume() const
  585. {
  586. // Volume of a tapered cylinder is: integrate(%pi*(b+x*(t-b)/h)^2,x,0,h) where t is the top radius, b is the bottom radius and h is the height
  587. return (JPH_PI / 3.0f) * (mTop - mBottom) * (Square(mTopRadius) + mTopRadius * mBottomRadius + Square(mBottomRadius));
  588. }
  589. bool TaperedCylinderShape::IsValidScale(Vec3Arg inScale) const
  590. {
  591. return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScaleXZ(inScale.Abs());
  592. }
  593. Vec3 TaperedCylinderShape::MakeScaleValid(Vec3Arg inScale) const
  594. {
  595. Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
  596. return scale.GetSign() * ScaleHelpers::MakeUniformScaleXZ(scale.Abs());
  597. }
  598. void TaperedCylinderShape::sRegister()
  599. {
  600. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::TaperedCylinder);
  601. f.mConstruct = []() -> Shape * { return new TaperedCylinderShape; };
  602. f.mColor = Color::sGreen;
  603. }
  604. JPH_NAMESPACE_END