MeshShape.cpp 47 KB

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