imgui_impl_dx9.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // ImGui Win32 + DirectX9 binding
  2. // Implemented features:
  3. // [X] User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  4. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  5. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  6. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  7. // https://github.com/ocornut/imgui
  8. #include "imgui.h"
  9. #include "imgui_impl_dx9.h"
  10. // DirectX
  11. #include <d3d9.h>
  12. #define DIRECTINPUT_VERSION 0x0800
  13. #include <dinput.h>
  14. // Data
  15. static HWND g_hWnd = 0;
  16. static INT64 g_Time = 0;
  17. static INT64 g_TicksPerSecond = 0;
  18. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
  19. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL;
  20. static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL;
  21. static LPDIRECT3DTEXTURE9 g_FontTexture = NULL;
  22. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  23. struct CUSTOMVERTEX
  24. {
  25. float pos[3];
  26. D3DCOLOR col;
  27. float uv[2];
  28. };
  29. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  30. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  31. // If text or lines are blurry when integrating ImGui in your engine:
  32. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  33. void ImGui_ImplDX9_RenderDrawLists(ImDrawData* draw_data)
  34. {
  35. // Avoid rendering when minimized
  36. ImGuiIO& io = ImGui::GetIO();
  37. if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f)
  38. return;
  39. // Create and grow buffers if needed
  40. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  41. {
  42. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  43. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  44. if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  45. return;
  46. }
  47. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  48. {
  49. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  50. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  51. if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0)
  52. return;
  53. }
  54. // Backup the DX9 state
  55. IDirect3DStateBlock9* d3d9_state_block = NULL;
  56. if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
  57. return;
  58. // Copy and convert all vertices into a single contiguous buffer
  59. CUSTOMVERTEX* vtx_dst;
  60. ImDrawIdx* idx_dst;
  61. if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  62. return;
  63. if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
  64. return;
  65. for (int n = 0; n < draw_data->CmdListsCount; n++)
  66. {
  67. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  68. const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
  69. for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
  70. {
  71. vtx_dst->pos[0] = vtx_src->pos.x;
  72. vtx_dst->pos[1] = vtx_src->pos.y;
  73. vtx_dst->pos[2] = 0.0f;
  74. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  75. vtx_dst->uv[0] = vtx_src->uv.x;
  76. vtx_dst->uv[1] = vtx_src->uv.y;
  77. vtx_dst++;
  78. vtx_src++;
  79. }
  80. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  81. idx_dst += cmd_list->IdxBuffer.Size;
  82. }
  83. g_pVB->Unlock();
  84. g_pIB->Unlock();
  85. g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
  86. g_pd3dDevice->SetIndices(g_pIB);
  87. g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
  88. // Setup viewport
  89. D3DVIEWPORT9 vp;
  90. vp.X = vp.Y = 0;
  91. vp.Width = (DWORD)io.DisplaySize.x;
  92. vp.Height = (DWORD)io.DisplaySize.y;
  93. vp.MinZ = 0.0f;
  94. vp.MaxZ = 1.0f;
  95. g_pd3dDevice->SetViewport(&vp);
  96. // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing
  97. g_pd3dDevice->SetPixelShader(NULL);
  98. g_pd3dDevice->SetVertexShader(NULL);
  99. g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
  100. g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false);
  101. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
  102. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
  103. g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false);
  104. g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
  105. g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
  106. g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
  107. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true);
  108. g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
  109. g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
  110. g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
  111. g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
  112. g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
  113. g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
  114. g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
  115. g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
  116. // Setup orthographic projection matrix
  117. // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
  118. {
  119. const float L = 0.5f, R = io.DisplaySize.x+0.5f, T = 0.5f, B = io.DisplaySize.y+0.5f;
  120. D3DMATRIX mat_identity = { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } };
  121. D3DMATRIX mat_projection =
  122. {
  123. 2.0f/(R-L), 0.0f, 0.0f, 0.0f,
  124. 0.0f, 2.0f/(T-B), 0.0f, 0.0f,
  125. 0.0f, 0.0f, 0.5f, 0.0f,
  126. (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f,
  127. };
  128. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
  129. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
  130. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
  131. }
  132. // Render command lists
  133. int vtx_offset = 0;
  134. int idx_offset = 0;
  135. for (int n = 0; n < draw_data->CmdListsCount; n++)
  136. {
  137. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  138. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  139. {
  140. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  141. if (pcmd->UserCallback)
  142. {
  143. pcmd->UserCallback(cmd_list, pcmd);
  144. }
  145. else
  146. {
  147. const RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  148. g_pd3dDevice->SetTexture(0, (LPDIRECT3DTEXTURE9)pcmd->TextureId);
  149. g_pd3dDevice->SetScissorRect(&r);
  150. g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, idx_offset, pcmd->ElemCount/3);
  151. }
  152. idx_offset += pcmd->ElemCount;
  153. }
  154. vtx_offset += cmd_list->VtxBuffer.Size;
  155. }
  156. // Restore the DX9 state
  157. d3d9_state_block->Apply();
  158. d3d9_state_block->Release();
  159. }
  160. static bool IsAnyMouseButtonDown()
  161. {
  162. ImGuiIO& io = ImGui::GetIO();
  163. for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
  164. if (io.MouseDown[n])
  165. return true;
  166. return false;
  167. }
  168. // Process Win32 mouse/keyboard inputs.
  169. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  170. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  171. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  172. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  173. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
  174. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
  175. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  176. {
  177. ImGuiIO& io = ImGui::GetIO();
  178. switch (msg)
  179. {
  180. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  181. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  182. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  183. {
  184. int button = 0;
  185. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  186. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  187. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  188. if (!IsAnyMouseButtonDown() && GetCapture() == NULL)
  189. SetCapture(hwnd);
  190. io.MouseDown[button] = true;
  191. return 0;
  192. }
  193. case WM_LBUTTONUP:
  194. case WM_RBUTTONUP:
  195. case WM_MBUTTONUP:
  196. {
  197. int button = 0;
  198. if (msg == WM_LBUTTONUP) button = 0;
  199. if (msg == WM_RBUTTONUP) button = 1;
  200. if (msg == WM_MBUTTONUP) button = 2;
  201. io.MouseDown[button] = false;
  202. if (!IsAnyMouseButtonDown() && GetCapture() == hwnd)
  203. ReleaseCapture();
  204. return 0;
  205. }
  206. case WM_MOUSEWHEEL:
  207. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  208. return 0;
  209. case WM_MOUSEHWHEEL:
  210. io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  211. return 0;
  212. case WM_MOUSEMOVE:
  213. io.MousePos.x = (signed short)(lParam);
  214. io.MousePos.y = (signed short)(lParam >> 16);
  215. return 0;
  216. case WM_KEYDOWN:
  217. case WM_SYSKEYDOWN:
  218. if (wParam < 256)
  219. io.KeysDown[wParam] = 1;
  220. return 0;
  221. case WM_KEYUP:
  222. case WM_SYSKEYUP:
  223. if (wParam < 256)
  224. io.KeysDown[wParam] = 0;
  225. return 0;
  226. case WM_CHAR:
  227. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  228. if (wParam > 0 && wParam < 0x10000)
  229. io.AddInputCharacter((unsigned short)wParam);
  230. return 0;
  231. }
  232. return 0;
  233. }
  234. bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
  235. {
  236. g_hWnd = (HWND)hwnd;
  237. g_pd3dDevice = device;
  238. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  239. return false;
  240. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  241. return false;
  242. ImGuiIO& io = ImGui::GetIO();
  243. 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.
  244. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  245. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  246. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  247. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  248. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  249. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  250. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  251. io.KeyMap[ImGuiKey_End] = VK_END;
  252. io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
  253. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  254. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  255. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  256. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  257. io.KeyMap[ImGuiKey_A] = 'A';
  258. io.KeyMap[ImGuiKey_C] = 'C';
  259. io.KeyMap[ImGuiKey_V] = 'V';
  260. io.KeyMap[ImGuiKey_X] = 'X';
  261. io.KeyMap[ImGuiKey_Y] = 'Y';
  262. io.KeyMap[ImGuiKey_Z] = 'Z';
  263. io.RenderDrawListsFn = ImGui_ImplDX9_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  264. io.ImeWindowHandle = g_hWnd;
  265. return true;
  266. }
  267. void ImGui_ImplDX9_Shutdown()
  268. {
  269. ImGui_ImplDX9_InvalidateDeviceObjects();
  270. ImGui::Shutdown();
  271. g_pd3dDevice = NULL;
  272. g_hWnd = 0;
  273. }
  274. static bool ImGui_ImplDX9_CreateFontsTexture()
  275. {
  276. // Build texture atlas
  277. ImGuiIO& io = ImGui::GetIO();
  278. unsigned char* pixels;
  279. int width, height, bytes_per_pixel;
  280. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
  281. // Upload texture to graphics system
  282. g_FontTexture = NULL;
  283. if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0)
  284. return false;
  285. D3DLOCKED_RECT tex_locked_rect;
  286. if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  287. return false;
  288. for (int y = 0; y < height; y++)
  289. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  290. g_FontTexture->UnlockRect(0);
  291. // Store our identifier
  292. io.Fonts->TexID = (void *)g_FontTexture;
  293. return true;
  294. }
  295. bool ImGui_ImplDX9_CreateDeviceObjects()
  296. {
  297. if (!g_pd3dDevice)
  298. return false;
  299. if (!ImGui_ImplDX9_CreateFontsTexture())
  300. return false;
  301. return true;
  302. }
  303. void ImGui_ImplDX9_InvalidateDeviceObjects()
  304. {
  305. if (!g_pd3dDevice)
  306. return;
  307. if (g_pVB)
  308. {
  309. g_pVB->Release();
  310. g_pVB = NULL;
  311. }
  312. if (g_pIB)
  313. {
  314. g_pIB->Release();
  315. g_pIB = NULL;
  316. }
  317. // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both.
  318. ImGuiIO& io = ImGui::GetIO();
  319. IM_ASSERT(g_FontTexture == io.Fonts->TexID);
  320. if (g_FontTexture)
  321. g_FontTexture->Release();
  322. g_FontTexture = NULL;
  323. io.Fonts->TexID = NULL;
  324. }
  325. void ImGui_ImplDX9_NewFrame()
  326. {
  327. if (!g_FontTexture)
  328. ImGui_ImplDX9_CreateDeviceObjects();
  329. ImGuiIO& io = ImGui::GetIO();
  330. // Setup display size (every frame to accommodate for window resizing)
  331. RECT rect;
  332. GetClientRect(g_hWnd, &rect);
  333. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  334. // Setup time step
  335. INT64 current_time;
  336. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  337. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  338. g_Time = current_time;
  339. // Read keyboard modifiers inputs
  340. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  341. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  342. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  343. io.KeySuper = false;
  344. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  345. // io.MousePos : filled by WM_MOUSEMOVE events
  346. // io.MouseDown : filled by WM_*BUTTON* events
  347. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  348. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  349. if (io.WantMoveMouse)
  350. {
  351. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  352. ClientToScreen(g_hWnd, &pos);
  353. SetCursorPos(pos.x, pos.y);
  354. }
  355. // Hide OS mouse cursor if ImGui is drawing it
  356. if (io.MouseDrawCursor)
  357. SetCursor(NULL);
  358. // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
  359. ImGui::NewFrame();
  360. }