Debian Codegraph @

subprojects/imgui-1.91.6/backends/imgui_impl_dx11.cpp

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