imgui_impl_dx11.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // dear imgui: Renderer Backend for DirectX11
  2. // This needs to be used along with a Platform Backend (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
  6. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  7. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  8. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  9. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  10. // CHANGELOG
  11. // (minor and older changes stripped away, please see git history for details)
  12. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
  13. // 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  14. // 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer.
  15. // 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled).
  16. // 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore.
  17. // 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  18. // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  19. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  20. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  21. // 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
  22. // 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
  23. // 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
  24. // 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  25. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
  26. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  27. // 2016-05-07: DirectX11: Disabling depth-write.
  28. #include "imgui.h"
  29. #include "imgui_impl_dx11.h"
  30. // DirectX
  31. #include <stdio.h>
  32. #include <d3d11.h>
  33. #include <d3dcompiler.h>
  34. #ifdef _MSC_VER
  35. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  36. #endif
  37. // DirectX11 data
  38. struct ImGui_ImplDX11_Data
  39. {
  40. ID3D11Device* pd3dDevice;
  41. ID3D11DeviceContext* pd3dDeviceContext;
  42. IDXGIFactory* pFactory;
  43. ID3D11Buffer* pVB;
  44. ID3D11Buffer* pIB;
  45. ID3D11VertexShader* pVertexShader;
  46. ID3D11InputLayout* pInputLayout;
  47. ID3D11Buffer* pVertexConstantBuffer;
  48. ID3D11PixelShader* pPixelShader;
  49. ID3D11SamplerState* pFontSampler;
  50. ID3D11ShaderResourceView* pFontTextureView;
  51. ID3D11RasterizerState* pRasterizerState;
  52. ID3D11BlendState* pBlendState;
  53. ID3D11DepthStencilState* pDepthStencilState;
  54. int VertexBufferSize;
  55. int IndexBufferSize;
  56. ImGui_ImplDX11_Data() { memset(this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
  57. };
  58. struct VERTEX_CONSTANT_BUFFER
  59. {
  60. float mvp[4][4];
  61. };
  62. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  63. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  64. static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData()
  65. {
  66. return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : NULL;
  67. }
  68. // Functions
  69. static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx)
  70. {
  71. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  72. // Setup viewport
  73. D3D11_VIEWPORT vp;
  74. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  75. vp.Width = draw_data->DisplaySize.x;
  76. vp.Height = draw_data->DisplaySize.y;
  77. vp.MinDepth = 0.0f;
  78. vp.MaxDepth = 1.0f;
  79. vp.TopLeftX = vp.TopLeftY = 0;
  80. ctx->RSSetViewports(1, &vp);
  81. // Setup shader and vertex buffers
  82. unsigned int stride = sizeof(ImDrawVert);
  83. unsigned int offset = 0;
  84. ctx->IASetInputLayout(bd->pInputLayout);
  85. ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
  86. ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  87. ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  88. ctx->VSSetShader(bd->pVertexShader, NULL, 0);
  89. ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
  90. ctx->PSSetShader(bd->pPixelShader, NULL, 0);
  91. ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
  92. ctx->GSSetShader(NULL, NULL, 0);
  93. ctx->HSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used..
  94. ctx->DSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used..
  95. ctx->CSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used..
  96. // Setup blend state
  97. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  98. ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
  99. ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
  100. ctx->RSSetState(bd->pRasterizerState);
  101. }
  102. // Render function
  103. void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
  104. {
  105. // Avoid rendering when minimized
  106. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  107. return;
  108. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  109. ID3D11DeviceContext* ctx = bd->pd3dDeviceContext;
  110. // Create and grow vertex/index buffers if needed
  111. if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
  112. {
  113. if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; }
  114. bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  115. D3D11_BUFFER_DESC desc;
  116. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  117. desc.Usage = D3D11_USAGE_DYNAMIC;
  118. desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
  119. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  120. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  121. desc.MiscFlags = 0;
  122. if (bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pVB) < 0)
  123. return;
  124. }
  125. if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
  126. {
  127. if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; }
  128. bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  129. D3D11_BUFFER_DESC desc;
  130. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  131. desc.Usage = D3D11_USAGE_DYNAMIC;
  132. desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
  133. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  134. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  135. if (bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pIB) < 0)
  136. return;
  137. }
  138. // Upload vertex/index data into a single contiguous GPU buffer
  139. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  140. if (ctx->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  141. return;
  142. if (ctx->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  143. return;
  144. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  145. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  146. for (int n = 0; n < draw_data->CmdListsCount; n++)
  147. {
  148. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  149. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  150. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  151. vtx_dst += cmd_list->VtxBuffer.Size;
  152. idx_dst += cmd_list->IdxBuffer.Size;
  153. }
  154. ctx->Unmap(bd->pVB, 0);
  155. ctx->Unmap(bd->pIB, 0);
  156. // Setup orthographic projection matrix into our constant buffer
  157. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
  158. {
  159. D3D11_MAPPED_SUBRESOURCE mapped_resource;
  160. if (ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  161. return;
  162. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
  163. float L = draw_data->DisplayPos.x;
  164. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  165. float T = draw_data->DisplayPos.y;
  166. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  167. float mvp[4][4] =
  168. {
  169. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  170. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  171. { 0.0f, 0.0f, 0.5f, 0.0f },
  172. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  173. };
  174. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  175. ctx->Unmap(bd->pVertexConstantBuffer, 0);
  176. }
  177. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  178. struct BACKUP_DX11_STATE
  179. {
  180. UINT ScissorRectsCount, ViewportsCount;
  181. D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  182. D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  183. ID3D11RasterizerState* RS;
  184. ID3D11BlendState* BlendState;
  185. FLOAT BlendFactor[4];
  186. UINT SampleMask;
  187. UINT StencilRef;
  188. ID3D11DepthStencilState* DepthStencilState;
  189. ID3D11ShaderResourceView* PSShaderResource;
  190. ID3D11SamplerState* PSSampler;
  191. ID3D11PixelShader* PS;
  192. ID3D11VertexShader* VS;
  193. ID3D11GeometryShader* GS;
  194. UINT PSInstancesCount, VSInstancesCount, GSInstancesCount;
  195. ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation
  196. D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  197. ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  198. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  199. DXGI_FORMAT IndexBufferFormat;
  200. ID3D11InputLayout* InputLayout;
  201. };
  202. BACKUP_DX11_STATE old = {};
  203. old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  204. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  205. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  206. ctx->RSGetState(&old.RS);
  207. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  208. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  209. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  210. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  211. old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
  212. ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
  213. ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
  214. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  215. ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
  216. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  217. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  218. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  219. ctx->IAGetInputLayout(&old.InputLayout);
  220. // Setup desired DX state
  221. ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
  222. // Render command lists
  223. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  224. int global_idx_offset = 0;
  225. int global_vtx_offset = 0;
  226. ImVec2 clip_off = draw_data->DisplayPos;
  227. for (int n = 0; n < draw_data->CmdListsCount; n++)
  228. {
  229. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  230. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  231. {
  232. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  233. if (pcmd->UserCallback != NULL)
  234. {
  235. // User callback, registered via ImDrawList::AddCallback()
  236. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  237. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  238. ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
  239. else
  240. pcmd->UserCallback(cmd_list, pcmd);
  241. }
  242. else
  243. {
  244. // Project scissor/clipping rectangles into framebuffer space
  245. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  246. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  247. if (clip_max.x < clip_min.x || clip_max.y < clip_min.y)
  248. continue;
  249. // Apply scissor/clipping rectangle
  250. const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  251. ctx->RSSetScissorRects(1, &r);
  252. // Bind texture, Draw
  253. ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID();
  254. ctx->PSSetShaderResources(0, 1, &texture_srv);
  255. ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
  256. }
  257. }
  258. global_idx_offset += cmd_list->IdxBuffer.Size;
  259. global_vtx_offset += cmd_list->VtxBuffer.Size;
  260. }
  261. // Restore modified DX state
  262. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  263. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  264. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  265. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  266. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  267. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  268. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  269. ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
  270. for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
  271. ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
  272. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  273. ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
  274. for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
  275. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  276. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  277. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  278. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  279. }
  280. static void ImGui_ImplDX11_CreateFontsTexture()
  281. {
  282. // Build texture atlas
  283. ImGuiIO& io = ImGui::GetIO();
  284. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  285. unsigned char* pixels;
  286. int width, height;
  287. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  288. // Upload texture to graphics system
  289. {
  290. D3D11_TEXTURE2D_DESC desc;
  291. ZeroMemory(&desc, sizeof(desc));
  292. desc.Width = width;
  293. desc.Height = height;
  294. desc.MipLevels = 1;
  295. desc.ArraySize = 1;
  296. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  297. desc.SampleDesc.Count = 1;
  298. desc.Usage = D3D11_USAGE_DEFAULT;
  299. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  300. desc.CPUAccessFlags = 0;
  301. ID3D11Texture2D* pTexture = NULL;
  302. D3D11_SUBRESOURCE_DATA subResource;
  303. subResource.pSysMem = pixels;
  304. subResource.SysMemPitch = desc.Width * 4;
  305. subResource.SysMemSlicePitch = 0;
  306. bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  307. IM_ASSERT(pTexture != NULL);
  308. // Create texture view
  309. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  310. ZeroMemory(&srvDesc, sizeof(srvDesc));
  311. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  312. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  313. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  314. srvDesc.Texture2D.MostDetailedMip = 0;
  315. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &bd->pFontTextureView);
  316. pTexture->Release();
  317. }
  318. // Store our identifier
  319. io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
  320. // Create texture sampler
  321. {
  322. D3D11_SAMPLER_DESC desc;
  323. ZeroMemory(&desc, sizeof(desc));
  324. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  325. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  326. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  327. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  328. desc.MipLODBias = 0.f;
  329. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  330. desc.MinLOD = 0.f;
  331. desc.MaxLOD = 0.f;
  332. bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
  333. }
  334. }
  335. bool ImGui_ImplDX11_CreateDeviceObjects()
  336. {
  337. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  338. if (!bd->pd3dDevice)
  339. return false;
  340. if (bd->pFontSampler)
  341. ImGui_ImplDX11_InvalidateDeviceObjects();
  342. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  343. // If you would like to use this DX11 sample code but remove this dependency you can:
  344. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  345. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  346. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  347. // Create the vertex shader
  348. {
  349. static const char* vertexShader =
  350. "cbuffer vertexBuffer : register(b0) \
  351. {\
  352. float4x4 ProjectionMatrix; \
  353. };\
  354. struct VS_INPUT\
  355. {\
  356. float2 pos : POSITION;\
  357. float4 col : COLOR0;\
  358. float2 uv : TEXCOORD0;\
  359. };\
  360. \
  361. struct PS_INPUT\
  362. {\
  363. float4 pos : SV_POSITION;\
  364. float4 col : COLOR0;\
  365. float2 uv : TEXCOORD0;\
  366. };\
  367. \
  368. PS_INPUT main(VS_INPUT input)\
  369. {\
  370. PS_INPUT output;\
  371. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  372. output.col = input.col;\
  373. output.uv = input.uv;\
  374. return output;\
  375. }";
  376. ID3DBlob* vertexShaderBlob;
  377. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL)))
  378. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  379. if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &bd->pVertexShader) != S_OK)
  380. {
  381. vertexShaderBlob->Release();
  382. return false;
  383. }
  384. // Create the input layout
  385. D3D11_INPUT_ELEMENT_DESC local_layout[] =
  386. {
  387. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  388. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  389. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  390. };
  391. if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
  392. {
  393. vertexShaderBlob->Release();
  394. return false;
  395. }
  396. vertexShaderBlob->Release();
  397. // Create the constant buffer
  398. {
  399. D3D11_BUFFER_DESC desc;
  400. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  401. desc.Usage = D3D11_USAGE_DYNAMIC;
  402. desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  403. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  404. desc.MiscFlags = 0;
  405. bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pVertexConstantBuffer);
  406. }
  407. }
  408. // Create the pixel shader
  409. {
  410. static const char* pixelShader =
  411. "struct PS_INPUT\
  412. {\
  413. float4 pos : SV_POSITION;\
  414. float4 col : COLOR0;\
  415. float2 uv : TEXCOORD0;\
  416. };\
  417. sampler sampler0;\
  418. Texture2D texture0;\
  419. \
  420. float4 main(PS_INPUT input) : SV_Target\
  421. {\
  422. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  423. return out_col; \
  424. }";
  425. ID3DBlob* pixelShaderBlob;
  426. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL)))
  427. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  428. if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &bd->pPixelShader) != S_OK)
  429. {
  430. pixelShaderBlob->Release();
  431. return false;
  432. }
  433. pixelShaderBlob->Release();
  434. }
  435. // Create the blending setup
  436. {
  437. D3D11_BLEND_DESC desc;
  438. ZeroMemory(&desc, sizeof(desc));
  439. desc.AlphaToCoverageEnable = false;
  440. desc.RenderTarget[0].BlendEnable = true;
  441. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  442. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  443. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  444. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
  445. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  446. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  447. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  448. bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
  449. }
  450. // Create the rasterizer state
  451. {
  452. D3D11_RASTERIZER_DESC desc;
  453. ZeroMemory(&desc, sizeof(desc));
  454. desc.FillMode = D3D11_FILL_SOLID;
  455. desc.CullMode = D3D11_CULL_NONE;
  456. desc.ScissorEnable = true;
  457. desc.DepthClipEnable = true;
  458. bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
  459. }
  460. // Create depth-stencil State
  461. {
  462. D3D11_DEPTH_STENCIL_DESC desc;
  463. ZeroMemory(&desc, sizeof(desc));
  464. desc.DepthEnable = false;
  465. desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  466. desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
  467. desc.StencilEnable = false;
  468. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  469. desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  470. desc.BackFace = desc.FrontFace;
  471. bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
  472. }
  473. ImGui_ImplDX11_CreateFontsTexture();
  474. return true;
  475. }
  476. void ImGui_ImplDX11_InvalidateDeviceObjects()
  477. {
  478. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  479. if (!bd->pd3dDevice)
  480. return;
  481. if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = NULL; }
  482. if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = NULL; ImGui::GetIO().Fonts->SetTexID(NULL); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well.
  483. if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; }
  484. if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; }
  485. if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = NULL; }
  486. if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = NULL; }
  487. if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = NULL; }
  488. if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = NULL; }
  489. if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = NULL; }
  490. if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = NULL; }
  491. if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = NULL; }
  492. }
  493. bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
  494. {
  495. ImGuiIO& io = ImGui::GetIO();
  496. IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!");
  497. // Setup backend capabilities flags
  498. ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)();
  499. io.BackendRendererUserData = (void*)bd;
  500. io.BackendRendererName = "imgui_impl_dx11";
  501. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  502. // Get factory from device
  503. IDXGIDevice* pDXGIDevice = NULL;
  504. IDXGIAdapter* pDXGIAdapter = NULL;
  505. IDXGIFactory* pFactory = NULL;
  506. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
  507. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
  508. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
  509. {
  510. bd->pd3dDevice = device;
  511. bd->pd3dDeviceContext = device_context;
  512. bd->pFactory = pFactory;
  513. }
  514. if (pDXGIDevice) pDXGIDevice->Release();
  515. if (pDXGIAdapter) pDXGIAdapter->Release();
  516. bd->pd3dDevice->AddRef();
  517. bd->pd3dDeviceContext->AddRef();
  518. return true;
  519. }
  520. void ImGui_ImplDX11_Shutdown()
  521. {
  522. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  523. IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?");
  524. ImGuiIO& io = ImGui::GetIO();
  525. ImGui_ImplDX11_InvalidateDeviceObjects();
  526. if (bd->pFactory) { bd->pFactory->Release(); }
  527. if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
  528. if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); }
  529. io.BackendRendererName = NULL;
  530. io.BackendRendererUserData = NULL;
  531. IM_DELETE(bd);
  532. }
  533. void ImGui_ImplDX11_NewFrame()
  534. {
  535. ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
  536. IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX11_Init()?");
  537. if (!bd->pFontSampler)
  538. ImGui_ImplDX11_CreateDeviceObjects();
  539. }