main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #include <windows.h>
  2. #include <mmsystem.h>
  3. #include <d3dx9.h>
  4. #define DIRECTINPUT_VERSION 0x0800
  5. #include <dinput.h>
  6. #include "../../imgui.h"
  7. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
  8. static HWND hWnd;
  9. static LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice
  10. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device
  11. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices
  12. static LPDIRECT3DTEXTURE9 g_pTexture = NULL; // Our texture
  13. struct CUSTOMVERTEX
  14. {
  15. D3DXVECTOR3 position;
  16. D3DCOLOR color;
  17. float tu, tv;
  18. };
  19. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  20. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structuer)
  21. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  22. {
  23. size_t total_vtx_count = 0;
  24. for (int n = 0; n < cmd_lists_count; n++)
  25. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  26. if (total_vtx_count == 0)
  27. return;
  28. // Copy and convert all vertices into a single contiguous buffer
  29. CUSTOMVERTEX* vtx_dst;
  30. if (g_pVB->Lock(0, total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  31. return;
  32. for (int n = 0; n < cmd_lists_count; n++)
  33. {
  34. const ImDrawList* cmd_list = cmd_lists[n];
  35. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  36. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  37. {
  38. vtx_dst->position.x = vtx_src->pos.x;
  39. vtx_dst->position.y = vtx_src->pos.y;
  40. vtx_dst->position.z = 0.0f;
  41. vtx_dst->color = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  42. vtx_dst->tu = vtx_src->uv.x;
  43. vtx_dst->tv = vtx_src->uv.y;
  44. vtx_dst++;
  45. vtx_src++;
  46. }
  47. }
  48. g_pVB->Unlock();
  49. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  50. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  51. // Setup render state: alpha-blending, no face culling, no depth testing
  52. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  53. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  54. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  55. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  56. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  57. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  58. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  59. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  60. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  61. // Setup texture
  62. g_pd3dDevice->SetTexture( 0, g_pTexture );
  63. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
  64. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
  65. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
  66. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  67. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  68. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  69. // Setup orthographic projection matrix
  70. D3DXMATRIXA16 mat;
  71. D3DXMatrixIdentity(&mat);
  72. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat);
  73. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat);
  74. D3DXMatrixOrthoOffCenterLH(&mat, 0.0f, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, 0.0f, -1.0f, +1.0f);
  75. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat);
  76. // Render command lists
  77. int vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those
  78. for (int n = 0; n < cmd_lists_count; n++)
  79. {
  80. const ImDrawList* cmd_list = cmd_lists[n];
  81. // Setup stack of clipping rectangles
  82. bool clip_rect_dirty = true;
  83. int clip_rect_buf_consumed = 0;
  84. ImVector<ImVec4> clip_rect_stack;
  85. clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999));
  86. // Render command list
  87. const ImDrawCmd* pcmd = &cmd_list->commands.front();
  88. const ImDrawCmd* pcmd_end = &cmd_list->commands.back();
  89. while (pcmd <= pcmd_end)
  90. {
  91. const ImDrawCmd& cmd = *pcmd++;
  92. switch (cmd.cmd_type)
  93. {
  94. case ImDrawCmdType_DrawTriangleList:
  95. if (clip_rect_dirty)
  96. {
  97. const ImVec4& clip_rect = clip_rect_stack.back();
  98. const RECT r = { (LONG)clip_rect.x, (LONG)clip_rect.y, (LONG)clip_rect.z, (LONG)clip_rect.w };
  99. g_pd3dDevice->SetScissorRect(&r);
  100. clip_rect_dirty = false;
  101. }
  102. g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_consumed, cmd.vtx_count/3);
  103. vtx_consumed += cmd.vtx_count;
  104. break;
  105. case ImDrawCmdType_PushClipRect:
  106. clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_consumed++]);
  107. clip_rect_dirty = true;
  108. break;
  109. case ImDrawCmdType_PopClipRect:
  110. clip_rect_stack.pop_back();
  111. clip_rect_dirty = true;
  112. break;
  113. }
  114. }
  115. }
  116. }
  117. // Get text data in Win32 clipboard
  118. static const char* ImImpl_GetClipboardTextFn()
  119. {
  120. static char* buf_local = NULL;
  121. if (buf_local)
  122. {
  123. free(buf_local);
  124. buf_local = NULL;
  125. }
  126. if (!OpenClipboard(NULL))
  127. return NULL;
  128. HANDLE buf_handle = GetClipboardData(CF_TEXT);
  129. if (buf_handle == NULL)
  130. return NULL;
  131. if (char* buf_global = (char*)GlobalLock(buf_handle))
  132. buf_local = strdup(buf_global);
  133. GlobalUnlock(buf_handle);
  134. CloseClipboard();
  135. return buf_local;
  136. }
  137. // Set text data in Win32 clipboard
  138. static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
  139. {
  140. if (!OpenClipboard(NULL))
  141. return;
  142. if (!text_end)
  143. text_end = text + strlen(text);
  144. const int buf_length = (text_end - text) + 1;
  145. HGLOBAL buf_handle = GlobalAlloc(GMEM_MOVEABLE, buf_length * sizeof(char));
  146. if (buf_handle == NULL)
  147. return;
  148. char* buf_global = (char *)GlobalLock(buf_handle);
  149. memcpy(buf_global, text, text_end - text);
  150. buf_global[text_end - text] = 0;
  151. GlobalUnlock(buf_handle);
  152. EmptyClipboard();
  153. SetClipboardData(CF_TEXT, buf_handle);
  154. CloseClipboard();
  155. }
  156. HRESULT InitD3D(HWND hWnd)
  157. {
  158. if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
  159. return E_FAIL;
  160. D3DPRESENT_PARAMETERS d3dpp;
  161. ZeroMemory(&d3dpp, sizeof(d3dpp));
  162. d3dpp.Windowed = TRUE;
  163. d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  164. d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
  165. d3dpp.EnableAutoDepthStencil = TRUE;
  166. d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  167. d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  168. // Create the D3DDevice
  169. if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice) < 0)
  170. return E_FAIL;
  171. return S_OK;
  172. }
  173. void Cleanup()
  174. {
  175. if (g_pTexture != NULL)
  176. g_pTexture->Release();
  177. if (g_pd3dDevice != NULL)
  178. g_pd3dDevice->Release();
  179. if (g_pD3D != NULL)
  180. g_pD3D->Release();
  181. }
  182. LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  183. {
  184. ImGuiIO& io = ImGui::GetIO();
  185. switch (msg)
  186. {
  187. case WM_LBUTTONDOWN:
  188. io.MouseDown[0] = true;
  189. return true;
  190. case WM_LBUTTONUP:
  191. io.MouseDown[0] = false;
  192. return true;
  193. case WM_RBUTTONDOWN:
  194. io.MouseDown[1] = true;
  195. return true;
  196. case WM_RBUTTONUP:
  197. io.MouseDown[1] = false;
  198. return true;
  199. case WM_MOUSEWHEEL:
  200. // Mouse wheel: -1,0,+1
  201. io.MouseWheel = GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1 : -1;
  202. return true;
  203. case WM_MOUSEMOVE:
  204. // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  205. io.MousePos.x = (signed short)(lParam);
  206. io.MousePos.y = (signed short)(lParam >> 16);
  207. return true;
  208. case WM_CHAR:
  209. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  210. if (wParam > 1 && wParam < 256)
  211. io.AddInputCharacter((char)wParam);
  212. return true;
  213. case WM_DESTROY:
  214. {
  215. Cleanup();
  216. PostQuitMessage(0);
  217. return 0;
  218. }
  219. }
  220. return DefWindowProc(hWnd, msg, wParam, lParam);
  221. }
  222. void InitImGui()
  223. {
  224. RECT rect;
  225. GetClientRect(hWnd, &rect);
  226. ImGuiIO& io = ImGui::GetIO();
  227. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Display size, in pixels. For clamping windows positions.
  228. 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)
  229. io.PixelCenterOffset = 0.0f; // Align Direct3D Texels
  230. 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.
  231. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  232. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  233. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  234. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  235. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  236. io.KeyMap[ImGuiKey_End] = VK_END;
  237. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  238. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  239. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  240. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  241. io.KeyMap[ImGuiKey_A] = 'A';
  242. io.KeyMap[ImGuiKey_C] = 'C';
  243. io.KeyMap[ImGuiKey_V] = 'V';
  244. io.KeyMap[ImGuiKey_X] = 'X';
  245. io.KeyMap[ImGuiKey_Y] = 'Y';
  246. io.KeyMap[ImGuiKey_Z] = 'Z';
  247. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  248. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  249. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  250. // Create the vertex buffer
  251. if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  252. {
  253. IM_ASSERT(0);
  254. return;
  255. }
  256. // Load font texture
  257. const void* png_data;
  258. unsigned int png_size;
  259. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  260. if (D3DXCreateTextureFromFileInMemory(g_pd3dDevice, png_data, png_size, &g_pTexture) < 0)
  261. {
  262. IM_ASSERT(0);
  263. return;
  264. }
  265. }
  266. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
  267. {
  268. // Register the window class
  269. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, L"ImGui Example", NULL };
  270. RegisterClassEx(&wc);
  271. // Create the application's window
  272. hWnd = CreateWindow(L"ImGui Example", L"ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  273. INT64 ticks_per_second, time;
  274. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  275. return 1;
  276. if (!QueryPerformanceCounter((LARGE_INTEGER *)&time))
  277. return 1;
  278. // Initialize Direct3D
  279. if (InitD3D(hWnd) >= 0)
  280. {
  281. // Show the window
  282. ShowWindow(hWnd, SW_SHOWDEFAULT);
  283. UpdateWindow(hWnd);
  284. InitImGui();
  285. // Enter the message loop
  286. MSG msg;
  287. ZeroMemory(&msg, sizeof(msg));
  288. while (msg.message != WM_QUIT)
  289. {
  290. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  291. {
  292. TranslateMessage(&msg);
  293. DispatchMessage(&msg);
  294. continue;
  295. }
  296. // 1) ImGui start frame, setup time delta & inputs
  297. ImGuiIO& io = ImGui::GetIO();
  298. INT64 current_time;
  299. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  300. io.DeltaTime = (float)(current_time - time) / ticks_per_second;
  301. time = current_time;
  302. BYTE keystate[256];
  303. GetKeyboardState(keystate);
  304. for (int i = 0; i < 256; i++)
  305. io.KeysDown[i] = (keystate[i] & 0x80) != 0;
  306. io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
  307. io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
  308. // io.MousePos : filled by WM_MOUSEMOVE event
  309. // io.MouseDown : filled by WM_*BUTTON* events
  310. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  311. ImGui::NewFrame();
  312. // 2) ImGui usage
  313. static bool show_test_window = true;
  314. static bool show_another_window = false;
  315. static float f;
  316. ImGui::Text("Hello, world!");
  317. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  318. show_test_window ^= ImGui::Button("Test Window");
  319. show_another_window ^= ImGui::Button("Another Window");
  320. // Calculate and show framerate
  321. static float ms_per_frame[120] = { 0 };
  322. static int ms_per_frame_idx = 0;
  323. static float ms_per_frame_accum = 0.0f;
  324. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  325. ms_per_frame[ms_per_frame_idx] = io.DeltaTime * 1000.0f;
  326. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  327. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  328. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  329. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  330. if (show_test_window)
  331. {
  332. // More example code in ShowTestWindow()
  333. 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!
  334. ImGui::ShowTestWindow(&show_test_window);
  335. }
  336. if (show_another_window)
  337. {
  338. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  339. ImGui::Text("Hello");
  340. ImGui::End();
  341. }
  342. // 3) Rendering
  343. // Clear frame buffer
  344. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
  345. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
  346. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
  347. g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0);
  348. if (g_pd3dDevice->BeginScene() >= 0)
  349. {
  350. // Render ImGui
  351. ImGui::Render();
  352. g_pd3dDevice->EndScene();
  353. }
  354. g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
  355. }
  356. ImGui::Shutdown();
  357. }
  358. if (g_pVB)
  359. g_pVB->Release();
  360. UnregisterClass(L"ImGui Example", wc.hInstance);
  361. return 0;
  362. }