DebugRenderer.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #ifndef JPH_DEBUG_RENDERER
  6. #error This file should only be included when JPH_DEBUG_RENDERER is defined
  7. #endif // !JPH_DEBUG_RENDERER
  8. #ifndef JPH_DEBUG_RENDERER_EXPORT
  9. // By default export the debug renderer
  10. #define JPH_DEBUG_RENDERER_EXPORT JPH_EXPORT
  11. #endif // !JPH_DEBUG_RENDERER_EXPORT
  12. #include <Jolt/Core/Color.h>
  13. #include <Jolt/Core/Reference.h>
  14. #include <Jolt/Core/HashCombine.h>
  15. #include <Jolt/Core/UnorderedMap.h>
  16. #include <Jolt/Math/Float2.h>
  17. #include <Jolt/Geometry/IndexedTriangle.h>
  18. #include <Jolt/Geometry/AABox.h>
  19. JPH_NAMESPACE_BEGIN
  20. class OrientedBox;
  21. /// Simple triangle renderer for debugging purposes.
  22. class JPH_DEBUG_RENDERER_EXPORT DebugRenderer
  23. {
  24. public:
  25. JPH_OVERRIDE_NEW_DELETE
  26. /// Constructor
  27. DebugRenderer();
  28. virtual ~DebugRenderer();
  29. /// Call once after frame is complete. Releases unused dynamically generated geometry assets.
  30. void NextFrame();
  31. /// Draw line
  32. virtual void DrawLine(RVec3Arg inFrom, RVec3Arg inTo, ColorArg inColor) = 0;
  33. /// Draw wireframe box
  34. void DrawWireBox(const AABox &inBox, ColorArg inColor);
  35. void DrawWireBox(const OrientedBox &inBox, ColorArg inColor);
  36. void DrawWireBox(RMat44Arg inMatrix, const AABox &inBox, ColorArg inColor);
  37. /// Draw a marker on a position
  38. void DrawMarker(RVec3Arg inPosition, ColorArg inColor, float inSize);
  39. /// Draw an arrow
  40. void DrawArrow(RVec3Arg inFrom, RVec3Arg inTo, ColorArg inColor, float inSize);
  41. /// Draw coordinate system (3 arrows, x = red, y = green, z = blue)
  42. void DrawCoordinateSystem(RMat44Arg inTransform, float inSize = 1.0f);
  43. /// Draw a plane through inPoint with normal inNormal
  44. void DrawPlane(RVec3Arg inPoint, Vec3Arg inNormal, ColorArg inColor, float inSize);
  45. /// Draw wireframe triangle
  46. void DrawWireTriangle(RVec3Arg inV1, RVec3Arg inV2, RVec3Arg inV3, ColorArg inColor);
  47. /// Draw a wireframe polygon
  48. template <class VERTEX_ARRAY>
  49. void DrawWirePolygon(RMat44Arg inTransform, const VERTEX_ARRAY &inVertices, ColorArg inColor, float inArrowSize = 0.0f) { for (typename VERTEX_ARRAY::size_type i = 0; i < inVertices.size(); ++i) DrawArrow(inTransform * inVertices[i], inTransform * inVertices[(i + 1) % inVertices.size()], inColor, inArrowSize); }
  50. /// Draw wireframe sphere
  51. void DrawWireSphere(RVec3Arg inCenter, float inRadius, ColorArg inColor, int inLevel = 3);
  52. void DrawWireUnitSphere(RMat44Arg inMatrix, ColorArg inColor, int inLevel = 3);
  53. /// Enum that determines if a shadow should be cast or not
  54. enum class ECastShadow
  55. {
  56. On, // This shape should cast a shadow
  57. Off // This shape should not cast a shadow
  58. };
  59. /// Determines how triangles are drawn
  60. enum class EDrawMode
  61. {
  62. Solid, ///< Draw as a solid shape
  63. Wireframe, ///< Draw as wireframe
  64. };
  65. /// Draw a single back face culled triangle
  66. virtual void DrawTriangle(RVec3Arg inV1, RVec3Arg inV2, RVec3Arg inV3, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::Off) = 0;
  67. /// Draw a box
  68. void DrawBox(const AABox &inBox, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  69. void DrawBox(RMat44Arg inMatrix, const AABox &inBox, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  70. /// Draw a sphere
  71. void DrawSphere(RVec3Arg inCenter, float inRadius, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  72. void DrawUnitSphere(RMat44Arg inMatrix, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  73. /// Draw a capsule with one half sphere at (0, -inHalfHeightOfCylinder, 0) and the other half sphere at (0, inHalfHeightOfCylinder, 0) and radius inRadius.
  74. /// The capsule will be transformed by inMatrix.
  75. void DrawCapsule(RMat44Arg inMatrix, float inHalfHeightOfCylinder, float inRadius, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  76. /// Draw a cylinder with top (0, inHalfHeight, 0) and bottom (0, -inHalfHeight, 0) and radius inRadius.
  77. /// The cylinder will be transformed by inMatrix
  78. void DrawCylinder(RMat44Arg inMatrix, float inHalfHeight, float inRadius, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  79. /// Draw a bottomless cone.
  80. /// @param inTop Top of cone, center of base is at inTop + inAxis.
  81. /// @param inAxis Height and direction of cone
  82. /// @param inPerpendicular Perpendicular vector to inAxis.
  83. /// @param inHalfAngle Specifies the cone angle in radians (angle measured between inAxis and cone surface).
  84. /// @param inLength The length of the cone.
  85. /// @param inColor Color to use for drawing the cone.
  86. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  87. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  88. void DrawOpenCone(RVec3Arg inTop, Vec3Arg inAxis, Vec3Arg inPerpendicular, float inHalfAngle, float inLength, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  89. /// Draws cone rotation limits as used by the SwingTwistConstraintPart.
  90. /// @param inMatrix Matrix that transforms from constraint space to world space
  91. /// @param inSwingYHalfAngle See SwingTwistConstraintPart
  92. /// @param inSwingZHalfAngle See SwingTwistConstraintPart
  93. /// @param inEdgeLength Size of the edge of the cone shape
  94. /// @param inColor Color to use for drawing the cone.
  95. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  96. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  97. void DrawSwingConeLimits(RMat44Arg inMatrix, float inSwingYHalfAngle, float inSwingZHalfAngle, float inEdgeLength, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  98. /// Draws rotation limits as used by the SwingTwistConstraintPart.
  99. /// @param inMatrix Matrix that transforms from constraint space to world space
  100. /// @param inMinSwingYAngle See SwingTwistConstraintPart
  101. /// @param inMaxSwingYAngle See SwingTwistConstraintPart
  102. /// @param inMinSwingZAngle See SwingTwistConstraintPart
  103. /// @param inMaxSwingZAngle See SwingTwistConstraintPart
  104. /// @param inEdgeLength Size of the edge of the cone shape
  105. /// @param inColor Color to use for drawing the cone.
  106. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  107. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  108. void DrawSwingPyramidLimits(RMat44Arg inMatrix, float inMinSwingYAngle, float inMaxSwingYAngle, float inMinSwingZAngle, float inMaxSwingZAngle, float inEdgeLength, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  109. /// Draw a pie (part of a circle).
  110. /// @param inCenter The center of the circle.
  111. /// @param inRadius Radius of the circle.
  112. /// @param inNormal The plane normal in which the pie resides.
  113. /// @param inAxis The axis that defines an angle of 0 radians.
  114. /// @param inMinAngle The pie will be drawn between [inMinAngle, inMaxAngle] (in radians).
  115. /// @param inMaxAngle The pie will be drawn between [inMinAngle, inMaxAngle] (in radians).
  116. /// @param inColor Color to use for drawing the pie.
  117. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  118. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  119. void DrawPie(RVec3Arg inCenter, float inRadius, Vec3Arg inNormal, Vec3Arg inAxis, float inMinAngle, float inMaxAngle, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  120. /// Singleton instance
  121. static DebugRenderer * sInstance;
  122. /// Vertex format used by the triangle renderer
  123. class Vertex
  124. {
  125. public:
  126. Float3 mPosition;
  127. Float3 mNormal;
  128. Float2 mUV;
  129. Color mColor;
  130. };
  131. /// A single triangle
  132. class JPH_DEBUG_RENDERER_EXPORT Triangle
  133. {
  134. public:
  135. Triangle() = default;
  136. Triangle(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, ColorArg inColor);
  137. Triangle(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, ColorArg inColor, Vec3Arg inUVOrigin, Vec3Arg inUVDirection);
  138. Vertex mV[3];
  139. };
  140. /// Handle for a batch of triangles
  141. using Batch = Ref<RefTargetVirtual>;
  142. /// A single level of detail
  143. class LOD
  144. {
  145. public:
  146. Batch mTriangleBatch;
  147. float mDistance;
  148. };
  149. /// A geometry primitive containing triangle batches for various lods
  150. class Geometry : public RefTarget<Geometry>
  151. {
  152. public:
  153. JPH_OVERRIDE_NEW_DELETE
  154. /// Constructor
  155. Geometry(const AABox &inBounds) : mBounds(inBounds) { }
  156. Geometry(const Batch &inBatch, const AABox &inBounds) : mBounds(inBounds) { mLODs.push_back({ inBatch, FLT_MAX }); }
  157. /// All level of details for this mesh
  158. Array<LOD> mLODs;
  159. /// Bounding box that encapsulates all LODs
  160. AABox mBounds;
  161. };
  162. /// Handle for a lodded triangle batch
  163. using GeometryRef = Ref<Geometry>;
  164. /// Calculate bounding box for a batch of triangles
  165. static AABox sCalculateBounds(const Vertex *inVertices, int inVertexCount);
  166. /// Create a batch of triangles that can be drawn efficiently
  167. virtual Batch CreateTriangleBatch(const Triangle *inTriangles, int inTriangleCount) = 0;
  168. virtual Batch CreateTriangleBatch(const Vertex *inVertices, int inVertexCount, const uint32 *inIndices, int inIndexCount) = 0;
  169. Batch CreateTriangleBatch(const Array<Triangle> &inTriangles) { return CreateTriangleBatch(inTriangles.empty()? nullptr : &inTriangles[0], int(inTriangles.size())); }
  170. Batch CreateTriangleBatch(const Array<Vertex> &inVertices, const Array<uint32> &inIndices) { return CreateTriangleBatch(inVertices.empty()? nullptr : &inVertices[0], int(inVertices.size()), inIndices.empty()? nullptr : &inIndices[0], int(inIndices.size())); }
  171. Batch CreateTriangleBatch(const VertexList &inVertices, const IndexedTriangleNoMaterialList &inTriangles);
  172. /// Create a primitive for a convex shape using its support function
  173. using SupportFunction = function<Vec3 (Vec3Arg inDirection)>;
  174. Batch CreateTriangleBatchForConvex(SupportFunction inGetSupport, int inLevel, AABox *outBounds = nullptr);
  175. GeometryRef CreateTriangleGeometryForConvex(SupportFunction inGetSupport);
  176. /// Determines which polygons are culled
  177. enum class ECullMode
  178. {
  179. CullBackFace, ///< Don't draw backfacing polygons
  180. CullFrontFace, ///< Don't draw front facing polygons
  181. Off ///< Don't do culling and draw both sides
  182. };
  183. /// Draw some geometry
  184. /// @param inModelMatrix is the matrix that transforms the geometry to world space.
  185. /// @param inWorldSpaceBounds is the bounding box of the geometry after transforming it into world space.
  186. /// @param inLODScaleSq is the squared scale of the model matrix, it is multiplied with the LOD distances in inGeometry to calculate the real LOD distance (so a number > 1 will force a higher LOD).
  187. /// @param inModelColor is the color with which to multiply the vertex colors in inGeometry.
  188. /// @param inGeometry The geometry to draw.
  189. /// @param inCullMode determines which polygons are culled.
  190. /// @param inCastShadow determines if this geometry should cast a shadow or not.
  191. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  192. virtual void DrawGeometry(RMat44Arg inModelMatrix, const AABox &inWorldSpaceBounds, float inLODScaleSq, ColorArg inModelColor, const GeometryRef &inGeometry, ECullMode inCullMode = ECullMode::CullBackFace, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid) = 0;
  193. void DrawGeometry(RMat44Arg inModelMatrix, ColorArg inModelColor, const GeometryRef &inGeometry, ECullMode inCullMode = ECullMode::CullBackFace, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid) { DrawGeometry(inModelMatrix, inGeometry->mBounds.Transformed(inModelMatrix), max(max(inModelMatrix.GetAxisX().LengthSq(), inModelMatrix.GetAxisY().LengthSq()), inModelMatrix.GetAxisZ().LengthSq()), inModelColor, inGeometry, inCullMode, inCastShadow, inDrawMode); }
  194. /// Draw text
  195. virtual void DrawText3D(RVec3Arg inPosition, const string_view &inString, ColorArg inColor = Color::sWhite, float inHeight = 0.5f) = 0;
  196. protected:
  197. /// Initialize the system, must be called from the constructor of the DebugRenderer implementation
  198. void Initialize();
  199. private:
  200. /// Recursive helper function for DrawWireUnitSphere
  201. void DrawWireUnitSphereRecursive(RMat44Arg inMatrix, ColorArg inColor, Vec3Arg inDir1, Vec3Arg inDir2, Vec3Arg inDir3, int inLevel);
  202. /// Helper functions to create a box
  203. void CreateQuad(Array<uint32> &ioIndices, Array<Vertex> &ioVertices, Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, Vec3Arg inV4);
  204. /// Helper functions to create a vertex and index buffer for a sphere
  205. void Create8thSphereRecursive(Array<uint32> &ioIndices, Array<Vertex> &ioVertices, Vec3Arg inDir1, uint32 &ioIdx1, Vec3Arg inDir2, uint32 &ioIdx2, Vec3Arg inDir3, uint32 &ioIdx3, const Float2 &inUV, SupportFunction inGetSupport, int inLevel);
  206. void Create8thSphere(Array<uint32> &ioIndices, Array<Vertex> &ioVertices, Vec3Arg inDir1, Vec3Arg inDir2, Vec3Arg inDir3, const Float2 &inUV, SupportFunction inGetSupport, int inLevel);
  207. /// Helper function for DrawSwingConeLimits and DrawSwingPyramidLimits
  208. Geometry * CreateSwingLimitGeometry(int inNumSegments, const Vec3 *inVertices);
  209. // Predefined shapes
  210. GeometryRef mBox;
  211. GeometryRef mSphere;
  212. GeometryRef mCapsuleTop;
  213. GeometryRef mCapsuleMid;
  214. GeometryRef mCapsuleBottom;
  215. GeometryRef mOpenCone;
  216. GeometryRef mCylinder;
  217. struct SwingConeLimits
  218. {
  219. bool operator == (const SwingConeLimits &inRHS) const
  220. {
  221. return mSwingYHalfAngle == inRHS.mSwingYHalfAngle
  222. && mSwingZHalfAngle == inRHS.mSwingZHalfAngle;
  223. }
  224. float mSwingYHalfAngle;
  225. float mSwingZHalfAngle;
  226. };
  227. JPH_MAKE_HASH_STRUCT(SwingConeLimits, SwingConeLimitsHasher, t.mSwingYHalfAngle, t.mSwingZHalfAngle)
  228. using SwingConeBatches = UnorderedMap<SwingConeLimits, GeometryRef, SwingConeLimitsHasher>;
  229. SwingConeBatches mSwingConeLimits;
  230. SwingConeBatches mPrevSwingConeLimits;
  231. struct SwingPyramidLimits
  232. {
  233. bool operator == (const SwingPyramidLimits &inRHS) const
  234. {
  235. return mMinSwingYAngle == inRHS.mMinSwingYAngle
  236. && mMaxSwingYAngle == inRHS.mMaxSwingYAngle
  237. && mMinSwingZAngle == inRHS.mMinSwingZAngle
  238. && mMaxSwingZAngle == inRHS.mMaxSwingZAngle;
  239. }
  240. float mMinSwingYAngle;
  241. float mMaxSwingYAngle;
  242. float mMinSwingZAngle;
  243. float mMaxSwingZAngle;
  244. };
  245. JPH_MAKE_HASH_STRUCT(SwingPyramidLimits, SwingPyramidLimitsHasher, t.mMinSwingYAngle, t.mMaxSwingYAngle, t.mMinSwingZAngle, t.mMaxSwingZAngle)
  246. using SwingPyramidBatches = UnorderedMap<SwingPyramidLimits, GeometryRef, SwingPyramidLimitsHasher>;
  247. SwingPyramidBatches mSwingPyramidLimits;
  248. SwingPyramidBatches mPrevSwingPyramidLimits;
  249. using PieBatces = UnorderedMap<float, GeometryRef>;
  250. PieBatces mPieLimits;
  251. PieBatces mPrevPieLimits;
  252. };
  253. JPH_NAMESPACE_END