imgui_impl_dx11.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. // ImGui Renderer for: DirectX11
  2. // This needs to be used along with a Platform Binding (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  5. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  6. // If you are new to dear imgui, read examples/README.txt and read the 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-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
  11. // 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
  12. // 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  13. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
  14. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  15. // 2016-05-07: DirectX11: Disabling depth-write.
  16. #include "imgui.h"
  17. #include "imgui_impl_dx11.h"
  18. // DirectX
  19. #include <stdio.h>
  20. #include <d3d11.h>
  21. #include <d3dcompiler.h>
  22. // DirectX data
  23. static ID3D11Device* g_pd3dDevice = NULL;
  24. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  25. static IDXGIFactory* g_pFactory = NULL;
  26. static ID3D11Buffer* g_pVB = NULL;
  27. static ID3D11Buffer* g_pIB = NULL;
  28. static ID3D10Blob* g_pVertexShaderBlob = NULL;
  29. static ID3D11VertexShader* g_pVertexShader = NULL;
  30. static ID3D11InputLayout* g_pInputLayout = NULL;
  31. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  32. static ID3D10Blob* g_pPixelShaderBlob = NULL;
  33. static ID3D11PixelShader* g_pPixelShader = NULL;
  34. static ID3D11SamplerState* g_pFontSampler = NULL;
  35. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  36. static ID3D11RasterizerState* g_pRasterizerState = NULL;
  37. static ID3D11BlendState* g_pBlendState = NULL;
  38. static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
  39. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  40. struct VERTEX_CONSTANT_BUFFER
  41. {
  42. float mvp[4][4];
  43. };
  44. // Render function
  45. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  46. void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
  47. {
  48. ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
  49. // Create and grow vertex/index buffers if needed
  50. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  51. {
  52. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  53. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  54. D3D11_BUFFER_DESC desc;
  55. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  56. desc.Usage = D3D11_USAGE_DYNAMIC;
  57. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  58. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  59. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  60. desc.MiscFlags = 0;
  61. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  62. return;
  63. }
  64. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  65. {
  66. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  67. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  68. D3D11_BUFFER_DESC desc;
  69. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  70. desc.Usage = D3D11_USAGE_DYNAMIC;
  71. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  72. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  73. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  74. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  75. return;
  76. }
  77. // Copy and convert all vertices into a single contiguous buffer
  78. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  79. if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  80. return;
  81. if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  82. return;
  83. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  84. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  85. for (int n = 0; n < draw_data->CmdListsCount; n++)
  86. {
  87. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  88. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  89. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  90. vtx_dst += cmd_list->VtxBuffer.Size;
  91. idx_dst += cmd_list->IdxBuffer.Size;
  92. }
  93. ctx->Unmap(g_pVB, 0);
  94. ctx->Unmap(g_pIB, 0);
  95. // Setup orthographic projection matrix into our constant buffer
  96. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  97. {
  98. D3D11_MAPPED_SUBRESOURCE mapped_resource;
  99. if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  100. return;
  101. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
  102. float L = draw_data->DisplayPos.x;
  103. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  104. float T = draw_data->DisplayPos.y;
  105. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  106. float mvp[4][4] =
  107. {
  108. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  109. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  110. { 0.0f, 0.0f, 0.5f, 0.0f },
  111. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  112. };
  113. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  114. ctx->Unmap(g_pVertexConstantBuffer, 0);
  115. }
  116. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  117. struct BACKUP_DX11_STATE
  118. {
  119. UINT ScissorRectsCount, ViewportsCount;
  120. D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  121. D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  122. ID3D11RasterizerState* RS;
  123. ID3D11BlendState* BlendState;
  124. FLOAT BlendFactor[4];
  125. UINT SampleMask;
  126. UINT StencilRef;
  127. ID3D11DepthStencilState* DepthStencilState;
  128. ID3D11ShaderResourceView* PSShaderResource;
  129. ID3D11SamplerState* PSSampler;
  130. ID3D11PixelShader* PS;
  131. ID3D11VertexShader* VS;
  132. UINT PSInstancesCount, VSInstancesCount;
  133. ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
  134. D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  135. ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  136. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  137. DXGI_FORMAT IndexBufferFormat;
  138. ID3D11InputLayout* InputLayout;
  139. };
  140. BACKUP_DX11_STATE old;
  141. old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  142. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  143. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  144. ctx->RSGetState(&old.RS);
  145. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  146. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  147. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  148. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  149. old.PSInstancesCount = old.VSInstancesCount = 256;
  150. ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
  151. ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
  152. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  153. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  154. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  155. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  156. ctx->IAGetInputLayout(&old.InputLayout);
  157. // Setup viewport
  158. D3D11_VIEWPORT vp;
  159. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  160. vp.Width = draw_data->DisplaySize.x;
  161. vp.Height = draw_data->DisplaySize.y;
  162. vp.MinDepth = 0.0f;
  163. vp.MaxDepth = 1.0f;
  164. vp.TopLeftX = vp.TopLeftY = 0;
  165. ctx->RSSetViewports(1, &vp);
  166. // Bind shader and vertex buffers
  167. unsigned int stride = sizeof(ImDrawVert);
  168. unsigned int offset = 0;
  169. ctx->IASetInputLayout(g_pInputLayout);
  170. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  171. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  172. ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  173. ctx->VSSetShader(g_pVertexShader, NULL, 0);
  174. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  175. ctx->PSSetShader(g_pPixelShader, NULL, 0);
  176. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  177. // Setup render state
  178. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  179. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  180. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  181. ctx->RSSetState(g_pRasterizerState);
  182. // Render command lists
  183. int vtx_offset = 0;
  184. int idx_offset = 0;
  185. ImVec2 pos = draw_data->DisplayPos;
  186. for (int n = 0; n < draw_data->CmdListsCount; n++)
  187. {
  188. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  189. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  190. {
  191. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  192. if (pcmd->UserCallback)
  193. {
  194. // User callback (registered via ImDrawList::AddCallback)
  195. pcmd->UserCallback(cmd_list, pcmd);
  196. }
  197. else
  198. {
  199. // Apply scissor/clipping rectangle
  200. const D3D11_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) };
  201. ctx->RSSetScissorRects(1, &r);
  202. // Bind texture, Draw
  203. ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
  204. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  205. }
  206. idx_offset += pcmd->ElemCount;
  207. }
  208. vtx_offset += cmd_list->VtxBuffer.Size;
  209. }
  210. // Restore modified DX state
  211. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  212. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  213. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  214. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  215. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  216. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  217. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  218. ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
  219. for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
  220. ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
  221. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  222. for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
  223. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  224. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  225. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  226. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  227. }
  228. static void ImGui_ImplDX11_CreateFontsTexture()
  229. {
  230. // Build texture atlas
  231. ImGuiIO& io = ImGui::GetIO();
  232. unsigned char* pixels;
  233. int width, height;
  234. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  235. // Upload texture to graphics system
  236. {
  237. D3D11_TEXTURE2D_DESC desc;
  238. ZeroMemory(&desc, sizeof(desc));
  239. desc.Width = width;
  240. desc.Height = height;
  241. desc.MipLevels = 1;
  242. desc.ArraySize = 1;
  243. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  244. desc.SampleDesc.Count = 1;
  245. desc.Usage = D3D11_USAGE_DEFAULT;
  246. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  247. desc.CPUAccessFlags = 0;
  248. ID3D11Texture2D *pTexture = NULL;
  249. D3D11_SUBRESOURCE_DATA subResource;
  250. subResource.pSysMem = pixels;
  251. subResource.SysMemPitch = desc.Width * 4;
  252. subResource.SysMemSlicePitch = 0;
  253. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  254. // Create texture view
  255. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  256. ZeroMemory(&srvDesc, sizeof(srvDesc));
  257. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  258. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  259. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  260. srvDesc.Texture2D.MostDetailedMip = 0;
  261. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  262. pTexture->Release();
  263. }
  264. // Store our identifier
  265. io.Fonts->TexID = (void *)g_pFontTextureView;
  266. // Create texture sampler
  267. {
  268. D3D11_SAMPLER_DESC desc;
  269. ZeroMemory(&desc, sizeof(desc));
  270. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  271. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  272. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  273. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  274. desc.MipLODBias = 0.f;
  275. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  276. desc.MinLOD = 0.f;
  277. desc.MaxLOD = 0.f;
  278. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  279. }
  280. }
  281. bool ImGui_ImplDX11_CreateDeviceObjects()
  282. {
  283. if (!g_pd3dDevice)
  284. return false;
  285. if (g_pFontSampler)
  286. ImGui_ImplDX11_InvalidateDeviceObjects();
  287. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  288. // If you would like to use this DX11 sample code but remove this dependency you can:
  289. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  290. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  291. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  292. // Create the vertex shader
  293. {
  294. static const char* vertexShader =
  295. "cbuffer vertexBuffer : register(b0) \
  296. {\
  297. float4x4 ProjectionMatrix; \
  298. };\
  299. struct VS_INPUT\
  300. {\
  301. float2 pos : POSITION;\
  302. float4 col : COLOR0;\
  303. float2 uv : TEXCOORD0;\
  304. };\
  305. \
  306. struct PS_INPUT\
  307. {\
  308. float4 pos : SV_POSITION;\
  309. float4 col : COLOR0;\
  310. float2 uv : TEXCOORD0;\
  311. };\
  312. \
  313. PS_INPUT main(VS_INPUT input)\
  314. {\
  315. PS_INPUT output;\
  316. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  317. output.col = input.col;\
  318. output.uv = input.uv;\
  319. return output;\
  320. }";
  321. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  322. 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!
  323. return false;
  324. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  325. return false;
  326. // Create the input layout
  327. D3D11_INPUT_ELEMENT_DESC local_layout[] =
  328. {
  329. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  330. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  331. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  332. };
  333. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  334. return false;
  335. // Create the constant buffer
  336. {
  337. D3D11_BUFFER_DESC desc;
  338. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  339. desc.Usage = D3D11_USAGE_DYNAMIC;
  340. desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  341. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  342. desc.MiscFlags = 0;
  343. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  344. }
  345. }
  346. // Create the pixel shader
  347. {
  348. static const char* pixelShader =
  349. "struct PS_INPUT\
  350. {\
  351. float4 pos : SV_POSITION;\
  352. float4 col : COLOR0;\
  353. float2 uv : TEXCOORD0;\
  354. };\
  355. sampler sampler0;\
  356. Texture2D texture0;\
  357. \
  358. float4 main(PS_INPUT input) : SV_Target\
  359. {\
  360. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  361. return out_col; \
  362. }";
  363. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  364. 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!
  365. return false;
  366. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  367. return false;
  368. }
  369. // Create the blending setup
  370. {
  371. D3D11_BLEND_DESC desc;
  372. ZeroMemory(&desc, sizeof(desc));
  373. desc.AlphaToCoverageEnable = false;
  374. desc.RenderTarget[0].BlendEnable = true;
  375. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  376. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  377. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  378. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  379. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  380. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  381. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  382. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  383. }
  384. // Create the rasterizer state
  385. {
  386. D3D11_RASTERIZER_DESC desc;
  387. ZeroMemory(&desc, sizeof(desc));
  388. desc.FillMode = D3D11_FILL_SOLID;
  389. desc.CullMode = D3D11_CULL_NONE;
  390. desc.ScissorEnable = true;
  391. desc.DepthClipEnable = true;
  392. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  393. }
  394. // Create depth-stencil State
  395. {
  396. D3D11_DEPTH_STENCIL_DESC desc;
  397. ZeroMemory(&desc, sizeof(desc));
  398. desc.DepthEnable = false;
  399. desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  400. desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
  401. desc.StencilEnable = false;
  402. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  403. desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  404. desc.BackFace = desc.FrontFace;
  405. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  406. }
  407. ImGui_ImplDX11_CreateFontsTexture();
  408. return true;
  409. }
  410. void ImGui_ImplDX11_InvalidateDeviceObjects()
  411. {
  412. if (!g_pd3dDevice)
  413. return;
  414. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  415. 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.
  416. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  417. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  418. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  419. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  420. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  421. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  422. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  423. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  424. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  425. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  426. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  427. }
  428. bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
  429. {
  430. // Get factory from device
  431. IDXGIDevice* pDXGIDevice = NULL;
  432. IDXGIAdapter* pDXGIAdapter = NULL;
  433. IDXGIFactory* pFactory = NULL;
  434. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
  435. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
  436. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
  437. {
  438. g_pd3dDevice = device;
  439. g_pd3dDeviceContext = device_context;
  440. g_pFactory = pFactory;
  441. }
  442. if (pDXGIDevice) pDXGIDevice->Release();
  443. if (pDXGIAdapter) pDXGIAdapter->Release();
  444. return true;
  445. }
  446. void ImGui_ImplDX11_Shutdown()
  447. {
  448. ImGui_ImplDX11_InvalidateDeviceObjects();
  449. if (g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; }
  450. g_pd3dDevice = NULL;
  451. g_pd3dDeviceContext = NULL;
  452. }
  453. void ImGui_ImplDX11_NewFrame()
  454. {
  455. if (!g_pFontSampler)
  456. ImGui_ImplDX11_CreateDeviceObjects();
  457. }