MeshShape.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Collision/Shape/Shape.h>
  5. #include <Jolt/Physics/Collision/PhysicsMaterial.h>
  6. #include <Jolt/Core/ByteBuffer.h>
  7. #include <Jolt/Geometry/Triangle.h>
  8. #include <Jolt/Geometry/IndexedTriangle.h>
  9. #ifdef JPH_DEBUG_RENDERER
  10. #include <Jolt/Renderer/DebugRenderer.h>
  11. #endif // JPH_DEBUG_RENDERER
  12. JPH_NAMESPACE_BEGIN
  13. class ConvexShape;
  14. class CollideShapeSettings;
  15. /// Class that constructs a MeshShape
  16. class MeshShapeSettings final : public ShapeSettings
  17. {
  18. public:
  19. JPH_DECLARE_SERIALIZABLE_VIRTUAL(MeshShapeSettings)
  20. /// Default constructor for deserialization
  21. MeshShapeSettings() = default;
  22. /// Create a mesh shape.
  23. MeshShapeSettings(const TriangleList &inTriangles, const PhysicsMaterialList &inMaterials = PhysicsMaterialList());
  24. MeshShapeSettings(const VertexList &inVertices, const IndexedTriangleList &inTriangles, const PhysicsMaterialList &inMaterials = PhysicsMaterialList());
  25. /// Sanitize the mesh data. Remove duplicate and degenerate triangles.
  26. void Sanitize();
  27. // See: ShapeSettings
  28. virtual ShapeResult Create() const override;
  29. /// Mesh data.
  30. VertexList mTriangleVertices; ///< Vertices belonging to mIndexedTriangles
  31. IndexedTriangleList mIndexedTriangles; ///< Original list of indexed triangles
  32. /// Materials assigned to the triangles. Each triangle specifies which material it uses through its mMaterialIndex
  33. PhysicsMaterialList mMaterials;
  34. /// Maximum number of triangles in each leaf of the axis aligned box tree. This is a balance between memory and performance. Can be in the range [1, MeshShape::MaxTrianglesPerLeaf].
  35. /// Sensible values are between 4 (for better performance) and 8 (for less memory usage).
  36. uint mMaxTrianglesPerLeaf = 8;
  37. };
  38. /// A mesh shape, consisting of triangles. Cannot be used as a dynamic object.
  39. class MeshShape final : public Shape
  40. {
  41. public:
  42. JPH_OVERRIDE_NEW_DELETE
  43. /// Constructor
  44. MeshShape() : Shape(EShapeType::Mesh, EShapeSubType::Mesh) { }
  45. MeshShape(const MeshShapeSettings &inSettings, ShapeResult &outResult);
  46. // See Shape::MustBeStatic
  47. virtual bool MustBeStatic() const override { return true; }
  48. // See Shape::GetLocalBounds
  49. virtual AABox GetLocalBounds() const override;
  50. // See Shape::GetSubShapeIDBitsRecursive
  51. virtual uint GetSubShapeIDBitsRecursive() const override;
  52. // See Shape::GetInnerRadius
  53. virtual float GetInnerRadius() const override { return 0.0f; }
  54. // See Shape::GetMassProperties
  55. virtual MassProperties GetMassProperties() const override;
  56. // See Shape::GetMaterial
  57. virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
  58. /// Get the list of all materials
  59. const PhysicsMaterialList & GetMaterialList() const { return mMaterials; }
  60. /// Determine which material index a particular sub shape uses (note that if there are no materials this function will return 0 so check the array size)
  61. /// Note: This could for example be used to create a decorator shape around a mesh shape that overrides the GetMaterial call to replace a material with another material.
  62. uint GetMaterialIndex(const SubShapeID &inSubShapeID) const;
  63. // See Shape::GetSurfaceNormal
  64. virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
  65. // See Shape::GetSupportingFace
  66. virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
  67. #ifdef JPH_DEBUG_RENDERER
  68. // See Shape::Draw
  69. virtual void Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
  70. #endif // JPH_DEBUG_RENDERER
  71. // See Shape::CastRay
  72. virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
  73. virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
  74. /// See: Shape::CollidePoint
  75. /// Note that for CollidePoint to work for a mesh shape, the mesh needs to be closed (a manifold) or multiple non-intersecting manifolds. Triangles may be facing the interior of the manifold.
  76. /// Insideness is tested by counting the amount of triangles encountered when casting an infinite ray from inPoint. If the number of hits is odd we're inside, if it's even we're outside.
  77. virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
  78. // See Shape::GetTrianglesStart
  79. virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
  80. // See Shape::GetTrianglesNext
  81. virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
  82. // See Shape::GetSubmergedVolume
  83. virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy) const override { JPH_ASSERT(false, "Not supported"); }
  84. // See Shape
  85. virtual void SaveBinaryState(StreamOut &inStream) const override;
  86. virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const override;
  87. virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials) override;
  88. // See Shape::GetStats
  89. virtual Stats GetStats() const override;
  90. // See Shape::GetVolume
  91. virtual float GetVolume() const override { return 0; }
  92. #ifdef JPH_DEBUG_RENDERER
  93. // Settings
  94. static bool sDrawTriangleGroups;
  95. static bool sDrawTriangleOutlines;
  96. #endif // JPH_DEBUG_RENDERER
  97. // Register shape functions with the registry
  98. static void sRegister();
  99. protected:
  100. // See: Shape::RestoreBinaryState
  101. virtual void RestoreBinaryState(StreamIn &inStream) override;
  102. private:
  103. struct MSGetTrianglesContext; ///< Context class for GetTrianglesStart/Next
  104. static constexpr int NumTriangleBits = 3; ///< How many bits to reserve to encode the triangle index
  105. static constexpr int MaxTrianglesPerLeaf = 1 << NumTriangleBits; ///< Number of triangles that are stored max per leaf aabb node
  106. /// Find and flag active edges
  107. static void sFindActiveEdges(const VertexList &inVertices, IndexedTriangleList &ioIndices);
  108. /// Visit the entire tree using a visitor pattern
  109. template <class Visitor>
  110. void WalkTree(Visitor &ioVisitor) const;
  111. /// Same as above but with a callback per triangle instead of per block of triangles
  112. template <class Visitor>
  113. void WalkTreePerTriangle(const SubShapeIDCreator &inSubShapeIDCreator2, Visitor &ioVisitor) const;
  114. /// Decode a sub shape ID
  115. inline void DecodeSubShapeID(const SubShapeID &inSubShapeID, const void *&outTriangleBlock, uint32 &outTriangleIndex) const;
  116. // Helper functions called by CollisionDispatch
  117. static void 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, const ShapeFilter &inShapeFilter);
  118. static void 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, const ShapeFilter &inShapeFilter);
  119. static void sCastConvexVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
  120. static void sCastSphereVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
  121. /// Materials assigned to the triangles. Each triangle specifies which material it uses through its mMaterialIndex
  122. PhysicsMaterialList mMaterials;
  123. ByteBuffer mTree; ///< Resulting packed data structure
  124. /// 8 bit flags stored per triangle
  125. enum ETriangleFlags
  126. {
  127. /// Material index
  128. FLAGS_MATERIAL_BITS = 5,
  129. FLAGS_MATERIAL_MASK = (1 << FLAGS_MATERIAL_BITS) - 1,
  130. /// Active edge bits
  131. FLAGS_ACTIVE_EGDE_SHIFT = FLAGS_MATERIAL_BITS,
  132. FLAGS_ACTIVE_EDGE_BITS = 3,
  133. FLAGS_ACTIVE_EDGE_MASK = (1 << FLAGS_ACTIVE_EDGE_BITS) - 1
  134. };
  135. #ifdef JPH_DEBUG_RENDERER
  136. mutable DebugRenderer::GeometryRef mGeometry; ///< Debug rendering data
  137. mutable bool mCachedTrianglesColoredPerGroup = false; ///< This is used to regenerate the triangle batch if the drawing settings change
  138. mutable bool mCachedUseMaterialColors = false; ///< This is used to regenerate the triangle batch if the drawing settings change
  139. #endif // JPH_DEBUG_RENDERER
  140. };
  141. JPH_NAMESPACE_END