imgui_impl_dx12.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. // dear imgui: Renderer Backend for DirectX12
  2. // This needs to be used along with a Platform Backend (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  7. // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
  8. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  9. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  10. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  11. // Learn about Dear ImGui:
  12. // - FAQ https://dearimgui.com/faq
  13. // - Getting Started https://dearimgui.com/getting-started
  14. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  15. // - Introduction, links and more at the top of imgui.cpp
  16. // CHANGELOG
  17. // (minor and older changes stripped away, please see git history for details)
  18. // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own.
  19. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
  20. // 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
  21. // 2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple.
  22. // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
  23. // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  24. // 2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
  25. // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  26. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  27. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
  28. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  29. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  30. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  31. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  32. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  33. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  34. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  35. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  36. // 2019-03-29: Misc: Various minor tidying up.
  37. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  38. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  39. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  40. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  41. // 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport).
  42. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  43. #include "imgui.h"
  44. #ifndef IMGUI_DISABLE
  45. #include "imgui_impl_dx12.h"
  46. // DirectX
  47. #include <d3d12.h>
  48. #include <dxgi1_4.h>
  49. #include <d3dcompiler.h>
  50. #ifdef _MSC_VER
  51. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  52. #endif
  53. // DirectX12 data
  54. struct ImGui_ImplDX12_RenderBuffers;
  55. struct ImGui_ImplDX12_Texture
  56. {
  57. ID3D12Resource* pTextureResource;
  58. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  59. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  60. ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
  61. };
  62. struct ImGui_ImplDX12_Data
  63. {
  64. ImGui_ImplDX12_InitInfo InitInfo;
  65. ID3D12Device* pd3dDevice;
  66. ID3D12RootSignature* pRootSignature;
  67. ID3D12PipelineState* pPipelineState;
  68. DXGI_FORMAT RTVFormat;
  69. DXGI_FORMAT DSVFormat;
  70. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  71. UINT numFramesInFlight;
  72. ImGui_ImplDX12_RenderBuffers* pFrameResources;
  73. UINT frameIndex;
  74. ImGui_ImplDX12_Texture FontTexture;
  75. bool LegacySingleDescriptorUsed;
  76. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; }
  77. };
  78. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  79. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  80. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  81. {
  82. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  83. }
  84. // Buffers used during the rendering of a frame
  85. struct ImGui_ImplDX12_RenderBuffers
  86. {
  87. ID3D12Resource* IndexBuffer;
  88. ID3D12Resource* VertexBuffer;
  89. int IndexBufferSize;
  90. int VertexBufferSize;
  91. };
  92. struct VERTEX_CONSTANT_BUFFER_DX12
  93. {
  94. float mvp[4][4];
  95. };
  96. // Functions
  97. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
  98. {
  99. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  100. // Setup orthographic projection matrix into our constant buffer
  101. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  102. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  103. {
  104. float L = draw_data->DisplayPos.x;
  105. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  106. float T = draw_data->DisplayPos.y;
  107. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  108. float mvp[4][4] =
  109. {
  110. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  111. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  112. { 0.0f, 0.0f, 0.5f, 0.0f },
  113. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  114. };
  115. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  116. }
  117. // Setup viewport
  118. D3D12_VIEWPORT vp;
  119. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  120. vp.Width = draw_data->DisplaySize.x;
  121. vp.Height = draw_data->DisplaySize.y;
  122. vp.MinDepth = 0.0f;
  123. vp.MaxDepth = 1.0f;
  124. vp.TopLeftX = vp.TopLeftY = 0.0f;
  125. command_list->RSSetViewports(1, &vp);
  126. // Bind shader and vertex buffers
  127. unsigned int stride = sizeof(ImDrawVert);
  128. unsigned int offset = 0;
  129. D3D12_VERTEX_BUFFER_VIEW vbv;
  130. memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
  131. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  132. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  133. vbv.StrideInBytes = stride;
  134. command_list->IASetVertexBuffers(0, 1, &vbv);
  135. D3D12_INDEX_BUFFER_VIEW ibv;
  136. memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
  137. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  138. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  139. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  140. command_list->IASetIndexBuffer(&ibv);
  141. command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  142. command_list->SetPipelineState(bd->pPipelineState);
  143. command_list->SetGraphicsRootSignature(bd->pRootSignature);
  144. command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  145. // Setup blend factor
  146. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  147. command_list->OMSetBlendFactor(blend_factor);
  148. }
  149. template<typename T>
  150. static inline void SafeRelease(T*& res)
  151. {
  152. if (res)
  153. res->Release();
  154. res = nullptr;
  155. }
  156. // Render function
  157. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
  158. {
  159. // Avoid rendering when minimized
  160. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  161. return;
  162. // FIXME: We are assuming that this only gets called once per frame!
  163. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  164. bd->frameIndex = bd->frameIndex + 1;
  165. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
  166. // Create and grow vertex/index buffers if needed
  167. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  168. {
  169. SafeRelease(fr->VertexBuffer);
  170. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  171. D3D12_HEAP_PROPERTIES props;
  172. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  173. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  174. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  175. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  176. D3D12_RESOURCE_DESC desc;
  177. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  178. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  179. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  180. desc.Height = 1;
  181. desc.DepthOrArraySize = 1;
  182. desc.MipLevels = 1;
  183. desc.Format = DXGI_FORMAT_UNKNOWN;
  184. desc.SampleDesc.Count = 1;
  185. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  186. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  187. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  188. return;
  189. }
  190. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  191. {
  192. SafeRelease(fr->IndexBuffer);
  193. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  194. D3D12_HEAP_PROPERTIES props;
  195. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  196. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  197. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  198. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  199. D3D12_RESOURCE_DESC desc;
  200. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  201. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  202. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  203. desc.Height = 1;
  204. desc.DepthOrArraySize = 1;
  205. desc.MipLevels = 1;
  206. desc.Format = DXGI_FORMAT_UNKNOWN;
  207. desc.SampleDesc.Count = 1;
  208. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  209. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  210. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  211. return;
  212. }
  213. // Upload vertex/index data into a single contiguous GPU buffer
  214. // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
  215. void* vtx_resource, *idx_resource;
  216. D3D12_RANGE range = { 0, 0 };
  217. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  218. return;
  219. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  220. return;
  221. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  222. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  223. for (int n = 0; n < draw_data->CmdListsCount; n++)
  224. {
  225. const ImDrawList* draw_list = draw_data->CmdLists[n];
  226. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  227. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  228. vtx_dst += draw_list->VtxBuffer.Size;
  229. idx_dst += draw_list->IdxBuffer.Size;
  230. }
  231. // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
  232. range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
  233. IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
  234. fr->VertexBuffer->Unmap(0, &range);
  235. range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
  236. IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
  237. fr->IndexBuffer->Unmap(0, &range);
  238. // Setup desired DX state
  239. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  240. // Setup render state structure (for callbacks and custom texture bindings)
  241. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  242. ImGui_ImplDX12_RenderState render_state;
  243. render_state.Device = bd->pd3dDevice;
  244. render_state.CommandList = command_list;
  245. platform_io.Renderer_RenderState = &render_state;
  246. // Render command lists
  247. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  248. int global_vtx_offset = 0;
  249. int global_idx_offset = 0;
  250. ImVec2 clip_off = draw_data->DisplayPos;
  251. for (int n = 0; n < draw_data->CmdListsCount; n++)
  252. {
  253. const ImDrawList* draw_list = draw_data->CmdLists[n];
  254. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  255. {
  256. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  257. if (pcmd->UserCallback != nullptr)
  258. {
  259. // User callback, registered via ImDrawList::AddCallback()
  260. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  261. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  262. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  263. else
  264. pcmd->UserCallback(draw_list, pcmd);
  265. }
  266. else
  267. {
  268. // Project scissor/clipping rectangles into framebuffer space
  269. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  270. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  271. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  272. continue;
  273. // Apply scissor/clipping rectangle
  274. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  275. command_list->RSSetScissorRects(1, &r);
  276. // Bind texture, Draw
  277. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  278. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  279. command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
  280. command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  281. }
  282. }
  283. global_idx_offset += draw_list->IdxBuffer.Size;
  284. global_vtx_offset += draw_list->VtxBuffer.Size;
  285. }
  286. platform_io.Renderer_RenderState = nullptr;
  287. }
  288. static void ImGui_ImplDX12_CreateFontsTexture()
  289. {
  290. // Build texture atlas
  291. ImGuiIO& io = ImGui::GetIO();
  292. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  293. unsigned char* pixels;
  294. int width, height;
  295. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  296. // Upload texture to graphics system
  297. ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
  298. {
  299. D3D12_HEAP_PROPERTIES props;
  300. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  301. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  302. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  303. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  304. D3D12_RESOURCE_DESC desc;
  305. ZeroMemory(&desc, sizeof(desc));
  306. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  307. desc.Alignment = 0;
  308. desc.Width = width;
  309. desc.Height = height;
  310. desc.DepthOrArraySize = 1;
  311. desc.MipLevels = 1;
  312. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  313. desc.SampleDesc.Count = 1;
  314. desc.SampleDesc.Quality = 0;
  315. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  316. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  317. ID3D12Resource* pTexture = nullptr;
  318. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  319. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  320. UINT upload_pitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  321. UINT upload_size = height * upload_pitch;
  322. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  323. desc.Alignment = 0;
  324. desc.Width = upload_size;
  325. desc.Height = 1;
  326. desc.DepthOrArraySize = 1;
  327. desc.MipLevels = 1;
  328. desc.Format = DXGI_FORMAT_UNKNOWN;
  329. desc.SampleDesc.Count = 1;
  330. desc.SampleDesc.Quality = 0;
  331. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  332. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  333. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  334. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  335. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  336. ID3D12Resource* uploadBuffer = nullptr;
  337. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  338. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
  339. IM_ASSERT(SUCCEEDED(hr));
  340. void* mapped = nullptr;
  341. D3D12_RANGE range = { 0, upload_size };
  342. hr = uploadBuffer->Map(0, &range, &mapped);
  343. IM_ASSERT(SUCCEEDED(hr));
  344. for (int y = 0; y < height; y++)
  345. memcpy((void*) ((uintptr_t) mapped + y * upload_pitch), pixels + y * width * 4, width * 4);
  346. uploadBuffer->Unmap(0, &range);
  347. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  348. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  349. {
  350. srcLocation.pResource = uploadBuffer;
  351. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  352. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  353. srcLocation.PlacedFootprint.Footprint.Width = width;
  354. srcLocation.PlacedFootprint.Footprint.Height = height;
  355. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  356. srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch;
  357. dstLocation.pResource = pTexture;
  358. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  359. dstLocation.SubresourceIndex = 0;
  360. }
  361. D3D12_RESOURCE_BARRIER barrier = {};
  362. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  363. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  364. barrier.Transition.pResource = pTexture;
  365. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  366. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  367. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  368. ID3D12Fence* fence = nullptr;
  369. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  370. IM_ASSERT(SUCCEEDED(hr));
  371. HANDLE event = ::CreateEvent(0, 0, 0, 0);
  372. IM_ASSERT(event != nullptr);
  373. ID3D12CommandAllocator* cmdAlloc = nullptr;
  374. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  375. IM_ASSERT(SUCCEEDED(hr));
  376. ID3D12GraphicsCommandList* cmdList = nullptr;
  377. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
  378. IM_ASSERT(SUCCEEDED(hr));
  379. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr);
  380. cmdList->ResourceBarrier(1, &barrier);
  381. hr = cmdList->Close();
  382. IM_ASSERT(SUCCEEDED(hr));
  383. ID3D12CommandQueue* cmdQueue = bd->InitInfo.CommandQueue;
  384. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  385. hr = cmdQueue->Signal(fence, 1);
  386. IM_ASSERT(SUCCEEDED(hr));
  387. fence->SetEventOnCompletion(1, event);
  388. ::WaitForSingleObject(event, INFINITE);
  389. cmdList->Release();
  390. cmdAlloc->Release();
  391. ::CloseHandle(event);
  392. fence->Release();
  393. uploadBuffer->Release();
  394. // Create texture view
  395. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  396. ZeroMemory(&srvDesc, sizeof(srvDesc));
  397. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  398. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  399. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  400. srvDesc.Texture2D.MostDetailedMip = 0;
  401. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  402. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, font_tex->hFontSrvCpuDescHandle);
  403. SafeRelease(font_tex->pTextureResource);
  404. font_tex->pTextureResource = pTexture;
  405. }
  406. // Store our identifier
  407. io.Fonts->SetTexID((ImTextureID)font_tex->hFontSrvGpuDescHandle.ptr);
  408. }
  409. bool ImGui_ImplDX12_CreateDeviceObjects()
  410. {
  411. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  412. if (!bd || !bd->pd3dDevice)
  413. return false;
  414. if (bd->pPipelineState)
  415. ImGui_ImplDX12_InvalidateDeviceObjects();
  416. // Create the root signature
  417. {
  418. D3D12_DESCRIPTOR_RANGE descRange = {};
  419. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  420. descRange.NumDescriptors = 1;
  421. descRange.BaseShaderRegister = 0;
  422. descRange.RegisterSpace = 0;
  423. descRange.OffsetInDescriptorsFromTableStart = 0;
  424. D3D12_ROOT_PARAMETER param[2] = {};
  425. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  426. param[0].Constants.ShaderRegister = 0;
  427. param[0].Constants.RegisterSpace = 0;
  428. param[0].Constants.Num32BitValues = 16;
  429. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  430. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  431. param[1].DescriptorTable.NumDescriptorRanges = 1;
  432. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  433. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  434. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  435. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  436. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  437. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  438. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  439. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  440. staticSampler.MipLODBias = 0.f;
  441. staticSampler.MaxAnisotropy = 0;
  442. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  443. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  444. staticSampler.MinLOD = 0.f;
  445. staticSampler.MaxLOD = 0.f;
  446. staticSampler.ShaderRegister = 0;
  447. staticSampler.RegisterSpace = 0;
  448. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  449. D3D12_ROOT_SIGNATURE_DESC desc = {};
  450. desc.NumParameters = _countof(param);
  451. desc.pParameters = param;
  452. desc.NumStaticSamplers = 1;
  453. desc.pStaticSamplers = &staticSampler;
  454. desc.Flags =
  455. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  456. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  457. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  458. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  459. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  460. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  461. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  462. if (d3d12_dll == nullptr)
  463. {
  464. // Attempt to load d3d12.dll from local directories. This will only succeed if
  465. // (1) the current OS is Windows 7, and
  466. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  467. // See https://github.com/ocornut/imgui/pull/3696 for details.
  468. const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample
  469. for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
  470. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  471. break;
  472. // If failed, we are on Windows >= 10.
  473. if (d3d12_dll == nullptr)
  474. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  475. if (d3d12_dll == nullptr)
  476. return false;
  477. }
  478. PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  479. if (D3D12SerializeRootSignatureFn == nullptr)
  480. return false;
  481. ID3DBlob* blob = nullptr;
  482. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  483. return false;
  484. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
  485. blob->Release();
  486. }
  487. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  488. // If you would like to use this DX12 sample code but remove this dependency you can:
  489. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  490. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  491. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  492. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  493. memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  494. psoDesc.NodeMask = 1;
  495. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  496. psoDesc.pRootSignature = bd->pRootSignature;
  497. psoDesc.SampleMask = UINT_MAX;
  498. psoDesc.NumRenderTargets = 1;
  499. psoDesc.RTVFormats[0] = bd->RTVFormat;
  500. psoDesc.DSVFormat = bd->DSVFormat;
  501. psoDesc.SampleDesc.Count = 1;
  502. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  503. ID3DBlob* vertexShaderBlob;
  504. ID3DBlob* pixelShaderBlob;
  505. // Create the vertex shader
  506. {
  507. static const char* vertexShader =
  508. "cbuffer vertexBuffer : register(b0) \
  509. {\
  510. float4x4 ProjectionMatrix; \
  511. };\
  512. struct VS_INPUT\
  513. {\
  514. float2 pos : POSITION;\
  515. float4 col : COLOR0;\
  516. float2 uv : TEXCOORD0;\
  517. };\
  518. \
  519. struct PS_INPUT\
  520. {\
  521. float4 pos : SV_POSITION;\
  522. float4 col : COLOR0;\
  523. float2 uv : TEXCOORD0;\
  524. };\
  525. \
  526. PS_INPUT main(VS_INPUT input)\
  527. {\
  528. PS_INPUT output;\
  529. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  530. output.col = input.col;\
  531. output.uv = input.uv;\
  532. return output;\
  533. }";
  534. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  535. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  536. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  537. // Create the input layout
  538. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  539. {
  540. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  541. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  542. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  543. };
  544. psoDesc.InputLayout = { local_layout, 3 };
  545. }
  546. // Create the pixel shader
  547. {
  548. static const char* pixelShader =
  549. "struct PS_INPUT\
  550. {\
  551. float4 pos : SV_POSITION;\
  552. float4 col : COLOR0;\
  553. float2 uv : TEXCOORD0;\
  554. };\
  555. SamplerState sampler0 : register(s0);\
  556. Texture2D texture0 : register(t0);\
  557. \
  558. float4 main(PS_INPUT input) : SV_Target\
  559. {\
  560. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  561. return out_col; \
  562. }";
  563. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  564. {
  565. vertexShaderBlob->Release();
  566. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  567. }
  568. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  569. }
  570. // Create the blending setup
  571. {
  572. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  573. desc.AlphaToCoverageEnable = false;
  574. desc.RenderTarget[0].BlendEnable = true;
  575. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  576. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  577. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  578. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  579. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  580. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  581. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  582. }
  583. // Create the rasterizer state
  584. {
  585. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  586. desc.FillMode = D3D12_FILL_MODE_SOLID;
  587. desc.CullMode = D3D12_CULL_MODE_NONE;
  588. desc.FrontCounterClockwise = FALSE;
  589. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  590. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  591. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  592. desc.DepthClipEnable = true;
  593. desc.MultisampleEnable = FALSE;
  594. desc.AntialiasedLineEnable = FALSE;
  595. desc.ForcedSampleCount = 0;
  596. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  597. }
  598. // Create depth-stencil State
  599. {
  600. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  601. desc.DepthEnable = false;
  602. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  603. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  604. desc.StencilEnable = false;
  605. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  606. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  607. desc.BackFace = desc.FrontFace;
  608. }
  609. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
  610. vertexShaderBlob->Release();
  611. pixelShaderBlob->Release();
  612. if (result_pipeline_state != S_OK)
  613. return false;
  614. ImGui_ImplDX12_CreateFontsTexture();
  615. return true;
  616. }
  617. void ImGui_ImplDX12_InvalidateDeviceObjects()
  618. {
  619. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  620. if (!bd || !bd->pd3dDevice)
  621. return;
  622. SafeRelease(bd->pRootSignature);
  623. SafeRelease(bd->pPipelineState);
  624. // Free SRV descriptor used by texture
  625. ImGuiIO& io = ImGui::GetIO();
  626. ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
  627. bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle);
  628. SafeRelease(font_tex->pTextureResource);
  629. io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well.
  630. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  631. {
  632. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  633. SafeRelease(fr->IndexBuffer);
  634. SafeRelease(fr->VertexBuffer);
  635. }
  636. }
  637. bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
  638. {
  639. ImGuiIO& io = ImGui::GetIO();
  640. IMGUI_CHECKVERSION();
  641. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  642. // Setup backend capabilities flags
  643. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  644. bd->InitInfo = *init_info; // Deep copy
  645. init_info = &bd->InitInfo;
  646. bd->pd3dDevice = init_info->Device;
  647. bd->RTVFormat = init_info->RTVFormat;
  648. bd->DSVFormat = init_info->DSVFormat;
  649. bd->numFramesInFlight = init_info->NumFramesInFlight;
  650. bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
  651. io.BackendRendererUserData = (void*)bd;
  652. io.BackendRendererName = "imgui_impl_dx12";
  653. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  654. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  655. if (init_info->SrvDescriptorAllocFn == nullptr)
  656. {
  657. // Wrap legacy behavior of passing space for a single descriptor
  658. IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
  659. init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
  660. {
  661. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  662. IM_ASSERT(bd->LegacySingleDescriptorUsed == false);
  663. *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
  664. *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
  665. bd->LegacySingleDescriptorUsed = true;
  666. };
  667. init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
  668. {
  669. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  670. IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
  671. bd->LegacySingleDescriptorUsed = false;
  672. };
  673. }
  674. #endif
  675. // Allocate 1 SRV descriptor for the font texture
  676. IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
  677. init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
  678. // Create buffers with a default size (they will later be grown as needed)
  679. bd->frameIndex = UINT_MAX;
  680. bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[bd->numFramesInFlight];
  681. for (int i = 0; i < (int)bd->numFramesInFlight; i++)
  682. {
  683. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  684. fr->IndexBuffer = nullptr;
  685. fr->VertexBuffer = nullptr;
  686. fr->IndexBufferSize = 10000;
  687. fr->VertexBufferSize = 5000;
  688. }
  689. return true;
  690. }
  691. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  692. // Legacy initialization API Obsoleted in 1.91.5
  693. // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
  694. bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  695. {
  696. ImGui_ImplDX12_InitInfo init_info;
  697. init_info.Device = device;
  698. init_info.NumFramesInFlight = num_frames_in_flight;
  699. init_info.RTVFormat = rtv_format;
  700. init_info.SrvDescriptorHeap = srv_descriptor_heap;
  701. init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
  702. init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;;
  703. return ImGui_ImplDX12_Init(&init_info);
  704. }
  705. #endif
  706. void ImGui_ImplDX12_Shutdown()
  707. {
  708. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  709. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  710. ImGuiIO& io = ImGui::GetIO();
  711. // Clean up windows and device objects
  712. ImGui_ImplDX12_InvalidateDeviceObjects();
  713. delete[] bd->pFrameResources;
  714. io.BackendRendererName = nullptr;
  715. io.BackendRendererUserData = nullptr;
  716. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  717. IM_DELETE(bd);
  718. }
  719. void ImGui_ImplDX12_NewFrame()
  720. {
  721. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  722. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
  723. if (!bd->pPipelineState)
  724. ImGui_ImplDX12_CreateDeviceObjects();
  725. }
  726. //-----------------------------------------------------------------------------
  727. #endif // #ifndef IMGUI_DISABLE