main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 vbo;
  12. static GLuint vao;
  13. static GLuint vertexShader;
  14. static GLuint fragmentShader;
  15. static GLuint shaderProgram;
  16. static GLuint fontTex;
  17. static GLint uniMVP;
  18. static GLint uniClipRect;
  19. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structuer)
  20. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  21. {
  22. size_t total_vtx_count = 0;
  23. for (int n = 0; n < cmd_lists_count; n++)
  24. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  25. if (total_vtx_count == 0)
  26. return;
  27. // Copy all vertices into a single contiguous GL buffer
  28. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  29. glBindVertexArray(vao);
  30. glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW);
  31. unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  32. if (!buffer_data)
  33. return;
  34. int vtx_consumed = 0;
  35. for (int n = 0; n < cmd_lists_count; n++)
  36. {
  37. const ImDrawList* cmd_list = cmd_lists[n];
  38. memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  39. buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  40. vtx_consumed += cmd_list->vtx_buffer.size();
  41. }
  42. glUnmapBuffer(GL_ARRAY_BUFFER);
  43. // Setup render state: alpha-blending enabled, no face culling, no depth testing
  44. glEnable(GL_BLEND);
  45. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  46. glDisable(GL_CULL_FACE);
  47. glDisable(GL_DEPTH_TEST);
  48. // Bind texture and enable our shader
  49. glBindTexture(GL_TEXTURE_2D, fontTex);
  50. glUseProgram(shaderProgram);
  51. // Setup orthographic projection matrix
  52. const float L = 0.0f;
  53. const float R = ImGui::GetIO().DisplaySize.x;
  54. const float B = ImGui::GetIO().DisplaySize.y;
  55. const float T = 0.0f;
  56. const float mvp[4][4] =
  57. {
  58. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  59. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  60. { 0.0f, 0.0f, -1.0f, 0.0f },
  61. { -(R+L)/(R-L), -(T+B)/(T-B), 0.0f, 1.0f },
  62. };
  63. glUniformMatrix4fv(uniMVP, 1, GL_FALSE, &mvp[0][0]);
  64. // Render command lists
  65. vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those
  66. for (int n = 0; n < cmd_lists_count; n++)
  67. {
  68. const ImDrawList* cmd_list = cmd_lists[n];
  69. // Setup stack of clipping rectangles
  70. bool clip_rect_dirty = true;
  71. int clip_rect_buf_consumed = 0;
  72. ImVector<ImVec4> clip_rect_stack;
  73. clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999));
  74. // Render command list
  75. const ImDrawCmd* pcmd = &cmd_list->commands.front();
  76. const ImDrawCmd* pcmd_end = &cmd_list->commands.back();
  77. while (pcmd <= pcmd_end)
  78. {
  79. const ImDrawCmd& cmd = *pcmd++;
  80. switch (cmd.cmd_type)
  81. {
  82. case ImDrawCmdType_DrawTriangleList:
  83. if (clip_rect_dirty)
  84. {
  85. glUniform4fv(uniClipRect, 1, (float*)&clip_rect_stack.back());
  86. clip_rect_dirty = false;
  87. }
  88. glDrawArrays(GL_TRIANGLES, vtx_consumed, cmd.vtx_count);
  89. vtx_consumed += cmd.vtx_count;
  90. break;
  91. case ImDrawCmdType_PushClipRect:
  92. clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_consumed++]);
  93. clip_rect_dirty = true;
  94. break;
  95. case ImDrawCmdType_PopClipRect:
  96. clip_rect_stack.pop_back();
  97. clip_rect_dirty = true;
  98. break;
  99. }
  100. }
  101. }
  102. }
  103. static const char* ImImpl_GetClipboardTextFn()
  104. {
  105. return glfwGetClipboardString(window);
  106. }
  107. static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
  108. {
  109. if (!text_end)
  110. text_end = text + strlen(text);
  111. char* buf = (char*)malloc(text_end - text + 1);
  112. memcpy(buf, text, text_end-text);
  113. buf[text_end-text] = '\0';
  114. glfwSetClipboardString(window, buf);
  115. free(buf);
  116. }
  117. // Shader sources
  118. const GLchar* vertexSource =
  119. "#version 150 core\n"
  120. "uniform mat4 MVP;"
  121. "in vec2 i_pos;"
  122. "in vec2 i_uv;"
  123. "in vec4 i_col;"
  124. "out vec4 col;"
  125. "out vec2 pixel_pos;"
  126. "out vec2 uv;"
  127. "void main() {"
  128. " col = i_col;"
  129. " pixel_pos = i_pos;"
  130. " uv = i_uv;"
  131. " gl_Position = MVP * vec4(i_pos.x, i_pos.y, 0.0f, 1.0f);"
  132. "}";
  133. const GLchar* fragmentSource =
  134. "#version 150 core\n"
  135. "uniform sampler2D Tex;"
  136. "uniform vec4 ClipRect;"
  137. "in vec4 col;"
  138. "in vec2 pixel_pos;"
  139. "in vec2 uv;"
  140. "out vec4 o_col;"
  141. "void main() {"
  142. " o_col = texture(Tex, uv) * col;"
  143. //" if (pixel_pos.x < ClipRect.x || pixel_pos.y < ClipRect.y || pixel_pos.x > ClipRect.z || pixel_pos.y > ClipRect.w) discard;" // Clipping: using discard
  144. //" if (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w) < 1.0f) discard;" // Clipping: using discard and step
  145. " o_col.w *= (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w));" // Clipping: branch-less, set alpha 0.0f
  146. "}";
  147. // GLFW callbacks to get events
  148. static void glfw_error_callback(int error, const char* description)
  149. {
  150. fputs(description, stderr);
  151. }
  152. static float mouse_wheel = 0.0f;
  153. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  154. {
  155. mouse_wheel = (float)yoffset;
  156. }
  157. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  158. {
  159. ImGuiIO& io = ImGui::GetIO();
  160. if (action == GLFW_PRESS)
  161. io.KeysDown[key] = true;
  162. if (action == GLFW_RELEASE)
  163. io.KeysDown[key] = false;
  164. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  165. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  166. }
  167. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  168. {
  169. if (c > 0 && c <= 255)
  170. ImGui::GetIO().AddInputCharacter((char)c);
  171. }
  172. // OpenGL code based on http://open.gl tutorials
  173. void InitGL()
  174. {
  175. glfwSetErrorCallback(glfw_error_callback);
  176. if (!glfwInit())
  177. exit(1);
  178. //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  179. //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
  180. //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  181. //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  182. glfwWindowHint(GLFW_REFRESH_RATE, 60);
  183. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  184. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", nullptr, nullptr);
  185. glfwMakeContextCurrent(window);
  186. glfwSetKeyCallback(window, glfw_key_callback);
  187. glfwSetScrollCallback(window, glfw_scroll_callback);
  188. glfwSetCharCallback(window, glfw_char_callback);
  189. glewExperimental = GL_TRUE;
  190. glewInit();
  191. GLenum err = GL_NO_ERROR;
  192. err = glGetError(); IM_ASSERT(err == GL_NO_ERROR);
  193. }
  194. void InitImGui()
  195. {
  196. int w, h;
  197. glfwGetWindowSize(window, &w, &h);
  198. ImGuiIO& io = ImGui::GetIO();
  199. io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions.
  200. 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)
  201. io.PixelCenterOffset = 0.5f; // Align OpenGL texels
  202. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  203. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  204. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  205. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  206. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  207. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  208. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  209. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  210. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  211. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  212. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  213. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  214. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  215. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  216. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  217. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  218. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  219. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  220. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  221. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  222. // Setup graphics backend
  223. GLint status = GL_TRUE;
  224. GLenum err = GL_NO_ERROR;
  225. err = glGetError(); IM_ASSERT(err == GL_NO_ERROR);
  226. // Create and compile the vertex shader
  227. vertexShader = glCreateShader(GL_VERTEX_SHADER);
  228. glShaderSource(vertexShader, 1, &vertexSource, NULL);
  229. glCompileShader(vertexShader);
  230. glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
  231. if (status != GL_TRUE)
  232. {
  233. char buffer[512];
  234. glGetShaderInfoLog(vertexShader, 1024, NULL, buffer);
  235. printf("%s", buffer);
  236. IM_ASSERT(status == GL_TRUE);
  237. }
  238. // Create and compile the fragment shader
  239. fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
  240. glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
  241. glCompileShader(fragmentShader);
  242. glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
  243. IM_ASSERT(status == GL_TRUE);
  244. // Link the vertex and fragment shader into a shader program
  245. shaderProgram = glCreateProgram();
  246. glAttachShader(shaderProgram, vertexShader);
  247. glAttachShader(shaderProgram, fragmentShader);
  248. glBindFragDataLocation(shaderProgram, 0, "o_col");
  249. glLinkProgram(shaderProgram);
  250. glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status);
  251. IM_ASSERT(status == GL_TRUE);
  252. uniMVP = glGetUniformLocation(shaderProgram, "MVP");
  253. uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect");
  254. // Create Vertex Buffer Objects & Vertex Array Objects
  255. glGenBuffers(1, &vbo);
  256. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  257. glGenVertexArrays(1, &vao);
  258. glBindVertexArray(vao);
  259. GLint posAttrib = glGetAttribLocation(shaderProgram, "i_pos");
  260. glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), 0);
  261. glEnableVertexAttribArray(posAttrib);
  262. GLint uvAttrib = glGetAttribLocation(shaderProgram, "i_uv");
  263. glEnableVertexAttribArray(uvAttrib);
  264. glVertexAttribPointer(uvAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (void*)(2*sizeof(float)));
  265. GLint colAttrib = glGetAttribLocation(shaderProgram, "i_col");
  266. glVertexAttribPointer(colAttrib, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (void*)(4*sizeof(float)));
  267. glEnableVertexAttribArray(colAttrib);
  268. err = glGetError(); IM_ASSERT(err == GL_NO_ERROR);
  269. // Load font texture
  270. glGenTextures(1, &fontTex);
  271. glBindTexture(GL_TEXTURE_2D, fontTex);
  272. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  273. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  274. const void* png_data;
  275. unsigned int png_size;
  276. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  277. int tex_x, tex_y, tex_comp;
  278. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  279. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  280. stbi_image_free(tex_data);
  281. }
  282. void Shutdown()
  283. {
  284. ImGui::Shutdown();
  285. glDeleteProgram(shaderProgram);
  286. glDeleteShader(fragmentShader);
  287. glDeleteShader(vertexShader);
  288. glDeleteBuffers(1, &vbo);
  289. glDeleteVertexArrays(1, &vao);
  290. glfwTerminate();
  291. }
  292. int main(int argc, char** argv)
  293. {
  294. InitGL();
  295. InitImGui();
  296. double time = glfwGetTime();
  297. while (!glfwWindowShouldClose(window))
  298. {
  299. ImGuiIO& io = ImGui::GetIO();
  300. glfwPollEvents();
  301. // 1) ImGui start frame, setup time delta & inputs
  302. const double current_time = glfwGetTime();
  303. io.DeltaTime = (float)(current_time - time);
  304. time = current_time;
  305. double mouse_x, mouse_y;
  306. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  307. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  308. io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
  309. io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  310. io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
  311. mouse_wheel = 0.0f;
  312. ImGui::NewFrame();
  313. // 2) ImGui usage
  314. static bool show_test_window = true;
  315. static bool show_another_window = false;
  316. static float f;
  317. ImGui::Text("Hello, world!");
  318. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  319. show_test_window ^= ImGui::Button("Test Window");
  320. show_another_window ^= ImGui::Button("Another Window");
  321. // Calculate and show framerate
  322. static float ms_per_frame[120] = { 0 };
  323. static int ms_per_frame_idx = 0;
  324. static float ms_per_frame_accum = 0.0f;
  325. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  326. ms_per_frame[ms_per_frame_idx] = io.DeltaTime * 1000.0f;
  327. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  328. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  329. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  330. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  331. if (show_test_window)
  332. {
  333. // More example code in ShowTestWindow()
  334. 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!
  335. ImGui::ShowTestWindow(&show_test_window);
  336. }
  337. if (show_another_window)
  338. {
  339. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  340. ImGui::Text("Hello");
  341. ImGui::End();
  342. }
  343. // 3) Rendering
  344. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  345. glClear(GL_COLOR_BUFFER_BIT);
  346. ImGui::Render();
  347. glfwSwapBuffers(window);
  348. }
  349. Shutdown();
  350. return 0;
  351. }