MeshShape.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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/MeshShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ConvexShape.h>
  7. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  9. #include <Jolt/Physics/Collision/RayCast.h>
  10. #include <Jolt/Physics/Collision/ShapeCast.h>
  11. #include <Jolt/Physics/Collision/ShapeFilter.h>
  12. #include <Jolt/Physics/Collision/CastResult.h>
  13. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  14. #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h>
  15. #include <Jolt/Physics/Collision/CastConvexVsTriangles.h>
  16. #include <Jolt/Physics/Collision/CastSphereVsTriangles.h>
  17. #include <Jolt/Physics/Collision/TransformedShape.h>
  18. #include <Jolt/Physics/Collision/ActiveEdges.h>
  19. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  20. #include <Jolt/Physics/Collision/SortReverseAndStore.h>
  21. #include <Jolt/Physics/Collision/CollideSoftBodyVerticesVsTriangles.h>
  22. #include <Jolt/Core/StringTools.h>
  23. #include <Jolt/Core/StreamIn.h>
  24. #include <Jolt/Core/StreamOut.h>
  25. #include <Jolt/Core/Profiler.h>
  26. #include <Jolt/Core/UnorderedMap.h>
  27. #include <Jolt/Geometry/AABox4.h>
  28. #include <Jolt/Geometry/RayAABox.h>
  29. #include <Jolt/Geometry/Indexify.h>
  30. #include <Jolt/Geometry/Plane.h>
  31. #include <Jolt/Geometry/OrientedBox.h>
  32. #include <Jolt/TriangleSplitter/TriangleSplitterBinning.h>
  33. #include <Jolt/AABBTree/AABBTreeBuilder.h>
  34. #include <Jolt/AABBTree/AABBTreeToBuffer.h>
  35. #include <Jolt/AABBTree/TriangleCodec/TriangleCodecIndexed8BitPackSOA4Flags.h>
  36. #include <Jolt/AABBTree/NodeCodec/NodeCodecQuadTreeHalfFloat.h>
  37. #include <Jolt/ObjectStream/TypeDeclarations.h>
  38. JPH_NAMESPACE_BEGIN
  39. #ifdef JPH_DEBUG_RENDERER
  40. bool MeshShape::sDrawTriangleGroups = false;
  41. bool MeshShape::sDrawTriangleOutlines = false;
  42. #endif // JPH_DEBUG_RENDERER
  43. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(MeshShapeSettings)
  44. {
  45. JPH_ADD_BASE_CLASS(MeshShapeSettings, ShapeSettings)
  46. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mTriangleVertices)
  47. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mIndexedTriangles)
  48. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mMaterials)
  49. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mMaxTrianglesPerLeaf)
  50. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mActiveEdgeCosThresholdAngle)
  51. JPH_ADD_ATTRIBUTE(MeshShapeSettings, mPerTriangleUserData)
  52. }
  53. // Codecs this mesh shape is using
  54. using TriangleCodec = TriangleCodecIndexed8BitPackSOA4Flags;
  55. using NodeCodec = NodeCodecQuadTreeHalfFloat<1>;
  56. // Get header for tree
  57. static JPH_INLINE const NodeCodec::Header *sGetNodeHeader(const ByteBuffer &inTree)
  58. {
  59. return inTree.Get<NodeCodec::Header>(0);
  60. }
  61. // Get header for triangles
  62. static JPH_INLINE const TriangleCodec::TriangleHeader *sGetTriangleHeader(const ByteBuffer &inTree)
  63. {
  64. return inTree.Get<TriangleCodec::TriangleHeader>(NodeCodec::HeaderSize);
  65. }
  66. MeshShapeSettings::MeshShapeSettings(const TriangleList &inTriangles, PhysicsMaterialList inMaterials) :
  67. mMaterials(std::move(inMaterials))
  68. {
  69. Indexify(inTriangles, mTriangleVertices, mIndexedTriangles);
  70. Sanitize();
  71. }
  72. MeshShapeSettings::MeshShapeSettings(VertexList inVertices, IndexedTriangleList inTriangles, PhysicsMaterialList inMaterials) :
  73. mTriangleVertices(std::move(inVertices)),
  74. mIndexedTriangles(std::move(inTriangles)),
  75. mMaterials(std::move(inMaterials))
  76. {
  77. Sanitize();
  78. }
  79. void MeshShapeSettings::Sanitize()
  80. {
  81. // Remove degenerate and duplicate triangles
  82. UnorderedSet<IndexedTriangle> triangles;
  83. triangles.reserve(mIndexedTriangles.size());
  84. TriangleCodec::ValidationContext validation_ctx(mIndexedTriangles, mTriangleVertices);
  85. for (int t = (int)mIndexedTriangles.size() - 1; t >= 0; --t)
  86. {
  87. const IndexedTriangle &tri = mIndexedTriangles[t];
  88. if (tri.IsDegenerate(mTriangleVertices) // Degenerate triangle
  89. || validation_ctx.IsDegenerate(tri) // Triangle is degenerate in the quantized space
  90. || !triangles.insert(tri.GetLowestIndexFirst()).second) // Duplicate triangle
  91. {
  92. // The order of triangles doesn't matter (gets reordered while building the tree), so we can just swap the last triangle into this slot
  93. mIndexedTriangles[t] = mIndexedTriangles.back();
  94. mIndexedTriangles.pop_back();
  95. }
  96. }
  97. }
  98. ShapeSettings::ShapeResult MeshShapeSettings::Create() const
  99. {
  100. if (mCachedResult.IsEmpty())
  101. Ref<Shape> shape = new MeshShape(*this, mCachedResult);
  102. return mCachedResult;
  103. }
  104. MeshShape::MeshShape(const MeshShapeSettings &inSettings, ShapeResult &outResult) :
  105. Shape(EShapeType::Mesh, EShapeSubType::Mesh, inSettings, outResult)
  106. {
  107. // Check if there are any triangles
  108. if (inSettings.mIndexedTriangles.empty())
  109. {
  110. outResult.SetError("Need triangles to create a mesh shape!");
  111. return;
  112. }
  113. // Check triangles
  114. TriangleCodec::ValidationContext validation_ctx(inSettings.mIndexedTriangles, inSettings.mTriangleVertices);
  115. for (int t = (int)inSettings.mIndexedTriangles.size() - 1; t >= 0; --t)
  116. {
  117. const IndexedTriangle &triangle = inSettings.mIndexedTriangles[t];
  118. if (triangle.IsDegenerate(inSettings.mTriangleVertices)
  119. || validation_ctx.IsDegenerate(triangle))
  120. {
  121. outResult.SetError(StringFormat("Triangle %d is degenerate!", t));
  122. return;
  123. }
  124. else
  125. {
  126. // Check vertex indices
  127. for (uint32 idx : triangle.mIdx)
  128. if (idx >= inSettings.mTriangleVertices.size())
  129. {
  130. outResult.SetError(StringFormat("Vertex index %u is beyond vertex list (size: %u)", idx, (uint)inSettings.mTriangleVertices.size()));
  131. return;
  132. }
  133. }
  134. }
  135. // Copy materials
  136. mMaterials = inSettings.mMaterials;
  137. if (!mMaterials.empty())
  138. {
  139. // Validate materials
  140. if (mMaterials.size() > (1 << FLAGS_MATERIAL_BITS))
  141. {
  142. outResult.SetError(StringFormat("Supporting max %d materials per mesh", 1 << FLAGS_MATERIAL_BITS));
  143. return;
  144. }
  145. for (const IndexedTriangle &t : inSettings.mIndexedTriangles)
  146. if (t.mMaterialIndex >= mMaterials.size())
  147. {
  148. outResult.SetError(StringFormat("Triangle material %u is beyond material list (size: %u)", t.mMaterialIndex, (uint)mMaterials.size()));
  149. return;
  150. }
  151. }
  152. else
  153. {
  154. // No materials assigned, validate that all triangles use material index 0
  155. for (const IndexedTriangle &t : inSettings.mIndexedTriangles)
  156. if (t.mMaterialIndex != 0)
  157. {
  158. outResult.SetError("No materials present, all triangles should have material index 0");
  159. return;
  160. }
  161. }
  162. // Check max triangles
  163. if (inSettings.mMaxTrianglesPerLeaf < 1 || inSettings.mMaxTrianglesPerLeaf > MaxTrianglesPerLeaf)
  164. {
  165. outResult.SetError("Invalid max triangles per leaf");
  166. return;
  167. }
  168. // Fill in active edge bits
  169. IndexedTriangleList indexed_triangles = inSettings.mIndexedTriangles; // Copy indices since we're adding the 'active edge' flag
  170. sFindActiveEdges(inSettings, indexed_triangles);
  171. // Create triangle splitter
  172. TriangleSplitterBinning splitter(inSettings.mTriangleVertices, indexed_triangles);
  173. // Build tree
  174. AABBTreeBuilder builder(splitter, inSettings.mMaxTrianglesPerLeaf);
  175. AABBTreeBuilderStats builder_stats;
  176. AABBTreeBuilder::Node *root = builder.Build(builder_stats);
  177. // Convert to buffer
  178. AABBTreeToBuffer<TriangleCodec, NodeCodec> buffer;
  179. const char *error = nullptr;
  180. if (!buffer.Convert(builder.GetTriangles(), builder.GetNodes(), inSettings.mTriangleVertices, root, inSettings.mPerTriangleUserData, error))
  181. {
  182. outResult.SetError(error);
  183. delete root;
  184. return;
  185. }
  186. // Move data to this class
  187. mTree.swap(buffer.GetBuffer());
  188. // Check if we're not exceeding the amount of sub shape id bits
  189. if (GetSubShapeIDBitsRecursive() > SubShapeID::MaxBits)
  190. {
  191. outResult.SetError("Mesh is too big and exceeds the amount of available sub shape ID bits");
  192. return;
  193. }
  194. outResult.Set(this);
  195. }
  196. void MeshShape::sFindActiveEdges(const MeshShapeSettings &inSettings, IndexedTriangleList &ioIndices)
  197. {
  198. // A struct to hold the two vertex indices of an edge
  199. struct Edge
  200. {
  201. Edge(int inIdx1, int inIdx2) : mIdx1(min(inIdx1, inIdx2)), mIdx2(max(inIdx1, inIdx2)) { }
  202. uint GetIndexInTriangle(const IndexedTriangle &inTriangle) const
  203. {
  204. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  205. {
  206. Edge edge(inTriangle.mIdx[edge_idx], inTriangle.mIdx[(edge_idx + 1) % 3]);
  207. if (*this == edge)
  208. return edge_idx;
  209. }
  210. JPH_ASSERT(false);
  211. return ~uint(0);
  212. }
  213. bool operator == (const Edge &inRHS) const
  214. {
  215. return mIdx1 == inRHS.mIdx1 && mIdx2 == inRHS.mIdx2;
  216. }
  217. int mIdx1;
  218. int mIdx2;
  219. };
  220. JPH_MAKE_HASH_STRUCT(Edge, EdgeHash, t.mIdx1, t.mIdx2)
  221. // A struct to hold the triangles that are connected to an edge
  222. struct TriangleIndices
  223. {
  224. uint mNumTriangles = 0;
  225. uint mTriangleIndices[2];
  226. };
  227. // Build a list of edge to triangles
  228. using EdgeToTriangle = UnorderedMap<Edge, TriangleIndices, EdgeHash>;
  229. EdgeToTriangle edge_to_triangle;
  230. edge_to_triangle.reserve(ioIndices.size() * 3);
  231. for (uint triangle_idx = 0; triangle_idx < ioIndices.size(); ++triangle_idx)
  232. {
  233. IndexedTriangle &triangle = ioIndices[triangle_idx];
  234. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  235. {
  236. Edge edge(triangle.mIdx[edge_idx], triangle.mIdx[(edge_idx + 1) % 3]);
  237. TriangleIndices &indices = edge_to_triangle[edge];
  238. if (indices.mNumTriangles < 2)
  239. {
  240. // Store index of triangle that connects to this edge
  241. indices.mTriangleIndices[indices.mNumTriangles] = triangle_idx;
  242. indices.mNumTriangles++;
  243. }
  244. else
  245. {
  246. // 3 or more triangles share an edge, mark this edge as active
  247. uint32 mask = 1 << (edge_idx + FLAGS_ACTIVE_EGDE_SHIFT);
  248. JPH_ASSERT((triangle.mMaterialIndex & mask) == 0);
  249. triangle.mMaterialIndex |= mask;
  250. }
  251. }
  252. }
  253. // Walk over all edges and determine which ones are active
  254. for (const EdgeToTriangle::value_type &edge : edge_to_triangle)
  255. {
  256. uint num_active = 0;
  257. if (edge.second.mNumTriangles == 1)
  258. {
  259. // Edge is not shared, it is an active edge
  260. num_active = 1;
  261. }
  262. else if (edge.second.mNumTriangles == 2)
  263. {
  264. // Simple shared edge, determine if edge is active based on the two adjacent triangles
  265. const IndexedTriangle &triangle1 = ioIndices[edge.second.mTriangleIndices[0]];
  266. const IndexedTriangle &triangle2 = ioIndices[edge.second.mTriangleIndices[1]];
  267. // Find which edge this is for both triangles
  268. uint edge_idx1 = edge.first.GetIndexInTriangle(triangle1);
  269. uint edge_idx2 = edge.first.GetIndexInTriangle(triangle2);
  270. // Construct a plane for triangle 1 (e1 = edge vertex 1, e2 = edge vertex 2, op = opposing vertex)
  271. Vec3 triangle1_e1 = Vec3(inSettings.mTriangleVertices[triangle1.mIdx[edge_idx1]]);
  272. Vec3 triangle1_e2 = Vec3(inSettings.mTriangleVertices[triangle1.mIdx[(edge_idx1 + 1) % 3]]);
  273. Vec3 triangle1_op = Vec3(inSettings.mTriangleVertices[triangle1.mIdx[(edge_idx1 + 2) % 3]]);
  274. Plane triangle1_plane = Plane::sFromPointsCCW(triangle1_e1, triangle1_e2, triangle1_op);
  275. // Construct a plane for triangle 2
  276. Vec3 triangle2_e1 = Vec3(inSettings.mTriangleVertices[triangle2.mIdx[edge_idx2]]);
  277. Vec3 triangle2_e2 = Vec3(inSettings.mTriangleVertices[triangle2.mIdx[(edge_idx2 + 1) % 3]]);
  278. Vec3 triangle2_op = Vec3(inSettings.mTriangleVertices[triangle2.mIdx[(edge_idx2 + 2) % 3]]);
  279. Plane triangle2_plane = Plane::sFromPointsCCW(triangle2_e1, triangle2_e2, triangle2_op);
  280. // Determine if the edge is active
  281. num_active = ActiveEdges::IsEdgeActive(triangle1_plane.GetNormal(), triangle2_plane.GetNormal(), triangle1_e2 - triangle1_e1, inSettings.mActiveEdgeCosThresholdAngle)? 2 : 0;
  282. }
  283. else
  284. {
  285. // More edges incoming, we've already marked all edges beyond the 2nd as active
  286. num_active = 2;
  287. }
  288. // Mark edges of all original triangles active
  289. for (uint i = 0; i < num_active; ++i)
  290. {
  291. uint triangle_idx = edge.second.mTriangleIndices[i];
  292. IndexedTriangle &triangle = ioIndices[triangle_idx];
  293. uint edge_idx = edge.first.GetIndexInTriangle(triangle);
  294. uint32 mask = 1 << (edge_idx + FLAGS_ACTIVE_EGDE_SHIFT);
  295. JPH_ASSERT((triangle.mMaterialIndex & mask) == 0);
  296. triangle.mMaterialIndex |= mask;
  297. }
  298. }
  299. }
  300. MassProperties MeshShape::GetMassProperties() const
  301. {
  302. // We cannot calculate the volume for an arbitrary mesh, so we return invalid mass properties.
  303. // If you want your mesh to be dynamic, then you should provide the mass properties yourself when
  304. // creating a Body:
  305. //
  306. // BodyCreationSettings::mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  307. // BodyCreationSettings::mMassPropertiesOverride.SetMassAndInertiaOfSolidBox(Vec3::sReplicate(1.0f), 1000.0f);
  308. //
  309. // Note that for a mesh shape to simulate properly, it is best if the mesh is manifold
  310. // (i.e. closed, all edges shared by only two triangles, consistent winding order).
  311. return MassProperties();
  312. }
  313. void MeshShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, const void *&outTriangleBlock, uint32 &outTriangleIndex) const
  314. {
  315. // Get block
  316. SubShapeID triangle_idx_subshape_id;
  317. uint32 block_id = inSubShapeID.PopID(NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree), triangle_idx_subshape_id);
  318. outTriangleBlock = NodeCodec::DecodingContext::sGetTriangleBlockStart(&mTree[0], block_id);
  319. // Fetch the triangle index
  320. SubShapeID remainder;
  321. outTriangleIndex = triangle_idx_subshape_id.PopID(NumTriangleBits, remainder);
  322. JPH_ASSERT(remainder.IsEmpty(), "Invalid subshape ID");
  323. }
  324. uint MeshShape::GetMaterialIndex(const SubShapeID &inSubShapeID) const
  325. {
  326. // Decode ID
  327. const void *block_start;
  328. uint32 triangle_idx;
  329. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  330. // Fetch the flags
  331. uint8 flags = TriangleCodec::DecodingContext::sGetFlags(block_start, triangle_idx);
  332. return flags & FLAGS_MATERIAL_MASK;
  333. }
  334. const PhysicsMaterial *MeshShape::GetMaterial(const SubShapeID &inSubShapeID) const
  335. {
  336. // Return the default material if there are no materials on this shape
  337. if (mMaterials.empty())
  338. return PhysicsMaterial::sDefault;
  339. return mMaterials[GetMaterialIndex(inSubShapeID)];
  340. }
  341. Vec3 MeshShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  342. {
  343. // Decode ID
  344. const void *block_start;
  345. uint32 triangle_idx;
  346. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  347. // Decode triangle
  348. Vec3 v1, v2, v3;
  349. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  350. triangle_ctx.GetTriangle(block_start, triangle_idx, v1, v2, v3);
  351. // Calculate normal
  352. return (v3 - v2).Cross(v1 - v2).Normalized();
  353. }
  354. void MeshShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  355. {
  356. // Decode ID
  357. const void *block_start;
  358. uint32 triangle_idx;
  359. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  360. // Decode triangle
  361. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  362. outVertices.resize(3);
  363. triangle_ctx.GetTriangle(block_start, triangle_idx, outVertices[0], outVertices[1], outVertices[2]);
  364. // Flip triangle if scaled inside out
  365. if (ScaleHelpers::IsInsideOut(inScale))
  366. swap(outVertices[1], outVertices[2]);
  367. // Calculate transform with scale
  368. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  369. // Transform to world space
  370. for (Vec3 &v : outVertices)
  371. v = transform * v;
  372. }
  373. AABox MeshShape::GetLocalBounds() const
  374. {
  375. const NodeCodec::Header *header = sGetNodeHeader(mTree);
  376. return AABox(Vec3::sLoadFloat3Unsafe(header->mRootBoundsMin), Vec3::sLoadFloat3Unsafe(header->mRootBoundsMax));
  377. }
  378. uint MeshShape::GetSubShapeIDBitsRecursive() const
  379. {
  380. return NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree) + NumTriangleBits;
  381. }
  382. template <class Visitor>
  383. JPH_INLINE void MeshShape::WalkTree(Visitor &ioVisitor) const
  384. {
  385. const NodeCodec::Header *header = sGetNodeHeader(mTree);
  386. NodeCodec::DecodingContext node_ctx(header);
  387. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  388. const uint8 *buffer_start = &mTree[0];
  389. node_ctx.WalkTree(buffer_start, triangle_ctx, ioVisitor);
  390. }
  391. template <class Visitor>
  392. JPH_INLINE void MeshShape::WalkTreePerTriangle(const SubShapeIDCreator &inSubShapeIDCreator2, Visitor &ioVisitor) const
  393. {
  394. struct ChainedVisitor
  395. {
  396. JPH_INLINE ChainedVisitor(Visitor &ioVisitor, const SubShapeIDCreator &inSubShapeIDCreator2, uint inTriangleBlockIDBits) :
  397. mVisitor(ioVisitor),
  398. mSubShapeIDCreator2(inSubShapeIDCreator2),
  399. mTriangleBlockIDBits(inTriangleBlockIDBits)
  400. {
  401. }
  402. JPH_INLINE bool ShouldAbort() const
  403. {
  404. return mVisitor.ShouldAbort();
  405. }
  406. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  407. {
  408. return mVisitor.ShouldVisitNode(inStackTop);
  409. }
  410. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  411. {
  412. return mVisitor.VisitNodes(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, ioProperties, inStackTop);
  413. }
  414. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, uint32 inTriangleBlockID)
  415. {
  416. // Create ID for triangle block
  417. SubShapeIDCreator block_sub_shape_id = mSubShapeIDCreator2.PushID(inTriangleBlockID, mTriangleBlockIDBits);
  418. // Decode vertices and flags
  419. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  420. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  421. uint8 flags[MaxTrianglesPerLeaf];
  422. ioContext.Unpack(inTriangles, inNumTriangles, vertices, flags);
  423. int triangle_idx = 0;
  424. for (const Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3, triangle_idx++)
  425. {
  426. // Determine active edges
  427. uint8 active_edges = (flags[triangle_idx] >> FLAGS_ACTIVE_EGDE_SHIFT) & FLAGS_ACTIVE_EDGE_MASK;
  428. // Create ID for triangle
  429. SubShapeIDCreator triangle_sub_shape_id = block_sub_shape_id.PushID(triangle_idx, NumTriangleBits);
  430. mVisitor.VisitTriangle(v[0], v[1], v[2], active_edges, triangle_sub_shape_id.GetID());
  431. // Check if we should early out now
  432. if (mVisitor.ShouldAbort())
  433. break;
  434. }
  435. }
  436. Visitor & mVisitor;
  437. SubShapeIDCreator mSubShapeIDCreator2;
  438. uint mTriangleBlockIDBits;
  439. };
  440. ChainedVisitor visitor(ioVisitor, inSubShapeIDCreator2, NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree));
  441. WalkTree(visitor);
  442. }
  443. #ifdef JPH_DEBUG_RENDERER
  444. void MeshShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  445. {
  446. // Reset the batch if we switch coloring mode
  447. if (mCachedTrianglesColoredPerGroup != sDrawTriangleGroups || mCachedUseMaterialColors != inUseMaterialColors)
  448. {
  449. mGeometry = nullptr;
  450. mCachedTrianglesColoredPerGroup = sDrawTriangleGroups;
  451. mCachedUseMaterialColors = inUseMaterialColors;
  452. }
  453. if (mGeometry == nullptr)
  454. {
  455. struct Visitor
  456. {
  457. JPH_INLINE bool ShouldAbort() const
  458. {
  459. return false;
  460. }
  461. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  462. {
  463. return true;
  464. }
  465. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  466. {
  467. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  468. return CountAndSortTrues(valid, ioProperties);
  469. }
  470. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, [[maybe_unused]] uint32 inTriangleBlockID)
  471. {
  472. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  473. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  474. ioContext.Unpack(inTriangles, inNumTriangles, vertices);
  475. if (mDrawTriangleGroups || !mUseMaterialColors || mMaterials.empty())
  476. {
  477. // Single color for mesh
  478. Color color = mDrawTriangleGroups? Color::sGetDistinctColor(mColorIdx++) : (mUseMaterialColors? PhysicsMaterial::sDefault->GetDebugColor() : Color::sWhite);
  479. for (const Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3)
  480. mTriangles.push_back({ v[0], v[1], v[2], color });
  481. }
  482. else
  483. {
  484. // Per triangle color
  485. uint8 flags[MaxTrianglesPerLeaf];
  486. TriangleCodec::DecodingContext::sGetFlags(inTriangles, inNumTriangles, flags);
  487. const uint8 *f = flags;
  488. for (const Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3, f++)
  489. mTriangles.push_back({ v[0], v[1], v[2], mMaterials[*f & FLAGS_MATERIAL_MASK]->GetDebugColor() });
  490. }
  491. }
  492. Array<DebugRenderer::Triangle> & mTriangles;
  493. const PhysicsMaterialList & mMaterials;
  494. bool mUseMaterialColors;
  495. bool mDrawTriangleGroups;
  496. int mColorIdx = 0;
  497. };
  498. Array<DebugRenderer::Triangle> triangles;
  499. Visitor visitor { triangles, mMaterials, mCachedUseMaterialColors, mCachedTrianglesColoredPerGroup };
  500. WalkTree(visitor);
  501. mGeometry = new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), GetLocalBounds());
  502. }
  503. // Test if the shape is scaled inside out
  504. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  505. // Determine the draw mode
  506. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  507. // Draw the geometry
  508. inRenderer->DrawGeometry(inCenterOfMassTransform * Mat44::sScale(inScale), inColor, mGeometry, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  509. if (sDrawTriangleOutlines)
  510. {
  511. struct Visitor
  512. {
  513. JPH_INLINE Visitor(DebugRenderer *inRenderer, RMat44Arg inTransform) :
  514. mRenderer(inRenderer),
  515. mTransform(inTransform)
  516. {
  517. }
  518. JPH_INLINE bool ShouldAbort() const
  519. {
  520. return false;
  521. }
  522. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  523. {
  524. return true;
  525. }
  526. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  527. {
  528. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  529. return CountAndSortTrues(valid, ioProperties);
  530. }
  531. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, uint32 inTriangleBlockID)
  532. {
  533. // Decode vertices and flags
  534. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  535. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  536. uint8 flags[MaxTrianglesPerLeaf];
  537. ioContext.Unpack(inTriangles, inNumTriangles, vertices, flags);
  538. // Loop through triangles
  539. const uint8 *f = flags;
  540. for (Vec3 *v = vertices, *v_end = vertices + inNumTriangles * 3; v < v_end; v += 3, ++f)
  541. {
  542. // Loop through edges
  543. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  544. {
  545. RVec3 v1 = mTransform * v[edge_idx];
  546. RVec3 v2 = mTransform * v[(edge_idx + 1) % 3];
  547. // Draw active edge as a green arrow, other edges as grey
  548. if (*f & (1 << (edge_idx + FLAGS_ACTIVE_EGDE_SHIFT)))
  549. mRenderer->DrawArrow(v1, v2, Color::sGreen, 0.01f);
  550. else
  551. mRenderer->DrawLine(v1, v2, Color::sGrey);
  552. }
  553. }
  554. }
  555. DebugRenderer * mRenderer;
  556. RMat44 mTransform;
  557. };
  558. Visitor visitor { inRenderer, inCenterOfMassTransform.PreScaled(inScale) };
  559. WalkTree(visitor);
  560. }
  561. }
  562. #endif // JPH_DEBUG_RENDERER
  563. bool MeshShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  564. {
  565. JPH_PROFILE_FUNCTION();
  566. struct Visitor
  567. {
  568. JPH_INLINE explicit Visitor(RayCastResult &ioHit) :
  569. mHit(ioHit)
  570. {
  571. }
  572. JPH_INLINE bool ShouldAbort() const
  573. {
  574. return mHit.mFraction <= 0.0f;
  575. }
  576. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  577. {
  578. return mDistanceStack[inStackTop] < mHit.mFraction;
  579. }
  580. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  581. {
  582. // Test bounds of 4 children
  583. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  584. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  585. return SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);
  586. }
  587. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, uint32 inTriangleBlockID)
  588. {
  589. // Test against triangles
  590. uint32 triangle_idx;
  591. float fraction = ioContext.TestRay(mRayOrigin, mRayDirection, inTriangles, inNumTriangles, mHit.mFraction, triangle_idx);
  592. if (fraction < mHit.mFraction)
  593. {
  594. mHit.mFraction = fraction;
  595. mHit.mSubShapeID2 = mSubShapeIDCreator.PushID(inTriangleBlockID, mTriangleBlockIDBits).PushID(triangle_idx, NumTriangleBits).GetID();
  596. mReturnValue = true;
  597. }
  598. }
  599. RayCastResult & mHit;
  600. Vec3 mRayOrigin;
  601. Vec3 mRayDirection;
  602. RayInvDirection mRayInvDirection;
  603. uint mTriangleBlockIDBits;
  604. SubShapeIDCreator mSubShapeIDCreator;
  605. bool mReturnValue = false;
  606. float mDistanceStack[NodeCodec::StackSize];
  607. };
  608. Visitor visitor(ioHit);
  609. visitor.mRayOrigin = inRay.mOrigin;
  610. visitor.mRayDirection = inRay.mDirection;
  611. visitor.mRayInvDirection.Set(inRay.mDirection);
  612. visitor.mTriangleBlockIDBits = NodeCodec::DecodingContext::sTriangleBlockIDBits(mTree);
  613. visitor.mSubShapeIDCreator = inSubShapeIDCreator;
  614. WalkTree(visitor);
  615. return visitor.mReturnValue;
  616. }
  617. void MeshShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  618. {
  619. JPH_PROFILE_FUNCTION();
  620. // Test shape filter
  621. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  622. return;
  623. struct Visitor
  624. {
  625. JPH_INLINE explicit Visitor(CastRayCollector &ioCollector) :
  626. mCollector(ioCollector)
  627. {
  628. }
  629. JPH_INLINE bool ShouldAbort() const
  630. {
  631. return mCollector.ShouldEarlyOut();
  632. }
  633. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  634. {
  635. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  636. }
  637. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  638. {
  639. // Test bounds of 4 children
  640. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  641. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  642. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  643. }
  644. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, [[maybe_unused]] uint8 inActiveEdges, SubShapeID inSubShapeID2)
  645. {
  646. // Back facing check
  647. if (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)
  648. return;
  649. // Check the triangle
  650. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  651. if (fraction < mCollector.GetEarlyOutFraction())
  652. {
  653. RayCastResult hit;
  654. hit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());
  655. hit.mFraction = fraction;
  656. hit.mSubShapeID2 = inSubShapeID2;
  657. mCollector.AddHit(hit);
  658. }
  659. }
  660. CastRayCollector & mCollector;
  661. Vec3 mRayOrigin;
  662. Vec3 mRayDirection;
  663. RayInvDirection mRayInvDirection;
  664. EBackFaceMode mBackFaceMode;
  665. float mDistanceStack[NodeCodec::StackSize];
  666. };
  667. Visitor visitor(ioCollector);
  668. visitor.mBackFaceMode = inRayCastSettings.mBackFaceModeTriangles;
  669. visitor.mRayOrigin = inRay.mOrigin;
  670. visitor.mRayDirection = inRay.mDirection;
  671. visitor.mRayInvDirection.Set(inRay.mDirection);
  672. WalkTreePerTriangle(inSubShapeIDCreator, visitor);
  673. }
  674. void MeshShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  675. {
  676. sCollidePointUsingRayCast(*this, inPoint, inSubShapeIDCreator, ioCollector, inShapeFilter);
  677. }
  678. void MeshShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
  679. {
  680. JPH_PROFILE_FUNCTION();
  681. struct Visitor : public CollideSoftBodyVerticesVsTriangles
  682. {
  683. using CollideSoftBodyVerticesVsTriangles::CollideSoftBodyVerticesVsTriangles;
  684. JPH_INLINE bool ShouldAbort() const
  685. {
  686. return false;
  687. }
  688. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  689. {
  690. return mDistanceStack[inStackTop] < mClosestDistanceSq;
  691. }
  692. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  693. {
  694. // Get distance to vertex
  695. Vec4 dist_sq = AABox4DistanceSqToPoint(mLocalPosition, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  696. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  697. return SortReverseAndStore(dist_sq, mClosestDistanceSq, ioProperties, &mDistanceStack[inStackTop]);
  698. }
  699. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, [[maybe_unused]] uint8 inActiveEdges, [[maybe_unused]] SubShapeID inSubShapeID2)
  700. {
  701. ProcessTriangle(inV0, inV1, inV2);
  702. }
  703. float mDistanceStack[NodeCodec::StackSize];
  704. };
  705. Visitor visitor(inCenterOfMassTransform, inScale);
  706. for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
  707. if (v.GetInvMass() > 0.0f)
  708. {
  709. visitor.StartVertex(v);
  710. WalkTreePerTriangle(SubShapeIDCreator(), visitor);
  711. visitor.FinishVertex(v, inCollidingShapeIndex);
  712. }
  713. }
  714. void MeshShape::sCastConvexVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  715. {
  716. JPH_PROFILE_FUNCTION();
  717. struct Visitor : public CastConvexVsTriangles
  718. {
  719. using CastConvexVsTriangles::CastConvexVsTriangles;
  720. JPH_INLINE bool ShouldAbort() const
  721. {
  722. return mCollector.ShouldEarlyOut();
  723. }
  724. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  725. {
  726. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  727. }
  728. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  729. {
  730. // Scale the bounding boxes of this node
  731. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  732. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  733. // Enlarge them by the casted shape's box extents
  734. AABox4EnlargeWithExtent(mBoxExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  735. // Test bounds of 4 children
  736. Vec4 distance = RayAABox4(mBoxCenter, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  737. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  738. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  739. }
  740. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  741. {
  742. Cast(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  743. }
  744. RayInvDirection mInvDirection;
  745. Vec3 mBoxCenter;
  746. Vec3 mBoxExtent;
  747. float mDistanceStack[NodeCodec::StackSize];
  748. };
  749. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Mesh);
  750. const MeshShape *shape = static_cast<const MeshShape *>(inShape);
  751. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  752. visitor.mInvDirection.Set(inShapeCast.mDirection);
  753. visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();
  754. visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();
  755. shape->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  756. }
  757. void MeshShape::sCastSphereVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  758. {
  759. JPH_PROFILE_FUNCTION();
  760. struct Visitor : public CastSphereVsTriangles
  761. {
  762. using CastSphereVsTriangles::CastSphereVsTriangles;
  763. JPH_INLINE bool ShouldAbort() const
  764. {
  765. return mCollector.ShouldEarlyOut();
  766. }
  767. JPH_INLINE bool ShouldVisitNode(int inStackTop) const
  768. {
  769. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  770. }
  771. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  772. {
  773. // Scale the bounding boxes of this node
  774. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  775. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  776. // Enlarge them by the radius of the sphere
  777. AABox4EnlargeWithExtent(Vec3::sReplicate(mRadius), bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  778. // Test bounds of 4 children
  779. Vec4 distance = RayAABox4(mStart, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  780. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  781. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  782. }
  783. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  784. {
  785. Cast(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  786. }
  787. RayInvDirection mInvDirection;
  788. float mDistanceStack[NodeCodec::StackSize];
  789. };
  790. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Mesh);
  791. const MeshShape *shape = static_cast<const MeshShape *>(inShape);
  792. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  793. visitor.mInvDirection.Set(inShapeCast.mDirection);
  794. shape->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  795. }
  796. struct MeshShape::MSGetTrianglesContext
  797. {
  798. JPH_INLINE MSGetTrianglesContext(const MeshShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  799. mDecodeCtx(sGetNodeHeader(inShape->mTree)),
  800. mShape(inShape),
  801. mLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),
  802. mMeshScale(inScale),
  803. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  804. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  805. {
  806. }
  807. JPH_INLINE bool ShouldAbort() const
  808. {
  809. return mShouldAbort;
  810. }
  811. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  812. {
  813. return true;
  814. }
  815. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  816. {
  817. // Scale the bounding boxes of this node
  818. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  819. AABox4Scale(mMeshScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  820. // Test which nodes collide
  821. UVec4 collides = AABox4VsBox(mLocalBox, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  822. return CountAndSortTrues(collides, ioProperties);
  823. }
  824. JPH_INLINE void VisitTriangles(const TriangleCodec::DecodingContext &ioContext, const void *inTriangles, int inNumTriangles, [[maybe_unused]] uint32 inTriangleBlockID)
  825. {
  826. // When the buffer is full and we cannot process the triangles, abort the tree walk. The next time GetTrianglesNext is called we will continue here.
  827. if (mNumTrianglesFound + inNumTriangles > mMaxTrianglesRequested)
  828. {
  829. mShouldAbort = true;
  830. return;
  831. }
  832. // Decode vertices
  833. JPH_ASSERT(inNumTriangles <= MaxTrianglesPerLeaf);
  834. Vec3 vertices[MaxTrianglesPerLeaf * 3];
  835. ioContext.Unpack(inTriangles, inNumTriangles, vertices);
  836. // Store vertices as Float3
  837. if (mIsInsideOut)
  838. {
  839. // Scaled inside out, flip the triangles
  840. for (const Vec3 *v = vertices, *v_end = v + 3 * inNumTriangles; v < v_end; v += 3)
  841. {
  842. (mLocalToWorld * v[0]).StoreFloat3(mTriangleVertices++);
  843. (mLocalToWorld * v[2]).StoreFloat3(mTriangleVertices++);
  844. (mLocalToWorld * v[1]).StoreFloat3(mTriangleVertices++);
  845. }
  846. }
  847. else
  848. {
  849. // Normal scale
  850. for (const Vec3 *v = vertices, *v_end = v + 3 * inNumTriangles; v < v_end; ++v)
  851. (mLocalToWorld * *v).StoreFloat3(mTriangleVertices++);
  852. }
  853. if (mMaterials != nullptr)
  854. {
  855. if (mShape->mMaterials.empty())
  856. {
  857. // No materials, output default
  858. const PhysicsMaterial *default_material = PhysicsMaterial::sDefault;
  859. for (int m = 0; m < inNumTriangles; ++m)
  860. *mMaterials++ = default_material;
  861. }
  862. else
  863. {
  864. // Decode triangle flags
  865. uint8 flags[MaxTrianglesPerLeaf];
  866. TriangleCodec::DecodingContext::sGetFlags(inTriangles, inNumTriangles, flags);
  867. // Store materials
  868. for (const uint8 *f = flags, *f_end = f + inNumTriangles; f < f_end; ++f)
  869. *mMaterials++ = mShape->mMaterials[*f & FLAGS_MATERIAL_MASK].GetPtr();
  870. }
  871. }
  872. // Accumulate triangles found
  873. mNumTrianglesFound += inNumTriangles;
  874. }
  875. NodeCodec::DecodingContext mDecodeCtx;
  876. const MeshShape * mShape;
  877. OrientedBox mLocalBox;
  878. Vec3 mMeshScale;
  879. Mat44 mLocalToWorld;
  880. int mMaxTrianglesRequested;
  881. Float3 * mTriangleVertices;
  882. int mNumTrianglesFound;
  883. const PhysicsMaterial ** mMaterials;
  884. bool mShouldAbort;
  885. bool mIsInsideOut;
  886. };
  887. void MeshShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  888. {
  889. static_assert(sizeof(MSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  890. JPH_ASSERT(IsAligned(&ioContext, alignof(MSGetTrianglesContext)));
  891. new (&ioContext) MSGetTrianglesContext(this, inBox, inPositionCOM, inRotation, inScale);
  892. }
  893. int MeshShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  894. {
  895. static_assert(cGetTrianglesMinTrianglesRequested >= MaxTrianglesPerLeaf, "cGetTrianglesMinTrianglesRequested is too small");
  896. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  897. // Check if we're done
  898. MSGetTrianglesContext &context = (MSGetTrianglesContext &)ioContext;
  899. if (context.mDecodeCtx.IsDoneWalking())
  900. return 0;
  901. // Store parameters on context
  902. context.mMaxTrianglesRequested = inMaxTrianglesRequested;
  903. context.mTriangleVertices = outTriangleVertices;
  904. context.mMaterials = outMaterials;
  905. context.mShouldAbort = false; // Reset the abort flag
  906. context.mNumTrianglesFound = 0;
  907. // Continue (or start) walking the tree
  908. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  909. const uint8 *buffer_start = &mTree[0];
  910. context.mDecodeCtx.WalkTree(buffer_start, triangle_ctx, context);
  911. return context.mNumTrianglesFound;
  912. }
  913. void MeshShape::sCollideConvexVsMesh(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  914. {
  915. JPH_PROFILE_FUNCTION();
  916. // Get the shapes
  917. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  918. JPH_ASSERT(inShape2->GetType() == EShapeType::Mesh);
  919. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  920. const MeshShape *shape2 = static_cast<const MeshShape *>(inShape2);
  921. struct Visitor : public CollideConvexVsTriangles
  922. {
  923. using CollideConvexVsTriangles::CollideConvexVsTriangles;
  924. JPH_INLINE bool ShouldAbort() const
  925. {
  926. return mCollector.ShouldEarlyOut();
  927. }
  928. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  929. {
  930. return true;
  931. }
  932. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  933. {
  934. // Scale the bounding boxes of this node
  935. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  936. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  937. // Test which nodes collide
  938. UVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  939. return CountAndSortTrues(collides, ioProperties);
  940. }
  941. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  942. {
  943. Collide(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  944. }
  945. };
  946. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  947. shape2->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  948. }
  949. void MeshShape::sCollideSphereVsMesh(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  950. {
  951. JPH_PROFILE_FUNCTION();
  952. // Get the shapes
  953. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  954. JPH_ASSERT(inShape2->GetType() == EShapeType::Mesh);
  955. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  956. const MeshShape *shape2 = static_cast<const MeshShape *>(inShape2);
  957. struct Visitor : public CollideSphereVsTriangles
  958. {
  959. using CollideSphereVsTriangles::CollideSphereVsTriangles;
  960. JPH_INLINE bool ShouldAbort() const
  961. {
  962. return mCollector.ShouldEarlyOut();
  963. }
  964. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  965. {
  966. return true;
  967. }
  968. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  969. {
  970. // Scale the bounding boxes of this node
  971. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  972. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  973. // Test which nodes collide
  974. UVec4 collides = AABox4VsSphere(mSphereCenterIn2, mRadiusPlusMaxSeparationSq, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  975. return CountAndSortTrues(collides, ioProperties);
  976. }
  977. JPH_INLINE void VisitTriangle(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, SubShapeID inSubShapeID2)
  978. {
  979. Collide(inV0, inV1, inV2, inActiveEdges, inSubShapeID2);
  980. }
  981. };
  982. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  983. shape2->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);
  984. }
  985. void MeshShape::SaveBinaryState(StreamOut &inStream) const
  986. {
  987. Shape::SaveBinaryState(inStream);
  988. inStream.Write(static_cast<const ByteBufferVector &>(mTree)); // Make sure we use the Array<> overload
  989. }
  990. void MeshShape::RestoreBinaryState(StreamIn &inStream)
  991. {
  992. Shape::RestoreBinaryState(inStream);
  993. inStream.Read(static_cast<ByteBufferVector &>(mTree)); // Make sure we use the Array<> overload
  994. }
  995. void MeshShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  996. {
  997. outMaterials = mMaterials;
  998. }
  999. void MeshShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  1000. {
  1001. mMaterials.assign(inMaterials, inMaterials + inNumMaterials);
  1002. }
  1003. Shape::Stats MeshShape::GetStats() const
  1004. {
  1005. // Walk the tree to count the triangles
  1006. struct Visitor
  1007. {
  1008. JPH_INLINE bool ShouldAbort() const
  1009. {
  1010. return false;
  1011. }
  1012. JPH_INLINE bool ShouldVisitNode([[maybe_unused]] int inStackTop) const
  1013. {
  1014. return true;
  1015. }
  1016. JPH_INLINE int VisitNodes(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1017. {
  1018. // Visit all valid children
  1019. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  1020. return CountAndSortTrues(valid, ioProperties);
  1021. }
  1022. JPH_INLINE void VisitTriangles([[maybe_unused]] const TriangleCodec::DecodingContext &ioContext, [[maybe_unused]] const void *inTriangles, int inNumTriangles, [[maybe_unused]] uint32 inTriangleBlockID)
  1023. {
  1024. mNumTriangles += inNumTriangles;
  1025. }
  1026. uint mNumTriangles = 0;
  1027. };
  1028. Visitor visitor;
  1029. WalkTree(visitor);
  1030. return Stats(sizeof(*this) + mMaterials.size() * sizeof(Ref<PhysicsMaterial>) + mTree.size() * sizeof(uint8), visitor.mNumTriangles);
  1031. }
  1032. uint32 MeshShape::GetTriangleUserData(const SubShapeID &inSubShapeID) const
  1033. {
  1034. // Decode ID
  1035. const void *block_start;
  1036. uint32 triangle_idx;
  1037. DecodeSubShapeID(inSubShapeID, block_start, triangle_idx);
  1038. // Decode triangle
  1039. const TriangleCodec::DecodingContext triangle_ctx(sGetTriangleHeader(mTree));
  1040. return triangle_ctx.GetUserData(block_start, triangle_idx);
  1041. }
  1042. void MeshShape::sRegister()
  1043. {
  1044. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Mesh);
  1045. f.mConstruct = []() -> Shape * { return new MeshShape; };
  1046. f.mColor = Color::sRed;
  1047. for (EShapeSubType s : sConvexSubShapeTypes)
  1048. {
  1049. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Mesh, sCollideConvexVsMesh);
  1050. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Mesh, sCastConvexVsMesh);
  1051. CollisionDispatch::sRegisterCastShape(EShapeSubType::Mesh, s, CollisionDispatch::sReversedCastShape);
  1052. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Mesh, s, CollisionDispatch::sReversedCollideShape);
  1053. }
  1054. // Specialized collision functions
  1055. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Mesh, sCollideSphereVsMesh);
  1056. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Mesh, sCastSphereVsMesh);
  1057. }
  1058. JPH_NAMESPACE_END