main.cpp 15 KB

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