main.cpp 12 KB

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