main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Dear ImGui: standalone example application for Windows API + DirectX 9
  2. // Learn about Dear ImGui:
  3. // - FAQ https://dearimgui.com/faq
  4. // - Getting Started https://dearimgui.com/getting-started
  5. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  6. // - Introduction, links and more at the top of imgui.cpp
  7. #include "imgui.h"
  8. #include "imgui_impl_dx9.h"
  9. #include "imgui_impl_win32.h"
  10. #include <d3d9.h>
  11. #include <tchar.h>
  12. // Data
  13. static LPDIRECT3D9 g_pD3D = nullptr;
  14. static LPDIRECT3DDEVICE9 g_pd3dDevice = nullptr;
  15. static bool g_DeviceLost = false;
  16. static UINT g_ResizeWidth = 0, g_ResizeHeight = 0;
  17. static D3DPRESENT_PARAMETERS g_d3dpp = {};
  18. // Forward declarations of helper functions
  19. bool CreateDeviceD3D(HWND hWnd);
  20. void CleanupDeviceD3D();
  21. void ResetDevice();
  22. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  23. // Main code
  24. int main(int, char**)
  25. {
  26. // Make process DPI aware and obtain main monitor scale
  27. ImGui_ImplWin32_EnableDpiAwareness();
  28. float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY));
  29. // Create application window
  30. WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr };
  31. ::RegisterClassExW(&wc);
  32. HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr);
  33. // Initialize Direct3D
  34. if (!CreateDeviceD3D(hwnd))
  35. {
  36. CleanupDeviceD3D();
  37. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  38. return 1;
  39. }
  40. // Show the window
  41. ::ShowWindow(hwnd, SW_SHOWDEFAULT);
  42. ::UpdateWindow(hwnd);
  43. // Setup Dear ImGui context
  44. IMGUI_CHECKVERSION();
  45. ImGui::CreateContext();
  46. ImGuiIO& io = ImGui::GetIO(); (void)io;
  47. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  48. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  49. // Setup Dear ImGui style
  50. ImGui::StyleColorsDark();
  51. //ImGui::StyleColorsLight();
  52. // Setup scaling
  53. ImGuiStyle& style = ImGui::GetStyle();
  54. style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
  55. style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor)
  56. // Setup Platform/Renderer backends
  57. ImGui_ImplWin32_Init(hwnd);
  58. ImGui_ImplDX9_Init(g_pd3dDevice);
  59. // Load Fonts
  60. // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
  61. // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
  62. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  63. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
  64. // - Read 'docs/FONTS.md' for more instructions and details.
  65. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
  66. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  67. //style.FontSizeBase = 20.0f;
  68. //io.Fonts->AddFontDefaultVector();
  69. //io.Fonts->AddFontDefaultBitmap();
  70. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  71. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  72. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  73. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  74. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  75. //IM_ASSERT(font != nullptr);
  76. // Our state
  77. bool show_demo_window = true;
  78. bool show_another_window = false;
  79. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  80. // Main loop
  81. bool done = false;
  82. while (!done)
  83. {
  84. // Poll and handle messages (inputs, window resize, etc.)
  85. // See the WndProc() function below for our to dispatch events to the Win32 backend.
  86. MSG msg;
  87. while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
  88. {
  89. ::TranslateMessage(&msg);
  90. ::DispatchMessage(&msg);
  91. if (msg.message == WM_QUIT)
  92. done = true;
  93. }
  94. if (done)
  95. break;
  96. // Handle lost D3D9 device
  97. if (g_DeviceLost)
  98. {
  99. HRESULT hr = g_pd3dDevice->TestCooperativeLevel();
  100. if (hr == D3DERR_DEVICELOST)
  101. {
  102. ::Sleep(10);
  103. continue;
  104. }
  105. if (hr == D3DERR_DEVICENOTRESET)
  106. ResetDevice();
  107. g_DeviceLost = false;
  108. }
  109. // Handle window resize (we don't resize directly in the WM_SIZE handler)
  110. if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
  111. {
  112. g_d3dpp.BackBufferWidth = g_ResizeWidth;
  113. g_d3dpp.BackBufferHeight = g_ResizeHeight;
  114. g_ResizeWidth = g_ResizeHeight = 0;
  115. ResetDevice();
  116. }
  117. // Start the Dear ImGui frame
  118. ImGui_ImplDX9_NewFrame();
  119. ImGui_ImplWin32_NewFrame();
  120. ImGui::NewFrame();
  121. // 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!).
  122. if (show_demo_window)
  123. ImGui::ShowDemoWindow(&show_demo_window);
  124. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  125. {
  126. static float f = 0.0f;
  127. static int counter = 0;
  128. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  129. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  130. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  131. ImGui::Checkbox("Another Window", &show_another_window);
  132. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  133. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  134. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  135. counter++;
  136. ImGui::SameLine();
  137. ImGui::Text("counter = %d", counter);
  138. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  139. ImGui::End();
  140. }
  141. // 3. Show another simple window.
  142. if (show_another_window)
  143. {
  144. ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
  145. ImGui::Text("Hello from another window!");
  146. if (ImGui::Button("Close Me"))
  147. show_another_window = false;
  148. ImGui::End();
  149. }
  150. // Rendering
  151. ImGui::EndFrame();
  152. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
  153. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
  154. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
  155. D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*clear_color.w*255.0f), (int)(clear_color.y*clear_color.w*255.0f), (int)(clear_color.z*clear_color.w*255.0f), (int)(clear_color.w*255.0f));
  156. g_pd3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
  157. if (g_pd3dDevice->BeginScene() >= 0)
  158. {
  159. ImGui::Render();
  160. ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
  161. g_pd3dDevice->EndScene();
  162. }
  163. HRESULT result = g_pd3dDevice->Present(nullptr, nullptr, nullptr, nullptr);
  164. if (result == D3DERR_DEVICELOST)
  165. g_DeviceLost = true;
  166. }
  167. // Cleanup
  168. ImGui_ImplDX9_Shutdown();
  169. ImGui_ImplWin32_Shutdown();
  170. ImGui::DestroyContext();
  171. CleanupDeviceD3D();
  172. ::DestroyWindow(hwnd);
  173. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  174. return 0;
  175. }
  176. // Helper functions
  177. bool CreateDeviceD3D(HWND hWnd)
  178. {
  179. if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == nullptr)
  180. return false;
  181. // Create the D3DDevice
  182. ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
  183. g_d3dpp.Windowed = TRUE;
  184. g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  185. g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // Need to use an explicit format with alpha if needing per-pixel alpha composition.
  186. g_d3dpp.EnableAutoDepthStencil = TRUE;
  187. g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  188. g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync
  189. //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate
  190. if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
  191. return false;
  192. return true;
  193. }
  194. void CleanupDeviceD3D()
  195. {
  196. if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; }
  197. if (g_pD3D) { g_pD3D->Release(); g_pD3D = nullptr; }
  198. }
  199. void ResetDevice()
  200. {
  201. ImGui_ImplDX9_InvalidateDeviceObjects();
  202. HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
  203. if (hr == D3DERR_INVALIDCALL)
  204. IM_ASSERT(0);
  205. ImGui_ImplDX9_CreateDeviceObjects();
  206. }
  207. // Forward declare message handler from imgui_impl_win32.cpp
  208. extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  209. // Win32 message handler
  210. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  211. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  212. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  213. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  214. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  215. {
  216. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  217. return true;
  218. switch (msg)
  219. {
  220. case WM_SIZE:
  221. if (wParam == SIZE_MINIMIZED)
  222. return 0;
  223. g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize
  224. g_ResizeHeight = (UINT)HIWORD(lParam);
  225. return 0;
  226. case WM_SYSCOMMAND:
  227. if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
  228. return 0;
  229. break;
  230. case WM_DESTROY:
  231. ::PostQuitMessage(0);
  232. return 0;
  233. }
  234. return ::DefWindowProcW(hWnd, msg, wParam, lParam);
  235. }