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