imgui_impl_dx12.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. // ImGui Win32 + DirectX12 binding
  2. // FIXME: 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*))
  3. // Implemented features:
  4. // [X] User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  5. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  6. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  7. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  8. // https://github.com/ocornut/imgui
  9. // CHANGELOG
  10. // (minor and older changes stripped away, please see git history for details)
  11. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  12. #include "imgui.h"
  13. #include "imgui_impl_dx12.h"
  14. // DirectX
  15. #include <d3d12.h>
  16. #include <d3dcompiler.h>
  17. // Win32 data
  18. static HWND g_hWnd = 0;
  19. static INT64 g_Time = 0;
  20. static INT64 g_TicksPerSecond = 0;
  21. static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_Count_;
  22. // DirectX data
  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 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. // Render function
  48. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  49. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data)
  50. {
  51. // NOTE: I'm assuming that this only get's called once per frame!
  52. // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
  53. g_frameIndex = g_frameIndex + 1;
  54. FrameResources* frameResources = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
  55. ID3D12Resource* g_pVB = frameResources->VB;
  56. ID3D12Resource* g_pIB = frameResources->IB;
  57. int g_VertexBufferSize = frameResources->VertexBufferSize;
  58. int g_IndexBufferSize = frameResources->IndexBufferSize;
  59. ID3D12GraphicsCommandList* ctx = g_pd3dCommandList;
  60. // Create and grow vertex/index buffers if needed
  61. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  62. {
  63. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  64. g_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 = g_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,
  82. &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pVB)) < 0)
  83. return;
  84. frameResources->VB = g_pVB;
  85. frameResources->VertexBufferSize = g_VertexBufferSize;
  86. }
  87. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  88. {
  89. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  90. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  91. D3D12_HEAP_PROPERTIES props;
  92. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  93. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  94. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  95. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  96. D3D12_RESOURCE_DESC desc;
  97. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  98. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  99. desc.Width = g_IndexBufferSize * sizeof(ImDrawIdx);
  100. desc.Height = 1;
  101. desc.DepthOrArraySize = 1;
  102. desc.MipLevels = 1;
  103. desc.Format = DXGI_FORMAT_UNKNOWN;
  104. desc.SampleDesc.Count = 1;
  105. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  106. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  107. if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE,
  108. &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. VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
  135. {
  136. VERTEX_CONSTANT_BUFFER* constant_buffer = &vertex_constant_buffer;
  137. float L = 0.0f;
  138. float R = ImGui::GetIO().DisplaySize.x;
  139. float B = ImGui::GetIO().DisplaySize.y;
  140. float T = 0.0f;
  141. float mvp[4][4] =
  142. {
  143. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  144. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  145. { 0.0f, 0.0f, 0.5f, 0.0f },
  146. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  147. };
  148. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  149. }
  150. // Setup viewport
  151. D3D12_VIEWPORT vp;
  152. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  153. vp.Width = ImGui::GetIO().DisplaySize.x;
  154. vp.Height = ImGui::GetIO().DisplaySize.y;
  155. vp.MinDepth = 0.0f;
  156. vp.MaxDepth = 1.0f;
  157. vp.TopLeftX = vp.TopLeftY = 0.0f;
  158. ctx->RSSetViewports(1, &vp);
  159. // Bind shader and vertex buffers
  160. unsigned int stride = sizeof(ImDrawVert);
  161. unsigned int offset = 0;
  162. D3D12_VERTEX_BUFFER_VIEW vbv;
  163. memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
  164. vbv.BufferLocation = g_pVB->GetGPUVirtualAddress() + offset;
  165. vbv.SizeInBytes = g_VertexBufferSize * stride;
  166. vbv.StrideInBytes = stride;
  167. ctx->IASetVertexBuffers(0, 1, &vbv);
  168. D3D12_INDEX_BUFFER_VIEW ibv;
  169. memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
  170. ibv.BufferLocation = g_pIB->GetGPUVirtualAddress();
  171. ibv.SizeInBytes = g_IndexBufferSize * sizeof(ImDrawIdx);
  172. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  173. ctx->IASetIndexBuffer(&ibv);
  174. ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  175. ctx->SetPipelineState(g_pPipelineState);
  176. ctx->SetGraphicsRootSignature(g_pRootSignature);
  177. ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  178. // Setup render state
  179. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  180. ctx->OMSetBlendFactor(blend_factor);
  181. // Render command lists
  182. int vtx_offset = 0;
  183. int idx_offset = 0;
  184. for (int n = 0; n < draw_data->CmdListsCount; n++)
  185. {
  186. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  187. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  188. {
  189. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  190. if (pcmd->UserCallback)
  191. {
  192. pcmd->UserCallback(cmd_list, pcmd);
  193. }
  194. else
  195. {
  196. const D3D12_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  197. ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId);
  198. ctx->RSSetScissorRects(1, &r);
  199. ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
  200. }
  201. idx_offset += pcmd->ElemCount;
  202. }
  203. vtx_offset += cmd_list->VtxBuffer.Size;
  204. }
  205. }
  206. static void ImGui_ImplWin32_UpdateMouseCursor()
  207. {
  208. ImGuiIO& io = ImGui::GetIO();
  209. ImGuiMouseCursor imgui_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  210. if (imgui_cursor == ImGuiMouseCursor_None)
  211. {
  212. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  213. ::SetCursor(NULL);
  214. }
  215. else
  216. {
  217. // Hardware cursor type
  218. LPTSTR win32_cursor = IDC_ARROW;
  219. switch (imgui_cursor)
  220. {
  221. case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
  222. case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
  223. case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
  224. case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
  225. case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
  226. case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
  227. case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
  228. }
  229. ::SetCursor(::LoadCursor(NULL, win32_cursor));
  230. }
  231. }
  232. // Process Win32 mouse/keyboard inputs.
  233. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  234. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  235. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  236. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  237. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
  238. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
  239. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  240. {
  241. if (ImGui::GetCurrentContext() == NULL)
  242. return 0;
  243. ImGuiIO& io = ImGui::GetIO();
  244. switch (msg)
  245. {
  246. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  247. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  248. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  249. {
  250. int button = 0;
  251. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  252. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  253. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  254. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
  255. ::SetCapture(hwnd);
  256. io.MouseDown[button] = true;
  257. return 0;
  258. }
  259. case WM_LBUTTONUP:
  260. case WM_RBUTTONUP:
  261. case WM_MBUTTONUP:
  262. {
  263. int button = 0;
  264. if (msg == WM_LBUTTONUP) button = 0;
  265. if (msg == WM_RBUTTONUP) button = 1;
  266. if (msg == WM_MBUTTONUP) button = 2;
  267. io.MouseDown[button] = false;
  268. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
  269. ::ReleaseCapture();
  270. return 0;
  271. }
  272. case WM_MOUSEWHEEL:
  273. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  274. return 0;
  275. case WM_MOUSEHWHEEL:
  276. io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  277. return 0;
  278. case WM_MOUSEMOVE:
  279. io.MousePos.x = (signed short)(lParam);
  280. io.MousePos.y = (signed short)(lParam >> 16);
  281. return 0;
  282. case WM_KEYDOWN:
  283. case WM_SYSKEYDOWN:
  284. if (wParam < 256)
  285. io.KeysDown[wParam] = 1;
  286. return 0;
  287. case WM_KEYUP:
  288. case WM_SYSKEYUP:
  289. if (wParam < 256)
  290. io.KeysDown[wParam] = 0;
  291. return 0;
  292. case WM_CHAR:
  293. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  294. if (wParam > 0 && wParam < 0x10000)
  295. io.AddInputCharacter((unsigned short)wParam);
  296. return 0;
  297. case WM_SETCURSOR:
  298. if (LOWORD(lParam) == HTCLIENT)
  299. {
  300. ImGui_ImplWin32_UpdateMouseCursor();
  301. return 1;
  302. }
  303. return 0;
  304. }
  305. return 0;
  306. }
  307. static void ImGui_ImplDX12_CreateFontsTexture()
  308. {
  309. // Build texture atlas
  310. ImGuiIO& io = ImGui::GetIO();
  311. unsigned char* pixels;
  312. int width, height;
  313. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  314. // Upload texture to graphics system
  315. {
  316. D3D12_HEAP_PROPERTIES props;
  317. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  318. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  319. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  320. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  321. D3D12_RESOURCE_DESC desc;
  322. ZeroMemory(&desc, sizeof(desc));
  323. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  324. desc.Alignment = 0;
  325. desc.Width = width;
  326. desc.Height = height;
  327. desc.DepthOrArraySize = 1;
  328. desc.MipLevels = 1;
  329. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  330. desc.SampleDesc.Count = 1;
  331. desc.SampleDesc.Quality = 0;
  332. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  333. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  334. ID3D12Resource* pTexture = NULL;
  335. g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  336. D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture));
  337. UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  338. UINT uploadSize = height * uploadPitch;
  339. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  340. desc.Alignment = 0;
  341. desc.Width = uploadSize;
  342. desc.Height = 1;
  343. desc.DepthOrArraySize = 1;
  344. desc.MipLevels = 1;
  345. desc.Format = DXGI_FORMAT_UNKNOWN;
  346. desc.SampleDesc.Count = 1;
  347. desc.SampleDesc.Quality = 0;
  348. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  349. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  350. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  351. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  352. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  353. ID3D12Resource* uploadBuffer = NULL;
  354. HRESULT hr = g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  355. D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
  356. IM_ASSERT(SUCCEEDED(hr));
  357. void* mapped = NULL;
  358. D3D12_RANGE range = { 0, uploadSize };
  359. hr = uploadBuffer->Map(0, &range, &mapped);
  360. IM_ASSERT(SUCCEEDED(hr));
  361. for (int y = 0; y < height; y++)
  362. memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
  363. uploadBuffer->Unmap(0, &range);
  364. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  365. srcLocation.pResource = uploadBuffer;
  366. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  367. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  368. srcLocation.PlacedFootprint.Footprint.Width = width;
  369. srcLocation.PlacedFootprint.Footprint.Height = height;
  370. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  371. srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
  372. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  373. dstLocation.pResource = pTexture;
  374. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  375. dstLocation.SubresourceIndex = 0;
  376. D3D12_RESOURCE_BARRIER barrier = {};
  377. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  378. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  379. barrier.Transition.pResource = pTexture;
  380. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  381. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  382. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  383. ID3D12Fence* fence = NULL;
  384. hr = g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  385. IM_ASSERT(SUCCEEDED(hr));
  386. HANDLE event = CreateEvent(0, 0, 0, 0);
  387. IM_ASSERT(event != NULL);
  388. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  389. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  390. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  391. queueDesc.NodeMask = 1;
  392. ID3D12CommandQueue* cmdQueue = NULL;
  393. hr = g_pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
  394. IM_ASSERT(SUCCEEDED(hr));
  395. ID3D12CommandAllocator* cmdAlloc = NULL;
  396. hr = g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  397. IM_ASSERT(SUCCEEDED(hr));
  398. ID3D12GraphicsCommandList* cmdList = NULL;
  399. hr = g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList));
  400. IM_ASSERT(SUCCEEDED(hr));
  401. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL);
  402. cmdList->ResourceBarrier(1, &barrier);
  403. hr = cmdList->Close();
  404. IM_ASSERT(SUCCEEDED(hr));
  405. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &cmdList);
  406. hr = cmdQueue->Signal(fence, 1);
  407. IM_ASSERT(SUCCEEDED(hr));
  408. fence->SetEventOnCompletion(1, event);
  409. WaitForSingleObject(event, INFINITE);
  410. cmdList->Release();
  411. cmdAlloc->Release();
  412. cmdQueue->Release();
  413. CloseHandle(event);
  414. fence->Release();
  415. uploadBuffer->Release();
  416. // Create texture view
  417. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  418. ZeroMemory(&srvDesc, sizeof(srvDesc));
  419. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  420. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  421. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  422. srvDesc.Texture2D.MostDetailedMip = 0;
  423. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  424. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, g_hFontSrvCpuDescHandle);
  425. if (g_pFontTextureResource != NULL)
  426. g_pFontTextureResource->Release();
  427. g_pFontTextureResource = pTexture;
  428. }
  429. // Store our identifier
  430. static_assert(sizeof(void*) >= sizeof(g_hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID");
  431. io.Fonts->TexID = (void *)g_hFontSrvGpuDescHandle.ptr;
  432. }
  433. bool ImGui_ImplDX12_CreateDeviceObjects()
  434. {
  435. if (!g_pd3dDevice)
  436. return false;
  437. if (g_pPipelineState)
  438. ImGui_ImplDX12_InvalidateDeviceObjects();
  439. // Create the root signature
  440. {
  441. D3D12_DESCRIPTOR_RANGE descRange = {};
  442. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  443. descRange.NumDescriptors = 1;
  444. descRange.BaseShaderRegister = 0;
  445. descRange.RegisterSpace = 0;
  446. descRange.OffsetInDescriptorsFromTableStart = 0;
  447. D3D12_ROOT_PARAMETER param[2] = {};
  448. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  449. param[0].Constants.ShaderRegister = 0;
  450. param[0].Constants.RegisterSpace = 0;
  451. param[0].Constants.Num32BitValues = 16;
  452. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  453. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  454. param[1].DescriptorTable.NumDescriptorRanges = 1;
  455. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  456. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  457. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  458. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  459. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  460. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  461. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  462. staticSampler.MipLODBias = 0.f;
  463. staticSampler.MaxAnisotropy = 0;
  464. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  465. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  466. staticSampler.MinLOD = 0.f;
  467. staticSampler.MaxLOD = 0.f;
  468. staticSampler.ShaderRegister = 0;
  469. staticSampler.RegisterSpace = 0;
  470. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  471. D3D12_ROOT_SIGNATURE_DESC desc = {};
  472. desc.NumParameters = _countof(param);
  473. desc.pParameters = param;
  474. desc.NumStaticSamplers = 1;
  475. desc.pStaticSamplers = &staticSampler;
  476. desc.Flags =
  477. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  478. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  479. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  480. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  481. ID3DBlob* blob = NULL;
  482. if (D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK)
  483. return false;
  484. g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature));
  485. blob->Release();
  486. }
  487. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  488. // If you would like to use this DX12 sample code but remove this dependency you can:
  489. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  490. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  491. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  492. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  493. memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  494. psoDesc.NodeMask = 1;
  495. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  496. psoDesc.pRootSignature = g_pRootSignature;
  497. psoDesc.SampleMask = UINT_MAX;
  498. psoDesc.NumRenderTargets = 1;
  499. psoDesc.RTVFormats[0] = g_RTVFormat;
  500. psoDesc.SampleDesc.Count = 1;
  501. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  502. // Create the vertex shader
  503. {
  504. static const char* vertexShader =
  505. "cbuffer vertexBuffer : register(b0) \
  506. {\
  507. float4x4 ProjectionMatrix; \
  508. };\
  509. struct VS_INPUT\
  510. {\
  511. float2 pos : POSITION;\
  512. float4 col : COLOR0;\
  513. float2 uv : TEXCOORD0;\
  514. };\
  515. \
  516. struct PS_INPUT\
  517. {\
  518. float4 pos : SV_POSITION;\
  519. float4 col : COLOR0;\
  520. float2 uv : TEXCOORD0;\
  521. };\
  522. \
  523. PS_INPUT main(VS_INPUT input)\
  524. {\
  525. PS_INPUT output;\
  526. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  527. output.col = input.col;\
  528. output.uv = input.uv;\
  529. return output;\
  530. }";
  531. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
  532. 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!
  533. return false;
  534. psoDesc.VS = { g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize() };
  535. // Create the input layout
  536. static D3D12_INPUT_ELEMENT_DESC local_layout[] = {
  537. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  538. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  539. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  540. };
  541. psoDesc.InputLayout = { local_layout, 3 };
  542. }
  543. // Create the pixel shader
  544. {
  545. static const char* pixelShader =
  546. "struct PS_INPUT\
  547. {\
  548. float4 pos : SV_POSITION;\
  549. float4 col : COLOR0;\
  550. float2 uv : TEXCOORD0;\
  551. };\
  552. SamplerState sampler0 : register(s0);\
  553. Texture2D texture0 : register(t0);\
  554. \
  555. float4 main(PS_INPUT input) : SV_Target\
  556. {\
  557. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  558. return out_col; \
  559. }";
  560. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
  561. 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!
  562. return false;
  563. psoDesc.PS = { g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize() };
  564. }
  565. // Create the blending setup
  566. {
  567. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  568. desc.AlphaToCoverageEnable = false;
  569. desc.RenderTarget[0].BlendEnable = true;
  570. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  571. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  572. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  573. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  574. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO;
  575. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  576. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  577. }
  578. // Create the rasterizer state
  579. {
  580. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  581. desc.FillMode = D3D12_FILL_MODE_SOLID;
  582. desc.CullMode = D3D12_CULL_MODE_NONE;
  583. desc.FrontCounterClockwise = FALSE;
  584. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  585. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  586. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  587. desc.DepthClipEnable = true;
  588. desc.MultisampleEnable = FALSE;
  589. desc.AntialiasedLineEnable = FALSE;
  590. desc.ForcedSampleCount = 0;
  591. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  592. }
  593. // Create depth-stencil State
  594. {
  595. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  596. desc.DepthEnable = false;
  597. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  598. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  599. desc.StencilEnable = false;
  600. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  601. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  602. desc.BackFace = desc.FrontFace;
  603. }
  604. if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK)
  605. return false;
  606. ImGui_ImplDX12_CreateFontsTexture();
  607. return true;
  608. }
  609. void ImGui_ImplDX12_InvalidateDeviceObjects()
  610. {
  611. if (!g_pd3dDevice)
  612. return;
  613. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  614. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  615. if (g_pRootSignature) { g_pRootSignature->Release(); g_pRootSignature = NULL; }
  616. if (g_pPipelineState) { g_pPipelineState->Release(); g_pPipelineState = NULL; }
  617. 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.
  618. for (UINT i = 0; i < g_numFramesInFlight; i++)
  619. {
  620. if (g_pFrameResources[i].IB) { g_pFrameResources[i].IB->Release(); g_pFrameResources[i].IB = NULL; }
  621. if (g_pFrameResources[i].VB) { g_pFrameResources[i].VB->Release(); g_pFrameResources[i].VB = NULL; }
  622. }
  623. }
  624. bool ImGui_ImplDX12_Init(void* hwnd, int num_frames_in_flight,
  625. ID3D12Device* device,
  626. DXGI_FORMAT rtv_format,
  627. D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle,
  628. D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  629. {
  630. g_hWnd = (HWND)hwnd;
  631. g_pd3dDevice = device;
  632. g_RTVFormat = rtv_format;
  633. g_hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
  634. g_hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
  635. g_pFrameResources = new FrameResources [num_frames_in_flight];
  636. g_numFramesInFlight = num_frames_in_flight;
  637. g_frameIndex = UINT_MAX;
  638. for (int i = 0; i < num_frames_in_flight; i++)
  639. {
  640. g_pFrameResources[i].IB = NULL;
  641. g_pFrameResources[i].VB = NULL;
  642. g_pFrameResources[i].VertexBufferSize = 5000;
  643. g_pFrameResources[i].IndexBufferSize = 10000;
  644. }
  645. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  646. return false;
  647. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  648. return false;
  649. ImGuiIO& io = ImGui::GetIO();
  650. 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.
  651. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  652. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  653. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  654. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  655. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  656. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  657. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  658. io.KeyMap[ImGuiKey_End] = VK_END;
  659. io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
  660. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  661. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  662. io.KeyMap[ImGuiKey_Space] = VK_SPACE;
  663. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  664. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  665. io.KeyMap[ImGuiKey_A] = 'A';
  666. io.KeyMap[ImGuiKey_C] = 'C';
  667. io.KeyMap[ImGuiKey_V] = 'V';
  668. io.KeyMap[ImGuiKey_X] = 'X';
  669. io.KeyMap[ImGuiKey_Y] = 'Y';
  670. io.KeyMap[ImGuiKey_Z] = 'Z';
  671. io.ImeWindowHandle = g_hWnd;
  672. return true;
  673. }
  674. void ImGui_ImplDX12_Shutdown()
  675. {
  676. ImGui_ImplDX12_InvalidateDeviceObjects();
  677. delete[] g_pFrameResources;
  678. g_pd3dDevice = NULL;
  679. g_hWnd = (HWND)0;
  680. g_pd3dCommandList = NULL;
  681. g_hFontSrvCpuDescHandle.ptr = 0;
  682. g_hFontSrvGpuDescHandle.ptr = 0;
  683. g_pFrameResources = NULL;
  684. g_numFramesInFlight = 0;
  685. g_frameIndex = UINT_MAX;
  686. }
  687. void ImGui_ImplDX12_NewFrame(ID3D12GraphicsCommandList* command_list)
  688. {
  689. if (!g_pPipelineState)
  690. ImGui_ImplDX12_CreateDeviceObjects();
  691. g_pd3dCommandList = command_list;
  692. ImGuiIO& io = ImGui::GetIO();
  693. // Setup display size (every frame to accommodate for window resizing)
  694. RECT rect;
  695. GetClientRect(g_hWnd, &rect);
  696. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  697. // Setup time step
  698. INT64 current_time;
  699. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  700. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  701. g_Time = current_time;
  702. // Read keyboard modifiers inputs
  703. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  704. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  705. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  706. io.KeySuper = false;
  707. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  708. // io.MousePos : filled by WM_MOUSEMOVE events
  709. // io.MouseDown : filled by WM_*BUTTON* events
  710. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  711. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  712. if (io.WantMoveMouse)
  713. {
  714. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  715. ClientToScreen(g_hWnd, &pos);
  716. SetCursorPos(pos.x, pos.y);
  717. }
  718. // Update OS mouse cursor with the cursor requested by imgui
  719. ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  720. if (g_LastMouseCursor != mouse_cursor)
  721. {
  722. g_LastMouseCursor = mouse_cursor;
  723. ImGui_ImplWin32_UpdateMouseCursor();
  724. }
  725. // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
  726. ImGui::NewFrame();
  727. }