main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #ifdef _MSC_VER
  2. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  3. #include <Windows.h>
  4. #include <Imm.h>
  5. #endif
  6. #define STB_IMAGE_IMPLEMENTATION
  7. #include "stb_image.h" // for .png loading
  8. #include "../../imgui.h"
  9. // glew & glfw
  10. #define GLEW_STATIC
  11. #include <GL/glew.h>
  12. #include <GLFW/glfw3.h>
  13. #ifdef _MSC_VER
  14. #define GLFW_EXPOSE_NATIVE_WIN32
  15. #define GLFW_EXPOSE_NATIVE_WGL
  16. #include <GLFW/glfw3native.h>
  17. #endif
  18. static GLFWwindow* window;
  19. static GLuint fontTex;
  20. static bool mousePressed[2] = { false, false };
  21. static ImVec2 mousePosScale(1.0f, 1.0f);
  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. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 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. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  31. // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
  32. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  33. glEnable(GL_BLEND);
  34. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  35. glDisable(GL_CULL_FACE);
  36. glDisable(GL_DEPTH_TEST);
  37. glEnable(GL_SCISSOR_TEST);
  38. glEnableClientState(GL_VERTEX_ARRAY);
  39. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  40. glEnableClientState(GL_COLOR_ARRAY);
  41. // Setup texture
  42. glBindTexture(GL_TEXTURE_2D, fontTex);
  43. glEnable(GL_TEXTURE_2D);
  44. // Setup orthographic projection matrix
  45. const float width = ImGui::GetIO().DisplaySize.x;
  46. const float height = ImGui::GetIO().DisplaySize.y;
  47. glMatrixMode(GL_PROJECTION);
  48. glLoadIdentity();
  49. glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
  50. glMatrixMode(GL_MODELVIEW);
  51. glLoadIdentity();
  52. // Render command lists
  53. for (int n = 0; n < cmd_lists_count; n++)
  54. {
  55. const ImDrawList* cmd_list = cmd_lists[n];
  56. const unsigned char* vtx_buffer = (const unsigned char*)cmd_list->vtx_buffer.begin();
  57. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer));
  58. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer+8));
  59. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer+16));
  60. int vtx_offset = 0;
  61. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  62. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  63. {
  64. 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));
  65. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  66. vtx_offset += pcmd->vtx_count;
  67. }
  68. }
  69. glDisable(GL_SCISSOR_TEST);
  70. glDisableClientState(GL_COLOR_ARRAY);
  71. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  72. glDisableClientState(GL_VERTEX_ARRAY);
  73. }
  74. // NB: ImGui already provide OS clipboard support for Windows so this isn't needed if you are using Windows only.
  75. static const char* ImImpl_GetClipboardTextFn()
  76. {
  77. return glfwGetClipboardString(window);
  78. }
  79. static void ImImpl_SetClipboardTextFn(const char* text)
  80. {
  81. glfwSetClipboardString(window, text);
  82. }
  83. #ifdef _MSC_VER
  84. // Notify OS Input Method Editor of text input position (e.g. when using Japanese/Chinese inputs, otherwise this isn't needed)
  85. static void ImImpl_ImeSetInputScreenPosFn(int x, int y)
  86. {
  87. HWND hwnd = glfwGetWin32Window(window);
  88. if (HIMC himc = ImmGetContext(hwnd))
  89. {
  90. COMPOSITIONFORM cf;
  91. cf.ptCurrentPos.x = x;
  92. cf.ptCurrentPos.y = y;
  93. cf.dwStyle = CFS_FORCE_POSITION;
  94. ImmSetCompositionWindow(himc, &cf);
  95. }
  96. }
  97. #endif
  98. // GLFW callbacks to get events
  99. static void glfw_error_callback(int error, const char* description)
  100. {
  101. fputs(description, stderr);
  102. }
  103. static void glfw_mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
  104. {
  105. if (action == GLFW_PRESS && button >= 0 && button < 2)
  106. mousePressed[button] = true;
  107. }
  108. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  109. {
  110. ImGuiIO& io = ImGui::GetIO();
  111. io.MouseWheel = (yoffset != 0.0f) ? yoffset > 0.0f ? 1 : - 1 : 0; // Mouse wheel: -1,0,+1
  112. }
  113. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  114. {
  115. ImGuiIO& io = ImGui::GetIO();
  116. if (action == GLFW_PRESS)
  117. io.KeysDown[key] = true;
  118. if (action == GLFW_RELEASE)
  119. io.KeysDown[key] = false;
  120. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  121. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  122. }
  123. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  124. {
  125. if (c > 0 && c < 0x10000)
  126. ImGui::GetIO().AddInputCharacter((unsigned short)c);
  127. }
  128. // OpenGL code based on http://open.gl tutorials
  129. void InitGL()
  130. {
  131. glfwSetErrorCallback(glfw_error_callback);
  132. if (!glfwInit())
  133. exit(1);
  134. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  135. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
  136. glfwMakeContextCurrent(window);
  137. glfwSetKeyCallback(window, glfw_key_callback);
  138. glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
  139. glfwSetScrollCallback(window, glfw_scroll_callback);
  140. glfwSetCharCallback(window, glfw_char_callback);
  141. glewInit();
  142. }
  143. void InitImGui()
  144. {
  145. int w, h;
  146. int fb_w, fb_h;
  147. glfwGetWindowSize(window, &w, &h);
  148. glfwGetFramebufferSize(window, &fb_w, &fb_h);
  149. mousePosScale.x = (float)fb_w / w; // Some screens e.g. Retina display have framebuffer size != from window size, and mouse inputs are given in window/screen coordinates.
  150. mousePosScale.y = (float)fb_h / h;
  151. ImGuiIO& io = ImGui::GetIO();
  152. io.DisplaySize = ImVec2((float)fb_w, (float)fb_h); // Display size, in pixels. For clamping windows positions.
  153. 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)
  154. io.PixelCenterOffset = 0.0f; // Align OpenGL texels
  155. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  156. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  157. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  158. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  159. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  160. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  161. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  162. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  163. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  164. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  165. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  166. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  167. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  168. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  169. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  170. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  171. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  172. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  173. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  174. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  175. #ifdef _MSC_VER
  176. io.ImeSetInputScreenPosFn = ImImpl_ImeSetInputScreenPosFn;
  177. #endif
  178. // Load font texture
  179. glGenTextures(1, &fontTex);
  180. glBindTexture(GL_TEXTURE_2D, fontTex);
  181. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  182. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  183. #if 1
  184. // Default font (embedded in code)
  185. const void* png_data;
  186. unsigned int png_size;
  187. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  188. int tex_x, tex_y, tex_comp;
  189. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  190. IM_ASSERT(tex_data != NULL);
  191. #else
  192. // Custom font from filesystem
  193. io.Font = new ImBitmapFont();
  194. io.Font->LoadFromFile("../../extra_fonts/mplus-2m-medium_18.fnt");
  195. IM_ASSERT(io.Font->IsLoaded());
  196. int tex_x, tex_y, tex_comp;
  197. void* tex_data = stbi_load("../../extra_fonts/mplus-2m-medium_18.png", &tex_x, &tex_y, &tex_comp, 0);
  198. IM_ASSERT(tex_data != NULL);
  199. // Automatically find white pixel from the texture we just loaded
  200. // (io.FontTexUvForWhite needs to contains UV coordinates pointing to a white pixel in order to render solid objects)
  201. for (int tex_data_off = 0; tex_data_off < tex_x*tex_y; tex_data_off++)
  202. if (((unsigned int*)tex_data)[tex_data_off] == 0xffffffff)
  203. {
  204. io.FontTexUvForWhite = ImVec2((float)(tex_data_off % tex_x)/(tex_x), (float)(tex_data_off / tex_x)/(tex_y));
  205. break;
  206. }
  207. #endif
  208. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  209. stbi_image_free(tex_data);
  210. }
  211. void UpdateImGui()
  212. {
  213. ImGuiIO& io = ImGui::GetIO();
  214. // Setup timestep
  215. static double time = 0.0f;
  216. const double current_time = glfwGetTime();
  217. io.DeltaTime = (float)(current_time - time);
  218. time = current_time;
  219. // Setup inputs
  220. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  221. double mouse_x, mouse_y;
  222. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  223. io.MousePos = ImVec2((float)mouse_x * mousePosScale.x, (float)mouse_y * mousePosScale.y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  224. 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.
  225. io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  226. // Start the frame
  227. ImGui::NewFrame();
  228. }
  229. // Application code
  230. int main(int argc, char** argv)
  231. {
  232. InitGL();
  233. InitImGui();
  234. while (!glfwWindowShouldClose(window))
  235. {
  236. ImGuiIO& io = ImGui::GetIO();
  237. mousePressed[0] = mousePressed[1] = false;
  238. io.MouseWheel = 0;
  239. glfwPollEvents();
  240. UpdateImGui();
  241. static bool show_test_window = true;
  242. static bool show_another_window = false;
  243. // 1. Show a simple window
  244. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  245. {
  246. static float f;
  247. ImGui::Text("Hello, world!");
  248. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  249. show_test_window ^= ImGui::Button("Test Window");
  250. show_another_window ^= ImGui::Button("Another Window");
  251. // Calculate and show framerate
  252. static float ms_per_frame[120] = { 0 };
  253. static int ms_per_frame_idx = 0;
  254. static float ms_per_frame_accum = 0.0f;
  255. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  256. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  257. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  258. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  259. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  260. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  261. }
  262. // 2. Show another simple window, this time using an explicit Begin/End pair
  263. if (show_another_window)
  264. {
  265. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  266. ImGui::Text("Hello");
  267. ImGui::End();
  268. }
  269. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  270. if (show_test_window)
  271. {
  272. ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call this, because positions are saved in .ini file. Here we just want to make the demo initial state a bit more friendly!
  273. ImGui::ShowTestWindow(&show_test_window);
  274. }
  275. // Rendering
  276. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  277. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  278. glClear(GL_COLOR_BUFFER_BIT);
  279. ImGui::Render();
  280. glfwSwapBuffers(window);
  281. }
  282. ImGui::Shutdown();
  283. glfwTerminate();
  284. return 0;
  285. }