main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Dear ImGui: standalone example application for 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. // Create application window
  27. //ImGui_ImplWin32_EnableDpiAwareness();
  28. WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr };
  29. ::RegisterClassExW(&wc);
  30. HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr);
  31. // Initialize Direct3D
  32. if (!CreateDeviceD3D(hwnd))
  33. {
  34. CleanupDeviceD3D();
  35. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  36. return 1;
  37. }
  38. // Show the window
  39. ::ShowWindow(hwnd, SW_SHOWDEFAULT);
  40. ::UpdateWindow(hwnd);
  41. // Setup Dear ImGui context
  42. IMGUI_CHECKVERSION();
  43. ImGui::CreateContext();
  44. ImGuiIO& io = ImGui::GetIO(); (void)io;
  45. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  46. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  47. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  48. io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
  49. //io.ConfigViewportsNoAutoMerge = true;
  50. //io.ConfigViewportsNoTaskBarIcon = true;
  51. // Setup Dear ImGui style
  52. ImGui::StyleColorsDark();
  53. //ImGui::StyleColorsLight();
  54. // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
  55. ImGuiStyle& style = ImGui::GetStyle();
  56. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  57. {
  58. style.WindowRounding = 0.0f;
  59. style.Colors[ImGuiCol_WindowBg].w = 1.0f;
  60. }
  61. // Setup Platform/Renderer backends
  62. ImGui_ImplWin32_Init(hwnd);
  63. ImGui_ImplDX9_Init(g_pd3dDevice);
  64. // Load Fonts
  65. // - 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.
  66. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  67. // - 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).
  68. // - 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.
  69. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  70. // - Read 'docs/FONTS.md' for more instructions and details.
  71. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  72. //io.Fonts->AddFontDefault();
  73. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f);
  74. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
  75. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
  76. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
  77. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
  78. //IM_ASSERT(font != nullptr);
  79. // Our state
  80. bool show_demo_window = true;
  81. bool show_another_window = false;
  82. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  83. // Main loop
  84. bool done = false;
  85. while (!done)
  86. {
  87. // Poll and handle messages (inputs, window resize, etc.)
  88. // See the WndProc() function below for our to dispatch events to the Win32 backend.
  89. MSG msg;
  90. while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
  91. {
  92. ::TranslateMessage(&msg);
  93. ::DispatchMessage(&msg);
  94. if (msg.message == WM_QUIT)
  95. done = true;
  96. }
  97. if (done)
  98. break;
  99. // Handle lost D3D9 device
  100. if (g_DeviceLost)
  101. {
  102. HRESULT hr = g_pd3dDevice->TestCooperativeLevel();
  103. if (hr == D3DERR_DEVICELOST)
  104. {
  105. ::Sleep(10);
  106. continue;
  107. }
  108. if (hr == D3DERR_DEVICENOTRESET)
  109. ResetDevice();
  110. g_DeviceLost = false;
  111. }
  112. // Handle window resize (we don't resize directly in the WM_SIZE handler)
  113. if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
  114. {
  115. g_d3dpp.BackBufferWidth = g_ResizeWidth;
  116. g_d3dpp.BackBufferHeight = g_ResizeHeight;
  117. g_ResizeWidth = g_ResizeHeight = 0;
  118. ResetDevice();
  119. }
  120. // Start the Dear ImGui frame
  121. ImGui_ImplDX9_NewFrame();
  122. ImGui_ImplWin32_NewFrame();
  123. ImGui::NewFrame();
  124. // 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!).
  125. if (show_demo_window)
  126. ImGui::ShowDemoWindow(&show_demo_window);
  127. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  128. {
  129. static float f = 0.0f;
  130. static int counter = 0;
  131. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  132. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  133. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  134. ImGui::Checkbox("Another Window", &show_another_window);
  135. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  136. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  137. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  138. counter++;
  139. ImGui::SameLine();
  140. ImGui::Text("counter = %d", counter);
  141. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  142. ImGui::End();
  143. }
  144. // 3. Show another simple window.
  145. if (show_another_window)
  146. {
  147. 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)
  148. ImGui::Text("Hello from another window!");
  149. if (ImGui::Button("Close Me"))
  150. show_another_window = false;
  151. ImGui::End();
  152. }
  153. // Rendering
  154. ImGui::EndFrame();
  155. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
  156. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
  157. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
  158. 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));
  159. g_pd3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
  160. if (g_pd3dDevice->BeginScene() >= 0)
  161. {
  162. ImGui::Render();
  163. ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
  164. g_pd3dDevice->EndScene();
  165. }
  166. // Update and Render additional Platform Windows
  167. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  168. {
  169. ImGui::UpdatePlatformWindows();
  170. ImGui::RenderPlatformWindowsDefault();
  171. }
  172. HRESULT result = g_pd3dDevice->Present(nullptr, nullptr, nullptr, nullptr);
  173. if (result == D3DERR_DEVICELOST)
  174. g_DeviceLost = true;
  175. }
  176. // Cleanup
  177. ImGui_ImplDX9_Shutdown();
  178. ImGui_ImplWin32_Shutdown();
  179. ImGui::DestroyContext();
  180. CleanupDeviceD3D();
  181. ::DestroyWindow(hwnd);
  182. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  183. return 0;
  184. }
  185. // Helper functions
  186. bool CreateDeviceD3D(HWND hWnd)
  187. {
  188. if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == nullptr)
  189. return false;
  190. // Create the D3DDevice
  191. ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
  192. g_d3dpp.Windowed = TRUE;
  193. g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  194. g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // Need to use an explicit format with alpha if needing per-pixel alpha composition.
  195. g_d3dpp.EnableAutoDepthStencil = TRUE;
  196. g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  197. g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync
  198. //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate
  199. if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
  200. return false;
  201. return true;
  202. }
  203. void CleanupDeviceD3D()
  204. {
  205. if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; }
  206. if (g_pD3D) { g_pD3D->Release(); g_pD3D = nullptr; }
  207. }
  208. void ResetDevice()
  209. {
  210. ImGui_ImplDX9_InvalidateDeviceObjects();
  211. HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
  212. if (hr == D3DERR_INVALIDCALL)
  213. IM_ASSERT(0);
  214. ImGui_ImplDX9_CreateDeviceObjects();
  215. }
  216. #ifndef WM_DPICHANGED
  217. #define WM_DPICHANGED 0x02E0 // From Windows SDK 8.1+ headers
  218. #endif
  219. // Forward declare message handler from imgui_impl_win32.cpp
  220. extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  221. // Win32 message handler
  222. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  223. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  224. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  225. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  226. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  227. {
  228. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  229. return true;
  230. switch (msg)
  231. {
  232. case WM_SIZE:
  233. if (wParam == SIZE_MINIMIZED)
  234. return 0;
  235. g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize
  236. g_ResizeHeight = (UINT)HIWORD(lParam);
  237. return 0;
  238. case WM_SYSCOMMAND:
  239. if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
  240. return 0;
  241. break;
  242. case WM_DESTROY:
  243. ::PostQuitMessage(0);
  244. return 0;
  245. case WM_DPICHANGED:
  246. if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
  247. {
  248. //const int dpi = HIWORD(wParam);
  249. //printf("WM_DPICHANGED to %d (%.0f%%)\n", dpi, (float)dpi / 96.0f * 100.0f);
  250. const RECT* suggested_rect = (RECT*)lParam;
  251. ::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);
  252. }
  253. break;
  254. }
  255. return ::DefWindowProcW(hWnd, msg, wParam, lParam);
  256. }