imgui_impl_dx12.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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 texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
  7. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  8. // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  9. // FIXME: The transition from removing a viewport and moving the window in an existing hosted viewport tends to flicker.
  10. // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
  11. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  12. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  13. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  14. // Learn about Dear ImGui:
  15. // - FAQ https://dearimgui.com/faq
  16. // - Getting Started https://dearimgui.com/getting-started
  17. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  18. // - Introduction, links and more at the top of imgui.cpp
  19. // CHANGELOG
  20. // (minor and older changes stripped away, please see git history for details)
  21. // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  22. // 2025-10-23: [Docking] DirectX12: Fixed an issue in synchronization logic improving rendering throughput for secondary viewports. (#8961, #9025)
  23. // 2025-10-11: DirectX12: Reuse texture upload buffer and grow it only when necessary. (#9002)
  24. // 2025-09-29: DirectX12: Rework synchronization logic. (#8961)
  25. // 2025-09-29: DirectX12: Enable swapchain tearing to eliminate viewports framerate throttling. (#8965)
  26. // 2025-09-29: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963)
  27. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
  28. // 2025-06-19: Fixed build on MinGW. (#8702, #4594)
  29. // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
  30. // 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
  31. // 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429)
  32. // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own.
  33. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
  34. // 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).
  35. // 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.
  36. // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
  37. // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  38. // 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.
  39. // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  40. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  41. // 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).
  42. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  43. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  44. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  45. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  46. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  47. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  48. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  49. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  50. // 2019-03-29: Misc: Various minor tidying up.
  51. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  52. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  53. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  54. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  55. // 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).
  56. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  57. #include "imgui.h"
  58. #ifndef IMGUI_DISABLE
  59. #include "imgui_impl_dx12.h"
  60. // DirectX
  61. #include <d3d12.h>
  62. #include <dxgi1_5.h>
  63. #include <d3dcompiler.h>
  64. #ifdef _MSC_VER
  65. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  66. #endif
  67. // Clang/GCC warnings with -Weverything
  68. #if defined(__clang__)
  69. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  70. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  71. #endif
  72. // MinGW workaround, see #4594
  73. typedef decltype(D3D12SerializeRootSignature) *_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE;
  74. // DirectX12 data
  75. struct ImGui_ImplDX12_RenderBuffers;
  76. struct ImGui_ImplDX12_Texture
  77. {
  78. ID3D12Resource* pTextureResource;
  79. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  80. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  81. ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
  82. };
  83. struct ImGui_ImplDX12_Data
  84. {
  85. ImGui_ImplDX12_InitInfo InitInfo;
  86. IDXGIFactory5* pdxgiFactory;
  87. ID3D12Device* pd3dDevice;
  88. ID3D12RootSignature* pRootSignature;
  89. ID3D12PipelineState* pPipelineState;
  90. ID3D12CommandQueue* pCommandQueue;
  91. bool commandQueueOwned;
  92. DXGI_FORMAT RTVFormat;
  93. DXGI_FORMAT DSVFormat;
  94. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  95. ID3D12Fence* Fence;
  96. UINT64 FenceLastSignaledValue;
  97. HANDLE FenceEvent;
  98. UINT numFramesInFlight;
  99. bool tearingSupport;
  100. bool LegacySingleDescriptorUsed;
  101. ID3D12CommandAllocator* pTexCmdAllocator;
  102. ID3D12GraphicsCommandList* pTexCmdList;
  103. ID3D12Resource* pTexUploadBuffer;
  104. UINT pTexUploadBufferSize;
  105. void* pTexUploadBufferMapped;
  106. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); }
  107. };
  108. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  109. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  110. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  111. {
  112. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  113. }
  114. // Buffers used during the rendering of a frame
  115. struct ImGui_ImplDX12_RenderBuffers
  116. {
  117. ID3D12Resource* IndexBuffer;
  118. ID3D12Resource* VertexBuffer;
  119. int IndexBufferSize;
  120. int VertexBufferSize;
  121. };
  122. // Buffers used for secondary viewports created by the multi-viewports systems
  123. struct ImGui_ImplDX12_FrameContext
  124. {
  125. UINT64 FenceValue;
  126. ID3D12CommandAllocator* CommandAllocator;
  127. ID3D12Resource* RenderTarget;
  128. D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors;
  129. };
  130. // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
  131. // Main viewport created by application will only use the Resources field.
  132. // Secondary viewports created by this backend will use all the fields (including Window fields),
  133. struct ImGui_ImplDX12_ViewportData
  134. {
  135. // Window
  136. ID3D12CommandQueue* CommandQueue;
  137. ID3D12GraphicsCommandList* CommandList;
  138. ID3D12DescriptorHeap* RtvDescHeap;
  139. IDXGISwapChain3* SwapChain;
  140. HANDLE SwapChainWaitableObject;
  141. UINT NumFramesInFlight;
  142. ImGui_ImplDX12_FrameContext* FrameCtx;
  143. // Render buffers
  144. UINT FrameIndex;
  145. ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers;
  146. ImGui_ImplDX12_ViewportData(UINT num_frames_in_flight)
  147. {
  148. CommandQueue = nullptr;
  149. CommandList = nullptr;
  150. RtvDescHeap = nullptr;
  151. SwapChain = nullptr;
  152. SwapChainWaitableObject = nullptr;
  153. NumFramesInFlight = num_frames_in_flight;
  154. FrameCtx = new ImGui_ImplDX12_FrameContext[NumFramesInFlight];
  155. FrameIndex = 0;
  156. FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[NumFramesInFlight];
  157. for (UINT i = 0; i < NumFramesInFlight; ++i)
  158. {
  159. FrameCtx[i].FenceValue = 0;
  160. FrameCtx[i].CommandAllocator = nullptr;
  161. FrameCtx[i].RenderTarget = nullptr;
  162. // Create buffers with a default size (they will later be grown as needed)
  163. FrameRenderBuffers[i].IndexBuffer = nullptr;
  164. FrameRenderBuffers[i].VertexBuffer = nullptr;
  165. FrameRenderBuffers[i].VertexBufferSize = 5000;
  166. FrameRenderBuffers[i].IndexBufferSize = 10000;
  167. }
  168. }
  169. ~ImGui_ImplDX12_ViewportData()
  170. {
  171. IM_ASSERT(CommandQueue == nullptr && CommandList == nullptr);
  172. IM_ASSERT(RtvDescHeap == nullptr);
  173. IM_ASSERT(SwapChain == nullptr);
  174. IM_ASSERT(SwapChainWaitableObject == nullptr);
  175. for (UINT i = 0; i < NumFramesInFlight; ++i)
  176. {
  177. IM_ASSERT(FrameCtx[i].CommandAllocator == nullptr && FrameCtx[i].RenderTarget == nullptr);
  178. IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == nullptr && FrameRenderBuffers[i].VertexBuffer == nullptr);
  179. }
  180. delete[] FrameCtx; FrameCtx = nullptr;
  181. delete[] FrameRenderBuffers; FrameRenderBuffers = nullptr;
  182. }
  183. };
  184. struct VERTEX_CONSTANT_BUFFER_DX12
  185. {
  186. float mvp[4][4];
  187. };
  188. // Forward Declarations
  189. static void ImGui_ImplDX12_InitMultiViewportSupport();
  190. static void ImGui_ImplDX12_ShutdownMultiViewportSupport();
  191. // Functions
  192. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
  193. {
  194. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  195. // Setup orthographic projection matrix into our constant buffer
  196. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  197. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  198. {
  199. float L = draw_data->DisplayPos.x;
  200. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  201. float T = draw_data->DisplayPos.y;
  202. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  203. float mvp[4][4] =
  204. {
  205. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  206. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  207. { 0.0f, 0.0f, 0.5f, 0.0f },
  208. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  209. };
  210. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  211. }
  212. // Setup viewport
  213. D3D12_VIEWPORT vp = {};
  214. vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
  215. vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
  216. vp.MinDepth = 0.0f;
  217. vp.MaxDepth = 1.0f;
  218. vp.TopLeftX = vp.TopLeftY = 0.0f;
  219. command_list->RSSetViewports(1, &vp);
  220. // Bind shader and vertex buffers
  221. unsigned int stride = sizeof(ImDrawVert);
  222. unsigned int offset = 0;
  223. D3D12_VERTEX_BUFFER_VIEW vbv = {};
  224. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  225. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  226. vbv.StrideInBytes = stride;
  227. command_list->IASetVertexBuffers(0, 1, &vbv);
  228. D3D12_INDEX_BUFFER_VIEW ibv = {};
  229. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  230. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  231. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  232. command_list->IASetIndexBuffer(&ibv);
  233. command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  234. command_list->SetPipelineState(bd->pPipelineState);
  235. command_list->SetGraphicsRootSignature(bd->pRootSignature);
  236. command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  237. // Setup blend factor
  238. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  239. command_list->OMSetBlendFactor(blend_factor);
  240. }
  241. template<typename T>
  242. static inline void SafeRelease(T*& res)
  243. {
  244. if (res)
  245. res->Release();
  246. res = nullptr;
  247. }
  248. // Render function
  249. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
  250. {
  251. // Avoid rendering when minimized
  252. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  253. return;
  254. // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
  255. // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
  256. if (draw_data->Textures != nullptr)
  257. for (ImTextureData* tex : *draw_data->Textures)
  258. if (tex->Status != ImTextureStatus_OK)
  259. ImGui_ImplDX12_UpdateTexture(tex);
  260. // FIXME: We are assuming that this only gets called once per frame!
  261. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  262. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)draw_data->OwnerViewport->RendererUserData;
  263. ImGui_ImplDX12_RenderBuffers* fr = &vd->FrameRenderBuffers[vd->FrameIndex % bd->numFramesInFlight];
  264. vd->FrameIndex++;
  265. // Create and grow vertex/index buffers if needed
  266. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  267. {
  268. SafeRelease(fr->VertexBuffer);
  269. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  270. D3D12_HEAP_PROPERTIES props = {};
  271. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  272. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  273. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  274. D3D12_RESOURCE_DESC desc = {};
  275. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  276. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  277. desc.Height = 1;
  278. desc.DepthOrArraySize = 1;
  279. desc.MipLevels = 1;
  280. desc.Format = DXGI_FORMAT_UNKNOWN;
  281. desc.SampleDesc.Count = 1;
  282. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  283. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  284. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  285. return;
  286. }
  287. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  288. {
  289. SafeRelease(fr->IndexBuffer);
  290. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  291. D3D12_HEAP_PROPERTIES props = {};
  292. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  293. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  294. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  295. D3D12_RESOURCE_DESC desc = {};
  296. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  297. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  298. desc.Height = 1;
  299. desc.DepthOrArraySize = 1;
  300. desc.MipLevels = 1;
  301. desc.Format = DXGI_FORMAT_UNKNOWN;
  302. desc.SampleDesc.Count = 1;
  303. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  304. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  305. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  306. return;
  307. }
  308. // Upload vertex/index data into a single contiguous GPU buffer
  309. // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
  310. void* vtx_resource, *idx_resource;
  311. D3D12_RANGE range = { 0, 0 };
  312. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  313. return;
  314. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  315. return;
  316. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  317. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  318. for (const ImDrawList* draw_list : draw_data->CmdLists)
  319. {
  320. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  321. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  322. vtx_dst += draw_list->VtxBuffer.Size;
  323. idx_dst += draw_list->IdxBuffer.Size;
  324. }
  325. // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
  326. range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
  327. IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
  328. fr->VertexBuffer->Unmap(0, &range);
  329. range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
  330. IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
  331. fr->IndexBuffer->Unmap(0, &range);
  332. // Setup desired DX state
  333. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  334. // Setup render state structure (for callbacks and custom texture bindings)
  335. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  336. ImGui_ImplDX12_RenderState render_state;
  337. render_state.Device = bd->pd3dDevice;
  338. render_state.CommandList = command_list;
  339. platform_io.Renderer_RenderState = &render_state;
  340. // Render command lists
  341. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  342. int global_vtx_offset = 0;
  343. int global_idx_offset = 0;
  344. ImVec2 clip_off = draw_data->DisplayPos;
  345. ImVec2 clip_scale = draw_data->FramebufferScale;
  346. for (const ImDrawList* draw_list : draw_data->CmdLists)
  347. {
  348. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  349. {
  350. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  351. if (pcmd->UserCallback != nullptr)
  352. {
  353. // User callback, registered via ImDrawList::AddCallback()
  354. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  355. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  356. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  357. else
  358. pcmd->UserCallback(draw_list, pcmd);
  359. }
  360. else
  361. {
  362. // Project scissor/clipping rectangles into framebuffer space
  363. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  364. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  365. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  366. continue;
  367. // Apply scissor/clipping rectangle
  368. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  369. command_list->RSSetScissorRects(1, &r);
  370. // Bind texture, Draw
  371. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  372. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  373. command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
  374. command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  375. }
  376. }
  377. global_idx_offset += draw_list->IdxBuffer.Size;
  378. global_vtx_offset += draw_list->VtxBuffer.Size;
  379. }
  380. platform_io.Renderer_RenderState = nullptr;
  381. }
  382. static void ImGui_ImplDX12_DestroyTexture(ImTextureData* tex)
  383. {
  384. if (ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData)
  385. {
  386. IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID);
  387. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  388. bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle);
  389. SafeRelease(backend_tex->pTextureResource);
  390. backend_tex->hFontSrvCpuDescHandle.ptr = 0;
  391. backend_tex->hFontSrvGpuDescHandle.ptr = 0;
  392. IM_DELETE(backend_tex);
  393. // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
  394. tex->SetTexID(ImTextureID_Invalid);
  395. tex->BackendUserData = nullptr;
  396. }
  397. tex->SetStatus(ImTextureStatus_Destroyed);
  398. }
  399. void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex)
  400. {
  401. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  402. bool need_barrier_before_copy = true; // Do we need a resource barrier before we copy new data in?
  403. if (tex->Status == ImTextureStatus_WantCreate)
  404. {
  405. // Create and upload new texture to graphics system
  406. //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
  407. IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
  408. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  409. ImGui_ImplDX12_Texture* backend_tex = IM_NEW(ImGui_ImplDX12_Texture)();
  410. bd->InitInfo.SrvDescriptorAllocFn(&bd->InitInfo, &backend_tex->hFontSrvCpuDescHandle, &backend_tex->hFontSrvGpuDescHandle); // Allocate a desctriptor handle
  411. D3D12_HEAP_PROPERTIES props = {};
  412. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  413. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  414. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  415. D3D12_RESOURCE_DESC desc;
  416. ZeroMemory(&desc, sizeof(desc));
  417. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  418. desc.Alignment = 0;
  419. desc.Width = tex->Width;
  420. desc.Height = tex->Height;
  421. desc.DepthOrArraySize = 1;
  422. desc.MipLevels = 1;
  423. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  424. desc.SampleDesc.Count = 1;
  425. desc.SampleDesc.Quality = 0;
  426. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  427. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  428. ID3D12Resource* pTexture = nullptr;
  429. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  430. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  431. // Create SRV
  432. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  433. ZeroMemory(&srvDesc, sizeof(srvDesc));
  434. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  435. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  436. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  437. srvDesc.Texture2D.MostDetailedMip = 0;
  438. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  439. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, backend_tex->hFontSrvCpuDescHandle);
  440. SafeRelease(backend_tex->pTextureResource);
  441. backend_tex->pTextureResource = pTexture;
  442. // Store identifiers
  443. tex->SetTexID((ImTextureID)backend_tex->hFontSrvGpuDescHandle.ptr);
  444. tex->BackendUserData = backend_tex;
  445. need_barrier_before_copy = false; // Because this is a newly-created texture it will be in D3D12_RESOURCE_STATE_COMMON and thus we don't need a barrier
  446. // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
  447. }
  448. if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
  449. {
  450. ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData;
  451. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  452. // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
  453. // FIXME-OPT: Uploading single box even when using ImTextureStatus_WantUpdates. Could use tex->Updates[]
  454. // - Copy all blocks contiguously in upload buffer.
  455. // - Barrier before copy, submit all CopyTextureRegion(), barrier after copy.
  456. const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
  457. const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
  458. const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
  459. const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
  460. // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
  461. // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
  462. UINT upload_pitch_src = upload_w * tex->BytesPerPixel;
  463. UINT upload_pitch_dst = (upload_pitch_src + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  464. UINT upload_size = upload_pitch_dst * upload_h;
  465. if (bd->pTexUploadBuffer == nullptr || upload_size > bd->pTexUploadBufferSize)
  466. {
  467. if (bd->pTexUploadBufferMapped)
  468. {
  469. D3D12_RANGE range = { 0, bd->pTexUploadBufferSize };
  470. bd->pTexUploadBuffer->Unmap(0, &range);
  471. bd->pTexUploadBufferMapped = nullptr;
  472. }
  473. SafeRelease(bd->pTexUploadBuffer);
  474. D3D12_RESOURCE_DESC desc;
  475. ZeroMemory(&desc, sizeof(desc));
  476. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  477. desc.Alignment = 0;
  478. desc.Width = upload_size;
  479. desc.Height = 1;
  480. desc.DepthOrArraySize = 1;
  481. desc.MipLevels = 1;
  482. desc.Format = DXGI_FORMAT_UNKNOWN;
  483. desc.SampleDesc.Count = 1;
  484. desc.SampleDesc.Quality = 0;
  485. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  486. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  487. D3D12_HEAP_PROPERTIES props;
  488. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  489. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  490. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  491. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  492. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  493. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&bd->pTexUploadBuffer));
  494. IM_ASSERT(SUCCEEDED(hr));
  495. D3D12_RANGE range = {0, upload_size};
  496. hr = bd->pTexUploadBuffer->Map(0, &range, &bd->pTexUploadBufferMapped);
  497. IM_ASSERT(SUCCEEDED(hr));
  498. bd->pTexUploadBufferSize = upload_size;
  499. }
  500. bd->pTexCmdAllocator->Reset();
  501. bd->pTexCmdList->Reset(bd->pTexCmdAllocator, nullptr);
  502. ID3D12GraphicsCommandList* cmdList = bd->pTexCmdList;
  503. // Copy to upload buffer
  504. for (int y = 0; y < upload_h; y++)
  505. memcpy((void*)((uintptr_t)bd->pTexUploadBufferMapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src);
  506. if (need_barrier_before_copy)
  507. {
  508. D3D12_RESOURCE_BARRIER barrier = {};
  509. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  510. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  511. barrier.Transition.pResource = backend_tex->pTextureResource;
  512. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  513. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  514. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
  515. cmdList->ResourceBarrier(1, &barrier);
  516. }
  517. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  518. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  519. {
  520. srcLocation.pResource = bd->pTexUploadBuffer;
  521. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  522. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  523. srcLocation.PlacedFootprint.Footprint.Width = upload_w;
  524. srcLocation.PlacedFootprint.Footprint.Height = upload_h;
  525. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  526. srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch_dst;
  527. dstLocation.pResource = backend_tex->pTextureResource;
  528. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  529. dstLocation.SubresourceIndex = 0;
  530. }
  531. cmdList->CopyTextureRegion(&dstLocation, upload_x, upload_y, 0, &srcLocation, nullptr);
  532. {
  533. D3D12_RESOURCE_BARRIER barrier = {};
  534. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  535. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  536. barrier.Transition.pResource = backend_tex->pTextureResource;
  537. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  538. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  539. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  540. cmdList->ResourceBarrier(1, &barrier);
  541. }
  542. HRESULT hr = cmdList->Close();
  543. IM_ASSERT(SUCCEEDED(hr));
  544. ID3D12CommandQueue* cmdQueue = bd->pCommandQueue;
  545. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  546. hr = cmdQueue->Signal(bd->Fence, ++bd->FenceLastSignaledValue);
  547. IM_ASSERT(SUCCEEDED(hr));
  548. // FIXME-OPT: Suboptimal?
  549. // - To remove this may need to create NumFramesInFlight x ImGui_ImplDX12_FrameContext in backend data (mimick docking version)
  550. // - Store per-frame in flight: upload buffer?
  551. // - Where do cmdList and cmdAlloc fit?
  552. bd->Fence->SetEventOnCompletion(bd->FenceLastSignaledValue, bd->FenceEvent);
  553. ::WaitForSingleObject(bd->FenceEvent, INFINITE);
  554. tex->SetStatus(ImTextureStatus_OK);
  555. }
  556. if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames >= (int)bd->numFramesInFlight)
  557. ImGui_ImplDX12_DestroyTexture(tex);
  558. }
  559. bool ImGui_ImplDX12_CreateDeviceObjects()
  560. {
  561. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  562. if (!bd || !bd->pd3dDevice)
  563. return false;
  564. if (bd->pPipelineState)
  565. ImGui_ImplDX12_InvalidateDeviceObjects();
  566. HRESULT hr = ::CreateDXGIFactory1(IID_PPV_ARGS(&bd->pdxgiFactory));
  567. IM_ASSERT(hr == S_OK);
  568. BOOL allow_tearing = FALSE;
  569. bd->pdxgiFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing, sizeof(allow_tearing));
  570. bd->tearingSupport = (allow_tearing == TRUE);
  571. // Create the root signature
  572. {
  573. D3D12_DESCRIPTOR_RANGE descRange = {};
  574. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  575. descRange.NumDescriptors = 1;
  576. descRange.BaseShaderRegister = 0;
  577. descRange.RegisterSpace = 0;
  578. descRange.OffsetInDescriptorsFromTableStart = 0;
  579. D3D12_ROOT_PARAMETER param[2] = {};
  580. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  581. param[0].Constants.ShaderRegister = 0;
  582. param[0].Constants.RegisterSpace = 0;
  583. param[0].Constants.Num32BitValues = 16;
  584. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  585. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  586. param[1].DescriptorTable.NumDescriptorRanges = 1;
  587. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  588. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  589. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  590. D3D12_STATIC_SAMPLER_DESC staticSampler[1] = {};
  591. staticSampler[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  592. staticSampler[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  593. staticSampler[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  594. staticSampler[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  595. staticSampler[0].MipLODBias = 0.f;
  596. staticSampler[0].MaxAnisotropy = 0;
  597. staticSampler[0].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  598. staticSampler[0].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  599. staticSampler[0].MinLOD = 0.f;
  600. staticSampler[0].MaxLOD = D3D12_FLOAT32_MAX;
  601. staticSampler[0].ShaderRegister = 0;
  602. staticSampler[0].RegisterSpace = 0;
  603. staticSampler[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  604. D3D12_ROOT_SIGNATURE_DESC desc = {};
  605. desc.NumParameters = _countof(param);
  606. desc.pParameters = param;
  607. desc.NumStaticSamplers = 1;
  608. desc.pStaticSamplers = &staticSampler[0];
  609. desc.Flags =
  610. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  611. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  612. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  613. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  614. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  615. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  616. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  617. if (d3d12_dll == nullptr)
  618. {
  619. // Attempt to load d3d12.dll from local directories. This will only succeed if
  620. // (1) the current OS is Windows 7, and
  621. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  622. // See https://github.com/ocornut/imgui/pull/3696 for details.
  623. 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
  624. for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
  625. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  626. break;
  627. // If failed, we are on Windows >= 10.
  628. if (d3d12_dll == nullptr)
  629. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  630. if (d3d12_dll == nullptr)
  631. return false;
  632. }
  633. _PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  634. if (D3D12SerializeRootSignatureFn == nullptr)
  635. return false;
  636. ID3DBlob* blob = nullptr;
  637. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  638. return false;
  639. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
  640. blob->Release();
  641. }
  642. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  643. // If you would like to use this DX12 sample code but remove this dependency you can:
  644. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  645. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  646. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  647. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  648. psoDesc.NodeMask = 1;
  649. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  650. psoDesc.pRootSignature = bd->pRootSignature;
  651. psoDesc.SampleMask = UINT_MAX;
  652. psoDesc.NumRenderTargets = 1;
  653. psoDesc.RTVFormats[0] = bd->RTVFormat;
  654. psoDesc.DSVFormat = bd->DSVFormat;
  655. psoDesc.SampleDesc.Count = 1;
  656. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  657. ID3DBlob* vertexShaderBlob;
  658. ID3DBlob* pixelShaderBlob;
  659. // Create the vertex shader
  660. {
  661. static const char* vertexShader =
  662. "cbuffer vertexBuffer : register(b0) \
  663. {\
  664. float4x4 ProjectionMatrix; \
  665. };\
  666. struct VS_INPUT\
  667. {\
  668. float2 pos : POSITION;\
  669. float4 col : COLOR0;\
  670. float2 uv : TEXCOORD0;\
  671. };\
  672. \
  673. struct PS_INPUT\
  674. {\
  675. float4 pos : SV_POSITION;\
  676. float4 col : COLOR0;\
  677. float2 uv : TEXCOORD0;\
  678. };\
  679. \
  680. PS_INPUT main(VS_INPUT input)\
  681. {\
  682. PS_INPUT output;\
  683. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  684. output.col = input.col;\
  685. output.uv = input.uv;\
  686. return output;\
  687. }";
  688. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  689. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  690. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  691. // Create the input layout
  692. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  693. {
  694. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  695. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  696. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  697. };
  698. psoDesc.InputLayout = { local_layout, 3 };
  699. }
  700. // Create the pixel shader
  701. {
  702. static const char* pixelShader =
  703. "struct PS_INPUT\
  704. {\
  705. float4 pos : SV_POSITION;\
  706. float4 col : COLOR0;\
  707. float2 uv : TEXCOORD0;\
  708. };\
  709. SamplerState sampler0 : register(s0);\
  710. Texture2D texture0 : register(t0);\
  711. \
  712. float4 main(PS_INPUT input) : SV_Target\
  713. {\
  714. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  715. return out_col; \
  716. }";
  717. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  718. {
  719. vertexShaderBlob->Release();
  720. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  721. }
  722. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  723. }
  724. // Create the blending setup
  725. {
  726. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  727. desc.AlphaToCoverageEnable = false;
  728. desc.RenderTarget[0].BlendEnable = true;
  729. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  730. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  731. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  732. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  733. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  734. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  735. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  736. }
  737. // Create the rasterizer state
  738. {
  739. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  740. desc.FillMode = D3D12_FILL_MODE_SOLID;
  741. desc.CullMode = D3D12_CULL_MODE_NONE;
  742. desc.FrontCounterClockwise = FALSE;
  743. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  744. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  745. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  746. desc.DepthClipEnable = true;
  747. desc.MultisampleEnable = FALSE;
  748. desc.AntialiasedLineEnable = FALSE;
  749. desc.ForcedSampleCount = 0;
  750. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  751. }
  752. // Create depth-stencil State
  753. {
  754. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  755. desc.DepthEnable = false;
  756. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  757. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  758. desc.StencilEnable = false;
  759. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  760. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  761. desc.BackFace = desc.FrontFace;
  762. }
  763. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
  764. vertexShaderBlob->Release();
  765. pixelShaderBlob->Release();
  766. if (result_pipeline_state != S_OK)
  767. return false;
  768. // Create command allocator and command list for ImGui_ImplDX12_UpdateTexture()
  769. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&bd->pTexCmdAllocator));
  770. IM_ASSERT(SUCCEEDED(hr));
  771. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, bd->pTexCmdAllocator, nullptr, IID_PPV_ARGS(&bd->pTexCmdList));
  772. IM_ASSERT(SUCCEEDED(hr));
  773. hr = bd->pTexCmdList->Close();
  774. IM_ASSERT(SUCCEEDED(hr));
  775. // Create fence.
  776. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&bd->Fence));
  777. IM_ASSERT(hr == S_OK);
  778. bd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  779. IM_ASSERT(bd->FenceEvent != nullptr);
  780. return true;
  781. }
  782. static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers)
  783. {
  784. SafeRelease(render_buffers->IndexBuffer);
  785. SafeRelease(render_buffers->VertexBuffer);
  786. render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0;
  787. }
  788. void ImGui_ImplDX12_InvalidateDeviceObjects()
  789. {
  790. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  791. if (!bd || !bd->pd3dDevice)
  792. return;
  793. SafeRelease(bd->pdxgiFactory);
  794. if (bd->commandQueueOwned)
  795. SafeRelease(bd->pCommandQueue);
  796. bd->commandQueueOwned = false;
  797. SafeRelease(bd->pRootSignature);
  798. SafeRelease(bd->pPipelineState);
  799. if (bd->pTexUploadBufferMapped)
  800. {
  801. D3D12_RANGE range = { 0, bd->pTexUploadBufferSize };
  802. bd->pTexUploadBuffer->Unmap(0, &range);
  803. bd->pTexUploadBufferMapped = nullptr;
  804. }
  805. SafeRelease(bd->pTexUploadBuffer);
  806. SafeRelease(bd->pTexCmdList);
  807. SafeRelease(bd->pTexCmdAllocator);
  808. SafeRelease(bd->Fence);
  809. CloseHandle(bd->FenceEvent);
  810. bd->FenceEvent = nullptr;
  811. // Destroy all textures
  812. for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
  813. if (tex->RefCount == 1)
  814. ImGui_ImplDX12_DestroyTexture(tex);
  815. }
  816. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  817. static void ImGui_ImplDX12_InitLegacySingleDescriptorMode(ImGui_ImplDX12_InitInfo* init_info)
  818. {
  819. // Wrap legacy behavior of passing space for a single descriptor
  820. IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
  821. init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
  822. {
  823. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  824. IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!");
  825. *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
  826. *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
  827. bd->LegacySingleDescriptorUsed = true;
  828. };
  829. init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
  830. {
  831. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  832. IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
  833. bd->LegacySingleDescriptorUsed = false;
  834. };
  835. }
  836. #endif
  837. bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
  838. {
  839. ImGuiIO& io = ImGui::GetIO();
  840. IMGUI_CHECKVERSION();
  841. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  842. // Setup backend capabilities flags
  843. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  844. bd->InitInfo = *init_info; // Deep copy
  845. init_info = &bd->InitInfo;
  846. bd->pd3dDevice = init_info->Device;
  847. IM_ASSERT(init_info->CommandQueue != NULL);
  848. bd->pCommandQueue = init_info->CommandQueue;
  849. bd->RTVFormat = init_info->RTVFormat;
  850. bd->DSVFormat = init_info->DSVFormat;
  851. bd->numFramesInFlight = init_info->NumFramesInFlight;
  852. bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
  853. bd->tearingSupport = false;
  854. io.BackendRendererUserData = (void*)bd;
  855. io.BackendRendererName = "imgui_impl_dx12";
  856. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  857. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
  858. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  859. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  860. ImGui_ImplDX12_InitMultiViewportSupport();
  861. // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport,
  862. // Since this is created and managed by the application, we will only use the ->Resources[] fields.
  863. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  864. main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
  865. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  866. if (init_info->SrvDescriptorAllocFn == nullptr)
  867. ImGui_ImplDX12_InitLegacySingleDescriptorMode(init_info);
  868. #endif
  869. IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
  870. return true;
  871. }
  872. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  873. // Legacy initialization API Obsoleted in 1.91.5
  874. // 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'
  875. 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)
  876. {
  877. ImGui_ImplDX12_InitInfo init_info;
  878. init_info.Device = device;
  879. init_info.NumFramesInFlight = num_frames_in_flight;
  880. init_info.RTVFormat = rtv_format;
  881. init_info.SrvDescriptorHeap = srv_descriptor_heap;
  882. init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
  883. init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;
  884. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  885. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  886. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  887. queueDesc.NodeMask = 1;
  888. HRESULT hr = device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&init_info.CommandQueue));
  889. IM_ASSERT(SUCCEEDED(hr));
  890. bool ret = ImGui_ImplDX12_Init(&init_info);
  891. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  892. bd->commandQueueOwned = true;
  893. ImGuiIO& io = ImGui::GetIO();
  894. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; // Using legacy ImGui_ImplDX12_Init() call with 1 SRV descriptor we cannot support multiple textures.
  895. return ret;
  896. }
  897. #endif
  898. void ImGui_ImplDX12_Shutdown()
  899. {
  900. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  901. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  902. ImGuiIO& io = ImGui::GetIO();
  903. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  904. // Manually delete main viewport render resources in-case we haven't initialized for viewports
  905. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  906. if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)main_viewport->RendererUserData)
  907. {
  908. // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[]
  909. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  910. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  911. IM_DELETE(vd);
  912. main_viewport->RendererUserData = nullptr;
  913. }
  914. ImGui_ImplDX12_ShutdownMultiViewportSupport();
  915. ImGui_ImplDX12_InvalidateDeviceObjects();
  916. io.BackendRendererName = nullptr;
  917. io.BackendRendererUserData = nullptr;
  918. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
  919. platform_io.ClearRendererHandlers();
  920. IM_DELETE(bd);
  921. }
  922. void ImGui_ImplDX12_NewFrame()
  923. {
  924. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  925. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
  926. if (!bd->pPipelineState)
  927. if (!ImGui_ImplDX12_CreateDeviceObjects())
  928. IM_ASSERT(0 && "ImGui_ImplDX12_CreateDeviceObjects() failed!");
  929. }
  930. //--------------------------------------------------------------------------------------------------------
  931. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  932. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  933. // 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..
  934. //--------------------------------------------------------------------------------------------------------
  935. static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport)
  936. {
  937. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  938. ImGui_ImplDX12_ViewportData* vd = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
  939. viewport->RendererUserData = vd;
  940. // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL's WindowID).
  941. // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
  942. HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
  943. IM_ASSERT(hwnd != 0);
  944. // Use shared command queue from init info
  945. vd->FrameIndex = 0;
  946. vd->CommandQueue = bd->pCommandQueue;
  947. // Create command allocator.
  948. HRESULT res = S_OK;
  949. for (UINT i = 0; i < bd->numFramesInFlight; ++i)
  950. {
  951. res = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&vd->FrameCtx[i].CommandAllocator));
  952. IM_ASSERT(res == S_OK);
  953. }
  954. // Create command list.
  955. res = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, vd->FrameCtx[0].CommandAllocator, nullptr, IID_PPV_ARGS(&vd->CommandList));
  956. IM_ASSERT(res == S_OK);
  957. vd->CommandList->Close();
  958. // Create swap chain
  959. // FIXME-VIEWPORT: May want to copy/inherit swap chain settings from the user/application.
  960. DXGI_SWAP_CHAIN_DESC1 sd1;
  961. ZeroMemory(&sd1, sizeof(sd1));
  962. sd1.BufferCount = bd->numFramesInFlight;
  963. sd1.Width = (UINT)viewport->Size.x;
  964. sd1.Height = (UINT)viewport->Size.y;
  965. sd1.Format = bd->RTVFormat;
  966. sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  967. sd1.SampleDesc.Count = 1;
  968. sd1.SampleDesc.Quality = 0;
  969. sd1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  970. sd1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  971. sd1.Scaling = DXGI_SCALING_NONE;
  972. sd1.Stereo = FALSE;
  973. sd1.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
  974. if (bd->tearingSupport)
  975. sd1.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
  976. IDXGISwapChain1* swap_chain = nullptr;
  977. res = bd->pdxgiFactory->CreateSwapChainForHwnd(vd->CommandQueue, hwnd, &sd1, nullptr, nullptr, &swap_chain);
  978. IM_ASSERT(res == S_OK);
  979. res = bd->pdxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); // Disable e.g. Alt+Enter
  980. IM_ASSERT(res == S_OK);
  981. // Or swapChain.As(&mSwapChain)
  982. IM_ASSERT(vd->SwapChain == nullptr);
  983. swap_chain->QueryInterface(IID_PPV_ARGS(&vd->SwapChain));
  984. swap_chain->Release();
  985. // Create the render targets and waitable object
  986. if (vd->SwapChain)
  987. {
  988. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  989. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  990. desc.NumDescriptors = bd->numFramesInFlight;
  991. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  992. desc.NodeMask = 1;
  993. HRESULT hr = bd->pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&vd->RtvDescHeap));
  994. IM_ASSERT(hr == S_OK);
  995. SIZE_T rtv_descriptor_size = bd->pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  996. D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = vd->RtvDescHeap->GetCPUDescriptorHandleForHeapStart();
  997. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  998. {
  999. vd->FrameCtx[i].RenderTargetCpuDescriptors = rtv_handle;
  1000. rtv_handle.ptr += rtv_descriptor_size;
  1001. }
  1002. ID3D12Resource* back_buffer;
  1003. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1004. {
  1005. IM_ASSERT(vd->FrameCtx[i].RenderTarget == nullptr);
  1006. vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
  1007. bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
  1008. vd->FrameCtx[i].RenderTarget = back_buffer;
  1009. }
  1010. hr = vd->SwapChain->SetMaximumFrameLatency(bd->numFramesInFlight);
  1011. IM_ASSERT(hr == S_OK);
  1012. vd->SwapChainWaitableObject = vd->SwapChain->GetFrameLatencyWaitableObject();
  1013. }
  1014. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1015. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  1016. }
  1017. static void ImGui_WaitForPendingOperations(ImGui_ImplDX12_ViewportData* vd)
  1018. {
  1019. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1020. HRESULT hr = vd->CommandQueue->Signal(bd->Fence, ++bd->FenceLastSignaledValue);
  1021. IM_ASSERT(hr == S_OK);
  1022. hr = bd->Fence->SetEventOnCompletion(bd->FenceLastSignaledValue, bd->FenceEvent);
  1023. IM_ASSERT(hr == S_OK);
  1024. ::WaitForSingleObject(bd->FenceEvent, INFINITE);
  1025. }
  1026. static ImGui_ImplDX12_FrameContext* ImGui_WaitForNextFrameContext(ImGui_ImplDX12_ViewportData* vd)
  1027. {
  1028. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1029. ImGui_ImplDX12_FrameContext* frame_context = &vd->FrameCtx[vd->FrameIndex % vd->NumFramesInFlight];
  1030. if (bd->Fence->GetCompletedValue() < frame_context->FenceValue)
  1031. {
  1032. HRESULT hr = bd->Fence->SetEventOnCompletion(frame_context->FenceValue, bd->FenceEvent);
  1033. IM_ASSERT(hr == S_OK);
  1034. HANDLE waitableObjects[] = { vd->SwapChainWaitableObject, bd->FenceEvent };
  1035. ::WaitForMultipleObjects(2, waitableObjects, TRUE, INFINITE);
  1036. }
  1037. else
  1038. {
  1039. ::WaitForSingleObject(vd->SwapChainWaitableObject, INFINITE);
  1040. }
  1041. return frame_context;
  1042. }
  1043. static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport)
  1044. {
  1045. // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
  1046. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1047. if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData)
  1048. {
  1049. ImGui_WaitForPendingOperations(vd);
  1050. vd->CommandQueue = nullptr;
  1051. ::CloseHandle(vd->SwapChainWaitableObject);
  1052. vd->SwapChainWaitableObject = nullptr;
  1053. SafeRelease(vd->CommandList);
  1054. SafeRelease(vd->SwapChain);
  1055. SafeRelease(vd->RtvDescHeap);
  1056. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1057. {
  1058. SafeRelease(vd->FrameCtx[i].RenderTarget);
  1059. SafeRelease(vd->FrameCtx[i].CommandAllocator);
  1060. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  1061. }
  1062. IM_DELETE(vd);
  1063. }
  1064. viewport->RendererUserData = nullptr;
  1065. }
  1066. static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  1067. {
  1068. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1069. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  1070. ImGui_WaitForPendingOperations(vd);
  1071. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1072. SafeRelease(vd->FrameCtx[i].RenderTarget);
  1073. if (vd->SwapChain)
  1074. {
  1075. ID3D12Resource* back_buffer = nullptr;
  1076. DXGI_SWAP_CHAIN_DESC1 desc = {};
  1077. vd->SwapChain->GetDesc1(&desc);
  1078. vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, desc.Format, desc.Flags);
  1079. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1080. {
  1081. vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
  1082. bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
  1083. vd->FrameCtx[i].RenderTarget = back_buffer;
  1084. }
  1085. }
  1086. }
  1087. static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*)
  1088. {
  1089. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1090. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  1091. ImGui_ImplDX12_FrameContext* frame_context = ImGui_WaitForNextFrameContext(vd);
  1092. UINT back_buffer_idx = vd->SwapChain->GetCurrentBackBufferIndex();
  1093. const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  1094. D3D12_RESOURCE_BARRIER barrier = {};
  1095. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  1096. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  1097. barrier.Transition.pResource = vd->FrameCtx[back_buffer_idx].RenderTarget;
  1098. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  1099. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  1100. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  1101. // Draw
  1102. ID3D12GraphicsCommandList* cmd_list = vd->CommandList;
  1103. frame_context->CommandAllocator->Reset();
  1104. cmd_list->Reset(frame_context->CommandAllocator, nullptr);
  1105. cmd_list->ResourceBarrier(1, &barrier);
  1106. cmd_list->OMSetRenderTargets(1, &vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, FALSE, nullptr);
  1107. if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
  1108. cmd_list->ClearRenderTargetView(vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, (const float*)&clear_color, 0, nullptr);
  1109. cmd_list->SetDescriptorHeaps(1, &bd->pd3dSrvDescHeap);
  1110. ImGui_ImplDX12_RenderDrawData(viewport->DrawData, cmd_list);
  1111. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  1112. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  1113. cmd_list->ResourceBarrier(1, &barrier);
  1114. cmd_list->Close();
  1115. vd->CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmd_list);
  1116. HRESULT hr = vd->CommandQueue->Signal(bd->Fence, ++bd->FenceLastSignaledValue);
  1117. IM_ASSERT(hr == S_OK);
  1118. frame_context->FenceValue = bd->FenceLastSignaledValue;
  1119. }
  1120. static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport, void*)
  1121. {
  1122. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1123. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  1124. vd->SwapChain->Present(0, bd->tearingSupport ? DXGI_PRESENT_ALLOW_TEARING : 0);
  1125. }
  1126. void ImGui_ImplDX12_InitMultiViewportSupport()
  1127. {
  1128. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1129. platform_io.Renderer_CreateWindow = ImGui_ImplDX12_CreateWindow;
  1130. platform_io.Renderer_DestroyWindow = ImGui_ImplDX12_DestroyWindow;
  1131. platform_io.Renderer_SetWindowSize = ImGui_ImplDX12_SetWindowSize;
  1132. platform_io.Renderer_RenderWindow = ImGui_ImplDX12_RenderWindow;
  1133. platform_io.Renderer_SwapBuffers = ImGui_ImplDX12_SwapBuffers;
  1134. }
  1135. void ImGui_ImplDX12_ShutdownMultiViewportSupport()
  1136. {
  1137. ImGui::DestroyPlatformWindows();
  1138. }
  1139. //-----------------------------------------------------------------------------
  1140. #endif // #ifndef IMGUI_DISABLE