imgui

FORK: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
git clone https://git.neptards.moe/neptards/imgui.git
Log | Files | Refs

main.cpp (10204B)


      1 // Dear ImGui: standalone example application for DirectX 11
      2 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
      3 // Read online: https://github.com/ocornut/imgui/tree/master/docs
      4 
      5 #include "imgui.h"
      6 #include "imgui_impl_win32.h"
      7 #include "imgui_impl_dx11.h"
      8 #include <d3d11.h>
      9 #include <tchar.h>
     10 
     11 // Data
     12 static ID3D11Device*            g_pd3dDevice = NULL;
     13 static ID3D11DeviceContext*     g_pd3dDeviceContext = NULL;
     14 static IDXGISwapChain*          g_pSwapChain = NULL;
     15 static ID3D11RenderTargetView*  g_mainRenderTargetView = NULL;
     16 
     17 // Forward declarations of helper functions
     18 bool CreateDeviceD3D(HWND hWnd);
     19 void CleanupDeviceD3D();
     20 void CreateRenderTarget();
     21 void CleanupRenderTarget();
     22 LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
     23 
     24 // Main code
     25 int main(int, char**)
     26 {
     27     // Create application window
     28     //ImGui_ImplWin32_EnableDpiAwareness();
     29     WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
     30     ::RegisterClassEx(&wc);
     31     HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
     32 
     33     // Initialize Direct3D
     34     if (!CreateDeviceD3D(hwnd))
     35     {
     36         CleanupDeviceD3D();
     37         ::UnregisterClass(wc.lpszClassName, wc.hInstance);
     38         return 1;
     39     }
     40 
     41     // Show the window
     42     ::ShowWindow(hwnd, SW_SHOWDEFAULT);
     43     ::UpdateWindow(hwnd);
     44 
     45     // Setup Dear ImGui context
     46     IMGUI_CHECKVERSION();
     47     ImGui::CreateContext();
     48     ImGuiIO& io = ImGui::GetIO(); (void)io;
     49     //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
     50     //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
     51 
     52     // Setup Dear ImGui style
     53     ImGui::StyleColorsDark();
     54     //ImGui::StyleColorsClassic();
     55 
     56     // Setup Platform/Renderer backends
     57     ImGui_ImplWin32_Init(hwnd);
     58     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
     59 
     60     // Load Fonts
     61     // - 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.
     62     // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
     63     // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
     64     // - 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.
     65     // - Read 'docs/FONTS.md' for more instructions and details.
     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     //io.Fonts->AddFontDefault();
     68     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
     69     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
     70     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
     71     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
     72     //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
     73     //IM_ASSERT(font != NULL);
     74 
     75     // Our state
     76     bool show_demo_window = true;
     77     bool show_another_window = false;
     78     ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
     79 
     80     // Main loop
     81     bool done = false;
     82     while (!done)
     83     {
     84         // Poll and handle messages (inputs, window resize, etc.)
     85         // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
     86         // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
     87         // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
     88         // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
     89         MSG msg;
     90         while (::PeekMessage(&msg, NULL, 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 
    100         // Start the Dear ImGui frame
    101         ImGui_ImplDX11_NewFrame();
    102         ImGui_ImplWin32_NewFrame();
    103         ImGui::NewFrame();
    104 
    105         // 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!).
    106         if (show_demo_window)
    107             ImGui::ShowDemoWindow(&show_demo_window);
    108 
    109         // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
    110         {
    111             static float f = 0.0f;
    112             static int counter = 0;
    113 
    114             ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.
    115 
    116             ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
    117             ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
    118             ImGui::Checkbox("Another Window", &show_another_window);
    119 
    120             ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
    121             ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
    122 
    123             if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
    124                 counter++;
    125             ImGui::SameLine();
    126             ImGui::Text("counter = %d", counter);
    127 
    128             ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
    129             ImGui::End();
    130         }
    131 
    132         // 3. Show another simple window.
    133         if (show_another_window)
    134         {
    135             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)
    136             ImGui::Text("Hello from another window!");
    137             if (ImGui::Button("Close Me"))
    138                 show_another_window = false;
    139             ImGui::End();
    140         }
    141 
    142         // Rendering
    143         ImGui::Render();
    144         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 };
    145         g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
    146         g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
    147         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
    148 
    149         g_pSwapChain->Present(1, 0); // Present with vsync
    150         //g_pSwapChain->Present(0, 0); // Present without vsync
    151     }
    152 
    153     // Cleanup
    154     ImGui_ImplDX11_Shutdown();
    155     ImGui_ImplWin32_Shutdown();
    156     ImGui::DestroyContext();
    157 
    158     CleanupDeviceD3D();
    159     ::DestroyWindow(hwnd);
    160     ::UnregisterClass(wc.lpszClassName, wc.hInstance);
    161 
    162     return 0;
    163 }
    164 
    165 // Helper functions
    166 
    167 bool CreateDeviceD3D(HWND hWnd)
    168 {
    169     // Setup swap chain
    170     DXGI_SWAP_CHAIN_DESC sd;
    171     ZeroMemory(&sd, sizeof(sd));
    172     sd.BufferCount = 2;
    173     sd.BufferDesc.Width = 0;
    174     sd.BufferDesc.Height = 0;
    175     sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    176     sd.BufferDesc.RefreshRate.Numerator = 60;
    177     sd.BufferDesc.RefreshRate.Denominator = 1;
    178     sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    179     sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    180     sd.OutputWindow = hWnd;
    181     sd.SampleDesc.Count = 1;
    182     sd.SampleDesc.Quality = 0;
    183     sd.Windowed = TRUE;
    184     sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    185 
    186     UINT createDeviceFlags = 0;
    187     //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
    188     D3D_FEATURE_LEVEL featureLevel;
    189     const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
    190     if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
    191         return false;
    192 
    193     CreateRenderTarget();
    194     return true;
    195 }
    196 
    197 void CleanupDeviceD3D()
    198 {
    199     CleanupRenderTarget();
    200     if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
    201     if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
    202     if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
    203 }
    204 
    205 void CreateRenderTarget()
    206 {
    207     ID3D11Texture2D* pBackBuffer;
    208     g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
    209     g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
    210     pBackBuffer->Release();
    211 }
    212 
    213 void CleanupRenderTarget()
    214 {
    215     if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
    216 }
    217 
    218 // Forward declare message handler from imgui_impl_win32.cpp
    219 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
    220 
    221 // Win32 message handler
    222 LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
    223 {
    224     if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
    225         return true;
    226 
    227     switch (msg)
    228     {
    229     case WM_SIZE:
    230         if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
    231         {
    232             CleanupRenderTarget();
    233             g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
    234             CreateRenderTarget();
    235         }
    236         return 0;
    237     case WM_SYSCOMMAND:
    238         if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
    239             return 0;
    240         break;
    241     case WM_DESTROY:
    242         ::PostQuitMessage(0);
    243         return 0;
    244     }
    245     return ::DefWindowProc(hWnd, msg, wParam, lParam);
    246 }