TriangleShape.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. mTriangleSuport(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 mTriangleSuport.GetSupport(inDirection);
  89. }
  90. virtual float GetConvexRadius() const override
  91. {
  92. return 0.0f;
  93. }
  94. private:
  95. TriangleConvexSupport mTriangleSuport;
  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. mTriangleSuport(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 = mTriangleSuport.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 mTriangleSuport;
  122. };
  123. const ConvexShape::Support *TriangleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  124. {
  125. switch (inMode)
  126. {
  127. case ESupportMode::IncludeConvexRadius:
  128. if (mConvexRadius > 0.0f)
  129. return new (&inBuffer) TriangleWithConvex(inScale * mV1, inScale * mV2, inScale * mV3, mConvexRadius);
  130. [[fallthrough]];
  131. case ESupportMode::ExcludeConvexRadius:
  132. return new (&inBuffer) TriangleNoConvex(inScale * mV1, inScale * mV2, inScale * mV3);
  133. }
  134. JPH_ASSERT(false);
  135. return nullptr;
  136. }
  137. void TriangleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  138. {
  139. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  140. // Calculate transform with scale
  141. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  142. // Flip triangle if scaled inside out
  143. if (ScaleHelpers::IsInsideOut(inScale))
  144. {
  145. outVertices.push_back(transform * mV1);
  146. outVertices.push_back(transform * mV3);
  147. outVertices.push_back(transform * mV2);
  148. }
  149. else
  150. {
  151. outVertices.push_back(transform * mV1);
  152. outVertices.push_back(transform * mV2);
  153. outVertices.push_back(transform * mV3);
  154. }
  155. }
  156. MassProperties TriangleShape::GetMassProperties() const
  157. {
  158. // Object should always be static, return default mass properties
  159. return MassProperties();
  160. }
  161. Vec3 TriangleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  162. {
  163. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  164. Vec3 cross = (mV2 - mV1).Cross(mV3 - mV1);
  165. float len = cross.Length();
  166. return len != 0.0f? cross / len : Vec3::sAxisY();
  167. }
  168. void TriangleShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
  169. {
  170. // A triangle has no volume
  171. outTotalVolume = outSubmergedVolume = 0.0f;
  172. outCenterOfBuoyancy = Vec3::sZero();
  173. }
  174. #ifdef JPH_DEBUG_RENDERER
  175. void TriangleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  176. {
  177. RVec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  178. RVec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  179. RVec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  180. if (ScaleHelpers::IsInsideOut(inScale))
  181. swap(v1, v2);
  182. if (inDrawWireframe)
  183. inRenderer->DrawWireTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  184. else
  185. inRenderer->DrawTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  186. }
  187. #endif // JPH_DEBUG_RENDERER
  188. bool TriangleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  189. {
  190. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  191. if (fraction < ioHit.mFraction)
  192. {
  193. ioHit.mFraction = fraction;
  194. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  195. return true;
  196. }
  197. return false;
  198. }
  199. void TriangleShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  200. {
  201. // Test shape filter
  202. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  203. return;
  204. // Back facing check
  205. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (mV2 - mV1).Cross(mV3 - mV1).Dot(inRay.mDirection) > 0.0f)
  206. return;
  207. // Test ray against triangle
  208. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  209. if (fraction < ioCollector.GetEarlyOutFraction())
  210. {
  211. // Better hit than the current hit
  212. RayCastResult hit;
  213. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  214. hit.mFraction = fraction;
  215. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  216. ioCollector.AddHit(hit);
  217. }
  218. }
  219. void TriangleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  220. {
  221. // Can't be inside a triangle
  222. }
  223. void TriangleShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  224. {
  225. CollideSoftBodyVerticesVsTriangles collider(inCenterOfMassTransform, inScale);
  226. for (SoftBodyVertex *v = ioVertices, *sbv_end = ioVertices + inNumVertices; v < sbv_end; ++v)
  227. if (v->mInvMass > 0.0f)
  228. {
  229. collider.StartVertex(*v);
  230. collider.ProcessTriangle(mV1, mV2, mV3);
  231. collider.FinishVertex(*v, inCollidingShapeIndex);
  232. }
  233. }
  234. 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)
  235. {
  236. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  237. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  238. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  239. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  240. CollideConvexVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  241. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  242. }
  243. 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)
  244. {
  245. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  246. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  247. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  248. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  249. CollideSphereVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  250. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  251. }
  252. 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)
  253. {
  254. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  255. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  256. CastConvexVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  257. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  258. }
  259. 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)
  260. {
  261. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  262. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  263. CastSphereVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  264. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  265. }
  266. void TriangleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  267. {
  268. Vec3 scale;
  269. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  270. TransformedShape ts(RVec3(transform.GetTranslation()), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  271. ts.SetShapeScale(mConvexRadius == 0.0f? scale : scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()));
  272. ioCollector.AddHit(ts);
  273. }
  274. class TriangleShape::TSGetTrianglesContext
  275. {
  276. public:
  277. TSGetTrianglesContext(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) : mV1(inV1), mV2(inV2), mV3(inV3) { }
  278. Vec3 mV1;
  279. Vec3 mV2;
  280. Vec3 mV3;
  281. bool mIsDone = false;
  282. };
  283. void TriangleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  284. {
  285. static_assert(sizeof(TSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  286. JPH_ASSERT(IsAligned(&ioContext, alignof(TSGetTrianglesContext)));
  287. Mat44 m = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale);
  288. new (&ioContext) TSGetTrianglesContext(m * mV1, m * mV2, m * mV3);
  289. }
  290. int TriangleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  291. {
  292. static_assert(cGetTrianglesMinTrianglesRequested >= 3, "cGetTrianglesMinTrianglesRequested is too small");
  293. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  294. TSGetTrianglesContext &context = (TSGetTrianglesContext &)ioContext;
  295. // Only return the triangle the 1st time
  296. if (context.mIsDone)
  297. return 0;
  298. context.mIsDone = true;
  299. // Store triangle
  300. context.mV1.StoreFloat3(outTriangleVertices);
  301. context.mV2.StoreFloat3(outTriangleVertices + 1);
  302. context.mV3.StoreFloat3(outTriangleVertices + 2);
  303. // Store material
  304. if (outMaterials != nullptr)
  305. *outMaterials = GetMaterial();
  306. return 1;
  307. }
  308. void TriangleShape::SaveBinaryState(StreamOut &inStream) const
  309. {
  310. ConvexShape::SaveBinaryState(inStream);
  311. inStream.Write(mV1);
  312. inStream.Write(mV2);
  313. inStream.Write(mV3);
  314. inStream.Write(mConvexRadius);
  315. }
  316. void TriangleShape::RestoreBinaryState(StreamIn &inStream)
  317. {
  318. ConvexShape::RestoreBinaryState(inStream);
  319. inStream.Read(mV1);
  320. inStream.Read(mV2);
  321. inStream.Read(mV3);
  322. inStream.Read(mConvexRadius);
  323. }
  324. bool TriangleShape::IsValidScale(Vec3Arg inScale) const
  325. {
  326. return ConvexShape::IsValidScale(inScale) && (mConvexRadius == 0.0f || ScaleHelpers::IsUniformScale(inScale.Abs()));
  327. }
  328. void TriangleShape::sRegister()
  329. {
  330. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Triangle);
  331. f.mConstruct = []() -> Shape * { return new TriangleShape; };
  332. f.mColor = Color::sGreen;
  333. for (EShapeSubType s : sConvexSubShapeTypes)
  334. {
  335. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Triangle, sCollideConvexVsTriangle);
  336. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Triangle, sCastConvexVsTriangle);
  337. }
  338. // Specialized collision functions
  339. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCollideSphereVsTriangle);
  340. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCastSphereVsTriangle);
  341. }
  342. JPH_NAMESPACE_END