imgui_impl_dx10.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. // dear imgui: Renderer for DirectX10
  2. // This needs to be used along with a Platform Binding (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  5. // [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  6. // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices.
  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. // CHANGELOG
  11. // (minor and older changes stripped away, please see git history for details)
  12. // 2019-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  13. // 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData().
  14. // 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  15. // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  16. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  17. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  18. // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions.
  19. // 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example.
  20. // 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  21. // 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other back-ends.
  22. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself.
  23. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  24. // 2016-05-07: DirectX10: Disabling depth-write.
  25. #include "imgui.h"
  26. #include "imgui_impl_dx10.h"
  27. // DirectX
  28. #include <stdio.h>
  29. #include <d3d10_1.h>
  30. #include <d3d10.h>
  31. #include <d3dcompiler.h>
  32. #ifdef _MSC_VER
  33. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  34. #endif
  35. // DirectX data
  36. static ID3D10Device* g_pd3dDevice = NULL;
  37. static IDXGIFactory* g_pFactory = NULL;
  38. static ID3D10Buffer* g_pVB = NULL;
  39. static ID3D10Buffer* g_pIB = NULL;
  40. static ID3D10Blob* g_pVertexShaderBlob = NULL;
  41. static ID3D10VertexShader* g_pVertexShader = NULL;
  42. static ID3D10InputLayout* g_pInputLayout = NULL;
  43. static ID3D10Buffer* g_pVertexConstantBuffer = NULL;
  44. static ID3D10Blob* g_pPixelShaderBlob = NULL;
  45. static ID3D10PixelShader* g_pPixelShader = NULL;
  46. static ID3D10SamplerState* g_pFontSampler = NULL;
  47. static ID3D10ShaderResourceView*g_pFontTextureView = NULL;
  48. static ID3D10RasterizerState* g_pRasterizerState = NULL;
  49. static ID3D10BlendState* g_pBlendState = NULL;
  50. static ID3D10DepthStencilState* g_pDepthStencilState = NULL;
  51. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  52. struct VERTEX_CONSTANT_BUFFER
  53. {
  54. float mvp[4][4];
  55. };
  56. // Forward Declarations
  57. static void ImGui_ImplDX10_InitPlatformInterface();
  58. static void ImGui_ImplDX10_ShutdownPlatformInterface();
  59. static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ctx)
  60. {
  61. // Setup viewport
  62. D3D10_VIEWPORT vp;
  63. memset(&vp, 0, sizeof(D3D10_VIEWPORT));
  64. vp.Width = (UINT)draw_data->DisplaySize.x;
  65. vp.Height = (UINT)draw_data->DisplaySize.y;
  66. vp.MinDepth = 0.0f;
  67. vp.MaxDepth = 1.0f;
  68. vp.TopLeftX = vp.TopLeftY = 0;
  69. ctx->RSSetViewports(1, &vp);
  70. // Bind shader and vertex buffers
  71. unsigned int stride = sizeof(ImDrawVert);
  72. unsigned int offset = 0;
  73. ctx->IASetInputLayout(g_pInputLayout);
  74. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  75. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  76. ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  77. ctx->VSSetShader(g_pVertexShader);
  78. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  79. ctx->PSSetShader(g_pPixelShader);
  80. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  81. ctx->GSSetShader(NULL);
  82. // Setup render state
  83. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  84. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  85. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  86. ctx->RSSetState(g_pRasterizerState);
  87. }
  88. // Render function
  89. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  90. void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
  91. {
  92. // Avoid rendering when minimized
  93. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  94. return;
  95. ID3D10Device* ctx = g_pd3dDevice;
  96. // Create and grow vertex/index buffers if needed
  97. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  98. {
  99. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  100. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  101. D3D10_BUFFER_DESC desc;
  102. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  103. desc.Usage = D3D10_USAGE_DYNAMIC;
  104. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  105. desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  106. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  107. desc.MiscFlags = 0;
  108. if (ctx->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  109. return;
  110. }
  111. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  112. {
  113. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  114. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  115. D3D10_BUFFER_DESC desc;
  116. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  117. desc.Usage = D3D10_USAGE_DYNAMIC;
  118. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  119. desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
  120. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  121. if (ctx->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  122. return;
  123. }
  124. // Copy and convert all vertices into a single contiguous buffer
  125. ImDrawVert* vtx_dst = NULL;
  126. ImDrawIdx* idx_dst = NULL;
  127. g_pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
  128. g_pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
  129. for (int n = 0; n < draw_data->CmdListsCount; n++)
  130. {
  131. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  132. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  133. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  134. vtx_dst += cmd_list->VtxBuffer.Size;
  135. idx_dst += cmd_list->IdxBuffer.Size;
  136. }
  137. g_pVB->Unmap();
  138. g_pIB->Unmap();
  139. // Setup orthographic projection matrix into our constant buffer
  140. // 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.
  141. {
  142. void* mapped_resource;
  143. if (g_pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  144. return;
  145. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource;
  146. float L = draw_data->DisplayPos.x;
  147. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  148. float T = draw_data->DisplayPos.y;
  149. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  150. float mvp[4][4] =
  151. {
  152. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  153. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  154. { 0.0f, 0.0f, 0.5f, 0.0f },
  155. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  156. };
  157. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  158. g_pVertexConstantBuffer->Unmap();
  159. }
  160. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  161. struct BACKUP_DX10_STATE
  162. {
  163. UINT ScissorRectsCount, ViewportsCount;
  164. D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  165. D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  166. ID3D10RasterizerState* RS;
  167. ID3D10BlendState* BlendState;
  168. FLOAT BlendFactor[4];
  169. UINT SampleMask;
  170. UINT StencilRef;
  171. ID3D10DepthStencilState* DepthStencilState;
  172. ID3D10ShaderResourceView* PSShaderResource;
  173. ID3D10SamplerState* PSSampler;
  174. ID3D10PixelShader* PS;
  175. ID3D10VertexShader* VS;
  176. ID3D10GeometryShader* GS;
  177. D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  178. ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  179. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  180. DXGI_FORMAT IndexBufferFormat;
  181. ID3D10InputLayout* InputLayout;
  182. };
  183. BACKUP_DX10_STATE old;
  184. old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  185. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  186. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  187. ctx->RSGetState(&old.RS);
  188. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  189. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  190. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  191. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  192. ctx->PSGetShader(&old.PS);
  193. ctx->VSGetShader(&old.VS);
  194. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  195. ctx->GSGetShader(&old.GS);
  196. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  197. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  198. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  199. ctx->IAGetInputLayout(&old.InputLayout);
  200. // Setup desired DX state
  201. ImGui_ImplDX10_SetupRenderState(draw_data, ctx);
  202. // Render command lists
  203. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  204. int global_vtx_offset = 0;
  205. int global_idx_offset = 0;
  206. ImVec2 clip_off = draw_data->DisplayPos;
  207. for (int n = 0; n < draw_data->CmdListsCount; n++)
  208. {
  209. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  210. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  211. {
  212. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  213. if (pcmd->UserCallback)
  214. {
  215. // User callback, registered via ImDrawList::AddCallback()
  216. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  217. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  218. ImGui_ImplDX10_SetupRenderState(draw_data, ctx);
  219. else
  220. pcmd->UserCallback(cmd_list, pcmd);
  221. }
  222. else
  223. {
  224. // Apply scissor/clipping rectangle
  225. const D3D10_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)};
  226. ctx->RSSetScissorRects(1, &r);
  227. // Bind texture, Draw
  228. ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->TextureId;
  229. ctx->PSSetShaderResources(0, 1, &texture_srv);
  230. ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
  231. }
  232. }
  233. global_idx_offset += cmd_list->IdxBuffer.Size;
  234. global_vtx_offset += cmd_list->VtxBuffer.Size;
  235. }
  236. // Restore modified DX state
  237. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  238. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  239. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  240. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  241. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  242. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  243. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  244. ctx->PSSetShader(old.PS); if (old.PS) old.PS->Release();
  245. ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release();
  246. ctx->GSSetShader(old.GS); if (old.GS) old.GS->Release();
  247. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  248. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  249. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  250. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  251. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  252. }
  253. static void ImGui_ImplDX10_CreateFontsTexture()
  254. {
  255. // Build texture atlas
  256. ImGuiIO& io = ImGui::GetIO();
  257. unsigned char* pixels;
  258. int width, height;
  259. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  260. // Upload texture to graphics system
  261. {
  262. D3D10_TEXTURE2D_DESC desc;
  263. ZeroMemory(&desc, sizeof(desc));
  264. desc.Width = width;
  265. desc.Height = height;
  266. desc.MipLevels = 1;
  267. desc.ArraySize = 1;
  268. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  269. desc.SampleDesc.Count = 1;
  270. desc.Usage = D3D10_USAGE_DEFAULT;
  271. desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
  272. desc.CPUAccessFlags = 0;
  273. ID3D10Texture2D *pTexture = NULL;
  274. D3D10_SUBRESOURCE_DATA subResource;
  275. subResource.pSysMem = pixels;
  276. subResource.SysMemPitch = desc.Width * 4;
  277. subResource.SysMemSlicePitch = 0;
  278. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  279. // Create texture view
  280. D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
  281. ZeroMemory(&srv_desc, sizeof(srv_desc));
  282. srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  283. srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
  284. srv_desc.Texture2D.MipLevels = desc.MipLevels;
  285. srv_desc.Texture2D.MostDetailedMip = 0;
  286. g_pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &g_pFontTextureView);
  287. pTexture->Release();
  288. }
  289. // Store our identifier
  290. io.Fonts->TexID = (ImTextureID)g_pFontTextureView;
  291. // Create texture sampler
  292. {
  293. D3D10_SAMPLER_DESC desc;
  294. ZeroMemory(&desc, sizeof(desc));
  295. desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
  296. desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP;
  297. desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP;
  298. desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP;
  299. desc.MipLODBias = 0.f;
  300. desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
  301. desc.MinLOD = 0.f;
  302. desc.MaxLOD = 0.f;
  303. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  304. }
  305. }
  306. bool ImGui_ImplDX10_CreateDeviceObjects()
  307. {
  308. if (!g_pd3dDevice)
  309. return false;
  310. if (g_pFontSampler)
  311. ImGui_ImplDX10_InvalidateDeviceObjects();
  312. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  313. // If you would like to use this DX10 sample code but remove this dependency you can:
  314. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  315. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  316. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  317. // Create the vertex shader
  318. {
  319. static const char* vertexShader =
  320. "cbuffer vertexBuffer : register(b0) \
  321. {\
  322. float4x4 ProjectionMatrix; \
  323. };\
  324. struct VS_INPUT\
  325. {\
  326. float2 pos : POSITION;\
  327. float4 col : COLOR0;\
  328. float2 uv : TEXCOORD0;\
  329. };\
  330. \
  331. struct PS_INPUT\
  332. {\
  333. float4 pos : SV_POSITION;\
  334. float4 col : COLOR0;\
  335. float2 uv : TEXCOORD0;\
  336. };\
  337. \
  338. PS_INPUT main(VS_INPUT input)\
  339. {\
  340. PS_INPUT output;\
  341. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  342. output.col = input.col;\
  343. output.uv = input.uv;\
  344. return output;\
  345. }";
  346. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  347. if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  348. return false;
  349. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK)
  350. return false;
  351. // Create the input layout
  352. D3D10_INPUT_ELEMENT_DESC local_layout[] =
  353. {
  354. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  355. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  356. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  357. };
  358. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  359. return false;
  360. // Create the constant buffer
  361. {
  362. D3D10_BUFFER_DESC desc;
  363. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  364. desc.Usage = D3D10_USAGE_DYNAMIC;
  365. desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
  366. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  367. desc.MiscFlags = 0;
  368. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  369. }
  370. }
  371. // Create the pixel shader
  372. {
  373. static const char* pixelShader =
  374. "struct PS_INPUT\
  375. {\
  376. float4 pos : SV_POSITION;\
  377. float4 col : COLOR0;\
  378. float2 uv : TEXCOORD0;\
  379. };\
  380. sampler sampler0;\
  381. Texture2D texture0;\
  382. \
  383. float4 main(PS_INPUT input) : SV_Target\
  384. {\
  385. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  386. return out_col; \
  387. }";
  388. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  389. if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  390. return false;
  391. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK)
  392. return false;
  393. }
  394. // Create the blending setup
  395. {
  396. D3D10_BLEND_DESC desc;
  397. ZeroMemory(&desc, sizeof(desc));
  398. desc.AlphaToCoverageEnable = false;
  399. desc.BlendEnable[0] = true;
  400. desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
  401. desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
  402. desc.BlendOp = D3D10_BLEND_OP_ADD;
  403. desc.SrcBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
  404. desc.DestBlendAlpha = D3D10_BLEND_ZERO;
  405. desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
  406. desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
  407. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  408. }
  409. // Create the rasterizer state
  410. {
  411. D3D10_RASTERIZER_DESC desc;
  412. ZeroMemory(&desc, sizeof(desc));
  413. desc.FillMode = D3D10_FILL_SOLID;
  414. desc.CullMode = D3D10_CULL_NONE;
  415. desc.ScissorEnable = true;
  416. desc.DepthClipEnable = true;
  417. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  418. }
  419. // Create depth-stencil State
  420. {
  421. D3D10_DEPTH_STENCIL_DESC desc;
  422. ZeroMemory(&desc, sizeof(desc));
  423. desc.DepthEnable = false;
  424. desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
  425. desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
  426. desc.StencilEnable = false;
  427. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
  428. desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
  429. desc.BackFace = desc.FrontFace;
  430. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  431. }
  432. ImGui_ImplDX10_CreateFontsTexture();
  433. return true;
  434. }
  435. void ImGui_ImplDX10_InvalidateDeviceObjects()
  436. {
  437. if (!g_pd3dDevice)
  438. return;
  439. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  440. if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
  441. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  442. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  443. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  444. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  445. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  446. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  447. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  448. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  449. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  450. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  451. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  452. }
  453. bool ImGui_ImplDX10_Init(ID3D10Device* device)
  454. {
  455. // Setup back-end capabilities flags
  456. ImGuiIO& io = ImGui::GetIO();
  457. io.BackendRendererName = "imgui_impl_dx10";
  458. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  459. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  460. // Get factory from device
  461. IDXGIDevice* pDXGIDevice = NULL;
  462. IDXGIAdapter* pDXGIAdapter = NULL;
  463. IDXGIFactory* pFactory = NULL;
  464. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
  465. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
  466. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
  467. {
  468. g_pd3dDevice = device;
  469. g_pFactory = pFactory;
  470. }
  471. if (pDXGIDevice) pDXGIDevice->Release();
  472. if (pDXGIAdapter) pDXGIAdapter->Release();
  473. g_pd3dDevice->AddRef();
  474. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  475. ImGui_ImplDX10_InitPlatformInterface();
  476. return true;
  477. }
  478. void ImGui_ImplDX10_Shutdown()
  479. {
  480. ImGui_ImplDX10_ShutdownPlatformInterface();
  481. ImGui_ImplDX10_InvalidateDeviceObjects();
  482. if (g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; }
  483. if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
  484. }
  485. void ImGui_ImplDX10_NewFrame()
  486. {
  487. if (!g_pFontSampler)
  488. ImGui_ImplDX10_CreateDeviceObjects();
  489. }
  490. //--------------------------------------------------------------------------------------------------------
  491. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  492. // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
  493. // 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..
  494. //--------------------------------------------------------------------------------------------------------
  495. struct ImGuiViewportDataDx10
  496. {
  497. IDXGISwapChain* SwapChain;
  498. ID3D10RenderTargetView* RTView;
  499. ImGuiViewportDataDx10() { SwapChain = NULL; RTView = NULL; }
  500. ~ImGuiViewportDataDx10() { IM_ASSERT(SwapChain == NULL && RTView == NULL); }
  501. };
  502. static void ImGui_ImplDX10_CreateWindow(ImGuiViewport* viewport)
  503. {
  504. ImGuiViewportDataDx10* data = IM_NEW(ImGuiViewportDataDx10)();
  505. viewport->RendererUserData = data;
  506. // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
  507. // Some back-ends will leave PlatformHandleRaw NULL, in which case we assume PlatformHandle will contain the HWND.
  508. HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
  509. IM_ASSERT(hwnd != 0);
  510. // Create swap chain
  511. DXGI_SWAP_CHAIN_DESC sd;
  512. ZeroMemory(&sd, sizeof(sd));
  513. sd.BufferDesc.Width = (UINT)viewport->Size.x;
  514. sd.BufferDesc.Height = (UINT)viewport->Size.y;
  515. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  516. sd.SampleDesc.Count = 1;
  517. sd.SampleDesc.Quality = 0;
  518. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  519. sd.BufferCount = 1;
  520. sd.OutputWindow = hwnd;
  521. sd.Windowed = TRUE;
  522. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  523. sd.Flags = 0;
  524. IM_ASSERT(data->SwapChain == NULL && data->RTView == NULL);
  525. g_pFactory->CreateSwapChain(g_pd3dDevice, &sd, &data->SwapChain);
  526. // Create the render target
  527. if (data->SwapChain)
  528. {
  529. ID3D10Texture2D* pBackBuffer;
  530. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  531. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  532. pBackBuffer->Release();
  533. }
  534. }
  535. static void ImGui_ImplDX10_DestroyWindow(ImGuiViewport* viewport)
  536. {
  537. // The main viewport (owned by the application) will always have RendererUserData == NULL here since we didn't create the data for it.
  538. if (ImGuiViewportDataDx10* data = (ImGuiViewportDataDx10*)viewport->RendererUserData)
  539. {
  540. if (data->SwapChain)
  541. data->SwapChain->Release();
  542. data->SwapChain = NULL;
  543. if (data->RTView)
  544. data->RTView->Release();
  545. data->RTView = NULL;
  546. IM_DELETE(data);
  547. }
  548. viewport->RendererUserData = NULL;
  549. }
  550. static void ImGui_ImplDX10_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  551. {
  552. ImGuiViewportDataDx10* data = (ImGuiViewportDataDx10*)viewport->RendererUserData;
  553. if (data->RTView)
  554. {
  555. data->RTView->Release();
  556. data->RTView = NULL;
  557. }
  558. if (data->SwapChain)
  559. {
  560. ID3D10Texture2D* pBackBuffer = NULL;
  561. data->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
  562. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  563. if (pBackBuffer == NULL) { fprintf(stderr, "ImGui_ImplDX10_SetWindowSize() failed creating buffers.\n"); return; }
  564. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  565. pBackBuffer->Release();
  566. }
  567. }
  568. static void ImGui_ImplDX10_RenderViewport(ImGuiViewport* viewport, void*)
  569. {
  570. ImGuiViewportDataDx10* data = (ImGuiViewportDataDx10*)viewport->RendererUserData;
  571. ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  572. g_pd3dDevice->OMSetRenderTargets(1, &data->RTView, NULL);
  573. if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
  574. g_pd3dDevice->ClearRenderTargetView(data->RTView, (float*)&clear_color);
  575. ImGui_ImplDX10_RenderDrawData(viewport->DrawData);
  576. }
  577. static void ImGui_ImplDX10_SwapBuffers(ImGuiViewport* viewport, void*)
  578. {
  579. ImGuiViewportDataDx10* data = (ImGuiViewportDataDx10*)viewport->RendererUserData;
  580. data->SwapChain->Present(0, 0); // Present without vsync
  581. }
  582. void ImGui_ImplDX10_InitPlatformInterface()
  583. {
  584. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  585. platform_io.Renderer_CreateWindow = ImGui_ImplDX10_CreateWindow;
  586. platform_io.Renderer_DestroyWindow = ImGui_ImplDX10_DestroyWindow;
  587. platform_io.Renderer_SetWindowSize = ImGui_ImplDX10_SetWindowSize;
  588. platform_io.Renderer_RenderWindow = ImGui_ImplDX10_RenderViewport;
  589. platform_io.Renderer_SwapBuffers = ImGui_ImplDX10_SwapBuffers;
  590. }
  591. void ImGui_ImplDX10_ShutdownPlatformInterface()
  592. {
  593. ImGui::DestroyPlatformWindows();
  594. }