imgui_impl_dx12.cpp 42 KB

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