1 // dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline
2 // - Desktop GL: 2.x 3.x 4.x
3 // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
4 // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
5 
6 // Implemented features:
7 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
8 //  [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9 //  [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
10 
11 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
12 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
13 // https://github.com/ocornut/imgui
14 
15 // CHANGELOG
16 // (minor and older changes stripped away, please see git history for details)
17 //  2020-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
18 //  2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
19 //  2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
20 //  2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
21 //  2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
22 //  2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
23 //  2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
24 //  2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
25 //  2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
26 //  2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
27 //  2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
28 //  2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
29 //  2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
30 //  2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
31 //  2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
32 //  2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
33 //  2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
34 //  2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
35 //  2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
36 //  2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
37 //  2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
38 //  2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
39 //  2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
40 //  2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
41 //  2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
42 //  2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
43 //  2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
44 //  2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer.
45 //  2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
46 //  2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
47 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
48 //  2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
49 //  2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
50 //  2017-05-01: OpenGL: Fixed save and restore of current blend func state.
51 //  2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
52 //  2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
53 //  2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
54 
55 //----------------------------------------
56 // OpenGL    GLSL      GLSL
57 // version   version   string
58 //----------------------------------------
59 //  2.0       110       "#version 110"
60 //  2.1       120       "#version 120"
61 //  3.0       130       "#version 130"
62 //  3.1       140       "#version 140"
63 //  3.2       150       "#version 150"
64 //  3.3       330       "#version 330 core"
65 //  4.0       400       "#version 400 core"
66 //  4.1       410       "#version 410 core"
67 //  4.2       420       "#version 410 core"
68 //  4.3       430       "#version 430 core"
69 //  ES 2.0    100       "#version 100"      = WebGL 1.0
70 //  ES 3.0    300       "#version 300 es"   = WebGL 2.0
71 //----------------------------------------
72 
73 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
74 #define _CRT_SECURE_NO_WARNINGS
75 #endif
76 
77 #include "imgui.h"
78 #include "imgui_impl_opengl3.h"
79 #include <stdio.h>
80 #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
81 #include <stddef.h>     // intptr_t
82 #else
83 #include <stdint.h>     // intptr_t
84 #endif
85 
86 #if defined(__APPLE__)
87 #include "TargetConditionals.h"
88 #endif
89 
90 // [Bruno Levy] Auto-enable GLES on matching platforms, copied from previous version
91 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
92 #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
93 #define IMGUI_IMPL_OPENGL_ES3           // iOS, Android  -> GL ES 3, "#version 300 es"
94 #undef IMGUI_IMPL_OPENGL_LOADER_GL3W
95 #undef IMGUI_IMPL_OPENGL_LOADER_GLEW
96 #undef IMGUI_IMPL_OPENGL_LOADER_GLAD
97 #undef IMGUI_IMPL_OPENGL_LOADER_GLBINDING
98 #undef IMGUI_IMPL_OPENGL_LOADER_CUSTOM
99 #elif defined(__EMSCRIPTEN__)
100 #define IMGUI_IMPL_OPENGL_ES2           // Emscripten    -> GL ES 2, "#version 100"
101 #undef IMGUI_IMPL_OPENGL_LOADER_GL3W
102 #undef IMGUI_IMPL_OPENGL_LOADER_GLEW
103 #undef IMGUI_IMPL_OPENGL_LOADER_GLAD
104 #undef IMGUI_IMPL_OPENGL_LOADER_GLBINDING
105 #undef IMGUI_IMPL_OPENGL_LOADER_CUSTOM
106 #endif
107 #endif
108 // end [Bruno Levy]
109 
110 // GL includes
111 #if defined(IMGUI_IMPL_OPENGL_ES2)
112 #include <GLES2/gl2.h>
113 #elif defined(IMGUI_IMPL_OPENGL_ES3)
114 #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
115 #include <OpenGLES/ES3/gl.h>    // Use GL ES 3
116 #else
117 #include <GLES3/gl3.h>          // Use GL ES 3
118 #endif
119 #else
120 // About Desktop OpenGL function loaders:
121 //  Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
122 //  Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
123 //  You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
124 #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
125 #include <GL/gl3w.h>            // Needs to be initialized with gl3wInit() in user's code
126 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
127 #include <GL/glew.h>            // Needs to be initialized with glewInit() in user's code.
128 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
129 #include <glad/glad.h>          // Needs to be initialized with gladLoadGL() in user's code.
130 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
131 #include <glad/gl.h>            // Needs to be initialized with gladLoadGL(...) or gladLoaderLoadGL() in user's code.
132 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
133 #ifndef GLFW_INCLUDE_NONE
134 #define GLFW_INCLUDE_NONE       // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
135 #endif
136 #include <glbinding/Binding.h>  // Needs to be initialized with glbinding::Binding::initialize() in user's code.
137 #include <glbinding/gl/gl.h>
138 using namespace gl;
139 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
140 #ifndef GLFW_INCLUDE_NONE
141 #define GLFW_INCLUDE_NONE       // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
142 #endif
143 #include <glbinding/glbinding.h>// Needs to be initialized with glbinding::initialize() in user's code.
144 #include <glbinding/gl/gl.h>
145 using namespace gl;
146 #else
147 #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
148 #endif
149 #endif
150 
151 // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
152 #if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) || !defined(GL_VERSION_3_2)
153 #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET   0
154 #else
155 #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET   1
156 #endif
157 
158 // OpenGL Data
159 static GLuint       g_GlVersion = 0;                // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
160 static char         g_GlslVersionString[32] = "";   // Specified by user or detected based on compile time GL settings.
161 static GLuint       g_FontTexture = 0;
162 static GLuint       g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
163 static GLint        g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;                                // Uniforms location
164 static GLuint       g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location
165 static unsigned int g_VboHandle = 0, g_ElementsHandle = 0;
166 
167 // Forward Declarations
168 static void ImGui_ImplOpenGL3_InitPlatformInterface();
169 static void ImGui_ImplOpenGL3_ShutdownPlatformInterface();
170 
171 // Functions
ImGui_ImplOpenGL3_Init(const char * glsl_version)172 bool    ImGui_ImplOpenGL3_Init(const char* glsl_version)
173 {
174     // Query for GL version (e.g. 320 for GL 3.2)
175 #if !defined(IMGUI_IMPL_OPENGL_ES2)
176     GLint major, minor;
177     glGetIntegerv(GL_MAJOR_VERSION, &major);
178     glGetIntegerv(GL_MINOR_VERSION, &minor);
179     g_GlVersion = (GLuint)(major * 100 + minor * 10);
180 #else
181     g_GlVersion = 200; // GLES 2
182 #endif
183 
184     // Setup back-end capabilities flags
185     ImGuiIO& io = ImGui::GetIO();
186     io.BackendRendererName = "imgui_impl_opengl3";
187 #if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
188     if (g_GlVersion >= 320)
189         io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
190 #endif
191     io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports;  // We can create multi-viewports on the Renderer side (optional)
192 
193     // Store GLSL version string so we can refer to it later in case we recreate shaders.
194     // Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure.
195 #if defined(IMGUI_IMPL_OPENGL_ES2)
196     if (glsl_version == NULL)
197         glsl_version = "#version 100";
198 #elif defined(IMGUI_IMPL_OPENGL_ES3)
199     if (glsl_version == NULL)
200         glsl_version = "#version 300 es";
201 #elif defined(__APPLE__)
202     if (glsl_version == NULL)
203         glsl_version = "#version 150";
204 #else
205     if (glsl_version == NULL)
206         glsl_version = "#version 130";
207 #endif
208     IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
209     strcpy(g_GlslVersionString, glsl_version);
210     strcat(g_GlslVersionString, "\n");
211 
212     // Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected.
213     // The code actually never uses the 'gl_loader' variable! It is only here so you can read it!
214     // If auto-detection fails or doesn't select the same GL loader file as used by your application,
215     // you are likely to get a crash below.
216     // You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
217     const char* gl_loader = "Unknown";
218     IM_UNUSED(gl_loader);
219 #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
220     gl_loader = "GL3W";
221 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
222     gl_loader = "GLEW";
223 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
224     gl_loader = "GLAD";
225 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
226     gl_loader = "GLAD2";
227 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
228     gl_loader = "glbinding2";
229 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
230     gl_loader = "glbinding3";
231 #elif defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
232     gl_loader = "custom";
233 #else
234     gl_loader = "none";
235 #endif
236 
237     // Make an arbitrary GL call (we don't actually need the result)
238     // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code.
239     // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above.
240     GLint current_texture;
241     glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
242 
243     if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
244         ImGui_ImplOpenGL3_InitPlatformInterface();
245 
246     return true;
247 }
248 
ImGui_ImplOpenGL3_Shutdown()249 void    ImGui_ImplOpenGL3_Shutdown()
250 {
251     ImGui_ImplOpenGL3_ShutdownPlatformInterface();
252     ImGui_ImplOpenGL3_DestroyDeviceObjects();
253 }
254 
ImGui_ImplOpenGL3_NewFrame()255 void    ImGui_ImplOpenGL3_NewFrame()
256 {
257     if (!g_ShaderHandle)
258         ImGui_ImplOpenGL3_CreateDeviceObjects();
259 }
260 
ImGui_ImplOpenGL3_SetupRenderState(ImDrawData * draw_data,int fb_width,int fb_height,GLuint vertex_array_object)261 static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
262 {
263     // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
264     glEnable(GL_BLEND);
265     glBlendEquation(GL_FUNC_ADD);
266     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
267     glDisable(GL_CULL_FACE);
268     glDisable(GL_DEPTH_TEST);
269     glEnable(GL_SCISSOR_TEST);
270 #ifdef GL_POLYGON_MODE
271     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
272 #endif
273 
274     // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
275     bool clip_origin_lower_left = true;
276 #if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__)
277     GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
278     if (current_clip_origin == GL_UPPER_LEFT)
279         clip_origin_lower_left = false;
280 #endif
281 
282     // Setup viewport, orthographic projection matrix
283     // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
284     glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
285     float L = draw_data->DisplayPos.x;
286     float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
287     float T = draw_data->DisplayPos.y;
288     float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
289     if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
290     const float ortho_projection[4][4] =
291     {
292         { 2.0f/(R-L),   0.0f,         0.0f,   0.0f },
293         { 0.0f,         2.0f/(T-B),   0.0f,   0.0f },
294         { 0.0f,         0.0f,        -1.0f,   0.0f },
295         { (R+L)/(L-R),  (T+B)/(B-T),  0.0f,   1.0f },
296     };
297     glUseProgram(g_ShaderHandle);
298     glUniform1i(g_AttribLocationTex, 0);
299     glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
300 #ifdef GL_SAMPLER_BINDING
301     glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
302 #endif
303 
304     (void)vertex_array_object;
305 #ifndef IMGUI_IMPL_OPENGL_ES2
306     glBindVertexArray(vertex_array_object);
307 #endif
308 
309     // Bind vertex/index buffers and setup attributes for ImDrawVert
310     glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
311     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
312     glEnableVertexAttribArray(g_AttribLocationVtxPos);
313     glEnableVertexAttribArray(g_AttribLocationVtxUV);
314     glEnableVertexAttribArray(g_AttribLocationVtxColor);
315     glVertexAttribPointer(g_AttribLocationVtxPos,   2, GL_FLOAT,         GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
316     glVertexAttribPointer(g_AttribLocationVtxUV,    2, GL_FLOAT,         GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
317     glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE,  sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
318 }
319 
320 // OpenGL3 Render function.
321 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
322 // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
ImGui_ImplOpenGL3_RenderDrawData(ImDrawData * draw_data)323 void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
324 {
325     // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
326     int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
327     int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
328     if (fb_width <= 0 || fb_height <= 0)
329         return;
330 
331     // Backup GL state
332     GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
333     glActiveTexture(GL_TEXTURE0);
334     GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
335     GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
336 #ifdef GL_SAMPLER_BINDING
337     GLuint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler);
338 #endif
339     GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
340 #ifndef IMGUI_IMPL_OPENGL_ES2
341     GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
342 #endif
343 #ifdef GL_POLYGON_MODE
344     GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
345 #endif
346     GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
347     GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
348     GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
349     GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
350     GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
351     GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
352     GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
353     GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
354     GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
355     GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
356     GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
357     GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
358 
359     // Setup desired GL state
360     // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
361     // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
362     GLuint vertex_array_object = 0;
363 #ifndef IMGUI_IMPL_OPENGL_ES2
364     glGenVertexArrays(1, &vertex_array_object);
365 #endif
366     ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
367 
368     // Will project scissor/clipping rectangles into framebuffer space
369     ImVec2 clip_off = draw_data->DisplayPos;         // (0,0) unless using multi-viewports
370     ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
371 
372     // Render command lists
373     for (int n = 0; n < draw_data->CmdListsCount; n++)
374     {
375         const ImDrawList* cmd_list = draw_data->CmdLists[n];
376 
377         // Upload vertex/index buffers
378         glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
379         glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
380 
381         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
382         {
383             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
384             if (pcmd->UserCallback != NULL)
385             {
386                 // User callback, registered via ImDrawList::AddCallback()
387                 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
388                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
389                     ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
390                 else
391                     pcmd->UserCallback(cmd_list, pcmd);
392             }
393             else
394             {
395                 // Project scissor/clipping rectangles into framebuffer space
396                 ImVec4 clip_rect;
397                 clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
398                 clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
399                 clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
400                 clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
401 
402                 if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
403                 {
404                     // Apply scissor/clipping rectangle
405                     glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y));
406 
407                     // Bind texture, Draw
408                     glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
409 #if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
410                     if (g_GlVersion >= 320)
411                         glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset);
412                     else
413 #endif
414                     glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)));
415                 }
416             }
417         }
418     }
419 
420     // Destroy the temporary VAO
421 #ifndef IMGUI_IMPL_OPENGL_ES2
422     glDeleteVertexArrays(1, &vertex_array_object);
423 #endif
424 
425     // Restore modified GL state
426     glUseProgram(last_program);
427     glBindTexture(GL_TEXTURE_2D, last_texture);
428 #ifdef GL_SAMPLER_BINDING
429     glBindSampler(0, last_sampler);
430 #endif
431     glActiveTexture(last_active_texture);
432 #ifndef IMGUI_IMPL_OPENGL_ES2
433     glBindVertexArray(last_vertex_array_object);
434 #endif
435     glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
436     glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
437     glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
438     if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
439     if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
440     if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
441     if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
442 #ifdef GL_POLYGON_MODE
443     glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
444 #endif
445     glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
446     glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
447 }
448 
ImGui_ImplOpenGL3_CreateFontsTexture()449 bool ImGui_ImplOpenGL3_CreateFontsTexture()
450 {
451     // Build texture atlas
452     ImGuiIO& io = ImGui::GetIO();
453     unsigned char* pixels;
454     int width, height;
455     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);   // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
456 
457     // Upload texture to graphics system
458     GLint last_texture;
459     glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
460     glGenTextures(1, &g_FontTexture);
461     glBindTexture(GL_TEXTURE_2D, g_FontTexture);
462     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
463     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
464 #ifdef GL_UNPACK_ROW_LENGTH
465     glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
466 #endif
467     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
468 
469     // Store our identifier
470     io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontTexture;
471 
472     // Restore state
473     glBindTexture(GL_TEXTURE_2D, last_texture);
474 
475     return true;
476 }
477 
ImGui_ImplOpenGL3_DestroyFontsTexture()478 void ImGui_ImplOpenGL3_DestroyFontsTexture()
479 {
480     if (g_FontTexture)
481     {
482         ImGuiIO& io = ImGui::GetIO();
483         glDeleteTextures(1, &g_FontTexture);
484         io.Fonts->TexID = 0;
485         g_FontTexture = 0;
486     }
487 }
488 
489 // If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
CheckShader(GLuint handle,const char * desc)490 static bool CheckShader(GLuint handle, const char* desc)
491 {
492     GLint status = 0, log_length = 0;
493     glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
494     glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
495     if ((GLboolean)status == GL_FALSE)
496         fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc);
497     if (log_length > 1)
498     {
499         ImVector<char> buf;
500         buf.resize((int)(log_length + 1));
501         glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
502         fprintf(stderr, "%s\n", buf.begin());
503     }
504     return (GLboolean)status == GL_TRUE;
505 }
506 
507 // If you get an error please report on GitHub. You may try different GL context version or GLSL version.
CheckProgram(GLuint handle,const char * desc)508 static bool CheckProgram(GLuint handle, const char* desc)
509 {
510     GLint status = 0, log_length = 0;
511     glGetProgramiv(handle, GL_LINK_STATUS, &status);
512     glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
513     if ((GLboolean)status == GL_FALSE)
514         fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString);
515     if (log_length > 1)
516     {
517         ImVector<char> buf;
518         buf.resize((int)(log_length + 1));
519         glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
520         fprintf(stderr, "%s\n", buf.begin());
521     }
522     return (GLboolean)status == GL_TRUE;
523 }
524 
ImGui_ImplOpenGL3_CreateDeviceObjects()525 bool    ImGui_ImplOpenGL3_CreateDeviceObjects()
526 {
527     // Backup GL state
528     GLint last_texture, last_array_buffer;
529     glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
530     glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
531 #ifndef IMGUI_IMPL_OPENGL_ES2
532     GLint last_vertex_array;
533     glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
534 #endif
535 
536     // Parse GLSL version string
537     int glsl_version = 130;
538     sscanf(g_GlslVersionString, "#version %d", &glsl_version);
539 
540     const GLchar* vertex_shader_glsl_120 =
541         "uniform mat4 ProjMtx;\n"
542         "attribute vec2 Position;\n"
543         "attribute vec2 UV;\n"
544         "attribute vec4 Color;\n"
545         "varying vec2 Frag_UV;\n"
546         "varying vec4 Frag_Color;\n"
547         "void main()\n"
548         "{\n"
549         "    Frag_UV = UV;\n"
550         "    Frag_Color = Color;\n"
551         "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
552         "}\n";
553 
554     const GLchar* vertex_shader_glsl_130 =
555         "uniform mat4 ProjMtx;\n"
556         "in vec2 Position;\n"
557         "in vec2 UV;\n"
558         "in vec4 Color;\n"
559         "out vec2 Frag_UV;\n"
560         "out vec4 Frag_Color;\n"
561         "void main()\n"
562         "{\n"
563         "    Frag_UV = UV;\n"
564         "    Frag_Color = Color;\n"
565         "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
566         "}\n";
567 
568     const GLchar* vertex_shader_glsl_300_es =
569         "precision mediump float;\n"
570         "layout (location = 0) in vec2 Position;\n"
571         "layout (location = 1) in vec2 UV;\n"
572         "layout (location = 2) in vec4 Color;\n"
573         "uniform mat4 ProjMtx;\n"
574         "out vec2 Frag_UV;\n"
575         "out vec4 Frag_Color;\n"
576         "void main()\n"
577         "{\n"
578         "    Frag_UV = UV;\n"
579         "    Frag_Color = Color;\n"
580         "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
581         "}\n";
582 
583     const GLchar* vertex_shader_glsl_410_core =
584         "layout (location = 0) in vec2 Position;\n"
585         "layout (location = 1) in vec2 UV;\n"
586         "layout (location = 2) in vec4 Color;\n"
587         "uniform mat4 ProjMtx;\n"
588         "out vec2 Frag_UV;\n"
589         "out vec4 Frag_Color;\n"
590         "void main()\n"
591         "{\n"
592         "    Frag_UV = UV;\n"
593         "    Frag_Color = Color;\n"
594         "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
595         "}\n";
596 
597     const GLchar* fragment_shader_glsl_120 =
598         "#ifdef GL_ES\n"
599         "    precision mediump float;\n"
600         "#endif\n"
601         "uniform sampler2D Texture;\n"
602         "varying vec2 Frag_UV;\n"
603         "varying vec4 Frag_Color;\n"
604         "void main()\n"
605         "{\n"
606         "    gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
607         "}\n";
608 
609     const GLchar* fragment_shader_glsl_130 =
610         "uniform sampler2D Texture;\n"
611         "in vec2 Frag_UV;\n"
612         "in vec4 Frag_Color;\n"
613         "out vec4 Out_Color;\n"
614         "void main()\n"
615         "{\n"
616         "    Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
617         "}\n";
618 
619     const GLchar* fragment_shader_glsl_300_es =
620         "precision mediump float;\n"
621         "uniform sampler2D Texture;\n"
622         "in vec2 Frag_UV;\n"
623         "in vec4 Frag_Color;\n"
624         "layout (location = 0) out vec4 Out_Color;\n"
625         "void main()\n"
626         "{\n"
627         "    Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
628         "}\n";
629 
630     const GLchar* fragment_shader_glsl_410_core =
631         "in vec2 Frag_UV;\n"
632         "in vec4 Frag_Color;\n"
633         "uniform sampler2D Texture;\n"
634         "layout (location = 0) out vec4 Out_Color;\n"
635         "void main()\n"
636         "{\n"
637         "    Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
638         "}\n";
639 
640     // Select shaders matching our GLSL versions
641     const GLchar* vertex_shader = NULL;
642     const GLchar* fragment_shader = NULL;
643     if (glsl_version < 130)
644     {
645         vertex_shader = vertex_shader_glsl_120;
646         fragment_shader = fragment_shader_glsl_120;
647     }
648     else if (glsl_version >= 410)
649     {
650         vertex_shader = vertex_shader_glsl_410_core;
651         fragment_shader = fragment_shader_glsl_410_core;
652     }
653     else if (glsl_version == 300)
654     {
655         vertex_shader = vertex_shader_glsl_300_es;
656         fragment_shader = fragment_shader_glsl_300_es;
657     }
658     else
659     {
660         vertex_shader = vertex_shader_glsl_130;
661         fragment_shader = fragment_shader_glsl_130;
662     }
663 
664     // Create shaders
665     const GLchar* vertex_shader_with_version[2] = { g_GlslVersionString, vertex_shader };
666     g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
667     glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL);
668     glCompileShader(g_VertHandle);
669     CheckShader(g_VertHandle, "vertex shader");
670 
671     const GLchar* fragment_shader_with_version[2] = { g_GlslVersionString, fragment_shader };
672     g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
673     glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL);
674     glCompileShader(g_FragHandle);
675     CheckShader(g_FragHandle, "fragment shader");
676 
677     g_ShaderHandle = glCreateProgram();
678     glAttachShader(g_ShaderHandle, g_VertHandle);
679     glAttachShader(g_ShaderHandle, g_FragHandle);
680     glLinkProgram(g_ShaderHandle);
681     CheckProgram(g_ShaderHandle, "shader program");
682 
683     g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
684     g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
685     g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position");
686     g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV");
687     g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color");
688 
689     // Create buffers
690     glGenBuffers(1, &g_VboHandle);
691     glGenBuffers(1, &g_ElementsHandle);
692 
693     ImGui_ImplOpenGL3_CreateFontsTexture();
694 
695     // Restore modified GL state
696     glBindTexture(GL_TEXTURE_2D, last_texture);
697     glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
698 #ifndef IMGUI_IMPL_OPENGL_ES2
699     glBindVertexArray(last_vertex_array);
700 #endif
701 
702     return true;
703 }
704 
ImGui_ImplOpenGL3_DestroyDeviceObjects()705 void    ImGui_ImplOpenGL3_DestroyDeviceObjects()
706 {
707     if (g_VboHandle)        { glDeleteBuffers(1, &g_VboHandle); g_VboHandle = 0; }
708     if (g_ElementsHandle)   { glDeleteBuffers(1, &g_ElementsHandle); g_ElementsHandle = 0; }
709     if (g_ShaderHandle && g_VertHandle) { glDetachShader(g_ShaderHandle, g_VertHandle); }
710     if (g_ShaderHandle && g_FragHandle) { glDetachShader(g_ShaderHandle, g_FragHandle); }
711     if (g_VertHandle)       { glDeleteShader(g_VertHandle); g_VertHandle = 0; }
712     if (g_FragHandle)       { glDeleteShader(g_FragHandle); g_FragHandle = 0; }
713     if (g_ShaderHandle)     { glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; }
714 
715     ImGui_ImplOpenGL3_DestroyFontsTexture();
716 }
717 
718 //--------------------------------------------------------------------------------------------------------
719 // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
720 // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
721 // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
722 //--------------------------------------------------------------------------------------------------------
723 
ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport * viewport,void *)724 static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*)
725 {
726     if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
727     {
728         ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
729         glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
730         glClear(GL_COLOR_BUFFER_BIT);
731     }
732     ImGui_ImplOpenGL3_RenderDrawData(viewport->DrawData);
733 }
734 
ImGui_ImplOpenGL3_InitPlatformInterface()735 static void ImGui_ImplOpenGL3_InitPlatformInterface()
736 {
737     ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
738     platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL3_RenderWindow;
739 }
740 
ImGui_ImplOpenGL3_ShutdownPlatformInterface()741 static void ImGui_ImplOpenGL3_ShutdownPlatformInterface()
742 {
743     ImGui::DestroyPlatformWindows();
744 }
745