imgui_impl_dx12.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. // ImGui Win32 + DirectX12 binding
  2. // In this binding, ImTextureID is used to store a 'D3D12_GPU_DESCRIPTOR_HANDLE' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  4. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  5. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  6. // https://github.com/ocornut/imgui
  7. #include <imgui.h>
  8. #include "imgui_impl_dx12.h"
  9. // DirectX
  10. #include <d3d12.h>
  11. #include <d3dcompiler.h>
  12. struct FrameResources
  13. {
  14. ID3D12Resource* IB;
  15. ID3D12Resource* VB;
  16. int VertexBufferSize;
  17. int IndexBufferSize;
  18. };
  19. // Data
  20. static INT64 g_Time = 0;
  21. static INT64 g_TicksPerSecond = 0;
  22. static HWND g_hWnd = 0;
  23. static ID3D12Device* g_pd3dDevice = NULL;
  24. static ID3D12GraphicsCommandList* g_pd3dCommandList = 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 ID3D12Resource* g_pFontTextureResource = NULL;
  30. static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle = {};
  31. static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {};
  32. static FrameResources* g_pFrameResources = NULL;
  33. static UINT g_numFramesInFlight = 0;
  34. static UINT g_frameIndex = UINT_MAX;
  35. struct VERTEX_CONSTANT_BUFFER
  36. {
  37. float mvp[4][4];
  38. };
  39. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  40. // If text or lines are blurry when integrating ImGui in your engine:
  41. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  42. void ImGui_ImplDX12_RenderDrawLists(ImDrawData* draw_data)
  43. {
  44. // NOTE: I'm assuming that this only get's called once per frame! If not,
  45. // we can't just re-allocate the IB or VB, we'll have to do a proper
  46. // allocator.
  47. g_frameIndex = g_frameIndex + 1;
  48. FrameResources* frameResources = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
  49. ID3D12Resource* g_pVB = frameResources->VB;
  50. ID3D12Resource* g_pIB = frameResources->IB;
  51. int g_VertexBufferSize = frameResources->VertexBufferSize;
  52. int g_IndexBufferSize = frameResources->IndexBufferSize;
  53. ID3D12GraphicsCommandList* ctx = g_pd3dCommandList;
  54. // Create and grow vertex/index buffers if needed
  55. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  56. {
  57. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  58. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  59. D3D12_HEAP_PROPERTIES props;
  60. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  61. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  62. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  63. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  64. D3D12_RESOURCE_DESC desc;
  65. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  66. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  67. desc.Width = g_VertexBufferSize * sizeof(ImDrawVert);
  68. desc.Height = 1;
  69. desc.DepthOrArraySize = 1;
  70. desc.MipLevels = 1;
  71. desc.Format = DXGI_FORMAT_UNKNOWN;
  72. desc.SampleDesc.Count = 1;
  73. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  74. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  75. if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE,
  76. &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pVB)) < 0)
  77. return;
  78. frameResources->VB = g_pVB;
  79. frameResources->VertexBufferSize = g_VertexBufferSize;
  80. }
  81. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  82. {
  83. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  84. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  85. D3D12_HEAP_PROPERTIES props;
  86. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  87. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  88. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  89. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  90. D3D12_RESOURCE_DESC desc;
  91. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  92. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  93. desc.Width = g_IndexBufferSize * sizeof(ImDrawIdx);
  94. desc.Height = 1;
  95. desc.DepthOrArraySize = 1;
  96. desc.MipLevels = 1;
  97. desc.Format = DXGI_FORMAT_UNKNOWN;
  98. desc.SampleDesc.Count = 1;
  99. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  100. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  101. if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE,
  102. &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pIB)) < 0)
  103. return;
  104. frameResources->IB = g_pIB;
  105. frameResources->IndexBufferSize = g_IndexBufferSize;
  106. }
  107. // Copy and convert all vertices into a single contiguous buffer
  108. void* vtx_resource, *idx_resource;
  109. D3D12_RANGE range;
  110. memset(&range, 0, sizeof(D3D12_RANGE));
  111. if (g_pVB->Map(0, &range, &vtx_resource) != S_OK)
  112. return;
  113. if (g_pIB->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. g_pVB->Unmap(0, &range);
  126. g_pIB->Unmap(0, &range);
  127. // Setup orthographic projection matrix into our constant buffer
  128. VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
  129. {
  130. VERTEX_CONSTANT_BUFFER* constant_buffer = &vertex_constant_buffer;
  131. float L = 0.0f;
  132. float R = ImGui::GetIO().DisplaySize.x;
  133. float B = ImGui::GetIO().DisplaySize.y;
  134. float T = 0.0f;
  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(&constant_buffer->mvp, mvp, sizeof(mvp));
  143. }
  144. // Setup viewport
  145. D3D12_VIEWPORT vp;
  146. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  147. vp.Width = ImGui::GetIO().DisplaySize.x;
  148. vp.Height = ImGui::GetIO().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 = g_pVB->GetGPUVirtualAddress() + offset;
  159. vbv.SizeInBytes = g_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 = g_pIB->GetGPUVirtualAddress();
  165. ibv.SizeInBytes = g_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 render state
  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. for (int n = 0; n < draw_data->CmdListsCount; n++)
  179. {
  180. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  181. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  182. {
  183. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  184. if (pcmd->UserCallback)
  185. {
  186. pcmd->UserCallback(cmd_list, pcmd);
  187. }
  188. else
  189. {
  190. const D3D12_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  191. ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId);
  192. ctx->RSSetScissorRects(1, &r);
  193. ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
  194. }
  195. idx_offset += pcmd->ElemCount;
  196. }
  197. vtx_offset += cmd_list->VtxBuffer.Size;
  198. }
  199. }
  200. IMGUI_API LRESULT ImGui_ImplDX12_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  201. {
  202. ImGuiIO& io = ImGui::GetIO();
  203. switch (msg)
  204. {
  205. case WM_LBUTTONDOWN:
  206. io.MouseDown[0] = true;
  207. return true;
  208. case WM_LBUTTONUP:
  209. io.MouseDown[0] = false;
  210. return true;
  211. case WM_RBUTTONDOWN:
  212. io.MouseDown[1] = true;
  213. return true;
  214. case WM_RBUTTONUP:
  215. io.MouseDown[1] = false;
  216. return true;
  217. case WM_MBUTTONDOWN:
  218. io.MouseDown[2] = true;
  219. return true;
  220. case WM_MBUTTONUP:
  221. io.MouseDown[2] = false;
  222. return true;
  223. case WM_MOUSEWHEEL:
  224. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  225. return true;
  226. case WM_MOUSEMOVE:
  227. io.MousePos.x = (signed short)(lParam);
  228. io.MousePos.y = (signed short)(lParam >> 16);
  229. return true;
  230. case WM_KEYDOWN:
  231. if (wParam < 256)
  232. io.KeysDown[wParam] = 1;
  233. return true;
  234. case WM_KEYUP:
  235. if (wParam < 256)
  236. io.KeysDown[wParam] = 0;
  237. return true;
  238. case WM_CHAR:
  239. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  240. if (wParam > 0 && wParam < 0x10000)
  241. io.AddInputCharacter((unsigned short)wParam);
  242. return true;
  243. }
  244. return 0;
  245. }
  246. static void ImGui_ImplDX12_CreateFontsTexture()
  247. {
  248. // Build texture atlas
  249. ImGuiIO& io = ImGui::GetIO();
  250. unsigned char* pixels;
  251. int width, height;
  252. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  253. // Upload texture to graphics system
  254. {
  255. D3D12_HEAP_PROPERTIES props;
  256. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  257. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  258. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  259. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  260. D3D12_RESOURCE_DESC desc;
  261. ZeroMemory(&desc, sizeof(desc));
  262. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  263. desc.Alignment = 0;
  264. desc.Width = width;
  265. desc.Height = height;
  266. desc.DepthOrArraySize = 1;
  267. desc.MipLevels = 1;
  268. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  269. desc.SampleDesc.Count = 1;
  270. desc.SampleDesc.Quality = 0;
  271. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  272. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  273. ID3D12Resource* pTexture = NULL;
  274. g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  275. D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture));
  276. UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  277. UINT uploadSize = height * uploadPitch;
  278. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  279. desc.Alignment = 0;
  280. desc.Width = uploadSize;
  281. desc.Height = 1;
  282. desc.DepthOrArraySize = 1;
  283. desc.MipLevels = 1;
  284. desc.Format = DXGI_FORMAT_UNKNOWN;
  285. desc.SampleDesc.Count = 1;
  286. desc.SampleDesc.Quality = 0;
  287. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  288. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  289. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  290. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  291. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  292. ID3D12Resource* uploadBuffer = NULL;
  293. HRESULT hr = g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  294. D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
  295. assert(SUCCEEDED(hr));
  296. void* mapped = NULL;
  297. D3D12_RANGE range = { 0, uploadSize };
  298. hr = uploadBuffer->Map(0, &range, &mapped);
  299. assert(SUCCEEDED(hr));
  300. for (int y = 0; y < height; ++y)
  301. {
  302. memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
  303. }
  304. uploadBuffer->Unmap(0, &range);
  305. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  306. srcLocation.pResource = uploadBuffer;
  307. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  308. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  309. srcLocation.PlacedFootprint.Footprint.Width = width;
  310. srcLocation.PlacedFootprint.Footprint.Height = height;
  311. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  312. srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
  313. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  314. dstLocation.pResource = pTexture;
  315. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  316. dstLocation.SubresourceIndex = 0;
  317. D3D12_RESOURCE_BARRIER barrier = {};
  318. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  319. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  320. barrier.Transition.pResource = pTexture;
  321. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  322. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  323. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  324. ID3D12Fence* fence = NULL;
  325. hr = g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  326. assert(SUCCEEDED(hr));
  327. HANDLE event = CreateEvent(0, 0, 0, 0);
  328. assert(event != NULL);
  329. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  330. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  331. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  332. queueDesc.NodeMask = 1;
  333. ID3D12CommandQueue* cmdQueue = NULL;
  334. hr = g_pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
  335. assert(SUCCEEDED(hr));
  336. ID3D12CommandAllocator* cmdAlloc = NULL;
  337. hr = g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  338. assert(SUCCEEDED(hr));
  339. ID3D12GraphicsCommandList* cmdList = NULL;
  340. hr = g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList));
  341. assert(SUCCEEDED(hr));
  342. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL);
  343. cmdList->ResourceBarrier(1, &barrier);
  344. hr = cmdList->Close();
  345. assert(SUCCEEDED(hr));
  346. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &cmdList);
  347. hr = cmdQueue->Signal(fence, 1);
  348. assert(SUCCEEDED(hr));
  349. fence->SetEventOnCompletion(1, event);
  350. WaitForSingleObject(event, INFINITE);
  351. cmdList->Release();
  352. cmdAlloc->Release();
  353. cmdQueue->Release();
  354. CloseHandle(event);
  355. fence->Release();
  356. uploadBuffer->Release();
  357. // Create texture view
  358. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  359. ZeroMemory(&srvDesc, sizeof(srvDesc));
  360. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  361. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  362. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  363. srvDesc.Texture2D.MostDetailedMip = 0;
  364. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  365. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, g_hFontSrvCpuDescHandle);
  366. if (g_pFontTextureResource != NULL)
  367. g_pFontTextureResource->Release();
  368. g_pFontTextureResource = pTexture;
  369. }
  370. // Store our identifier
  371. static_assert(sizeof(void*) >= sizeof(g_hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID");
  372. io.Fonts->TexID = (void *)g_hFontSrvGpuDescHandle.ptr;
  373. }
  374. bool ImGui_ImplDX12_CreateDeviceObjects()
  375. {
  376. if (!g_pd3dDevice)
  377. return false;
  378. if (g_pPipelineState)
  379. ImGui_ImplDX12_InvalidateDeviceObjects();
  380. // Create the root signature
  381. {
  382. D3D12_DESCRIPTOR_RANGE descRange = {};
  383. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  384. descRange.NumDescriptors = 1;
  385. descRange.BaseShaderRegister = 0;
  386. descRange.RegisterSpace = 0;
  387. descRange.OffsetInDescriptorsFromTableStart = 0;
  388. D3D12_ROOT_PARAMETER param[2] = {};
  389. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  390. param[0].Constants.ShaderRegister = 0;
  391. param[0].Constants.RegisterSpace = 0;
  392. param[0].Constants.Num32BitValues = 16;
  393. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  394. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  395. param[1].DescriptorTable.NumDescriptorRanges = 1;
  396. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  397. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  398. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  399. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  400. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  401. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  402. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  403. staticSampler.MipLODBias = 0.f;
  404. staticSampler.MaxAnisotropy = 0;
  405. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  406. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  407. staticSampler.MinLOD = 0.f;
  408. staticSampler.MaxLOD = 0.f;
  409. staticSampler.ShaderRegister = 0;
  410. staticSampler.RegisterSpace = 0;
  411. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  412. D3D12_ROOT_SIGNATURE_DESC desc = {};
  413. desc.NumParameters = _countof(param);
  414. desc.pParameters = param;
  415. desc.NumStaticSamplers = 1;
  416. desc.pStaticSamplers = &staticSampler;
  417. desc.Flags =
  418. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  419. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  420. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  421. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  422. ID3DBlob* blob = NULL;
  423. if (D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK)
  424. return false;
  425. g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature));
  426. blob->Release();
  427. }
  428. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  429. // If you would like to use this DX12 sample code but remove this dependency you can:
  430. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  431. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  432. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  433. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  434. memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  435. psoDesc.NodeMask = 1;
  436. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  437. psoDesc.pRootSignature = g_pRootSignature;
  438. psoDesc.SampleMask = UINT_MAX;
  439. psoDesc.NumRenderTargets = 1;
  440. psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  441. psoDesc.SampleDesc.Count = 1;
  442. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  443. // Create the vertex shader
  444. {
  445. static const char* vertexShader =
  446. "cbuffer vertexBuffer : register(b0) \
  447. {\
  448. float4x4 ProjectionMatrix; \
  449. };\
  450. struct VS_INPUT\
  451. {\
  452. float2 pos : POSITION;\
  453. float4 col : COLOR0;\
  454. float2 uv : TEXCOORD0;\
  455. };\
  456. \
  457. struct PS_INPUT\
  458. {\
  459. float4 pos : SV_POSITION;\
  460. float4 col : COLOR0;\
  461. float2 uv : TEXCOORD0;\
  462. };\
  463. \
  464. PS_INPUT main(VS_INPUT input)\
  465. {\
  466. PS_INPUT output;\
  467. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  468. output.col = input.col;\
  469. output.uv = input.uv;\
  470. return output;\
  471. }";
  472. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
  473. 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!
  474. return false;
  475. psoDesc.VS = { g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize() };
  476. // Create the input layout
  477. static D3D12_INPUT_ELEMENT_DESC local_layout[] = {
  478. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  479. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  480. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  481. };
  482. psoDesc.InputLayout = { local_layout, 3 };
  483. }
  484. // Create the pixel shader
  485. {
  486. static const char* pixelShader =
  487. "struct PS_INPUT\
  488. {\
  489. float4 pos : SV_POSITION;\
  490. float4 col : COLOR0;\
  491. float2 uv : TEXCOORD0;\
  492. };\
  493. SamplerState sampler0 : register(s0);\
  494. Texture2D texture0 : register(t0);\
  495. \
  496. float4 main(PS_INPUT input) : SV_Target\
  497. {\
  498. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  499. return out_col; \
  500. }";
  501. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
  502. 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!
  503. return false;
  504. psoDesc.PS = { g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize() };
  505. }
  506. // Create the blending setup
  507. {
  508. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  509. desc.AlphaToCoverageEnable = false;
  510. desc.RenderTarget[0].BlendEnable = true;
  511. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  512. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  513. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  514. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  515. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO;
  516. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  517. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  518. }
  519. // Create the rasterizer state
  520. {
  521. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  522. desc.FillMode = D3D12_FILL_MODE_SOLID;
  523. desc.CullMode = D3D12_CULL_MODE_NONE;
  524. desc.FrontCounterClockwise = FALSE;
  525. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  526. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  527. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  528. desc.DepthClipEnable = true;
  529. desc.MultisampleEnable = FALSE;
  530. desc.AntialiasedLineEnable = FALSE;
  531. desc.ForcedSampleCount = 0;
  532. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  533. }
  534. // Create depth-stencil State
  535. {
  536. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  537. desc.DepthEnable = false;
  538. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  539. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  540. desc.StencilEnable = false;
  541. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  542. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  543. desc.BackFace = desc.FrontFace;
  544. }
  545. if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK)
  546. return false;
  547. ImGui_ImplDX12_CreateFontsTexture();
  548. return true;
  549. }
  550. void ImGui_ImplDX12_InvalidateDeviceObjects()
  551. {
  552. if (!g_pd3dDevice)
  553. return;
  554. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  555. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  556. if (g_pRootSignature) { g_pRootSignature->Release(); g_pRootSignature = NULL; }
  557. if (g_pPipelineState) { g_pPipelineState->Release(); g_pPipelineState = NULL; }
  558. 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.
  559. for (UINT i = 0; i < g_numFramesInFlight; ++i)
  560. {
  561. if (g_pFrameResources[i].IB) { g_pFrameResources[i].IB->Release(); g_pFrameResources[i].IB = NULL; }
  562. if (g_pFrameResources[i].VB) { g_pFrameResources[i].VB->Release(); g_pFrameResources[i].VB = NULL; }
  563. }
  564. }
  565. bool ImGui_ImplDX12_Init(void* hwnd, int num_frames_in_flight,
  566. ID3D12Device* device, ID3D12GraphicsCommandList* command_list,
  567. D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle,
  568. D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  569. {
  570. g_hWnd = (HWND)hwnd;
  571. g_pd3dDevice = device;
  572. g_pd3dCommandList = command_list;
  573. g_hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
  574. g_hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
  575. g_pFrameResources = new FrameResources [num_frames_in_flight];
  576. g_numFramesInFlight = num_frames_in_flight;
  577. g_frameIndex = UINT_MAX;
  578. for (int i = 0; i < num_frames_in_flight; ++i)
  579. {
  580. g_pFrameResources[i].IB = NULL;
  581. g_pFrameResources[i].VB = NULL;
  582. g_pFrameResources[i].VertexBufferSize = 5000;
  583. g_pFrameResources[i].IndexBufferSize = 10000;
  584. }
  585. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  586. return false;
  587. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  588. return false;
  589. ImGuiIO& io = ImGui::GetIO();
  590. io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  591. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  592. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  593. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  594. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  595. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  596. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  597. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  598. io.KeyMap[ImGuiKey_End] = VK_END;
  599. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  600. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  601. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  602. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  603. io.KeyMap[ImGuiKey_A] = 'A';
  604. io.KeyMap[ImGuiKey_C] = 'C';
  605. io.KeyMap[ImGuiKey_V] = 'V';
  606. io.KeyMap[ImGuiKey_X] = 'X';
  607. io.KeyMap[ImGuiKey_Y] = 'Y';
  608. io.KeyMap[ImGuiKey_Z] = 'Z';
  609. io.RenderDrawListsFn = ImGui_ImplDX12_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  610. io.ImeWindowHandle = g_hWnd;
  611. return true;
  612. }
  613. void ImGui_ImplDX12_Shutdown()
  614. {
  615. ImGui_ImplDX12_InvalidateDeviceObjects();
  616. ImGui::Shutdown();
  617. delete[] g_pFrameResources;
  618. g_pd3dDevice = NULL;
  619. g_hWnd = (HWND)0;
  620. g_pd3dCommandList = NULL;
  621. g_hFontSrvCpuDescHandle.ptr = 0;
  622. g_hFontSrvGpuDescHandle.ptr = 0;
  623. g_pFrameResources = NULL;
  624. g_numFramesInFlight = 0;
  625. g_frameIndex = UINT_MAX;
  626. }
  627. void ImGui_ImplDX12_NewFrame()
  628. {
  629. if (!g_pPipelineState)
  630. ImGui_ImplDX12_CreateDeviceObjects();
  631. ImGuiIO& io = ImGui::GetIO();
  632. // Setup display size (every frame to accommodate for window resizing)
  633. RECT rect;
  634. GetClientRect(g_hWnd, &rect);
  635. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  636. // Setup time step
  637. INT64 current_time;
  638. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  639. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  640. g_Time = current_time;
  641. // Read keyboard modifiers inputs
  642. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  643. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  644. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  645. io.KeySuper = false;
  646. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  647. // io.MousePos : filled by WM_MOUSEMOVE events
  648. // io.MouseDown : filled by WM_*BUTTON* events
  649. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  650. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  651. if (io.WantMoveMouse)
  652. {
  653. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  654. ClientToScreen(g_hWnd, &pos);
  655. SetCursorPos(pos.x, pos.y);
  656. }
  657. // Hide OS mouse cursor if ImGui is drawing it
  658. if (io.MouseDrawCursor)
  659. SetCursor(NULL);
  660. // Start the frame
  661. ImGui::NewFrame();
  662. }