main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // ImGui - standalone example application for OpenGL 3, using programmable 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. #ifdef __clang__
  6. #pragma clang diagnostic ignored "-Wunused-function" // warning: unused function
  7. #endif
  8. #include "../../imgui.h"
  9. #include <stdio.h>
  10. // Glfw/Glew
  11. #define GLEW_STATIC
  12. #include <GL/glew.h>
  13. #include <GLFW/glfw3.h>
  14. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  15. static GLFWwindow* window;
  16. static bool mousePressed[2] = { false, false };
  17. // Shader variables
  18. static int shader_handle, vert_handle, frag_handle;
  19. static int texture_location, proj_mtx_location;
  20. static int position_location, uv_location, colour_location;
  21. static size_t vbo_max_size = 20000;
  22. static unsigned int vbo_handle, vao_handle;
  23. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  24. // If text or lines are blurry when integrating ImGui in your engine:
  25. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,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. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  31. glEnable(GL_BLEND);
  32. glBlendEquation(GL_FUNC_ADD);
  33. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  34. glDisable(GL_CULL_FACE);
  35. glDisable(GL_DEPTH_TEST);
  36. glEnable(GL_SCISSOR_TEST);
  37. glActiveTexture(GL_TEXTURE0);
  38. // Setup orthographic projection matrix
  39. const float width = ImGui::GetIO().DisplaySize.x;
  40. const float height = ImGui::GetIO().DisplaySize.y;
  41. const float ortho_projection[4][4] =
  42. {
  43. { 2.0f/width, 0.0f, 0.0f, 0.0f },
  44. { 0.0f, 2.0f/-height, 0.0f, 0.0f },
  45. { 0.0f, 0.0f, -1.0f, 0.0f },
  46. { -1.0f, 1.0f, 0.0f, 1.0f },
  47. };
  48. glUseProgram(shader_handle);
  49. glUniform1i(texture_location, 0);
  50. glUniformMatrix4fv(proj_mtx_location, 1, GL_FALSE, &ortho_projection[0][0]);
  51. // Grow our buffer according to what we need
  52. size_t total_vtx_count = 0;
  53. for (int n = 0; n < cmd_lists_count; n++)
  54. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  55. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  56. size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert);
  57. if (neededBufferSize > vbo_max_size)
  58. {
  59. vbo_max_size = neededBufferSize + 5000; // Grow buffer
  60. glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_STREAM_DRAW);
  61. }
  62. // Copy and convert all vertices into a single contiguous buffer
  63. unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  64. if (!buffer_data)
  65. return;
  66. for (int n = 0; n < cmd_lists_count; n++)
  67. {
  68. const ImDrawList* cmd_list = cmd_lists[n];
  69. memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  70. buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  71. }
  72. glUnmapBuffer(GL_ARRAY_BUFFER);
  73. glBindBuffer(GL_ARRAY_BUFFER, 0);
  74. glBindVertexArray(vao_handle);
  75. int cmd_offset = 0;
  76. for (int n = 0; n < cmd_lists_count; n++)
  77. {
  78. const ImDrawList* cmd_list = cmd_lists[n];
  79. int vtx_offset = cmd_offset;
  80. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  81. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  82. {
  83. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
  84. 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));
  85. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  86. vtx_offset += pcmd->vtx_count;
  87. }
  88. cmd_offset = vtx_offset;
  89. }
  90. // Restore modified state
  91. glBindVertexArray(0);
  92. glUseProgram(0);
  93. glDisable(GL_SCISSOR_TEST);
  94. glBindTexture(GL_TEXTURE_2D, 0);
  95. }
  96. static const char* ImImpl_GetClipboardTextFn()
  97. {
  98. return glfwGetClipboardString(window);
  99. }
  100. static void ImImpl_SetClipboardTextFn(const char* text)
  101. {
  102. glfwSetClipboardString(window, text);
  103. }
  104. // GLFW callbacks to get events
  105. static void glfw_error_callback(int error, const char* description)
  106. {
  107. fputs(description, stderr);
  108. }
  109. static void glfw_mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
  110. {
  111. if (action == GLFW_PRESS && button >= 0 && button < 2)
  112. mousePressed[button] = true;
  113. }
  114. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  115. {
  116. ImGuiIO& io = ImGui::GetIO();
  117. io.MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  118. }
  119. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  120. {
  121. ImGuiIO& io = ImGui::GetIO();
  122. if (action == GLFW_PRESS)
  123. io.KeysDown[key] = true;
  124. if (action == GLFW_RELEASE)
  125. io.KeysDown[key] = false;
  126. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  127. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  128. }
  129. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  130. {
  131. if (c > 0 && c < 0x10000)
  132. ImGui::GetIO().AddInputCharacter((unsigned short)c);
  133. }
  134. void InitGL()
  135. {
  136. glfwSetErrorCallback(glfw_error_callback);
  137. if (!glfwInit())
  138. exit(1);
  139. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  140. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  141. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  142. window = glfwCreateWindow(1280, 720, "ImGui OpenGL3 example", NULL, NULL);
  143. glfwMakeContextCurrent(window);
  144. glfwSetKeyCallback(window, glfw_key_callback);
  145. glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
  146. glfwSetScrollCallback(window, glfw_scroll_callback);
  147. glfwSetCharCallback(window, glfw_char_callback);
  148. glewExperimental = GL_TRUE;
  149. GLenum err = glewInit();
  150. if (GLEW_OK != err)
  151. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  152. const GLchar *vertex_shader =
  153. "#version 330\n"
  154. "uniform mat4 ProjMtx;\n"
  155. "in vec2 Position;\n"
  156. "in vec2 UV;\n"
  157. "in vec4 Color;\n"
  158. "out vec2 Frag_UV;\n"
  159. "out vec4 Frag_Color;\n"
  160. "void main()\n"
  161. "{\n"
  162. " Frag_UV = UV;\n"
  163. " Frag_Color = Color;\n"
  164. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  165. "}\n";
  166. const GLchar* fragment_shader =
  167. "#version 330\n"
  168. "uniform sampler2D Texture;\n"
  169. "in vec2 Frag_UV;\n"
  170. "in vec4 Frag_Color;\n"
  171. "out vec4 Out_Color;\n"
  172. "void main()\n"
  173. "{\n"
  174. " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
  175. "}\n";
  176. shader_handle = glCreateProgram();
  177. vert_handle = glCreateShader(GL_VERTEX_SHADER);
  178. frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
  179. glShaderSource(vert_handle, 1, &vertex_shader, 0);
  180. glShaderSource(frag_handle, 1, &fragment_shader, 0);
  181. glCompileShader(vert_handle);
  182. glCompileShader(frag_handle);
  183. glAttachShader(shader_handle, vert_handle);
  184. glAttachShader(shader_handle, frag_handle);
  185. glLinkProgram(shader_handle);
  186. texture_location = glGetUniformLocation(shader_handle, "Texture");
  187. proj_mtx_location = glGetUniformLocation(shader_handle, "ProjMtx");
  188. position_location = glGetAttribLocation(shader_handle, "Position");
  189. uv_location = glGetAttribLocation(shader_handle, "UV");
  190. colour_location = glGetAttribLocation(shader_handle, "Color");
  191. glGenBuffers(1, &vbo_handle);
  192. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  193. glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW);
  194. glGenVertexArrays(1, &vao_handle);
  195. glBindVertexArray(vao_handle);
  196. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  197. glEnableVertexAttribArray(position_location);
  198. glEnableVertexAttribArray(uv_location);
  199. glEnableVertexAttribArray(colour_location);
  200. glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  201. glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  202. glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  203. glBindVertexArray(0);
  204. glBindBuffer(GL_ARRAY_BUFFER, 0);
  205. }
  206. void LoadFontsTexture()
  207. {
  208. ImGuiIO& io = ImGui::GetIO();
  209. //ImFont* my_font1 = io.Fonts->AddFontDefault();
  210. //ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("extra_fonts/Karla-Regular.ttf", 15.0f);
  211. //ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
  212. //ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
  213. //ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 20.0f, io.Fonts->GetGlyphRangesJapanese());
  214. unsigned char* pixels;
  215. int width, height;
  216. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
  217. GLuint tex_id;
  218. glGenTextures(1, &tex_id);
  219. glBindTexture(GL_TEXTURE_2D, tex_id);
  220. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  221. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  222. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  223. // Store our identifier
  224. io.Fonts->TexID = (void *)(intptr_t)tex_id;
  225. }
  226. void InitImGui()
  227. {
  228. ImGuiIO& io = ImGui::GetIO();
  229. 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)
  230. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  231. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  232. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  233. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  234. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  235. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  236. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  237. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  238. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  239. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  240. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  241. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  242. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  243. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  244. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  245. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  246. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  247. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  248. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  249. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  250. LoadFontsTexture();
  251. }
  252. void UpdateImGui()
  253. {
  254. ImGuiIO& io = ImGui::GetIO();
  255. // Setup resolution (every frame to accommodate for window resizing)
  256. int w, h;
  257. int display_w, display_h;
  258. glfwGetWindowSize(window, &w, &h);
  259. glfwGetFramebufferSize(window, &display_w, &display_h);
  260. io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
  261. // Setup time step
  262. static double time = 0.0f;
  263. const double current_time = glfwGetTime();
  264. io.DeltaTime = (float)(current_time - time);
  265. time = current_time;
  266. // Setup inputs
  267. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  268. double mouse_x, mouse_y;
  269. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  270. mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
  271. mouse_y *= (float)display_h / h;
  272. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  273. 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.
  274. io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  275. // Start the frame
  276. ImGui::NewFrame();
  277. }
  278. // Application code
  279. int main(int argc, char** argv)
  280. {
  281. InitGL();
  282. InitImGui();
  283. bool show_test_window = true;
  284. bool show_another_window = false;
  285. ImVec4 clear_col = ImColor(114, 144, 154);
  286. while (!glfwWindowShouldClose(window))
  287. {
  288. ImGuiIO& io = ImGui::GetIO();
  289. io.MouseWheel = 0;
  290. mousePressed[0] = mousePressed[1] = false;
  291. glfwPollEvents();
  292. UpdateImGui();
  293. // 1. Show a simple window
  294. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  295. {
  296. static float f;
  297. ImGui::Text("Hello, world!");
  298. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  299. ImGui::ColorEdit3("clear color", (float*)&clear_col);
  300. if (ImGui::Button("Test Window")) show_test_window ^= 1;
  301. if (ImGui::Button("Another Window")) show_another_window ^= 1;
  302. // Calculate and show frame rate
  303. static int ms_per_frame_idx = 0;
  304. static float ms_per_frame[60] = { 0 };
  305. static float ms_per_frame_accum = 0.0f;
  306. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  307. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  308. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  309. ms_per_frame_idx = (ms_per_frame_idx + 1) % 60;
  310. const float ms_per_frame_avg = ms_per_frame_accum / 60;
  311. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  312. }
  313. // 2. Show another simple window, this time using an explicit Begin/End pair
  314. if (show_another_window)
  315. {
  316. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  317. ImGui::Text("Hello");
  318. ImGui::End();
  319. }
  320. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  321. if (show_test_window)
  322. {
  323. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver);
  324. ImGui::ShowTestWindow(&show_test_window);
  325. }
  326. // Rendering
  327. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  328. glClearColor(clear_col.x, clear_col.y, clear_col.z, clear_col.w);
  329. glClear(GL_COLOR_BUFFER_BIT);
  330. ImGui::Render();
  331. glfwSwapBuffers(window);
  332. }
  333. // Cleanup
  334. if (vao_handle) glDeleteVertexArrays(1, &vao_handle);
  335. if (vbo_handle) glDeleteBuffers(1, &vbo_handle);
  336. glDetachShader(shader_handle, vert_handle);
  337. glDetachShader(shader_handle, frag_handle);
  338. glDeleteShader(vert_handle);
  339. glDeleteShader(frag_handle);
  340. glDeleteProgram(shader_handle);
  341. ImGui::Shutdown();
  342. glfwTerminate();
  343. return 0;
  344. }