1 | // Dear ImGui: standalone example application for DirectX 11 |
2 | |
3 | // Learn about Dear ImGui: |
4 | // - FAQ https://dearimgui.com/faq |
5 | // - Getting Started https://dearimgui.com/getting-started |
6 | // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). |
7 | // - Introduction, links and more at the top of imgui.cpp |
8 | |
9 | #include "imgui.h" |
10 | #include "imgui_impl_win32.h" |
11 | #include "imgui_impl_dx11.h" |
12 | #include <d3d11.h> |
13 | #include <tchar.h> |
14 | |
15 | // Data |
16 | static ID3D11Device* g_pd3dDevice = nullptr; |
17 | static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr; |
18 | static IDXGISwapChain* g_pSwapChain = nullptr; |
19 | static bool g_SwapChainOccluded = false; |
20 | static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; |
21 | static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr; |
22 | |
23 | // Forward declarations of helper functions |
24 | bool CreateDeviceD3D(HWND hWnd); |
25 | void CleanupDeviceD3D(); |
26 | void CreateRenderTarget(); |
27 | void CleanupRenderTarget(); |
28 | LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); |
29 | |
30 | // Main code |
31 | int main(int, char**) |
32 | { |
33 | // Create application window |
34 | //ImGui_ImplWin32_EnableDpiAwareness(); |
35 | WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example" , nullptr }; |
36 | ::RegisterClassExW(&wc); |
37 | HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX11 Example" , WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); |
38 | |
39 | // Initialize Direct3D |
40 | if (!CreateDeviceD3D(hwnd)) |
41 | { |
42 | CleanupDeviceD3D(); |
43 | ::UnregisterClassW(wc.lpszClassName, wc.hInstance); |
44 | return 1; |
45 | } |
46 | |
47 | // Show the window |
48 | ::ShowWindow(hwnd, SW_SHOWDEFAULT); |
49 | ::UpdateWindow(hwnd); |
50 | |
51 | // Setup Dear ImGui context |
52 | IMGUI_CHECKVERSION(); |
53 | ImGui::CreateContext(); |
54 | ImGuiIO& io = ImGui::GetIO(); (void)io; |
55 | io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls |
56 | io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls |
57 | io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking |
58 | io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows |
59 | //io.ConfigViewportsNoAutoMerge = true; |
60 | //io.ConfigViewportsNoTaskBarIcon = true; |
61 | //io.ConfigViewportsNoDefaultParent = true; |
62 | //io.ConfigDockingAlwaysTabBar = true; |
63 | //io.ConfigDockingTransparentPayload = true; |
64 | //io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleFonts; // FIXME-DPI: Experimental. THIS CURRENTLY DOESN'T WORK AS EXPECTED. DON'T USE IN USER APP! |
65 | //io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleViewports; // FIXME-DPI: Experimental. |
66 | |
67 | // Setup Dear ImGui style |
68 | ImGui::StyleColorsDark(); |
69 | //ImGui::StyleColorsLight(); |
70 | |
71 | // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. |
72 | ImGuiStyle& style = ImGui::GetStyle(); |
73 | if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) |
74 | { |
75 | style.WindowRounding = 0.0f; |
76 | style.Colors[ImGuiCol_WindowBg].w = 1.0f; |
77 | } |
78 | |
79 | // Setup Platform/Renderer backends |
80 | ImGui_ImplWin32_Init(hwnd); |
81 | ImGui_ImplDX11_Init(device: g_pd3dDevice, device_context: g_pd3dDeviceContext); |
82 | |
83 | // Load Fonts |
84 | // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. |
85 | // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. |
86 | // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). |
87 | // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. |
88 | // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. |
89 | // - Read 'docs/FONTS.md' for more instructions and details. |
90 | // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! |
91 | //io.Fonts->AddFontDefault(); |
92 | //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); |
93 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); |
94 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); |
95 | //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); |
96 | //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); |
97 | //IM_ASSERT(font != nullptr); |
98 | |
99 | // Our state |
100 | bool show_demo_window = true; |
101 | bool show_another_window = false; |
102 | ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); |
103 | |
104 | // Main loop |
105 | bool done = false; |
106 | while (!done) |
107 | { |
108 | // Poll and handle messages (inputs, window resize, etc.) |
109 | // See the WndProc() function below for our to dispatch events to the Win32 backend. |
110 | MSG msg; |
111 | while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) |
112 | { |
113 | ::TranslateMessage(&msg); |
114 | ::DispatchMessage(&msg); |
115 | if (msg.message == WM_QUIT) |
116 | done = true; |
117 | } |
118 | if (done) |
119 | break; |
120 | |
121 | // Handle window being minimized or screen locked |
122 | if (g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED) |
123 | { |
124 | ::Sleep(10); |
125 | continue; |
126 | } |
127 | g_SwapChainOccluded = false; |
128 | |
129 | // Handle window resize (we don't resize directly in the WM_SIZE handler) |
130 | if (g_ResizeWidth != 0 && g_ResizeHeight != 0) |
131 | { |
132 | CleanupRenderTarget(); |
133 | g_pSwapChain->ResizeBuffers(0, g_ResizeWidth, g_ResizeHeight, DXGI_FORMAT_UNKNOWN, 0); |
134 | g_ResizeWidth = g_ResizeHeight = 0; |
135 | CreateRenderTarget(); |
136 | } |
137 | |
138 | // Start the Dear ImGui frame |
139 | ImGui_ImplDX11_NewFrame(); |
140 | ImGui_ImplWin32_NewFrame(); |
141 | ImGui::NewFrame(); |
142 | |
143 | // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). |
144 | if (show_demo_window) |
145 | ImGui::ShowDemoWindow(p_open: &show_demo_window); |
146 | |
147 | // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. |
148 | { |
149 | static float f = 0.0f; |
150 | static int counter = 0; |
151 | |
152 | ImGui::Begin(name: "Hello, world!" ); // Create a window called "Hello, world!" and append into it. |
153 | |
154 | ImGui::Text(fmt: "This is some useful text." ); // Display some text (you can use a format strings too) |
155 | ImGui::Checkbox(label: "Demo Window" , v: &show_demo_window); // Edit bools storing our window open/close state |
156 | ImGui::Checkbox(label: "Another Window" , v: &show_another_window); |
157 | |
158 | ImGui::SliderFloat(label: "float" , v: &f, v_min: 0.0f, v_max: 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f |
159 | ImGui::ColorEdit3(label: "clear color" , col: (float*)&clear_color); // Edit 3 floats representing a color |
160 | |
161 | if (ImGui::Button(label: "Button" )) // Buttons return true when clicked (most widgets return true when edited/activated) |
162 | counter++; |
163 | ImGui::SameLine(); |
164 | ImGui::Text(fmt: "counter = %d" , counter); |
165 | |
166 | ImGui::Text(fmt: "Application average %.3f ms/frame (%.1f FPS)" , 1000.0f / io.Framerate, io.Framerate); |
167 | ImGui::End(); |
168 | } |
169 | |
170 | // 3. Show another simple window. |
171 | if (show_another_window) |
172 | { |
173 | ImGui::Begin(name: "Another Window" , p_open: &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) |
174 | ImGui::Text(fmt: "Hello from another window!" ); |
175 | if (ImGui::Button(label: "Close Me" )) |
176 | show_another_window = false; |
177 | ImGui::End(); |
178 | } |
179 | |
180 | // Rendering |
181 | ImGui::Render(); |
182 | const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; |
183 | g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr); |
184 | g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); |
185 | ImGui_ImplDX11_RenderDrawData(draw_data: ImGui::GetDrawData()); |
186 | |
187 | // Update and Render additional Platform Windows |
188 | if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) |
189 | { |
190 | ImGui::UpdatePlatformWindows(); |
191 | ImGui::RenderPlatformWindowsDefault(); |
192 | } |
193 | |
194 | // Present |
195 | HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync |
196 | //HRESULT hr = g_pSwapChain->Present(0, 0); // Present without vsync |
197 | g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED); |
198 | } |
199 | |
200 | // Cleanup |
201 | ImGui_ImplDX11_Shutdown(); |
202 | ImGui_ImplWin32_Shutdown(); |
203 | ImGui::DestroyContext(); |
204 | |
205 | CleanupDeviceD3D(); |
206 | ::DestroyWindow(hwnd); |
207 | ::UnregisterClassW(wc.lpszClassName, wc.hInstance); |
208 | |
209 | return 0; |
210 | } |
211 | |
212 | // Helper functions |
213 | bool CreateDeviceD3D(HWND hWnd) |
214 | { |
215 | // Setup swap chain |
216 | DXGI_SWAP_CHAIN_DESC sd; |
217 | ZeroMemory(&sd, sizeof(sd)); |
218 | sd.BufferCount = 2; |
219 | sd.BufferDesc.Width = 0; |
220 | sd.BufferDesc.Height = 0; |
221 | sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; |
222 | sd.BufferDesc.RefreshRate.Numerator = 60; |
223 | sd.BufferDesc.RefreshRate.Denominator = 1; |
224 | sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; |
225 | sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; |
226 | sd.OutputWindow = hWnd; |
227 | sd.SampleDesc.Count = 1; |
228 | sd.SampleDesc.Quality = 0; |
229 | sd.Windowed = TRUE; |
230 | sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; |
231 | |
232 | UINT createDeviceFlags = 0; |
233 | //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; |
234 | D3D_FEATURE_LEVEL featureLevel; |
235 | const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; |
236 | HRESULT res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); |
237 | if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available. |
238 | res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); |
239 | if (res != S_OK) |
240 | return false; |
241 | |
242 | CreateRenderTarget(); |
243 | return true; |
244 | } |
245 | |
246 | void CleanupDeviceD3D() |
247 | { |
248 | CleanupRenderTarget(); |
249 | if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; } |
250 | if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; } |
251 | if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } |
252 | } |
253 | |
254 | void CreateRenderTarget() |
255 | { |
256 | ID3D11Texture2D* pBackBuffer; |
257 | g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); |
258 | g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView); |
259 | pBackBuffer->Release(); |
260 | } |
261 | |
262 | void CleanupRenderTarget() |
263 | { |
264 | if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; } |
265 | } |
266 | |
267 | #ifndef WM_DPICHANGED |
268 | #define WM_DPICHANGED 0x02E0 // From Windows SDK 8.1+ headers |
269 | #endif |
270 | |
271 | // Forward declare message handler from imgui_impl_win32.cpp |
272 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); |
273 | |
274 | // Win32 message handler |
275 | // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. |
276 | // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. |
277 | // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. |
278 | // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. |
279 | LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) |
280 | { |
281 | if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) |
282 | return true; |
283 | |
284 | switch (msg) |
285 | { |
286 | case WM_SIZE: |
287 | if (wParam == SIZE_MINIMIZED) |
288 | return 0; |
289 | g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize |
290 | g_ResizeHeight = (UINT)HIWORD(lParam); |
291 | return 0; |
292 | case WM_SYSCOMMAND: |
293 | if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu |
294 | return 0; |
295 | break; |
296 | case WM_DESTROY: |
297 | ::PostQuitMessage(0); |
298 | return 0; |
299 | case WM_DPICHANGED: |
300 | if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) |
301 | { |
302 | //const int dpi = HIWORD(wParam); |
303 | //printf("WM_DPICHANGED to %d (%.0f%%)\n", dpi, (float)dpi / 96.0f * 100.0f); |
304 | const RECT* suggested_rect = (RECT*)lParam; |
305 | ::SetWindowPos(hWnd, nullptr, suggested_rect->left, suggested_rect->top, suggested_rect->right - suggested_rect->left, suggested_rect->bottom - suggested_rect->top, SWP_NOZORDER | SWP_NOACTIVATE); |
306 | } |
307 | break; |
308 | } |
309 | return ::DefWindowProcW(hWnd, msg, wParam, lParam); |
310 | } |
311 | |