1 // ImGui Renderer for: DirectX9
2 // This needs to be used along with a Platform Binding (e.g. Win32)
3 
4 // Implemented features:
5 //  [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
6 
7 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
8 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
9 // https://github.com/ocornut/imgui
10 
11 // CHANGELOG
12 // (minor and older changes stripped away, please see git history for details)
13 //  2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
14 //  2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
15 //  2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
16 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
17 //  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
18 
19 #include "imgui.h"
20 #include "imgui_impl_dx9.h"
21 
22 // DirectX
23 #include <d3d9.h>
24 #define DIRECTINPUT_VERSION 0x0800
25 #include <dinput.h>
26 
27 // DirectX data
28 static LPDIRECT3DDEVICE9        g_pd3dDevice = NULL;
29 static LPDIRECT3DVERTEXBUFFER9  g_pVB = NULL;
30 static LPDIRECT3DINDEXBUFFER9   g_pIB = NULL;
31 static LPDIRECT3DTEXTURE9       g_FontTexture = NULL;
32 static int                      g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
33 
34 struct CUSTOMVERTEX
35 {
36     float    pos[3];
37     D3DCOLOR col;
38     float    uv[2];
39 };
40 #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
41 
42 // Render function.
43 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
ImGui_ImplDX9_RenderDrawData(ImDrawData * draw_data)44 void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
45 {
46     // Avoid rendering when minimized
47     if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
48         return;
49 
50     // Create and grow buffers if needed
51     if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
52     {
53         if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
54         g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
55         if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
56             return;
57     }
58     if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
59     {
60         if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
61         g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
62         if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0)
63             return;
64     }
65 
66     // Backup the DX9 state
67     IDirect3DStateBlock9* d3d9_state_block = NULL;
68     if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
69         return;
70 
71     // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
72     D3DMATRIX last_world, last_view, last_projection;
73     g_pd3dDevice->GetTransform(D3DTS_WORLD, &last_world);
74     g_pd3dDevice->GetTransform(D3DTS_VIEW, &last_view);
75     g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection);
76 
77     // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
78     // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and
79     //  1) to avoid repacking colors:   #define IMGUI_USE_BGRA_PACKED_COLOR
80     //  2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
81     CUSTOMVERTEX* vtx_dst;
82     ImDrawIdx* idx_dst;
83     if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
84         return;
85     if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
86         return;
87     for (int n = 0; n < draw_data->CmdListsCount; n++)
88     {
89         const ImDrawList* cmd_list = draw_data->CmdLists[n];
90         const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
91         for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
92         {
93             vtx_dst->pos[0] = vtx_src->pos.x;
94             vtx_dst->pos[1] = vtx_src->pos.y;
95             vtx_dst->pos[2] = 0.0f;
96             vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16);     // RGBA --> ARGB for DirectX9
97             vtx_dst->uv[0] = vtx_src->uv.x;
98             vtx_dst->uv[1] = vtx_src->uv.y;
99             vtx_dst++;
100             vtx_src++;
101         }
102         memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
103         idx_dst += cmd_list->IdxBuffer.Size;
104     }
105     g_pVB->Unlock();
106     g_pIB->Unlock();
107     g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
108     g_pd3dDevice->SetIndices(g_pIB);
109     g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
110 
111     // Setup viewport
112     D3DVIEWPORT9 vp;
113     vp.X = vp.Y = 0;
114     vp.Width = (DWORD)draw_data->DisplaySize.x;
115     vp.Height = (DWORD)draw_data->DisplaySize.y;
116     vp.MinZ = 0.0f;
117     vp.MaxZ = 1.0f;
118     g_pd3dDevice->SetViewport(&vp);
119 
120     // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient)
121     g_pd3dDevice->SetPixelShader(NULL);
122     g_pd3dDevice->SetVertexShader(NULL);
123     g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
124     g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false);
125     g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
126     g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
127     g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false);
128     g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
129     g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
130     g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
131     g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true);
132     g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
133     g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
134     g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
135     g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
136     g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
137     g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
138     g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
139     g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
140     g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
141 
142     // Setup orthographic projection matrix
143     // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
144     // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
145     {
146         float L = draw_data->DisplayPos.x + 0.5f;
147         float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
148         float T = draw_data->DisplayPos.y + 0.5f;
149         float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
150         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 } };
151         D3DMATRIX mat_projection =
152         {
153             2.0f/(R-L),   0.0f,         0.0f,  0.0f,
154             0.0f,         2.0f/(T-B),   0.0f,  0.0f,
155             0.0f,         0.0f,         0.5f,  0.0f,
156             (L+R)/(L-R),  (T+B)/(B-T),  0.5f,  1.0f,
157         };
158         g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
159         g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
160         g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
161     }
162 
163     // Render command lists
164     int vtx_offset = 0;
165     int idx_offset = 0;
166     ImVec2 pos = draw_data->DisplayPos;
167     for (int n = 0; n < draw_data->CmdListsCount; n++)
168     {
169         const ImDrawList* cmd_list = draw_data->CmdLists[n];
170         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
171         {
172             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
173             if (pcmd->UserCallback)
174             {
175                 pcmd->UserCallback(cmd_list, pcmd);
176             }
177             else
178             {
179                 const RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) };
180                 const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId;
181                 g_pd3dDevice->SetTexture(0, texture);
182                 g_pd3dDevice->SetScissorRect(&r);
183                 g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, idx_offset, pcmd->ElemCount/3);
184             }
185             idx_offset += pcmd->ElemCount;
186         }
187         vtx_offset += cmd_list->VtxBuffer.Size;
188     }
189 
190     // Restore the DX9 transform
191     g_pd3dDevice->SetTransform(D3DTS_WORLD, &last_world);
192     g_pd3dDevice->SetTransform(D3DTS_VIEW, &last_view);
193     g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection);
194 
195     // Restore the DX9 state
196     d3d9_state_block->Apply();
197     d3d9_state_block->Release();
198 }
199 
ImGui_ImplDX9_Init(IDirect3DDevice9 * device)200 bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
201 {
202     g_pd3dDevice = device;
203     return true;
204 }
205 
ImGui_ImplDX9_Shutdown()206 void ImGui_ImplDX9_Shutdown()
207 {
208     ImGui_ImplDX9_InvalidateDeviceObjects();
209     g_pd3dDevice = NULL;
210 }
211 
ImGui_ImplDX9_CreateFontsTexture()212 static bool ImGui_ImplDX9_CreateFontsTexture()
213 {
214     // Build texture atlas
215     ImGuiIO& io = ImGui::GetIO();
216     unsigned char* pixels;
217     int width, height, bytes_per_pixel;
218     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
219 
220     // Upload texture to graphics system
221     g_FontTexture = NULL;
222     if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0)
223         return false;
224     D3DLOCKED_RECT tex_locked_rect;
225     if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
226         return false;
227     for (int y = 0; y < height; y++)
228         memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
229     g_FontTexture->UnlockRect(0);
230 
231     // Store our identifier
232     io.Fonts->TexID = (ImTextureID)g_FontTexture;
233 
234     return true;
235 }
236 
ImGui_ImplDX9_CreateDeviceObjects()237 bool ImGui_ImplDX9_CreateDeviceObjects()
238 {
239     if (!g_pd3dDevice)
240         return false;
241     if (!ImGui_ImplDX9_CreateFontsTexture())
242         return false;
243     return true;
244 }
245 
ImGui_ImplDX9_InvalidateDeviceObjects()246 void ImGui_ImplDX9_InvalidateDeviceObjects()
247 {
248     if (!g_pd3dDevice)
249         return;
250     if (g_pVB)
251     {
252         g_pVB->Release();
253         g_pVB = NULL;
254     }
255     if (g_pIB)
256     {
257         g_pIB->Release();
258         g_pIB = NULL;
259     }
260 
261     // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both.
262     ImGuiIO& io = ImGui::GetIO();
263     IM_ASSERT(g_FontTexture == io.Fonts->TexID);
264     if (g_FontTexture)
265         g_FontTexture->Release();
266     g_FontTexture = NULL;
267     io.Fonts->TexID = NULL;
268 }
269 
ImGui_ImplDX9_NewFrame()270 void ImGui_ImplDX9_NewFrame()
271 {
272     if (!g_FontTexture)
273         ImGui_ImplDX9_CreateDeviceObjects();
274 }
275