main.cpp 12 KB

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