imgui

FORK: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
git clone https://git.neptards.moe/neptards/imgui.git
Log | Files | Refs

imgui_impl_dx11.cpp (26325B)


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