imgui_impl_dx9.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // ImGui Win32 + DirectX9 binding
  2. // https://github.com/ocornut/imgui
  3. #include <imgui.h>
  4. #include "imgui_impl_dx9.h"
  5. // DirectX
  6. #include <d3dx9.h>
  7. #define DIRECTINPUT_VERSION 0x0800
  8. #include <dinput.h>
  9. // Data
  10. static HWND g_hWnd = 0;
  11. static INT64 g_Time = 0;
  12. static INT64 g_TicksPerSecond = 0;
  13. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
  14. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL;
  15. static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL;
  16. static LPDIRECT3DTEXTURE9 g_FontTexture = NULL;
  17. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  18. struct CUSTOMVERTEX
  19. {
  20. D3DXVECTOR3 pos;
  21. D3DCOLOR col;
  22. D3DXVECTOR2 uv;
  23. };
  24. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  25. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  26. // If text or lines are blurry when integrating ImGui in your engine:
  27. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  28. static void ImGui_ImplDX9_RenderDrawLists(ImDrawData* draw_data)
  29. {
  30. // Grow buffers if needed
  31. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  32. {
  33. if (g_pVB) g_pVB->Release();
  34. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  35. if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  36. return;
  37. }
  38. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  39. {
  40. if (g_pIB) g_pIB->Release();
  41. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  42. if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0)
  43. return;
  44. }
  45. // Copy and convert all vertices into a single contiguous buffer
  46. CUSTOMVERTEX* vtx_dst;
  47. ImDrawIdx* idx_dst;
  48. if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  49. return;
  50. if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
  51. return;
  52. for (int n = 0; n < draw_data->CmdListsCount; n++)
  53. {
  54. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  55. const ImDrawVert* vtx_src = &cmd_list->VtxBuffer[0];
  56. for (int i = 0; i < cmd_list->VtxBuffer.size(); i++)
  57. {
  58. vtx_dst->pos.x = vtx_src->pos.x;
  59. vtx_dst->pos.y = vtx_src->pos.y;
  60. vtx_dst->pos.z = 0.0f;
  61. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  62. vtx_dst->uv.x = vtx_src->uv.x;
  63. vtx_dst->uv.y = vtx_src->uv.y;
  64. vtx_dst++;
  65. vtx_src++;
  66. }
  67. memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
  68. idx_dst += cmd_list->IdxBuffer.size();
  69. }
  70. g_pVB->Unlock();
  71. g_pIB->Unlock();
  72. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  73. g_pd3dDevice->SetIndices( g_pIB );
  74. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  75. // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing
  76. g_pd3dDevice->SetPixelShader( NULL );
  77. g_pd3dDevice->SetVertexShader( NULL );
  78. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  79. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  80. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  81. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  82. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  83. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  84. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  85. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  86. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  87. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
  88. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
  89. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  90. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  91. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  92. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
  93. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
  94. // Setup orthographic projection matrix
  95. D3DXMATRIXA16 mat;
  96. D3DXMatrixIdentity(&mat);
  97. g_pd3dDevice->SetTransform( D3DTS_WORLD, &mat );
  98. g_pd3dDevice->SetTransform( D3DTS_VIEW, &mat );
  99. D3DXMatrixOrthoOffCenterLH( &mat, 0.5f, ImGui::GetIO().DisplaySize.x+0.5f, ImGui::GetIO().DisplaySize.y+0.5f, 0.5f, -1.0f, +1.0f );
  100. g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &mat );
  101. // Render command lists
  102. int vtx_offset = 0;
  103. int idx_offset = 0;
  104. for (int n = 0; n < draw_data->CmdListsCount; n++)
  105. {
  106. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  107. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
  108. {
  109. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  110. if (pcmd->UserCallback)
  111. {
  112. pcmd->UserCallback(cmd_list, pcmd);
  113. }
  114. else
  115. {
  116. const RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  117. g_pd3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)pcmd->TextureId );
  118. g_pd3dDevice->SetScissorRect( &r );
  119. g_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.size(), idx_offset, pcmd->ElemCount/3 );
  120. }
  121. idx_offset += pcmd->ElemCount;
  122. }
  123. vtx_offset += cmd_list->VtxBuffer.size();
  124. }
  125. }
  126. LRESULT ImGui_ImplDX9_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  127. {
  128. ImGuiIO& io = ImGui::GetIO();
  129. switch (msg)
  130. {
  131. case WM_LBUTTONDOWN:
  132. io.MouseDown[0] = true;
  133. return true;
  134. case WM_LBUTTONUP:
  135. io.MouseDown[0] = false;
  136. return true;
  137. case WM_RBUTTONDOWN:
  138. io.MouseDown[1] = true;
  139. return true;
  140. case WM_RBUTTONUP:
  141. io.MouseDown[1] = false;
  142. return true;
  143. case WM_MOUSEWHEEL:
  144. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  145. return true;
  146. case WM_MOUSEMOVE:
  147. io.MousePos.x = (signed short)(lParam);
  148. io.MousePos.y = (signed short)(lParam >> 16);
  149. return true;
  150. case WM_KEYDOWN:
  151. if (wParam < 256)
  152. io.KeysDown[wParam] = 1;
  153. return true;
  154. case WM_KEYUP:
  155. if (wParam < 256)
  156. io.KeysDown[wParam] = 0;
  157. return true;
  158. case WM_CHAR:
  159. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  160. if (wParam > 0 && wParam < 0x10000)
  161. io.AddInputCharacter((unsigned short)wParam);
  162. return true;
  163. }
  164. return 0;
  165. }
  166. bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
  167. {
  168. g_hWnd = (HWND)hwnd;
  169. g_pd3dDevice = device;
  170. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  171. return false;
  172. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  173. return false;
  174. ImGuiIO& io = ImGui::GetIO();
  175. 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.
  176. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  177. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  178. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  179. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  180. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  181. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  182. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  183. io.KeyMap[ImGuiKey_End] = VK_END;
  184. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  185. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  186. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  187. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  188. io.KeyMap[ImGuiKey_A] = 'A';
  189. io.KeyMap[ImGuiKey_C] = 'C';
  190. io.KeyMap[ImGuiKey_V] = 'V';
  191. io.KeyMap[ImGuiKey_X] = 'X';
  192. io.KeyMap[ImGuiKey_Y] = 'Y';
  193. io.KeyMap[ImGuiKey_Z] = 'Z';
  194. io.RenderDrawListsFn = ImGui_ImplDX9_RenderDrawLists;
  195. io.ImeWindowHandle = g_hWnd;
  196. return true;
  197. }
  198. void ImGui_ImplDX9_Shutdown()
  199. {
  200. ImGui_ImplDX9_InvalidateDeviceObjects();
  201. ImGui::Shutdown();
  202. g_pd3dDevice = NULL;
  203. g_hWnd = 0;
  204. }
  205. static bool ImGui_ImplDX9_CreateFontsTexture()
  206. {
  207. ImGuiIO& io = ImGui::GetIO();
  208. // Build
  209. unsigned char* pixels;
  210. int width, height, bytes_per_pixel;
  211. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height, &bytes_per_pixel);
  212. // Create DX9 texture
  213. g_FontTexture = NULL;
  214. if (D3DXCreateTexture(g_pd3dDevice, width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &g_FontTexture) < 0)
  215. return false;
  216. D3DLOCKED_RECT tex_locked_rect;
  217. if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  218. return false;
  219. for (int y = 0; y < height; y++)
  220. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  221. g_FontTexture->UnlockRect(0);
  222. // Store our identifier
  223. io.Fonts->TexID = (void *)g_FontTexture;
  224. // Cleanup (don't clear the input data if you want to append new fonts later)
  225. io.Fonts->ClearInputData();
  226. io.Fonts->ClearTexData();
  227. return true;
  228. }
  229. bool ImGui_ImplDX9_CreateDeviceObjects()
  230. {
  231. if (!g_pd3dDevice)
  232. return false;
  233. if (!ImGui_ImplDX9_CreateFontsTexture())
  234. return false;
  235. return true;
  236. }
  237. void ImGui_ImplDX9_InvalidateDeviceObjects()
  238. {
  239. if (!g_pd3dDevice)
  240. return;
  241. if (g_pVB)
  242. {
  243. g_pVB->Release();
  244. g_pVB = NULL;
  245. }
  246. if (g_pIB)
  247. {
  248. g_pIB->Release();
  249. g_pIB = NULL;
  250. }
  251. if (LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)ImGui::GetIO().Fonts->TexID)
  252. {
  253. tex->Release();
  254. ImGui::GetIO().Fonts->TexID = 0;
  255. }
  256. }
  257. void ImGui_ImplDX9_NewFrame()
  258. {
  259. if (!g_FontTexture)
  260. ImGui_ImplDX9_CreateDeviceObjects();
  261. ImGuiIO& io = ImGui::GetIO();
  262. // Setup display size (every frame to accommodate for window resizing)
  263. RECT rect;
  264. GetClientRect(g_hWnd, &rect);
  265. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  266. // Setup time step
  267. INT64 current_time;
  268. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  269. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  270. g_Time = current_time;
  271. // Read keyboard modifiers inputs
  272. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  273. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  274. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  275. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  276. // io.MousePos : filled by WM_MOUSEMOVE events
  277. // io.MouseDown : filled by WM_*BUTTON* events
  278. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  279. // Hide OS mouse cursor if ImGui is drawing it
  280. SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));
  281. // Start the frame
  282. ImGui::NewFrame();
  283. }