ConvexHullShape.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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/ConvexHullShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Jolt/Physics/Collision/Shape/PolyhedronSubmergedVolumeCalculator.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/SoftBody/SoftBodyVertex.h>
  13. #include <Jolt/Geometry/ConvexHullBuilder.h>
  14. #include <Jolt/Geometry/ClosestPoint.h>
  15. #include <Jolt/ObjectStream/TypeDeclarations.h>
  16. #include <Jolt/Core/StringTools.h>
  17. #include <Jolt/Core/StreamIn.h>
  18. #include <Jolt/Core/StreamOut.h>
  19. #include <Jolt/Core/UnorderedMap.h>
  20. #include <Jolt/Core/UnorderedSet.h>
  21. JPH_NAMESPACE_BEGIN
  22. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(ConvexHullShapeSettings)
  23. {
  24. JPH_ADD_BASE_CLASS(ConvexHullShapeSettings, ConvexShapeSettings)
  25. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mPoints)
  26. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mMaxConvexRadius)
  27. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mMaxErrorConvexRadius)
  28. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mHullTolerance)
  29. }
  30. ShapeSettings::ShapeResult ConvexHullShapeSettings::Create() const
  31. {
  32. if (mCachedResult.IsEmpty())
  33. Ref<Shape> shape = new ConvexHullShape(*this, mCachedResult);
  34. return mCachedResult;
  35. }
  36. ConvexHullShape::ConvexHullShape(const ConvexHullShapeSettings &inSettings, ShapeResult &outResult) :
  37. ConvexShape(EShapeSubType::ConvexHull, inSettings, outResult),
  38. mConvexRadius(inSettings.mMaxConvexRadius)
  39. {
  40. using BuilderFace = ConvexHullBuilder::Face;
  41. using Edge = ConvexHullBuilder::Edge;
  42. using Faces = Array<BuilderFace *>;
  43. // Check convex radius
  44. if (mConvexRadius < 0.0f)
  45. {
  46. outResult.SetError("Invalid convex radius");
  47. return;
  48. }
  49. // Build convex hull
  50. const char *error = nullptr;
  51. ConvexHullBuilder builder(inSettings.mPoints);
  52. ConvexHullBuilder::EResult result = builder.Initialize(cMaxPointsInHull, inSettings.mHullTolerance, error);
  53. if (result != ConvexHullBuilder::EResult::Success && result != ConvexHullBuilder::EResult::MaxVerticesReached)
  54. {
  55. outResult.SetError(error);
  56. return;
  57. }
  58. const Faces &builder_faces = builder.GetFaces();
  59. // Check the consistency of the resulting hull if we fully built it
  60. if (result == ConvexHullBuilder::EResult::Success)
  61. {
  62. ConvexHullBuilder::Face *max_error_face;
  63. float max_error_distance, coplanar_distance;
  64. int max_error_idx;
  65. builder.DetermineMaxError(max_error_face, max_error_distance, max_error_idx, coplanar_distance);
  66. if (max_error_distance > 4.0f * max(coplanar_distance, inSettings.mHullTolerance)) // Coplanar distance could be bigger than the allowed tolerance if the points are far apart
  67. {
  68. outResult.SetError(StringFormat("Hull building failed, point %d had an error of %g (relative to tolerance: %g)", max_error_idx, (double)max_error_distance, double(max_error_distance / inSettings.mHullTolerance)));
  69. return;
  70. }
  71. }
  72. // Calculate center of mass and volume
  73. builder.GetCenterOfMassAndVolume(mCenterOfMass, mVolume);
  74. // Calculate covariance matrix
  75. // See:
  76. // - Why the inertia tensor is the inertia tensor - Jonathan Blow (http://number-none.com/blow/inertia/deriving_i.html)
  77. // - How to find the inertia tensor (or other mass properties) of a 3D solid body represented by a triangle mesh (Draft) - Jonathan Blow, Atman J Binstock (http://number-none.com/blow/inertia/bb_inertia.doc)
  78. Mat44 covariance_canonical(Vec4(1.0f / 60.0f, 1.0f / 120.0f, 1.0f / 120.0f, 0), Vec4(1.0f / 120.0f, 1.0f / 60.0f, 1.0f / 120.0f, 0), Vec4(1.0f / 120.0f, 1.0f / 120.0f, 1.0f / 60.0f, 0), Vec4(0, 0, 0, 1));
  79. Mat44 covariance_matrix = Mat44::sZero();
  80. for (BuilderFace *f : builder_faces)
  81. {
  82. // Fourth point of the tetrahedron is at the center of mass, we subtract it from the other points so we get a tetrahedron with one vertex at zero
  83. // The first point on the face will be used to form a triangle fan
  84. Edge *e = f->mFirstEdge;
  85. Vec3 v1 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  86. // Get the 2nd point
  87. e = e->mNextEdge;
  88. Vec3 v2 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  89. // Loop over the triangle fan
  90. for (e = e->mNextEdge; e != f->mFirstEdge; e = e->mNextEdge)
  91. {
  92. Vec3 v3 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  93. // Affine transform that transforms a unit tetrahedon (with vertices (0, 0, 0), (1, 0, 0), (0, 1, 0) and (0, 0, 1) to this tetrahedron
  94. Mat44 a(Vec4(v1, 0), Vec4(v2, 0), Vec4(v3, 0), Vec4(0, 0, 0, 1));
  95. // Calculate covariance matrix for this tetrahedron
  96. float det_a = a.GetDeterminant3x3();
  97. Mat44 c = det_a * (a * covariance_canonical * a.Transposed());
  98. // Add it
  99. covariance_matrix += c;
  100. // Prepare for next triangle
  101. v2 = v3;
  102. }
  103. }
  104. // Calculate inertia matrix assuming density is 1, note that element (3, 3) is garbage
  105. mInertia = Mat44::sIdentity() * (covariance_matrix(0, 0) + covariance_matrix(1, 1) + covariance_matrix(2, 2)) - covariance_matrix;
  106. // Convert polygons fron the builder to our internal representation
  107. using VtxMap = UnorderedMap<int, uint8>;
  108. VtxMap vertex_map;
  109. for (BuilderFace *builder_face : builder_faces)
  110. {
  111. // Determine where the vertices go
  112. uint16 first_vertex = (uint16)mVertexIdx.size();
  113. uint16 num_vertices = 0;
  114. // Loop over vertices in face
  115. Edge *edge = builder_face->mFirstEdge;
  116. do
  117. {
  118. // Remap to new index, not all points in the original input set are required to form the hull
  119. uint8 new_idx;
  120. int original_idx = edge->mStartIdx;
  121. VtxMap::iterator m = vertex_map.find(original_idx);
  122. if (m != vertex_map.end())
  123. {
  124. // Found, reuse
  125. new_idx = m->second;
  126. }
  127. else
  128. {
  129. // This is a new point
  130. // Make relative to center of mass
  131. Vec3 p = inSettings.mPoints[original_idx] - mCenterOfMass;
  132. // Update local bounds
  133. mLocalBounds.Encapsulate(p);
  134. // Add to point list
  135. JPH_ASSERT(mPoints.size() <= 0xff);
  136. new_idx = (uint8)mPoints.size();
  137. mPoints.push_back({ p });
  138. vertex_map[original_idx] = new_idx;
  139. }
  140. // Append to vertex list
  141. JPH_ASSERT(mVertexIdx.size() < 0xffff);
  142. mVertexIdx.push_back(new_idx);
  143. num_vertices++;
  144. edge = edge->mNextEdge;
  145. } while (edge != builder_face->mFirstEdge);
  146. // Add face
  147. mFaces.push_back({ first_vertex, num_vertices });
  148. // Add plane
  149. Plane plane = Plane::sFromPointAndNormal(builder_face->mCentroid - mCenterOfMass, builder_face->mNormal.Normalized());
  150. mPlanes.push_back(plane);
  151. }
  152. // Test if GetSupportFunction can support this many points
  153. if (mPoints.size() > cMaxPointsInHull)
  154. {
  155. outResult.SetError(StringFormat("Internal error: Too many points in hull (%d), max allowed %d", mPoints.size(), cMaxPointsInHull));
  156. return;
  157. }
  158. for (int p = 0; p < (int)mPoints.size(); ++p)
  159. {
  160. // For each point, find faces that use the point
  161. Array<int> faces;
  162. for (int f = 0; f < (int)mFaces.size(); ++f)
  163. {
  164. const Face &face = mFaces[f];
  165. for (int v = 0; v < face.mNumVertices; ++v)
  166. if (mVertexIdx[face.mFirstVertex + v] == p)
  167. {
  168. faces.push_back(f);
  169. break;
  170. }
  171. }
  172. if (faces.size() < 2)
  173. {
  174. outResult.SetError("A point must be connected to 2 or more faces!");
  175. return;
  176. }
  177. if (faces.size() > 1)
  178. {
  179. // Find the 3 normals that form the largest tetrahedron
  180. // The largest tetrahedron we can get is ((1, 0, 0) x (0, 1, 0)) . (0, 0, 1) = 1, if the volume is only 5% of that,
  181. // the three vectors are too coplanar and we fall back to using only 2 plane normals
  182. float biggest_volume = 0.05f;
  183. int best3[3] = { -1, -1, -1 };
  184. // When using 2 normals, we get the two with the biggest angle between them with a minimal difference of 1 degree
  185. // otherwise we fall back to just using 1 plane normal
  186. float smallest_dot = Cos(DegreesToRadians(1.0f));
  187. int best2[2] = { -1, -1 };
  188. for (int face1 = 0; face1 < (int)faces.size(); ++face1)
  189. {
  190. Vec3 normal1 = mPlanes[faces[face1]].GetNormal();
  191. for (int face2 = face1 + 1; face2 < (int)faces.size(); ++face2)
  192. {
  193. Vec3 normal2 = mPlanes[faces[face2]].GetNormal();
  194. Vec3 cross = normal1.Cross(normal2);
  195. // Determine the 2 face normals that are most apart
  196. float dot = normal1.Dot(normal2);
  197. if (dot < smallest_dot)
  198. {
  199. smallest_dot = dot;
  200. best2[0] = faces[face1];
  201. best2[1] = faces[face2];
  202. }
  203. // Determine the 3 face normals that form the largest tetrahedron
  204. for (int face3 = face2 + 1; face3 < (int)faces.size(); ++face3)
  205. {
  206. Vec3 normal3 = mPlanes[faces[face3]].GetNormal();
  207. float volume = abs(cross.Dot(normal3));
  208. if (volume > biggest_volume)
  209. {
  210. biggest_volume = volume;
  211. best3[0] = faces[face1];
  212. best3[1] = faces[face2];
  213. best3[2] = faces[face3];
  214. }
  215. }
  216. }
  217. }
  218. // If we didn't find 3 planes, use 2, if we didn't find 2 use 1
  219. if (best3[0] != -1)
  220. faces = { best3[0], best3[1], best3[2] };
  221. else if (best2[0] != -1)
  222. faces = { best2[0], best2[1] };
  223. else
  224. faces = { faces[0] };
  225. }
  226. // Copy the faces to the points buffer
  227. Point &point = mPoints[p];
  228. point.mNumFaces = (int)faces.size();
  229. for (int i = 0; i < (int)faces.size(); ++i)
  230. point.mFaces[i] = faces[i];
  231. }
  232. // If the convex radius is already zero, there's no point in further reducing it
  233. if (mConvexRadius > 0.0f)
  234. {
  235. // Find out how thin the hull is by walking over all planes and checking the thickness of the hull in that direction
  236. float min_size = FLT_MAX;
  237. for (const Plane &plane : mPlanes)
  238. {
  239. // Take the point that is furthest away from the plane as thickness of this hull
  240. float max_dist = 0.0f;
  241. for (const Point &point : mPoints)
  242. {
  243. float dist = -plane.SignedDistance(point.mPosition); // Point is always behind plane, so we need to negate
  244. if (dist > max_dist)
  245. max_dist = dist;
  246. }
  247. min_size = min(min_size, max_dist);
  248. }
  249. // We need to fit in 2x the convex radius in min_size, so reduce the convex radius if it's bigger than that
  250. mConvexRadius = min(mConvexRadius, 0.5f * min_size);
  251. }
  252. // Now walk over all points and see if we have to further reduce the convex radius because of sharp edges
  253. if (mConvexRadius > 0.0f)
  254. {
  255. for (const Point &point : mPoints)
  256. if (point.mNumFaces != 1) // If we have a single face, shifting back is easy and we don't need to reduce the convex radius
  257. {
  258. // Get first two planes
  259. Plane p1 = mPlanes[point.mFaces[0]];
  260. Plane p2 = mPlanes[point.mFaces[1]];
  261. Plane p3;
  262. Vec3 offset_mask;
  263. if (point.mNumFaces == 3)
  264. {
  265. // Get third plane
  266. p3 = mPlanes[point.mFaces[2]];
  267. // All 3 planes will be offset by the convex radius
  268. offset_mask = Vec3::sReplicate(1);
  269. }
  270. else
  271. {
  272. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  273. JPH_ASSERT(point.mNumFaces == 2);
  274. p3 = Plane::sFromPointAndNormal(point.mPosition, p1.GetNormal().Cross(p2.GetNormal()));
  275. // Only the first and 2nd plane will be offset, the 3rd plane is only there to guide the intersection point
  276. offset_mask = Vec3(1, 1, 0);
  277. }
  278. // Plane equation: point . normal + constant = 0
  279. // Offsetting the plane backwards with convex radius r: point . normal + constant + r = 0
  280. // To find the intersection 'point' of 3 planes we solve:
  281. // |n1x n1y n1z| |x| | r + c1 |
  282. // |n2x n2y n2z| |y| = - | r + c2 | <=> n point = -r (1, 1, 1) - (c1, c2, c3)
  283. // |n3x n3y n3z| |z| | r + c3 |
  284. // Where point = (x, y, z), n1x is the x component of the first plane, c1 = plane constant of plane 1, etc.
  285. // The relation between how much the interesection point shifts as a function of r is: -r * n^-1 (1, 1, 1) = r * offset
  286. // Where offset = -n^-1 (1, 1, 1) or -n^-1 (1, 1, 0) in case only the first 2 planes are offset
  287. // The error that is introduced by a convex radius r is: error = r * |offset| - r
  288. // So the max convex radius given error is: r = error / (|offset| - 1)
  289. Mat44 n = Mat44(Vec4(p1.GetNormal(), 0), Vec4(p2.GetNormal(), 0), Vec4(p3.GetNormal(), 0), Vec4(0, 0, 0, 1)).Transposed();
  290. float det_n = n.GetDeterminant3x3();
  291. if (det_n == 0.0f)
  292. {
  293. // If the determinant is zero, the matrix is not invertible so no solution exists to move the point backwards and we have to choose a convex radius of zero
  294. mConvexRadius = 0.0f;
  295. break;
  296. }
  297. Mat44 adj_n = n.Adjointed3x3();
  298. float offset = ((adj_n * offset_mask) / det_n).Length();
  299. JPH_ASSERT(offset > 1.0f);
  300. float max_convex_radius = inSettings.mMaxErrorConvexRadius / (offset - 1.0f);
  301. mConvexRadius = min(mConvexRadius, max_convex_radius);
  302. }
  303. }
  304. // Calculate the inner radius by getting the minimum distance from the origin to the planes of the hull
  305. mInnerRadius = FLT_MAX;
  306. for (const Plane &p : mPlanes)
  307. mInnerRadius = min(mInnerRadius, -p.GetConstant());
  308. mInnerRadius = max(0.0f, mInnerRadius); // Clamp against zero, this should do nothing as the shape is centered around the center of mass but for flat convex hulls there may be numerical round off issues
  309. outResult.Set(this);
  310. }
  311. MassProperties ConvexHullShape::GetMassProperties() const
  312. {
  313. MassProperties p;
  314. float density = GetDensity();
  315. // Calculate mass
  316. p.mMass = density * mVolume;
  317. // Calculate inertia matrix
  318. p.mInertia = density * mInertia;
  319. p.mInertia(3, 3) = 1.0f;
  320. return p;
  321. }
  322. Vec3 ConvexHullShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  323. {
  324. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  325. const Plane &first_plane = mPlanes[0];
  326. Vec3 best_normal = first_plane.GetNormal();
  327. float best_dist = abs(first_plane.SignedDistance(inLocalSurfacePosition));
  328. // Find the face that has the shortest distance to the surface point
  329. for (Array<Face>::size_type i = 1; i < mFaces.size(); ++i)
  330. {
  331. const Plane &plane = mPlanes[i];
  332. Vec3 plane_normal = plane.GetNormal();
  333. float dist = abs(plane.SignedDistance(inLocalSurfacePosition));
  334. if (dist < best_dist)
  335. {
  336. best_dist = dist;
  337. best_normal = plane_normal;
  338. }
  339. }
  340. return best_normal;
  341. }
  342. class ConvexHullShape::HullNoConvex final : public Support
  343. {
  344. public:
  345. explicit HullNoConvex(float inConvexRadius) :
  346. mConvexRadius(inConvexRadius)
  347. {
  348. static_assert(sizeof(HullNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  349. JPH_ASSERT(IsAligned(this, alignof(HullNoConvex)));
  350. }
  351. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  352. {
  353. // Find the point with the highest projection on inDirection
  354. float best_dot = -FLT_MAX;
  355. Vec3 best_point = Vec3::sZero();
  356. for (Vec3 point : mPoints)
  357. {
  358. // Check if its support is bigger than the current max
  359. float dot = point.Dot(inDirection);
  360. if (dot > best_dot)
  361. {
  362. best_dot = dot;
  363. best_point = point;
  364. }
  365. }
  366. return best_point;
  367. }
  368. virtual float GetConvexRadius() const override
  369. {
  370. return mConvexRadius;
  371. }
  372. using PointsArray = StaticArray<Vec3, cMaxPointsInHull>;
  373. inline PointsArray & GetPoints()
  374. {
  375. return mPoints;
  376. }
  377. const PointsArray & GetPoints() const
  378. {
  379. return mPoints;
  380. }
  381. private:
  382. float mConvexRadius;
  383. PointsArray mPoints;
  384. };
  385. class ConvexHullShape::HullWithConvex final : public Support
  386. {
  387. public:
  388. explicit HullWithConvex(const ConvexHullShape *inShape) :
  389. mShape(inShape)
  390. {
  391. static_assert(sizeof(HullWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  392. JPH_ASSERT(IsAligned(this, alignof(HullWithConvex)));
  393. }
  394. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  395. {
  396. // Find the point with the highest projection on inDirection
  397. float best_dot = -FLT_MAX;
  398. Vec3 best_point = Vec3::sZero();
  399. for (const Point &point : mShape->mPoints)
  400. {
  401. // Check if its support is bigger than the current max
  402. float dot = point.mPosition.Dot(inDirection);
  403. if (dot > best_dot)
  404. {
  405. best_dot = dot;
  406. best_point = point.mPosition;
  407. }
  408. }
  409. return best_point;
  410. }
  411. virtual float GetConvexRadius() const override
  412. {
  413. return 0.0f;
  414. }
  415. private:
  416. const ConvexHullShape * mShape;
  417. };
  418. class ConvexHullShape::HullWithConvexScaled final : public Support
  419. {
  420. public:
  421. HullWithConvexScaled(const ConvexHullShape *inShape, Vec3Arg inScale) :
  422. mShape(inShape),
  423. mScale(inScale)
  424. {
  425. static_assert(sizeof(HullWithConvexScaled) <= sizeof(SupportBuffer), "Buffer size too small");
  426. JPH_ASSERT(IsAligned(this, alignof(HullWithConvexScaled)));
  427. }
  428. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  429. {
  430. // Find the point with the highest projection on inDirection
  431. float best_dot = -FLT_MAX;
  432. Vec3 best_point = Vec3::sZero();
  433. for (const Point &point : mShape->mPoints)
  434. {
  435. // Calculate scaled position
  436. Vec3 pos = mScale * point.mPosition;
  437. // Check if its support is bigger than the current max
  438. float dot = pos.Dot(inDirection);
  439. if (dot > best_dot)
  440. {
  441. best_dot = dot;
  442. best_point = pos;
  443. }
  444. }
  445. return best_point;
  446. }
  447. virtual float GetConvexRadius() const override
  448. {
  449. return 0.0f;
  450. }
  451. private:
  452. const ConvexHullShape * mShape;
  453. Vec3 mScale;
  454. };
  455. const ConvexShape::Support *ConvexHullShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  456. {
  457. // If there's no convex radius, we don't need to shrink the hull
  458. if (mConvexRadius == 0.0f)
  459. {
  460. if (ScaleHelpers::IsNotScaled(inScale))
  461. return new (&inBuffer) HullWithConvex(this);
  462. else
  463. return new (&inBuffer) HullWithConvexScaled(this, inScale);
  464. }
  465. switch (inMode)
  466. {
  467. case ESupportMode::IncludeConvexRadius:
  468. if (ScaleHelpers::IsNotScaled(inScale))
  469. return new (&inBuffer) HullWithConvex(this);
  470. else
  471. return new (&inBuffer) HullWithConvexScaled(this, inScale);
  472. case ESupportMode::ExcludeConvexRadius:
  473. if (ScaleHelpers::IsNotScaled(inScale))
  474. {
  475. // Create support function
  476. HullNoConvex *hull = new (&inBuffer) HullNoConvex(mConvexRadius);
  477. HullNoConvex::PointsArray &transformed_points = hull->GetPoints();
  478. JPH_ASSERT(mPoints.size() <= cMaxPointsInHull, "Not enough space, this should have been caught during shape creation!");
  479. for (const Point &point : mPoints)
  480. {
  481. Vec3 new_point;
  482. if (point.mNumFaces == 1)
  483. {
  484. // Simply shift back by the convex radius using our 1 plane
  485. new_point = point.mPosition - mPlanes[point.mFaces[0]].GetNormal() * mConvexRadius;
  486. }
  487. else
  488. {
  489. // Get first two planes and offset inwards by convex radius
  490. Plane p1 = mPlanes[point.mFaces[0]].Offset(-mConvexRadius);
  491. Plane p2 = mPlanes[point.mFaces[1]].Offset(-mConvexRadius);
  492. Plane p3;
  493. if (point.mNumFaces == 3)
  494. {
  495. // Get third plane and offset inwards by convex radius
  496. p3 = mPlanes[point.mFaces[2]].Offset(-mConvexRadius);
  497. }
  498. else
  499. {
  500. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  501. JPH_ASSERT(point.mNumFaces == 2);
  502. p3 = Plane::sFromPointAndNormal(point.mPosition, p1.GetNormal().Cross(p2.GetNormal()));
  503. }
  504. // Find intersection point between the three planes
  505. if (!Plane::sIntersectPlanes(p1, p2, p3, new_point))
  506. {
  507. // Fallback: Just push point back using the first plane
  508. new_point = point.mPosition - p1.GetNormal() * mConvexRadius;
  509. }
  510. }
  511. // Add point
  512. transformed_points.push_back(new_point);
  513. }
  514. return hull;
  515. }
  516. else
  517. {
  518. // Calculate scaled convex radius
  519. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  520. // Create new support function
  521. HullNoConvex *hull = new (&inBuffer) HullNoConvex(convex_radius);
  522. HullNoConvex::PointsArray &transformed_points = hull->GetPoints();
  523. JPH_ASSERT(mPoints.size() <= cMaxPointsInHull, "Not enough space, this should have been caught during shape creation!");
  524. // Precalculate inverse scale
  525. Vec3 inv_scale = inScale.Reciprocal();
  526. for (const Point &point : mPoints)
  527. {
  528. // Calculate scaled position
  529. Vec3 pos = inScale * point.mPosition;
  530. // Transform normals for plane 1 with scale
  531. Vec3 n1 = (inv_scale * mPlanes[point.mFaces[0]].GetNormal()).Normalized();
  532. Vec3 new_point;
  533. if (point.mNumFaces == 1)
  534. {
  535. // Simply shift back by the convex radius using our 1 plane
  536. new_point = pos - n1 * convex_radius;
  537. }
  538. else
  539. {
  540. // Transform normals for plane 2 with scale
  541. Vec3 n2 = (inv_scale * mPlanes[point.mFaces[1]].GetNormal()).Normalized();
  542. // Get first two planes and offset inwards by convex radius
  543. Plane p1 = Plane::sFromPointAndNormal(pos, n1).Offset(-convex_radius);
  544. Plane p2 = Plane::sFromPointAndNormal(pos, n2).Offset(-convex_radius);
  545. Plane p3;
  546. if (point.mNumFaces == 3)
  547. {
  548. // Transform last normal with scale
  549. Vec3 n3 = (inv_scale * mPlanes[point.mFaces[2]].GetNormal()).Normalized();
  550. // Get third plane and offset inwards by convex radius
  551. p3 = Plane::sFromPointAndNormal(pos, n3).Offset(-convex_radius);
  552. }
  553. else
  554. {
  555. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  556. JPH_ASSERT(point.mNumFaces == 2);
  557. p3 = Plane::sFromPointAndNormal(pos, n1.Cross(n2));
  558. }
  559. // Find intersection point between the three planes
  560. if (!Plane::sIntersectPlanes(p1, p2, p3, new_point))
  561. {
  562. // Fallback: Just push point back using the first plane
  563. new_point = pos - n1 * convex_radius;
  564. }
  565. }
  566. // Add point
  567. transformed_points.push_back(new_point);
  568. }
  569. return hull;
  570. }
  571. }
  572. JPH_ASSERT(false);
  573. return nullptr;
  574. }
  575. void ConvexHullShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  576. {
  577. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  578. Vec3 inv_scale = inScale.Reciprocal();
  579. // Need to transform the plane normals using inScale
  580. // Transforming a direction with matrix M is done through multiplying by (M^-1)^T
  581. // In this case M is a diagonal matrix with the scale vector, so we need to multiply our normal by 1 / scale and renormalize afterwards
  582. Vec3 plane0_normal = inv_scale * mPlanes[0].GetNormal();
  583. float best_dot = plane0_normal.Dot(inDirection) / plane0_normal.Length();
  584. int best_face_idx = 0;
  585. for (Array<Plane>::size_type i = 1; i < mPlanes.size(); ++i)
  586. {
  587. Vec3 plane_normal = inv_scale * mPlanes[i].GetNormal();
  588. float dot = plane_normal.Dot(inDirection) / plane_normal.Length();
  589. if (dot < best_dot)
  590. {
  591. best_dot = dot;
  592. best_face_idx = (int)i;
  593. }
  594. }
  595. // Get vertices
  596. const Face &best_face = mFaces[best_face_idx];
  597. const uint8 *first_vtx = mVertexIdx.data() + best_face.mFirstVertex;
  598. const uint8 *end_vtx = first_vtx + best_face.mNumVertices;
  599. // If we have more than 1/2 the capacity of outVertices worth of vertices, we start skipping vertices (note we can't fill the buffer completely since extra edges will be generated by clipping).
  600. // TODO: This really needs a better algorithm to determine which vertices are important!
  601. int max_vertices_to_return = outVertices.capacity() / 2;
  602. int delta_vtx = (int(best_face.mNumVertices) + max_vertices_to_return) / max_vertices_to_return;
  603. // Calculate transform with scale
  604. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  605. if (ScaleHelpers::IsInsideOut(inScale))
  606. {
  607. // Flip winding of supporting face
  608. for (const uint8 *v = end_vtx - 1; v >= first_vtx; v -= delta_vtx)
  609. outVertices.push_back(transform * mPoints[*v].mPosition);
  610. }
  611. else
  612. {
  613. // Normal winding of supporting face
  614. for (const uint8 *v = first_vtx; v < end_vtx; v += delta_vtx)
  615. outVertices.push_back(transform * mPoints[*v].mPosition);
  616. }
  617. }
  618. void ConvexHullShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  619. {
  620. // Trivially calculate total volume
  621. Vec3 abs_scale = inScale.Abs();
  622. outTotalVolume = mVolume * abs_scale.GetX() * abs_scale.GetY() * abs_scale.GetZ();
  623. // Check if shape has been scaled inside out
  624. bool is_inside_out = ScaleHelpers::IsInsideOut(inScale);
  625. // Convert the points to world space and determine the distance to the surface
  626. int num_points = int(mPoints.size());
  627. PolyhedronSubmergedVolumeCalculator::Point *buffer = (PolyhedronSubmergedVolumeCalculator::Point *)JPH_STACK_ALLOC(num_points * sizeof(PolyhedronSubmergedVolumeCalculator::Point));
  628. PolyhedronSubmergedVolumeCalculator submerged_vol_calc(inCenterOfMassTransform * Mat44::sScale(inScale), &mPoints[0].mPosition, sizeof(Point), num_points, inSurface, buffer JPH_IF_DEBUG_RENDERER(, inBaseOffset));
  629. if (submerged_vol_calc.AreAllAbove())
  630. {
  631. // We're above the water
  632. outSubmergedVolume = 0.0f;
  633. outCenterOfBuoyancy = Vec3::sZero();
  634. }
  635. else if (submerged_vol_calc.AreAllBelow())
  636. {
  637. // We're fully submerged
  638. outSubmergedVolume = outTotalVolume;
  639. outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation();
  640. }
  641. else
  642. {
  643. // Calculate submerged volume
  644. int reference_point_idx = submerged_vol_calc.GetReferencePointIdx();
  645. for (const Face &f : mFaces)
  646. {
  647. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  648. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  649. // If any of the vertices of this face are the reference point, the volume will be zero so we can skip this face
  650. bool degenerate = false;
  651. for (const uint8 *v = first_vtx; v < end_vtx; ++v)
  652. if (*v == reference_point_idx)
  653. {
  654. degenerate = true;
  655. break;
  656. }
  657. if (degenerate)
  658. continue;
  659. // Triangulate the face
  660. int i1 = *first_vtx;
  661. if (is_inside_out)
  662. {
  663. // Reverse winding
  664. for (const uint8 *v = first_vtx + 2; v < end_vtx; ++v)
  665. {
  666. int i2 = *(v - 1);
  667. int i3 = *v;
  668. submerged_vol_calc.AddFace(i1, i3, i2);
  669. }
  670. }
  671. else
  672. {
  673. // Normal winding
  674. for (const uint8 *v = first_vtx + 2; v < end_vtx; ++v)
  675. {
  676. int i2 = *(v - 1);
  677. int i3 = *v;
  678. submerged_vol_calc.AddFace(i1, i2, i3);
  679. }
  680. }
  681. }
  682. // Get the results
  683. submerged_vol_calc.GetResult(outSubmergedVolume, outCenterOfBuoyancy);
  684. }
  685. #ifdef JPH_DEBUG_RENDERER
  686. // Draw center of buoyancy
  687. if (sDrawSubmergedVolumes)
  688. DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  689. #endif // JPH_DEBUG_RENDERER
  690. }
  691. #ifdef JPH_DEBUG_RENDERER
  692. void ConvexHullShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  693. {
  694. if (mGeometry == nullptr)
  695. {
  696. Array<DebugRenderer::Triangle> triangles;
  697. for (const Face &f : mFaces)
  698. {
  699. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  700. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  701. // Draw first triangle of polygon
  702. Vec3 v0 = mPoints[first_vtx[0]].mPosition;
  703. Vec3 v1 = mPoints[first_vtx[1]].mPosition;
  704. Vec3 v2 = mPoints[first_vtx[2]].mPosition;
  705. Vec3 uv_direction = (v1 - v0).Normalized();
  706. triangles.push_back({ v0, v1, v2, Color::sWhite, v0, uv_direction });
  707. // Draw any other triangles in this polygon
  708. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  709. triangles.push_back({ v0, mPoints[*(v - 1)].mPosition, mPoints[*v].mPosition, Color::sWhite, v0, uv_direction });
  710. }
  711. mGeometry = new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), GetLocalBounds());
  712. }
  713. // Test if the shape is scaled inside out
  714. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  715. // Determine the draw mode
  716. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  717. // Draw the geometry
  718. Color color = inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor;
  719. RMat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  720. inRenderer->DrawGeometry(transform, color, mGeometry, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  721. // Draw the outline if requested
  722. if (sDrawFaceOutlines)
  723. for (const Face &f : mFaces)
  724. {
  725. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  726. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  727. // Draw edges of face
  728. inRenderer->DrawLine(transform * mPoints[*(end_vtx - 1)].mPosition, transform * mPoints[*first_vtx].mPosition, Color::sGrey);
  729. for (const uint8 *v = first_vtx + 1; v < end_vtx; ++v)
  730. inRenderer->DrawLine(transform * mPoints[*(v - 1)].mPosition, transform * mPoints[*v].mPosition, Color::sGrey);
  731. }
  732. }
  733. void ConvexHullShape::DrawShrunkShape(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  734. {
  735. // Get the shrunk points
  736. SupportBuffer buffer;
  737. const HullNoConvex *support = mConvexRadius > 0.0f? static_cast<const HullNoConvex *>(GetSupportFunction(ESupportMode::ExcludeConvexRadius, buffer, inScale)) : nullptr;
  738. RMat44 transform = inCenterOfMassTransform * Mat44::sScale(inScale);
  739. for (int p = 0; p < (int)mPoints.size(); ++p)
  740. {
  741. const Point &point = mPoints[p];
  742. RVec3 position = transform * point.mPosition;
  743. RVec3 shrunk_point = support != nullptr? transform * support->GetPoints()[p] : position;
  744. // Draw difference between shrunk position and position
  745. inRenderer->DrawLine(position, shrunk_point, Color::sGreen);
  746. // Draw face normals that are contributing
  747. for (int i = 0; i < point.mNumFaces; ++i)
  748. inRenderer->DrawLine(position, position + 0.1f * mPlanes[point.mFaces[i]].GetNormal(), Color::sYellow);
  749. // Draw point index
  750. inRenderer->DrawText3D(position, ConvertToString(p), Color::sWhite, 0.1f);
  751. }
  752. }
  753. #endif // JPH_DEBUG_RENDERER
  754. bool ConvexHullShape::CastRayHelper(const RayCast &inRay, float &outMinFraction, float &outMaxFraction) const
  755. {
  756. if (mFaces.size() == 2)
  757. {
  758. // If we have only 2 faces, we're a flat convex hull and we need to test edges instead of planes
  759. // Check if plane is parallel to ray
  760. const Plane &p = mPlanes.front();
  761. Vec3 plane_normal = p.GetNormal();
  762. float direction_projection = inRay.mDirection.Dot(plane_normal);
  763. if (abs(direction_projection) >= 1.0e-12f)
  764. {
  765. // Calculate intersection point
  766. float distance_to_plane = inRay.mOrigin.Dot(plane_normal) + p.GetConstant();
  767. float fraction = -distance_to_plane / direction_projection;
  768. if (fraction < 0.0f || fraction > 1.0f)
  769. {
  770. // Does not hit plane, no hit
  771. outMinFraction = 0.0f;
  772. outMaxFraction = 1.0f + FLT_EPSILON;
  773. return false;
  774. }
  775. Vec3 intersection_point = inRay.mOrigin + fraction * inRay.mDirection;
  776. // Test all edges to see if point is inside polygon
  777. const Face &f = mFaces.front();
  778. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  779. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  780. Vec3 p1 = mPoints[*end_vtx].mPosition;
  781. for (const uint8 *v = first_vtx; v < end_vtx; ++v)
  782. {
  783. Vec3 p2 = mPoints[*v].mPosition;
  784. if ((p2 - p1).Cross(intersection_point - p1).Dot(plane_normal) < 0.0f)
  785. {
  786. // Outside polygon, no hit
  787. outMinFraction = 0.0f;
  788. outMaxFraction = 1.0f + FLT_EPSILON;
  789. return false;
  790. }
  791. p1 = p2;
  792. }
  793. // Inside polygon, a hit
  794. outMinFraction = fraction;
  795. outMaxFraction = fraction;
  796. return true;
  797. }
  798. else
  799. {
  800. // Parallel ray doesn't hit
  801. outMinFraction = 0.0f;
  802. outMaxFraction = 1.0f + FLT_EPSILON;
  803. return false;
  804. }
  805. }
  806. else
  807. {
  808. // Clip ray against all planes
  809. int fractions_set = 0;
  810. bool all_inside = true;
  811. float min_fraction = 0.0f, max_fraction = 1.0f + FLT_EPSILON;
  812. for (const Plane &p : mPlanes)
  813. {
  814. // Check if the ray origin is behind this plane
  815. Vec3 plane_normal = p.GetNormal();
  816. float distance_to_plane = inRay.mOrigin.Dot(plane_normal) + p.GetConstant();
  817. bool is_outside = distance_to_plane > 0.0f;
  818. all_inside &= !is_outside;
  819. // Check if plane is parallel to ray
  820. float direction_projection = inRay.mDirection.Dot(plane_normal);
  821. if (abs(direction_projection) >= 1.0e-12f)
  822. {
  823. // Get intersection fraction between ray and plane
  824. float fraction = -distance_to_plane / direction_projection;
  825. // Update interval of ray that is inside the hull
  826. if (direction_projection < 0.0f)
  827. {
  828. min_fraction = max(fraction, min_fraction);
  829. fractions_set |= 1;
  830. }
  831. else
  832. {
  833. max_fraction = min(fraction, max_fraction);
  834. fractions_set |= 2;
  835. }
  836. }
  837. else if (is_outside)
  838. return false; // Outside the plane and parallel, no hit!
  839. }
  840. // Test if both min and max have been set
  841. if (fractions_set == 3)
  842. {
  843. // Output fractions
  844. outMinFraction = min_fraction;
  845. outMaxFraction = max_fraction;
  846. // Test if the infinite ray intersects with the hull (the length will be checked later)
  847. return min_fraction <= max_fraction && max_fraction >= 0.0f;
  848. }
  849. else
  850. {
  851. // Degenerate case, either the ray is parallel to all planes or the ray has zero length
  852. outMinFraction = 0.0f;
  853. outMaxFraction = 1.0f + FLT_EPSILON;
  854. // Return if the origin is inside the hull
  855. return all_inside;
  856. }
  857. }
  858. }
  859. bool ConvexHullShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  860. {
  861. // Determine if ray hits the shape
  862. float min_fraction, max_fraction;
  863. if (CastRayHelper(inRay, min_fraction, max_fraction)
  864. && min_fraction < ioHit.mFraction) // Check if this is a closer hit
  865. {
  866. // Better hit than the current hit
  867. ioHit.mFraction = min_fraction;
  868. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  869. return true;
  870. }
  871. return false;
  872. }
  873. void ConvexHullShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  874. {
  875. // Test shape filter
  876. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  877. return;
  878. // Determine if ray hits the shape
  879. float min_fraction, max_fraction;
  880. if (CastRayHelper(inRay, min_fraction, max_fraction)
  881. && min_fraction < ioCollector.GetEarlyOutFraction()) // Check if this is closer than the early out fraction
  882. {
  883. // Better hit than the current hit
  884. RayCastResult hit;
  885. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  886. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  887. // Check front side hit
  888. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  889. {
  890. hit.mFraction = min_fraction;
  891. ioCollector.AddHit(hit);
  892. }
  893. // Check back side hit
  894. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  895. && max_fraction < ioCollector.GetEarlyOutFraction())
  896. {
  897. hit.mFraction = max_fraction;
  898. ioCollector.AddHit(hit);
  899. }
  900. }
  901. }
  902. void ConvexHullShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  903. {
  904. // Test shape filter
  905. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  906. return;
  907. // Check if point is behind all planes
  908. for (const Plane &p : mPlanes)
  909. if (p.SignedDistance(inPoint) > 0.0f)
  910. return;
  911. // Point is inside
  912. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  913. }
  914. void ConvexHullShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, Array<SoftBodyVertex> &ioVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  915. {
  916. Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
  917. Vec3 inv_scale = inScale.Reciprocal();
  918. bool is_not_scaled = ScaleHelpers::IsNotScaled(inScale);
  919. float scale_flip = ScaleHelpers::IsInsideOut(inScale)? -1.0f : 1.0f;
  920. for (SoftBodyVertex &v : ioVertices)
  921. if (v.mInvMass > 0.0f)
  922. {
  923. Vec3 local_pos = inverse_transform * v.mPosition;
  924. // Find most facing plane
  925. float max_distance = -FLT_MAX;
  926. Vec3 max_plane_normal = Vec3::sZero();
  927. uint max_plane_idx = 0;
  928. if (is_not_scaled)
  929. {
  930. // Without scale, it is trivial to calculate the distance to the hull
  931. for (const Plane &p : mPlanes)
  932. {
  933. float distance = p.SignedDistance(local_pos);
  934. if (distance > max_distance)
  935. {
  936. max_distance = distance;
  937. max_plane_normal = p.GetNormal();
  938. max_plane_idx = uint(&p - mPlanes.data());
  939. }
  940. }
  941. }
  942. else
  943. {
  944. // When there's scale we need to calculate the planes first
  945. for (uint i = 0; i < (uint)mPlanes.size(); ++i)
  946. {
  947. // Calculate plane normal and point by scaling the original plane
  948. Vec3 plane_normal = (inv_scale * mPlanes[i].GetNormal()).Normalized();
  949. Vec3 plane_point = inScale * mPoints[mVertexIdx[mFaces[i].mFirstVertex]].mPosition;
  950. float distance = plane_normal.Dot(local_pos - plane_point);
  951. if (distance > max_distance)
  952. {
  953. max_distance = distance;
  954. max_plane_normal = plane_normal;
  955. max_plane_idx = i;
  956. }
  957. }
  958. }
  959. bool is_outside = max_distance > 0.0f;
  960. // Project point onto that plane
  961. Vec3 closest_point = local_pos - max_distance * max_plane_normal;
  962. // Check edges if we're outside the hull (when inside we know the closest face is also the closest point to the surface)
  963. if (is_outside)
  964. {
  965. // Loop over edges
  966. float closest_point_dist_sq = FLT_MAX;
  967. const Face &face = mFaces[max_plane_idx];
  968. for (const uint8 *v_start = &mVertexIdx[face.mFirstVertex], *v1 = v_start, *v_end = v_start + face.mNumVertices; v1 < v_end; ++v1)
  969. {
  970. // Find second point
  971. const uint8 *v2 = v1 + 1;
  972. if (v2 == v_end)
  973. v2 = v_start;
  974. // Get edge points
  975. Vec3 p1 = inScale * mPoints[*v1].mPosition;
  976. Vec3 p2 = inScale * mPoints[*v2].mPosition;
  977. // Check if the position is outside the edge (if not, the face will be closer)
  978. Vec3 edge_normal = (p2 - p1).Cross(max_plane_normal);
  979. if (scale_flip * edge_normal.Dot(local_pos - p1) > 0.0f)
  980. {
  981. // Get closest point on edge
  982. uint32 set;
  983. Vec3 closest = ClosestPoint::GetClosestPointOnLine(p1 - local_pos, p2 - local_pos, set);
  984. float distance_sq = closest.LengthSq();
  985. if (distance_sq < closest_point_dist_sq)
  986. closest_point = local_pos + closest;
  987. }
  988. }
  989. }
  990. // Check if this is the largest penetration
  991. Vec3 normal = local_pos - closest_point;
  992. float normal_length = normal.Length();
  993. float penetration = normal_length;
  994. if (is_outside)
  995. penetration = -penetration;
  996. else
  997. normal = -normal;
  998. if (penetration > v.mLargestPenetration)
  999. {
  1000. v.mLargestPenetration = penetration;
  1001. // Calculate contact plane
  1002. normal = normal_length > 0.0f? normal / normal_length : max_plane_normal;
  1003. Plane plane = Plane::sFromPointAndNormal(closest_point, normal);
  1004. // Store collision
  1005. v.mCollisionPlane = plane.GetTransformed(inCenterOfMassTransform);
  1006. v.mCollidingShapeIndex = inCollidingShapeIndex;
  1007. }
  1008. }
  1009. }
  1010. class ConvexHullShape::CHSGetTrianglesContext
  1011. {
  1012. public:
  1013. CHSGetTrianglesContext(Mat44Arg inTransform, bool inIsInsideOut) : mTransform(inTransform), mIsInsideOut(inIsInsideOut) { }
  1014. Mat44 mTransform;
  1015. bool mIsInsideOut;
  1016. size_t mCurrentFace = 0;
  1017. };
  1018. void ConvexHullShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  1019. {
  1020. static_assert(sizeof(CHSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  1021. JPH_ASSERT(IsAligned(&ioContext, alignof(CHSGetTrianglesContext)));
  1022. new (&ioContext) CHSGetTrianglesContext(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale), ScaleHelpers::IsInsideOut(inScale));
  1023. }
  1024. int ConvexHullShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  1025. {
  1026. static_assert(cGetTrianglesMinTrianglesRequested >= 12, "cGetTrianglesMinTrianglesRequested is too small");
  1027. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  1028. CHSGetTrianglesContext &context = (CHSGetTrianglesContext &)ioContext;
  1029. int total_num_triangles = 0;
  1030. for (; context.mCurrentFace < mFaces.size(); ++context.mCurrentFace)
  1031. {
  1032. const Face &f = mFaces[context.mCurrentFace];
  1033. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  1034. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  1035. // Check if there is still room in the output buffer for this face
  1036. int num_triangles = f.mNumVertices - 2;
  1037. inMaxTrianglesRequested -= num_triangles;
  1038. if (inMaxTrianglesRequested < 0)
  1039. break;
  1040. total_num_triangles += num_triangles;
  1041. // Get first triangle of polygon
  1042. Vec3 v0 = context.mTransform * mPoints[first_vtx[0]].mPosition;
  1043. Vec3 v1 = context.mTransform * mPoints[first_vtx[1]].mPosition;
  1044. Vec3 v2 = context.mTransform * mPoints[first_vtx[2]].mPosition;
  1045. v0.StoreFloat3(outTriangleVertices++);
  1046. if (context.mIsInsideOut)
  1047. {
  1048. // Store first triangle in this polygon flipped
  1049. v2.StoreFloat3(outTriangleVertices++);
  1050. v1.StoreFloat3(outTriangleVertices++);
  1051. // Store other triangles in this polygon flipped
  1052. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  1053. {
  1054. v0.StoreFloat3(outTriangleVertices++);
  1055. (context.mTransform * mPoints[*v].mPosition).StoreFloat3(outTriangleVertices++);
  1056. (context.mTransform * mPoints[*(v - 1)].mPosition).StoreFloat3(outTriangleVertices++);
  1057. }
  1058. }
  1059. else
  1060. {
  1061. // Store first triangle in this polygon
  1062. v1.StoreFloat3(outTriangleVertices++);
  1063. v2.StoreFloat3(outTriangleVertices++);
  1064. // Store other triangles in this polygon
  1065. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  1066. {
  1067. v0.StoreFloat3(outTriangleVertices++);
  1068. (context.mTransform * mPoints[*(v - 1)].mPosition).StoreFloat3(outTriangleVertices++);
  1069. (context.mTransform * mPoints[*v].mPosition).StoreFloat3(outTriangleVertices++);
  1070. }
  1071. }
  1072. }
  1073. // Store materials
  1074. if (outMaterials != nullptr)
  1075. {
  1076. const PhysicsMaterial *material = GetMaterial();
  1077. for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
  1078. *m = material;
  1079. }
  1080. return total_num_triangles;
  1081. }
  1082. void ConvexHullShape::SaveBinaryState(StreamOut &inStream) const
  1083. {
  1084. ConvexShape::SaveBinaryState(inStream);
  1085. inStream.Write(mCenterOfMass);
  1086. inStream.Write(mInertia);
  1087. inStream.Write(mLocalBounds.mMin);
  1088. inStream.Write(mLocalBounds.mMax);
  1089. inStream.Write(mPoints);
  1090. inStream.Write(mFaces);
  1091. inStream.Write(mPlanes);
  1092. inStream.Write(mVertexIdx);
  1093. inStream.Write(mConvexRadius);
  1094. inStream.Write(mVolume);
  1095. inStream.Write(mInnerRadius);
  1096. }
  1097. void ConvexHullShape::RestoreBinaryState(StreamIn &inStream)
  1098. {
  1099. ConvexShape::RestoreBinaryState(inStream);
  1100. inStream.Read(mCenterOfMass);
  1101. inStream.Read(mInertia);
  1102. inStream.Read(mLocalBounds.mMin);
  1103. inStream.Read(mLocalBounds.mMax);
  1104. inStream.Read(mPoints);
  1105. inStream.Read(mFaces);
  1106. inStream.Read(mPlanes);
  1107. inStream.Read(mVertexIdx);
  1108. inStream.Read(mConvexRadius);
  1109. inStream.Read(mVolume);
  1110. inStream.Read(mInnerRadius);
  1111. }
  1112. Shape::Stats ConvexHullShape::GetStats() const
  1113. {
  1114. // Count number of triangles
  1115. uint triangle_count = 0;
  1116. for (const Face &f : mFaces)
  1117. triangle_count += f.mNumVertices - 2;
  1118. return Stats(
  1119. sizeof(*this)
  1120. + mPoints.size() * sizeof(Point)
  1121. + mFaces.size() * sizeof(Face)
  1122. + mPlanes.size() * sizeof(Plane)
  1123. + mVertexIdx.size() * sizeof(uint8),
  1124. triangle_count);
  1125. }
  1126. void ConvexHullShape::sRegister()
  1127. {
  1128. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::ConvexHull);
  1129. f.mConstruct = []() -> Shape * { return new ConvexHullShape; };
  1130. f.mColor = Color::sGreen;
  1131. }
  1132. JPH_NAMESPACE_END