main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #include <windows.h>
  2. #include <imm.h>
  3. #include <mmsystem.h>
  4. #include <d3dx9.h>
  5. #define DIRECTINPUT_VERSION 0x0800
  6. #include <dinput.h>
  7. #include "../../imgui.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. static LPDIRECT3DTEXTURE9 g_pTexture = NULL; // Our texture
  14. struct CUSTOMVERTEX
  15. {
  16. D3DXVECTOR3 position;
  17. D3DCOLOR color;
  18. float tu, tv;
  19. };
  20. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  21. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  22. // If text or lines are blurry when integrating ImGui in your engine:
  23. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  24. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
  25. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  26. {
  27. size_t total_vtx_count = 0;
  28. for (int n = 0; n < cmd_lists_count; n++)
  29. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  30. if (total_vtx_count == 0)
  31. return;
  32. // Copy and convert all vertices into a single contiguous buffer
  33. CUSTOMVERTEX* vtx_dst;
  34. if (g_pVB->Lock(0, total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  35. return;
  36. for (int n = 0; n < cmd_lists_count; n++)
  37. {
  38. const ImDrawList* cmd_list = cmd_lists[n];
  39. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  40. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  41. {
  42. vtx_dst->position.x = vtx_src->pos.x;
  43. vtx_dst->position.y = vtx_src->pos.y;
  44. vtx_dst->position.z = 0.0f;
  45. vtx_dst->color = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  46. vtx_dst->tu = vtx_src->uv.x;
  47. vtx_dst->tv = vtx_src->uv.y;
  48. vtx_dst++;
  49. vtx_src++;
  50. }
  51. }
  52. g_pVB->Unlock();
  53. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  54. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  55. // Setup render state: alpha-blending, no face culling, no depth testing
  56. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  57. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  58. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  59. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  60. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  61. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  62. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  63. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  64. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  65. // Setup texture
  66. g_pd3dDevice->SetTexture( 0, g_pTexture );
  67. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
  68. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
  69. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
  70. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  71. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  72. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  73. // Setup orthographic projection matrix
  74. D3DXMATRIXA16 mat;
  75. D3DXMatrixIdentity(&mat);
  76. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat);
  77. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat);
  78. D3DXMatrixOrthoOffCenterLH(&mat, 0.5f, ImGui::GetIO().DisplaySize.x+0.5f, ImGui::GetIO().DisplaySize.y+0.5f, 0.5f, -1.0f, +1.0f);
  79. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat);
  80. // Render command lists
  81. int vtx_offset = 0;
  82. for (int n = 0; n < cmd_lists_count; n++)
  83. {
  84. // Render command list
  85. const ImDrawList* cmd_list = cmd_lists[n];
  86. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  87. {
  88. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  89. const RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
  90. g_pd3dDevice->SetScissorRect(&r);
  91. g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_offset, pcmd->vtx_count/3);
  92. vtx_offset += pcmd->vtx_count;
  93. }
  94. }
  95. }
  96. HRESULT InitD3D(HWND hWnd)
  97. {
  98. if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
  99. return E_FAIL;
  100. D3DPRESENT_PARAMETERS d3dpp;
  101. ZeroMemory(&d3dpp, sizeof(d3dpp));
  102. d3dpp.Windowed = TRUE;
  103. d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  104. d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
  105. d3dpp.EnableAutoDepthStencil = TRUE;
  106. d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  107. d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  108. // Create the D3DDevice
  109. if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice) < 0)
  110. return E_FAIL;
  111. return S_OK;
  112. }
  113. void Cleanup()
  114. {
  115. if (g_pTexture != NULL)
  116. g_pTexture->Release();
  117. if (g_pd3dDevice != NULL)
  118. g_pd3dDevice->Release();
  119. if (g_pD3D != NULL)
  120. g_pD3D->Release();
  121. }
  122. LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  123. {
  124. ImGuiIO& io = ImGui::GetIO();
  125. switch (msg)
  126. {
  127. case WM_LBUTTONDOWN:
  128. io.MouseDown[0] = true;
  129. return true;
  130. case WM_LBUTTONUP:
  131. io.MouseDown[0] = false;
  132. return true;
  133. case WM_RBUTTONDOWN:
  134. io.MouseDown[1] = true;
  135. return true;
  136. case WM_RBUTTONUP:
  137. io.MouseDown[1] = false;
  138. return true;
  139. case WM_MOUSEWHEEL:
  140. // Mouse wheel: -1,0,+1
  141. io.MouseWheel = GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1 : -1;
  142. return true;
  143. case WM_MOUSEMOVE:
  144. // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  145. io.MousePos.x = (signed short)(lParam);
  146. io.MousePos.y = (signed short)(lParam >> 16);
  147. return true;
  148. case WM_CHAR:
  149. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  150. if (wParam > 0 && wParam < 0x10000)
  151. io.AddInputCharacter((unsigned short)wParam);
  152. return true;
  153. case WM_DESTROY:
  154. Cleanup();
  155. PostQuitMessage(0);
  156. return 0;
  157. }
  158. return DefWindowProc(hWnd, msg, wParam, lParam);
  159. }
  160. // Notify OS Input Method Editor of text input position (e.g. when using Japanese/Chinese inputs, otherwise this isn't needed)
  161. static void ImImpl_ImeSetInputScreenPosFn(int x, int y)
  162. {
  163. if (HIMC himc = ImmGetContext(hWnd))
  164. {
  165. COMPOSITIONFORM cf;
  166. cf.ptCurrentPos.x = x;
  167. cf.ptCurrentPos.y = y;
  168. cf.dwStyle = CFS_FORCE_POSITION;
  169. ImmSetCompositionWindow(himc, &cf);
  170. }
  171. }
  172. void InitImGui()
  173. {
  174. RECT rect;
  175. GetClientRect(hWnd, &rect);
  176. ImGuiIO& io = ImGui::GetIO();
  177. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Display size, in pixels. For clamping windows positions.
  178. 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 timestep is variable)
  179. io.PixelCenterOffset = 0.0f; // Align Direct3D Texels
  180. 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.
  181. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  182. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  183. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  184. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  185. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  186. io.KeyMap[ImGuiKey_End] = VK_END;
  187. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  188. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  189. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  190. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  191. io.KeyMap[ImGuiKey_A] = 'A';
  192. io.KeyMap[ImGuiKey_C] = 'C';
  193. io.KeyMap[ImGuiKey_V] = 'V';
  194. io.KeyMap[ImGuiKey_X] = 'X';
  195. io.KeyMap[ImGuiKey_Y] = 'Y';
  196. io.KeyMap[ImGuiKey_Z] = 'Z';
  197. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  198. io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn;
  199. // Create the vertex buffer
  200. if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  201. {
  202. IM_ASSERT(0);
  203. return;
  204. }
  205. // Load font texture
  206. const void* png_data;
  207. unsigned int png_size;
  208. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  209. if (D3DXCreateTextureFromFileInMemory(g_pd3dDevice, png_data, png_size, &g_pTexture) < 0)
  210. {
  211. IM_ASSERT(0);
  212. return;
  213. }
  214. }
  215. INT64 ticks_per_second = 0;
  216. INT64 time = 0;
  217. void UpdateImGui()
  218. {
  219. ImGuiIO& io = ImGui::GetIO();
  220. // Setup timestep
  221. INT64 current_time;
  222. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  223. io.DeltaTime = (float)(current_time - time) / ticks_per_second;
  224. time = current_time;
  225. // Setup inputs
  226. // (we already got mouse position, buttons, wheel from the window message callback)
  227. BYTE keystate[256];
  228. GetKeyboardState(keystate);
  229. for (int i = 0; i < 256; i++)
  230. io.KeysDown[i] = (keystate[i] & 0x80) != 0;
  231. io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
  232. io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
  233. // io.MousePos : filled by WM_MOUSEMOVE event
  234. // io.MouseDown : filled by WM_*BUTTON* events
  235. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  236. // Start the frame
  237. ImGui::NewFrame();
  238. }
  239. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
  240. {
  241. // Register the window class
  242. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, L"ImGui Example", NULL };
  243. RegisterClassEx(&wc);
  244. // Create the application's window
  245. hWnd = CreateWindow(L"ImGui Example", L"ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  246. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  247. return 1;
  248. if (!QueryPerformanceCounter((LARGE_INTEGER *)&time))
  249. return 1;
  250. // Initialize Direct3D
  251. if (InitD3D(hWnd) < 0)
  252. {
  253. if (g_pVB)
  254. g_pVB->Release();
  255. UnregisterClass(L"ImGui Example", wc.hInstance);
  256. return 1;
  257. }
  258. // Show the window
  259. ShowWindow(hWnd, SW_SHOWDEFAULT);
  260. UpdateWindow(hWnd);
  261. InitImGui();
  262. // Enter the message loop
  263. MSG msg;
  264. ZeroMemory(&msg, sizeof(msg));
  265. while (msg.message != WM_QUIT)
  266. {
  267. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  268. {
  269. TranslateMessage(&msg);
  270. DispatchMessage(&msg);
  271. continue;
  272. }
  273. UpdateImGui();
  274. static bool show_test_window = true;
  275. static bool show_another_window = false;
  276. // 1. Show a simple window
  277. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  278. {
  279. static float f;
  280. ImGui::Text("Hello, world!");
  281. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  282. show_test_window ^= ImGui::Button("Test Window");
  283. show_another_window ^= ImGui::Button("Another Window");
  284. // Calculate and show framerate
  285. static float ms_per_frame[120] = { 0 };
  286. static int ms_per_frame_idx = 0;
  287. static float ms_per_frame_accum = 0.0f;
  288. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  289. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  290. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  291. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  292. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  293. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  294. }
  295. // 2. Show another simple window, this time using an explicit Begin/End pair
  296. if (show_another_window)
  297. {
  298. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  299. ImGui::Text("Hello");
  300. ImGui::End();
  301. }
  302. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  303. if (show_test_window)
  304. {
  305. ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  306. ImGui::ShowTestWindow(&show_test_window);
  307. }
  308. // Rendering
  309. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
  310. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
  311. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
  312. g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0);
  313. if (g_pd3dDevice->BeginScene() >= 0)
  314. {
  315. ImGui::Render();
  316. g_pd3dDevice->EndScene();
  317. }
  318. g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
  319. }
  320. ImGui::Shutdown();
  321. if (g_pVB)
  322. g_pVB->Release();
  323. UnregisterClass(L"ImGui Example", wc.hInstance);
  324. return 0;
  325. }