imgui_impl_dx12.cpp 40 KB

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