imgui_impl_dx12.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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) with 16-bit indices.
  6. // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  7. // FIXME: The transition from removing a viewport and moving the window in an existing hosted viewport tends to flicker.
  8. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
  9. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
  10. // To build this on 32-bit systems:
  11. // - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file)
  12. // - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
  13. // - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
  14. // - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file)
  15. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  16. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  17. // Learn about Dear ImGui:
  18. // - FAQ https://dearimgui.com/faq
  19. // - Getting Started https://dearimgui.com/getting-started
  20. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  21. // - Introduction, links and more at the top of imgui.cpp
  22. // CHANGELOG
  23. // (minor and older changes stripped away, please see git history for details)
  24. // 2023-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  25. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  26. // 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).
  27. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  28. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  29. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  30. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  31. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  32. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  33. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  34. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  35. // 2019-03-29: Misc: Various minor tidying up.
  36. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  37. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  38. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  39. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  40. // 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).
  41. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  42. #include "imgui.h"
  43. #ifndef IMGUI_DISABLE
  44. #include "imgui_impl_dx12.h"
  45. // DirectX
  46. #include <d3d12.h>
  47. #include <dxgi1_4.h>
  48. #include <d3dcompiler.h>
  49. #ifdef _MSC_VER
  50. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  51. #endif
  52. // DirectX data
  53. struct ImGui_ImplDX12_Data
  54. {
  55. ID3D12Device* pd3dDevice;
  56. ID3D12RootSignature* pRootSignature;
  57. ID3D12PipelineState* pPipelineState;
  58. DXGI_FORMAT RTVFormat;
  59. ID3D12Resource* pFontTextureResource;
  60. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  61. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  62. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  63. UINT numFramesInFlight;
  64. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); }
  65. };
  66. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  67. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  68. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  69. {
  70. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  71. }
  72. // Buffers used during the rendering of a frame
  73. struct ImGui_ImplDX12_RenderBuffers
  74. {
  75. ID3D12Resource* IndexBuffer;
  76. ID3D12Resource* VertexBuffer;
  77. int IndexBufferSize;
  78. int VertexBufferSize;
  79. };
  80. // Buffers used for secondary viewports created by the multi-viewports systems
  81. struct ImGui_ImplDX12_FrameContext
  82. {
  83. ID3D12CommandAllocator* CommandAllocator;
  84. ID3D12Resource* RenderTarget;
  85. D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors;
  86. };
  87. // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
  88. // Main viewport created by application will only use the Resources field.
  89. // Secondary viewports created by this backend will use all the fields (including Window fields),
  90. struct ImGui_ImplDX12_ViewportData
  91. {
  92. // Window
  93. ID3D12CommandQueue* CommandQueue;
  94. ID3D12GraphicsCommandList* CommandList;
  95. ID3D12DescriptorHeap* RtvDescHeap;
  96. IDXGISwapChain3* SwapChain;
  97. ID3D12Fence* Fence;
  98. UINT64 FenceSignaledValue;
  99. HANDLE FenceEvent;
  100. UINT NumFramesInFlight;
  101. ImGui_ImplDX12_FrameContext* FrameCtx;
  102. // Render buffers
  103. UINT FrameIndex;
  104. ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers;
  105. ImGui_ImplDX12_ViewportData(UINT num_frames_in_flight)
  106. {
  107. CommandQueue = nullptr;
  108. CommandList = nullptr;
  109. RtvDescHeap = nullptr;
  110. SwapChain = nullptr;
  111. Fence = nullptr;
  112. FenceSignaledValue = 0;
  113. FenceEvent = nullptr;
  114. NumFramesInFlight = num_frames_in_flight;
  115. FrameCtx = new ImGui_ImplDX12_FrameContext[NumFramesInFlight];
  116. FrameIndex = UINT_MAX;
  117. FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[NumFramesInFlight];
  118. for (UINT i = 0; i < NumFramesInFlight; ++i)
  119. {
  120. FrameCtx[i].CommandAllocator = nullptr;
  121. FrameCtx[i].RenderTarget = nullptr;
  122. // Create buffers with a default size (they will later be grown as needed)
  123. FrameRenderBuffers[i].IndexBuffer = nullptr;
  124. FrameRenderBuffers[i].VertexBuffer = nullptr;
  125. FrameRenderBuffers[i].VertexBufferSize = 5000;
  126. FrameRenderBuffers[i].IndexBufferSize = 10000;
  127. }
  128. }
  129. ~ImGui_ImplDX12_ViewportData()
  130. {
  131. IM_ASSERT(CommandQueue == nullptr && CommandList == nullptr);
  132. IM_ASSERT(RtvDescHeap == nullptr);
  133. IM_ASSERT(SwapChain == nullptr);
  134. IM_ASSERT(Fence == nullptr);
  135. IM_ASSERT(FenceEvent == nullptr);
  136. for (UINT i = 0; i < NumFramesInFlight; ++i)
  137. {
  138. IM_ASSERT(FrameCtx[i].CommandAllocator == nullptr && FrameCtx[i].RenderTarget == nullptr);
  139. IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == nullptr && FrameRenderBuffers[i].VertexBuffer == nullptr);
  140. }
  141. delete[] FrameCtx; FrameCtx = nullptr;
  142. delete[] FrameRenderBuffers; FrameRenderBuffers = nullptr;
  143. }
  144. };
  145. struct VERTEX_CONSTANT_BUFFER_DX12
  146. {
  147. float mvp[4][4];
  148. };
  149. // Forward Declarations
  150. static void ImGui_ImplDX12_InitPlatformInterface();
  151. static void ImGui_ImplDX12_ShutdownPlatformInterface();
  152. // Functions
  153. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr)
  154. {
  155. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  156. // Setup orthographic projection matrix into our constant buffer
  157. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  158. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  159. {
  160. float L = draw_data->DisplayPos.x;
  161. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  162. float T = draw_data->DisplayPos.y;
  163. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  164. float mvp[4][4] =
  165. {
  166. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  167. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  168. { 0.0f, 0.0f, 0.5f, 0.0f },
  169. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  170. };
  171. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  172. }
  173. // Setup viewport
  174. D3D12_VIEWPORT vp;
  175. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  176. vp.Width = draw_data->DisplaySize.x;
  177. vp.Height = draw_data->DisplaySize.y;
  178. vp.MinDepth = 0.0f;
  179. vp.MaxDepth = 1.0f;
  180. vp.TopLeftX = vp.TopLeftY = 0.0f;
  181. ctx->RSSetViewports(1, &vp);
  182. // Bind shader and vertex buffers
  183. unsigned int stride = sizeof(ImDrawVert);
  184. unsigned int offset = 0;
  185. D3D12_VERTEX_BUFFER_VIEW vbv;
  186. memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
  187. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  188. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  189. vbv.StrideInBytes = stride;
  190. ctx->IASetVertexBuffers(0, 1, &vbv);
  191. D3D12_INDEX_BUFFER_VIEW ibv;
  192. memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
  193. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  194. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  195. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  196. ctx->IASetIndexBuffer(&ibv);
  197. ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  198. ctx->SetPipelineState(bd->pPipelineState);
  199. ctx->SetGraphicsRootSignature(bd->pRootSignature);
  200. ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  201. // Setup blend factor
  202. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  203. ctx->OMSetBlendFactor(blend_factor);
  204. }
  205. template<typename T>
  206. static inline void SafeRelease(T*& res)
  207. {
  208. if (res)
  209. res->Release();
  210. res = nullptr;
  211. }
  212. // Render function
  213. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx)
  214. {
  215. // Avoid rendering when minimized
  216. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  217. return;
  218. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  219. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)draw_data->OwnerViewport->RendererUserData;
  220. vd->FrameIndex++;
  221. ImGui_ImplDX12_RenderBuffers* fr = &vd->FrameRenderBuffers[vd->FrameIndex % bd->numFramesInFlight];
  222. // Create and grow vertex/index buffers if needed
  223. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  224. {
  225. SafeRelease(fr->VertexBuffer);
  226. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  227. D3D12_HEAP_PROPERTIES props;
  228. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  229. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  230. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  231. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  232. D3D12_RESOURCE_DESC desc;
  233. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  234. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  235. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  236. desc.Height = 1;
  237. desc.DepthOrArraySize = 1;
  238. desc.MipLevels = 1;
  239. desc.Format = DXGI_FORMAT_UNKNOWN;
  240. desc.SampleDesc.Count = 1;
  241. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  242. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  243. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  244. return;
  245. }
  246. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  247. {
  248. SafeRelease(fr->IndexBuffer);
  249. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  250. D3D12_HEAP_PROPERTIES props;
  251. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  252. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  253. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  254. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  255. D3D12_RESOURCE_DESC desc;
  256. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  257. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  258. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  259. desc.Height = 1;
  260. desc.DepthOrArraySize = 1;
  261. desc.MipLevels = 1;
  262. desc.Format = DXGI_FORMAT_UNKNOWN;
  263. desc.SampleDesc.Count = 1;
  264. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  265. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  266. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  267. return;
  268. }
  269. // Upload vertex/index data into a single contiguous GPU buffer
  270. void* vtx_resource, *idx_resource;
  271. D3D12_RANGE range;
  272. memset(&range, 0, sizeof(D3D12_RANGE));
  273. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  274. return;
  275. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  276. return;
  277. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  278. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  279. for (int n = 0; n < draw_data->CmdListsCount; n++)
  280. {
  281. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  282. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  283. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  284. vtx_dst += cmd_list->VtxBuffer.Size;
  285. idx_dst += cmd_list->IdxBuffer.Size;
  286. }
  287. fr->VertexBuffer->Unmap(0, &range);
  288. fr->IndexBuffer->Unmap(0, &range);
  289. // Setup desired DX state
  290. ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
  291. // Render command lists
  292. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  293. int global_vtx_offset = 0;
  294. int global_idx_offset = 0;
  295. ImVec2 clip_off = draw_data->DisplayPos;
  296. for (int n = 0; n < draw_data->CmdListsCount; n++)
  297. {
  298. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  299. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  300. {
  301. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  302. if (pcmd->UserCallback != nullptr)
  303. {
  304. // User callback, registered via ImDrawList::AddCallback()
  305. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  306. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  307. ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
  308. else
  309. pcmd->UserCallback(cmd_list, pcmd);
  310. }
  311. else
  312. {
  313. // Project scissor/clipping rectangles into framebuffer space
  314. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  315. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  316. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  317. continue;
  318. // Apply Scissor/clipping rectangle, Bind texture, Draw
  319. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  320. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  321. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  322. ctx->SetGraphicsRootDescriptorTable(1, texture_handle);
  323. ctx->RSSetScissorRects(1, &r);
  324. ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  325. }
  326. }
  327. global_idx_offset += cmd_list->IdxBuffer.Size;
  328. global_vtx_offset += cmd_list->VtxBuffer.Size;
  329. }
  330. }
  331. static void ImGui_ImplDX12_CreateFontsTexture()
  332. {
  333. // Build texture atlas
  334. ImGuiIO& io = ImGui::GetIO();
  335. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  336. unsigned char* pixels;
  337. int width, height;
  338. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  339. // Upload texture to graphics system
  340. {
  341. D3D12_HEAP_PROPERTIES props;
  342. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  343. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  344. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  345. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  346. D3D12_RESOURCE_DESC desc;
  347. ZeroMemory(&desc, sizeof(desc));
  348. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  349. desc.Alignment = 0;
  350. desc.Width = width;
  351. desc.Height = height;
  352. desc.DepthOrArraySize = 1;
  353. desc.MipLevels = 1;
  354. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  355. desc.SampleDesc.Count = 1;
  356. desc.SampleDesc.Quality = 0;
  357. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  358. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  359. ID3D12Resource* pTexture = nullptr;
  360. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  361. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  362. UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  363. UINT uploadSize = height * uploadPitch;
  364. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  365. desc.Alignment = 0;
  366. desc.Width = uploadSize;
  367. desc.Height = 1;
  368. desc.DepthOrArraySize = 1;
  369. desc.MipLevels = 1;
  370. desc.Format = DXGI_FORMAT_UNKNOWN;
  371. desc.SampleDesc.Count = 1;
  372. desc.SampleDesc.Quality = 0;
  373. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  374. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  375. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  376. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  377. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  378. ID3D12Resource* uploadBuffer = nullptr;
  379. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  380. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
  381. IM_ASSERT(SUCCEEDED(hr));
  382. void* mapped = nullptr;
  383. D3D12_RANGE range = { 0, uploadSize };
  384. hr = uploadBuffer->Map(0, &range, &mapped);
  385. IM_ASSERT(SUCCEEDED(hr));
  386. for (int y = 0; y < height; y++)
  387. memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
  388. uploadBuffer->Unmap(0, &range);
  389. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  390. srcLocation.pResource = uploadBuffer;
  391. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  392. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  393. srcLocation.PlacedFootprint.Footprint.Width = width;
  394. srcLocation.PlacedFootprint.Footprint.Height = height;
  395. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  396. srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
  397. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  398. dstLocation.pResource = pTexture;
  399. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  400. dstLocation.SubresourceIndex = 0;
  401. D3D12_RESOURCE_BARRIER barrier = {};
  402. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  403. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  404. barrier.Transition.pResource = pTexture;
  405. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  406. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  407. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  408. ID3D12Fence* fence = nullptr;
  409. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  410. IM_ASSERT(SUCCEEDED(hr));
  411. HANDLE event = CreateEvent(0, 0, 0, 0);
  412. IM_ASSERT(event != nullptr);
  413. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  414. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  415. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  416. queueDesc.NodeMask = 1;
  417. ID3D12CommandQueue* cmdQueue = nullptr;
  418. hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
  419. IM_ASSERT(SUCCEEDED(hr));
  420. ID3D12CommandAllocator* cmdAlloc = nullptr;
  421. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  422. IM_ASSERT(SUCCEEDED(hr));
  423. ID3D12GraphicsCommandList* cmdList = nullptr;
  424. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
  425. IM_ASSERT(SUCCEEDED(hr));
  426. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr);
  427. cmdList->ResourceBarrier(1, &barrier);
  428. hr = cmdList->Close();
  429. IM_ASSERT(SUCCEEDED(hr));
  430. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  431. hr = cmdQueue->Signal(fence, 1);
  432. IM_ASSERT(SUCCEEDED(hr));
  433. fence->SetEventOnCompletion(1, event);
  434. WaitForSingleObject(event, INFINITE);
  435. cmdList->Release();
  436. cmdAlloc->Release();
  437. cmdQueue->Release();
  438. CloseHandle(event);
  439. fence->Release();
  440. uploadBuffer->Release();
  441. // Create texture view
  442. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  443. ZeroMemory(&srvDesc, sizeof(srvDesc));
  444. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  445. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  446. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  447. srvDesc.Texture2D.MostDetailedMip = 0;
  448. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  449. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle);
  450. SafeRelease(bd->pFontTextureResource);
  451. bd->pFontTextureResource = pTexture;
  452. }
  453. // Store our identifier
  454. // READ THIS IF THE STATIC_ASSERT() TRIGGERS:
  455. // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
  456. // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
  457. // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file)
  458. // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
  459. // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
  460. // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file)
  461. static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
  462. io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr);
  463. }
  464. bool ImGui_ImplDX12_CreateDeviceObjects()
  465. {
  466. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  467. if (!bd || !bd->pd3dDevice)
  468. return false;
  469. if (bd->pPipelineState)
  470. ImGui_ImplDX12_InvalidateDeviceObjects();
  471. // Create the root signature
  472. {
  473. D3D12_DESCRIPTOR_RANGE descRange = {};
  474. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  475. descRange.NumDescriptors = 1;
  476. descRange.BaseShaderRegister = 0;
  477. descRange.RegisterSpace = 0;
  478. descRange.OffsetInDescriptorsFromTableStart = 0;
  479. D3D12_ROOT_PARAMETER param[2] = {};
  480. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  481. param[0].Constants.ShaderRegister = 0;
  482. param[0].Constants.RegisterSpace = 0;
  483. param[0].Constants.Num32BitValues = 16;
  484. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  485. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  486. param[1].DescriptorTable.NumDescriptorRanges = 1;
  487. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  488. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  489. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  490. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  491. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  492. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  493. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  494. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  495. staticSampler.MipLODBias = 0.f;
  496. staticSampler.MaxAnisotropy = 0;
  497. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  498. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  499. staticSampler.MinLOD = 0.f;
  500. staticSampler.MaxLOD = 0.f;
  501. staticSampler.ShaderRegister = 0;
  502. staticSampler.RegisterSpace = 0;
  503. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  504. D3D12_ROOT_SIGNATURE_DESC desc = {};
  505. desc.NumParameters = _countof(param);
  506. desc.pParameters = param;
  507. desc.NumStaticSamplers = 1;
  508. desc.pStaticSamplers = &staticSampler;
  509. desc.Flags =
  510. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  511. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  512. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  513. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  514. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  515. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  516. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  517. if (d3d12_dll == nullptr)
  518. {
  519. // Attempt to load d3d12.dll from local directories. This will only succeed if
  520. // (1) the current OS is Windows 7, and
  521. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  522. // See https://github.com/ocornut/imgui/pull/3696 for details.
  523. 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
  524. for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
  525. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  526. break;
  527. // If failed, we are on Windows >= 10.
  528. if (d3d12_dll == nullptr)
  529. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  530. if (d3d12_dll == nullptr)
  531. return false;
  532. }
  533. PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  534. if (D3D12SerializeRootSignatureFn == nullptr)
  535. return false;
  536. ID3DBlob* blob = nullptr;
  537. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  538. return false;
  539. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
  540. blob->Release();
  541. }
  542. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  543. // If you would like to use this DX12 sample code but remove this dependency you can:
  544. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  545. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  546. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  547. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  548. memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  549. psoDesc.NodeMask = 1;
  550. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  551. psoDesc.pRootSignature = bd->pRootSignature;
  552. psoDesc.SampleMask = UINT_MAX;
  553. psoDesc.NumRenderTargets = 1;
  554. psoDesc.RTVFormats[0] = bd->RTVFormat;
  555. psoDesc.SampleDesc.Count = 1;
  556. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  557. ID3DBlob* vertexShaderBlob;
  558. ID3DBlob* pixelShaderBlob;
  559. // Create the vertex shader
  560. {
  561. static const char* vertexShader =
  562. "cbuffer vertexBuffer : register(b0) \
  563. {\
  564. float4x4 ProjectionMatrix; \
  565. };\
  566. struct VS_INPUT\
  567. {\
  568. float2 pos : POSITION;\
  569. float4 col : COLOR0;\
  570. float2 uv : TEXCOORD0;\
  571. };\
  572. \
  573. struct PS_INPUT\
  574. {\
  575. float4 pos : SV_POSITION;\
  576. float4 col : COLOR0;\
  577. float2 uv : TEXCOORD0;\
  578. };\
  579. \
  580. PS_INPUT main(VS_INPUT input)\
  581. {\
  582. PS_INPUT output;\
  583. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  584. output.col = input.col;\
  585. output.uv = input.uv;\
  586. return output;\
  587. }";
  588. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  589. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  590. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  591. // Create the input layout
  592. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  593. {
  594. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  595. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  596. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  597. };
  598. psoDesc.InputLayout = { local_layout, 3 };
  599. }
  600. // Create the pixel shader
  601. {
  602. static const char* pixelShader =
  603. "struct PS_INPUT\
  604. {\
  605. float4 pos : SV_POSITION;\
  606. float4 col : COLOR0;\
  607. float2 uv : TEXCOORD0;\
  608. };\
  609. SamplerState sampler0 : register(s0);\
  610. Texture2D texture0 : register(t0);\
  611. \
  612. float4 main(PS_INPUT input) : SV_Target\
  613. {\
  614. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  615. return out_col; \
  616. }";
  617. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  618. {
  619. vertexShaderBlob->Release();
  620. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  621. }
  622. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  623. }
  624. // Create the blending setup
  625. {
  626. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  627. desc.AlphaToCoverageEnable = false;
  628. desc.RenderTarget[0].BlendEnable = true;
  629. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  630. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  631. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  632. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  633. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  634. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  635. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  636. }
  637. // Create the rasterizer state
  638. {
  639. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  640. desc.FillMode = D3D12_FILL_MODE_SOLID;
  641. desc.CullMode = D3D12_CULL_MODE_NONE;
  642. desc.FrontCounterClockwise = FALSE;
  643. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  644. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  645. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  646. desc.DepthClipEnable = true;
  647. desc.MultisampleEnable = FALSE;
  648. desc.AntialiasedLineEnable = FALSE;
  649. desc.ForcedSampleCount = 0;
  650. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  651. }
  652. // Create depth-stencil State
  653. {
  654. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  655. desc.DepthEnable = false;
  656. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  657. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  658. desc.StencilEnable = false;
  659. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  660. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  661. desc.BackFace = desc.FrontFace;
  662. }
  663. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
  664. vertexShaderBlob->Release();
  665. pixelShaderBlob->Release();
  666. if (result_pipeline_state != S_OK)
  667. return false;
  668. ImGui_ImplDX12_CreateFontsTexture();
  669. return true;
  670. }
  671. static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers)
  672. {
  673. SafeRelease(render_buffers->IndexBuffer);
  674. SafeRelease(render_buffers->VertexBuffer);
  675. render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0;
  676. }
  677. void ImGui_ImplDX12_InvalidateDeviceObjects()
  678. {
  679. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  680. if (!bd || !bd->pd3dDevice)
  681. return;
  682. ImGuiIO& io = ImGui::GetIO();
  683. SafeRelease(bd->pRootSignature);
  684. SafeRelease(bd->pPipelineState);
  685. SafeRelease(bd->pFontTextureResource);
  686. io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
  687. }
  688. bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
  689. D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  690. {
  691. ImGuiIO& io = ImGui::GetIO();
  692. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  693. // Setup backend capabilities flags
  694. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  695. io.BackendRendererUserData = (void*)bd;
  696. io.BackendRendererName = "imgui_impl_dx12";
  697. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  698. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  699. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  700. ImGui_ImplDX12_InitPlatformInterface();
  701. bd->pd3dDevice = device;
  702. bd->RTVFormat = rtv_format;
  703. bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
  704. bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
  705. bd->numFramesInFlight = num_frames_in_flight;
  706. bd->pd3dSrvDescHeap = cbv_srv_heap;
  707. // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport,
  708. // Since this is created and managed by the application, we will only use the ->Resources[] fields.
  709. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  710. main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
  711. return true;
  712. }
  713. void ImGui_ImplDX12_Shutdown()
  714. {
  715. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  716. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  717. ImGuiIO& io = ImGui::GetIO();
  718. // Manually delete main viewport render resources in-case we haven't initialized for viewports
  719. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  720. if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)main_viewport->RendererUserData)
  721. {
  722. // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[]
  723. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  724. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  725. IM_DELETE(vd);
  726. main_viewport->RendererUserData = nullptr;
  727. }
  728. // Clean up windows and device objects
  729. ImGui_ImplDX12_ShutdownPlatformInterface();
  730. ImGui_ImplDX12_InvalidateDeviceObjects();
  731. io.BackendRendererName = nullptr;
  732. io.BackendRendererUserData = nullptr;
  733. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
  734. IM_DELETE(bd);
  735. }
  736. void ImGui_ImplDX12_NewFrame()
  737. {
  738. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  739. IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX12_Init()?");
  740. if (!bd->pPipelineState)
  741. ImGui_ImplDX12_CreateDeviceObjects();
  742. }
  743. //--------------------------------------------------------------------------------------------------------
  744. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  745. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  746. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
  747. //--------------------------------------------------------------------------------------------------------
  748. static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport)
  749. {
  750. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  751. ImGui_ImplDX12_ViewportData* vd = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
  752. viewport->RendererUserData = vd;
  753. // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
  754. // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
  755. HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
  756. IM_ASSERT(hwnd != 0);
  757. vd->FrameIndex = UINT_MAX;
  758. // Create command queue.
  759. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  760. queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  761. queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  762. HRESULT res = S_OK;
  763. res = bd->pd3dDevice->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&vd->CommandQueue));
  764. IM_ASSERT(res == S_OK);
  765. // Create command allocator.
  766. for (UINT i = 0; i < bd->numFramesInFlight; ++i)
  767. {
  768. res = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&vd->FrameCtx[i].CommandAllocator));
  769. IM_ASSERT(res == S_OK);
  770. }
  771. // Create command list.
  772. res = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, vd->FrameCtx[0].CommandAllocator, nullptr, IID_PPV_ARGS(&vd->CommandList));
  773. IM_ASSERT(res == S_OK);
  774. vd->CommandList->Close();
  775. // Create fence.
  776. res = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&vd->Fence));
  777. IM_ASSERT(res == S_OK);
  778. vd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  779. IM_ASSERT(vd->FenceEvent != nullptr);
  780. // Create swap chain
  781. // FIXME-VIEWPORT: May want to copy/inherit swap chain settings from the user/application.
  782. DXGI_SWAP_CHAIN_DESC1 sd1;
  783. ZeroMemory(&sd1, sizeof(sd1));
  784. sd1.BufferCount = bd->numFramesInFlight;
  785. sd1.Width = (UINT)viewport->Size.x;
  786. sd1.Height = (UINT)viewport->Size.y;
  787. sd1.Format = bd->RTVFormat;
  788. sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  789. sd1.SampleDesc.Count = 1;
  790. sd1.SampleDesc.Quality = 0;
  791. sd1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  792. sd1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  793. sd1.Scaling = DXGI_SCALING_NONE;
  794. sd1.Stereo = FALSE;
  795. IDXGIFactory4* dxgi_factory = nullptr;
  796. res = ::CreateDXGIFactory1(IID_PPV_ARGS(&dxgi_factory));
  797. IM_ASSERT(res == S_OK);
  798. IDXGISwapChain1* swap_chain = nullptr;
  799. res = dxgi_factory->CreateSwapChainForHwnd(vd->CommandQueue, hwnd, &sd1, nullptr, nullptr, &swap_chain);
  800. IM_ASSERT(res == S_OK);
  801. dxgi_factory->Release();
  802. // Or swapChain.As(&mSwapChain)
  803. IM_ASSERT(vd->SwapChain == nullptr);
  804. swap_chain->QueryInterface(IID_PPV_ARGS(&vd->SwapChain));
  805. swap_chain->Release();
  806. // Create the render targets
  807. if (vd->SwapChain)
  808. {
  809. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  810. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  811. desc.NumDescriptors = bd->numFramesInFlight;
  812. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  813. desc.NodeMask = 1;
  814. HRESULT hr = bd->pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&vd->RtvDescHeap));
  815. IM_ASSERT(hr == S_OK);
  816. SIZE_T rtv_descriptor_size = bd->pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  817. D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = vd->RtvDescHeap->GetCPUDescriptorHandleForHeapStart();
  818. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  819. {
  820. vd->FrameCtx[i].RenderTargetCpuDescriptors = rtv_handle;
  821. rtv_handle.ptr += rtv_descriptor_size;
  822. }
  823. ID3D12Resource* back_buffer;
  824. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  825. {
  826. IM_ASSERT(vd->FrameCtx[i].RenderTarget == nullptr);
  827. vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
  828. bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
  829. vd->FrameCtx[i].RenderTarget = back_buffer;
  830. }
  831. }
  832. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  833. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  834. }
  835. static void ImGui_WaitForPendingOperations(ImGui_ImplDX12_ViewportData* vd)
  836. {
  837. HRESULT hr = S_FALSE;
  838. if (vd && vd->CommandQueue && vd->Fence && vd->FenceEvent)
  839. {
  840. hr = vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue);
  841. IM_ASSERT(hr == S_OK);
  842. ::WaitForSingleObject(vd->FenceEvent, 0); // Reset any forgotten waits
  843. hr = vd->Fence->SetEventOnCompletion(vd->FenceSignaledValue, vd->FenceEvent);
  844. IM_ASSERT(hr == S_OK);
  845. ::WaitForSingleObject(vd->FenceEvent, INFINITE);
  846. }
  847. }
  848. static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport)
  849. {
  850. // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
  851. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  852. if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData)
  853. {
  854. ImGui_WaitForPendingOperations(vd);
  855. SafeRelease(vd->CommandQueue);
  856. SafeRelease(vd->CommandList);
  857. SafeRelease(vd->SwapChain);
  858. SafeRelease(vd->RtvDescHeap);
  859. SafeRelease(vd->Fence);
  860. ::CloseHandle(vd->FenceEvent);
  861. vd->FenceEvent = nullptr;
  862. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  863. {
  864. SafeRelease(vd->FrameCtx[i].RenderTarget);
  865. SafeRelease(vd->FrameCtx[i].CommandAllocator);
  866. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  867. }
  868. IM_DELETE(vd);
  869. }
  870. viewport->RendererUserData = nullptr;
  871. }
  872. static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  873. {
  874. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  875. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  876. ImGui_WaitForPendingOperations(vd);
  877. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  878. SafeRelease(vd->FrameCtx[i].RenderTarget);
  879. if (vd->SwapChain)
  880. {
  881. ID3D12Resource* back_buffer = nullptr;
  882. vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
  883. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  884. {
  885. vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
  886. bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
  887. vd->FrameCtx[i].RenderTarget = back_buffer;
  888. }
  889. }
  890. }
  891. static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*)
  892. {
  893. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  894. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  895. ImGui_ImplDX12_FrameContext* frame_context = &vd->FrameCtx[vd->FrameIndex % bd->numFramesInFlight];
  896. UINT back_buffer_idx = vd->SwapChain->GetCurrentBackBufferIndex();
  897. const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  898. D3D12_RESOURCE_BARRIER barrier = {};
  899. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  900. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  901. barrier.Transition.pResource = vd->FrameCtx[back_buffer_idx].RenderTarget;
  902. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  903. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  904. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  905. // Draw
  906. ID3D12GraphicsCommandList* cmd_list = vd->CommandList;
  907. frame_context->CommandAllocator->Reset();
  908. cmd_list->Reset(frame_context->CommandAllocator, nullptr);
  909. cmd_list->ResourceBarrier(1, &barrier);
  910. cmd_list->OMSetRenderTargets(1, &vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, FALSE, nullptr);
  911. if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
  912. cmd_list->ClearRenderTargetView(vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, (float*)&clear_color, 0, nullptr);
  913. cmd_list->SetDescriptorHeaps(1, &bd->pd3dSrvDescHeap);
  914. ImGui_ImplDX12_RenderDrawData(viewport->DrawData, cmd_list);
  915. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  916. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  917. cmd_list->ResourceBarrier(1, &barrier);
  918. cmd_list->Close();
  919. vd->CommandQueue->Wait(vd->Fence, vd->FenceSignaledValue);
  920. vd->CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmd_list);
  921. vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue);
  922. }
  923. static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport, void*)
  924. {
  925. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  926. vd->SwapChain->Present(0, 0);
  927. while (vd->Fence->GetCompletedValue() < vd->FenceSignaledValue)
  928. ::SwitchToThread();
  929. }
  930. void ImGui_ImplDX12_InitPlatformInterface()
  931. {
  932. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  933. platform_io.Renderer_CreateWindow = ImGui_ImplDX12_CreateWindow;
  934. platform_io.Renderer_DestroyWindow = ImGui_ImplDX12_DestroyWindow;
  935. platform_io.Renderer_SetWindowSize = ImGui_ImplDX12_SetWindowSize;
  936. platform_io.Renderer_RenderWindow = ImGui_ImplDX12_RenderWindow;
  937. platform_io.Renderer_SwapBuffers = ImGui_ImplDX12_SwapBuffers;
  938. }
  939. void ImGui_ImplDX12_ShutdownPlatformInterface()
  940. {
  941. ImGui::DestroyPlatformWindows();
  942. }
  943. //-----------------------------------------------------------------------------
  944. #endif // #ifndef IMGUI_DISABLE