31.4 KB、651行 生 Blame 履歴
1// dear imgui: Renderer Backend for DirectX9
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 'LPDIRECT3DTEXTURE9' 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: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
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: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378)
23// 2026-03-19: Fixed issue in ImGui_ImplDX9_UpdateTexture() if ImTextureID_Invalid is defined to be != 0, which became the default since 2026-03-12. (#9295, #9310)
24// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
25// 2025-06-11: DirectX9: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
26// 2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap.
27// 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575)
28// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
29// 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).
30// 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
31// 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
32// 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states.
33// 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857).
34// 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file.
35// 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer.
36// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
37// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
38// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
39// 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
40// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
41// 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
42// 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
43// 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
44// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
45// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
46
47#include "imgui.h"
48#ifndef IMGUI_DISABLE
49#include "imgui_impl_dx9.h"
50
51// DirectX
52#include <d3d9.h>
53
54// Clang/GCC warnings with -Weverything
55#if defined(__clang__)
56#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
57#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
58#endif
59
60// DirectX data
61struct ImGui_ImplDX9_Data
62{
63 LPDIRECT3DDEVICE9 pd3dDevice;
64 LPDIRECT3DVERTEXBUFFER9 pVB;
65 LPDIRECT3DINDEXBUFFER9 pIB;
66 int VertexBufferSize;
67 int IndexBufferSize;
68 bool HasRgbaSupport;
69
70 ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
71};
72
73struct CUSTOMVERTEX
74{
75 float pos[3];
76 D3DCOLOR col;
77 float uv[2];
78};
79#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
80
81#ifdef IMGUI_USE_BGRA_PACKED_COLOR
82#define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL)
83#else
84#define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16))
85#endif
86
87// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
88// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
89static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData()
90{
91 return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
92}
93
94// Forward Declarations
95static void ImGui_ImplDX9_InitMultiViewportSupport();
96static void ImGui_ImplDX9_ShutdownMultiViewportSupport();
97static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
98static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
99
100// Functions
101static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
102{
103 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
104
105 // Setup viewport
106 D3DVIEWPORT9 vp;
107 vp.X = vp.Y = 0;
108 vp.Width = (DWORD)draw_data->DisplaySize.x;
109 vp.Height = (DWORD)draw_data->DisplaySize.y;
110 vp.MinZ = 0.0f;
111 vp.MaxZ = 1.0f;
112
113 LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
114 device->SetViewport(&vp);
115
116 // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling.
117 device->SetPixelShader(nullptr);
118 device->SetVertexShader(nullptr);
119 device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
120 device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
121 device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
122 device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
123 device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
124 device->SetRenderState(D3DRS_ZENABLE, FALSE);
125 device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
126 device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
127 device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
128 device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
129 device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
130 device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
131 device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
132 device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
133 device->SetRenderState(D3DRS_FOGENABLE, FALSE);
134 device->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
135 device->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
136 device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
137 device->SetRenderState(D3DRS_CLIPPING, TRUE);
138 device->SetRenderState(D3DRS_LIGHTING, FALSE);
139 device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
140 device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
141 device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
142 device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
143 device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
144 device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
145 device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
146 device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
147 device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
148 device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
149 device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
150 device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
151
152 // Setup orthographic projection matrix
153 // 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.
154 // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
155 {
156 float L = draw_data->DisplayPos.x + 0.5f;
157 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
158 float T = draw_data->DisplayPos.y + 0.5f;
159 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
160 D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } };
161 D3DMATRIX mat_projection =
162 { { {
163 2.0f/(R-L), 0.0f, 0.0f, 0.0f,
164 0.0f, 2.0f/(T-B), 0.0f, 0.0f,
165 0.0f, 0.0f, 0.5f, 0.0f,
166 (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f
167 } } };
168 device->SetTransform(D3DTS_WORLD, &mat_identity);
169 device->SetTransform(D3DTS_VIEW, &mat_identity);
170 device->SetTransform(D3DTS_PROJECTION, &mat_projection);
171 }
172}
173
174// Draw callbacks
175static void ImGui_ImplDX9_DrawCallback_ResetRenderState(const ImDrawList*, const ImDrawCmd*) {} // Intentionally empty. Used as an identifier for rendering loop to call its code. Simpler to implement this way.
176static void ImGui_ImplDX9_DrawCallback_SetSamplerLinear(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); }
177static void ImGui_ImplDX9_DrawCallback_SetSamplerNearest(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); }
178
179// Render function.
180void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
181{
182 // Avoid rendering when minimized
183 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
184 return;
185
186 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
187 LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
188
189 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
190 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
191 if (draw_data->Textures != nullptr)
192 for (ImTextureData* tex : *draw_data->Textures)
193 if (tex->Status != ImTextureStatus_OK)
194 ImGui_ImplDX9_UpdateTexture(tex);
195
196 // Create and grow buffers if needed
197 if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
198 {
199 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
200 bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
201 if (device->CreateVertexBuffer((UINT)bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
202 return;
203 }
204 if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
205 {
206 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
207 bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
208 if (device->CreateIndexBuffer((UINT)bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0)
209 return;
210 }
211
212 // Backup the DX9 state
213 IDirect3DStateBlock9* state_block = nullptr;
214 if (device->CreateStateBlock(D3DSBT_ALL, &state_block) < 0)
215 return;
216 if (state_block->Capture() < 0)
217 {
218 state_block->Release();
219 return;
220 }
221
222 // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
223 D3DMATRIX last_world, last_view, last_projection;
224 device->GetTransform(D3DTS_WORLD, &last_world);
225 device->GetTransform(D3DTS_VIEW, &last_view);
226 device->GetTransform(D3DTS_PROJECTION, &last_projection);
227
228 // Allocate buffers
229 CUSTOMVERTEX* vtx_dst;
230 ImDrawIdx* idx_dst;
231 if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
232 {
233 state_block->Release();
234 return;
235 }
236 if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
237 {
238 bd->pVB->Unlock();
239 state_block->Release();
240 return;
241 }
242
243 // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
244 // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and
245 // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
246 // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
247 for (const ImDrawList* draw_list : draw_data->CmdLists)
248 {
249 const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data;
250 for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
251 {
252 vtx_dst->pos[0] = vtx_src->pos.x;
253 vtx_dst->pos[1] = vtx_src->pos.y;
254 vtx_dst->pos[2] = 0.0f;
255 vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col);
256 vtx_dst->uv[0] = vtx_src->uv.x;
257 vtx_dst->uv[1] = vtx_src->uv.y;
258 vtx_dst++;
259 vtx_src++;
260 }
261 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
262 idx_dst += draw_list->IdxBuffer.Size;
263 }
264 bd->pVB->Unlock();
265 bd->pIB->Unlock();
266 device->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
267 device->SetIndices(bd->pIB);
268 device->SetFVF(D3DFVF_CUSTOMVERTEX);
269
270 // Setup desired DX state
271 ImGui_ImplDX9_SetupRenderState(draw_data);
272
273 // Render command lists
274 // (Because we merged all buffers into a single one, we maintain our own offset into them)
275 int global_vtx_offset = 0;
276 int global_idx_offset = 0;
277 ImVec2 clip_off = draw_data->DisplayPos;
278 for (const ImDrawList* draw_list : draw_data->CmdLists)
279 {
280 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
281 {
282 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
283 if (pcmd->UserCallback != nullptr)
284 {
285 // User callback, registered via ImDrawList::AddCallback()
286 if (pcmd->UserCallback == ImGui_ImplDX9_DrawCallback_ResetRenderState)
287 ImGui_ImplDX9_SetupRenderState(draw_data);
288 else
289 pcmd->UserCallback(draw_list, pcmd);
290 }
291 else
292 {
293 // Project scissor/clipping rectangles into framebuffer space
294 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
295 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
296 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
297 continue;
298
299 // Apply scissor/clipping rectangle
300 const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
301 device->SetScissorRect(&r);
302
303 // Bind texture, Draw
304 const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
305 device->SetTexture(0, texture);
306 device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)draw_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
307 }
308 }
309 global_idx_offset += draw_list->IdxBuffer.Size;
310 global_vtx_offset += draw_list->VtxBuffer.Size;
311 }
312
313 // When using multi-viewports, it appears that there's an odd logic in DirectX9 which prevent subsequent windows
314 // from rendering until the first window submits at least one draw call, even once. That's our workaround. (see #2560)
315 if (global_vtx_offset == 0)
316 bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 0, 0, 0);
317
318 // Restore the DX9 transform
319 device->SetTransform(D3DTS_WORLD, &last_world);
320 device->SetTransform(D3DTS_VIEW, &last_view);
321 device->SetTransform(D3DTS_PROJECTION, &last_projection);
322
323 // Restore the DX9 state
324 state_block->Apply();
325 state_block->Release();
326}
327
328static bool ImGui_ImplDX9_CheckFormatSupport(LPDIRECT3DDEVICE9 pDevice, D3DFORMAT format)
329{
330 LPDIRECT3D9 pd3d = nullptr;
331 if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
332 return false;
333 D3DDEVICE_CREATION_PARAMETERS param = {};
334 D3DDISPLAYMODE mode = {};
335 if (pDevice->GetCreationParameters(&param) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
336 {
337 pd3d->Release();
338 return false;
339 }
340 // Font texture should support linear filter, color blend and write to render-target
341 bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
342 pd3d->Release();
343 return support;
344}
345
346// Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
347static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, const ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h)
348{
349#ifndef IMGUI_USE_BGRA_PACKED_COLOR
350 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
351 const bool convert_rgba_to_bgra = (!bd->HasRgbaSupport && tex_use_colors);
352#else
353 const bool convert_rgba_to_bgra = false;
354 IM_UNUSED(tex_use_colors);
355#endif
356 for (int y = 0; y < h; y++)
357 {
358 const ImU32* src_p = (const ImU32*)(const void*)((const unsigned char*)src + src_pitch * y);
359 ImU32* dst_p = (ImU32*)(void*)((unsigned char*)dst + dst_pitch * y);
360 if (convert_rgba_to_bgra)
361 for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy
362 *dst_p = IMGUI_COL_TO_DX9_ARGB(*src_p);
363 else
364 memcpy(dst_p, src_p, w * 4); // Raw copy
365 }
366}
367
368void ImGui_ImplDX9_UpdateTexture(ImTextureData* tex)
369{
370 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
371
372 if (tex->Status == ImTextureStatus_WantCreate)
373 {
374 // Create and upload new texture to graphics system
375 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
376 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
377 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
378 LPDIRECT3DTEXTURE9 dx_tex = nullptr;
379 HRESULT hr = bd->pd3dDevice->CreateTexture(tex->Width, tex->Height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &dx_tex, nullptr);
380 if (hr < 0)
381 {
382 IM_ASSERT(hr >= 0 && "Backend failed to create texture!");
383 return;
384 }
385
386 D3DLOCKED_RECT locked_rect;
387 if (dx_tex->LockRect(0, &locked_rect, nullptr, 0) == D3D_OK)
388 {
389 ImGui_ImplDX9_CopyTextureRegion(tex->UseColors, (ImU32*)tex->GetPixels(), tex->Width * 4, (ImU32*)locked_rect.pBits, (ImU32)locked_rect.Pitch, tex->Width, tex->Height);
390 dx_tex->UnlockRect(0);
391 }
392
393 // Store identifiers
394 tex->SetTexID((ImTextureID)(intptr_t)dx_tex);
395 tex->SetStatus(ImTextureStatus_OK);
396 }
397 else if (tex->Status == ImTextureStatus_WantUpdates)
398 {
399 // Update selected blocks. We only ever write to textures regions which have never been used before!
400 // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
401 LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)(intptr_t)tex->TexID;
402 RECT update_rect = { (LONG)tex->UpdateRect.x, (LONG)tex->UpdateRect.y, (LONG)(tex->UpdateRect.x + tex->UpdateRect.w), (LONG)(tex->UpdateRect.y + tex->UpdateRect.h) };
403 D3DLOCKED_RECT locked_rect;
404 if (backend_tex->LockRect(0, &locked_rect, &update_rect, 0) == D3D_OK)
405 for (ImTextureRect& r : tex->Updates)
406 ImGui_ImplDX9_CopyTextureRegion(tex->UseColors, (ImU32*)tex->GetPixelsAt(r.x, r.y), tex->Width * 4,
407 (ImU32*)locked_rect.pBits + (r.x - update_rect.left) + (r.y - update_rect.top) * (locked_rect.Pitch / 4), (int)locked_rect.Pitch, r.w, r.h);
408 backend_tex->UnlockRect(0);
409 tex->SetStatus(ImTextureStatus_OK);
410 }
411 else if (tex->Status == ImTextureStatus_WantDestroy)
412 {
413 if (tex->TexID != ImTextureID_Invalid)
414 if (LPDIRECT3DTEXTURE9 backend_tex = (LPDIRECT3DTEXTURE9)tex->TexID)
415 {
416 IM_ASSERT(tex->TexID == (ImTextureID)(intptr_t)backend_tex);
417 backend_tex->Release();
418
419 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
420 tex->SetTexID(ImTextureID_Invalid);
421 }
422 tex->SetStatus(ImTextureStatus_Destroyed);
423 }
424}
425
426bool ImGui_ImplDX9_CreateDeviceObjects()
427{
428 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
429 if (!bd || !bd->pd3dDevice)
430 return false;
431 ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
432 return true;
433}
434
435void ImGui_ImplDX9_InvalidateDeviceObjects()
436{
437 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
438 if (!bd || !bd->pd3dDevice)
439 return;
440
441 // Destroy all textures
442 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
443 if (tex->RefCount == 1)
444 {
445 tex->SetStatus(ImTextureStatus_WantDestroy);
446 ImGui_ImplDX9_UpdateTexture(tex);
447 }
448 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
449 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
450 ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
451}
452
453void ImGui_ImplDX9_NewFrame()
454{
455 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
456 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?");
457 IM_UNUSED(bd);
458}
459
460bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
461{
462 ImGuiIO& io = ImGui::GetIO();
463 IMGUI_CHECKVERSION();
464 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
465
466 // Setup backend capabilities flags
467 ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)();
468 io.BackendRendererUserData = (void*)bd;
469 io.BackendRendererName = "imgui_impl_dx9";
470 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
471 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
472 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
473
474 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
475 platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = 4096;
476 platform_io.DrawCallback_ResetRenderState = ImGui_ImplDX9_DrawCallback_ResetRenderState;
477 platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplDX9_DrawCallback_SetSamplerLinear;
478 platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplDX9_DrawCallback_SetSamplerNearest;
479
480 bd->pd3dDevice = device;
481 bd->pd3dDevice->AddRef();
482 bd->HasRgbaSupport = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8);
483
484 ImGui_ImplDX9_InitMultiViewportSupport();
485
486 return true;
487}
488
489void ImGui_ImplDX9_Shutdown()
490{
491 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
492 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
493 ImGuiIO& io = ImGui::GetIO();
494 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
495
496 ImGui_ImplDX9_ShutdownMultiViewportSupport();
497 ImGui_ImplDX9_InvalidateDeviceObjects();
498 if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
499
500 io.BackendRendererName = nullptr;
501 io.BackendRendererUserData = nullptr;
502 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
503 platform_io.ClearRendererHandlers();
504 IM_DELETE(bd);
505}
506
507//--------------------------------------------------------------------------------------------------------
508// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
509// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
510// 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..
511//--------------------------------------------------------------------------------------------------------
512
513// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
514struct ImGui_ImplDX9_ViewportData
515{
516 IDirect3DSwapChain9* SwapChain;
517 D3DPRESENT_PARAMETERS d3dpp;
518
519 ImGui_ImplDX9_ViewportData() { SwapChain = nullptr; ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); }
520 ~ImGui_ImplDX9_ViewportData() { IM_ASSERT(SwapChain == nullptr); }
521};
522
523static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport)
524{
525 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
526 ImGui_ImplDX9_ViewportData* vd = IM_NEW(ImGui_ImplDX9_ViewportData)();
527 viewport->RendererUserData = vd;
528
529 // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL's WindowID).
530 // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
531 HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
532 IM_ASSERT(hwnd != 0);
533
534 ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
535 vd->d3dpp.Windowed = TRUE;
536 vd->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
537 vd->d3dpp.BackBufferWidth = (UINT)viewport->Size.x;
538 vd->d3dpp.BackBufferHeight = (UINT)viewport->Size.y;
539 vd->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
540 vd->d3dpp.hDeviceWindow = hwnd;
541 vd->d3dpp.EnableAutoDepthStencil = FALSE;
542 vd->d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
543 vd->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync
544
545 HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
546 IM_ASSERT(hr == D3D_OK);
547 IM_ASSERT(vd->SwapChain != nullptr);
548}
549
550static void ImGui_ImplDX9_DestroyWindow(ImGuiViewport* viewport)
551{
552 // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
553 if (ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData)
554 {
555 if (vd->SwapChain)
556 vd->SwapChain->Release();
557 vd->SwapChain = nullptr;
558 ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
559 IM_DELETE(vd);
560 }
561 viewport->RendererUserData = nullptr;
562}
563
564static void ImGui_ImplDX9_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
565{
566 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
567 ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
568 if (vd->SwapChain)
569 {
570 vd->SwapChain->Release();
571 vd->SwapChain = nullptr;
572 vd->d3dpp.BackBufferWidth = (UINT)size.x;
573 vd->d3dpp.BackBufferHeight = (UINT)size.y;
574 HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
575 IM_ASSERT(hr == D3D_OK);
576 }
577}
578
579static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*)
580{
581 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
582 ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
583 ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
584
585 LPDIRECT3DSURFACE9 render_target = nullptr;
586 LPDIRECT3DSURFACE9 last_render_target = nullptr;
587 LPDIRECT3DSURFACE9 last_depth_stencil = nullptr;
588 vd->SwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &render_target);
589 bd->pd3dDevice->GetRenderTarget(0, &last_render_target);
590 bd->pd3dDevice->GetDepthStencilSurface(&last_depth_stencil);
591 bd->pd3dDevice->SetRenderTarget(0, render_target);
592 bd->pd3dDevice->SetDepthStencilSurface(nullptr);
593
594 if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
595 {
596 D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f));
597 bd->pd3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET, clear_col_dx, 1.0f, 0);
598 }
599
600 ImGui_ImplDX9_RenderDrawData(viewport->DrawData);
601
602 // Restore render target
603 bd->pd3dDevice->SetRenderTarget(0, last_render_target);
604 bd->pd3dDevice->SetDepthStencilSurface(last_depth_stencil);
605 render_target->Release();
606 last_render_target->Release();
607 if (last_depth_stencil) last_depth_stencil->Release();
608}
609
610static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*)
611{
612 ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
613 HRESULT hr = vd->SwapChain->Present(nullptr, nullptr, vd->d3dpp.hDeviceWindow, nullptr, 0);
614 // Let main application handle D3DERR_DEVICELOST by resetting the device.
615 IM_ASSERT(SUCCEEDED(hr) || hr == D3DERR_DEVICELOST);
616}
617
618static void ImGui_ImplDX9_InitMultiViewportSupport()
619{
620 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
621 platform_io.Renderer_CreateWindow = ImGui_ImplDX9_CreateWindow;
622 platform_io.Renderer_DestroyWindow = ImGui_ImplDX9_DestroyWindow;
623 platform_io.Renderer_SetWindowSize = ImGui_ImplDX9_SetWindowSize;
624 platform_io.Renderer_RenderWindow = ImGui_ImplDX9_RenderWindow;
625 platform_io.Renderer_SwapBuffers = ImGui_ImplDX9_SwapBuffers;
626}
627
628static void ImGui_ImplDX9_ShutdownMultiViewportSupport()
629{
630 ImGui::DestroyPlatformWindows();
631}
632
633static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows()
634{
635 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
636 for (int i = 1; i < platform_io.Viewports.Size; i++)
637 if (!platform_io.Viewports[i]->RendererUserData)
638 ImGui_ImplDX9_CreateWindow(platform_io.Viewports[i]);
639}
640
641static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows()
642{
643 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
644 for (int i = 1; i < platform_io.Viewports.Size; i++)
645 if (platform_io.Viewports[i]->RendererUserData)
646 ImGui_ImplDX9_DestroyWindow(platform_io.Viewports[i]);
647}
648
649//-----------------------------------------------------------------------------
650
651#endif // #ifndef IMGUI_DISABLE