42.8 KB、850行 生 Blame 履歴
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 texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
6// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
8// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
9// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
10
11// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
12// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
13// Learn about Dear ImGui:
14// - FAQ https://dearimgui.com/faq
15// - Getting Started https://dearimgui.com/getting-started
16// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
17// - Introduction, links and more at the top of imgui.cpp
18
19// CHANGELOG
20// (minor and older changes stripped away, please see git history for details)
21// 2026-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
22// 2026-04-23: DirectX11: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. Obsoleting samplers from ImGui_ImplDX11_RenderState. (#9378)
23// 2026-01-19: DirectX11: Added 'SamplerNearest' in ImGui_ImplDX11_RenderState. Renamed 'SamplerDefault' to 'SamplerLinear'.
24// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
25// 2025-06-11: DirectX11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
26// 2025-05-07: DirectX11: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
27// 2025-02-24: [Docking] Added undocumented ImGui_ImplDX11_SetSwapChainDescs() to configure swap chain creation for secondary viewports.
28// 2025-01-06: DirectX11: Expose VertexConstantBuffer in ImGui_ImplDX11_RenderState. Reset projection matrix in ImDrawCallback_ResetRenderState handler.
29// 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap.
30// 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.
31// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
32// 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).
33// 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
34// 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer.
35// 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled).
36// 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.
37// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
38// 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
39// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
40// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
41// 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
42// 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
43// 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
44// 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
45// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
46// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
47// 2016-05-07: DirectX11: Disabling depth-write.
48
49#include "imgui.h"
50#ifndef IMGUI_DISABLE
51#include "imgui_impl_dx11.h"
52
53// DirectX
54#include <stdio.h>
55#include <d3d11.h>
56#include <d3dcompiler.h>
57#ifdef _MSC_VER
58#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
59#endif
60
61// Clang/GCC warnings with -Weverything
62#if defined(__clang__)
63#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
64#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
65#endif
66
67// DirectX11 data
68struct ImGui_ImplDX11_Texture
69{
70 ID3D11Texture2D* pTexture;
71 ID3D11ShaderResourceView* pTextureView;
72};
73
74struct ImGui_ImplDX11_Data
75{
76 ID3D11Device* pd3dDevice;
77 ID3D11DeviceContext* pd3dDeviceContext;
78 IDXGIFactory* pFactory;
79 ID3D11Buffer* pVB;
80 ID3D11Buffer* pIB;
81 ID3D11VertexShader* pVertexShader;
82 ID3D11InputLayout* pInputLayout;
83 ID3D11Buffer* pVertexConstantBuffer;
84 ID3D11PixelShader* pPixelShader;
85 ID3D11SamplerState* pTexSamplerLinear;
86 ID3D11SamplerState* pTexSamplerNearest;
87 ID3D11RasterizerState* pRasterizerState;
88 ID3D11BlendState* pBlendState;
89 ID3D11DepthStencilState* pDepthStencilState;
90 int VertexBufferSize;
91 int IndexBufferSize;
92 ImGui_ImplDX11_RenderState* RenderState; // == (ImGui_ImplDX11_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState during rendering.
93 ImVector<DXGI_SWAP_CHAIN_DESC> SwapChainDescsForViewports;
94
95 ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
96};
97
98struct VERTEX_CONSTANT_BUFFER_DX11
99{
100 float mvp[4][4];
101};
102
103// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
104// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
105static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData()
106{
107 return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
108}
109
110// Forward Declarations
111static void ImGui_ImplDX11_InitMultiViewportSupport();
112static void ImGui_ImplDX11_ShutdownMultiViewportSupport();
113
114// Functions
115static void ImGui_ImplDX11_SetupRenderState(const ImDrawData* draw_data, ID3D11DeviceContext* device_ctx)
116{
117 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
118
119 // Setup viewport
120 D3D11_VIEWPORT vp = {};
121 vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
122 vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
123 vp.MinDepth = 0.0f;
124 vp.MaxDepth = 1.0f;
125 vp.TopLeftX = vp.TopLeftY = 0;
126 device_ctx->RSSetViewports(1, &vp);
127
128 // Setup orthographic projection matrix into our constant buffer
129 // 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.
130 D3D11_MAPPED_SUBRESOURCE mapped_resource;
131 if (device_ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK)
132 {
133 VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData;
134 float L = draw_data->DisplayPos.x;
135 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
136 float T = draw_data->DisplayPos.y;
137 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
138 float mvp[4][4] =
139 {
140 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
141 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
142 { 0.0f, 0.0f, 0.5f, 0.0f },
143 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
144 };
145 memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
146 device_ctx->Unmap(bd->pVertexConstantBuffer, 0);
147 }
148
149 // Setup shader and vertex buffers
150 unsigned int stride = sizeof(ImDrawVert);
151 unsigned int offset = 0;
152 device_ctx->IASetInputLayout(bd->pInputLayout);
153 device_ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
154 device_ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
155 device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
156 device_ctx->VSSetShader(bd->pVertexShader, nullptr, 0);
157 device_ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
158 device_ctx->PSSetShader(bd->pPixelShader, nullptr, 0);
159 device_ctx->PSSetSamplers(0, 1, &bd->pTexSamplerLinear);
160 device_ctx->GSSetShader(nullptr, nullptr, 0);
161 device_ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
162 device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
163 device_ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
164
165 // Setup render state
166 const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
167 device_ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
168 device_ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
169 device_ctx->RSSetState(bd->pRasterizerState);
170}
171
172// Draw callbacks
173static void ImGui_ImplDX11_DrawCallback_ResetRenderState(const ImDrawList*, const ImDrawCmd*) {} // Intentionally empty. Used as an identifier for rendering loop to call its code. Simpler to implement this way.
174static void ImGui_ImplDX11_DrawCallback_SetSamplerLinear(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); bd->RenderState->DeviceContext->PSSetSamplers(0, 1, &bd->pTexSamplerLinear); }
175static void ImGui_ImplDX11_DrawCallback_SetSamplerNearest(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); bd->RenderState->DeviceContext->PSSetSamplers(0, 1, &bd->pTexSamplerNearest); }
176
177// Render function
178void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
179{
180 // Avoid rendering when minimized
181 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
182 return;
183
184 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
185 ID3D11DeviceContext* device = bd->pd3dDeviceContext;
186
187 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
188 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
189 if (draw_data->Textures != nullptr)
190 for (ImTextureData* tex : *draw_data->Textures)
191 if (tex->Status != ImTextureStatus_OK)
192 ImGui_ImplDX11_UpdateTexture(tex);
193
194 // Create and grow vertex/index buffers if needed
195 if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
196 {
197 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
198 bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
199 D3D11_BUFFER_DESC desc = {};
200 desc.Usage = D3D11_USAGE_DYNAMIC;
201 desc.ByteWidth = (UINT)bd->VertexBufferSize * sizeof(ImDrawVert);
202 desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
203 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
204 desc.MiscFlags = 0;
205 if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
206 return;
207 }
208 if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
209 {
210 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
211 bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
212 D3D11_BUFFER_DESC desc = {};
213 desc.Usage = D3D11_USAGE_DYNAMIC;
214 desc.ByteWidth = (UINT)bd->IndexBufferSize * sizeof(ImDrawIdx);
215 desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
216 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
217 if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
218 return;
219 }
220
221 // Upload vertex/index data into a single contiguous GPU buffer
222 D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
223 if (device->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
224 return;
225 if (device->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
226 return;
227 ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
228 ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
229 for (const ImDrawList* draw_list : draw_data->CmdLists)
230 {
231 memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
232 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
233 vtx_dst += draw_list->VtxBuffer.Size;
234 idx_dst += draw_list->IdxBuffer.Size;
235 }
236 device->Unmap(bd->pVB, 0);
237 device->Unmap(bd->pIB, 0);
238
239 // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
240 struct BACKUP_DX11_STATE
241 {
242 UINT ScissorRectsCount, ViewportsCount;
243 D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
244 D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
245 ID3D11RasterizerState* RS;
246 ID3D11BlendState* BlendState;
247 FLOAT BlendFactor[4];
248 UINT SampleMask;
249 UINT StencilRef;
250 ID3D11DepthStencilState* DepthStencilState;
251 ID3D11ShaderResourceView* PSShaderResource;
252 ID3D11SamplerState* PSSampler;
253 ID3D11PixelShader* PS;
254 ID3D11VertexShader* VS;
255 ID3D11GeometryShader* GS;
256 UINT PSInstancesCount, VSInstancesCount, GSInstancesCount;
257 ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation
258 D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
259 ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
260 UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
261 DXGI_FORMAT IndexBufferFormat;
262 ID3D11InputLayout* InputLayout;
263 };
264 BACKUP_DX11_STATE old = {};
265 old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
266 device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
267 device->RSGetViewports(&old.ViewportsCount, old.Viewports);
268 device->RSGetState(&old.RS);
269 device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
270 device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
271 device->PSGetShaderResources(0, 1, &old.PSShaderResource);
272 device->PSGetSamplers(0, 1, &old.PSSampler);
273 old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
274 device->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
275 device->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
276 device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
277 device->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
278
279 device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
280 device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
281 device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
282 device->IAGetInputLayout(&old.InputLayout);
283
284 // Setup desired DX state
285 ImGui_ImplDX11_SetupRenderState(draw_data, device);
286
287 // Setup render state structure (for callbacks and custom texture bindings)
288 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
289 ImGui_ImplDX11_RenderState render_state;
290 render_state.Device = bd->pd3dDevice;
291 render_state.DeviceContext = bd->pd3dDeviceContext;
292 render_state.VertexConstantBuffer = bd->pVertexConstantBuffer;
293 platform_io.Renderer_RenderState = bd->RenderState = &render_state;
294
295 // Render command lists
296 // (Because we merged all buffers into a single one, we maintain our own offset into them)
297 int global_idx_offset = 0;
298 int global_vtx_offset = 0;
299 ImVec2 clip_off = draw_data->DisplayPos;
300 ImVec2 clip_scale = draw_data->FramebufferScale;
301 for (const ImDrawList* draw_list : draw_data->CmdLists)
302 {
303 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
304 {
305 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
306 if (pcmd->UserCallback != nullptr)
307 {
308 // User callback, registered via ImDrawList::AddCallback()
309 if (pcmd->UserCallback == ImGui_ImplDX11_DrawCallback_ResetRenderState)
310 ImGui_ImplDX11_SetupRenderState(draw_data, device);
311 else
312 pcmd->UserCallback(draw_list, pcmd);
313 }
314 else
315 {
316 // Project scissor/clipping rectangles into framebuffer space
317 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
318 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
319 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
320 continue;
321
322 // Apply scissor/clipping rectangle
323 const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
324 device->RSSetScissorRects(1, &r);
325
326 // Bind texture, Draw
327 ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID();
328 device->PSSetShaderResources(0, 1, &texture_srv);
329 device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
330 }
331 }
332 global_idx_offset += draw_list->IdxBuffer.Size;
333 global_vtx_offset += draw_list->VtxBuffer.Size;
334 }
335 platform_io.Renderer_RenderState = bd->RenderState = nullptr;
336
337 // Restore modified DX state
338 device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
339 device->RSSetViewports(old.ViewportsCount, old.Viewports);
340 device->RSSetState(old.RS); if (old.RS) old.RS->Release();
341 device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
342 device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
343 device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
344 device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
345 device->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
346 for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
347 device->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
348 device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
349 device->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
350 for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
351 device->IASetPrimitiveTopology(old.PrimitiveTopology);
352 device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
353 device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
354 device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
355}
356
357static void ImGui_ImplDX11_DestroyTexture(ImTextureData* tex)
358{
359 if (ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData)
360 {
361 IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID);
362 backend_tex->pTextureView->Release();
363 backend_tex->pTexture->Release();
364 IM_DELETE(backend_tex);
365
366 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
367 tex->SetTexID(ImTextureID_Invalid);
368 tex->BackendUserData = nullptr;
369 }
370 tex->SetStatus(ImTextureStatus_Destroyed);
371}
372
373void ImGui_ImplDX11_UpdateTexture(ImTextureData* tex)
374{
375 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
376 if (tex->Status == ImTextureStatus_WantCreate)
377 {
378 // Create and upload new texture to graphics system
379 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
380 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
381 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
382 unsigned int* pixels = (unsigned int*)tex->GetPixels();
383 ImGui_ImplDX11_Texture* backend_tex = IM_NEW(ImGui_ImplDX11_Texture)();
384
385 // Create texture
386 D3D11_TEXTURE2D_DESC desc;
387 ZeroMemory(&desc, sizeof(desc));
388 desc.Width = (UINT)tex->Width;
389 desc.Height = (UINT)tex->Height;
390 desc.MipLevels = 1;
391 desc.ArraySize = 1;
392 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
393 desc.SampleDesc.Count = 1;
394 desc.Usage = D3D11_USAGE_DEFAULT;
395 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
396 desc.CPUAccessFlags = 0;
397 D3D11_SUBRESOURCE_DATA subResource;
398 subResource.pSysMem = pixels;
399 subResource.SysMemPitch = desc.Width * 4;
400 subResource.SysMemSlicePitch = 0;
401 bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture);
402 IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!");
403
404 // Create texture view
405 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
406 ZeroMemory(&srvDesc, sizeof(srvDesc));
407 srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
408 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
409 srvDesc.Texture2D.MipLevels = desc.MipLevels;
410 srvDesc.Texture2D.MostDetailedMip = 0;
411 bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srvDesc, &backend_tex->pTextureView);
412 IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!");
413
414 // Store identifiers
415 tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView);
416 tex->SetStatus(ImTextureStatus_OK);
417 tex->BackendUserData = backend_tex;
418 }
419 else if (tex->Status == ImTextureStatus_WantUpdates)
420 {
421 // Update selected blocks. We only ever write to textures regions which have never been used before!
422 // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
423 ImGui_ImplDX11_Texture* backend_tex = (ImGui_ImplDX11_Texture*)tex->BackendUserData;
424 IM_ASSERT(backend_tex->pTextureView == (ID3D11ShaderResourceView*)(intptr_t)tex->TexID);
425 for (ImTextureRect& r : tex->Updates)
426 {
427 D3D11_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r .h), (UINT)1 };
428 bd->pd3dDeviceContext->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0);
429 }
430 tex->SetStatus(ImTextureStatus_OK);
431 }
432 if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
433 ImGui_ImplDX11_DestroyTexture(tex);
434}
435
436bool ImGui_ImplDX11_CreateDeviceObjects()
437{
438 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
439 if (!bd->pd3dDevice)
440 return false;
441 ImGui_ImplDX11_InvalidateDeviceObjects();
442
443 // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
444 // If you would like to use this DX11 sample code but remove this dependency you can:
445 // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
446 // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
447 // See https://github.com/ocornut/imgui/pull/638 for sources and details.
448
449 // Create the vertex shader
450 {
451 static const char* vertexShader =
452 "cbuffer vertexBuffer : register(b0) \
453 {\
454 float4x4 ProjectionMatrix; \
455 };\
456 struct VS_INPUT\
457 {\
458 float2 pos : POSITION;\
459 float4 col : COLOR0;\
460 float2 uv : TEXCOORD0;\
461 };\
462 \
463 struct PS_INPUT\
464 {\
465 float4 pos : SV_POSITION;\
466 float4 col : COLOR0;\
467 float2 uv : TEXCOORD0;\
468 };\
469 \
470 PS_INPUT main(VS_INPUT input)\
471 {\
472 PS_INPUT output;\
473 output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
474 output.col = input.col;\
475 output.uv = input.uv;\
476 return output;\
477 }";
478
479 ID3DBlob* vertexShaderBlob;
480 if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
481 return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
482 if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK)
483 {
484 vertexShaderBlob->Release();
485 return false;
486 }
487
488 // Create the input layout
489 D3D11_INPUT_ELEMENT_DESC local_layout[] =
490 {
491 { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
492 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
493 { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
494 };
495 if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
496 {
497 vertexShaderBlob->Release();
498 return false;
499 }
500 vertexShaderBlob->Release();
501
502 // Create the constant buffer
503 {
504 D3D11_BUFFER_DESC desc = {};
505 desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11);
506 desc.Usage = D3D11_USAGE_DYNAMIC;
507 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
508 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
509 desc.MiscFlags = 0;
510 bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
511 }
512 }
513
514 // Create the pixel shader
515 {
516 static const char* pixelShader =
517 "struct PS_INPUT\
518 {\
519 float4 pos : SV_POSITION;\
520 float4 col : COLOR0;\
521 float2 uv : TEXCOORD0;\
522 };\
523 sampler sampler0;\
524 Texture2D texture0;\
525 \
526 float4 main(PS_INPUT input) : SV_Target\
527 {\
528 float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
529 return out_col; \
530 }";
531
532 ID3DBlob* pixelShaderBlob;
533 if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
534 return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
535 if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK)
536 {
537 pixelShaderBlob->Release();
538 return false;
539 }
540 pixelShaderBlob->Release();
541 }
542
543 // Create the blending setup
544 {
545 D3D11_BLEND_DESC desc;
546 ZeroMemory(&desc, sizeof(desc));
547 desc.AlphaToCoverageEnable = false;
548 desc.RenderTarget[0].BlendEnable = true;
549 desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
550 desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
551 desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
552 desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
553 desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
554 desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
555 desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
556 bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
557 }
558
559 // Create the rasterizer state
560 {
561 D3D11_RASTERIZER_DESC desc;
562 ZeroMemory(&desc, sizeof(desc));
563 desc.FillMode = D3D11_FILL_SOLID;
564 desc.CullMode = D3D11_CULL_NONE;
565 desc.ScissorEnable = true;
566 desc.DepthClipEnable = true;
567 bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
568 }
569
570 // Create depth-stencil State
571 {
572 D3D11_DEPTH_STENCIL_DESC desc;
573 ZeroMemory(&desc, sizeof(desc));
574 desc.DepthEnable = false;
575 desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
576 desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
577 desc.StencilEnable = false;
578 desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
579 desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
580 desc.BackFace = desc.FrontFace;
581 bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
582 }
583
584 // Create texture sampler
585 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
586 {
587 D3D11_SAMPLER_DESC desc;
588 ZeroMemory(&desc, sizeof(desc));
589 desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
590 desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
591 desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
592 desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
593 desc.MipLODBias = 0.f;
594 desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
595 desc.MinLOD = 0.f;
596 desc.MaxLOD = 0.f;
597 bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear);
598 desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
599 bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerNearest);
600 }
601
602 return true;
603}
604
605void ImGui_ImplDX11_InvalidateDeviceObjects()
606{
607 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
608 if (!bd->pd3dDevice)
609 return;
610
611 // Destroy all textures
612 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
613 if (tex->RefCount == 1)
614 ImGui_ImplDX11_DestroyTexture(tex);
615
616 if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; }
617 if (bd->pTexSamplerNearest) { bd->pTexSamplerNearest->Release(); bd->pTexSamplerNearest = nullptr; }
618 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
619 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
620 if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
621 if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
622 if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
623 if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
624 if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
625 if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
626 if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
627}
628
629bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
630{
631 ImGuiIO& io = ImGui::GetIO();
632 IMGUI_CHECKVERSION();
633 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
634
635 // Setup backend capabilities flags
636 ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)();
637 io.BackendRendererUserData = (void*)bd;
638 io.BackendRendererName = "imgui_impl_dx11";
639 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
640 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
641 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
642
643 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
644 platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
645 platform_io.DrawCallback_ResetRenderState = ImGui_ImplDX11_DrawCallback_ResetRenderState;
646 platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplDX11_DrawCallback_SetSamplerLinear;
647 platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplDX11_DrawCallback_SetSamplerNearest;
648
649 // Get factory from device
650 IDXGIDevice* pDXGIDevice = nullptr;
651 IDXGIAdapter* pDXGIAdapter = nullptr;
652 IDXGIFactory* pFactory = nullptr;
653
654 if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
655 if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
656 if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
657 {
658 bd->pd3dDevice = device;
659 bd->pd3dDeviceContext = device_context;
660 bd->pFactory = pFactory;
661 }
662 if (pDXGIDevice) pDXGIDevice->Release();
663 if (pDXGIAdapter) pDXGIAdapter->Release();
664 bd->pd3dDevice->AddRef();
665 bd->pd3dDeviceContext->AddRef();
666
667 ImGui_ImplDX11_InitMultiViewportSupport();
668
669 return true;
670}
671
672void ImGui_ImplDX11_Shutdown()
673{
674 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
675 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
676 ImGuiIO& io = ImGui::GetIO();
677 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
678
679 ImGui_ImplDX11_ShutdownMultiViewportSupport();
680 ImGui_ImplDX11_InvalidateDeviceObjects();
681 if (bd->pFactory) { bd->pFactory->Release(); }
682 if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
683 if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); }
684
685 io.BackendRendererName = nullptr;
686 io.BackendRendererUserData = nullptr;
687 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
688 platform_io.ClearRendererHandlers();
689 IM_DELETE(bd);
690}
691
692void ImGui_ImplDX11_NewFrame()
693{
694 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
695 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?");
696
697 if (!bd->pVertexShader)
698 if (!ImGui_ImplDX11_CreateDeviceObjects())
699 IM_ASSERT(0 && "ImGui_ImplDX11_CreateDeviceObjects() failed!");
700}
701
702//--------------------------------------------------------------------------------------------------------
703// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
704// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
705// 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..
706//--------------------------------------------------------------------------------------------------------
707
708// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
709struct ImGui_ImplDX11_ViewportData
710{
711 IDXGISwapChain* SwapChain;
712 ID3D11RenderTargetView* RTView;
713
714 ImGui_ImplDX11_ViewportData() { SwapChain = nullptr; RTView = nullptr; }
715 ~ImGui_ImplDX11_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); }
716};
717
718// Multi-Viewports: configure templates used when creating swapchains for secondary viewports. Will try them in order.
719// This is intentionally not declared in the .h file yet, so you will need to copy this declaration:
720void ImGui_ImplDX11_SetSwapChainDescs(const DXGI_SWAP_CHAIN_DESC* desc_templates, int desc_templates_count);
721void ImGui_ImplDX11_SetSwapChainDescs(const DXGI_SWAP_CHAIN_DESC* desc_templates, int desc_templates_count)
722{
723 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
724 bd->SwapChainDescsForViewports.resize(desc_templates_count);
725 memcpy(bd->SwapChainDescsForViewports.Data, desc_templates, sizeof(DXGI_SWAP_CHAIN_DESC));
726}
727
728static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport)
729{
730 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
731 ImGui_ImplDX11_ViewportData* vd = IM_NEW(ImGui_ImplDX11_ViewportData)();
732 viewport->RendererUserData = vd;
733
734 // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL's WindowID).
735 // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
736 HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
737 IM_ASSERT(hwnd != 0);
738 IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr);
739
740 // Create swap chain
741 HRESULT hr = DXGI_ERROR_UNSUPPORTED;
742 for (const DXGI_SWAP_CHAIN_DESC& sd_template : bd->SwapChainDescsForViewports)
743 {
744 IM_ASSERT(sd_template.BufferDesc.Width == 0 && sd_template.BufferDesc.Height == 0 && sd_template.OutputWindow == nullptr);
745 DXGI_SWAP_CHAIN_DESC sd = sd_template;
746 sd.BufferDesc.Width = (UINT)viewport->Size.x;
747 sd.BufferDesc.Height = (UINT)viewport->Size.y;
748 sd.OutputWindow = hwnd;
749 hr = bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain);
750 if (SUCCEEDED(hr))
751 break;
752 }
753 IM_ASSERT(SUCCEEDED(hr));
754 bd->pFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); // Disable e.g. Alt+Enter
755
756 // Create the render target
757 if (vd->SwapChain != nullptr)
758 {
759 ID3D11Texture2D* pBackBuffer;
760 vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
761 bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
762 pBackBuffer->Release();
763 }
764}
765
766static void ImGui_ImplDX11_DestroyWindow(ImGuiViewport* viewport)
767{
768 // The main viewport (owned by the application) will always have RendererUserData == nullptr since we didn't create the data for it.
769 if (ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData)
770 {
771 if (vd->SwapChain)
772 vd->SwapChain->Release();
773 vd->SwapChain = nullptr;
774 if (vd->RTView)
775 vd->RTView->Release();
776 vd->RTView = nullptr;
777 IM_DELETE(vd);
778 }
779 viewport->RendererUserData = nullptr;
780}
781
782static void ImGui_ImplDX11_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
783{
784 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
785 ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
786 if (vd->RTView)
787 {
788 vd->RTView->Release();
789 vd->RTView = nullptr;
790 }
791 if (vd->SwapChain)
792 {
793 ID3D11Texture2D* pBackBuffer = nullptr;
794 vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
795 vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
796 if (pBackBuffer == nullptr) { fprintf(stderr, "ImGui_ImplDX11_SetWindowSize() failed creating buffers.\n"); return; }
797 bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
798 pBackBuffer->Release();
799 }
800}
801
802static void ImGui_ImplDX11_RenderWindow(ImGuiViewport* viewport, void*)
803{
804 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
805 ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
806 ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
807 bd->pd3dDeviceContext->OMSetRenderTargets(1, &vd->RTView, nullptr);
808 if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
809 bd->pd3dDeviceContext->ClearRenderTargetView(vd->RTView, (float*)&clear_color);
810 ImGui_ImplDX11_RenderDrawData(viewport->DrawData);
811}
812
813static void ImGui_ImplDX11_SwapBuffers(ImGuiViewport* viewport, void*)
814{
815 ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
816 if (vd->SwapChain)
817 vd->SwapChain->Present(0, 0); // Present without vsync
818}
819
820static void ImGui_ImplDX11_InitMultiViewportSupport()
821{
822 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
823 platform_io.Renderer_CreateWindow = ImGui_ImplDX11_CreateWindow;
824 platform_io.Renderer_DestroyWindow = ImGui_ImplDX11_DestroyWindow;
825 platform_io.Renderer_SetWindowSize = ImGui_ImplDX11_SetWindowSize;
826 platform_io.Renderer_RenderWindow = ImGui_ImplDX11_RenderWindow;
827 platform_io.Renderer_SwapBuffers = ImGui_ImplDX11_SwapBuffers;
828
829 // Default swapchain format
830 DXGI_SWAP_CHAIN_DESC sd;
831 ZeroMemory(&sd, sizeof(sd));
832 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
833 sd.SampleDesc.Count = 1;
834 sd.SampleDesc.Quality = 0;
835 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
836 sd.BufferCount = 1;
837 sd.Windowed = TRUE;
838 sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
839 sd.Flags = 0;
840 ImGui_ImplDX11_SetSwapChainDescs(&sd, 1);
841}
842
843static void ImGui_ImplDX11_ShutdownMultiViewportSupport()
844{
845 ImGui::DestroyPlatformWindows();
846}
847
848//-----------------------------------------------------------------------------
849
850#endif // #ifndef IMGUI_DISABLE