imgui_impl_dx12.cpp 27 KB

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