2
0

DebugRendererImp.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Renderer/DebugRendererImp.h>
  5. #include <Renderer/Renderer.h>
  6. #include <Renderer/RenderPrimitive.h>
  7. #include <Renderer/Texture.h>
  8. #include <Renderer/Font.h>
  9. #ifndef JPH_DEBUG_RENDERER
  10. // Hack to still compile DebugRenderer inside the test framework when Jolt is compiled without
  11. #define JPH_DEBUG_RENDERER
  12. #include <Jolt/Renderer/DebugRenderer.cpp>
  13. #undef JPH_DEBUG_RENDERER
  14. #endif // !JPH_DEBUG_RENDERER
  15. DebugRendererImp::DebugRendererImp(Renderer *inRenderer, const Font *inFont) :
  16. mRenderer(inRenderer),
  17. mFont(inFont)
  18. {
  19. // Create input layout for lines
  20. const D3D12_INPUT_ELEMENT_DESC line_vertex_desc[] =
  21. {
  22. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  23. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  24. };
  25. // Lines
  26. ComPtr<ID3DBlob> vtx_line = mRenderer->CreateVertexShader("Assets/Shaders/LineVertexShader.hlsl");
  27. ComPtr<ID3DBlob> pix_line = mRenderer->CreatePixelShader("Assets/Shaders/LinePixelShader.hlsl");
  28. mLineState = mRenderer->CreatePipelineState(vtx_line.Get(), line_vertex_desc, ARRAYSIZE(line_vertex_desc), pix_line.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  29. // Create input layout for triangles
  30. const D3D12_INPUT_ELEMENT_DESC triangles_vertex_desc[] =
  31. {
  32. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  33. { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  34. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  35. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 32, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  36. { "INSTANCE_TRANSFORM", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  37. { "INSTANCE_TRANSFORM", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  38. { "INSTANCE_TRANSFORM", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  39. { "INSTANCE_TRANSFORM", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  40. { "INSTANCE_INV_TRANSFORM", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 64, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  41. { "INSTANCE_INV_TRANSFORM", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 80, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  42. { "INSTANCE_INV_TRANSFORM", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 96, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  43. { "INSTANCE_INV_TRANSFORM", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 112, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  44. { "INSTANCE_COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 128, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 },
  45. };
  46. // Triangles
  47. ComPtr<ID3DBlob> vtx_triangle = mRenderer->CreateVertexShader("Assets/Shaders/TriangleVertexShader.hlsl");
  48. ComPtr<ID3DBlob> pix_triangle = mRenderer->CreatePixelShader("Assets/Shaders/TrianglePixelShader.hlsl");
  49. mTriangleStateBF = mRenderer->CreatePipelineState(vtx_triangle.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_triangle.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  50. mTriangleStateFF = mRenderer->CreatePipelineState(vtx_triangle.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_triangle.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::FrontFace);
  51. mTriangleStateWire = mRenderer->CreatePipelineState(vtx_triangle.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_triangle.Get(), D3D12_FILL_MODE_WIREFRAME, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  52. // Shadow pass
  53. ComPtr<ID3DBlob> vtx_shadow = mRenderer->CreateVertexShader("Assets/Shaders/TriangleDepthVertexShader.hlsl");
  54. ComPtr<ID3DBlob> pix_shadow = mRenderer->CreatePixelShader("Assets/Shaders/TriangleDepthPixelShader.hlsl");
  55. mShadowStateBF = mRenderer->CreatePipelineState(vtx_shadow.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_shadow.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  56. mShadowStateFF = mRenderer->CreatePipelineState(vtx_shadow.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_shadow.Get(), D3D12_FILL_MODE_SOLID, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::FrontFace);
  57. mShadowStateWire = mRenderer->CreatePipelineState(vtx_shadow.Get(), triangles_vertex_desc, ARRAYSIZE(triangles_vertex_desc), pix_shadow.Get(), D3D12_FILL_MODE_WIREFRAME, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, PipelineState::EDepthTest::On, PipelineState::EBlendMode::AlphaBlend, PipelineState::ECullMode::Backface);
  58. // Create depth only texture (no color buffer, as seen from light)
  59. mDepthTexture = mRenderer->CreateRenderTarget(4096, 4096);
  60. // Create instances buffer
  61. for (uint n = 0; n < Renderer::cFrameCount; ++n)
  62. mInstancesBuffer[n] = new RenderInstances(mRenderer);
  63. // Create empty batch
  64. Vertex empty_vertex { Float3(0, 0, 0), Float3(1, 0, 0), Float2(0, 0), Color::sWhite };
  65. uint32 empty_indices[] = { 0, 0, 0 };
  66. mEmptyBatch = CreateTriangleBatch(&empty_vertex, 1, empty_indices, 3);
  67. // Initialize base class
  68. DebugRenderer::Initialize();
  69. }
  70. void DebugRendererImp::DrawLine(const Float3 &inFrom, const Float3 &inTo, ColorArg inColor)
  71. {
  72. lock_guard lock(mLinesLock);
  73. mLines.push_back(Line(inFrom, inTo, inColor));
  74. }
  75. DebugRenderer::Batch DebugRendererImp::CreateTriangleBatch(const Triangle *inTriangles, int inTriangleCount)
  76. {
  77. if (inTriangles == nullptr || inTriangleCount == 0)
  78. return mEmptyBatch;
  79. BatchImpl *primitive = new BatchImpl(mRenderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  80. primitive->CreateVertexBuffer(3 * inTriangleCount, sizeof(Vertex), inTriangles);
  81. return primitive;
  82. }
  83. DebugRenderer::Batch DebugRendererImp::CreateTriangleBatch(const Vertex *inVertices, int inVertexCount, const uint32 *inIndices, int inIndexCount)
  84. {
  85. if (inVertices == nullptr || inVertexCount == 0 || inIndices == nullptr || inIndexCount == 0)
  86. return mEmptyBatch;
  87. BatchImpl *primitive = new BatchImpl(mRenderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  88. primitive->CreateVertexBuffer(inVertexCount, sizeof(Vertex), inVertices);
  89. primitive->CreateIndexBuffer(inIndexCount, inIndices);
  90. return primitive;
  91. }
  92. void DebugRendererImp::DrawGeometry(Mat44Arg inModelMatrix, const AABox &inWorldSpaceBounds, float inLODScaleSq, ColorArg inModelColor, const GeometryRef &inGeometry, ECullMode inCullMode, ECastShadow inCastShadow, EDrawMode inDrawMode)
  93. {
  94. lock_guard lock(mPrimitivesLock);
  95. // Our pixel shader uses alpha only to turn on/off shadows
  96. Color color = inCastShadow == ECastShadow::On? Color(inModelColor, 255) : Color(inModelColor, 0);
  97. if (inDrawMode == EDrawMode::Wireframe)
  98. {
  99. mWireframePrimitives[inGeometry].mInstances.push_back({ inModelMatrix, inModelMatrix.GetDirectionPreservingMatrix(), color, inWorldSpaceBounds, inLODScaleSq });
  100. ++mNumInstances;
  101. }
  102. else
  103. {
  104. if (inCullMode != ECullMode::CullFrontFace)
  105. {
  106. mPrimitives[inGeometry].mInstances.push_back({ inModelMatrix, inModelMatrix.GetDirectionPreservingMatrix(), color, inWorldSpaceBounds, inLODScaleSq });
  107. ++mNumInstances;
  108. }
  109. if (inCullMode != ECullMode::CullBackFace)
  110. {
  111. mPrimitivesBackFacing[inGeometry].mInstances.push_back({ inModelMatrix, inModelMatrix.GetDirectionPreservingMatrix(), color, inWorldSpaceBounds, inLODScaleSq });
  112. ++mNumInstances;
  113. }
  114. }
  115. }
  116. void DebugRendererImp::FinalizePrimitive()
  117. {
  118. JPH_PROFILE_FUNCTION();
  119. if (mLockedPrimitive != nullptr)
  120. {
  121. BatchImpl *primitive = static_cast<BatchImpl *>(mLockedPrimitive.GetPtr());
  122. // Unlock the primitive
  123. primitive->UnlockVertexBuffer();
  124. // Set number of indices to draw
  125. primitive->SetNumVtxToDraw(int(mLockedVertices - mLockedVerticesStart));
  126. // Add to draw list
  127. mTempPrimitives[new Geometry(mLockedPrimitive, mLockedPrimitiveBounds)].mInstances.push_back({ Mat44::sIdentity(), Mat44::sIdentity(), Color::sWhite, mLockedPrimitiveBounds, 1.0f });
  128. ++mNumInstances;
  129. // Clear pointers
  130. mLockedPrimitive = nullptr;
  131. mLockedVerticesStart = nullptr;
  132. mLockedVertices = nullptr;
  133. mLockedVerticesEnd = nullptr;
  134. mLockedPrimitiveBounds = AABox();
  135. }
  136. }
  137. void DebugRendererImp::EnsurePrimitiveSpace(int inVtxSize)
  138. {
  139. const int cVertexBufferSize = 10240;
  140. if (mLockedPrimitive == nullptr
  141. || mLockedVerticesEnd - mLockedVertices < inVtxSize)
  142. {
  143. FinalizePrimitive();
  144. // Create new
  145. BatchImpl *primitive = new BatchImpl(mRenderer, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  146. primitive->CreateVertexBuffer(cVertexBufferSize, sizeof(Vertex));
  147. mLockedPrimitive = primitive;
  148. // Lock buffers
  149. mLockedVerticesStart = mLockedVertices = (Vertex *)primitive->LockVertexBuffer();
  150. mLockedVerticesEnd = mLockedVertices + cVertexBufferSize;
  151. }
  152. }
  153. void DebugRendererImp::DrawTriangle(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, ColorArg inColor)
  154. {
  155. lock_guard lock(mPrimitivesLock);
  156. EnsurePrimitiveSpace(3);
  157. // Set alpha to zero to tell our pixel shader to not cast shadows for this triangle
  158. // this is because our algorithm only renders shadows for backfacing triangles and this
  159. // triangle doesn't have one
  160. Color color(inColor, 0);
  161. // Construct triangle
  162. new ((Triangle *)mLockedVertices) Triangle(inV1, inV2, inV3, color);
  163. mLockedVertices += 3;
  164. // Update bounding box
  165. mLockedPrimitiveBounds.Encapsulate(inV1);
  166. mLockedPrimitiveBounds.Encapsulate(inV2);
  167. mLockedPrimitiveBounds.Encapsulate(inV3);
  168. }
  169. void DebugRendererImp::DrawInstances(const Geometry *inGeometry, const Array<int> &inStartIdx)
  170. {
  171. RenderInstances *instances_buffer = mInstancesBuffer[mRenderer->GetCurrentFrameIndex()];
  172. if (!inStartIdx.empty())
  173. {
  174. // Get LODs
  175. const Array<LOD> &geometry_lods = inGeometry->mLODs;
  176. // Write instances for all LODS
  177. int next_start_idx = inStartIdx.front();
  178. for (size_t lod = 0; lod < geometry_lods.size(); ++lod)
  179. {
  180. int start_idx = next_start_idx;
  181. next_start_idx = inStartIdx[lod + 1];
  182. int num_instances = next_start_idx - start_idx;
  183. instances_buffer->Draw(static_cast<BatchImpl *>(geometry_lods[lod].mTriangleBatch.GetPtr()), start_idx, num_instances);
  184. }
  185. }
  186. }
  187. void DebugRendererImp::DrawText3D(Vec3Arg inPosition, const string_view &inString, ColorArg inColor, float inHeight)
  188. {
  189. lock_guard lock(mTextsLock);
  190. mTexts.emplace_back(inPosition, inString, inColor, inHeight);
  191. }
  192. void DebugRendererImp::DrawLines()
  193. {
  194. JPH_PROFILE_FUNCTION();
  195. lock_guard lock(mLinesLock);
  196. // Draw the lines
  197. if (!mLines.empty())
  198. {
  199. RenderPrimitive primitive(mRenderer, D3D_PRIMITIVE_TOPOLOGY_LINELIST);
  200. primitive.CreateVertexBuffer((int)mLines.size() * 2, sizeof(Line) / 2);
  201. void *data = primitive.LockVertexBuffer();
  202. memcpy(data, &mLines[0], mLines.size() * sizeof(Line));
  203. primitive.UnlockVertexBuffer();
  204. mLineState->Activate();
  205. primitive.Draw();
  206. }
  207. }
  208. void DebugRendererImp::DrawTriangles()
  209. {
  210. JPH_PROFILE_FUNCTION();
  211. lock_guard lock(mPrimitivesLock);
  212. // Finish the last primitive
  213. FinalizePrimitive();
  214. // Render to shadow map texture first
  215. mRenderer->SetRenderTarget(mDepthTexture);
  216. // Clear the shadow map texture to max depth
  217. mDepthTexture->ClearRenderTarget();
  218. // Get the camera and light frustum for culling
  219. Vec3 camera_pos = mRenderer->GetCameraState().mPos;
  220. const Frustum &camera_frustum = mRenderer->GetCameraFrustum();
  221. const Frustum &light_frustum = mRenderer->GetLightFrustum();
  222. // Resize instances buffer and copy all visible instance data into it
  223. if (mNumInstances > 0)
  224. {
  225. // Create instances buffer
  226. RenderInstances *instances_buffer = mInstancesBuffer[mRenderer->GetCurrentFrameIndex()];
  227. instances_buffer->CreateBuffer(2 * mNumInstances, sizeof(Instance));
  228. Instance *dst_instance = reinterpret_cast<Instance *>(instances_buffer->Lock());
  229. // Next write index
  230. int dst_index = 0;
  231. // This keeps track of which instances use which lod, first array: 0 = light pass, 1 = geometry pass
  232. Array<Array<int>> lod_indices[2];
  233. for (InstanceMap *primitive_map : { &mPrimitives, &mTempPrimitives, &mPrimitivesBackFacing, &mWireframePrimitives })
  234. for (InstanceMap::value_type &v : *primitive_map)
  235. {
  236. // Get LODs
  237. const Array<LOD> &geometry_lods = v.first->mLODs;
  238. size_t num_lods = geometry_lods.size();
  239. JPH_ASSERT(num_lods > 0);
  240. // Ensure that our lod index array is big enough (to avoid reallocating memory too often)
  241. if (lod_indices[0].size() < num_lods)
  242. lod_indices[0].resize(num_lods);
  243. if (lod_indices[1].size() < num_lods)
  244. lod_indices[1].resize(num_lods);
  245. // Iterate over all instances
  246. const Array<InstanceWithLODInfo> &instances = v.second.mInstances;
  247. for (size_t i = 0; i < instances.size(); ++i)
  248. {
  249. const InstanceWithLODInfo &src_instance = instances[i];
  250. // Check if it overlaps with the light or camera frustum
  251. bool light_overlaps = light_frustum.Overlaps(src_instance.mWorldSpaceBounds);
  252. bool camera_overlaps = camera_frustum.Overlaps(src_instance.mWorldSpaceBounds);
  253. if (light_overlaps || camera_overlaps)
  254. {
  255. // Figure out which LOD to use
  256. float dist_sq = src_instance.mWorldSpaceBounds.GetSqDistanceTo(camera_pos);
  257. for (size_t lod = 0; lod < num_lods; ++lod)
  258. if (dist_sq <= src_instance.mLODScaleSq * Square(geometry_lods[lod].mDistance))
  259. {
  260. // Store which index goes in which LOD
  261. if (light_overlaps)
  262. lod_indices[0][lod].push_back((int)i);
  263. if (camera_overlaps)
  264. lod_indices[1][lod].push_back((int)i);
  265. break;
  266. }
  267. }
  268. }
  269. // Loop over both passes: 0 = light, 1 = geometry
  270. Array<int> *start_idx[] = { &v.second.mLightStartIdx, &v.second.mGeometryStartIdx };
  271. for (int type = 0; type < 2; ++type)
  272. {
  273. // Reserve space for instance indices
  274. Array<int> &type_start_idx = *start_idx[type];
  275. type_start_idx.resize(num_lods + 1);
  276. // Write out geometry pass instances
  277. for (size_t lod = 0; lod < num_lods; ++lod)
  278. {
  279. // Write start index for this LOD
  280. type_start_idx[lod] = dst_index;
  281. // Copy instances
  282. Array<int> &this_lod_indices = lod_indices[type][lod];
  283. for (int i : this_lod_indices)
  284. {
  285. const Instance &src_instance = instances[i];
  286. dst_instance[dst_index++] = src_instance;
  287. }
  288. // Prepare for next iteration (will preserve memory)
  289. this_lod_indices.clear();
  290. }
  291. // Write out end of last LOD
  292. type_start_idx.back() = dst_index;
  293. }
  294. }
  295. instances_buffer->Unlock();
  296. }
  297. if (!mPrimitives.empty() || !mTempPrimitives.empty())
  298. {
  299. // Front face culling, we want to render the back side of the geometry for casting shadows
  300. mShadowStateFF->Activate();
  301. // Draw all primitives as seen from the light
  302. if (mNumInstances > 0)
  303. for (InstanceMap::value_type &v : mPrimitives)
  304. DrawInstances(v.first, v.second.mLightStartIdx);
  305. for (InstanceMap::value_type &v : mTempPrimitives)
  306. DrawInstances(v.first, v.second.mLightStartIdx);
  307. }
  308. if (!mPrimitivesBackFacing.empty())
  309. {
  310. // Back face culling, we want to render the front side of back facing geometry
  311. mShadowStateBF->Activate();
  312. // Draw all primitives as seen from the light
  313. for (InstanceMap::value_type &v : mPrimitivesBackFacing)
  314. DrawInstances(v.first, v.second.mLightStartIdx);
  315. }
  316. if (!mWireframePrimitives.empty())
  317. {
  318. // Switch to wireframe mode
  319. mShadowStateWire->Activate();
  320. // Draw all wireframe primitives as seen from the light
  321. for (InstanceMap::value_type &v : mWireframePrimitives)
  322. DrawInstances(v.first, v.second.mLightStartIdx);
  323. }
  324. // Switch to the main render target
  325. mRenderer->SetRenderTarget(nullptr);
  326. // Bind the shadow map texture
  327. mDepthTexture->Bind(2);
  328. if (!mPrimitives.empty() || !mTempPrimitives.empty())
  329. {
  330. // Bind the normal shader, back face culling
  331. mTriangleStateBF->Activate();
  332. // Draw all primitives
  333. if (mNumInstances > 0)
  334. for (InstanceMap::value_type &v : mPrimitives)
  335. DrawInstances(v.first, v.second.mGeometryStartIdx);
  336. for (InstanceMap::value_type &v : mTempPrimitives)
  337. DrawInstances(v.first, v.second.mGeometryStartIdx);
  338. }
  339. if (!mPrimitivesBackFacing.empty())
  340. {
  341. // Front face culling, the next batch needs to render inside out
  342. mTriangleStateFF->Activate();
  343. // Draw all back primitives
  344. for (InstanceMap::value_type &v : mPrimitivesBackFacing)
  345. DrawInstances(v.first, v.second.mGeometryStartIdx);
  346. }
  347. if (!mWireframePrimitives.empty())
  348. {
  349. // Wire frame mode
  350. mTriangleStateWire->Activate();
  351. // Draw all wireframe primitives
  352. for (InstanceMap::value_type &v : mWireframePrimitives)
  353. DrawInstances(v.first, v.second.mGeometryStartIdx);
  354. }
  355. }
  356. void DebugRendererImp::DrawTexts()
  357. {
  358. lock_guard lock(mTextsLock);
  359. JPH_PROFILE_FUNCTION();
  360. const CameraState &camera_state = mRenderer->GetCameraState();
  361. for (const Text &t : mTexts)
  362. {
  363. Vec3 forward = camera_state.mForward;
  364. Vec3 right = forward.Cross(camera_state.mUp).Normalized();
  365. Vec3 up = right.Cross(forward).Normalized();
  366. Mat44 transform(Vec4(right, 0), Vec4(up, 0), Vec4(forward, 0), Vec4(t.mPosition, 1));
  367. mFont->DrawText3D(transform * Mat44::sScale(t.mHeight), t.mText, t.mColor);
  368. }
  369. }
  370. void DebugRendererImp::Draw()
  371. {
  372. DrawLines();
  373. DrawTriangles();
  374. DrawTexts();
  375. }
  376. void DebugRendererImp::ClearLines()
  377. {
  378. lock_guard lock(mLinesLock);
  379. mLines.clear();
  380. }
  381. void DebugRendererImp::ClearMap(InstanceMap &ioInstances)
  382. {
  383. Array<GeometryRef> to_delete;
  384. for (InstanceMap::value_type &kv : ioInstances)
  385. {
  386. if (kv.second.mInstances.empty())
  387. to_delete.push_back(kv.first);
  388. else
  389. kv.second.mInstances.clear();
  390. }
  391. for (GeometryRef &b : to_delete)
  392. ioInstances.erase(b);
  393. }
  394. void DebugRendererImp::ClearTriangles()
  395. {
  396. lock_guard lock(mPrimitivesLock);
  397. // Close any primitive that's being built
  398. FinalizePrimitive();
  399. // Move primitives to draw back to the free list
  400. ClearMap(mWireframePrimitives);
  401. ClearMap(mPrimitives);
  402. mTempPrimitives.clear(); // These are created by FinalizePrimitive() and need to be cleared every frame
  403. ClearMap(mPrimitivesBackFacing);
  404. mNumInstances = 0;
  405. }
  406. void DebugRendererImp::ClearTexts()
  407. {
  408. lock_guard lock(mTextsLock);
  409. mTexts.clear();
  410. }
  411. void DebugRendererImp::Clear()
  412. {
  413. ClearLines();
  414. ClearTriangles();
  415. ClearTexts();
  416. }