main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // Dear ImGui: standalone example application for Windows API + OpenGL
  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. // This is provided for completeness, however it is strongly recommended you use OpenGL with SDL or GLFW.
  8. #include "imgui.h"
  9. #include "imgui_impl_opengl3.h"
  10. #include "imgui_impl_win32.h"
  11. #ifndef WIN32_LEAN_AND_MEAN
  12. #define WIN32_LEAN_AND_MEAN
  13. #endif
  14. #include <windows.h>
  15. #include <GL/gl.h>
  16. #include <tchar.h>
  17. // Data stored per platform window
  18. struct WGL_WindowData { HDC hDC; };
  19. // Data
  20. static HGLRC g_hRC;
  21. static WGL_WindowData g_MainWindow;
  22. static int g_Width;
  23. static int g_Height;
  24. // Forward declarations of helper functions
  25. bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data);
  26. void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data);
  27. void ResetDeviceWGL();
  28. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  29. // Support function for multi-viewports
  30. // Unlike most other backend combination, we need specific hooks to combine Win32+OpenGL.
  31. // We could in theory decide to support Win32-specific code in OpenGL backend via e.g. an hypothetical ImGui_ImplOpenGL3_InitForRawWin32().
  32. static void Hook_Renderer_CreateWindow(ImGuiViewport* viewport)
  33. {
  34. assert(viewport->RendererUserData == NULL);
  35. WGL_WindowData* data = IM_NEW(WGL_WindowData);
  36. CreateDeviceWGL((HWND)viewport->PlatformHandle, data);
  37. viewport->RendererUserData = data;
  38. }
  39. static void Hook_Renderer_DestroyWindow(ImGuiViewport* viewport)
  40. {
  41. if (viewport->RendererUserData != NULL)
  42. {
  43. WGL_WindowData* data = (WGL_WindowData*)viewport->RendererUserData;
  44. CleanupDeviceWGL((HWND)viewport->PlatformHandle, data);
  45. IM_DELETE(data);
  46. viewport->RendererUserData = NULL;
  47. }
  48. }
  49. static void Hook_Platform_RenderWindow(ImGuiViewport* viewport, void*)
  50. {
  51. // Activate the platform window DC in the OpenGL rendering context
  52. if (WGL_WindowData* data = (WGL_WindowData*)viewport->RendererUserData)
  53. wglMakeCurrent(data->hDC, g_hRC);
  54. }
  55. static void Hook_Renderer_SwapBuffers(ImGuiViewport* viewport, void*)
  56. {
  57. if (WGL_WindowData* data = (WGL_WindowData*)viewport->RendererUserData)
  58. ::SwapBuffers(data->hDC);
  59. }
  60. // Main code
  61. int main(int, char**)
  62. {
  63. // Make process DPI aware and obtain main monitor scale
  64. //ImGui_ImplWin32_EnableDpiAwareness(); // FIXME: This somehow doesn't work in the Win32+OpenGL example. Why?
  65. float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY));
  66. // Create application window
  67. WNDCLASSEXW wc = { sizeof(wc), CS_OWNDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr };
  68. ::RegisterClassExW(&wc);
  69. HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr);
  70. // Initialize OpenGL
  71. if (!CreateDeviceWGL(hwnd, &g_MainWindow))
  72. {
  73. CleanupDeviceWGL(hwnd, &g_MainWindow);
  74. ::DestroyWindow(hwnd);
  75. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  76. return 1;
  77. }
  78. wglMakeCurrent(g_MainWindow.hDC, g_hRC);
  79. // Show the window
  80. ::ShowWindow(hwnd, SW_SHOWDEFAULT);
  81. ::UpdateWindow(hwnd);
  82. // Setup Dear ImGui context
  83. IMGUI_CHECKVERSION();
  84. ImGui::CreateContext();
  85. ImGuiIO& io = ImGui::GetIO(); (void)io;
  86. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  87. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  88. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  89. io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
  90. // Setup Dear ImGui style
  91. ImGui::StyleColorsDark();
  92. //ImGui::StyleColorsClassic();
  93. // Setup scaling
  94. ImGuiStyle& style = ImGui::GetStyle();
  95. 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)
  96. style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose)
  97. io.ConfigDpiScaleFonts = true; // [Experimental] Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now.
  98. io.ConfigDpiScaleViewports = true; // [Experimental] Scale Dear ImGui and Platform Windows when Monitor DPI changes.
  99. // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
  100. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  101. {
  102. style.WindowRounding = 0.0f;
  103. style.Colors[ImGuiCol_WindowBg].w = 1.0f;
  104. }
  105. // Setup Platform/Renderer backends
  106. ImGui_ImplWin32_InitForOpenGL(hwnd);
  107. ImGui_ImplOpenGL3_Init();
  108. // Win32+GL needs specific hooks for viewport, as there are specific things needed to tie Win32 and GL api.
  109. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  110. {
  111. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  112. IM_ASSERT(platform_io.Renderer_CreateWindow == NULL);
  113. IM_ASSERT(platform_io.Renderer_DestroyWindow == NULL);
  114. IM_ASSERT(platform_io.Renderer_SwapBuffers == NULL);
  115. IM_ASSERT(platform_io.Platform_RenderWindow == NULL);
  116. platform_io.Renderer_CreateWindow = Hook_Renderer_CreateWindow;
  117. platform_io.Renderer_DestroyWindow = Hook_Renderer_DestroyWindow;
  118. platform_io.Renderer_SwapBuffers = Hook_Renderer_SwapBuffers;
  119. platform_io.Platform_RenderWindow = Hook_Platform_RenderWindow;
  120. }
  121. // Load Fonts
  122. // - 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.
  123. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  124. // - 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).
  125. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  126. // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author!
  127. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  128. //style.FontSizeBase = 20.0f;
  129. //io.Fonts->AddFontDefault();
  130. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  131. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  132. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  133. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  134. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  135. //IM_ASSERT(font != nullptr);
  136. // Our state
  137. bool show_demo_window = true;
  138. bool show_another_window = false;
  139. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  140. // Main loop
  141. bool done = false;
  142. while (!done)
  143. {
  144. // Poll and handle messages (inputs, window resize, etc.)
  145. // See the WndProc() function below for our to dispatch events to the Win32 backend.
  146. MSG msg;
  147. while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
  148. {
  149. ::TranslateMessage(&msg);
  150. ::DispatchMessage(&msg);
  151. if (msg.message == WM_QUIT)
  152. done = true;
  153. }
  154. if (done)
  155. break;
  156. if (::IsIconic(hwnd))
  157. {
  158. ::Sleep(10);
  159. continue;
  160. }
  161. // Start the Dear ImGui frame
  162. ImGui_ImplOpenGL3_NewFrame();
  163. ImGui_ImplWin32_NewFrame();
  164. ImGui::NewFrame();
  165. // 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!).
  166. if (show_demo_window)
  167. ImGui::ShowDemoWindow(&show_demo_window);
  168. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  169. {
  170. static float f = 0.0f;
  171. static int counter = 0;
  172. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  173. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  174. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  175. ImGui::Checkbox("Another Window", &show_another_window);
  176. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  177. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  178. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  179. counter++;
  180. ImGui::SameLine();
  181. ImGui::Text("counter = %d", counter);
  182. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  183. ImGui::End();
  184. }
  185. // 3. Show another simple window.
  186. if (show_another_window)
  187. {
  188. 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)
  189. ImGui::Text("Hello from another window!");
  190. if (ImGui::Button("Close Me"))
  191. show_another_window = false;
  192. ImGui::End();
  193. }
  194. // Rendering
  195. ImGui::Render();
  196. glViewport(0, 0, g_Width, g_Height);
  197. glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
  198. glClear(GL_COLOR_BUFFER_BIT);
  199. ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
  200. // Update and Render additional Platform Windows
  201. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  202. {
  203. ImGui::UpdatePlatformWindows();
  204. ImGui::RenderPlatformWindowsDefault();
  205. // Restore the OpenGL rendering context to the main window DC, since platform windows might have changed it.
  206. wglMakeCurrent(g_MainWindow.hDC, g_hRC);
  207. }
  208. // Present
  209. ::SwapBuffers(g_MainWindow.hDC);
  210. }
  211. ImGui_ImplOpenGL3_Shutdown();
  212. ImGui_ImplWin32_Shutdown();
  213. ImGui::DestroyContext();
  214. CleanupDeviceWGL(hwnd, &g_MainWindow);
  215. wglDeleteContext(g_hRC);
  216. ::DestroyWindow(hwnd);
  217. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  218. return 0;
  219. }
  220. // Helper functions
  221. bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data)
  222. {
  223. HDC hDc = ::GetDC(hWnd);
  224. PIXELFORMATDESCRIPTOR pfd = { 0 };
  225. pfd.nSize = sizeof(pfd);
  226. pfd.nVersion = 1;
  227. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  228. pfd.iPixelType = PFD_TYPE_RGBA;
  229. pfd.cColorBits = 32;
  230. const int pf = ::ChoosePixelFormat(hDc, &pfd);
  231. if (pf == 0)
  232. return false;
  233. if (::SetPixelFormat(hDc, pf, &pfd) == FALSE)
  234. return false;
  235. ::ReleaseDC(hWnd, hDc);
  236. data->hDC = ::GetDC(hWnd);
  237. if (!g_hRC)
  238. g_hRC = wglCreateContext(data->hDC);
  239. return true;
  240. }
  241. void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data)
  242. {
  243. wglMakeCurrent(nullptr, nullptr);
  244. ::ReleaseDC(hWnd, data->hDC);
  245. }
  246. // Forward declare message handler from imgui_impl_win32.cpp
  247. extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  248. // Win32 message handler
  249. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  250. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  251. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  252. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  253. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  254. {
  255. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  256. return true;
  257. switch (msg)
  258. {
  259. case WM_SIZE:
  260. if (wParam != SIZE_MINIMIZED)
  261. {
  262. g_Width = LOWORD(lParam);
  263. g_Height = HIWORD(lParam);
  264. }
  265. return 0;
  266. case WM_SYSCOMMAND:
  267. if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
  268. return 0;
  269. break;
  270. case WM_DESTROY:
  271. ::PostQuitMessage(0);
  272. return 0;
  273. }
  274. return ::DefWindowProcW(hWnd, msg, wParam, lParam);
  275. }