MeshShape.cpp 48 KB

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