imgui_impl_dx12.cpp 34 KB

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