imgui_impl_dx12.cpp 47 KB

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