main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // ImGui - standalone example application for DirectX 9
  2. #include <windows.h>
  3. #include "../../imgui.h"
  4. // DirectX 9
  5. #include <d3dx9.h>
  6. #define DIRECTINPUT_VERSION 0x0800
  7. #include <dinput.h>
  8. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
  9. static HWND hWnd;
  10. static LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice
  11. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device
  12. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices
  13. struct CUSTOMVERTEX
  14. {
  15. D3DXVECTOR3 pos;
  16. D3DCOLOR col;
  17. D3DXVECTOR2 uv;
  18. };
  19. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  20. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  21. // If text or lines are blurry when integrating ImGui in your engine:
  22. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  23. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  24. {
  25. size_t total_vtx_count = 0;
  26. for (int n = 0; n < cmd_lists_count; n++)
  27. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  28. if (total_vtx_count == 0)
  29. return;
  30. // Copy and convert all vertices into a single contiguous buffer
  31. CUSTOMVERTEX* vtx_dst;
  32. if (g_pVB->Lock(0, (UINT)total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  33. return;
  34. for (int n = 0; n < cmd_lists_count; n++)
  35. {
  36. const ImDrawList* cmd_list = cmd_lists[n];
  37. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  38. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  39. {
  40. vtx_dst->pos.x = vtx_src->pos.x;
  41. vtx_dst->pos.y = vtx_src->pos.y;
  42. vtx_dst->pos.z = 0.0f;
  43. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  44. vtx_dst->uv.x = vtx_src->uv.x;
  45. vtx_dst->uv.y = vtx_src->uv.y;
  46. vtx_dst++;
  47. vtx_src++;
  48. }
  49. }
  50. g_pVB->Unlock();
  51. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  52. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  53. // Setup render state: alpha-blending, no face culling, no depth testing
  54. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  55. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  56. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  57. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  58. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  59. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  60. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  61. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  62. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  63. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
  64. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
  65. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  66. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  67. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  68. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
  69. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
  70. // Setup orthographic projection matrix
  71. D3DXMATRIXA16 mat;
  72. D3DXMatrixIdentity(&mat);
  73. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat);
  74. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat);
  75. D3DXMatrixOrthoOffCenterLH(&mat, 0.5f, ImGui::GetIO().DisplaySize.x+0.5f, ImGui::GetIO().DisplaySize.y+0.5f, 0.5f, -1.0f, +1.0f);
  76. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat);
  77. // Render command lists
  78. int vtx_offset = 0;
  79. for (int n = 0; n < cmd_lists_count; n++)
  80. {
  81. // Render command list
  82. const ImDrawList* cmd_list = cmd_lists[n];
  83. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  84. {
  85. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  86. const RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
  87. g_pd3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)pcmd->texture_id );
  88. g_pd3dDevice->SetScissorRect(&r);
  89. g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_offset, pcmd->vtx_count/3);
  90. vtx_offset += pcmd->vtx_count;
  91. }
  92. }
  93. }
  94. HRESULT InitDeviceD3D(HWND hWnd)
  95. {
  96. if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
  97. return E_FAIL;
  98. D3DPRESENT_PARAMETERS d3dpp;
  99. ZeroMemory(&d3dpp, sizeof(d3dpp));
  100. d3dpp.Windowed = TRUE;
  101. d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  102. d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
  103. d3dpp.EnableAutoDepthStencil = TRUE;
  104. d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  105. d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  106. // Create the D3DDevice
  107. if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice) < 0)
  108. return E_FAIL;
  109. return S_OK;
  110. }
  111. void CleanupDevice()
  112. {
  113. // InitImGui
  114. if (g_pVB) g_pVB->Release();
  115. // InitDeviceD3D
  116. if (LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)ImGui::GetIO().Fonts->TexID)
  117. tex->Release();
  118. if (g_pd3dDevice) g_pd3dDevice->Release();
  119. if (g_pD3D) g_pD3D->Release();
  120. }
  121. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  122. {
  123. ImGuiIO& io = ImGui::GetIO();
  124. switch (msg)
  125. {
  126. case WM_LBUTTONDOWN:
  127. io.MouseDown[0] = true;
  128. return true;
  129. case WM_LBUTTONUP:
  130. io.MouseDown[0] = false;
  131. return true;
  132. case WM_RBUTTONDOWN:
  133. io.MouseDown[1] = true;
  134. return true;
  135. case WM_RBUTTONUP:
  136. io.MouseDown[1] = false;
  137. return true;
  138. case WM_MOUSEWHEEL:
  139. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  140. return true;
  141. case WM_MOUSEMOVE:
  142. // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  143. io.MousePos.x = (signed short)(lParam);
  144. io.MousePos.y = (signed short)(lParam >> 16);
  145. return true;
  146. case WM_CHAR:
  147. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  148. if (wParam > 0 && wParam < 0x10000)
  149. io.AddInputCharacter((unsigned short)wParam);
  150. return true;
  151. case WM_DESTROY:
  152. CleanupDevice();
  153. PostQuitMessage(0);
  154. return 0;
  155. }
  156. return DefWindowProc(hWnd, msg, wParam, lParam);
  157. }
  158. void LoadFontsTexture()
  159. {
  160. // Load one or more font
  161. ImGuiIO& io = ImGui::GetIO();
  162. //ImFont* my_font1 = io.Fonts->AddFontDefault();
  163. //ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("extra_fonts/Karla-Regular.ttf", 15.0f);
  164. //ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
  165. //ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
  166. //ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 20.0f, io.Fonts->GetGlyphRangesJapanese());
  167. // Build
  168. unsigned char* pixels;
  169. int width, height, bytes_per_pixel;
  170. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height, &bytes_per_pixel);
  171. // Create texture
  172. LPDIRECT3DTEXTURE9 pTexture = NULL;
  173. if (D3DXCreateTexture(g_pd3dDevice, width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &pTexture) < 0)
  174. {
  175. IM_ASSERT(0);
  176. return;
  177. }
  178. // Copy pixels
  179. D3DLOCKED_RECT tex_locked_rect;
  180. if (pTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  181. {
  182. IM_ASSERT(0);
  183. return;
  184. }
  185. for (int y = 0; y < height; y++)
  186. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  187. pTexture->UnlockRect(0);
  188. // Store our identifier
  189. io.Fonts->TexID = (void *)pTexture;
  190. }
  191. void InitImGui()
  192. {
  193. RECT rect;
  194. GetClientRect(hWnd, &rect);
  195. int display_w = (int)(rect.right - rect.left);
  196. int display_h = (int)(rect.bottom - rect.top);
  197. ImGuiIO& io = ImGui::GetIO();
  198. io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
  199. io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our time step is variable)
  200. io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  201. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  202. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  203. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  204. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  205. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  206. io.KeyMap[ImGuiKey_End] = VK_END;
  207. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  208. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  209. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  210. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  211. io.KeyMap[ImGuiKey_A] = 'A';
  212. io.KeyMap[ImGuiKey_C] = 'C';
  213. io.KeyMap[ImGuiKey_V] = 'V';
  214. io.KeyMap[ImGuiKey_X] = 'X';
  215. io.KeyMap[ImGuiKey_Y] = 'Y';
  216. io.KeyMap[ImGuiKey_Z] = 'Z';
  217. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  218. // Create the vertex buffer
  219. if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  220. {
  221. IM_ASSERT(0);
  222. return;
  223. }
  224. LoadFontsTexture();
  225. }
  226. INT64 ticks_per_second = 0;
  227. INT64 last_time = 0;
  228. void UpdateImGui()
  229. {
  230. ImGuiIO& io = ImGui::GetIO();
  231. // Setup time step
  232. INT64 current_time;
  233. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  234. io.DeltaTime = (float)(current_time - last_time) / ticks_per_second;
  235. last_time = current_time;
  236. // Setup inputs
  237. // (we already got mouse position, buttons, wheel from the window message callback)
  238. BYTE keystate[256];
  239. GetKeyboardState(keystate);
  240. for (int i = 0; i < 256; i++)
  241. io.KeysDown[i] = (keystate[i] & 0x80) != 0;
  242. io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
  243. io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
  244. // io.MousePos : filled by WM_MOUSEMOVE event
  245. // io.MouseDown : filled by WM_*BUTTON* events
  246. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  247. // Start the frame
  248. ImGui::NewFrame();
  249. }
  250. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
  251. {
  252. // Register the window class
  253. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, L"ImGui Example", NULL };
  254. RegisterClassEx(&wc);
  255. // Create the application's window
  256. hWnd = CreateWindow(L"ImGui Example", L"ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  257. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  258. return 1;
  259. if (!QueryPerformanceCounter((LARGE_INTEGER *)&last_time))
  260. return 1;
  261. // Initialize Direct3D
  262. if (InitDeviceD3D(hWnd) < 0)
  263. {
  264. CleanupDevice();
  265. UnregisterClass(L"ImGui Example", wc.hInstance);
  266. return 1;
  267. }
  268. // Show the window
  269. ShowWindow(hWnd, SW_SHOWDEFAULT);
  270. UpdateWindow(hWnd);
  271. InitImGui();
  272. bool show_test_window = true;
  273. bool show_another_window = false;
  274. ImVec4 clear_col = ImColor(114, 144, 154);
  275. // Enter the message loop
  276. MSG msg;
  277. ZeroMemory(&msg, sizeof(msg));
  278. while (msg.message != WM_QUIT)
  279. {
  280. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  281. {
  282. TranslateMessage(&msg);
  283. DispatchMessage(&msg);
  284. continue;
  285. }
  286. UpdateImGui();
  287. // 1. Show a simple window
  288. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  289. {
  290. static float f;
  291. ImGui::Text("Hello, world!");
  292. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  293. ImGui::ColorEdit3("clear color", (float*)&clear_col);
  294. if (ImGui::Button("Test Window")) show_test_window ^= 1;
  295. if (ImGui::Button("Another Window")) show_another_window ^= 1;
  296. // Calculate and show frame rate
  297. static int ms_per_frame_idx = 0;
  298. static float ms_per_frame[60] = { 0 };
  299. static float ms_per_frame_accum = 0.0f;
  300. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  301. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  302. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  303. ms_per_frame_idx = (ms_per_frame_idx + 1) % 60;
  304. const float ms_per_frame_avg = ms_per_frame_accum / 60;
  305. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  306. }
  307. // 2. Show another simple window, this time using an explicit Begin/End pair
  308. if (show_another_window)
  309. {
  310. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  311. ImGui::Text("Hello");
  312. ImGui::End();
  313. }
  314. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  315. if (show_test_window)
  316. {
  317. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver);
  318. ImGui::ShowTestWindow(&show_test_window);
  319. }
  320. // Rendering
  321. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
  322. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
  323. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
  324. D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_col.x*255.0f), (int)(clear_col.y*255.0f), (int)(clear_col.z*255.0f), (int)(clear_col.w*255.0f));
  325. g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
  326. if (g_pd3dDevice->BeginScene() >= 0)
  327. {
  328. ImGui::Render();
  329. g_pd3dDevice->EndScene();
  330. }
  331. g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
  332. }
  333. ImGui::Shutdown();
  334. UnregisterClass(L"ImGui Example", wc.hInstance);
  335. return 0;
  336. }