imgui_impl_dx12.cpp 27 KB

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