ConvexHullShape.cpp 43 KB

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