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