imgui_impl_dx11.cpp 34 KB

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