main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #ifdef _MSC_VER
  2. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  3. #include <Windows.h>
  4. #include <Imm.h>
  5. #endif
  6. #define STB_IMAGE_IMPLEMENTATION
  7. #include "stb_image.h" // for .png loading
  8. #include "../../imgui.h"
  9. // glew & glfw
  10. #define GLEW_STATIC
  11. #include <GL/glew.h>
  12. #include <GLFW/glfw3.h>
  13. #ifdef _MSC_VER
  14. #define GLFW_EXPOSE_NATIVE_WIN32
  15. #define GLFW_EXPOSE_NATIVE_WGL
  16. #include <GLFW/glfw3native.h>
  17. #endif
  18. static GLFWwindow* window;
  19. static GLuint fontTex;
  20. static bool mousePressed[2] = { false, false };
  21. static ImVec2 mousePosScale(1.0f, 1.0f);
  22. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  23. // If text or lines are blurry when integrating ImGui in your engine:
  24. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  25. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
  26. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  27. {
  28. if (cmd_lists_count == 0)
  29. return;
  30. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  31. // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
  32. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  33. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  34. glEnable(GL_BLEND);
  35. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  36. glDisable(GL_CULL_FACE);
  37. glDisable(GL_DEPTH_TEST);
  38. glEnable(GL_SCISSOR_TEST);
  39. glEnableClientState(GL_VERTEX_ARRAY);
  40. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  41. glEnableClientState(GL_COLOR_ARRAY);
  42. // Setup texture
  43. glBindTexture(GL_TEXTURE_2D, fontTex);
  44. glEnable(GL_TEXTURE_2D);
  45. // Setup orthographic projection matrix
  46. const float width = ImGui::GetIO().DisplaySize.x;
  47. const float height = ImGui::GetIO().DisplaySize.y;
  48. glMatrixMode(GL_PROJECTION);
  49. glPushMatrix();
  50. glLoadIdentity();
  51. glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
  52. glMatrixMode(GL_MODELVIEW);
  53. glPushMatrix();
  54. glLoadIdentity();
  55. // Render command lists
  56. for (int n = 0; n < cmd_lists_count; n++)
  57. {
  58. const ImDrawList* cmd_list = cmd_lists[n];
  59. const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->vtx_buffer.front();
  60. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, pos)));
  61. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, uv)));
  62. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, col)));
  63. int vtx_offset = 0;
  64. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  65. {
  66. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  67. glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
  68. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  69. vtx_offset += pcmd->vtx_count;
  70. }
  71. }
  72. glDisableClientState(GL_COLOR_ARRAY);
  73. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  74. glDisableClientState(GL_VERTEX_ARRAY);
  75. // Restore modified state
  76. glMatrixMode(GL_MODELVIEW);
  77. glPopMatrix();
  78. glMatrixMode(GL_PROJECTION);
  79. glPopMatrix();
  80. glPopAttrib();
  81. }
  82. // NB: ImGui already provide OS clipboard support for Windows so this isn't needed if you are using Windows only.
  83. static const char* ImImpl_GetClipboardTextFn()
  84. {
  85. return glfwGetClipboardString(window);
  86. }
  87. static void ImImpl_SetClipboardTextFn(const char* text)
  88. {
  89. glfwSetClipboardString(window, text);
  90. }
  91. #ifdef _MSC_VER
  92. // Notify OS Input Method Editor of text input position (e.g. when using Japanese/Chinese inputs, otherwise this isn't needed)
  93. static void ImImpl_ImeSetInputScreenPosFn(int x, int y)
  94. {
  95. HWND hwnd = glfwGetWin32Window(window);
  96. if (HIMC himc = ImmGetContext(hwnd))
  97. {
  98. COMPOSITIONFORM cf;
  99. cf.ptCurrentPos.x = x;
  100. cf.ptCurrentPos.y = y;
  101. cf.dwStyle = CFS_FORCE_POSITION;
  102. ImmSetCompositionWindow(himc, &cf);
  103. }
  104. }
  105. #endif
  106. // GLFW callbacks to get events
  107. static void glfw_error_callback(int error, const char* description)
  108. {
  109. fputs(description, stderr);
  110. }
  111. static void glfw_mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
  112. {
  113. if (action == GLFW_PRESS && button >= 0 && button < 2)
  114. mousePressed[button] = true;
  115. }
  116. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  117. {
  118. ImGuiIO& io = ImGui::GetIO();
  119. io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
  120. }
  121. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  122. {
  123. ImGuiIO& io = ImGui::GetIO();
  124. if (action == GLFW_PRESS)
  125. io.KeysDown[key] = true;
  126. if (action == GLFW_RELEASE)
  127. io.KeysDown[key] = false;
  128. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  129. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  130. }
  131. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  132. {
  133. if (c > 0 && c < 0x10000)
  134. ImGui::GetIO().AddInputCharacter((unsigned short)c);
  135. }
  136. // OpenGL code based on http://open.gl tutorials
  137. void InitGL()
  138. {
  139. glfwSetErrorCallback(glfw_error_callback);
  140. if (!glfwInit())
  141. exit(1);
  142. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  143. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
  144. glfwMakeContextCurrent(window);
  145. glfwSetKeyCallback(window, glfw_key_callback);
  146. glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
  147. glfwSetScrollCallback(window, glfw_scroll_callback);
  148. glfwSetCharCallback(window, glfw_char_callback);
  149. glewInit();
  150. }
  151. void InitImGui()
  152. {
  153. int w, h;
  154. int fb_w, fb_h;
  155. glfwGetWindowSize(window, &w, &h);
  156. glfwGetFramebufferSize(window, &fb_w, &fb_h);
  157. mousePosScale.x = (float)fb_w / w; // Some screens e.g. Retina display have framebuffer size != from window size, and mouse inputs are given in window/screen coordinates.
  158. mousePosScale.y = (float)fb_h / h;
  159. ImGuiIO& io = ImGui::GetIO();
  160. io.DisplaySize = ImVec2((float)fb_w, (float)fb_h); // Display size, in pixels. For clamping windows positions.
  161. 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)
  162. io.PixelCenterOffset = 0.0f; // Align OpenGL texels
  163. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  164. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  165. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  166. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  167. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  168. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  169. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  170. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  171. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  172. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  173. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  174. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  175. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  176. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  177. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  178. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  179. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  180. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  181. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  182. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  183. #ifdef _MSC_VER
  184. io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn;
  185. #endif
  186. // Load font texture
  187. glGenTextures(1, &fontTex);
  188. glBindTexture(GL_TEXTURE_2D, fontTex);
  189. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  190. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  191. #if 1
  192. // Default font (embedded in code)
  193. const void* png_data;
  194. unsigned int png_size;
  195. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  196. int tex_x, tex_y, tex_comp;
  197. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  198. IM_ASSERT(tex_data != NULL);
  199. #else
  200. // Custom font from filesystem
  201. io.Font = new ImBitmapFont();
  202. io.Font->LoadFromFile("../../extra_fonts/mplus-2m-medium_18.fnt");
  203. IM_ASSERT(io.Font->IsLoaded());
  204. int tex_x, tex_y, tex_comp;
  205. void* tex_data = stbi_load("../../extra_fonts/mplus-2m-medium_18.png", &tex_x, &tex_y, &tex_comp, 0);
  206. IM_ASSERT(tex_data != NULL);
  207. // Automatically find white pixel from the texture we just loaded
  208. // (io.FontTexUvForWhite needs to contains UV coordinates pointing to a white pixel in order to render solid objects)
  209. for (int tex_data_off = 0; tex_data_off < tex_x*tex_y; tex_data_off++)
  210. if (((unsigned int*)tex_data)[tex_data_off] == 0xffffffff)
  211. {
  212. io.FontTexUvForWhite = ImVec2((float)(tex_data_off % tex_x)/(tex_x), (float)(tex_data_off / tex_x)/(tex_y));
  213. break;
  214. }
  215. #endif
  216. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  217. stbi_image_free(tex_data);
  218. }
  219. void UpdateImGui()
  220. {
  221. ImGuiIO& io = ImGui::GetIO();
  222. // Setup timestep
  223. static double time = 0.0f;
  224. const double current_time = glfwGetTime();
  225. io.DeltaTime = (float)(current_time - time);
  226. time = current_time;
  227. // Setup inputs
  228. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  229. double mouse_x, mouse_y;
  230. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  231. io.MousePos = ImVec2((float)mouse_x * mousePosScale.x, (float)mouse_y * mousePosScale.y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  232. io.MouseDown[0] = mousePressed[0] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
  233. io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  234. // Start the frame
  235. ImGui::NewFrame();
  236. }
  237. // Application code
  238. int main(int argc, char** argv)
  239. {
  240. InitGL();
  241. InitImGui();
  242. while (!glfwWindowShouldClose(window))
  243. {
  244. ImGuiIO& io = ImGui::GetIO();
  245. mousePressed[0] = mousePressed[1] = false;
  246. io.MouseWheel = 0;
  247. glfwPollEvents();
  248. UpdateImGui();
  249. static bool show_test_window = true;
  250. static bool show_another_window = false;
  251. // 1. Show a simple window
  252. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  253. {
  254. static float f;
  255. ImGui::Text("Hello, world!");
  256. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  257. show_test_window ^= ImGui::Button("Test Window");
  258. show_another_window ^= ImGui::Button("Another Window");
  259. // Calculate and show framerate
  260. static float ms_per_frame[120] = { 0 };
  261. static int ms_per_frame_idx = 0;
  262. static float ms_per_frame_accum = 0.0f;
  263. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  264. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  265. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  266. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  267. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  268. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  269. }
  270. // 2. Show another simple window, this time using an explicit Begin/End pair
  271. if (show_another_window)
  272. {
  273. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  274. ImGui::Text("Hello");
  275. ImGui::End();
  276. }
  277. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  278. if (show_test_window)
  279. {
  280. ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call this, because positions are saved in .ini file. Here we just want to make the demo initial state a bit more friendly!
  281. ImGui::ShowTestWindow(&show_test_window);
  282. }
  283. // Rendering
  284. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  285. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  286. glClear(GL_COLOR_BUFFER_BIT);
  287. ImGui::Render();
  288. glfwSwapBuffers(window);
  289. }
  290. ImGui::Shutdown();
  291. glfwTerminate();
  292. return 0;
  293. }