main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #define GLEW_STATIC
  2. #include <GL/glew.h>
  3. #include <GLFW/glfw3.h>
  4. #define STB_IMAGE_IMPLEMENTATION
  5. #include "../shared/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. //Shader variables
  13. static int shader_handle, vert_handle, frag_handle;
  14. static int texture_location, ortho_location;
  15. static int position_location, uv_location, colour_location;
  16. //streaming vbo
  17. //we are going to use the same vertex buffer for all rendering of imgui
  18. //so we need to use a large enough buffer as default.
  19. //the buffer will be resized if needed in the rendering code, but it is not a "free" operation.
  20. static size_t vbo_max_size = 1000000;
  21. static unsigned int vbo_handle, vao_handle;
  22. template<typename T>
  23. unsigned int stream(GLenum target, unsigned int vbo, unsigned int *vbo_cursor, unsigned int *vbo_size, T *start, int elementCount)
  24. {
  25. unsigned int bytes = sizeof(T) *elementCount;
  26. unsigned int aligned = bytes + bytes % 64; //align memory
  27. glBindBuffer(target, vbo);
  28. //If there's not enough space left, orphan the buffer object, create a new one and start writing
  29. if (vbo_cursor[0] + aligned > vbo_size[0])
  30. {
  31. assert(aligned < vbo_size[0]);
  32. glBufferData(target, vbo_size[0], NULL, GL_DYNAMIC_DRAW);
  33. vbo_cursor[0] = 0;
  34. }
  35. void* mapped = glMapBufferRange(target, vbo_cursor[0], aligned, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT);
  36. memcpy(mapped, start, bytes);
  37. vbo_cursor[0] += aligned;
  38. glUnmapBuffer(target);
  39. return vbo_cursor[0] - aligned; //return the offset we use for glVertexAttribPointer call
  40. }
  41. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  42. // If text or lines are blurry when integrating ImGui in your engine:
  43. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f
  44. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  45. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  46. {
  47. if (cmd_lists_count == 0)
  48. return;
  49. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  50. glEnable(GL_BLEND);
  51. glBlendEquation(GL_FUNC_ADD);
  52. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  53. glDisable(GL_CULL_FACE);
  54. glDisable(GL_DEPTH_TEST);
  55. glEnable(GL_SCISSOR_TEST);
  56. // Setup texture
  57. glActiveTexture(GL_TEXTURE0);
  58. glBindTexture(GL_TEXTURE_2D, fontTex);
  59. // Setup orthographic projection matrix
  60. const float width = ImGui::GetIO().DisplaySize.x;
  61. const float height = ImGui::GetIO().DisplaySize.y;
  62. const float ortho_projection[4][4] =
  63. {
  64. { 2.0f/width, 0.0f, 0.0f, 0.0f },
  65. { 0.0f, 2.0f/-height, 0.0f, 0.0f },
  66. { 0.0f, 0.0f, -1.0f, 0.0f },
  67. { -1.0f, 1.0f, 0.0f, 1.0f },
  68. };
  69. glUseProgram(shader_handle);
  70. glUniform1i(texture_location, 0);
  71. glUniformMatrix4fv(ortho_location, 1, GL_FALSE, &ortho_projection[0][0]);
  72. // we will update the buffer in full, so we need to compute the total size of the buffer.
  73. size_t total_vtx_count = 0;
  74. for (int n = 0; n < cmd_lists_count; n++)
  75. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  76. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  77. size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert);
  78. if (neededBufferSize > vbo_max_size)
  79. {
  80. vbo_max_size = neededBufferSize;
  81. glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW);
  82. }
  83. unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  84. if (!buffer_data)
  85. return;
  86. for (int n = 0; n < cmd_lists_count; n++)
  87. {
  88. const ImDrawList* cmd_list = cmd_lists[n];
  89. memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  90. buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  91. }
  92. glUnmapBuffer(GL_ARRAY_BUFFER);
  93. glBindBuffer(GL_ARRAY_BUFFER, 0);
  94. glBindVertexArray(vao_handle);
  95. int cmd_offset = 0;
  96. for (int n = 0; n < cmd_lists_count; n++)
  97. {
  98. const ImDrawList* cmd_list = cmd_lists[n];
  99. int vtx_offset = cmd_offset;
  100. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  101. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  102. {
  103. 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));
  104. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  105. vtx_offset += pcmd->vtx_count;
  106. }
  107. cmd_offset = vtx_offset;
  108. }
  109. glBindVertexArray(0);
  110. glUseProgram(0);
  111. glDisable(GL_SCISSOR_TEST);
  112. glBindTexture(GL_TEXTURE_2D, 0);
  113. }
  114. static const char* ImImpl_GetClipboardTextFn()
  115. {
  116. return glfwGetClipboardString(window);
  117. }
  118. static void ImImpl_SetClipboardTextFn(const char* text)
  119. {
  120. glfwSetClipboardString(window, text);
  121. }
  122. // GLFW callbacks to get events
  123. static void glfw_error_callback(int error, const char* description)
  124. {
  125. fputs(description, stderr);
  126. }
  127. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  128. {
  129. ImGuiIO& io = ImGui::GetIO();
  130. io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1.0f : -1.0f : 0.0f; // Mouse wheel: -1,0,+1
  131. }
  132. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  133. {
  134. ImGuiIO& io = ImGui::GetIO();
  135. if (action == GLFW_PRESS)
  136. io.KeysDown[key] = true;
  137. if (action == GLFW_RELEASE)
  138. io.KeysDown[key] = false;
  139. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  140. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  141. }
  142. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  143. {
  144. if (c > 0 && c <= 255)
  145. ImGui::GetIO().AddInputCharacter((char)c);
  146. }
  147. // OpenGL code based on http://open.gl tutorials
  148. void InitGL()
  149. {
  150. glfwSetErrorCallback(glfw_error_callback);
  151. if (!glfwInit())
  152. exit(1);
  153. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  154. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  155. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  156. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  157. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
  158. glfwMakeContextCurrent(window);
  159. glfwSetKeyCallback(window, glfw_key_callback);
  160. glfwSetScrollCallback(window, glfw_scroll_callback);
  161. glfwSetCharCallback(window, glfw_char_callback);
  162. glewExperimental = GL_TRUE;
  163. GLenum err = glewInit();
  164. if (GLEW_OK != err)
  165. {
  166. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  167. }
  168. const GLchar *vertex_shader = \
  169. "#version 330\n"
  170. "uniform mat4 ortho;\n"
  171. "in vec2 Position;\n"
  172. "in vec2 UV;\n"
  173. "in vec4 Colour;\n"
  174. "out vec2 Frag_UV;\n"
  175. "out vec4 Frag_Colour;\n"
  176. "void main()\n"
  177. "{\n"
  178. " Frag_UV = UV;\n"
  179. " Frag_Colour = Colour;\n"
  180. "\n"
  181. " gl_Position = ortho*vec4(Position.xy,0,1);\n"
  182. "}\n";
  183. const GLchar* fragment_shader = \
  184. "#version 330\n"
  185. "uniform sampler2D Texture;\n"
  186. "in vec2 Frag_UV;\n"
  187. "in vec4 Frag_Colour;\n"
  188. "out vec4 FragColor;\n"
  189. "void main()\n"
  190. "{\n"
  191. " FragColor = Frag_Colour * texture( Texture, Frag_UV.st);\n"
  192. "}\n";
  193. shader_handle = glCreateProgram();
  194. vert_handle = glCreateShader(GL_VERTEX_SHADER);
  195. frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
  196. glShaderSource(vert_handle, 1, &vertex_shader, 0);
  197. glShaderSource(frag_handle, 1, &fragment_shader, 0);
  198. glCompileShader(vert_handle);
  199. glCompileShader(frag_handle);
  200. glAttachShader(shader_handle, vert_handle);
  201. glAttachShader(shader_handle, frag_handle);
  202. glLinkProgram(shader_handle);
  203. texture_location = glGetUniformLocation(shader_handle, "Texture");
  204. ortho_location = glGetUniformLocation(shader_handle, "ortho");
  205. position_location = glGetAttribLocation(shader_handle, "Position");
  206. uv_location = glGetAttribLocation(shader_handle, "UV");
  207. colour_location = glGetAttribLocation(shader_handle, "Colour");
  208. glGenBuffers(1, &vbo_handle);
  209. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  210. glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW);
  211. glGenVertexArrays(1, &vao_handle);
  212. glBindVertexArray(vao_handle);
  213. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  214. glEnableVertexAttribArray(position_location);
  215. glEnableVertexAttribArray(uv_location);
  216. glEnableVertexAttribArray(colour_location);
  217. glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, pos));
  218. glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, uv));
  219. glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, col));
  220. glBindVertexArray(0);
  221. glBindBuffer(GL_ARRAY_BUFFER, 0);
  222. }
  223. void InitImGui()
  224. {
  225. int w, h;
  226. glfwGetWindowSize(window, &w, &h);
  227. ImGuiIO& io = ImGui::GetIO();
  228. io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions.
  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.PixelCenterOffset = 0.5f; // Align OpenGL texels
  231. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  232. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  233. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  234. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  235. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  236. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  237. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  238. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  239. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  240. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  241. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  242. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  243. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  244. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  245. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  246. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  247. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  248. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  249. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  250. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  251. // Load font texture
  252. glGenTextures(1, &fontTex);
  253. glBindTexture(GL_TEXTURE_2D, fontTex);
  254. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  255. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  256. const void* png_data;
  257. unsigned int png_size;
  258. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  259. int tex_x, tex_y, tex_comp;
  260. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  261. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  262. stbi_image_free(tex_data);
  263. }
  264. void UpdateImGui()
  265. {
  266. ImGuiIO& io = ImGui::GetIO();
  267. // Setup timestep
  268. static double time = 0.0f;
  269. const double current_time = glfwGetTime();
  270. io.DeltaTime = (float)(current_time - time);
  271. time = current_time;
  272. // Setup inputs
  273. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  274. double mouse_x, mouse_y;
  275. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  276. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  277. io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
  278. io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  279. // Start the frame
  280. ImGui::NewFrame();
  281. }
  282. // Application code
  283. int main(int argc, char** argv)
  284. {
  285. InitGL();
  286. InitImGui();
  287. while (!glfwWindowShouldClose(window))
  288. {
  289. ImGuiIO& io = ImGui::GetIO();
  290. io.MouseWheel = 0;
  291. glfwPollEvents();
  292. UpdateImGui();
  293. // Create a simple window
  294. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  295. static bool show_test_window = true;
  296. static bool show_another_window = false;
  297. static float f;
  298. ImGui::Text("Hello, world!");
  299. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  300. show_test_window ^= ImGui::Button("Test Window");
  301. show_another_window ^= ImGui::Button("Another Window");
  302. // Calculate and show framerate
  303. static float ms_per_frame[120] = { 0 };
  304. static int ms_per_frame_idx = 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) % 120;
  310. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  311. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  312. // Show the ImGui test window
  313. // Most of user example code is in ImGui::ShowTestWindow()
  314. if (show_test_window)
  315. {
  316. 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!
  317. ImGui::ShowTestWindow(&show_test_window);
  318. }
  319. // Show another simple window
  320. if (show_another_window)
  321. {
  322. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  323. ImGui::Text("Hello");
  324. ImGui::End();
  325. }
  326. // Rendering
  327. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  328. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  329. glClear(GL_COLOR_BUFFER_BIT);
  330. ImGui::Render();
  331. glfwSwapBuffers(window);
  332. }
  333. if (vao_handle) glDeleteVertexArrays(1, &vao_handle);
  334. if (vbo_handle) glDeleteBuffers(1, &vbo_handle);
  335. glDetachShader(shader_handle, vert_handle);
  336. glDetachShader(shader_handle, frag_handle);
  337. glDeleteShader(vert_handle);
  338. glDeleteShader(frag_handle);
  339. glDeleteProgram(shader_handle);
  340. ImGui::Shutdown();
  341. glfwTerminate();
  342. return 0;
  343. }