TriangleShape.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/Collision/Shape/TriangleShape.h>
  5. #include <Physics/Collision/Shape/ScaleHelpers.h>
  6. #include <Physics/Collision/Shape/GetTrianglesContext.h>
  7. #include <Physics/Collision/RayCast.h>
  8. #include <Physics/Collision/ShapeCast.h>
  9. #include <Physics/Collision/CastResult.h>
  10. #include <Physics/Collision/CollidePointResult.h>
  11. #include <Physics/Collision/TransformedShape.h>
  12. #include <Physics/Collision/CastConvexVsTriangles.h>
  13. #include <Physics/Collision/CastSphereVsTriangles.h>
  14. #include <Physics/Collision/CollideConvexVsTriangles.h>
  15. #include <Physics/Collision/CollideSphereVsTriangles.h>
  16. #include <Physics/Collision/CollisionDispatch.h>
  17. #include <Geometry/ConvexSupport.h>
  18. #include <Geometry/RayTriangle.h>
  19. #include <ObjectStream/TypeDeclarations.h>
  20. #include <Core/StreamIn.h>
  21. #include <Core/StreamOut.h>
  22. #ifdef JPH_DEBUG_RENDERER
  23. #include <Renderer/DebugRenderer.h>
  24. #endif // JPH_DEBUG_RENDERER
  25. namespace JPH {
  26. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TriangleShapeSettings)
  27. {
  28. JPH_ADD_BASE_CLASS(TriangleShapeSettings, ConvexShapeSettings)
  29. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV1)
  30. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV2)
  31. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV3)
  32. JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mConvexRadius)
  33. }
  34. ShapeSettings::ShapeResult TriangleShapeSettings::Create() const
  35. {
  36. if (mCachedResult.IsEmpty())
  37. Ref<Shape> shape = new TriangleShape(*this, mCachedResult);
  38. return mCachedResult;
  39. }
  40. TriangleShape::TriangleShape(const TriangleShapeSettings &inSettings, ShapeResult &outResult) :
  41. ConvexShape(EShapeSubType::Triangle, inSettings, outResult),
  42. mV1(inSettings.mV1),
  43. mV2(inSettings.mV2),
  44. mV3(inSettings.mV3),
  45. mConvexRadius(inSettings.mConvexRadius)
  46. {
  47. if (inSettings.mConvexRadius < 0.0f)
  48. {
  49. outResult.SetError("Invalid convex radius");
  50. return;
  51. }
  52. outResult.Set(this);
  53. }
  54. AABox TriangleShape::GetLocalBounds() const
  55. {
  56. AABox bounds(mV1, mV1);
  57. bounds.Encapsulate(mV2);
  58. bounds.Encapsulate(mV3);
  59. bounds.ExpandBy(Vec3::sReplicate(mConvexRadius));
  60. return bounds;
  61. }
  62. AABox TriangleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
  63. {
  64. JPH_ASSERT(IsValidScale(inScale));
  65. Vec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  66. Vec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  67. Vec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  68. AABox bounds(v1, v1);
  69. bounds.Encapsulate(v2);
  70. bounds.Encapsulate(v3);
  71. bounds.ExpandBy(inScale * mConvexRadius);
  72. return bounds;
  73. }
  74. class TriangleShape::TriangleNoConvex final : public Support
  75. {
  76. public:
  77. TriangleNoConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) :
  78. mTriangleSuport(inV1, inV2, inV3)
  79. {
  80. static_assert(sizeof(TriangleNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  81. JPH_ASSERT(IsAligned(this, alignof(TriangleNoConvex)));
  82. }
  83. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  84. {
  85. return mTriangleSuport.GetSupport(inDirection);
  86. }
  87. virtual float GetConvexRadius() const override
  88. {
  89. return 0.0f;
  90. }
  91. private:
  92. TriangleConvexSupport mTriangleSuport;
  93. };
  94. class TriangleShape::TriangleWithConvex final : public Support
  95. {
  96. public:
  97. TriangleWithConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, float inConvexRadius) :
  98. mConvexRadius(inConvexRadius),
  99. mTriangleSuport(inV1, inV2, inV3)
  100. {
  101. static_assert(sizeof(TriangleWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
  102. JPH_ASSERT(IsAligned(this, alignof(TriangleWithConvex)));
  103. }
  104. virtual Vec3 GetSupport(Vec3Arg inDirection) const override
  105. {
  106. Vec3 support = mTriangleSuport.GetSupport(inDirection);
  107. float len = inDirection.Length();
  108. if (len > 0.0f)
  109. support += (mConvexRadius / len) * inDirection;
  110. return support;
  111. }
  112. virtual float GetConvexRadius() const override
  113. {
  114. return mConvexRadius;
  115. }
  116. private:
  117. float mConvexRadius;
  118. TriangleConvexSupport mTriangleSuport;
  119. };
  120. const ConvexShape::Support *TriangleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
  121. {
  122. switch (inMode)
  123. {
  124. case ESupportMode::IncludeConvexRadius:
  125. if (mConvexRadius > 0.0f)
  126. return new (&inBuffer) TriangleWithConvex(inScale * mV1, inScale * mV2, inScale * mV3, mConvexRadius);
  127. [[fallthrough]];
  128. case ESupportMode::ExcludeConvexRadius:
  129. return new (&inBuffer) TriangleNoConvex(inScale * mV1, inScale * mV2, inScale * mV3);
  130. }
  131. JPH_ASSERT(false);
  132. return nullptr;
  133. }
  134. void TriangleShape::GetSupportingFace(Vec3Arg inDirection, Vec3Arg inScale, SupportingFace &outVertices) const
  135. {
  136. outVertices.push_back(inScale * mV1);
  137. outVertices.push_back(inScale * mV2);
  138. outVertices.push_back(inScale * mV3);
  139. }
  140. MassProperties TriangleShape::GetMassProperties() const
  141. {
  142. // Object should always be static, return default mass properties
  143. return MassProperties();
  144. }
  145. Vec3 TriangleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  146. {
  147. JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
  148. Vec3 cross = (mV2 - mV1).Cross(mV3 - mV1);
  149. float len = cross.Length();
  150. return len != 0.0f? cross / len : Vec3::sAxisY();
  151. }
  152. void TriangleShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy) const
  153. {
  154. // A triangle has no volume
  155. outTotalVolume = outSubmergedVolume = 0.0f;
  156. outCenterOfBuoyancy = Vec3::sZero();
  157. }
  158. #ifdef JPH_DEBUG_RENDERER
  159. void TriangleShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  160. {
  161. Vec3 v1 = inCenterOfMassTransform * (inScale * mV1);
  162. Vec3 v2 = inCenterOfMassTransform * (inScale * mV2);
  163. Vec3 v3 = inCenterOfMassTransform * (inScale * mV3);
  164. if (ScaleHelpers::IsInsideOut(inScale))
  165. swap(v1, v2);
  166. if (inDrawWireframe)
  167. inRenderer->DrawWireTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  168. else
  169. inRenderer->DrawTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
  170. }
  171. #endif // JPH_DEBUG_RENDERER
  172. bool TriangleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  173. {
  174. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  175. if (fraction < ioHit.mFraction)
  176. {
  177. ioHit.mFraction = fraction;
  178. ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  179. return true;
  180. }
  181. return false;
  182. }
  183. void TriangleShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const
  184. {
  185. // Back facing check
  186. if (inRayCastSettings.mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (mV2 - mV1).Cross(mV3 - mV1).Dot(inRay.mDirection) > 0.0f)
  187. return;
  188. // Test ray against triangle
  189. float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
  190. if (fraction < ioCollector.GetEarlyOutFraction())
  191. {
  192. // Better hit than the current hit
  193. RayCastResult hit;
  194. hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
  195. hit.mFraction = fraction;
  196. hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
  197. ioCollector.AddHit(hit);
  198. }
  199. }
  200. void TriangleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const
  201. {
  202. // Can't be inside a triangle
  203. }
  204. 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)
  205. {
  206. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  207. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  208. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  209. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  210. CollideConvexVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  211. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  212. }
  213. 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)
  214. {
  215. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  216. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  217. JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
  218. const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
  219. CollideSphereVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  220. collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
  221. }
  222. void TriangleShape::sCastConvexVsTriangle(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  223. {
  224. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  225. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  226. CastConvexVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  227. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  228. }
  229. void TriangleShape::sCastSphereVsTriangle(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  230. {
  231. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
  232. const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
  233. CastSphereVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  234. caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
  235. }
  236. void TriangleShape::TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const
  237. {
  238. Vec3 scale;
  239. Mat44 transform = inCenterOfMassTransform.Decompose(scale);
  240. TransformedShape ts(transform.GetTranslation(), transform.GetRotation().GetQuaternion(), this, BodyID(), SubShapeIDCreator());
  241. ts.SetShapeScale(mConvexRadius == 0.0f? scale : scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs()));
  242. ioCollector.AddHit(ts);
  243. }
  244. class TriangleShape::TSGetTrianglesContext
  245. {
  246. public:
  247. TSGetTrianglesContext(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) : mV1(inV1), mV2(inV2), mV3(inV3) { }
  248. Vec3 mV1;
  249. Vec3 mV2;
  250. Vec3 mV3;
  251. bool mIsDone = false;
  252. };
  253. void TriangleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  254. {
  255. static_assert(sizeof(TSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  256. JPH_ASSERT(IsAligned(&ioContext, alignof(TSGetTrianglesContext)));
  257. Mat44 m = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale);
  258. new (&ioContext) TSGetTrianglesContext(m * mV1, m * mV2, m * mV3);
  259. }
  260. int TriangleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  261. {
  262. static_assert(cGetTrianglesMinTrianglesRequested >= 3, "cGetTrianglesMinTrianglesRequested is too small");
  263. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  264. TSGetTrianglesContext &context = (TSGetTrianglesContext &)ioContext;
  265. // Only return the triangle the 1st time
  266. if (context.mIsDone)
  267. return 0;
  268. context.mIsDone = true;
  269. // Store triangle
  270. context.mV1.StoreFloat3(outTriangleVertices);
  271. context.mV2.StoreFloat3(outTriangleVertices + 1);
  272. context.mV3.StoreFloat3(outTriangleVertices + 2);
  273. // Store material
  274. if (outMaterials != nullptr)
  275. *outMaterials = GetMaterial();
  276. return 1;
  277. }
  278. void TriangleShape::SaveBinaryState(StreamOut &inStream) const
  279. {
  280. ConvexShape::SaveBinaryState(inStream);
  281. inStream.Write(mV1);
  282. inStream.Write(mV2);
  283. inStream.Write(mV3);
  284. inStream.Write(mConvexRadius);
  285. }
  286. void TriangleShape::RestoreBinaryState(StreamIn &inStream)
  287. {
  288. ConvexShape::RestoreBinaryState(inStream);
  289. inStream.Read(mV1);
  290. inStream.Read(mV2);
  291. inStream.Read(mV3);
  292. inStream.Read(mConvexRadius);
  293. }
  294. bool TriangleShape::IsValidScale(Vec3Arg inScale) const
  295. {
  296. return ConvexShape::IsValidScale(inScale) && (mConvexRadius == 0.0f || ScaleHelpers::IsUniformScale(inScale.Abs()));
  297. }
  298. void TriangleShape::sRegister()
  299. {
  300. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Triangle);
  301. f.mConstruct = []() -> Shape * { return new TriangleShape; };
  302. f.mColor = Color::sGreen;
  303. for (EShapeSubType s : sConvexSubShapeTypes)
  304. {
  305. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Triangle, sCollideConvexVsTriangle);
  306. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Triangle, sCastConvexVsTriangle);
  307. }
  308. // Specialized collision functions
  309. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCollideSphereVsTriangle);
  310. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCastSphereVsTriangle);
  311. }
  312. } // JPH