main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #define GLEW_STATIC
  2. #include <GL/glew.h>
  3. #include <GLFW/glfw3.h>
  4. #define STB_IMAGE_IMPLEMENTATION
  5. #include "stb_image.h" // for .png loading
  6. #include "../../imgui.h"
  7. #ifdef _MSC_VER
  8. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  9. #endif
  10. static GLFWwindow* window;
  11. static GLuint fontTex;
  12. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  13. // If text or lines are blurry when integrating ImGui in your engine:
  14. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f
  15. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  16. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  17. {
  18. if (cmd_lists_count == 0)
  19. return;
  20. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  21. // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
  22. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  23. glEnable(GL_BLEND);
  24. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  25. glDisable(GL_CULL_FACE);
  26. glDisable(GL_DEPTH_TEST);
  27. glEnable(GL_SCISSOR_TEST);
  28. glEnableClientState(GL_VERTEX_ARRAY);
  29. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  30. glEnableClientState(GL_COLOR_ARRAY);
  31. // Setup texture
  32. glBindTexture(GL_TEXTURE_2D, fontTex);
  33. glEnable(GL_TEXTURE_2D);
  34. // Setup orthographic projection matrix
  35. const float width = ImGui::GetIO().DisplaySize.x;
  36. const float height = ImGui::GetIO().DisplaySize.y;
  37. glMatrixMode(GL_PROJECTION);
  38. glLoadIdentity();
  39. glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
  40. glMatrixMode(GL_MODELVIEW);
  41. glLoadIdentity();
  42. // Render command lists
  43. for (int n = 0; n < cmd_lists_count; n++)
  44. {
  45. const ImDrawList* cmd_list = cmd_lists[n];
  46. const unsigned char* vtx_buffer = (const unsigned char*)cmd_list->vtx_buffer.begin();
  47. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer));
  48. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer+8));
  49. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer+16));
  50. int vtx_offset = 0;
  51. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  52. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  53. {
  54. 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));
  55. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  56. vtx_offset += pcmd->vtx_count;
  57. }
  58. }
  59. glDisable(GL_SCISSOR_TEST);
  60. glDisableClientState(GL_COLOR_ARRAY);
  61. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  62. glDisableClientState(GL_VERTEX_ARRAY);
  63. }
  64. static const char* ImImpl_GetClipboardTextFn()
  65. {
  66. return glfwGetClipboardString(window);
  67. }
  68. static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
  69. {
  70. if (!text_end)
  71. text_end = text + strlen(text);
  72. if (*text_end == 0)
  73. {
  74. // Already got a zero-terminator at 'text_end', we don't need to add one
  75. glfwSetClipboardString(window, text);
  76. }
  77. else
  78. {
  79. // Add a zero-terminator because glfw function doesn't take a size
  80. char* buf = (char*)malloc(text_end - text + 1);
  81. memcpy(buf, text, text_end-text);
  82. buf[text_end-text] = '\0';
  83. glfwSetClipboardString(window, buf);
  84. free(buf);
  85. }
  86. }
  87. // GLFW callbacks to get events
  88. static void glfw_error_callback(int error, const char* description)
  89. {
  90. fputs(description, stderr);
  91. }
  92. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  93. {
  94. ImGuiIO& io = ImGui::GetIO();
  95. io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
  96. }
  97. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  98. {
  99. ImGuiIO& io = ImGui::GetIO();
  100. if (action == GLFW_PRESS)
  101. io.KeysDown[key] = true;
  102. if (action == GLFW_RELEASE)
  103. io.KeysDown[key] = false;
  104. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  105. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  106. }
  107. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  108. {
  109. if (c > 0 && c <= 255)
  110. ImGui::GetIO().AddInputCharacter((char)c);
  111. }
  112. // OpenGL code based on http://open.gl tutorials
  113. void InitGL()
  114. {
  115. glfwSetErrorCallback(glfw_error_callback);
  116. if (!glfwInit())
  117. exit(1);
  118. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  119. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
  120. glfwMakeContextCurrent(window);
  121. glfwSetKeyCallback(window, glfw_key_callback);
  122. glfwSetScrollCallback(window, glfw_scroll_callback);
  123. glfwSetCharCallback(window, glfw_char_callback);
  124. glewInit();
  125. }
  126. void InitImGui()
  127. {
  128. int w, h;
  129. glfwGetWindowSize(window, &w, &h);
  130. ImGuiIO& io = ImGui::GetIO();
  131. io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions.
  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 timestep is variable)
  133. io.PixelCenterOffset = 0.5f; // 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. const void* png_data;
  160. unsigned int png_size;
  161. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  162. int tex_x, tex_y, tex_comp;
  163. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  164. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  165. stbi_image_free(tex_data);
  166. }
  167. void UpdateImGui()
  168. {
  169. ImGuiIO& io = ImGui::GetIO();
  170. // Setup timestep
  171. static double time = 0.0f;
  172. const double current_time = glfwGetTime();
  173. io.DeltaTime = (float)(current_time - time);
  174. time = current_time;
  175. // Setup inputs
  176. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  177. double mouse_x, mouse_y;
  178. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  179. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  180. io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
  181. io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  182. // Start the frame
  183. ImGui::NewFrame();
  184. }
  185. // Application code
  186. int main(int argc, char** argv)
  187. {
  188. InitGL();
  189. InitImGui();
  190. while (!glfwWindowShouldClose(window))
  191. {
  192. ImGuiIO& io = ImGui::GetIO();
  193. io.MouseWheel = 0;
  194. glfwPollEvents();
  195. UpdateImGui();
  196. // Create a simple window
  197. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  198. static bool show_test_window = true;
  199. static bool show_another_window = false;
  200. static float f;
  201. ImGui::Text("Hello, world!");
  202. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  203. show_test_window ^= ImGui::Button("Test Window");
  204. show_another_window ^= ImGui::Button("Another Window");
  205. // Calculate and show framerate
  206. static float ms_per_frame[120] = { 0 };
  207. static int ms_per_frame_idx = 0;
  208. static float ms_per_frame_accum = 0.0f;
  209. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  210. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  211. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  212. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  213. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  214. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  215. // Show the ImGui test window
  216. // Most of user example code is in ImGui::ShowTestWindow()
  217. if (show_test_window)
  218. {
  219. 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!
  220. ImGui::ShowTestWindow(&show_test_window);
  221. }
  222. // Show another simple window
  223. if (show_another_window)
  224. {
  225. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  226. ImGui::Text("Hello");
  227. ImGui::End();
  228. }
  229. // Rendering
  230. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  231. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  232. glClear(GL_COLOR_BUFFER_BIT);
  233. ImGui::Render();
  234. glfwSwapBuffers(window);
  235. }
  236. ImGui::Shutdown();
  237. glfwTerminate();
  238. return 0;
  239. }