imgui_impl_dx10.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. // ImGui Win32 + DirectX10 binding
  2. // Implemented features:
  3. // [X] User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  4. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  5. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  6. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  7. // https://github.com/ocornut/imgui
  8. #include "imgui.h"
  9. #include "imgui_impl_dx10.h"
  10. // DirectX
  11. #include <d3d10_1.h>
  12. #include <d3d10.h>
  13. #include <d3dcompiler.h>
  14. #define DIRECTINPUT_VERSION 0x0800
  15. #include <dinput.h>
  16. // Data
  17. static INT64 g_Time = 0;
  18. static INT64 g_TicksPerSecond = 0;
  19. static HWND g_hWnd = 0;
  20. static ID3D10Device* g_pd3dDevice = NULL;
  21. static ID3D10Buffer* g_pVB = NULL;
  22. static ID3D10Buffer* g_pIB = NULL;
  23. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  24. static ID3D10VertexShader* g_pVertexShader = NULL;
  25. static ID3D10InputLayout* g_pInputLayout = NULL;
  26. static ID3D10Buffer* g_pVertexConstantBuffer = NULL;
  27. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  28. static ID3D10PixelShader* g_pPixelShader = NULL;
  29. static ID3D10SamplerState* g_pFontSampler = NULL;
  30. static ID3D10ShaderResourceView*g_pFontTextureView = NULL;
  31. static ID3D10RasterizerState* g_pRasterizerState = NULL;
  32. static ID3D10BlendState* g_pBlendState = NULL;
  33. static ID3D10DepthStencilState* g_pDepthStencilState = NULL;
  34. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  35. struct VERTEX_CONSTANT_BUFFER
  36. {
  37. float mvp[4][4];
  38. };
  39. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  40. // If text or lines are blurry when integrating ImGui in your engine:
  41. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  42. void ImGui_ImplDX10_RenderDrawLists(ImDrawData* draw_data)
  43. {
  44. ID3D10Device* ctx = g_pd3dDevice;
  45. // Create and grow vertex/index buffers if needed
  46. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  47. {
  48. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  49. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  50. D3D10_BUFFER_DESC desc;
  51. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  52. desc.Usage = D3D10_USAGE_DYNAMIC;
  53. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  54. desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  55. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  56. desc.MiscFlags = 0;
  57. if (ctx->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  58. return;
  59. }
  60. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  61. {
  62. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  63. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  64. D3D10_BUFFER_DESC desc;
  65. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  66. desc.Usage = D3D10_USAGE_DYNAMIC;
  67. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  68. desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
  69. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  70. if (ctx->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  71. return;
  72. }
  73. // Copy and convert all vertices into a single contiguous buffer
  74. ImDrawVert* vtx_dst = NULL;
  75. ImDrawIdx* idx_dst = NULL;
  76. g_pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
  77. g_pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
  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.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  82. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  83. vtx_dst += cmd_list->VtxBuffer.Size;
  84. idx_dst += cmd_list->IdxBuffer.Size;
  85. }
  86. g_pVB->Unmap();
  87. g_pIB->Unmap();
  88. // Setup orthographic projection matrix into our constant buffer
  89. {
  90. void* mapped_resource;
  91. if (g_pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  92. return;
  93. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource;
  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(&constant_buffer->mvp, mvp, sizeof(mvp));
  106. g_pVertexConstantBuffer->Unmap();
  107. }
  108. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  109. struct BACKUP_DX10_STATE
  110. {
  111. UINT ScissorRectsCount, ViewportsCount;
  112. D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  113. D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  114. ID3D10RasterizerState* RS;
  115. ID3D10BlendState* BlendState;
  116. FLOAT BlendFactor[4];
  117. UINT SampleMask;
  118. UINT StencilRef;
  119. ID3D10DepthStencilState* DepthStencilState;
  120. ID3D10ShaderResourceView* PSShaderResource;
  121. ID3D10SamplerState* PSSampler;
  122. ID3D10PixelShader* PS;
  123. ID3D10VertexShader* VS;
  124. D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  125. ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  126. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  127. DXGI_FORMAT IndexBufferFormat;
  128. ID3D10InputLayout* InputLayout;
  129. };
  130. BACKUP_DX10_STATE old;
  131. old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  132. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  133. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  134. ctx->RSGetState(&old.RS);
  135. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  136. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  137. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  138. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  139. ctx->PSGetShader(&old.PS);
  140. ctx->VSGetShader(&old.VS);
  141. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  142. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  143. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  144. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  145. ctx->IAGetInputLayout(&old.InputLayout);
  146. // Setup viewport
  147. D3D10_VIEWPORT vp;
  148. memset(&vp, 0, sizeof(D3D10_VIEWPORT));
  149. vp.Width = (UINT)ImGui::GetIO().DisplaySize.x;
  150. vp.Height = (UINT)ImGui::GetIO().DisplaySize.y;
  151. vp.MinDepth = 0.0f;
  152. vp.MaxDepth = 1.0f;
  153. vp.TopLeftX = vp.TopLeftY = 0;
  154. ctx->RSSetViewports(1, &vp);
  155. // Bind shader and vertex buffers
  156. unsigned int stride = sizeof(ImDrawVert);
  157. unsigned int offset = 0;
  158. ctx->IASetInputLayout(g_pInputLayout);
  159. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  160. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  161. ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  162. ctx->VSSetShader(g_pVertexShader);
  163. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  164. ctx->PSSetShader(g_pPixelShader);
  165. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  166. // Setup render state
  167. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  168. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  169. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  170. ctx->RSSetState(g_pRasterizerState);
  171. // Render command lists
  172. int vtx_offset = 0;
  173. int idx_offset = 0;
  174. for (int n = 0; n < draw_data->CmdListsCount; n++)
  175. {
  176. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  177. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  178. {
  179. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  180. if (pcmd->UserCallback)
  181. {
  182. pcmd->UserCallback(cmd_list, pcmd);
  183. }
  184. else
  185. {
  186. const D3D10_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  187. ctx->PSSetShaderResources(0, 1, (ID3D10ShaderResourceView**)&pcmd->TextureId);
  188. ctx->RSSetScissorRects(1, &r);
  189. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  190. }
  191. idx_offset += pcmd->ElemCount;
  192. }
  193. vtx_offset += cmd_list->VtxBuffer.Size;
  194. }
  195. // Restore modified DX state
  196. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  197. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  198. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  199. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  200. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  201. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  202. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  203. ctx->PSSetShader(old.PS); if (old.PS) old.PS->Release();
  204. ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release();
  205. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  206. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  207. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  208. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  209. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  210. }
  211. static bool IsAnyMouseButtonDown()
  212. {
  213. ImGuiIO& io = ImGui::GetIO();
  214. for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
  215. if (io.MouseDown[n])
  216. return true;
  217. return false;
  218. }
  219. // Process Win32 mouse/keyboard inputs.
  220. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  221. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  222. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  223. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  224. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
  225. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
  226. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  227. {
  228. ImGuiIO& io = ImGui::GetIO();
  229. switch (msg)
  230. {
  231. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  232. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  233. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  234. {
  235. int button = 0;
  236. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  237. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  238. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  239. if (!IsAnyMouseButtonDown() && GetCapture() == NULL)
  240. SetCapture(hwnd);
  241. io.MouseDown[button] = true;
  242. return 0;
  243. }
  244. case WM_LBUTTONUP:
  245. case WM_RBUTTONUP:
  246. case WM_MBUTTONUP:
  247. {
  248. int button = 0;
  249. if (msg == WM_LBUTTONUP) button = 0;
  250. if (msg == WM_RBUTTONUP) button = 1;
  251. if (msg == WM_MBUTTONUP) button = 2;
  252. io.MouseDown[button] = false;
  253. if (!IsAnyMouseButtonDown() && GetCapture() == hwnd)
  254. ReleaseCapture();
  255. return 0;
  256. }
  257. case WM_MOUSEWHEEL:
  258. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  259. return 0;
  260. case WM_MOUSEHWHEEL:
  261. io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  262. return 0;
  263. case WM_MOUSEMOVE:
  264. io.MousePos.x = (signed short)(lParam);
  265. io.MousePos.y = (signed short)(lParam >> 16);
  266. return 0;
  267. case WM_KEYDOWN:
  268. case WM_SYSKEYDOWN:
  269. if (wParam < 256)
  270. io.KeysDown[wParam] = 1;
  271. return 0;
  272. case WM_KEYUP:
  273. case WM_SYSKEYUP:
  274. if (wParam < 256)
  275. io.KeysDown[wParam] = 0;
  276. return 0;
  277. case WM_CHAR:
  278. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  279. if (wParam > 0 && wParam < 0x10000)
  280. io.AddInputCharacter((unsigned short)wParam);
  281. return 0;
  282. }
  283. return 0;
  284. }
  285. static void ImGui_ImplDX10_CreateFontsTexture()
  286. {
  287. ImGuiIO& io = ImGui::GetIO();
  288. // Build
  289. unsigned char* pixels;
  290. int width, height;
  291. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  292. // Create DX10 texture
  293. {
  294. D3D10_TEXTURE2D_DESC desc;
  295. ZeroMemory(&desc, sizeof(desc));
  296. desc.Width = width;
  297. desc.Height = height;
  298. desc.MipLevels = 1;
  299. desc.ArraySize = 1;
  300. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  301. desc.SampleDesc.Count = 1;
  302. desc.Usage = D3D10_USAGE_DEFAULT;
  303. desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
  304. desc.CPUAccessFlags = 0;
  305. ID3D10Texture2D *pTexture = NULL;
  306. D3D10_SUBRESOURCE_DATA subResource;
  307. subResource.pSysMem = pixels;
  308. subResource.SysMemPitch = desc.Width * 4;
  309. subResource.SysMemSlicePitch = 0;
  310. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  311. // Create texture view
  312. D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
  313. ZeroMemory(&srv_desc, sizeof(srv_desc));
  314. srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  315. srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
  316. srv_desc.Texture2D.MipLevels = desc.MipLevels;
  317. srv_desc.Texture2D.MostDetailedMip = 0;
  318. g_pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &g_pFontTextureView);
  319. pTexture->Release();
  320. }
  321. // Store our identifier
  322. io.Fonts->TexID = (void *)g_pFontTextureView;
  323. // Create texture sampler
  324. {
  325. D3D10_SAMPLER_DESC desc;
  326. ZeroMemory(&desc, sizeof(desc));
  327. desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
  328. desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP;
  329. desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP;
  330. desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP;
  331. desc.MipLODBias = 0.f;
  332. desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
  333. desc.MinLOD = 0.f;
  334. desc.MaxLOD = 0.f;
  335. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  336. }
  337. // Cleanup (don't clear the input data if you want to append new fonts later)
  338. io.Fonts->ClearInputData();
  339. io.Fonts->ClearTexData();
  340. }
  341. bool ImGui_ImplDX10_CreateDeviceObjects()
  342. {
  343. if (!g_pd3dDevice)
  344. return false;
  345. if (g_pFontSampler)
  346. ImGui_ImplDX10_InvalidateDeviceObjects();
  347. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  348. // If you would like to use this DX11 sample code but remove this dependency you can:
  349. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  350. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  351. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  352. // Create the vertex shader
  353. {
  354. static const char* vertexShader =
  355. "cbuffer vertexBuffer : register(b0) \
  356. {\
  357. float4x4 ProjectionMatrix; \
  358. };\
  359. struct VS_INPUT\
  360. {\
  361. float2 pos : POSITION;\
  362. float4 col : COLOR0;\
  363. float2 uv : TEXCOORD0;\
  364. };\
  365. \
  366. struct PS_INPUT\
  367. {\
  368. float4 pos : SV_POSITION;\
  369. float4 col : COLOR0;\
  370. float2 uv : TEXCOORD0;\
  371. };\
  372. \
  373. PS_INPUT main(VS_INPUT input)\
  374. {\
  375. PS_INPUT output;\
  376. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  377. output.col = input.col;\
  378. output.uv = input.uv;\
  379. return output;\
  380. }";
  381. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  382. 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!
  383. return false;
  384. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK)
  385. return false;
  386. // Create the input layout
  387. D3D10_INPUT_ELEMENT_DESC local_layout[] =
  388. {
  389. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  390. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  391. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  392. };
  393. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  394. return false;
  395. // Create the constant buffer
  396. {
  397. D3D10_BUFFER_DESC desc;
  398. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  399. desc.Usage = D3D10_USAGE_DYNAMIC;
  400. desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
  401. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  402. desc.MiscFlags = 0;
  403. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  404. }
  405. }
  406. // Create the pixel shader
  407. {
  408. static const char* pixelShader =
  409. "struct PS_INPUT\
  410. {\
  411. float4 pos : SV_POSITION;\
  412. float4 col : COLOR0;\
  413. float2 uv : TEXCOORD0;\
  414. };\
  415. sampler sampler0;\
  416. Texture2D texture0;\
  417. \
  418. float4 main(PS_INPUT input) : SV_Target\
  419. {\
  420. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  421. return out_col; \
  422. }";
  423. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  424. 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!
  425. return false;
  426. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK)
  427. return false;
  428. }
  429. // Create the blending setup
  430. {
  431. D3D10_BLEND_DESC desc;
  432. ZeroMemory(&desc, sizeof(desc));
  433. desc.AlphaToCoverageEnable = false;
  434. desc.BlendEnable[0] = true;
  435. desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
  436. desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
  437. desc.BlendOp = D3D10_BLEND_OP_ADD;
  438. desc.SrcBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
  439. desc.DestBlendAlpha = D3D10_BLEND_ZERO;
  440. desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
  441. desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
  442. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  443. }
  444. // Create the rasterizer state
  445. {
  446. D3D10_RASTERIZER_DESC desc;
  447. ZeroMemory(&desc, sizeof(desc));
  448. desc.FillMode = D3D10_FILL_SOLID;
  449. desc.CullMode = D3D10_CULL_NONE;
  450. desc.ScissorEnable = true;
  451. desc.DepthClipEnable = true;
  452. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  453. }
  454. // Create depth-stencil State
  455. {
  456. D3D10_DEPTH_STENCIL_DESC desc;
  457. ZeroMemory(&desc, sizeof(desc));
  458. desc.DepthEnable = false;
  459. desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
  460. desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
  461. desc.StencilEnable = false;
  462. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
  463. desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
  464. desc.BackFace = desc.FrontFace;
  465. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  466. }
  467. ImGui_ImplDX10_CreateFontsTexture();
  468. return true;
  469. }
  470. void ImGui_ImplDX10_InvalidateDeviceObjects()
  471. {
  472. if (!g_pd3dDevice)
  473. return;
  474. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  475. 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.
  476. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  477. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  478. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  479. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  480. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  481. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  482. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  483. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  484. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  485. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  486. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  487. }
  488. bool ImGui_ImplDX10_Init(void* hwnd, ID3D10Device* device)
  489. {
  490. g_hWnd = (HWND)hwnd;
  491. g_pd3dDevice = device;
  492. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  493. return false;
  494. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  495. return false;
  496. ImGuiIO& io = ImGui::GetIO();
  497. 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.
  498. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  499. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  500. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  501. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  502. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  503. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  504. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  505. io.KeyMap[ImGuiKey_End] = VK_END;
  506. io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
  507. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  508. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  509. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  510. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  511. io.KeyMap[ImGuiKey_A] = 'A';
  512. io.KeyMap[ImGuiKey_C] = 'C';
  513. io.KeyMap[ImGuiKey_V] = 'V';
  514. io.KeyMap[ImGuiKey_X] = 'X';
  515. io.KeyMap[ImGuiKey_Y] = 'Y';
  516. io.KeyMap[ImGuiKey_Z] = 'Z';
  517. io.RenderDrawListsFn = ImGui_ImplDX10_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  518. io.ImeWindowHandle = g_hWnd;
  519. return true;
  520. }
  521. void ImGui_ImplDX10_Shutdown()
  522. {
  523. ImGui_ImplDX10_InvalidateDeviceObjects();
  524. ImGui::Shutdown();
  525. g_pd3dDevice = NULL;
  526. g_hWnd = (HWND)0;
  527. }
  528. void ImGui_ImplDX10_NewFrame()
  529. {
  530. if (!g_pFontSampler)
  531. ImGui_ImplDX10_CreateDeviceObjects();
  532. ImGuiIO& io = ImGui::GetIO();
  533. // Setup display size (every frame to accommodate for window resizing)
  534. RECT rect;
  535. GetClientRect(g_hWnd, &rect);
  536. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  537. // Setup time step
  538. INT64 current_time;
  539. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  540. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  541. g_Time = current_time;
  542. // Read keyboard modifiers inputs
  543. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  544. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  545. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  546. io.KeySuper = false;
  547. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  548. // io.MousePos : filled by WM_MOUSEMOVE events
  549. // io.MouseDown : filled by WM_*BUTTON* events
  550. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  551. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  552. if (io.WantMoveMouse)
  553. {
  554. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  555. ClientToScreen(g_hWnd, &pos);
  556. SetCursorPos(pos.x, pos.y);
  557. }
  558. // Hide OS mouse cursor if ImGui is drawing it
  559. if (io.MouseDrawCursor)
  560. SetCursor(NULL);
  561. // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
  562. ImGui::NewFrame();
  563. }