imgui_impl_dx11.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. // [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  6. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  7. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  8. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  9. // https://github.com/ocornut/imgui
  10. // CHANGELOG
  11. // (minor and older changes stripped away, please see git history for details)
  12. // 2018-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  13. // 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
  14. // 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  15. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
  16. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  17. // 2016-05-07: DirectX11: Disabling depth-write.
  18. #include "imgui.h"
  19. #include "imgui_impl_dx11.h"
  20. // DirectX
  21. #include <stdio.h>
  22. #include <d3d11.h>
  23. #include <d3dcompiler.h>
  24. // DirectX data
  25. static ID3D11Device* g_pd3dDevice = NULL;
  26. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  27. static IDXGIFactory1* g_pFactory = NULL;
  28. static ID3D11Buffer* g_pVB = NULL;
  29. static ID3D11Buffer* g_pIB = NULL;
  30. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  31. static ID3D11VertexShader* g_pVertexShader = NULL;
  32. static ID3D11InputLayout* g_pInputLayout = NULL;
  33. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  34. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  35. static ID3D11PixelShader* g_pPixelShader = NULL;
  36. static ID3D11SamplerState* g_pFontSampler = NULL;
  37. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  38. static ID3D11RasterizerState* g_pRasterizerState = NULL;
  39. static ID3D11BlendState* g_pBlendState = NULL;
  40. static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
  41. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  42. struct VERTEX_CONSTANT_BUFFER
  43. {
  44. float mvp[4][4];
  45. };
  46. // Forward Declarations
  47. static void ImGui_ImplDX11_InitPlatformInterface();
  48. static void ImGui_ImplDX11_ShutdownPlatformInterface();
  49. // Render function
  50. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  51. void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
  52. {
  53. ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
  54. // Create and grow vertex/index buffers if needed
  55. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  56. {
  57. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  58. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  59. D3D11_BUFFER_DESC desc;
  60. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  61. desc.Usage = D3D11_USAGE_DYNAMIC;
  62. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  63. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  64. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  65. desc.MiscFlags = 0;
  66. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  67. return;
  68. }
  69. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  70. {
  71. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  72. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  73. D3D11_BUFFER_DESC desc;
  74. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  75. desc.Usage = D3D11_USAGE_DYNAMIC;
  76. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  77. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  78. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  79. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  80. return;
  81. }
  82. // Copy and convert all vertices into a single contiguous buffer
  83. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  84. if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  85. return;
  86. if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  87. return;
  88. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  89. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  90. for (int n = 0; n < draw_data->CmdListsCount; n++)
  91. {
  92. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  93. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  94. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  95. vtx_dst += cmd_list->VtxBuffer.Size;
  96. idx_dst += cmd_list->IdxBuffer.Size;
  97. }
  98. ctx->Unmap(g_pVB, 0);
  99. ctx->Unmap(g_pIB, 0);
  100. // Setup orthographic projection matrix into our constant buffer
  101. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is (0,0) for single viewport apps.
  102. {
  103. D3D11_MAPPED_SUBRESOURCE mapped_resource;
  104. if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  105. return;
  106. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
  107. float L = draw_data->DisplayPos.x;
  108. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  109. float T = draw_data->DisplayPos.y;
  110. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  111. float mvp[4][4] =
  112. {
  113. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  114. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  115. { 0.0f, 0.0f, 0.5f, 0.0f },
  116. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  117. };
  118. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  119. ctx->Unmap(g_pVertexConstantBuffer, 0);
  120. }
  121. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  122. struct BACKUP_DX11_STATE
  123. {
  124. UINT ScissorRectsCount, ViewportsCount;
  125. D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  126. D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  127. ID3D11RasterizerState* RS;
  128. ID3D11BlendState* BlendState;
  129. FLOAT BlendFactor[4];
  130. UINT SampleMask;
  131. UINT StencilRef;
  132. ID3D11DepthStencilState* DepthStencilState;
  133. ID3D11ShaderResourceView* PSShaderResource;
  134. ID3D11SamplerState* PSSampler;
  135. ID3D11PixelShader* PS;
  136. ID3D11VertexShader* VS;
  137. UINT PSInstancesCount, VSInstancesCount;
  138. ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
  139. D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  140. ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  141. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  142. DXGI_FORMAT IndexBufferFormat;
  143. ID3D11InputLayout* InputLayout;
  144. };
  145. BACKUP_DX11_STATE old;
  146. old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  147. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  148. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  149. ctx->RSGetState(&old.RS);
  150. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  151. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  152. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  153. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  154. old.PSInstancesCount = old.VSInstancesCount = 256;
  155. ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
  156. ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
  157. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  158. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  159. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  160. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  161. ctx->IAGetInputLayout(&old.InputLayout);
  162. // Setup viewport
  163. D3D11_VIEWPORT vp;
  164. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  165. vp.Width = draw_data->DisplaySize.x;
  166. vp.Height = draw_data->DisplaySize.y;
  167. vp.MinDepth = 0.0f;
  168. vp.MaxDepth = 1.0f;
  169. vp.TopLeftX = vp.TopLeftY = 0;
  170. ctx->RSSetViewports(1, &vp);
  171. // Bind shader and vertex buffers
  172. unsigned int stride = sizeof(ImDrawVert);
  173. unsigned int offset = 0;
  174. ctx->IASetInputLayout(g_pInputLayout);
  175. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  176. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  177. ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  178. ctx->VSSetShader(g_pVertexShader, NULL, 0);
  179. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  180. ctx->PSSetShader(g_pPixelShader, NULL, 0);
  181. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  182. // Setup render state
  183. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  184. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  185. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  186. ctx->RSSetState(g_pRasterizerState);
  187. // Render command lists
  188. int vtx_offset = 0;
  189. int idx_offset = 0;
  190. ImVec2 pos = draw_data->DisplayPos;
  191. for (int n = 0; n < draw_data->CmdListsCount; n++)
  192. {
  193. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  194. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  195. {
  196. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  197. if (pcmd->UserCallback)
  198. {
  199. // User callback (registered via ImDrawList::AddCallback)
  200. pcmd->UserCallback(cmd_list, pcmd);
  201. }
  202. else
  203. {
  204. // Apply scissor/clipping rectangle
  205. 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) };
  206. ctx->RSSetScissorRects(1, &r);
  207. // Bind texture, Draw
  208. ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
  209. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  210. }
  211. idx_offset += pcmd->ElemCount;
  212. }
  213. vtx_offset += cmd_list->VtxBuffer.Size;
  214. }
  215. // Restore modified DX state
  216. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  217. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  218. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  219. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  220. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  221. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  222. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  223. ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
  224. for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
  225. ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
  226. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  227. for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
  228. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  229. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  230. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  231. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  232. }
  233. static void ImGui_ImplDX11_CreateFontsTexture()
  234. {
  235. // Build texture atlas
  236. ImGuiIO& io = ImGui::GetIO();
  237. unsigned char* pixels;
  238. int width, height;
  239. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  240. // Upload texture to graphics system
  241. {
  242. D3D11_TEXTURE2D_DESC desc;
  243. ZeroMemory(&desc, sizeof(desc));
  244. desc.Width = width;
  245. desc.Height = height;
  246. desc.MipLevels = 1;
  247. desc.ArraySize = 1;
  248. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  249. desc.SampleDesc.Count = 1;
  250. desc.Usage = D3D11_USAGE_DEFAULT;
  251. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  252. desc.CPUAccessFlags = 0;
  253. ID3D11Texture2D *pTexture = NULL;
  254. D3D11_SUBRESOURCE_DATA subResource;
  255. subResource.pSysMem = pixels;
  256. subResource.SysMemPitch = desc.Width * 4;
  257. subResource.SysMemSlicePitch = 0;
  258. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  259. // Create texture view
  260. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  261. ZeroMemory(&srvDesc, sizeof(srvDesc));
  262. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  263. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  264. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  265. srvDesc.Texture2D.MostDetailedMip = 0;
  266. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  267. pTexture->Release();
  268. }
  269. // Store our identifier
  270. io.Fonts->TexID = (void *)g_pFontTextureView;
  271. // Create texture sampler
  272. {
  273. D3D11_SAMPLER_DESC desc;
  274. ZeroMemory(&desc, sizeof(desc));
  275. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  276. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  277. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  278. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  279. desc.MipLODBias = 0.f;
  280. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  281. desc.MinLOD = 0.f;
  282. desc.MaxLOD = 0.f;
  283. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  284. }
  285. }
  286. bool ImGui_ImplDX11_CreateDeviceObjects()
  287. {
  288. if (!g_pd3dDevice)
  289. return false;
  290. if (g_pFontSampler)
  291. ImGui_ImplDX11_InvalidateDeviceObjects();
  292. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  293. // If you would like to use this DX11 sample code but remove this dependency you can:
  294. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  295. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  296. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  297. // Create the vertex shader
  298. {
  299. static const char* vertexShader =
  300. "cbuffer vertexBuffer : register(b0) \
  301. {\
  302. float4x4 ProjectionMatrix; \
  303. };\
  304. struct VS_INPUT\
  305. {\
  306. float2 pos : POSITION;\
  307. float4 col : COLOR0;\
  308. float2 uv : TEXCOORD0;\
  309. };\
  310. \
  311. struct PS_INPUT\
  312. {\
  313. float4 pos : SV_POSITION;\
  314. float4 col : COLOR0;\
  315. float2 uv : TEXCOORD0;\
  316. };\
  317. \
  318. PS_INPUT main(VS_INPUT input)\
  319. {\
  320. PS_INPUT output;\
  321. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  322. output.col = input.col;\
  323. output.uv = input.uv;\
  324. return output;\
  325. }";
  326. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  327. 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!
  328. return false;
  329. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  330. return false;
  331. // Create the input layout
  332. D3D11_INPUT_ELEMENT_DESC local_layout[] =
  333. {
  334. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  335. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  336. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  337. };
  338. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  339. return false;
  340. // Create the constant buffer
  341. {
  342. D3D11_BUFFER_DESC desc;
  343. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  344. desc.Usage = D3D11_USAGE_DYNAMIC;
  345. desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  346. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  347. desc.MiscFlags = 0;
  348. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  349. }
  350. }
  351. // Create the pixel shader
  352. {
  353. static const char* pixelShader =
  354. "struct PS_INPUT\
  355. {\
  356. float4 pos : SV_POSITION;\
  357. float4 col : COLOR0;\
  358. float2 uv : TEXCOORD0;\
  359. };\
  360. sampler sampler0;\
  361. Texture2D texture0;\
  362. \
  363. float4 main(PS_INPUT input) : SV_Target\
  364. {\
  365. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  366. return out_col; \
  367. }";
  368. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  369. 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!
  370. return false;
  371. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  372. return false;
  373. }
  374. // Create the blending setup
  375. {
  376. D3D11_BLEND_DESC desc;
  377. ZeroMemory(&desc, sizeof(desc));
  378. desc.AlphaToCoverageEnable = false;
  379. desc.RenderTarget[0].BlendEnable = true;
  380. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  381. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  382. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  383. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  384. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  385. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  386. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  387. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  388. }
  389. // Create the rasterizer state
  390. {
  391. D3D11_RASTERIZER_DESC desc;
  392. ZeroMemory(&desc, sizeof(desc));
  393. desc.FillMode = D3D11_FILL_SOLID;
  394. desc.CullMode = D3D11_CULL_NONE;
  395. desc.ScissorEnable = true;
  396. desc.DepthClipEnable = true;
  397. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  398. }
  399. // Create depth-stencil State
  400. {
  401. D3D11_DEPTH_STENCIL_DESC desc;
  402. ZeroMemory(&desc, sizeof(desc));
  403. desc.DepthEnable = false;
  404. desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  405. desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
  406. desc.StencilEnable = false;
  407. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  408. desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  409. desc.BackFace = desc.FrontFace;
  410. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  411. }
  412. ImGui_ImplDX11_CreateFontsTexture();
  413. return true;
  414. }
  415. void ImGui_ImplDX11_InvalidateDeviceObjects()
  416. {
  417. if (!g_pd3dDevice)
  418. return;
  419. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  420. 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.
  421. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  422. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  423. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  424. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  425. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  426. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  427. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  428. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  429. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  430. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  431. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  432. }
  433. bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
  434. {
  435. // Get factory from device
  436. IDXGIDevice* pDXGIDevice = NULL;
  437. IDXGIAdapter* pDXGIAdapter = NULL;
  438. IDXGIFactory1* pFactory = NULL;
  439. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) != S_OK)
  440. return false;
  441. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) != S_OK)
  442. return false;
  443. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) != S_OK)
  444. return false;
  445. g_pd3dDevice = device;
  446. g_pd3dDeviceContext = device_context;
  447. g_pFactory = pFactory;
  448. // Setup back-end capabilities flags
  449. ImGuiIO& io = ImGui::GetIO();
  450. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  451. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  452. ImGui_ImplDX11_InitPlatformInterface();
  453. return true;
  454. }
  455. void ImGui_ImplDX11_Shutdown()
  456. {
  457. ImGui_ImplDX11_ShutdownPlatformInterface();
  458. ImGui_ImplDX11_InvalidateDeviceObjects();
  459. g_pd3dDevice = NULL;
  460. g_pd3dDeviceContext = NULL;
  461. }
  462. void ImGui_ImplDX11_NewFrame()
  463. {
  464. if (!g_pFontSampler)
  465. ImGui_ImplDX11_CreateDeviceObjects();
  466. }
  467. //--------------------------------------------------------------------------------------------------------
  468. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  469. // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
  470. // 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..
  471. //--------------------------------------------------------------------------------------------------------
  472. struct ImGuiViewportDataDx11
  473. {
  474. IDXGISwapChain* SwapChain;
  475. ID3D11RenderTargetView* RTView;
  476. ImGuiViewportDataDx11() { SwapChain = NULL; RTView = NULL; }
  477. ~ImGuiViewportDataDx11() { IM_ASSERT(SwapChain == NULL && RTView == NULL); }
  478. };
  479. static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport)
  480. {
  481. ImGuiViewportDataDx11* data = IM_NEW(ImGuiViewportDataDx11)();
  482. viewport->RendererUserData = data;
  483. HWND hwnd = (HWND)viewport->PlatformHandle;
  484. IM_ASSERT(hwnd != 0);
  485. // Create swap chain
  486. DXGI_SWAP_CHAIN_DESC sd;
  487. ZeroMemory(&sd, sizeof(sd));
  488. sd.BufferDesc.Width = (UINT)viewport->Size.x;
  489. sd.BufferDesc.Height = (UINT)viewport->Size.y;
  490. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  491. sd.SampleDesc.Count = 1;
  492. sd.SampleDesc.Quality = 0;
  493. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  494. sd.BufferCount = 1;
  495. sd.OutputWindow = hwnd;
  496. sd.Windowed = TRUE;
  497. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  498. sd.Flags = 0;
  499. IM_ASSERT(data->SwapChain == NULL && data->RTView == NULL);
  500. g_pFactory->CreateSwapChain(g_pd3dDevice, &sd, &data->SwapChain);
  501. // Create the render target
  502. if (data->SwapChain)
  503. {
  504. ID3D11Texture2D* pBackBuffer;
  505. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  506. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  507. pBackBuffer->Release();
  508. }
  509. }
  510. static void ImGui_ImplDX11_DestroyWindow(ImGuiViewport* viewport)
  511. {
  512. // The main viewport (owned by the application) will always have RendererUserData == NULL since we didn't create the data for it.
  513. if (ImGuiViewportDataDx11* data = (ImGuiViewportDataDx11*)viewport->RendererUserData)
  514. {
  515. if (data->SwapChain)
  516. data->SwapChain->Release();
  517. data->SwapChain = NULL;
  518. if (data->RTView)
  519. data->RTView->Release();
  520. data->RTView = NULL;
  521. IM_DELETE(data);
  522. }
  523. viewport->RendererUserData = NULL;
  524. }
  525. static void ImGui_ImplDX11_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  526. {
  527. ImGuiViewportDataDx11* data = (ImGuiViewportDataDx11*)viewport->RendererUserData;
  528. if (data->RTView)
  529. {
  530. data->RTView->Release();
  531. data->RTView = NULL;
  532. }
  533. if (data->SwapChain)
  534. {
  535. ID3D11Texture2D* pBackBuffer = NULL;
  536. data->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
  537. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  538. if (pBackBuffer == NULL) { fprintf(stderr, "ImGui_ImplDX11_SetWindowSize() failed creating buffers.\n"); return; }
  539. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  540. pBackBuffer->Release();
  541. }
  542. }
  543. static void ImGui_ImplDX11_RenderWindow(ImGuiViewport* viewport, void*)
  544. {
  545. ImGuiViewportDataDx11* data = (ImGuiViewportDataDx11*)viewport->RendererUserData;
  546. ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  547. g_pd3dDeviceContext->OMSetRenderTargets(1, &data->RTView, NULL);
  548. if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
  549. g_pd3dDeviceContext->ClearRenderTargetView(data->RTView, (float*)&clear_color);
  550. ImGui_ImplDX11_RenderDrawData(viewport->DrawData);
  551. }
  552. static void ImGui_ImplDX11_SwapBuffers(ImGuiViewport* viewport, void*)
  553. {
  554. ImGuiViewportDataDx11* data = (ImGuiViewportDataDx11*)viewport->RendererUserData;
  555. data->SwapChain->Present(0, 0); // Present without vsync
  556. }
  557. static void ImGui_ImplDX11_InitPlatformInterface()
  558. {
  559. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  560. platform_io.Renderer_CreateWindow = ImGui_ImplDX11_CreateWindow;
  561. platform_io.Renderer_DestroyWindow = ImGui_ImplDX11_DestroyWindow;
  562. platform_io.Renderer_SetWindowSize = ImGui_ImplDX11_SetWindowSize;
  563. platform_io.Renderer_RenderWindow = ImGui_ImplDX11_RenderWindow;
  564. platform_io.Renderer_SwapBuffers = ImGui_ImplDX11_SwapBuffers;
  565. }
  566. static void ImGui_ImplDX11_ShutdownPlatformInterface()
  567. {
  568. ImGui::DestroyPlatformWindows();
  569. }