TaperedCylinderShape.cpp 24 KB

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