main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // ImGui - standalone example application for DirectX 11
  2. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  3. #include <assert.h>
  4. #include <imgui.h>
  5. #include "imgui_impl_dx12.h"
  6. #include <d3d12.h>
  7. #include <dxgi1_4.h>
  8. #include <tchar.h>
  9. struct FrameContext
  10. {
  11. ID3D12CommandAllocator* CommandAllocator;
  12. UINT64 FenceValue;
  13. bool FenceSignalled;
  14. };
  15. // Data
  16. static int const NUM_FRAMES_IN_FLIGHT = 3;
  17. static FrameContext g_frameContext[NUM_FRAMES_IN_FLIGHT] = {};
  18. static UINT g_frameIndex = 0;
  19. static int const NUM_BACK_BUFFERS = 3;
  20. static IDXGIFactory4* g_pdxgiFactory = NULL;
  21. static ID3D12Device* g_pd3dDevice = NULL;
  22. static ID3D12DescriptorHeap* g_pd3dRtvDescHeap = NULL;
  23. static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL;
  24. static ID3D12CommandQueue* g_pd3dCommandQueue = NULL;
  25. static ID3D12GraphicsCommandList* g_pd3dCommandList = NULL;
  26. static ID3D12Fence* g_fence = NULL;
  27. static HANDLE g_fenceEvent = NULL;
  28. static UINT64 g_fenceLastSignalledValue = 0;
  29. static IDXGISwapChain3* g_pSwapChain = NULL;
  30. static HANDLE g_hSwapChainWaitableObject = NULL;
  31. static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
  32. static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
  33. static void WaitForLastSubmittedFrame()
  34. {
  35. FrameContext* frameCtxt = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT];
  36. UINT64 fenceValue = frameCtxt->FenceValue;
  37. if (fenceValue == 0) { // means no fence was signalled
  38. return;
  39. }
  40. frameCtxt->FenceValue = 0;
  41. if (g_fence->GetCompletedValue() >= fenceValue) {
  42. return;
  43. }
  44. HRESULT hr = g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
  45. assert(SUCCEEDED(hr));
  46. WaitForSingleObject(g_fenceEvent, INFINITE);
  47. }
  48. static FrameContext* WaitForNextFrameResources()
  49. {
  50. UINT nextFrameIndex = g_frameIndex + 1;
  51. g_frameIndex = nextFrameIndex;
  52. HANDLE waitableObjects[] = {
  53. g_hSwapChainWaitableObject,
  54. NULL,
  55. };
  56. DWORD numWaitableObjects = 1;
  57. FrameContext* frameCtxt = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT];
  58. UINT64 fenceValue = frameCtxt->FenceValue;
  59. if (fenceValue != 0) { // means no fence was signalled
  60. frameCtxt->FenceValue = 0;
  61. HRESULT hr = g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
  62. assert(SUCCEEDED(hr));
  63. waitableObjects[1] = g_fenceEvent;
  64. numWaitableObjects = 2;
  65. }
  66. HRESULT hr = WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE);
  67. assert(SUCCEEDED(hr));
  68. return frameCtxt;
  69. }
  70. void CreateRenderTarget(HWND hWnd, int width, int height)
  71. {
  72. DXGI_SWAP_CHAIN_DESC1 desc = {};
  73. desc.Width = width;
  74. desc.Height = height;
  75. desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  76. desc.Stereo = FALSE;
  77. desc.SampleDesc.Count = 1;
  78. desc.SampleDesc.Quality = 0;
  79. desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  80. desc.BufferCount = NUM_BACK_BUFFERS;
  81. desc.Scaling = DXGI_SCALING_STRETCH;
  82. desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  83. desc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  84. desc.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
  85. IDXGISwapChain1* swapChain1 = NULL;
  86. HRESULT hr = g_pdxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &desc, NULL, NULL, &swapChain1);
  87. assert(SUCCEEDED(hr));
  88. hr = swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain));
  89. assert(SUCCEEDED(hr));
  90. swapChain1->Release();
  91. hr = g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
  92. assert(SUCCEEDED(hr));
  93. g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
  94. assert(g_hSwapChainWaitableObject != NULL);
  95. for (UINT i = 0; i < NUM_BACK_BUFFERS; ++i)
  96. {
  97. hr = g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&g_mainRenderTargetResource[i]));
  98. assert(SUCCEEDED(hr));
  99. g_pd3dDevice->CreateRenderTargetView(g_mainRenderTargetResource[i], NULL, g_mainRenderTargetDescriptor[i]);
  100. }
  101. }
  102. void CleanupRenderTarget()
  103. {
  104. WaitForLastSubmittedFrame();
  105. if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
  106. for (UINT i = 0; i < NUM_BACK_BUFFERS; ++i)
  107. {
  108. if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; }
  109. }
  110. if (g_hSwapChainWaitableObject != NULL) { CloseHandle(g_hSwapChainWaitableObject); }
  111. }
  112. HRESULT CreateDeviceD3D(HWND hWnd)
  113. {
  114. (void) hWnd;
  115. #ifdef _DEBUG
  116. {
  117. ID3D12Debug* debugController = NULL;
  118. if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
  119. {
  120. debugController->EnableDebugLayer();
  121. debugController->Release();
  122. }
  123. }
  124. #endif
  125. if (CreateDXGIFactory1(IID_PPV_ARGS(&g_pdxgiFactory)) != S_OK)
  126. return E_FAIL;
  127. IDXGIAdapter1* adapter = NULL;
  128. for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != g_pdxgiFactory->EnumAdapters1(adapterIndex, &adapter); ++adapterIndex)
  129. {
  130. DXGI_ADAPTER_DESC1 desc = {};
  131. adapter->GetDesc1(&desc);
  132. if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
  133. {
  134. adapter->Release();
  135. continue;
  136. }
  137. if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), NULL)))
  138. {
  139. adapter->Release();
  140. continue;
  141. }
  142. break;
  143. }
  144. HRESULT hr = D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&g_pd3dDevice));
  145. if (adapter != NULL)
  146. {
  147. adapter->Release();
  148. }
  149. if (FAILED(hr))
  150. return hr;
  151. {
  152. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  153. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  154. desc.NumDescriptors = NUM_BACK_BUFFERS;
  155. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  156. desc.NodeMask = 1;
  157. if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK)
  158. return E_FAIL;
  159. SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  160. D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
  161. for (UINT i = 0; i < NUM_BACK_BUFFERS; ++i) {
  162. g_mainRenderTargetDescriptor[i] = rtvHandle;
  163. rtvHandle.ptr += rtvDescriptorSize;
  164. }
  165. }
  166. {
  167. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  168. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  169. desc.NumDescriptors = 1;
  170. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  171. if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK)
  172. return E_FAIL;
  173. }
  174. {
  175. D3D12_COMMAND_QUEUE_DESC desc = {};
  176. desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  177. desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  178. desc.NodeMask = 1;
  179. if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK)
  180. return E_FAIL;
  181. }
  182. for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; ++i)
  183. {
  184. if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK)
  185. return E_FAIL;
  186. }
  187. if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, NULL, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK ||
  188. g_pd3dCommandList->Close() != S_OK)
  189. return E_FAIL;
  190. if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK)
  191. return E_FAIL;
  192. g_fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  193. if (g_fenceEvent == NULL)
  194. return E_FAIL;
  195. return S_OK;
  196. }
  197. void CleanupDeviceD3D()
  198. {
  199. CleanupRenderTarget();
  200. for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; ++i)
  201. {
  202. if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = NULL; }
  203. }
  204. if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = NULL; }
  205. if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = NULL; }
  206. if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = NULL; }
  207. if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = NULL; }
  208. if (g_fence) { g_fence->Release(); g_fence = NULL; }
  209. if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = NULL; }
  210. if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
  211. if (g_pdxgiFactory) { g_pdxgiFactory->Release(); g_pdxgiFactory = NULL; }
  212. }
  213. extern LRESULT ImGui_ImplDX12_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  214. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  215. {
  216. if (ImGui_ImplDX12_WndProcHandler(hWnd, msg, wParam, lParam))
  217. return true;
  218. switch (msg)
  219. {
  220. case WM_SIZE:
  221. if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
  222. {
  223. ImGui_ImplDX12_InvalidateDeviceObjects();
  224. CleanupRenderTarget();
  225. CreateRenderTarget(hWnd, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam));
  226. ImGui_ImplDX12_CreateDeviceObjects();
  227. }
  228. return 0;
  229. case WM_SYSCOMMAND:
  230. if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
  231. return 0;
  232. break;
  233. case WM_DESTROY:
  234. PostQuitMessage(0);
  235. return 0;
  236. }
  237. return DefWindowProc(hWnd, msg, wParam, lParam);
  238. }
  239. int main(int, char**)
  240. {
  241. // Create application window
  242. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, _T("ImGui Example"), NULL };
  243. RegisterClassEx(&wc);
  244. HWND hwnd = CreateWindow(_T("ImGui Example"), _T("ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  245. // Initialize Direct3D
  246. if (CreateDeviceD3D(hwnd) < 0)
  247. {
  248. CleanupDeviceD3D();
  249. UnregisterClass(_T("ImGui Example"), wc.hInstance);
  250. return 1;
  251. }
  252. // Show the window
  253. ShowWindow(hwnd, SW_SHOWDEFAULT);
  254. UpdateWindow(hwnd);
  255. // Setup ImGui binding
  256. ImGui_ImplDX12_Init(hwnd, NUM_FRAMES_IN_FLIGHT, g_pd3dDevice, g_pd3dCommandList,
  257. g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(),
  258. g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
  259. // Load Fonts
  260. // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
  261. //ImGuiIO& io = ImGui::GetIO();
  262. //io.Fonts->AddFontDefault();
  263. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
  264. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
  265. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
  266. //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
  267. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
  268. bool show_test_window = true;
  269. bool show_another_window = false;
  270. ImVec4 clear_col = ImColor(114, 144, 154);
  271. // Main loop
  272. MSG msg;
  273. ZeroMemory(&msg, sizeof(msg));
  274. while (msg.message != WM_QUIT)
  275. {
  276. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  277. {
  278. TranslateMessage(&msg);
  279. DispatchMessage(&msg);
  280. continue;
  281. }
  282. // Wait for frame resources to be available
  283. ImGui_ImplDX12_NewFrame();
  284. // 1. Show a simple window
  285. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  286. {
  287. static float f = 0.0f;
  288. ImGui::Text("Hello, world!");
  289. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  290. ImGui::ColorEdit3("clear color", (float*)&clear_col);
  291. if (ImGui::Button("Test Window")) show_test_window ^= 1;
  292. if (ImGui::Button("Another Window")) show_another_window ^= 1;
  293. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  294. }
  295. // 2. Show another simple window, this time using an explicit Begin/End pair
  296. if (show_another_window)
  297. {
  298. ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
  299. ImGui::Begin("Another Window", &show_another_window);
  300. ImGui::Text("Hello");
  301. ImGui::End();
  302. }
  303. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  304. if (show_test_window)
  305. {
  306. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  307. ImGui::ShowTestWindow(&show_test_window);
  308. }
  309. // Rendering
  310. FrameContext* frameCtxt = WaitForNextFrameResources();
  311. UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex();
  312. HRESULT hr = frameCtxt->CommandAllocator->Reset();
  313. assert(SUCCEEDED(hr));
  314. hr = g_pd3dCommandList->Reset(frameCtxt->CommandAllocator, NULL);
  315. assert(SUCCEEDED(hr));
  316. D3D12_RESOURCE_BARRIER barrier = {};
  317. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  318. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  319. barrier.Transition.pResource = g_mainRenderTargetResource[backBufferIdx];
  320. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  321. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  322. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  323. g_pd3dCommandList->ResourceBarrier(1, &barrier);
  324. g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], (float*)&clear_col, 0, NULL);
  325. g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL);
  326. g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap);
  327. ImGui::Render();
  328. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  329. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  330. g_pd3dCommandList->ResourceBarrier(1, &barrier);
  331. hr = g_pd3dCommandList->Close();
  332. assert(SUCCEEDED(hr));
  333. g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &g_pd3dCommandList);
  334. hr = g_pSwapChain->Present(1, 0);
  335. assert(SUCCEEDED(hr));
  336. auto fenceValue = g_fenceLastSignalledValue + 1;
  337. hr = g_pd3dCommandQueue->Signal(g_fence, fenceValue);
  338. assert(SUCCEEDED(hr));
  339. g_fenceLastSignalledValue = fenceValue;
  340. frameCtxt->FenceValue = fenceValue;
  341. }
  342. ImGui_ImplDX12_Shutdown();
  343. CleanupDeviceD3D();
  344. UnregisterClass(_T("ImGui Example"), wc.hInstance);
  345. return 0;
  346. }