imgui_impl_dx11.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // ImGui Win32 + DirectX11 binding
  2. // In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  4. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  5. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  6. // https://github.com/ocornut/imgui
  7. #include <imgui.h>
  8. #include "imgui_impl_dx11.h"
  9. // DirectX
  10. #include <d3d11.h>
  11. #include <d3dcompiler.h>
  12. #define DIRECTINPUT_VERSION 0x0800
  13. #include <dinput.h>
  14. // Data
  15. static INT64 g_Time = 0;
  16. static INT64 g_TicksPerSecond = 0;
  17. static HWND g_hWnd = 0;
  18. static ID3D11Device* g_pd3dDevice = NULL;
  19. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  20. static ID3D11Buffer* g_pVB = NULL;
  21. static ID3D11Buffer* g_pIB = NULL;
  22. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  23. static ID3D11VertexShader* g_pVertexShader = NULL;
  24. static ID3D11InputLayout* g_pInputLayout = NULL;
  25. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  26. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  27. static ID3D11PixelShader* g_pPixelShader = NULL;
  28. static ID3D11SamplerState* g_pFontSampler = NULL;
  29. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  30. static ID3D11RasterizerState* g_pRasterizerState = NULL;
  31. static ID3D11BlendState* g_pBlendState = NULL;
  32. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  33. struct VERTEX_CONSTANT_BUFFER
  34. {
  35. float mvp[4][4];
  36. };
  37. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  38. // If text or lines are blurry when integrating ImGui in your engine:
  39. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  40. void ImGui_ImplDX11_RenderDrawLists(ImDrawData* draw_data)
  41. {
  42. // Create and grow vertex/index buffers if needed
  43. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  44. {
  45. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  46. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  47. D3D11_BUFFER_DESC desc;
  48. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  49. desc.Usage = D3D11_USAGE_DYNAMIC;
  50. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  51. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  52. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  53. desc.MiscFlags = 0;
  54. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  55. return;
  56. }
  57. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  58. {
  59. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  60. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  61. D3D11_BUFFER_DESC bufferDesc;
  62. memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
  63. bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
  64. bufferDesc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  65. bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  66. bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  67. if (g_pd3dDevice->CreateBuffer(&bufferDesc, NULL, &g_pIB) < 0)
  68. return;
  69. }
  70. // Copy and convert all vertices into a single contiguous buffer
  71. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  72. if (g_pd3dDeviceContext->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  73. return;
  74. if (g_pd3dDeviceContext->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  75. return;
  76. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  77. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  78. for (int n = 0; n < draw_data->CmdListsCount; n++)
  79. {
  80. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  81. memcpy(vtx_dst, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
  82. memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
  83. vtx_dst += cmd_list->VtxBuffer.size();
  84. idx_dst += cmd_list->IdxBuffer.size();
  85. }
  86. g_pd3dDeviceContext->Unmap(g_pVB, 0);
  87. g_pd3dDeviceContext->Unmap(g_pIB, 0);
  88. // Setup orthographic projection matrix into our constant buffer
  89. {
  90. D3D11_MAPPED_SUBRESOURCE mappedResource;
  91. if (g_pd3dDeviceContext->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  92. return;
  93. VERTEX_CONSTANT_BUFFER* pConstantBuffer = (VERTEX_CONSTANT_BUFFER*)mappedResource.pData;
  94. const float L = 0.0f;
  95. const float R = ImGui::GetIO().DisplaySize.x;
  96. const float B = ImGui::GetIO().DisplaySize.y;
  97. const float T = 0.0f;
  98. const float mvp[4][4] =
  99. {
  100. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  101. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  102. { 0.0f, 0.0f, 0.5f, 0.0f },
  103. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  104. };
  105. memcpy(&pConstantBuffer->mvp, mvp, sizeof(mvp));
  106. g_pd3dDeviceContext->Unmap(g_pVertexConstantBuffer, 0);
  107. }
  108. // Capture all the state that will be modified to restore it afterwards
  109. UINT oldNumScissorRects = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  110. D3D11_RECT oldScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  111. g_pd3dDeviceContext->RSGetScissorRects(&oldNumScissorRects, oldScissorRects);
  112. ID3D11ShaderResourceView* pOldPSSRV0;
  113. g_pd3dDeviceContext->PSGetShaderResources(0, 1, &pOldPSSRV0);
  114. ID3D11RasterizerState* pOldRS;
  115. g_pd3dDeviceContext->RSGetState(&pOldRS);
  116. ID3D11BlendState* pOldBlendState;
  117. FLOAT oldBlendFactor[4];
  118. UINT oldSampleMask;
  119. g_pd3dDeviceContext->OMGetBlendState(&pOldBlendState, oldBlendFactor, &oldSampleMask);
  120. ID3D11SamplerState* pOldPSSampler;
  121. g_pd3dDeviceContext->PSGetSamplers(0, 1, &pOldPSSampler);
  122. ID3D11PixelShader* pOldPS;
  123. ID3D11ClassInstance* pOldPSInstances[256]; // max according to PSSetShader documentation
  124. UINT oldNumPSInstances = 256;
  125. g_pd3dDeviceContext->PSGetShader(&pOldPS, pOldPSInstances, &oldNumPSInstances);
  126. ID3D11Buffer* pOldVSCBV;
  127. g_pd3dDeviceContext->VSGetConstantBuffers(0, 1, &pOldVSCBV);
  128. ID3D11VertexShader* pOldVS;
  129. ID3D11ClassInstance* pOldVSInstances[256]; // max according to VSSetShader documentation
  130. UINT oldNumVSInstances = 256;
  131. g_pd3dDeviceContext->VSGetShader(&pOldVS, pOldVSInstances, &oldNumVSInstances);
  132. D3D11_PRIMITIVE_TOPOLOGY oldPrimitiveTopology;
  133. g_pd3dDeviceContext->IAGetPrimitiveTopology(&oldPrimitiveTopology);
  134. ID3D11Buffer* pOldIndexBuffer;
  135. DXGI_FORMAT oldIndexBufferFormat;
  136. UINT oldIndexBufferOffset;
  137. g_pd3dDeviceContext->IAGetIndexBuffer(&pOldIndexBuffer, &oldIndexBufferFormat, &oldIndexBufferOffset);
  138. ID3D11Buffer* pOldVertexBuffer;
  139. UINT oldVertexBufferStride;
  140. UINT oldVertexBufferOffset;
  141. g_pd3dDeviceContext->IAGetVertexBuffers(0, 1, &pOldVertexBuffer, &oldVertexBufferStride, &oldVertexBufferOffset);
  142. ID3D11InputLayout* pOldInputLayout;
  143. g_pd3dDeviceContext->IAGetInputLayout(&pOldInputLayout);
  144. UINT oldNumViewports = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  145. D3D11_VIEWPORT oldViewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  146. g_pd3dDeviceContext->RSGetViewports(&oldNumViewports, oldViewports);
  147. // Setup viewport
  148. {
  149. D3D11_VIEWPORT vp;
  150. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  151. vp.Width = ImGui::GetIO().DisplaySize.x;
  152. vp.Height = ImGui::GetIO().DisplaySize.y;
  153. vp.MinDepth = 0.0f;
  154. vp.MaxDepth = 1.0f;
  155. vp.TopLeftX = 0;
  156. vp.TopLeftY = 0;
  157. g_pd3dDeviceContext->RSSetViewports(1, &vp);
  158. }
  159. // Bind shader and vertex buffers
  160. unsigned int stride = sizeof(ImDrawVert);
  161. unsigned int offset = 0;
  162. g_pd3dDeviceContext->IASetInputLayout(g_pInputLayout);
  163. g_pd3dDeviceContext->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  164. g_pd3dDeviceContext->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  165. g_pd3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  166. g_pd3dDeviceContext->VSSetShader(g_pVertexShader, NULL, 0);
  167. g_pd3dDeviceContext->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  168. g_pd3dDeviceContext->PSSetShader(g_pPixelShader, NULL, 0);
  169. g_pd3dDeviceContext->PSSetSamplers(0, 1, &g_pFontSampler);
  170. // Setup render state
  171. const float blendFactor[4] = { 0.f, 0.f, 0.f, 0.f };
  172. g_pd3dDeviceContext->OMSetBlendState(g_pBlendState, blendFactor, 0xffffffff);
  173. g_pd3dDeviceContext->RSSetState(g_pRasterizerState);
  174. // Render command lists
  175. int vtx_offset = 0;
  176. int idx_offset = 0;
  177. for (int n = 0; n < draw_data->CmdListsCount; n++)
  178. {
  179. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  180. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
  181. {
  182. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  183. if (pcmd->UserCallback)
  184. {
  185. pcmd->UserCallback(cmd_list, pcmd);
  186. }
  187. else
  188. {
  189. const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  190. g_pd3dDeviceContext->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
  191. g_pd3dDeviceContext->RSSetScissorRects(1, &r);
  192. g_pd3dDeviceContext->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  193. }
  194. idx_offset += pcmd->ElemCount;
  195. }
  196. vtx_offset += cmd_list->VtxBuffer.size();
  197. }
  198. // Restore modified state
  199. g_pd3dDeviceContext->RSSetScissorRects(oldNumScissorRects, oldScissorRects);
  200. g_pd3dDeviceContext->PSSetShaderResources(0, 1, &pOldPSSRV0);
  201. if (pOldPSSRV0) pOldPSSRV0->Release();
  202. g_pd3dDeviceContext->RSSetState(pOldRS);
  203. if (pOldRS) pOldRS->Release();
  204. g_pd3dDeviceContext->OMSetBlendState(pOldBlendState, oldBlendFactor, oldSampleMask);
  205. if (pOldBlendState) pOldBlendState->Release();
  206. g_pd3dDeviceContext->PSSetSamplers(0, 1, &pOldPSSampler);
  207. if (pOldPSSampler) pOldPSSampler->Release();
  208. g_pd3dDeviceContext->PSSetShader(pOldPS, pOldPSInstances, oldNumPSInstances);
  209. if (pOldPS) pOldPS->Release();
  210. for (UINT i = 0; i < oldNumPSInstances; i++) if (pOldPSInstances[i]) pOldPSInstances[i]->Release();
  211. g_pd3dDeviceContext->VSSetConstantBuffers(0, 1, &pOldVSCBV);
  212. if (pOldVSCBV) pOldVSCBV->Release();
  213. g_pd3dDeviceContext->VSSetShader(pOldVS, pOldVSInstances, oldNumVSInstances);
  214. if (pOldVS) pOldVS->Release();
  215. for (UINT i = 0; i < oldNumVSInstances; i++) if (pOldVSInstances[i]) pOldVSInstances[i]->Release();
  216. g_pd3dDeviceContext->IASetPrimitiveTopology(oldPrimitiveTopology);
  217. g_pd3dDeviceContext->IASetIndexBuffer(pOldIndexBuffer, oldIndexBufferFormat, oldIndexBufferOffset);
  218. if (pOldIndexBuffer) pOldIndexBuffer->Release();
  219. g_pd3dDeviceContext->IASetVertexBuffers(0, 1, &pOldVertexBuffer, &oldVertexBufferStride, &oldVertexBufferOffset);
  220. if (pOldVertexBuffer) pOldVertexBuffer->Release();
  221. g_pd3dDeviceContext->IASetInputLayout(pOldInputLayout);
  222. if (pOldInputLayout) pOldInputLayout->Release();
  223. g_pd3dDeviceContext->RSSetViewports(oldNumViewports, oldViewports);
  224. }
  225. IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  226. {
  227. ImGuiIO& io = ImGui::GetIO();
  228. switch (msg)
  229. {
  230. case WM_LBUTTONDOWN:
  231. io.MouseDown[0] = true;
  232. return true;
  233. case WM_LBUTTONUP:
  234. io.MouseDown[0] = false;
  235. return true;
  236. case WM_RBUTTONDOWN:
  237. io.MouseDown[1] = true;
  238. return true;
  239. case WM_RBUTTONUP:
  240. io.MouseDown[1] = false;
  241. return true;
  242. case WM_MBUTTONDOWN:
  243. io.MouseDown[2] = true;
  244. return true;
  245. case WM_MBUTTONUP:
  246. io.MouseDown[2] = false;
  247. return true;
  248. case WM_MOUSEWHEEL:
  249. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  250. return true;
  251. case WM_MOUSEMOVE:
  252. io.MousePos.x = (signed short)(lParam);
  253. io.MousePos.y = (signed short)(lParam >> 16);
  254. return true;
  255. case WM_KEYDOWN:
  256. if (wParam < 256)
  257. io.KeysDown[wParam] = 1;
  258. return true;
  259. case WM_KEYUP:
  260. if (wParam < 256)
  261. io.KeysDown[wParam] = 0;
  262. return true;
  263. case WM_CHAR:
  264. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  265. if (wParam > 0 && wParam < 0x10000)
  266. io.AddInputCharacter((unsigned short)wParam);
  267. return true;
  268. }
  269. return 0;
  270. }
  271. static void ImGui_ImplDX11_CreateFontsTexture()
  272. {
  273. // Build texture atlas
  274. ImGuiIO& io = ImGui::GetIO();
  275. unsigned char* pixels;
  276. int width, height;
  277. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  278. // Upload texture to graphics system
  279. {
  280. D3D11_TEXTURE2D_DESC texDesc;
  281. ZeroMemory(&texDesc, sizeof(texDesc));
  282. texDesc.Width = width;
  283. texDesc.Height = height;
  284. texDesc.MipLevels = 1;
  285. texDesc.ArraySize = 1;
  286. texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  287. texDesc.SampleDesc.Count = 1;
  288. texDesc.Usage = D3D11_USAGE_DEFAULT;
  289. texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  290. texDesc.CPUAccessFlags = 0;
  291. ID3D11Texture2D *pTexture = NULL;
  292. D3D11_SUBRESOURCE_DATA subResource;
  293. subResource.pSysMem = pixels;
  294. subResource.SysMemPitch = texDesc.Width * 4;
  295. subResource.SysMemSlicePitch = 0;
  296. g_pd3dDevice->CreateTexture2D(&texDesc, &subResource, &pTexture);
  297. // Create texture view
  298. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  299. ZeroMemory(&srvDesc, sizeof(srvDesc));
  300. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  301. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  302. srvDesc.Texture2D.MipLevels = texDesc.MipLevels;
  303. srvDesc.Texture2D.MostDetailedMip = 0;
  304. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  305. pTexture->Release();
  306. }
  307. // Store our identifier
  308. io.Fonts->TexID = (void *)g_pFontTextureView;
  309. // Create texture sampler
  310. {
  311. D3D11_SAMPLER_DESC samplerDesc;
  312. ZeroMemory(&samplerDesc, sizeof(samplerDesc));
  313. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  314. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  315. samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  316. samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  317. samplerDesc.MipLODBias = 0.f;
  318. samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  319. samplerDesc.MinLOD = 0.f;
  320. samplerDesc.MaxLOD = 0.f;
  321. g_pd3dDevice->CreateSamplerState(&samplerDesc, &g_pFontSampler);
  322. }
  323. }
  324. bool ImGui_ImplDX11_CreateDeviceObjects()
  325. {
  326. if (!g_pd3dDevice)
  327. return false;
  328. if (g_pFontSampler)
  329. ImGui_ImplDX11_InvalidateDeviceObjects();
  330. // Create the vertex shader
  331. {
  332. static const char* vertexShader =
  333. "cbuffer vertexBuffer : register(b0) \
  334. {\
  335. float4x4 ProjectionMatrix; \
  336. };\
  337. struct VS_INPUT\
  338. {\
  339. float2 pos : POSITION;\
  340. float4 col : COLOR0;\
  341. float2 uv : TEXCOORD0;\
  342. };\
  343. \
  344. struct PS_INPUT\
  345. {\
  346. float4 pos : SV_POSITION;\
  347. float4 col : COLOR0;\
  348. float2 uv : TEXCOORD0;\
  349. };\
  350. \
  351. PS_INPUT main(VS_INPUT input)\
  352. {\
  353. PS_INPUT output;\
  354. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  355. output.col = input.col;\
  356. output.uv = input.uv;\
  357. return output;\
  358. }";
  359. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  360. 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!
  361. return false;
  362. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  363. return false;
  364. // Create the input layout
  365. D3D11_INPUT_ELEMENT_DESC localLayout[] = {
  366. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  367. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  368. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  369. };
  370. if (g_pd3dDevice->CreateInputLayout(localLayout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  371. return false;
  372. // Create the constant buffer
  373. {
  374. D3D11_BUFFER_DESC cbDesc;
  375. cbDesc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  376. cbDesc.Usage = D3D11_USAGE_DYNAMIC;
  377. cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  378. cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  379. cbDesc.MiscFlags = 0;
  380. g_pd3dDevice->CreateBuffer(&cbDesc, NULL, &g_pVertexConstantBuffer);
  381. }
  382. }
  383. // Create the pixel shader
  384. {
  385. static const char* pixelShader =
  386. "struct PS_INPUT\
  387. {\
  388. float4 pos : SV_POSITION;\
  389. float4 col : COLOR0;\
  390. float2 uv : TEXCOORD0;\
  391. };\
  392. sampler sampler0;\
  393. Texture2D texture0;\
  394. \
  395. float4 main(PS_INPUT input) : SV_Target\
  396. {\
  397. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  398. return out_col; \
  399. }";
  400. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  401. 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!
  402. return false;
  403. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  404. return false;
  405. }
  406. // Create the blending setup
  407. {
  408. D3D11_BLEND_DESC desc;
  409. ZeroMemory(&desc, sizeof(desc));
  410. desc.AlphaToCoverageEnable = false;
  411. desc.RenderTarget[0].BlendEnable = true;
  412. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  413. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  414. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  415. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  416. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  417. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  418. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  419. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  420. }
  421. // Create the rasterizer state
  422. {
  423. D3D11_RASTERIZER_DESC desc;
  424. ZeroMemory(&desc, sizeof(desc));
  425. desc.FillMode = D3D11_FILL_SOLID;
  426. desc.CullMode = D3D11_CULL_NONE;
  427. desc.ScissorEnable = true;
  428. desc.DepthClipEnable = true;
  429. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  430. }
  431. ImGui_ImplDX11_CreateFontsTexture();
  432. return true;
  433. }
  434. void ImGui_ImplDX11_InvalidateDeviceObjects()
  435. {
  436. if (!g_pd3dDevice)
  437. return;
  438. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  439. if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = 0; }
  440. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  441. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  442. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  443. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  444. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  445. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  446. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  447. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  448. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  449. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  450. }
  451. bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context)
  452. {
  453. g_hWnd = (HWND)hwnd;
  454. g_pd3dDevice = device;
  455. g_pd3dDeviceContext = device_context;
  456. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  457. return false;
  458. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  459. return false;
  460. ImGuiIO& io = ImGui::GetIO();
  461. io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  462. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  463. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  464. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  465. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  466. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  467. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  468. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  469. io.KeyMap[ImGuiKey_End] = VK_END;
  470. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  471. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  472. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  473. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  474. io.KeyMap[ImGuiKey_A] = 'A';
  475. io.KeyMap[ImGuiKey_C] = 'C';
  476. io.KeyMap[ImGuiKey_V] = 'V';
  477. io.KeyMap[ImGuiKey_X] = 'X';
  478. io.KeyMap[ImGuiKey_Y] = 'Y';
  479. io.KeyMap[ImGuiKey_Z] = 'Z';
  480. io.RenderDrawListsFn = ImGui_ImplDX11_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  481. io.ImeWindowHandle = g_hWnd;
  482. return true;
  483. }
  484. void ImGui_ImplDX11_Shutdown()
  485. {
  486. ImGui_ImplDX11_InvalidateDeviceObjects();
  487. ImGui::Shutdown();
  488. g_pd3dDevice = NULL;
  489. g_pd3dDeviceContext = NULL;
  490. g_hWnd = (HWND)0;
  491. }
  492. void ImGui_ImplDX11_NewFrame()
  493. {
  494. if (!g_pFontSampler)
  495. ImGui_ImplDX11_CreateDeviceObjects();
  496. ImGuiIO& io = ImGui::GetIO();
  497. // Setup display size (every frame to accommodate for window resizing)
  498. RECT rect;
  499. GetClientRect(g_hWnd, &rect);
  500. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  501. // Setup time step
  502. INT64 current_time;
  503. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  504. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  505. g_Time = current_time;
  506. // Read keyboard modifiers inputs
  507. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  508. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  509. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  510. io.KeySuper = false;
  511. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  512. // io.MousePos : filled by WM_MOUSEMOVE events
  513. // io.MouseDown : filled by WM_*BUTTON* events
  514. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  515. // Hide OS mouse cursor if ImGui is drawing it
  516. SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));
  517. // Start the frame
  518. ImGui::NewFrame();
  519. }