main.cpp 23 KB

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