ConvexHullShape.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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/Geometry/ConvexHullBuilder.h>
  13. #include <Jolt/ObjectStream/TypeDeclarations.h>
  14. #include <Jolt/Core/StringTools.h>
  15. #include <Jolt/Core/StreamIn.h>
  16. #include <Jolt/Core/StreamOut.h>
  17. #include <Jolt/Core/UnorderedMap.h>
  18. #include <Jolt/Core/UnorderedSet.h>
  19. JPH_NAMESPACE_BEGIN
  20. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(ConvexHullShapeSettings)
  21. {
  22. JPH_ADD_BASE_CLASS(ConvexHullShapeSettings, ConvexShapeSettings)
  23. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mPoints)
  24. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mMaxConvexRadius)
  25. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mMaxErrorConvexRadius)
  26. JPH_ADD_ATTRIBUTE(ConvexHullShapeSettings, mHullTolerance)
  27. }
  28. ShapeSettings::ShapeResult ConvexHullShapeSettings::Create() const
  29. {
  30. if (mCachedResult.IsEmpty())
  31. Ref<Shape> shape = new ConvexHullShape(*this, mCachedResult);
  32. return mCachedResult;
  33. }
  34. ConvexHullShape::ConvexHullShape(const ConvexHullShapeSettings &inSettings, ShapeResult &outResult) :
  35. ConvexShape(EShapeSubType::ConvexHull, inSettings, outResult),
  36. mConvexRadius(inSettings.mMaxConvexRadius)
  37. {
  38. using BuilderFace = ConvexHullBuilder::Face;
  39. using Edge = ConvexHullBuilder::Edge;
  40. using Faces = Array<BuilderFace *>;
  41. // Check convex radius
  42. if (mConvexRadius < 0.0f)
  43. {
  44. outResult.SetError("Invalid convex radius");
  45. return;
  46. }
  47. // Build convex hull
  48. const char *error = nullptr;
  49. ConvexHullBuilder builder(inSettings.mPoints);
  50. ConvexHullBuilder::EResult result = builder.Initialize(cMaxPointsInHull, inSettings.mHullTolerance, error);
  51. if (result != ConvexHullBuilder::EResult::Success && result != ConvexHullBuilder::EResult::MaxVerticesReached)
  52. {
  53. outResult.SetError(error);
  54. return;
  55. }
  56. const Faces &builder_faces = builder.GetFaces();
  57. // Check the consistency of the resulting hull if we fully built it
  58. if (result == ConvexHullBuilder::EResult::Success)
  59. {
  60. ConvexHullBuilder::Face *max_error_face;
  61. float max_error_distance, coplanar_distance;
  62. int max_error_idx;
  63. builder.DetermineMaxError(max_error_face, max_error_distance, max_error_idx, coplanar_distance);
  64. 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
  65. {
  66. 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)));
  67. return;
  68. }
  69. }
  70. // Calculate center of mass and volume
  71. builder.GetCenterOfMassAndVolume(mCenterOfMass, mVolume);
  72. // Calculate covariance matrix
  73. // See:
  74. // - Why the inertia tensor is the inertia tensor - Jonathan Blow (http://number-none.com/blow/inertia/deriving_i.html)
  75. // - 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)
  76. 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));
  77. Mat44 covariance_matrix = Mat44::sZero();
  78. for (BuilderFace *f : builder_faces)
  79. {
  80. // 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
  81. // The first point on the face will be used to form a triangle fan
  82. Edge *e = f->mFirstEdge;
  83. Vec3 v1 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  84. // Get the 2nd point
  85. e = e->mNextEdge;
  86. Vec3 v2 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  87. // Loop over the triangle fan
  88. for (e = e->mNextEdge; e != f->mFirstEdge; e = e->mNextEdge)
  89. {
  90. Vec3 v3 = inSettings.mPoints[e->mStartIdx] - mCenterOfMass;
  91. // 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
  92. Mat44 a(Vec4(v1, 0), Vec4(v2, 0), Vec4(v3, 0), Vec4(0, 0, 0, 1));
  93. // Calculate covariance matrix for this tetrahedron
  94. float det_a = a.GetDeterminant3x3();
  95. Mat44 c = det_a * (a * covariance_canonical * a.Transposed());
  96. // Add it
  97. covariance_matrix += c;
  98. // Prepare for next triangle
  99. v2 = v3;
  100. }
  101. }
  102. // Calculate inertia matrix assuming density is 1, note that element (3, 3) is garbage
  103. mInertia = Mat44::sIdentity() * (covariance_matrix(0, 0) + covariance_matrix(1, 1) + covariance_matrix(2, 2)) - covariance_matrix;
  104. // Convert polygons fron the builder to our internal representation
  105. using VtxMap = UnorderedMap<int, uint8>;
  106. VtxMap vertex_map;
  107. for (BuilderFace *builder_face : builder_faces)
  108. {
  109. // Determine where the vertices go
  110. uint16 first_vertex = (uint16)mVertexIdx.size();
  111. uint16 num_vertices = 0;
  112. // Loop over vertices in face
  113. Edge *edge = builder_face->mFirstEdge;
  114. do
  115. {
  116. // Remap to new index, not all points in the original input set are required to form the hull
  117. uint8 new_idx;
  118. int original_idx = edge->mStartIdx;
  119. VtxMap::iterator m = vertex_map.find(original_idx);
  120. if (m != vertex_map.end())
  121. {
  122. // Found, reuse
  123. new_idx = m->second;
  124. }
  125. else
  126. {
  127. // This is a new point
  128. // Make relative to center of mass
  129. Vec3 p = inSettings.mPoints[original_idx] - mCenterOfMass;
  130. // Update local bounds
  131. mLocalBounds.Encapsulate(p);
  132. // Add to point list
  133. JPH_ASSERT(mPoints.size() <= 0xff);
  134. new_idx = (uint8)mPoints.size();
  135. mPoints.push_back({ p });
  136. vertex_map[original_idx] = new_idx;
  137. }
  138. // Append to vertex list
  139. JPH_ASSERT(mVertexIdx.size() < 0xffff);
  140. mVertexIdx.push_back(new_idx);
  141. num_vertices++;
  142. edge = edge->mNextEdge;
  143. } while (edge != builder_face->mFirstEdge);
  144. // Add face
  145. mFaces.push_back({ first_vertex, num_vertices });
  146. // Add plane
  147. Plane plane = Plane::sFromPointAndNormal(builder_face->mCentroid - mCenterOfMass, builder_face->mNormal.Normalized());
  148. mPlanes.push_back(plane);
  149. }
  150. // Test if GetSupportFunction can support this many points
  151. if (mPoints.size() > cMaxPointsInHull)
  152. {
  153. outResult.SetError(StringFormat("Internal error: Too many points in hull (%d), max allowed %d", mPoints.size(), cMaxPointsInHull));
  154. return;
  155. }
  156. for (int p = 0; p < (int)mPoints.size(); ++p)
  157. {
  158. // For each point, find faces that use the point
  159. Array<int> faces;
  160. for (int f = 0; f < (int)mFaces.size(); ++f)
  161. {
  162. const Face &face = mFaces[f];
  163. for (int v = 0; v < face.mNumVertices; ++v)
  164. if (mVertexIdx[face.mFirstVertex + v] == p)
  165. {
  166. faces.push_back(f);
  167. break;
  168. }
  169. }
  170. if (faces.size() < 2)
  171. {
  172. outResult.SetError("A point must be connected to 2 or more faces!");
  173. return;
  174. }
  175. if (faces.size() > 1)
  176. {
  177. // Find the 3 normals that form the largest tetrahedron
  178. // 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,
  179. // the three vectors are too coplanar and we fall back to using only 2 plane normals
  180. float biggest_volume = 0.05f;
  181. int best3[3] = { -1, -1, -1 };
  182. // When using 2 normals, we get the two with the biggest angle between them with a minimal difference of 1 degree
  183. // otherwise we fall back to just using 1 plane normal
  184. float smallest_dot = Cos(DegreesToRadians(1.0f));
  185. int best2[2] = { -1, -1 };
  186. for (int face1 = 0; face1 < (int)faces.size(); ++face1)
  187. {
  188. Vec3 normal1 = mPlanes[faces[face1]].GetNormal();
  189. for (int face2 = face1 + 1; face2 < (int)faces.size(); ++face2)
  190. {
  191. Vec3 normal2 = mPlanes[faces[face2]].GetNormal();
  192. Vec3 cross = normal1.Cross(normal2);
  193. // Determine the 2 face normals that are most apart
  194. float dot = normal1.Dot(normal2);
  195. if (dot < smallest_dot)
  196. {
  197. smallest_dot = dot;
  198. best2[0] = faces[face1];
  199. best2[1] = faces[face2];
  200. }
  201. // Determine the 3 face normals that form the largest tetrahedron
  202. for (int face3 = face2 + 1; face3 < (int)faces.size(); ++face3)
  203. {
  204. Vec3 normal3 = mPlanes[faces[face3]].GetNormal();
  205. float volume = abs(cross.Dot(normal3));
  206. if (volume > biggest_volume)
  207. {
  208. biggest_volume = volume;
  209. best3[0] = faces[face1];
  210. best3[1] = faces[face2];
  211. best3[2] = faces[face3];
  212. }
  213. }
  214. }
  215. }
  216. // If we didn't find 3 planes, use 2, if we didn't find 2 use 1
  217. if (best3[0] != -1)
  218. faces = { best3[0], best3[1], best3[2] };
  219. else if (best2[0] != -1)
  220. faces = { best2[0], best2[1] };
  221. else
  222. faces = { faces[0] };
  223. }
  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 interesection 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. if (ScaleHelpers::IsNotScaled(inScale))
  467. return new (&inBuffer) HullWithConvex(this);
  468. else
  469. return new (&inBuffer) HullWithConvexScaled(this, inScale);
  470. case ESupportMode::ExcludeConvexRadius:
  471. if (ScaleHelpers::IsNotScaled(inScale))
  472. {
  473. // Create support function
  474. HullNoConvex *hull = new (&inBuffer) HullNoConvex(mConvexRadius);
  475. HullNoConvex::PointsArray &transformed_points = hull->GetPoints();
  476. JPH_ASSERT(mPoints.size() <= cMaxPointsInHull, "Not enough space, this should have been caught during shape creation!");
  477. for (const Point &point : mPoints)
  478. {
  479. Vec3 new_point;
  480. if (point.mNumFaces == 1)
  481. {
  482. // Simply shift back by the convex radius using our 1 plane
  483. new_point = point.mPosition - mPlanes[point.mFaces[0]].GetNormal() * mConvexRadius;
  484. }
  485. else
  486. {
  487. // Get first two planes and offset inwards by convex radius
  488. Plane p1 = mPlanes[point.mFaces[0]].Offset(-mConvexRadius);
  489. Plane p2 = mPlanes[point.mFaces[1]].Offset(-mConvexRadius);
  490. Plane p3;
  491. if (point.mNumFaces == 3)
  492. {
  493. // Get third plane and offset inwards by convex radius
  494. p3 = mPlanes[point.mFaces[2]].Offset(-mConvexRadius);
  495. }
  496. else
  497. {
  498. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  499. JPH_ASSERT(point.mNumFaces == 2);
  500. p3 = Plane::sFromPointAndNormal(point.mPosition, p1.GetNormal().Cross(p2.GetNormal()));
  501. }
  502. // Find intersection point between the three planes
  503. if (!Plane::sIntersectPlanes(p1, p2, p3, new_point))
  504. {
  505. // Fallback: Just push point back using the first plane
  506. new_point = point.mPosition - p1.GetNormal() * mConvexRadius;
  507. }
  508. }
  509. // Add point
  510. transformed_points.push_back(new_point);
  511. }
  512. return hull;
  513. }
  514. else
  515. {
  516. // Calculate scaled convex radius
  517. float convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale);
  518. // Create new support function
  519. HullNoConvex *hull = new (&inBuffer) HullNoConvex(convex_radius);
  520. HullNoConvex::PointsArray &transformed_points = hull->GetPoints();
  521. JPH_ASSERT(mPoints.size() <= cMaxPointsInHull, "Not enough space, this should have been caught during shape creation!");
  522. // Precalculate inverse scale
  523. Vec3 inv_scale = inScale.Reciprocal();
  524. for (const Point &point : mPoints)
  525. {
  526. // Calculate scaled position
  527. Vec3 pos = inScale * point.mPosition;
  528. // Transform normals for plane 1 with scale
  529. Vec3 n1 = (inv_scale * mPlanes[point.mFaces[0]].GetNormal()).Normalized();
  530. Vec3 new_point;
  531. if (point.mNumFaces == 1)
  532. {
  533. // Simply shift back by the convex radius using our 1 plane
  534. new_point = pos - n1 * convex_radius;
  535. }
  536. else
  537. {
  538. // Transform normals for plane 2 with scale
  539. Vec3 n2 = (inv_scale * mPlanes[point.mFaces[1]].GetNormal()).Normalized();
  540. // Get first two planes and offset inwards by convex radius
  541. Plane p1 = Plane::sFromPointAndNormal(pos, n1).Offset(-convex_radius);
  542. Plane p2 = Plane::sFromPointAndNormal(pos, n2).Offset(-convex_radius);
  543. Plane p3;
  544. if (point.mNumFaces == 3)
  545. {
  546. // Transform last normal with scale
  547. Vec3 n3 = (inv_scale * mPlanes[point.mFaces[2]].GetNormal()).Normalized();
  548. // Get third plane and offset inwards by convex radius
  549. p3 = Plane::sFromPointAndNormal(pos, n3).Offset(-convex_radius);
  550. }
  551. else
  552. {
  553. // Third plane has normal perpendicular to the other two planes and goes through the vertex position
  554. JPH_ASSERT(point.mNumFaces == 2);
  555. p3 = Plane::sFromPointAndNormal(pos, n1.Cross(n2));
  556. }
  557. // Find intersection point between the three planes
  558. if (!Plane::sIntersectPlanes(p1, p2, p3, new_point))
  559. {
  560. // Fallback: Just push point back using the first plane
  561. new_point = pos - n1 * convex_radius;
  562. }
  563. }
  564. // Add point
  565. transformed_points.push_back(new_point);
  566. }
  567. return hull;
  568. }
  569. }
  570. JPH_ASSERT(false);
  571. return nullptr;
  572. }
  573. void ConvexHullShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  574. {
  575. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  576. Vec3 inv_scale = inScale.Reciprocal();
  577. // Need to transform the plane normals using inScale
  578. // Transforming a direction with matrix M is done through multiplying by (M^-1)^T
  579. // 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
  580. Vec3 plane0_normal = inv_scale * mPlanes[0].GetNormal();
  581. float best_dot = plane0_normal.Dot(inDirection) / plane0_normal.Length();
  582. int best_face_idx = 0;
  583. for (Array<Plane>::size_type i = 1; i < mPlanes.size(); ++i)
  584. {
  585. Vec3 plane_normal = inv_scale * mPlanes[i].GetNormal();
  586. float dot = plane_normal.Dot(inDirection) / plane_normal.Length();
  587. if (dot < best_dot)
  588. {
  589. best_dot = dot;
  590. best_face_idx = (int)i;
  591. }
  592. }
  593. // Get vertices
  594. const Face &best_face = mFaces[best_face_idx];
  595. const uint8 *first_vtx = mVertexIdx.data() + best_face.mFirstVertex;
  596. const uint8 *end_vtx = first_vtx + best_face.mNumVertices;
  597. // 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).
  598. // TODO: This really needs a better algorithm to determine which vertices are important!
  599. int max_vertices_to_return = outVertices.capacity() / 2;
  600. int delta_vtx = (int(best_face.mNumVertices) + max_vertices_to_return) / max_vertices_to_return;
  601. // Calculate transform with scale
  602. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  603. if (ScaleHelpers::IsInsideOut(inScale))
  604. {
  605. // Flip winding of supporting face
  606. for (const uint8 *v = end_vtx - 1; v >= first_vtx; v -= delta_vtx)
  607. outVertices.push_back(transform * mPoints[*v].mPosition);
  608. }
  609. else
  610. {
  611. // Normal winding of supporting face
  612. for (const uint8 *v = first_vtx; v < end_vtx; v += delta_vtx)
  613. outVertices.push_back(transform * mPoints[*v].mPosition);
  614. }
  615. }
  616. void ConvexHullShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  617. {
  618. // Trivially calculate total volume
  619. Vec3 abs_scale = inScale.Abs();
  620. outTotalVolume = mVolume * abs_scale.GetX() * abs_scale.GetY() * abs_scale.GetZ();
  621. // Check if shape has been scaled inside out
  622. bool is_inside_out = ScaleHelpers::IsInsideOut(inScale);
  623. // Convert the points to world space and determine the distance to the surface
  624. int num_points = int(mPoints.size());
  625. PolyhedronSubmergedVolumeCalculator::Point *buffer = (PolyhedronSubmergedVolumeCalculator::Point *)JPH_STACK_ALLOC(num_points * sizeof(PolyhedronSubmergedVolumeCalculator::Point));
  626. PolyhedronSubmergedVolumeCalculator submerged_vol_calc(inCenterOfMassTransform * Mat44::sScale(inScale), &mPoints[0].mPosition, sizeof(Point), num_points, inSurface, buffer JPH_IF_DEBUG_RENDERER(, inBaseOffset));
  627. if (submerged_vol_calc.AreAllAbove())
  628. {
  629. // We're above the water
  630. outSubmergedVolume = 0.0f;
  631. outCenterOfBuoyancy = Vec3::sZero();
  632. }
  633. else if (submerged_vol_calc.AreAllBelow())
  634. {
  635. // We're fully submerged
  636. outSubmergedVolume = outTotalVolume;
  637. outCenterOfBuoyancy = inCenterOfMassTransform.GetTranslation();
  638. }
  639. else
  640. {
  641. // Calculate submerged volume
  642. int reference_point_idx = submerged_vol_calc.GetReferencePointIdx();
  643. for (const Face &f : mFaces)
  644. {
  645. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  646. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  647. // If any of the vertices of this face are the reference point, the volume will be zero so we can skip this face
  648. bool degenerate = false;
  649. for (const uint8 *v = first_vtx; v < end_vtx; ++v)
  650. if (*v == reference_point_idx)
  651. {
  652. degenerate = true;
  653. break;
  654. }
  655. if (degenerate)
  656. continue;
  657. // Triangulate the face
  658. int i1 = *first_vtx;
  659. if (is_inside_out)
  660. {
  661. // Reverse winding
  662. for (const uint8 *v = first_vtx + 2; v < end_vtx; ++v)
  663. {
  664. int i2 = *(v - 1);
  665. int i3 = *v;
  666. submerged_vol_calc.AddFace(i1, i3, i2);
  667. }
  668. }
  669. else
  670. {
  671. // Normal winding
  672. for (const uint8 *v = first_vtx + 2; v < end_vtx; ++v)
  673. {
  674. int i2 = *(v - 1);
  675. int i3 = *v;
  676. submerged_vol_calc.AddFace(i1, i2, i3);
  677. }
  678. }
  679. }
  680. // Get the results
  681. submerged_vol_calc.GetResult(outSubmergedVolume, outCenterOfBuoyancy);
  682. }
  683. #ifdef JPH_DEBUG_RENDERER
  684. // Draw center of buoyancy
  685. if (sDrawSubmergedVolumes)
  686. DebugRenderer::sInstance->DrawWireSphere(inBaseOffset + outCenterOfBuoyancy, 0.05f, Color::sRed, 1);
  687. #endif // JPH_DEBUG_RENDERER
  688. }
  689. #ifdef JPH_DEBUG_RENDERER
  690. void ConvexHullShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  691. {
  692. if (mGeometry == nullptr)
  693. {
  694. Array<DebugRenderer::Triangle> triangles;
  695. for (const Face &f : mFaces)
  696. {
  697. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  698. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  699. // Draw first triangle of polygon
  700. Vec3 v0 = mPoints[first_vtx[0]].mPosition;
  701. Vec3 v1 = mPoints[first_vtx[1]].mPosition;
  702. Vec3 v2 = mPoints[first_vtx[2]].mPosition;
  703. Vec3 uv_direction = (v1 - v0).Normalized();
  704. triangles.push_back({ v0, v1, v2, Color::sWhite, v0, uv_direction });
  705. // Draw any other triangles in this polygon
  706. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  707. triangles.push_back({ v0, mPoints[*(v - 1)].mPosition, mPoints[*v].mPosition, Color::sWhite, v0, uv_direction });
  708. }
  709. mGeometry = new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), GetLocalBounds());
  710. }
  711. // Test if the shape is scaled inside out
  712. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  713. // Determine the draw mode
  714. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  715. // Draw the geometry
  716. Color color = inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor;
  717. RMat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  718. inRenderer->DrawGeometry(transform, color, mGeometry, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  719. // Draw the outline if requested
  720. if (sDrawFaceOutlines)
  721. for (const Face &f : mFaces)
  722. {
  723. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  724. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  725. // Draw edges of face
  726. inRenderer->DrawLine(transform * mPoints[*(end_vtx - 1)].mPosition, transform * mPoints[*first_vtx].mPosition, Color::sGrey);
  727. for (const uint8 *v = first_vtx + 1; v < end_vtx; ++v)
  728. inRenderer->DrawLine(transform * mPoints[*(v - 1)].mPosition, transform * mPoints[*v].mPosition, Color::sGrey);
  729. }
  730. }
  731. void ConvexHullShape::DrawShrunkShape(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  732. {
  733. // Get the shrunk points
  734. SupportBuffer buffer;
  735. const HullNoConvex *support = mConvexRadius > 0.0f? static_cast<const HullNoConvex *>(GetSupportFunction(ESupportMode::ExcludeConvexRadius, buffer, inScale)) : nullptr;
  736. RMat44 transform = inCenterOfMassTransform * Mat44::sScale(inScale);
  737. for (int p = 0; p < (int)mPoints.size(); ++p)
  738. {
  739. const Point &point = mPoints[p];
  740. RVec3 position = transform * point.mPosition;
  741. RVec3 shrunk_point = support != nullptr? transform * support->GetPoints()[p] : position;
  742. // Draw difference between shrunk position and position
  743. inRenderer->DrawLine(position, shrunk_point, Color::sGreen);
  744. // Draw face normals that are contributing
  745. for (int i = 0; i < point.mNumFaces; ++i)
  746. inRenderer->DrawLine(position, position + 0.1f * mPlanes[point.mFaces[i]].GetNormal(), Color::sYellow);
  747. // Draw point index
  748. inRenderer->DrawText3D(position, ConvertToString(p), Color::sWhite, 0.1f);
  749. }
  750. }
  751. #endif // JPH_DEBUG_RENDERER
  752. bool ConvexHullShape::CastRayHelper(const RayCast &inRay, float &outMinFraction, float &outMaxFraction) const
  753. {
  754. if (mFaces.size() == 2)
  755. {
  756. // If we have only 2 faces, we're a flat convex hull and we need to test edges instead of planes
  757. // Check if plane is parallel to ray
  758. const Plane &p = mPlanes.front();
  759. Vec3 plane_normal = p.GetNormal();
  760. float direction_projection = inRay.mDirection.Dot(plane_normal);
  761. if (abs(direction_projection) >= 1.0e-12f)
  762. {
  763. // Calculate intersection point
  764. float distance_to_plane = inRay.mOrigin.Dot(plane_normal) + p.GetConstant();
  765. float fraction = -distance_to_plane / direction_projection;
  766. if (fraction < 0.0f || fraction > 1.0f)
  767. {
  768. // Does not hit plane, no hit
  769. outMinFraction = 0.0f;
  770. outMaxFraction = 1.0f + FLT_EPSILON;
  771. return false;
  772. }
  773. Vec3 intersection_point = inRay.mOrigin + fraction * inRay.mDirection;
  774. // Test all edges to see if point is inside polygon
  775. const Face &f = mFaces.front();
  776. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  777. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  778. Vec3 p1 = mPoints[*end_vtx].mPosition;
  779. for (const uint8 *v = first_vtx; v < end_vtx; ++v)
  780. {
  781. Vec3 p2 = mPoints[*v].mPosition;
  782. if ((p2 - p1).Cross(intersection_point - p1).Dot(plane_normal) < 0.0f)
  783. {
  784. // Outside polygon, no hit
  785. outMinFraction = 0.0f;
  786. outMaxFraction = 1.0f + FLT_EPSILON;
  787. return false;
  788. }
  789. p1 = p2;
  790. }
  791. // Inside polygon, a hit
  792. outMinFraction = fraction;
  793. outMaxFraction = fraction;
  794. return true;
  795. }
  796. else
  797. {
  798. // Parallel ray doesn't hit
  799. outMinFraction = 0.0f;
  800. outMaxFraction = 1.0f + FLT_EPSILON;
  801. return false;
  802. }
  803. }
  804. else
  805. {
  806. // Clip ray against all planes
  807. int fractions_set = 0;
  808. bool all_inside = true;
  809. float min_fraction = 0.0f, max_fraction = 1.0f + FLT_EPSILON;
  810. for (const Plane &p : mPlanes)
  811. {
  812. // Check if the ray origin is behind this plane
  813. Vec3 plane_normal = p.GetNormal();
  814. float distance_to_plane = inRay.mOrigin.Dot(plane_normal) + p.GetConstant();
  815. bool is_outside = distance_to_plane > 0.0f;
  816. all_inside &= !is_outside;
  817. // Check if plane is parallel to ray
  818. float direction_projection = inRay.mDirection.Dot(plane_normal);
  819. if (abs(direction_projection) >= 1.0e-12f)
  820. {
  821. // Get intersection fraction between ray and plane
  822. float fraction = -distance_to_plane / direction_projection;
  823. // Update interval of ray that is inside the hull
  824. if (direction_projection < 0.0f)
  825. {
  826. min_fraction = max(fraction, min_fraction);
  827. fractions_set |= 1;
  828. }
  829. else
  830. {
  831. max_fraction = min(fraction, max_fraction);
  832. fractions_set |= 2;
  833. }
  834. }
  835. else if (is_outside)
  836. return false; // Outside the plane and parallel, no hit!
  837. }
  838. // Test if both min and max have been set
  839. if (fractions_set == 3)
  840. {
  841. // Output fractions
  842. outMinFraction = min_fraction;
  843. outMaxFraction = max_fraction;
  844. // Test if the infinite ray intersects with the hull (the length will be checked later)
  845. return min_fraction <= max_fraction && max_fraction >= 0.0f;
  846. }
  847. else
  848. {
  849. // Degenerate case, either the ray is parallel to all planes or the ray has zero length
  850. outMinFraction = 0.0f;
  851. outMaxFraction = 1.0f + FLT_EPSILON;
  852. // Return if the origin is inside the hull
  853. return all_inside;
  854. }
  855. }
  856. }
  857. bool ConvexHullShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  858. {
  859. // Determine if ray hits the shape
  860. float min_fraction, max_fraction;
  861. if (CastRayHelper(inRay, min_fraction, max_fraction)
  862. && min_fraction < ioHit.mFraction) // Check if this is a closer hit
  863. {
  864. // Better hit than the current hit
  865. ioHit.mFraction = min_fraction;
  866. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  867. return true;
  868. }
  869. return false;
  870. }
  871. void ConvexHullShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  872. {
  873. // Test shape filter
  874. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  875. return;
  876. // Determine if ray hits the shape
  877. float min_fraction, max_fraction;
  878. if (CastRayHelper(inRay, min_fraction, max_fraction)
  879. && min_fraction < ioCollector.GetEarlyOutFraction()) // Check if this is closer than the early out fraction
  880. {
  881. // Better hit than the current hit
  882. RayCastResult hit;
  883. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  884. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  885. // Check front side hit
  886. if (inRayCastSettings.mTreatConvexAsSolid || min_fraction > 0.0f)
  887. {
  888. hit.mFraction = min_fraction;
  889. ioCollector.AddHit(hit);
  890. }
  891. // Check back side hit
  892. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::CollideWithBackFaces
  893. && max_fraction < ioCollector.GetEarlyOutFraction())
  894. {
  895. hit.mFraction = max_fraction;
  896. ioCollector.AddHit(hit);
  897. }
  898. }
  899. }
  900. void ConvexHullShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  901. {
  902. // Test shape filter
  903. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  904. return;
  905. // Check if point is behind all planes
  906. for (const Plane &p : mPlanes)
  907. if (p.SignedDistance(inPoint) > 0.0f)
  908. return;
  909. // Point is inside
  910. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  911. }
  912. class ConvexHullShape::CHSGetTrianglesContext
  913. {
  914. public:
  915. CHSGetTrianglesContext(Mat44Arg inTransform, bool inIsInsideOut) : mTransform(inTransform), mIsInsideOut(inIsInsideOut) { }
  916. Mat44 mTransform;
  917. bool mIsInsideOut;
  918. size_t mCurrentFace = 0;
  919. };
  920. void ConvexHullShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  921. {
  922. static_assert(sizeof(CHSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  923. JPH_ASSERT(IsAligned(&ioContext, alignof(CHSGetTrianglesContext)));
  924. new (&ioContext) CHSGetTrianglesContext(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale), ScaleHelpers::IsInsideOut(inScale));
  925. }
  926. int ConvexHullShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  927. {
  928. static_assert(cGetTrianglesMinTrianglesRequested >= 12, "cGetTrianglesMinTrianglesRequested is too small");
  929. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  930. CHSGetTrianglesContext &context = (CHSGetTrianglesContext &)ioContext;
  931. int total_num_triangles = 0;
  932. for (; context.mCurrentFace < mFaces.size(); ++context.mCurrentFace)
  933. {
  934. const Face &f = mFaces[context.mCurrentFace];
  935. const uint8 *first_vtx = mVertexIdx.data() + f.mFirstVertex;
  936. const uint8 *end_vtx = first_vtx + f.mNumVertices;
  937. // Check if there is still room in the output buffer for this face
  938. int num_triangles = f.mNumVertices - 2;
  939. inMaxTrianglesRequested -= num_triangles;
  940. if (inMaxTrianglesRequested < 0)
  941. break;
  942. total_num_triangles += num_triangles;
  943. // Get first triangle of polygon
  944. Vec3 v0 = context.mTransform * mPoints[first_vtx[0]].mPosition;
  945. Vec3 v1 = context.mTransform * mPoints[first_vtx[1]].mPosition;
  946. Vec3 v2 = context.mTransform * mPoints[first_vtx[2]].mPosition;
  947. v0.StoreFloat3(outTriangleVertices++);
  948. if (context.mIsInsideOut)
  949. {
  950. // Store first triangle in this polygon flipped
  951. v2.StoreFloat3(outTriangleVertices++);
  952. v1.StoreFloat3(outTriangleVertices++);
  953. // Store other triangles in this polygon flipped
  954. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  955. {
  956. v0.StoreFloat3(outTriangleVertices++);
  957. (context.mTransform * mPoints[*v].mPosition).StoreFloat3(outTriangleVertices++);
  958. (context.mTransform * mPoints[*(v - 1)].mPosition).StoreFloat3(outTriangleVertices++);
  959. }
  960. }
  961. else
  962. {
  963. // Store first triangle in this polygon
  964. v1.StoreFloat3(outTriangleVertices++);
  965. v2.StoreFloat3(outTriangleVertices++);
  966. // Store other triangles in this polygon
  967. for (const uint8 *v = first_vtx + 3; v < end_vtx; ++v)
  968. {
  969. v0.StoreFloat3(outTriangleVertices++);
  970. (context.mTransform * mPoints[*(v - 1)].mPosition).StoreFloat3(outTriangleVertices++);
  971. (context.mTransform * mPoints[*v].mPosition).StoreFloat3(outTriangleVertices++);
  972. }
  973. }
  974. }
  975. // Store materials
  976. if (outMaterials != nullptr)
  977. {
  978. const PhysicsMaterial *material = GetMaterial();
  979. for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
  980. *m = material;
  981. }
  982. return total_num_triangles;
  983. }
  984. void ConvexHullShape::SaveBinaryState(StreamOut &inStream) const
  985. {
  986. ConvexShape::SaveBinaryState(inStream);
  987. inStream.Write(mCenterOfMass);
  988. inStream.Write(mInertia);
  989. inStream.Write(mLocalBounds.mMin);
  990. inStream.Write(mLocalBounds.mMax);
  991. inStream.Write(mPoints);
  992. inStream.Write(mFaces);
  993. inStream.Write(mPlanes);
  994. inStream.Write(mVertexIdx);
  995. inStream.Write(mConvexRadius);
  996. inStream.Write(mVolume);
  997. inStream.Write(mInnerRadius);
  998. }
  999. void ConvexHullShape::RestoreBinaryState(StreamIn &inStream)
  1000. {
  1001. ConvexShape::RestoreBinaryState(inStream);
  1002. inStream.Read(mCenterOfMass);
  1003. inStream.Read(mInertia);
  1004. inStream.Read(mLocalBounds.mMin);
  1005. inStream.Read(mLocalBounds.mMax);
  1006. inStream.Read(mPoints);
  1007. inStream.Read(mFaces);
  1008. inStream.Read(mPlanes);
  1009. inStream.Read(mVertexIdx);
  1010. inStream.Read(mConvexRadius);
  1011. inStream.Read(mVolume);
  1012. inStream.Read(mInnerRadius);
  1013. }
  1014. Shape::Stats ConvexHullShape::GetStats() const
  1015. {
  1016. // Count number of triangles
  1017. uint triangle_count = 0;
  1018. for (const Face &f : mFaces)
  1019. triangle_count += f.mNumVertices - 2;
  1020. return Stats(
  1021. sizeof(*this)
  1022. + mPoints.size() * sizeof(Point)
  1023. + mFaces.size() * sizeof(Face)
  1024. + mPlanes.size() * sizeof(Plane)
  1025. + mVertexIdx.size() * sizeof(uint8),
  1026. triangle_count);
  1027. }
  1028. void ConvexHullShape::sRegister()
  1029. {
  1030. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::ConvexHull);
  1031. f.mConstruct = []() -> Shape * { return new ConvexHullShape; };
  1032. f.mColor = Color::sGreen;
  1033. }
  1034. JPH_NAMESPACE_END