main.cpp 23 KB

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