TriangleShape.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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/TriangleShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
  8. #include <Jolt/Physics/Collision/RayCast.h>
  9. #include <Jolt/Physics/Collision/ShapeCast.h>
  10. #include <Jolt/Physics/Collision/CastResult.h>
  11. #include <Jolt/Physics/Collision/CollidePointResult.h>
  12. #include <Jolt/Physics/Collision/TransformedShape.h>
  13. #include <Jolt/Physics/Collision/CastConvexVsTriangles.h>
  14. #include <Jolt/Physics/Collision/CastSphereVsTriangles.h>
  15. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  16. #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h>
  17. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  18. #include <Jolt/Physics/Collision/CollideSoftBodyVerticesVsTriangles.h>
  19. #include <Jolt/Geometry/ConvexSupport.h>
  20. #include <Jolt/Geometry/RayTriangle.h>
  21. #include <Jolt/Geometry/ClosestPoint.h>
  22. #include <Jolt/ObjectStream/TypeDeclarations.h>
  23. #include <Jolt/Core/StreamIn.h>
  24. #include <Jolt/Core/StreamOut.h>
  25. #ifdef JPH_DEBUG_RENDERER
  26. #include <Jolt/Renderer/DebugRenderer.h>
  27. #endif // JPH_DEBUG_RENDERER
  28. JPH_NAMESPACE_BEGIN
  29. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TriangleShapeSettings)
  30. {
  31. JPH_ADD_BASE_CLASS(TriangleShapeSettings, ConvexShapeSettings)
  32. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV1)
  33. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV2)
  34. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV3)
  35. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mConvexRadius)
  36. }
  37. ShapeSettings::ShapeResult TriangleShapeSettings::Create() const
  38. {
  39. if (mCachedResult.IsEmpty())
  40. Ref<Shape> shape = new TriangleShape(*this, mCachedResult);
  41. return mCachedResult;
  42. }
  43. TriangleShape::TriangleShape(const TriangleShapeSettings &inSettings, ShapeResult &outResult) :
  44. ConvexShape(EShapeSubType::Triangle, inSettings, outResult),
  45. mV1(inSettings.mV1),
  46. mV2(inSettings.mV2),
  47. mV3(inSettings.mV3),
  48. mConvexRadius(inSettings.mConvexRadius)
  49. {
  50. if (inSettings.mConvexRadius < 0.0f)
  51. {
  52. outResult.SetError("Invalid convex radius");
  53. return;
  54. }
  55. outResult.Set(this);
  56. }
  57. AABox TriangleShape::GetLocalBounds() const
  58. {
  59. AABox bounds(mV1, mV1);
  60. bounds.Encapsulate(mV2);
  61. bounds.Encapsulate(mV3);
  62. bounds.ExpandBy(Vec3::sReplicate(mConvexRadius));
  63. return bounds;
  64. }
  65. AABox TriangleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  66. {
  67. JPH_ASSERT(IsValidScale(inScale));
  68. Vec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  69. Vec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  70. Vec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  71. AABox bounds(v1, v1);
  72. bounds.Encapsulate(v2);
  73. bounds.Encapsulate(v3);
  74. bounds.ExpandBy(inScale * mConvexRadius);
  75. return bounds;
  76. }
  77. class TriangleShape::TriangleNoConvex final : public Support
  78. {
  79. public:
  80. TriangleNoConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) :
  81. mTriangleSupport(inV1, inV2, inV3)
  82. {
  83. static_assert(sizeof(TriangleNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  84. JPH_ASSERT(IsAligned(this, alignof(TriangleNoConvex)));
  85. }
  86. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  87. {
  88. return mTriangleSupport.GetSupport(inDirection);
  89. }
  90. virtual float GetConvexRadius() const override
  91. {
  92. return 0.0f;
  93. }
  94. private:
  95. TriangleConvexSupport mTriangleSupport;
  96. };
  97. class TriangleShape::TriangleWithConvex final : public Support
  98. {
  99. public:
  100. TriangleWithConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, float inConvexRadius) :
  101. mConvexRadius(inConvexRadius),
  102. mTriangleSupport(inV1, inV2, inV3)
  103. {
  104. static_assert(sizeof(TriangleWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  105. JPH_ASSERT(IsAligned(this, alignof(TriangleWithConvex)));
  106. }
  107. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  108. {
  109. Vec3 support = mTriangleSupport.GetSupport(inDirection);
  110. float len = inDirection.Length();
  111. if (len > 0.0f)
  112. support += (mConvexRadius / len) * inDirection;
  113. return support;
  114. }
  115. virtual float GetConvexRadius() const override
  116. {
  117. return mConvexRadius;
  118. }
  119. private:
  120. float mConvexRadius;
  121. TriangleConvexSupport mTriangleSupport;
  122. };
  123. const ConvexShape::Support *TriangleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  124. {
  125. switch (inMode)
  126. {
  127. case ESupportMode::IncludeConvexRadius:
  128. case ESupportMode::Default:
  129. if (mConvexRadius > 0.0f)
  130. return new (&inBuffer) TriangleWithConvex(inScale * mV1, inScale * mV2, inScale * mV3, mConvexRadius);
  131. [[fallthrough]];
  132. case ESupportMode::ExcludeConvexRadius:
  133. return new (&inBuffer) TriangleNoConvex(inScale * mV1, inScale * mV2, inScale * mV3);
  134. }
  135. JPH_ASSERT(false);
  136. return nullptr;
  137. }
  138. void TriangleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  139. {
  140. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  141. // Calculate transform with scale
  142. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  143. // Flip triangle if scaled inside out
  144. if (ScaleHelpers::IsInsideOut(inScale))
  145. {
  146. outVertices.push_back(transform * mV1);
  147. outVertices.push_back(transform * mV3);
  148. outVertices.push_back(transform * mV2);
  149. }
  150. else
  151. {
  152. outVertices.push_back(transform * mV1);
  153. outVertices.push_back(transform * mV2);
  154. outVertices.push_back(transform * mV3);
  155. }
  156. }
  157. MassProperties TriangleShape::GetMassProperties() const
  158. {
  159. // We cannot calculate the volume for a triangle, so we return invalid mass properties.
  160. // If you want your triangle to be dynamic, then you should provide the mass properties yourself when
  161. // creating a Body:
  162. //
  163. // BodyCreationSettings::mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  164. // BodyCreationSettings::mMassPropertiesOverride.SetMassAndInertiaOfSolidBox(Vec3::sOne(), 1000.0f);
  165. //
  166. // Note that this makes the triangle shape behave the same as a mesh shape with a single triangle.
  167. // In practice there is very little use for a dynamic triangle shape as back side collisions will be ignored
  168. // so if the triangle falls the wrong way it will sink through the floor.
  169. return MassProperties();
  170. }
  171. Vec3 TriangleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  172. {
  173. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  174. Vec3 cross = (mV2 - mV1).Cross(mV3 - mV1);
  175. float len = cross.Length();
  176. return len != 0.0f? cross / len : Vec3::sAxisY();
  177. }
  178. void TriangleShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  179. {
  180. // A triangle has no volume
  181. outTotalVolume = outSubmergedVolume = 0.0f;
  182. outCenterOfBuoyancy = Vec3::sZero();
  183. }
  184. #ifdef JPH_DEBUG_RENDERER
  185. void TriangleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  186. {
  187. RVec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  188. RVec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  189. RVec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  190. if (ScaleHelpers::IsInsideOut(inScale))
  191. std::swap(v1, v2);
  192. if (inDrawWireframe)
  193. inRenderer->DrawWireTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  194. else
  195. inRenderer->DrawTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  196. }
  197. #endif // JPH_DEBUG_RENDERER
  198. bool TriangleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  199. {
  200. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  201. if (fraction < ioHit.mFraction)
  202. {
  203. ioHit.mFraction = fraction;
  204. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  205. return true;
  206. }
  207. return false;
  208. }
  209. void TriangleShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  210. {
  211. // Test shape filter
  212. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  213. return;
  214. // Back facing check
  215. if (inRayCastSettings.mBackFaceModeTriangles == EBackFaceMode::IgnoreBackFaces && (mV2 - mV1).Cross(mV3 - mV1).Dot(inRay.mDirection) > 0.0f)
  216. return;
  217. // Test ray against triangle
  218. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  219. if (fraction < ioCollector.GetEarlyOutFraction())
  220. {
  221. // Better hit than the current hit
  222. RayCastResult hit;
  223. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  224. hit.mFraction = fraction;
  225. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  226. ioCollector.AddHit(hit);
  227. }
  228. }
  229. void TriangleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  230. {
  231. // Can't be inside a triangle
  232. }
  233. void TriangleShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
  234. {
  235. CollideSoftBodyVerticesVsTriangles collider(inCenterOfMassTransform, inScale);
  236. for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
  237. if (v.GetInvMass() > 0.0f)
  238. {
  239. collider.StartVertex(v);
  240. collider.ProcessTriangle(mV1, mV2, mV3);
  241. collider.FinishVertex(v, inCollidingShapeIndex);
  242. }
  243. }
  244. void TriangleShape::sCollideConvexVsTriangle(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)
  245. {
  246. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  247. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  248. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  249. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  250. CollideConvexVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  251. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  252. }
  253. void TriangleShape::sCollideSphereVsTriangle(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)
  254. {
  255. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  256. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  257. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  258. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  259. CollideSphereVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  260. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  261. }
  262. void TriangleShape::sCastConvexVsTriangle(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)
  263. {
  264. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  265. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  266. CastConvexVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  267. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  268. }
  269. void TriangleShape::sCastSphereVsTriangle(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)
  270. {
  271. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  272. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  273. CastSphereVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  274. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  275. }
  276. class TriangleShape::TSGetTrianglesContext
  277. {
  278. public:
  279. TSGetTrianglesContext(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) : mV1(inV1), mV2(inV2), mV3(inV3) { }
  280. Vec3 mV1;
  281. Vec3 mV2;
  282. Vec3 mV3;
  283. bool mIsDone = false;
  284. };
  285. void TriangleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  286. {
  287. static_assert(sizeof(TSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  288. JPH_ASSERT(IsAligned(&ioContext, alignof(TSGetTrianglesContext)));
  289. Mat44 m = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale);
  290. new (&ioContext) TSGetTrianglesContext(m * mV1, m * mV2, m * mV3);
  291. }
  292. int TriangleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  293. {
  294. static_assert(cGetTrianglesMinTrianglesRequested >= 3, "cGetTrianglesMinTrianglesRequested is too small");
  295. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  296. TSGetTrianglesContext &context = (TSGetTrianglesContext &)ioContext;
  297. // Only return the triangle the 1st time
  298. if (context.mIsDone)
  299. return 0;
  300. context.mIsDone = true;
  301. // Store triangle
  302. context.mV1.StoreFloat3(outTriangleVertices);
  303. context.mV2.StoreFloat3(outTriangleVertices + 1);
  304. context.mV3.StoreFloat3(outTriangleVertices + 2);
  305. // Store material
  306. if (outMaterials != nullptr)
  307. *outMaterials = GetMaterial();
  308. return 1;
  309. }
  310. void TriangleShape::SaveBinaryState(StreamOut &inStream) const
  311. {
  312. ConvexShape::SaveBinaryState(inStream);
  313. inStream.Write(mV1);
  314. inStream.Write(mV2);
  315. inStream.Write(mV3);
  316. inStream.Write(mConvexRadius);
  317. }
  318. void TriangleShape::RestoreBinaryState(StreamIn &inStream)
  319. {
  320. ConvexShape::RestoreBinaryState(inStream);
  321. inStream.Read(mV1);
  322. inStream.Read(mV2);
  323. inStream.Read(mV3);
  324. inStream.Read(mConvexRadius);
  325. }
  326. bool TriangleShape::IsValidScale(Vec3Arg inScale) const
  327. {
  328. return ConvexShape::IsValidScale(inScale) && (mConvexRadius == 0.0f || ScaleHelpers::IsUniformScale(inScale.Abs()));
  329. }
  330. Vec3 TriangleShape::MakeScaleValid(Vec3Arg inScale) const
  331. {
  332. Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
  333. if (mConvexRadius == 0.0f)
  334. return scale;
  335. return scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs());
  336. }
  337. void TriangleShape::sRegister()
  338. {
  339. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Triangle);
  340. f.mConstruct = []() -> Shape * { return new TriangleShape; };
  341. f.mColor = Color::sGreen;
  342. for (EShapeSubType s : sConvexSubShapeTypes)
  343. {
  344. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Triangle, sCollideConvexVsTriangle);
  345. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Triangle, sCastConvexVsTriangle);
  346. // Avoid registering triangle vs triangle as a reversed test to prevent infinite recursion
  347. if (s != EShapeSubType::Triangle)
  348. {
  349. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Triangle, s, CollisionDispatch::sReversedCollideShape);
  350. CollisionDispatch::sRegisterCastShape(EShapeSubType::Triangle, s, CollisionDispatch::sReversedCastShape);
  351. }
  352. }
  353. // Specialized collision functions
  354. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCollideSphereVsTriangle);
  355. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCastSphereVsTriangle);
  356. }
  357. JPH_NAMESPACE_END