imgui_impl_dx12.cpp 32 KB

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