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