imgui_impl_dx11.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // ImGui Win32 + DirectX11 binding
  2. // Implemented features:
  3. // [X] User texture binding. Use 'ID3D11ShaderResourceView*' 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. // CHANGELOG
  9. // (minor and older changes stripped away, please see git history for details)
  10. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  11. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
  12. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
  13. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  14. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  15. // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavEnableSetMousePos is set).
  16. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  17. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
  18. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
  19. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
  20. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
  21. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set.
  22. // 2016-05-07: DirectX11: Disabling depth-write.
  23. #include "imgui.h"
  24. #include "imgui_impl_dx11.h"
  25. // DirectX
  26. #include <d3d11.h>
  27. #include <d3dcompiler.h>
  28. #define DIRECTINPUT_VERSION 0x0800
  29. #include <dinput.h>
  30. // Win32 data
  31. static HWND g_hWnd = 0;
  32. static INT64 g_Time = 0;
  33. static INT64 g_TicksPerSecond = 0;
  34. static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT;
  35. // DirectX data
  36. static ID3D11Device* g_pd3dDevice = NULL;
  37. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  38. static ID3D11Buffer* g_pVB = NULL;
  39. static ID3D11Buffer* g_pIB = NULL;
  40. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  41. static ID3D11VertexShader* g_pVertexShader = NULL;
  42. static ID3D11InputLayout* g_pInputLayout = NULL;
  43. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  44. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  45. static ID3D11PixelShader* g_pPixelShader = NULL;
  46. static ID3D11SamplerState* g_pFontSampler = NULL;
  47. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  48. static ID3D11RasterizerState* g_pRasterizerState = NULL;
  49. static ID3D11BlendState* g_pBlendState = NULL;
  50. static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
  51. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  52. struct VERTEX_CONSTANT_BUFFER
  53. {
  54. float mvp[4][4];
  55. };
  56. // Render function
  57. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  58. void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
  59. {
  60. ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
  61. // Create and grow vertex/index buffers if needed
  62. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  63. {
  64. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  65. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  66. D3D11_BUFFER_DESC desc;
  67. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  68. desc.Usage = D3D11_USAGE_DYNAMIC;
  69. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  70. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  71. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  72. desc.MiscFlags = 0;
  73. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  74. return;
  75. }
  76. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  77. {
  78. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  79. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  80. D3D11_BUFFER_DESC desc;
  81. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  82. desc.Usage = D3D11_USAGE_DYNAMIC;
  83. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  84. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  85. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  86. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  87. return;
  88. }
  89. // Copy and convert all vertices into a single contiguous buffer
  90. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  91. if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  92. return;
  93. if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  94. return;
  95. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  96. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  97. for (int n = 0; n < draw_data->CmdListsCount; n++)
  98. {
  99. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  100. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  101. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  102. vtx_dst += cmd_list->VtxBuffer.Size;
  103. idx_dst += cmd_list->IdxBuffer.Size;
  104. }
  105. ctx->Unmap(g_pVB, 0);
  106. ctx->Unmap(g_pIB, 0);
  107. // Setup orthographic projection matrix into our constant buffer
  108. {
  109. D3D11_MAPPED_SUBRESOURCE mapped_resource;
  110. if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  111. return;
  112. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
  113. float L = 0.0f;
  114. float R = ImGui::GetIO().DisplaySize.x;
  115. float B = ImGui::GetIO().DisplaySize.y;
  116. float T = 0.0f;
  117. float mvp[4][4] =
  118. {
  119. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  120. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  121. { 0.0f, 0.0f, 0.5f, 0.0f },
  122. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  123. };
  124. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  125. ctx->Unmap(g_pVertexConstantBuffer, 0);
  126. }
  127. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  128. struct BACKUP_DX11_STATE
  129. {
  130. UINT ScissorRectsCount, ViewportsCount;
  131. D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  132. D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  133. ID3D11RasterizerState* RS;
  134. ID3D11BlendState* BlendState;
  135. FLOAT BlendFactor[4];
  136. UINT SampleMask;
  137. UINT StencilRef;
  138. ID3D11DepthStencilState* DepthStencilState;
  139. ID3D11ShaderResourceView* PSShaderResource;
  140. ID3D11SamplerState* PSSampler;
  141. ID3D11PixelShader* PS;
  142. ID3D11VertexShader* VS;
  143. UINT PSInstancesCount, VSInstancesCount;
  144. ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
  145. D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  146. ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  147. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  148. DXGI_FORMAT IndexBufferFormat;
  149. ID3D11InputLayout* InputLayout;
  150. };
  151. BACKUP_DX11_STATE old;
  152. old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  153. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  154. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  155. ctx->RSGetState(&old.RS);
  156. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  157. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  158. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  159. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  160. old.PSInstancesCount = old.VSInstancesCount = 256;
  161. ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
  162. ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
  163. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  164. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  165. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  166. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  167. ctx->IAGetInputLayout(&old.InputLayout);
  168. // Setup viewport
  169. D3D11_VIEWPORT vp;
  170. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  171. vp.Width = ImGui::GetIO().DisplaySize.x;
  172. vp.Height = ImGui::GetIO().DisplaySize.y;
  173. vp.MinDepth = 0.0f;
  174. vp.MaxDepth = 1.0f;
  175. vp.TopLeftX = vp.TopLeftY = 0.0f;
  176. ctx->RSSetViewports(1, &vp);
  177. // Bind shader and vertex buffers
  178. unsigned int stride = sizeof(ImDrawVert);
  179. unsigned int offset = 0;
  180. ctx->IASetInputLayout(g_pInputLayout);
  181. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  182. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  183. ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  184. ctx->VSSetShader(g_pVertexShader, NULL, 0);
  185. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  186. ctx->PSSetShader(g_pPixelShader, NULL, 0);
  187. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  188. // Setup render state
  189. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  190. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  191. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  192. ctx->RSSetState(g_pRasterizerState);
  193. // Render command lists
  194. int vtx_offset = 0;
  195. int idx_offset = 0;
  196. for (int n = 0; n < draw_data->CmdListsCount; n++)
  197. {
  198. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  199. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  200. {
  201. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  202. if (pcmd->UserCallback)
  203. {
  204. pcmd->UserCallback(cmd_list, pcmd);
  205. }
  206. else
  207. {
  208. const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  209. ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
  210. ctx->RSSetScissorRects(1, &r);
  211. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  212. }
  213. idx_offset += pcmd->ElemCount;
  214. }
  215. vtx_offset += cmd_list->VtxBuffer.Size;
  216. }
  217. // Restore modified DX state
  218. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  219. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  220. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  221. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  222. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  223. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  224. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  225. ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
  226. for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
  227. ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
  228. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  229. for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
  230. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  231. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  232. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  233. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  234. }
  235. static bool ImGui_ImplWin32_UpdateMouseCursor()
  236. {
  237. ImGuiIO& io = ImGui::GetIO();
  238. if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
  239. return false;
  240. ImGuiMouseCursor imgui_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  241. if (imgui_cursor == ImGuiMouseCursor_None)
  242. {
  243. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  244. ::SetCursor(NULL);
  245. }
  246. else
  247. {
  248. // Hardware cursor type
  249. LPTSTR win32_cursor = IDC_ARROW;
  250. switch (imgui_cursor)
  251. {
  252. case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
  253. case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
  254. case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
  255. case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
  256. case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
  257. case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
  258. case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
  259. }
  260. ::SetCursor(::LoadCursor(NULL, win32_cursor));
  261. }
  262. return true;
  263. }
  264. // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
  265. #ifndef WM_MOUSEHWHEEL
  266. #define WM_MOUSEHWHEEL 0x020E
  267. #endif
  268. // Process Win32 mouse/keyboard inputs.
  269. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  270. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  271. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  272. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  273. // 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.
  274. // 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.
  275. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  276. {
  277. if (ImGui::GetCurrentContext() == NULL)
  278. return 0;
  279. ImGuiIO& io = ImGui::GetIO();
  280. switch (msg)
  281. {
  282. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  283. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  284. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  285. {
  286. int button = 0;
  287. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  288. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  289. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  290. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
  291. ::SetCapture(hwnd);
  292. io.MouseDown[button] = true;
  293. return 0;
  294. }
  295. case WM_LBUTTONUP:
  296. case WM_RBUTTONUP:
  297. case WM_MBUTTONUP:
  298. {
  299. int button = 0;
  300. if (msg == WM_LBUTTONUP) button = 0;
  301. if (msg == WM_RBUTTONUP) button = 1;
  302. if (msg == WM_MBUTTONUP) button = 2;
  303. io.MouseDown[button] = false;
  304. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
  305. ::ReleaseCapture();
  306. return 0;
  307. }
  308. case WM_MOUSEWHEEL:
  309. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  310. return 0;
  311. case WM_MOUSEHWHEEL:
  312. io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  313. return 0;
  314. case WM_MOUSEMOVE:
  315. io.MousePos.x = (signed short)(lParam);
  316. io.MousePos.y = (signed short)(lParam >> 16);
  317. return 0;
  318. case WM_KEYDOWN:
  319. case WM_SYSKEYDOWN:
  320. if (wParam < 256)
  321. io.KeysDown[wParam] = 1;
  322. return 0;
  323. case WM_KEYUP:
  324. case WM_SYSKEYUP:
  325. if (wParam < 256)
  326. io.KeysDown[wParam] = 0;
  327. return 0;
  328. case WM_CHAR:
  329. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  330. if (wParam > 0 && wParam < 0x10000)
  331. io.AddInputCharacter((unsigned short)wParam);
  332. return 0;
  333. case WM_SETCURSOR:
  334. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
  335. return 1;
  336. return 0;
  337. }
  338. return 0;
  339. }
  340. static void ImGui_ImplDX11_CreateFontsTexture()
  341. {
  342. // Build texture atlas
  343. ImGuiIO& io = ImGui::GetIO();
  344. unsigned char* pixels;
  345. int width, height;
  346. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  347. // Upload texture to graphics system
  348. {
  349. D3D11_TEXTURE2D_DESC desc;
  350. ZeroMemory(&desc, sizeof(desc));
  351. desc.Width = width;
  352. desc.Height = height;
  353. desc.MipLevels = 1;
  354. desc.ArraySize = 1;
  355. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  356. desc.SampleDesc.Count = 1;
  357. desc.Usage = D3D11_USAGE_DEFAULT;
  358. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  359. desc.CPUAccessFlags = 0;
  360. ID3D11Texture2D *pTexture = NULL;
  361. D3D11_SUBRESOURCE_DATA subResource;
  362. subResource.pSysMem = pixels;
  363. subResource.SysMemPitch = desc.Width * 4;
  364. subResource.SysMemSlicePitch = 0;
  365. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  366. // Create texture view
  367. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  368. ZeroMemory(&srvDesc, sizeof(srvDesc));
  369. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  370. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  371. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  372. srvDesc.Texture2D.MostDetailedMip = 0;
  373. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  374. pTexture->Release();
  375. }
  376. // Store our identifier
  377. io.Fonts->TexID = (void *)g_pFontTextureView;
  378. // Create texture sampler
  379. {
  380. D3D11_SAMPLER_DESC desc;
  381. ZeroMemory(&desc, sizeof(desc));
  382. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  383. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  384. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  385. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  386. desc.MipLODBias = 0.f;
  387. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  388. desc.MinLOD = 0.f;
  389. desc.MaxLOD = 0.f;
  390. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  391. }
  392. }
  393. bool ImGui_ImplDX11_CreateDeviceObjects()
  394. {
  395. if (!g_pd3dDevice)
  396. return false;
  397. if (g_pFontSampler)
  398. ImGui_ImplDX11_InvalidateDeviceObjects();
  399. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  400. // If you would like to use this DX11 sample code but remove this dependency you can:
  401. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  402. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  403. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  404. // Create the vertex shader
  405. {
  406. static const char* vertexShader =
  407. "cbuffer vertexBuffer : register(b0) \
  408. {\
  409. float4x4 ProjectionMatrix; \
  410. };\
  411. struct VS_INPUT\
  412. {\
  413. float2 pos : POSITION;\
  414. float4 col : COLOR0;\
  415. float2 uv : TEXCOORD0;\
  416. };\
  417. \
  418. struct PS_INPUT\
  419. {\
  420. float4 pos : SV_POSITION;\
  421. float4 col : COLOR0;\
  422. float2 uv : TEXCOORD0;\
  423. };\
  424. \
  425. PS_INPUT main(VS_INPUT input)\
  426. {\
  427. PS_INPUT output;\
  428. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  429. output.col = input.col;\
  430. output.uv = input.uv;\
  431. return output;\
  432. }";
  433. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  434. if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  435. return false;
  436. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  437. return false;
  438. // Create the input layout
  439. D3D11_INPUT_ELEMENT_DESC local_layout[] = {
  440. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  441. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  442. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  443. };
  444. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  445. return false;
  446. // Create the constant buffer
  447. {
  448. D3D11_BUFFER_DESC desc;
  449. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  450. desc.Usage = D3D11_USAGE_DYNAMIC;
  451. desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  452. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  453. desc.MiscFlags = 0;
  454. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  455. }
  456. }
  457. // Create the pixel shader
  458. {
  459. static const char* pixelShader =
  460. "struct PS_INPUT\
  461. {\
  462. float4 pos : SV_POSITION;\
  463. float4 col : COLOR0;\
  464. float2 uv : TEXCOORD0;\
  465. };\
  466. sampler sampler0;\
  467. Texture2D texture0;\
  468. \
  469. float4 main(PS_INPUT input) : SV_Target\
  470. {\
  471. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  472. return out_col; \
  473. }";
  474. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  475. if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  476. return false;
  477. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  478. return false;
  479. }
  480. // Create the blending setup
  481. {
  482. D3D11_BLEND_DESC desc;
  483. ZeroMemory(&desc, sizeof(desc));
  484. desc.AlphaToCoverageEnable = false;
  485. desc.RenderTarget[0].BlendEnable = true;
  486. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  487. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  488. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  489. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  490. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  491. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  492. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  493. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  494. }
  495. // Create the rasterizer state
  496. {
  497. D3D11_RASTERIZER_DESC desc;
  498. ZeroMemory(&desc, sizeof(desc));
  499. desc.FillMode = D3D11_FILL_SOLID;
  500. desc.CullMode = D3D11_CULL_NONE;
  501. desc.ScissorEnable = true;
  502. desc.DepthClipEnable = true;
  503. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  504. }
  505. // Create depth-stencil State
  506. {
  507. D3D11_DEPTH_STENCIL_DESC desc;
  508. ZeroMemory(&desc, sizeof(desc));
  509. desc.DepthEnable = false;
  510. desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  511. desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
  512. desc.StencilEnable = false;
  513. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  514. desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  515. desc.BackFace = desc.FrontFace;
  516. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  517. }
  518. ImGui_ImplDX11_CreateFontsTexture();
  519. return true;
  520. }
  521. void ImGui_ImplDX11_InvalidateDeviceObjects()
  522. {
  523. if (!g_pd3dDevice)
  524. return;
  525. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  526. if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
  527. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  528. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  529. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  530. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  531. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  532. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  533. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  534. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  535. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  536. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  537. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  538. }
  539. bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context)
  540. {
  541. g_hWnd = (HWND)hwnd;
  542. g_pd3dDevice = device;
  543. g_pd3dDeviceContext = device_context;
  544. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  545. return false;
  546. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  547. return false;
  548. // Setup back-end capabilities flags
  549. ImGuiIO& io = ImGui::GetIO();
  550. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  551. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  552. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime.
  553. io.KeyMap[ImGuiKey_Tab] = VK_TAB;
  554. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  555. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  556. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  557. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  558. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  559. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  560. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  561. io.KeyMap[ImGuiKey_End] = VK_END;
  562. io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
  563. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  564. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  565. io.KeyMap[ImGuiKey_Space] = VK_SPACE;
  566. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  567. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  568. io.KeyMap[ImGuiKey_A] = 'A';
  569. io.KeyMap[ImGuiKey_C] = 'C';
  570. io.KeyMap[ImGuiKey_V] = 'V';
  571. io.KeyMap[ImGuiKey_X] = 'X';
  572. io.KeyMap[ImGuiKey_Y] = 'Y';
  573. io.KeyMap[ImGuiKey_Z] = 'Z';
  574. io.ImeWindowHandle = g_hWnd;
  575. return true;
  576. }
  577. void ImGui_ImplDX11_Shutdown()
  578. {
  579. ImGui_ImplDX11_InvalidateDeviceObjects();
  580. g_pd3dDevice = NULL;
  581. g_pd3dDeviceContext = NULL;
  582. g_hWnd = (HWND)0;
  583. }
  584. void ImGui_ImplDX11_NewFrame()
  585. {
  586. if (!g_pFontSampler)
  587. ImGui_ImplDX11_CreateDeviceObjects();
  588. ImGuiIO& io = ImGui::GetIO();
  589. // Setup display size (every frame to accommodate for window resizing)
  590. RECT rect;
  591. GetClientRect(g_hWnd, &rect);
  592. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  593. // Setup time step
  594. INT64 current_time;
  595. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  596. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  597. g_Time = current_time;
  598. // Read keyboard modifiers inputs
  599. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  600. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  601. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  602. io.KeySuper = false;
  603. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  604. // io.MousePos : filled by WM_MOUSEMOVE events
  605. // io.MouseDown : filled by WM_*BUTTON* events
  606. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  607. // Set OS mouse position if requested (only used when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  608. if (io.WantSetMousePos)
  609. {
  610. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  611. ClientToScreen(g_hWnd, &pos);
  612. SetCursorPos(pos.x, pos.y);
  613. }
  614. // Update OS mouse cursor with the cursor requested by imgui
  615. ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  616. if (g_LastMouseCursor != mouse_cursor)
  617. {
  618. g_LastMouseCursor = mouse_cursor;
  619. ImGui_ImplWin32_UpdateMouseCursor();
  620. }
  621. // 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.
  622. ImGui::NewFrame();
  623. }