main.cpp 13 KB

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