main.cpp 23 KB

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