main.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // ImGui - standalone example application for DirectX 11
  2. #include <windows.h>
  3. #include "../../imgui.h"
  4. // DirectX 11
  5. #include <d3d11.h>
  6. #include <d3dcompiler.h>
  7. #define DIRECTINPUT_VERSION 0x0800
  8. #include <dinput.h>
  9. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
  10. static HWND hWnd;
  11. static ID3D11Device* g_pd3dDevice = NULL;
  12. static ID3D11DeviceContext* g_pd3dDeviceImmediateContext = NULL;
  13. static IDXGISwapChain* g_pSwapChain = NULL;
  14. static ID3D11Buffer* g_pVB = NULL;
  15. static ID3D11RenderTargetView* g_mainRenderTargetView;
  16. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  17. static ID3D11VertexShader* g_pVertexShader = NULL;
  18. static ID3D11InputLayout* g_pInputLayout = NULL;
  19. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  20. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  21. static ID3D11PixelShader* g_pPixelShader = NULL;
  22. static ID3D11SamplerState* g_pFontSampler = NULL;
  23. static ID3D11BlendState* g_blendState = NULL;
  24. struct CUSTOMVERTEX
  25. {
  26. float pos[2];
  27. float uv[2];
  28. unsigned int col;
  29. };
  30. struct VERTEX_CONSTANT_BUFFER
  31. {
  32. float mvp[4][4];
  33. };
  34. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  35. // If text or lines are blurry when integrating ImGui in your engine:
  36. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  37. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
  38. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  39. {
  40. size_t total_vtx_count = 0;
  41. for (int n = 0; n < cmd_lists_count; n++)
  42. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  43. if (total_vtx_count == 0)
  44. return;
  45. // Copy and convert all vertices into a single contiguous buffer
  46. D3D11_MAPPED_SUBRESOURCE mappedResource;
  47. if (g_pd3dDeviceImmediateContext->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  48. return;
  49. CUSTOMVERTEX* vtx_dst = (CUSTOMVERTEX*)mappedResource.pData;
  50. for (int n = 0; n < cmd_lists_count; n++)
  51. {
  52. const ImDrawList* cmd_list = cmd_lists[n];
  53. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  54. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  55. {
  56. vtx_dst->pos[0] = vtx_src->pos.x;
  57. vtx_dst->pos[1] = vtx_src->pos.y;
  58. vtx_dst->uv[0] = vtx_src->uv.x;
  59. vtx_dst->uv[1] = vtx_src->uv.y;
  60. vtx_dst->col = vtx_src->col;
  61. vtx_dst++;
  62. vtx_src++;
  63. }
  64. }
  65. g_pd3dDeviceImmediateContext->Unmap(g_pVB, 0);
  66. // Setup orthographic projection matrix into our constant buffer
  67. {
  68. D3D11_MAPPED_SUBRESOURCE mappedResource;
  69. if (g_pd3dDeviceImmediateContext->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  70. return;
  71. VERTEX_CONSTANT_BUFFER* pConstantBuffer = (VERTEX_CONSTANT_BUFFER*)mappedResource.pData;
  72. const float L = 0.0f;
  73. const float R = ImGui::GetIO().DisplaySize.x;
  74. const float B = ImGui::GetIO().DisplaySize.y;
  75. const float T = 0.0f;
  76. const float mvp[4][4] =
  77. {
  78. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f},
  79. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f,},
  80. { 0.0f, 0.0f, 0.5f, 0.0f },
  81. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  82. };
  83. memcpy(&pConstantBuffer->mvp, mvp, sizeof(mvp));
  84. g_pd3dDeviceImmediateContext->Unmap(g_pVertexConstantBuffer, 0);
  85. }
  86. // Setup viewport
  87. {
  88. D3D11_VIEWPORT vp;
  89. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  90. vp.Width = ImGui::GetIO().DisplaySize.x;
  91. vp.Height = ImGui::GetIO().DisplaySize.y;
  92. vp.MinDepth = 0.0f;
  93. vp.MaxDepth = 1.0f;
  94. vp.TopLeftX = 0;
  95. vp.TopLeftY = 0;
  96. g_pd3dDeviceImmediateContext->RSSetViewports(1, &vp);
  97. }
  98. // Bind shader and vertex buffers
  99. unsigned int stride = sizeof(CUSTOMVERTEX);
  100. unsigned int offset = 0;
  101. g_pd3dDeviceImmediateContext->IASetInputLayout(g_pInputLayout);
  102. g_pd3dDeviceImmediateContext->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  103. g_pd3dDeviceImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  104. g_pd3dDeviceImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
  105. g_pd3dDeviceImmediateContext->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  106. g_pd3dDeviceImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);
  107. g_pd3dDeviceImmediateContext->PSSetSamplers(0, 1, &g_pFontSampler);
  108. // Setup render state
  109. const float blendFactor[4] = { 0.f, 0.f, 0.f, 0.f };
  110. g_pd3dDeviceImmediateContext->OMSetBlendState(g_blendState, blendFactor, 0xffffffff);
  111. // Render command lists
  112. int vtx_offset = 0;
  113. for (int n = 0; n < cmd_lists_count; n++)
  114. {
  115. // Render command list
  116. const ImDrawList* cmd_list = cmd_lists[n];
  117. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  118. {
  119. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  120. const D3D11_RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
  121. g_pd3dDeviceImmediateContext->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->texture_id);
  122. g_pd3dDeviceImmediateContext->RSSetScissorRects(1, &r);
  123. g_pd3dDeviceImmediateContext->Draw(pcmd->vtx_count, vtx_offset);
  124. vtx_offset += pcmd->vtx_count;
  125. }
  126. }
  127. // Restore modified state
  128. g_pd3dDeviceImmediateContext->IASetInputLayout(NULL);
  129. g_pd3dDeviceImmediateContext->PSSetShader(NULL, NULL, 0);
  130. g_pd3dDeviceImmediateContext->VSSetShader(NULL, NULL, 0);
  131. }
  132. HRESULT InitDeviceD3D(HWND hWnd)
  133. {
  134. // Setup swap chain
  135. DXGI_SWAP_CHAIN_DESC sd;
  136. {
  137. ZeroMemory(&sd, sizeof(sd));
  138. sd.BufferCount = 2;
  139. sd.BufferDesc.Width = 0;
  140. sd.BufferDesc.Height = 0;
  141. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  142. sd.BufferDesc.RefreshRate.Numerator = 60;
  143. sd.BufferDesc.RefreshRate.Denominator = 1;
  144. sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
  145. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  146. sd.OutputWindow = hWnd;
  147. sd.SampleDesc.Count = 1;
  148. sd.SampleDesc.Quality = 0;
  149. sd.Windowed = TRUE;
  150. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  151. }
  152. UINT createDeviceFlags = 0;
  153. #ifdef _DEBUG
  154. createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
  155. #endif
  156. D3D_FEATURE_LEVEL featureLevel;
  157. const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
  158. if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceImmediateContext) != S_OK)
  159. return E_FAIL;
  160. // Setup rasterizer
  161. {
  162. D3D11_RASTERIZER_DESC RSDesc;
  163. memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
  164. RSDesc.FillMode = D3D11_FILL_SOLID;
  165. RSDesc.CullMode = D3D11_CULL_NONE;
  166. RSDesc.FrontCounterClockwise = FALSE;
  167. RSDesc.DepthBias = 0;
  168. RSDesc.SlopeScaledDepthBias = 0.0f;
  169. RSDesc.DepthBiasClamp = 0;
  170. RSDesc.DepthClipEnable = TRUE;
  171. RSDesc.ScissorEnable = TRUE;
  172. RSDesc.AntialiasedLineEnable = FALSE;
  173. RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;
  174. ID3D11RasterizerState* pRState = NULL;
  175. g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
  176. g_pd3dDeviceImmediateContext->RSSetState(pRState);
  177. pRState->Release();
  178. }
  179. // Create the render target
  180. {
  181. ID3D11Texture2D* pBackBuffer;
  182. D3D11_RENDER_TARGET_VIEW_DESC render_target_view_desc;
  183. ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
  184. render_target_view_desc.Format = sd.BufferDesc.Format;
  185. render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  186. g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
  187. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
  188. g_pd3dDeviceImmediateContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
  189. pBackBuffer->Release();
  190. }
  191. // Create the vertex shader
  192. {
  193. static const char* vertexShader =
  194. "cbuffer vertexBuffer : register(c0) \
  195. {\
  196. float4x4 ProjectionMatrix; \
  197. };\
  198. struct VS_INPUT\
  199. {\
  200. float2 pos : POSITION;\
  201. float4 col : COLOR0;\
  202. float2 uv : TEXCOORD0;\
  203. };\
  204. \
  205. struct PS_INPUT\
  206. {\
  207. float4 pos : SV_POSITION;\
  208. float4 col : COLOR0;\
  209. float2 uv : TEXCOORD0;\
  210. };\
  211. \
  212. PS_INPUT main(VS_INPUT input)\
  213. {\
  214. PS_INPUT output;\
  215. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  216. output.col = input.col;\
  217. output.uv = input.uv;\
  218. return output;\
  219. }";
  220. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
  221. 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!
  222. return E_FAIL;
  223. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  224. return E_FAIL;
  225. // Create the input layout
  226. D3D11_INPUT_ELEMENT_DESC localLayout[] = {
  227. { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  228. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((CUSTOMVERTEX*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  229. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  230. };
  231. if (g_pd3dDevice->CreateInputLayout(localLayout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  232. return E_FAIL;
  233. // Create the constant buffer
  234. {
  235. D3D11_BUFFER_DESC cbDesc;
  236. cbDesc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  237. cbDesc.Usage = D3D11_USAGE_DYNAMIC;
  238. cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  239. cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  240. cbDesc.MiscFlags = 0;
  241. g_pd3dDevice->CreateBuffer(&cbDesc, NULL, &g_pVertexConstantBuffer);
  242. }
  243. }
  244. // Create the pixel shader
  245. {
  246. static const char* pixelShader =
  247. "struct PS_INPUT\
  248. {\
  249. float4 pos : SV_POSITION;\
  250. float4 col : COLOR0;\
  251. float2 uv : TEXCOORD0;\
  252. };\
  253. sampler sampler0;\
  254. Texture2D texture0;\
  255. \
  256. float4 main(PS_INPUT input) : SV_Target\
  257. {\
  258. float4 out_col = input.col; \
  259. out_col.w *= texture0.Sample(sampler0, input.uv).w; \
  260. return out_col; \
  261. }";
  262. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
  263. 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!
  264. return E_FAIL;
  265. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  266. return E_FAIL;
  267. }
  268. // Create the blending setup
  269. {
  270. D3D11_BLEND_DESC desc;
  271. ZeroMemory(&desc, sizeof(desc));
  272. desc.AlphaToCoverageEnable = false;
  273. desc.RenderTarget[0].BlendEnable = true;
  274. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  275. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  276. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  277. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  278. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  279. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  280. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  281. g_pd3dDevice->CreateBlendState(&desc, &g_blendState);
  282. }
  283. return S_OK;
  284. }
  285. void CleanupDevice()
  286. {
  287. if (g_pd3dDeviceImmediateContext) g_pd3dDeviceImmediateContext->ClearState();
  288. // InitImGui
  289. if (g_pFontSampler) g_pFontSampler->Release();
  290. if (ID3D11ShaderResourceView* font_texture_view = (ID3D11ShaderResourceView*)ImGui::GetIO().Font->TexID)
  291. font_texture_view->Release();
  292. if (g_pVB) g_pVB->Release();
  293. // InitDeviceD3D
  294. if (g_blendState) g_blendState->Release();
  295. if (g_pPixelShader) g_pPixelShader->Release();
  296. if (g_pPixelShaderBlob) g_pPixelShaderBlob->Release();
  297. if (g_pVertexConstantBuffer) g_pVertexConstantBuffer->Release();
  298. if (g_pInputLayout) g_pInputLayout->Release();
  299. if (g_pVertexShader) g_pVertexShader->Release();
  300. if (g_pVertexShaderBlob) g_pVertexShaderBlob->Release();
  301. if (g_mainRenderTargetView) g_mainRenderTargetView->Release();
  302. if (g_pSwapChain) g_pSwapChain->Release();
  303. if (g_pd3dDeviceImmediateContext) g_pd3dDeviceImmediateContext->Release();
  304. if (g_pd3dDevice) g_pd3dDevice->Release();
  305. }
  306. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  307. {
  308. ImGuiIO& io = ImGui::GetIO();
  309. switch (msg)
  310. {
  311. case WM_LBUTTONDOWN:
  312. io.MouseDown[0] = true;
  313. return true;
  314. case WM_LBUTTONUP:
  315. io.MouseDown[0] = false;
  316. return true;
  317. case WM_RBUTTONDOWN:
  318. io.MouseDown[1] = true;
  319. return true;
  320. case WM_RBUTTONUP:
  321. io.MouseDown[1] = false;
  322. return true;
  323. case WM_MOUSEWHEEL:
  324. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  325. return true;
  326. case WM_MOUSEMOVE:
  327. // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  328. io.MousePos.x = (signed short)(lParam);
  329. io.MousePos.y = (signed short)(lParam >> 16);
  330. return true;
  331. case WM_CHAR:
  332. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  333. if (wParam > 0 && wParam < 0x10000)
  334. io.AddInputCharacter((unsigned short)wParam);
  335. return true;
  336. case WM_DESTROY:
  337. CleanupDevice();
  338. PostQuitMessage(0);
  339. return 0;
  340. }
  341. return DefWindowProc(hWnd, msg, wParam, lParam);
  342. }
  343. void LoadFontTexture(ImFont* font)
  344. {
  345. IM_ASSERT(font && font->IsLoaded());
  346. // Create texture
  347. D3D11_TEXTURE2D_DESC desc;
  348. ZeroMemory(&desc, sizeof(desc));
  349. desc.Width = font->TexWidth;
  350. desc.Height = font->TexHeight;
  351. desc.MipLevels = 1;
  352. desc.ArraySize = 1;
  353. desc.Format = DXGI_FORMAT_A8_UNORM;
  354. desc.SampleDesc.Count = 1;
  355. desc.Usage = D3D11_USAGE_DEFAULT;
  356. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  357. desc.CPUAccessFlags = 0;
  358. ID3D11Texture2D *pTexture = NULL;
  359. D3D11_SUBRESOURCE_DATA subResource;
  360. subResource.pSysMem = font->TexPixels;
  361. subResource.SysMemPitch = desc.Width * 1;
  362. subResource.SysMemSlicePitch = 0;
  363. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  364. // Create texture view
  365. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  366. ZeroMemory(&srvDesc, sizeof(srvDesc));
  367. srvDesc.Format = DXGI_FORMAT_A8_UNORM;
  368. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  369. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  370. srvDesc.Texture2D.MostDetailedMip = 0;
  371. ID3D11ShaderResourceView* font_texture_view = NULL;
  372. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &font_texture_view);
  373. pTexture->Release();
  374. // Store ID
  375. font->TexID = (void *)font_texture_view;
  376. }
  377. void InitImGui()
  378. {
  379. RECT rect;
  380. GetClientRect(hWnd, &rect);
  381. int display_w = (int)(rect.right - rect.left);
  382. int display_h = (int)(rect.bottom - rect.top);
  383. ImGuiIO& io = ImGui::GetIO();
  384. io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
  385. io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our time step is variable)
  386. io.PixelCenterOffset = 0.0f; // Align Direct3D Texels
  387. 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.
  388. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  389. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  390. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  391. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  392. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  393. io.KeyMap[ImGuiKey_End] = VK_END;
  394. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  395. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  396. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  397. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  398. io.KeyMap[ImGuiKey_A] = 'A';
  399. io.KeyMap[ImGuiKey_C] = 'C';
  400. io.KeyMap[ImGuiKey_V] = 'V';
  401. io.KeyMap[ImGuiKey_X] = 'X';
  402. io.KeyMap[ImGuiKey_Y] = 'Y';
  403. io.KeyMap[ImGuiKey_Z] = 'Z';
  404. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  405. // Create the vertex buffer
  406. {
  407. D3D11_BUFFER_DESC bufferDesc;
  408. memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
  409. bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
  410. bufferDesc.ByteWidth = 10000 * sizeof(CUSTOMVERTEX);
  411. bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  412. bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  413. bufferDesc.MiscFlags = 0;
  414. if (g_pd3dDevice->CreateBuffer(&bufferDesc, NULL, &g_pVB) < 0)
  415. {
  416. IM_ASSERT(0);
  417. return;
  418. }
  419. }
  420. // Load font
  421. io.Font = new ImFont();
  422. io.Font->LoadDefault();
  423. //io.Font->LoadFromFileTTF("myfont.ttf", font_size_px, ImFont::GetGlyphRangesDefault());
  424. //io.Font->DisplayOffset.y += 0.0f;
  425. LoadFontTexture(io.Font);
  426. // Create texture sampler
  427. {
  428. D3D11_SAMPLER_DESC desc;
  429. ZeroMemory(&desc, sizeof(desc));
  430. desc.Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
  431. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  432. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  433. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  434. desc.MipLODBias = 0.f;
  435. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  436. desc.MinLOD = 0.f;
  437. desc.MaxLOD = 0.f;
  438. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  439. }
  440. }
  441. INT64 ticks_per_second = 0;
  442. INT64 last_time = 0;
  443. void UpdateImGui()
  444. {
  445. ImGuiIO& io = ImGui::GetIO();
  446. // Setup time step
  447. INT64 current_time;
  448. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  449. io.DeltaTime = (float)(current_time - last_time) / ticks_per_second;
  450. last_time = current_time;
  451. // Setup inputs
  452. // (we already got mouse position, buttons, wheel from the window message callback)
  453. BYTE keystate[256];
  454. GetKeyboardState(keystate);
  455. for (int i = 0; i < 256; i++)
  456. io.KeysDown[i] = (keystate[i] & 0x80) != 0;
  457. io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
  458. io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
  459. // io.MousePos : filled by WM_MOUSEMOVE event
  460. // io.MouseDown : filled by WM_*BUTTON* events
  461. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  462. // Start the frame
  463. ImGui::NewFrame();
  464. }
  465. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
  466. {
  467. // Register the window class
  468. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, "ImGui Example", NULL };
  469. RegisterClassEx(&wc);
  470. // Create the application's window
  471. hWnd = CreateWindow("ImGui Example", "ImGui DirectX11 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  472. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  473. return 1;
  474. if (!QueryPerformanceCounter((LARGE_INTEGER *)&last_time))
  475. return 1;
  476. // Initialize Direct3D
  477. if (InitDeviceD3D(hWnd) < 0)
  478. {
  479. CleanupDevice();
  480. UnregisterClass("ImGui Example", wc.hInstance);
  481. return 1;
  482. }
  483. // Show the window
  484. ShowWindow(hWnd, SW_SHOWDEFAULT);
  485. UpdateWindow(hWnd);
  486. InitImGui();
  487. // Enter the message loop
  488. MSG msg;
  489. ZeroMemory(&msg, sizeof(msg));
  490. while (msg.message != WM_QUIT)
  491. {
  492. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  493. {
  494. TranslateMessage(&msg);
  495. DispatchMessage(&msg);
  496. continue;
  497. }
  498. UpdateImGui();
  499. static bool show_test_window = true;
  500. static bool show_another_window = false;
  501. // 1. Show a simple window
  502. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  503. {
  504. static float f;
  505. ImGui::Text("Hello, world!");
  506. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  507. show_test_window ^= ImGui::Button("Test Window");
  508. show_another_window ^= ImGui::Button("Another Window");
  509. static ImFont* font2 = NULL;
  510. if (!font2) { font2 = new ImFont(); font2->LoadFromFileTTF("../../extra_fonts/ArialUni.ttf", 30.0f); LoadFontTexture(font2); }
  511. ImGui::Image(font2->TexID, ImVec2((float)font2->TexWidth, (FLOAT)font2->TexHeight));
  512. //ImGui::GetWindowDrawList()->AddText(font2, 30.0f, ImGui::GetCursorScreenPos(), 0xFFFFFFFF, "Another font");
  513. // Calculate and show frame rate
  514. static float ms_per_frame[120] = { 0 };
  515. static int ms_per_frame_idx = 0;
  516. static float ms_per_frame_accum = 0.0f;
  517. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  518. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  519. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  520. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  521. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  522. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  523. }
  524. // 2. Show another simple window, this time using an explicit Begin/End pair
  525. if (show_another_window)
  526. {
  527. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  528. ImGui::Text("Hello");
  529. ImGui::End();
  530. }
  531. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  532. if (show_test_window)
  533. {
  534. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  535. ImGui::ShowTestWindow(&show_test_window);
  536. }
  537. // Rendering
  538. float clearColor[4] = { 204 / 255.f, 153 / 255.f, 153 / 255.f };
  539. g_pd3dDeviceImmediateContext->ClearRenderTargetView(g_mainRenderTargetView, clearColor);
  540. ImGui::Render();
  541. g_pSwapChain->Present(0, 0);
  542. }
  543. ImGui::Shutdown();
  544. UnregisterClass("ImGui Example", wc.hInstance);
  545. return 0;
  546. }