imgui_impl_dx9.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 int VERTEX_BUFFER_SIZE = 30000; // TODO: Make buffers smaller and grow dynamically as needed.
  17. static int INDEX_BUFFER_SIZE = 30000; // TODO: Make buffers smaller and grow dynamically as needed.
  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(ImDrawList** const cmd_lists, int cmd_lists_count)
  29. {
  30. size_t total_vtx_count = 0;
  31. size_t total_idx_count = 0;
  32. for (int n = 0; n < cmd_lists_count; n++)
  33. {
  34. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  35. total_idx_count += cmd_lists[n]->idx_buffer.size();
  36. }
  37. if (total_vtx_count == 0)
  38. return;
  39. // Copy and convert all vertices into a single contiguous buffer
  40. CUSTOMVERTEX* vtx_dst;
  41. ImDrawIdx* idx_dst;
  42. if (g_pVB->Lock(0, (UINT)total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  43. return;
  44. if (g_pIB->Lock(0, (UINT)total_idx_count, (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
  45. return;
  46. for (int n = 0; n < cmd_lists_count; n++)
  47. {
  48. const ImDrawList* cmd_list = cmd_lists[n];
  49. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  50. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  51. {
  52. vtx_dst->pos.x = vtx_src->pos.x;
  53. vtx_dst->pos.y = vtx_src->pos.y;
  54. vtx_dst->pos.z = 0.0f;
  55. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  56. vtx_dst->uv.x = vtx_src->uv.x;
  57. vtx_dst->uv.y = vtx_src->uv.y;
  58. vtx_dst++;
  59. vtx_src++;
  60. }
  61. memcpy(idx_dst, &cmd_list->idx_buffer[0], cmd_list->idx_buffer.size() * sizeof(ImDrawIdx));
  62. idx_dst += cmd_list->idx_buffer.size();
  63. }
  64. g_pVB->Unlock();
  65. g_pIB->Unlock();
  66. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  67. g_pd3dDevice->SetIndices( g_pIB );
  68. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  69. // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing
  70. g_pd3dDevice->SetPixelShader( NULL );
  71. g_pd3dDevice->SetVertexShader( NULL );
  72. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  73. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  74. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  75. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  76. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  77. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  78. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  79. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  80. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  81. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
  82. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
  83. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  84. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  85. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  86. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
  87. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
  88. // Setup orthographic projection matrix
  89. D3DXMATRIXA16 mat;
  90. D3DXMatrixIdentity(&mat);
  91. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat);
  92. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat);
  93. D3DXMatrixOrthoOffCenterLH(&mat, 0.5f, ImGui::GetIO().DisplaySize.x+0.5f, ImGui::GetIO().DisplaySize.y+0.5f, 0.5f, -1.0f, +1.0f);
  94. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat);
  95. // Render command lists
  96. int vtx_offset = 0;
  97. int idx_offset = 0;
  98. for (int n = 0; n < cmd_lists_count; n++)
  99. {
  100. const ImDrawList* cmd_list = cmd_lists[n];
  101. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  102. {
  103. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  104. if (pcmd->user_callback)
  105. {
  106. pcmd->user_callback(cmd_list, pcmd);
  107. }
  108. else
  109. {
  110. const RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
  111. g_pd3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)pcmd->texture_id );
  112. g_pd3dDevice->SetScissorRect(&r);
  113. g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->vtx_buffer.size(), idx_offset, pcmd->idx_count/3);
  114. }
  115. idx_offset += pcmd->idx_count;
  116. }
  117. vtx_offset += (int)cmd_list->vtx_buffer.size();
  118. }
  119. }
  120. LRESULT ImGui_ImplDX9_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  121. {
  122. ImGuiIO& io = ImGui::GetIO();
  123. switch (msg)
  124. {
  125. case WM_LBUTTONDOWN:
  126. io.MouseDown[0] = true;
  127. return true;
  128. case WM_LBUTTONUP:
  129. io.MouseDown[0] = false;
  130. return true;
  131. case WM_RBUTTONDOWN:
  132. io.MouseDown[1] = true;
  133. return true;
  134. case WM_RBUTTONUP:
  135. io.MouseDown[1] = false;
  136. return true;
  137. case WM_MOUSEWHEEL:
  138. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  139. return true;
  140. case WM_MOUSEMOVE:
  141. io.MousePos.x = (signed short)(lParam);
  142. io.MousePos.y = (signed short)(lParam >> 16);
  143. return true;
  144. case WM_KEYDOWN:
  145. if (wParam < 256)
  146. io.KeysDown[wParam] = 1;
  147. return true;
  148. case WM_KEYUP:
  149. if (wParam < 256)
  150. io.KeysDown[wParam] = 0;
  151. return true;
  152. case WM_CHAR:
  153. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  154. if (wParam > 0 && wParam < 0x10000)
  155. io.AddInputCharacter((unsigned short)wParam);
  156. return true;
  157. }
  158. return 0;
  159. }
  160. bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
  161. {
  162. g_hWnd = (HWND)hwnd;
  163. g_pd3dDevice = device;
  164. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  165. return false;
  166. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  167. return false;
  168. ImGuiIO& io = ImGui::GetIO();
  169. 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.
  170. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  171. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  172. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  173. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  174. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  175. io.KeyMap[ImGuiKey_End] = VK_END;
  176. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  177. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  178. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  179. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  180. io.KeyMap[ImGuiKey_A] = 'A';
  181. io.KeyMap[ImGuiKey_C] = 'C';
  182. io.KeyMap[ImGuiKey_V] = 'V';
  183. io.KeyMap[ImGuiKey_X] = 'X';
  184. io.KeyMap[ImGuiKey_Y] = 'Y';
  185. io.KeyMap[ImGuiKey_Z] = 'Z';
  186. io.RenderDrawListsFn = ImGui_ImplDX9_RenderDrawLists;
  187. io.ImeWindowHandle = g_hWnd;
  188. return true;
  189. }
  190. void ImGui_ImplDX9_Shutdown()
  191. {
  192. ImGui_ImplDX9_InvalidateDeviceObjects();
  193. ImGui::Shutdown();
  194. g_pd3dDevice = NULL;
  195. g_hWnd = 0;
  196. }
  197. static void ImGui_ImplDX9_CreateFontsTexture()
  198. {
  199. ImGuiIO& io = ImGui::GetIO();
  200. // Build
  201. unsigned char* pixels;
  202. int width, height, bytes_per_pixel;
  203. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height, &bytes_per_pixel);
  204. // Create DX9 texture
  205. LPDIRECT3DTEXTURE9 pTexture = NULL;
  206. if (D3DXCreateTexture(g_pd3dDevice, width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &pTexture) < 0)
  207. {
  208. IM_ASSERT(0);
  209. return;
  210. }
  211. D3DLOCKED_RECT tex_locked_rect;
  212. if (pTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  213. {
  214. IM_ASSERT(0);
  215. return;
  216. }
  217. for (int y = 0; y < height; y++)
  218. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  219. pTexture->UnlockRect(0);
  220. // Store our identifier
  221. io.Fonts->TexID = (void *)pTexture;
  222. // Cleanup (don't clear the input data if you want to append new fonts later)
  223. io.Fonts->ClearInputData();
  224. io.Fonts->ClearTexData();
  225. }
  226. bool ImGui_ImplDX9_CreateDeviceObjects()
  227. {
  228. if (!g_pd3dDevice)
  229. return false;
  230. if (g_pd3dDevice->CreateVertexBuffer(VERTEX_BUFFER_SIZE * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  231. return false;
  232. if (g_pd3dDevice->CreateIndexBuffer(INDEX_BUFFER_SIZE * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0)
  233. return false;
  234. ImGui_ImplDX9_CreateFontsTexture();
  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_pVB)
  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. }