imgui_impl_dx11.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // ImGui Win32 + DirectX11 binding
  2. // https://github.com/ocornut/imgui
  3. #include <imgui.h>
  4. #include "imgui_impl_dx11.h"
  5. // DirectX
  6. #include <d3d11.h>
  7. #include <d3dcompiler.h>
  8. #define DIRECTINPUT_VERSION 0x0800
  9. #include <dinput.h>
  10. // Data
  11. static INT64 g_Time = 0;
  12. static INT64 g_TicksPerSecond = 0;
  13. static bool g_FontTextureLoaded = false;
  14. static ID3D11Device* g_pd3dDevice = NULL;
  15. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  16. static ID3D11Buffer* g_pVB = NULL;
  17. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  18. static ID3D11VertexShader* g_pVertexShader = NULL;
  19. static ID3D11InputLayout* g_pInputLayout = NULL;
  20. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  21. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  22. static ID3D11PixelShader* g_pPixelShader = NULL;
  23. static ID3D11SamplerState* g_pFontSampler = NULL;
  24. static ID3D11BlendState* g_blendState = NULL;
  25. struct CUSTOMVERTEX
  26. {
  27. float pos[2];
  28. float uv[2];
  29. unsigned int col;
  30. };
  31. struct VERTEX_CONSTANT_BUFFER
  32. {
  33. float mvp[4][4];
  34. };
  35. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  36. // If text or lines are blurry when integrating ImGui in your engine:
  37. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  38. static void ImGui_ImplDX11_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  39. {
  40. // Copy and convert all vertices into a single contiguous buffer
  41. D3D11_MAPPED_SUBRESOURCE mappedResource;
  42. if (g_pd3dDeviceContext->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  43. return;
  44. CUSTOMVERTEX* vtx_dst = (CUSTOMVERTEX*)mappedResource.pData;
  45. for (int n = 0; n < cmd_lists_count; n++)
  46. {
  47. const ImDrawList* cmd_list = cmd_lists[n];
  48. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  49. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  50. {
  51. vtx_dst->pos[0] = vtx_src->pos.x;
  52. vtx_dst->pos[1] = vtx_src->pos.y;
  53. vtx_dst->uv[0] = vtx_src->uv.x;
  54. vtx_dst->uv[1] = vtx_src->uv.y;
  55. vtx_dst->col = vtx_src->col;
  56. vtx_dst++;
  57. vtx_src++;
  58. }
  59. }
  60. g_pd3dDeviceContext->Unmap(g_pVB, 0);
  61. // Setup orthographic projection matrix into our constant buffer
  62. {
  63. D3D11_MAPPED_SUBRESOURCE mappedResource;
  64. if (g_pd3dDeviceContext->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  65. return;
  66. VERTEX_CONSTANT_BUFFER* pConstantBuffer = (VERTEX_CONSTANT_BUFFER*)mappedResource.pData;
  67. const float L = 0.0f;
  68. const float R = ImGui::GetIO().DisplaySize.x;
  69. const float B = ImGui::GetIO().DisplaySize.y;
  70. const float T = 0.0f;
  71. const float mvp[4][4] =
  72. {
  73. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f},
  74. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f,},
  75. { 0.0f, 0.0f, 0.5f, 0.0f },
  76. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  77. };
  78. memcpy(&pConstantBuffer->mvp, mvp, sizeof(mvp));
  79. g_pd3dDeviceContext->Unmap(g_pVertexConstantBuffer, 0);
  80. }
  81. // Setup viewport
  82. {
  83. D3D11_VIEWPORT vp;
  84. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  85. vp.Width = ImGui::GetIO().DisplaySize.x;
  86. vp.Height = ImGui::GetIO().DisplaySize.y;
  87. vp.MinDepth = 0.0f;
  88. vp.MaxDepth = 1.0f;
  89. vp.TopLeftX = 0;
  90. vp.TopLeftY = 0;
  91. g_pd3dDeviceContext->RSSetViewports(1, &vp);
  92. }
  93. // Bind shader and vertex buffers
  94. unsigned int stride = sizeof(CUSTOMVERTEX);
  95. unsigned int offset = 0;
  96. g_pd3dDeviceContext->IASetInputLayout(g_pInputLayout);
  97. g_pd3dDeviceContext->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  98. g_pd3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  99. g_pd3dDeviceContext->VSSetShader(g_pVertexShader, NULL, 0);
  100. g_pd3dDeviceContext->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  101. g_pd3dDeviceContext->PSSetShader(g_pPixelShader, NULL, 0);
  102. g_pd3dDeviceContext->PSSetSamplers(0, 1, &g_pFontSampler);
  103. // Setup render state
  104. const float blendFactor[4] = { 0.f, 0.f, 0.f, 0.f };
  105. g_pd3dDeviceContext->OMSetBlendState(g_blendState, blendFactor, 0xffffffff);
  106. // Render command lists
  107. int vtx_offset = 0;
  108. for (int n = 0; n < cmd_lists_count; n++)
  109. {
  110. const ImDrawList* cmd_list = cmd_lists[n];
  111. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  112. {
  113. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  114. const D3D11_RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
  115. g_pd3dDeviceContext->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->texture_id);
  116. g_pd3dDeviceContext->RSSetScissorRects(1, &r);
  117. g_pd3dDeviceContext->Draw(pcmd->vtx_count, vtx_offset);
  118. vtx_offset += pcmd->vtx_count;
  119. }
  120. }
  121. // Restore modified state
  122. g_pd3dDeviceContext->IASetInputLayout(NULL);
  123. g_pd3dDeviceContext->PSSetShader(NULL, NULL, 0);
  124. g_pd3dDeviceContext->VSSetShader(NULL, NULL, 0);
  125. }
  126. LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  127. {
  128. ImGuiIO& io = ImGui::GetIO();
  129. switch (msg)
  130. {
  131. case WM_LBUTTONDOWN:
  132. io.MouseDown[0] = true;
  133. return true;
  134. case WM_LBUTTONUP:
  135. io.MouseDown[0] = false;
  136. return true;
  137. case WM_RBUTTONDOWN:
  138. io.MouseDown[1] = true;
  139. return true;
  140. case WM_RBUTTONUP:
  141. io.MouseDown[1] = false;
  142. return true;
  143. case WM_MOUSEWHEEL:
  144. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  145. return true;
  146. case WM_MOUSEMOVE:
  147. io.MousePos.x = (signed short)(lParam);
  148. io.MousePos.y = (signed short)(lParam >> 16);
  149. return true;
  150. case WM_KEYDOWN:
  151. if (wParam >= 0 && wParam < 256)
  152. io.KeysDown[wParam] = 1;
  153. return true;
  154. case WM_KEYUP:
  155. if (wParam >= 0 && wParam < 256)
  156. io.KeysDown[wParam] = 0;
  157. return true;
  158. case WM_CHAR:
  159. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  160. if (wParam > 0 && wParam < 0x10000)
  161. io.AddInputCharacter((unsigned short)wParam);
  162. return true;
  163. }
  164. return 0;
  165. }
  166. void ImGui_ImplDX11_InitFontsTexture()
  167. {
  168. ImGuiIO& io = ImGui::GetIO();
  169. // Build
  170. unsigned char* pixels;
  171. int width, height;
  172. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  173. // Create DX11 texture
  174. D3D11_TEXTURE2D_DESC texDesc;
  175. ZeroMemory(&texDesc, sizeof(texDesc));
  176. texDesc.Width = width;
  177. texDesc.Height = height;
  178. texDesc.MipLevels = 1;
  179. texDesc.ArraySize = 1;
  180. texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  181. texDesc.SampleDesc.Count = 1;
  182. texDesc.Usage = D3D11_USAGE_DEFAULT;
  183. texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  184. texDesc.CPUAccessFlags = 0;
  185. ID3D11Texture2D *pTexture = NULL;
  186. D3D11_SUBRESOURCE_DATA subResource;
  187. subResource.pSysMem = pixels;
  188. subResource.SysMemPitch = texDesc.Width * 4;
  189. subResource.SysMemSlicePitch = 0;
  190. g_pd3dDevice->CreateTexture2D(&texDesc, &subResource, &pTexture);
  191. // Create texture view
  192. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  193. ZeroMemory(&srvDesc, sizeof(srvDesc));
  194. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  195. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  196. srvDesc.Texture2D.MipLevels = texDesc.MipLevels;
  197. srvDesc.Texture2D.MostDetailedMip = 0;
  198. ID3D11ShaderResourceView* font_texture_view = NULL;
  199. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &font_texture_view);
  200. pTexture->Release();
  201. // Store our identifier
  202. io.Fonts->TexID = (void *)font_texture_view;
  203. // Create texture sampler
  204. D3D11_SAMPLER_DESC samplerDesc;
  205. ZeroMemory(&samplerDesc, sizeof(samplerDesc));
  206. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  207. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  208. samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  209. samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  210. samplerDesc.MipLODBias = 0.f;
  211. samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  212. samplerDesc.MinLOD = 0.f;
  213. samplerDesc.MaxLOD = 0.f;
  214. g_pd3dDevice->CreateSamplerState(&samplerDesc, &g_pFontSampler);
  215. }
  216. static bool InitDirect3DState()
  217. {
  218. // Create the vertex shader
  219. {
  220. static const char* vertexShader =
  221. "cbuffer vertexBuffer : register(c0) \
  222. {\
  223. float4x4 ProjectionMatrix; \
  224. };\
  225. struct VS_INPUT\
  226. {\
  227. float2 pos : POSITION;\
  228. float4 col : COLOR0;\
  229. float2 uv : TEXCOORD0;\
  230. };\
  231. \
  232. struct PS_INPUT\
  233. {\
  234. float4 pos : SV_POSITION;\
  235. float4 col : COLOR0;\
  236. float2 uv : TEXCOORD0;\
  237. };\
  238. \
  239. PS_INPUT main(VS_INPUT input)\
  240. {\
  241. PS_INPUT output;\
  242. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  243. output.col = input.col;\
  244. output.uv = input.uv;\
  245. return output;\
  246. }";
  247. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
  248. 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!
  249. return false;
  250. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  251. return false;
  252. // Create the input layout
  253. D3D11_INPUT_ELEMENT_DESC localLayout[] = {
  254. { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  255. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((CUSTOMVERTEX*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  256. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  257. };
  258. if (g_pd3dDevice->CreateInputLayout(localLayout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  259. return false;
  260. // Create the constant buffer
  261. {
  262. D3D11_BUFFER_DESC cbDesc;
  263. cbDesc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  264. cbDesc.Usage = D3D11_USAGE_DYNAMIC;
  265. cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  266. cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  267. cbDesc.MiscFlags = 0;
  268. g_pd3dDevice->CreateBuffer(&cbDesc, NULL, &g_pVertexConstantBuffer);
  269. }
  270. }
  271. // Create the pixel shader
  272. {
  273. static const char* pixelShader =
  274. "struct PS_INPUT\
  275. {\
  276. float4 pos : SV_POSITION;\
  277. float4 col : COLOR0;\
  278. float2 uv : TEXCOORD0;\
  279. };\
  280. sampler sampler0;\
  281. Texture2D texture0;\
  282. \
  283. float4 main(PS_INPUT input) : SV_Target\
  284. {\
  285. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  286. return out_col; \
  287. }";
  288. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
  289. 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!
  290. return false;
  291. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  292. return false;
  293. }
  294. // Create the blending setup
  295. {
  296. D3D11_BLEND_DESC desc;
  297. ZeroMemory(&desc, sizeof(desc));
  298. desc.AlphaToCoverageEnable = false;
  299. desc.RenderTarget[0].BlendEnable = true;
  300. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  301. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  302. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  303. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  304. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  305. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  306. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  307. g_pd3dDevice->CreateBlendState(&desc, &g_blendState);
  308. }
  309. // Create the vertex buffer
  310. {
  311. D3D11_BUFFER_DESC bufferDesc;
  312. memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
  313. bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
  314. bufferDesc.ByteWidth = 100000 * sizeof(CUSTOMVERTEX); // Maybe we should handle that more dynamically?
  315. bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  316. bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  317. bufferDesc.MiscFlags = 0;
  318. if (g_pd3dDevice->CreateBuffer(&bufferDesc, NULL, &g_pVB) < 0)
  319. return false;
  320. }
  321. return true;
  322. }
  323. bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context)
  324. {
  325. g_pd3dDevice = device;
  326. g_pd3dDeviceContext = device_context;
  327. if (!InitDirect3DState())
  328. {
  329. IM_ASSERT(0);
  330. return false;
  331. }
  332. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  333. return false;
  334. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  335. return false;
  336. // FIXME: resizing
  337. RECT rect;
  338. GetClientRect((HWND)hwnd, &rect);
  339. int display_w = (int)(rect.right - rect.left);
  340. int display_h = (int)(rect.bottom - rect.top);
  341. ImGuiIO& io = ImGui::GetIO();
  342. io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
  343. 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.
  344. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  345. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  346. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  347. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  348. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  349. io.KeyMap[ImGuiKey_End] = VK_END;
  350. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  351. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  352. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  353. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  354. io.KeyMap[ImGuiKey_A] = 'A';
  355. io.KeyMap[ImGuiKey_C] = 'C';
  356. io.KeyMap[ImGuiKey_V] = 'V';
  357. io.KeyMap[ImGuiKey_X] = 'X';
  358. io.KeyMap[ImGuiKey_Y] = 'Y';
  359. io.KeyMap[ImGuiKey_Z] = 'Z';
  360. io.RenderDrawListsFn = ImGui_ImplDX11_RenderDrawLists;
  361. io.ImeWindowHandle = hwnd;
  362. return true;
  363. }
  364. void ImGui_ImplDX11_Shutdown()
  365. {
  366. if (g_pd3dDeviceContext) g_pd3dDeviceContext->ClearState();
  367. if (g_pFontSampler) g_pFontSampler->Release();
  368. if (ID3D11ShaderResourceView* font_texture_view = (ID3D11ShaderResourceView*)ImGui::GetIO().Fonts->TexID)
  369. font_texture_view->Release();
  370. if (g_pVB) g_pVB->Release();
  371. if (g_blendState) g_blendState->Release();
  372. if (g_pPixelShader) g_pPixelShader->Release();
  373. if (g_pPixelShaderBlob) g_pPixelShaderBlob->Release();
  374. if (g_pVertexConstantBuffer) g_pVertexConstantBuffer->Release();
  375. if (g_pInputLayout) g_pInputLayout->Release();
  376. if (g_pVertexShader) g_pVertexShader->Release();
  377. if (g_pVertexShaderBlob) g_pVertexShaderBlob->Release();
  378. ImGui::Shutdown();
  379. }
  380. void ImGui_ImplDX11_NewFrame()
  381. {
  382. if (!g_FontTextureLoaded)
  383. ImGui_ImplDX11_InitFontsTexture();
  384. ImGuiIO& io = ImGui::GetIO();
  385. // Setup time step
  386. INT64 current_time;
  387. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  388. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  389. g_Time = current_time;
  390. // Read keyboard modifiers inputs
  391. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  392. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  393. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  394. // io.MousePos : filled by WM_MOUSEMOVE events
  395. // io.MouseDown : filled by WM_*BUTTON* events
  396. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  397. // Start the frame
  398. ImGui::NewFrame();
  399. }