git.s-ol.nu zig-imgui / master
zig-fmt everything s-ol 29 days ago
5 changed file(s) with 738 addition(s) and 734 deletion(s). Raw diff Collapse all Expand all
11 zig-cache
2 imgui.ini
11 pub usingnamespace @cImport({
2 @cInclude("epoxy/gl.h");
3 @cDefine("CIMGUI_DEFINE_ENUMS_AND_STRUCTS", "1");
4 @cInclude("cimgui.h");
5 @cInclude("GLFW/glfw3.h");
2 @cInclude("epoxy/gl.h");
3 @cDefine("CIMGUI_DEFINE_ENUMS_AND_STRUCTS", "1");
4 @cInclude("cimgui.h");
5 @cInclude("GLFW/glfw3.h");
66 });
1 /// this is a port of cimgui/imgui/examples/imgui_impl_opengl3.cpp
12 const c = @import("c.zig");
23 const mem = @import("std").mem;
34 const math = @import("std").math;
56 const builtin = @import("builtin");
67
78 const OpenGLHasDrawWithBaseVertex = @hasField(c, "IMGUI_IMPL_OPENGL_ES2") or
8 @hasField(c, "IMGUI_IMPL_OPENGL_ES3");
9 @hasField(c, "IMGUI_IMPL_OPENGL_ES3");
910
1011 // OpenGL Data
11 var g_GlslVersionString_buf : [32]u8 = undefined;
12 var g_GlslVersionString : []u8 = g_GlslVersionString_buf[0..0];
13
14 var g_FontTexture : c.GLuint = 0;
15 var g_ShaderHandle : c.GLuint = 0;
16 var g_VertHandle : c.GLuint = 0;
12 var g_GlslVersionString_buf: [32]u8 = undefined;
13 var g_GlslVersionString: []u8 = g_GlslVersionString_buf[0..0];
14
15 var g_FontTexture: c.GLuint = 0;
16 var g_ShaderHandle: c.GLuint = 0;
17 var g_VertHandle: c.GLuint = 0;
1718 var g_FragHandle: c.GLuint = 0;
18 var g_AttribLocationTex : c.GLint = 0;
19 var g_AttribLocationProjMtx : c.GLint = 0;
20 var g_AttribLocationVtxPos : c.GLint = 0;
21 var g_AttribLocationVtxUV : c.GLint = 0;
22 var g_AttribLocationVtxColor : c.GLint = 0;
23 var g_VboHandle : c.GLuint = 0;
24 var g_ElementsHandle : c.GLuint = 0;
19 var g_AttribLocationTex: c.GLint = 0;
20 var g_AttribLocationProjMtx: c.GLint = 0;
21 var g_AttribLocationVtxPos: c.GLint = 0;
22 var g_AttribLocationVtxUV: c.GLint = 0;
23 var g_AttribLocationVtxColor: c.GLint = 0;
24 var g_VboHandle: c.GLuint = 0;
25 var g_ElementsHandle: c.GLuint = 0;
2526
2627 pub fn Init() void {
27 const io = c.igGetIO();
28 io.*.BackendRendererName = c"imgui_impl_gl3.zig";
29 if (OpenGLHasDrawWithBaseVertex)
30 io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_RendererHasVtxOffset);
31 // @TODO: Viewports
32 // io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_RendererHasViewports);
33
34 // @TODO: GLSL versions?
35 // g_GlslVersionString = g_GlslVersionString_buf[0..glsl_version.len];
36 // mem.copy(u8, g_GlslVersionString, glsl_version);
37
38 // @FIXME: just for testing:
39 var tex : c.GLint = undefined;
40 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &tex);
41
42 // @TODO: Viewports
43 // if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0)
44 // InitPlatformInterface();
28 const io = c.igGetIO();
29 io.*.BackendRendererName = c"imgui_impl_gl3.zig";
30 if (OpenGLHasDrawWithBaseVertex)
31 io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_RendererHasVtxOffset);
32 // @TODO: Viewports
33 // io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_RendererHasViewports);
34
35 // @TODO: GLSL versions?
36 // g_GlslVersionString = g_GlslVersionString_buf[0..glsl_version.len];
37 // mem.copy(u8, g_GlslVersionString, glsl_version);
38
39 // @FIXME: just for testing:
40 var tex: c.GLint = undefined;
41 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &tex);
42
43 // @TODO: Viewports
44 // if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0)
45 // InitPlatformInterface();
4546 }
4647
4748 pub fn Shutdown() void {
48 // ImGui_ImplOpenGL3_ShutdownPlatformInterface();
49 DestroyDeviceObjects();
49 // ImGui_ImplOpenGL3_ShutdownPlatformInterface();
50 DestroyDeviceObjects();
5051 }
5152
5253 pub fn NewFrame() !void {
53 if (g_ShaderHandle == 0)
54 try CreateDeviceObjects();
54 if (g_ShaderHandle == 0)
55 try CreateDeviceObjects();
5556 }
5657
5758 fn CreateDeviceObjects() !void {
58 // back up GL state
59 var last_texture : c.GLint = undefined;
60 var last_array_buffer : c.GLint = undefined;
61 var last_vertex_array : c.GLint = undefined;
62
63 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
64 defer c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
65
66 c.glGetIntegerv(c.GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
67 c.glBindBuffer(c.GL_ARRAY_BUFFER, @intCast(c.GLuint, last_array_buffer));
68
69 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
70 c.glGetIntegerv(c.GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
71 defer if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
72 c.glBindVertexArray(@intCast(c.GLuint, last_vertex_array));
73
74 // @TODO: GLSL versions?
75 const vertex_shader_glsl : [*]const c.GLchar =
76 c\\#version 150
77 c\\uniform mat4 ProjMtx;
78 c\\in vec2 Position;
79 c\\in vec2 UV;
80 c\\in vec4 Color;
81 c\\out vec2 Frag_UV;
82 c\\out vec4 Frag_Color;
83 c\\void main()
84 c\\{
85 c\\ Frag_UV = UV;
86 c\\ Frag_Color = Color;
87 c\\ gl_Position = ProjMtx * vec4(Position.xy, 0, 1);
88 c\\}
89 ;
90
91 const fragment_shader_glsl : [*]const c.GLchar =
92 c\\#version 150
93 c\\uniform sampler2D Texture;
94 c\\in vec2 Frag_UV;
95 c\\in vec4 Frag_Color;
96 c\\out vec4 Out_Color;
97 c\\void main()
98 c\\{
99 c\\ Out_Color = Frag_Color * texture(Texture, Frag_UV.st);
100 c\\}
101 ;
102
103 // Create shaders / programs
104 g_VertHandle = c.glCreateShader(c.GL_VERTEX_SHADER);
105 c.glShaderSource(g_VertHandle, 1, &vertex_shader_glsl, null);
106 c.glCompileShader(g_VertHandle);
107 try CheckThing(.Shader, g_VertHandle, "vertex shader");
108
109 g_FragHandle = c.glCreateShader(c.GL_FRAGMENT_SHADER);
110 c.glShaderSource(g_FragHandle, 1, &fragment_shader_glsl, null);
111 c.glCompileShader(g_FragHandle);
112 try CheckThing(.Shader, g_FragHandle, "fragment shader");
113
114 g_ShaderHandle = c.glCreateProgram();
115 c.glAttachShader(g_ShaderHandle, g_VertHandle);
116 c.glAttachShader(g_ShaderHandle, g_FragHandle);
117 c.glLinkProgram(g_ShaderHandle);
118 try CheckThing(.Program, g_ShaderHandle, "shader program");
119
120 g_AttribLocationTex = c.glGetUniformLocation(g_ShaderHandle, c"Texture");
121 g_AttribLocationProjMtx = c.glGetUniformLocation(g_ShaderHandle, c"ProjMtx");
122 g_AttribLocationVtxPos = c.glGetAttribLocation(g_ShaderHandle, c"Position");
123 g_AttribLocationVtxUV = c.glGetAttribLocation(g_ShaderHandle, c"UV");
124 g_AttribLocationVtxColor = c.glGetAttribLocation(g_ShaderHandle, c"Color");
125
126 // Create buffers
127 c.glGenBuffers(1, &g_VboHandle);
128 c.glGenBuffers(1, &g_ElementsHandle);
129
130 CreateFontsTexture();
131 }
132
59 // back up GL state
60 var last_texture: c.GLint = undefined;
61 var last_array_buffer: c.GLint = undefined;
62 var last_vertex_array: c.GLint = undefined;
63
64 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
65 defer c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
66
67 c.glGetIntegerv(c.GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
68 c.glBindBuffer(c.GL_ARRAY_BUFFER, @intCast(c.GLuint, last_array_buffer));
69
70 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
71 c.glGetIntegerv(c.GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
72 defer if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
73 c.glBindVertexArray(@intCast(c.GLuint, last_vertex_array));
74
75 // @TODO: GLSL versions?
76 const vertex_shader_glsl: [*]const c.GLchar =
77 c\\#version 150
78 c\\uniform mat4 ProjMtx;
79 c\\in vec2 Position;
80 c\\in vec2 UV;
81 c\\in vec4 Color;
82 c\\out vec2 Frag_UV;
83 c\\out vec4 Frag_Color;
84 c\\void main()
85 c\\{
86 c\\ Frag_UV = UV;
87 c\\ Frag_Color = Color;
88 c\\ gl_Position = ProjMtx * vec4(Position.xy, 0, 1);
89 c\\}
90 ;
91
92 const fragment_shader_glsl: [*]const c.GLchar =
93 c\\#version 150
94 c\\uniform sampler2D Texture;
95 c\\in vec2 Frag_UV;
96 c\\in vec4 Frag_Color;
97 c\\out vec4 Out_Color;
98 c\\void main()
99 c\\{
100 c\\ Out_Color = Frag_Color * texture(Texture, Frag_UV.st);
101 c\\}
102 ;
103
104 // Create shaders / programs
105 g_VertHandle = c.glCreateShader(c.GL_VERTEX_SHADER);
106 c.glShaderSource(g_VertHandle, 1, &vertex_shader_glsl, null);
107 c.glCompileShader(g_VertHandle);
108 try CheckThing(.Shader, g_VertHandle, "vertex shader");
109
110 g_FragHandle = c.glCreateShader(c.GL_FRAGMENT_SHADER);
111 c.glShaderSource(g_FragHandle, 1, &fragment_shader_glsl, null);
112 c.glCompileShader(g_FragHandle);
113 try CheckThing(.Shader, g_FragHandle, "fragment shader");
114
115 g_ShaderHandle = c.glCreateProgram();
116 c.glAttachShader(g_ShaderHandle, g_VertHandle);
117 c.glAttachShader(g_ShaderHandle, g_FragHandle);
118 c.glLinkProgram(g_ShaderHandle);
119 try CheckThing(.Program, g_ShaderHandle, "shader program");
120
121 g_AttribLocationTex = c.glGetUniformLocation(g_ShaderHandle, c"Texture");
122 g_AttribLocationProjMtx = c.glGetUniformLocation(g_ShaderHandle, c"ProjMtx");
123 g_AttribLocationVtxPos = c.glGetAttribLocation(g_ShaderHandle, c"Position");
124 g_AttribLocationVtxUV = c.glGetAttribLocation(g_ShaderHandle, c"UV");
125 g_AttribLocationVtxColor = c.glGetAttribLocation(g_ShaderHandle, c"Color");
126
127 // Create buffers
128 c.glGenBuffers(1, &g_VboHandle);
129 c.glGenBuffers(1, &g_ElementsHandle);
130
131 CreateFontsTexture();
132 }
133133
134134 const CheckableThing = enum {
135 Shader,
136 Program,
135 Shader,
136 Program,
137137 };
138138 fn CheckThing(comptime thingType: CheckableThing, handle: c.GLuint, desc: []const u8) !void {
139 var status : c.GLint = undefined;
140 var log_length : c.GLint = undefined;
141 const getInfoLogFunc = switch (thingType) {
142 .Shader => blk: {
143 c.glGetShaderiv(handle, c.GL_COMPILE_STATUS, &status);
144 c.glGetShaderiv(handle, c.GL_INFO_LOG_LENGTH, &log_length);
145 break :blk c.glGetShaderInfoLog;
146 },
147 .Program => blk: {
148 c.glGetProgramiv(handle, c.GL_LINK_STATUS, &status);
149 c.glGetProgramiv(handle, c.GL_INFO_LOG_LENGTH, &log_length);
150 break :blk c.glGetProgramInfoLog;
151 },
152 };
153
154 if (log_length > 1)
155 {
156 var buf : [1024]u8 = undefined;
157 var length : c.GLsizei = undefined;
158 getInfoLogFunc(handle, buf.len, &length, &buf[0]);
159 debug.warn("{}\n", buf[0..@intCast(usize, length)]);
160 }
161
162 if (@intCast(c.GLboolean, status) == c.GL_FALSE) {
163 debug.warn("ERROR: CreateDeviceObjects: failed to compile/link {}! (with GLSL '{}')\n", desc, g_GlslVersionString);
164 return error.ShaderLinkError;
165 }
139 var status: c.GLint = undefined;
140 var log_length: c.GLint = undefined;
141 const getInfoLogFunc = switch (thingType) {
142 .Shader => blk: {
143 c.glGetShaderiv(handle, c.GL_COMPILE_STATUS, &status);
144 c.glGetShaderiv(handle, c.GL_INFO_LOG_LENGTH, &log_length);
145 break :blk c.glGetShaderInfoLog;
146 },
147 .Program => blk: {
148 c.glGetProgramiv(handle, c.GL_LINK_STATUS, &status);
149 c.glGetProgramiv(handle, c.GL_INFO_LOG_LENGTH, &log_length);
150 break :blk c.glGetProgramInfoLog;
151 },
152 };
153
154 if (log_length > 1) {
155 var buf: [1024]u8 = undefined;
156 var length: c.GLsizei = undefined;
157 getInfoLogFunc(handle, buf.len, &length, &buf[0]);
158 debug.warn("{}\n", buf[0..@intCast(usize, length)]);
159 }
160
161 if (@intCast(c.GLboolean, status) == c.GL_FALSE) {
162 debug.warn("ERROR: CreateDeviceObjects: failed to compile/link {}! (with GLSL '{}')\n", desc, g_GlslVersionString);
163 return error.ShaderLinkError;
164 }
166165 }
167166
168167 fn DestroyDeviceObjects() void {
169 if (g_VboHandle != 0) {
170 c.glDeleteBuffers(1, &g_VboHandle);
171 g_VboHandle = 0;
172 }
173
174 if (g_ElementsHandle != 0) {
175 c.glDeleteBuffers(1, &g_ElementsHandle);
176 g_ElementsHandle = 0;
177 }
178
179 if (g_ShaderHandle != 0 and g_VertHandle != 0)
180 c.glDetachShader(g_ShaderHandle, g_VertHandle);
181
182 if (g_ShaderHandle != 0 and g_FragHandle != 0)
183 c.glDetachShader(g_ShaderHandle, g_FragHandle);
184
185 if (g_VertHandle != 0) {
186 c.glDeleteShader(g_VertHandle);
187 g_VertHandle = 0;
188 }
189
190 if (g_FragHandle != 0) {
191 c.glDeleteShader(g_FragHandle);
192 g_FragHandle = 0;
193 }
194
195 if (g_ShaderHandle != 0) {
196 c.glDeleteProgram(g_ShaderHandle);
197 g_ShaderHandle = 0;
198 }
199
200 DestroyFontsTexture();
168 if (g_VboHandle != 0) {
169 c.glDeleteBuffers(1, &g_VboHandle);
170 g_VboHandle = 0;
171 }
172
173 if (g_ElementsHandle != 0) {
174 c.glDeleteBuffers(1, &g_ElementsHandle);
175 g_ElementsHandle = 0;
176 }
177
178 if (g_ShaderHandle != 0 and g_VertHandle != 0)
179 c.glDetachShader(g_ShaderHandle, g_VertHandle);
180
181 if (g_ShaderHandle != 0 and g_FragHandle != 0)
182 c.glDetachShader(g_ShaderHandle, g_FragHandle);
183
184 if (g_VertHandle != 0) {
185 c.glDeleteShader(g_VertHandle);
186 g_VertHandle = 0;
187 }
188
189 if (g_FragHandle != 0) {
190 c.glDeleteShader(g_FragHandle);
191 g_FragHandle = 0;
192 }
193
194 if (g_ShaderHandle != 0) {
195 c.glDeleteProgram(g_ShaderHandle);
196 g_ShaderHandle = 0;
197 }
198
199 DestroyFontsTexture();
201200 }
202201
203202 fn CreateFontsTexture() void {
204 const io = c.igGetIO();
205
206 // Get current font image data
207 var width : c_int = undefined;
208 var height : c_int = undefined;
209 var pixels : [*c]u8 = undefined;
210 c.ImFontAtlas_GetTexDataAsRGBA32(io.*.Fonts, &pixels, &width, &height, null);
211
212 // backup & restore state
213 var last_texture : c.GLint = undefined;
214 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
215 defer c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
216
217 // Upload texture to graphics system
218 c.glGenTextures(1, &g_FontTexture);
219 c.glBindTexture(c.GL_TEXTURE_2D, g_FontTexture);
220 c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR);
221 c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR);
222 if (@hasField(c, "GL_UNPACK_ROW_LENGTH"))
223 c.glPixelStorei(c.GL_UNPACK_ROW_LENGTH, 0);
224 c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_RGBA, width, height, 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, pixels);
225
226 // Store texture ID
227 io.*.Fonts.*.TexID = @intToPtr(c.ImTextureID, g_FontTexture);
203 const io = c.igGetIO();
204
205 // Get current font image data
206 var width: c_int = undefined;
207 var height: c_int = undefined;
208 var pixels: [*c]u8 = undefined;
209 c.ImFontAtlas_GetTexDataAsRGBA32(io.*.Fonts, &pixels, &width, &height, null);
210
211 // backup & restore state
212 var last_texture: c.GLint = undefined;
213 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
214 defer c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
215
216 // Upload texture to graphics system
217 c.glGenTextures(1, &g_FontTexture);
218 c.glBindTexture(c.GL_TEXTURE_2D, g_FontTexture);
219 c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR);
220 c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR);
221 if (@hasField(c, "GL_UNPACK_ROW_LENGTH"))
222 c.glPixelStorei(c.GL_UNPACK_ROW_LENGTH, 0);
223 c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_RGBA, width, height, 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, pixels);
224
225 // Store texture ID
226 io.*.Fonts.*.TexID = @intToPtr(c.ImTextureID, g_FontTexture);
228227 }
229228
230229 fn DestroyFontsTexture() void {
231 if (g_FontTexture == 0)
232 return;
233
234 const io = c.igGetIO();
235 c.glDeleteTextures(1, &g_FontTexture);
236 io.*.Fonts.*.TexID = @intToPtr(c.ImTextureID, 0);
237 g_FontTexture = 0;
238 }
239
240 pub fn RenderDrawData(draw_data : *c.ImDrawData) void {
241 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
242 const fb_width = @floatToInt(i32, draw_data.*.DisplaySize.x * draw_data.*.FramebufferScale.x);
243 const fb_height = @floatToInt(i32, draw_data.*.DisplaySize.y * draw_data.*.FramebufferScale.y);
244 if (fb_width <= 0 or fb_height <= 0)
245 return;
246
247 // Backup GL state
248 var last_program : c.GLint = undefined;
249 var last_texture : c.GLint = undefined;
250 var last_sampler : c.GLint = undefined;
251 var last_array_buffer : c.GLint = undefined;
252 var last_vertex_array_object : c.GLint = undefined;
253 var last_polygon_mode : [2]c.GLint = undefined;
254 var last_viewport : [4]c.GLint = undefined;
255 var last_scissor_box : [4]c.GLint = undefined;
256 var last_blend_src_rgb : c.GLint = undefined;
257 var last_blend_dst_rgb : c.GLint = undefined;
258 var last_blend_src_alpha : c.GLint = undefined;
259 var last_blend_dst_alpha : c.GLint = undefined;
260 var last_blend_equation_rgb : c.GLint = undefined;
261 var last_blend_equation_alpha : c.GLint = undefined;
262 var clip_origin_lower_left : bool = true;
263 var last_clip_origin : c.GLint = 0;
264 var last_active_texture : c.GLint = undefined;
265
266 c.glGetIntegerv(c.GL_ACTIVE_TEXTURE, &last_active_texture);
267 c.glActiveTexture(c.GL_TEXTURE0);
268 c.glGetIntegerv(c.GL_CURRENT_PROGRAM, &last_program);
269 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
270 if (@hasField(c, "GL_SAMPLER_BINDING"))
271 c.glGetIntegerv(c.GL_SAMPLER_BINDING, &last_sampler);
272 c.glGetIntegerv(c.GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
273 if (!@hasField(c, "IMGUI_IMPL_OPENc.GL_ES2"))
274 c.glGetIntegerv(c.GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object);
275 if (@hasField(c, "GL_POLYGON_MODE"))
276 c.glGetIntegerv(c.GL_POLYGON_MODE, last_polygon_mode);
277 c.glGetIntegerv(c.GL_VIEWPORT, &last_viewport[0]);
278 c.glGetIntegerv(c.GL_SCISSOR_BOX, &last_scissor_box[0]);
279 c.glGetIntegerv(c.GL_BLEND_SRC_RGB, &last_blend_src_rgb);
280 c.glGetIntegerv(c.GL_BLEND_DST_RGB, &last_blend_dst_rgb);
281 c.glGetIntegerv(c.GL_BLEND_SRC_ALPHA, &last_blend_src_alpha);
282 c.glGetIntegerv(c.GL_BLEND_DST_ALPHA, &last_blend_dst_alpha);
283 c.glGetIntegerv(c.GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
284 c.glGetIntegerv(c.GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
285 var last_enable_blend : c.GLboolean = c.glIsEnabled(c.GL_BLEND);
286 var last_enable_cull_face : c.GLboolean = c.glIsEnabled(c.GL_CULL_FACE);
287 var last_enable_depth_test : c.GLboolean = c.glIsEnabled(c.GL_DEPTH_TEST);
288 var last_enable_scissor_test : c.GLboolean = c.glIsEnabled(c.GL_SCISSOR_TEST);
289 if (@hasField(c, "GL_CLIP_ORIGIN") and builtin.os != builtin.Os.osx) {
290 // Support for GL 4.5's glClipControl(GL_UPPER_LEFT)
291 c.glGetIntegerv(c.GL_CLIP_ORIGIN, &last_clip_origin);
292 if (last_clip_origin == c.GL_UPPER_LEFT)
293 clip_origin_lower_left = false;
294 }
295
296 defer {
297 // Restore modified GL state
298 c.glUseProgram(@intCast(c.GLuint, last_program));
299 c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
230 if (g_FontTexture == 0)
231 return;
232
233 const io = c.igGetIO();
234 c.glDeleteTextures(1, &g_FontTexture);
235 io.*.Fonts.*.TexID = @intToPtr(c.ImTextureID, 0);
236 g_FontTexture = 0;
237 }
238
239 pub fn RenderDrawData(draw_data: *c.ImDrawData) void {
240 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
241 const fb_width = @floatToInt(i32, draw_data.*.DisplaySize.x * draw_data.*.FramebufferScale.x);
242 const fb_height = @floatToInt(i32, draw_data.*.DisplaySize.y * draw_data.*.FramebufferScale.y);
243 if (fb_width <= 0 or fb_height <= 0)
244 return;
245
246 // Backup GL state
247 var last_program: c.GLint = undefined;
248 var last_texture: c.GLint = undefined;
249 var last_sampler: c.GLint = undefined;
250 var last_array_buffer: c.GLint = undefined;
251 var last_vertex_array_object: c.GLint = undefined;
252 var last_polygon_mode: [2]c.GLint = undefined;
253 var last_viewport: [4]c.GLint = undefined;
254 var last_scissor_box: [4]c.GLint = undefined;
255 var last_blend_src_rgb: c.GLint = undefined;
256 var last_blend_dst_rgb: c.GLint = undefined;
257 var last_blend_src_alpha: c.GLint = undefined;
258 var last_blend_dst_alpha: c.GLint = undefined;
259 var last_blend_equation_rgb: c.GLint = undefined;
260 var last_blend_equation_alpha: c.GLint = undefined;
261 var clip_origin_lower_left: bool = true;
262 var last_clip_origin: c.GLint = 0;
263 var last_active_texture: c.GLint = undefined;
264
265 c.glGetIntegerv(c.GL_ACTIVE_TEXTURE, &last_active_texture);
266 c.glActiveTexture(c.GL_TEXTURE0);
267 c.glGetIntegerv(c.GL_CURRENT_PROGRAM, &last_program);
268 c.glGetIntegerv(c.GL_TEXTURE_BINDING_2D, &last_texture);
300269 if (@hasField(c, "GL_SAMPLER_BINDING"))
301 c.glBindSampler(0, @intCast(c.GLuint, last_sampler));
302 c.glActiveTexture(@intCast(c.GLuint, last_active_texture));
270 c.glGetIntegerv(c.GL_SAMPLER_BINDING, &last_sampler);
271 c.glGetIntegerv(c.GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
272 if (!@hasField(c, "IMGUI_IMPL_OPENc.GL_ES2"))
273 c.glGetIntegerv(c.GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object);
274 if (@hasField(c, "GL_POLYGON_MODE"))
275 c.glGetIntegerv(c.GL_POLYGON_MODE, last_polygon_mode);
276 c.glGetIntegerv(c.GL_VIEWPORT, &last_viewport[0]);
277 c.glGetIntegerv(c.GL_SCISSOR_BOX, &last_scissor_box[0]);
278 c.glGetIntegerv(c.GL_BLEND_SRC_RGB, &last_blend_src_rgb);
279 c.glGetIntegerv(c.GL_BLEND_DST_RGB, &last_blend_dst_rgb);
280 c.glGetIntegerv(c.GL_BLEND_SRC_ALPHA, &last_blend_src_alpha);
281 c.glGetIntegerv(c.GL_BLEND_DST_ALPHA, &last_blend_dst_alpha);
282 c.glGetIntegerv(c.GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
283 c.glGetIntegerv(c.GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
284 var last_enable_blend: c.GLboolean = c.glIsEnabled(c.GL_BLEND);
285 var last_enable_cull_face: c.GLboolean = c.glIsEnabled(c.GL_CULL_FACE);
286 var last_enable_depth_test: c.GLboolean = c.glIsEnabled(c.GL_DEPTH_TEST);
287 var last_enable_scissor_test: c.GLboolean = c.glIsEnabled(c.GL_SCISSOR_TEST);
288 if (@hasField(c, "GL_CLIP_ORIGIN") and builtin.os != builtin.Os.osx) {
289 // Support for GL 4.5's glClipControl(GL_UPPER_LEFT)
290 c.glGetIntegerv(c.GL_CLIP_ORIGIN, &last_clip_origin);
291 if (last_clip_origin == c.GL_UPPER_LEFT)
292 clip_origin_lower_left = false;
293 }
294
295 defer {
296 // Restore modified GL state
297 c.glUseProgram(@intCast(c.GLuint, last_program));
298 c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, last_texture));
299 if (@hasField(c, "GL_SAMPLER_BINDING"))
300 c.glBindSampler(0, @intCast(c.GLuint, last_sampler));
301 c.glActiveTexture(@intCast(c.GLuint, last_active_texture));
302 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
303 c.glBindVertexArray(@intCast(c.GLuint, last_vertex_array_object));
304 c.glBindBuffer(c.GL_ARRAY_BUFFER, @intCast(c.GLuint, last_array_buffer));
305 c.glBlendEquationSeparate(@intCast(c.GLuint, last_blend_equation_rgb), @intCast(c.GLuint, last_blend_equation_alpha));
306 c.glBlendFuncSeparate(@intCast(c.GLuint, last_blend_src_rgb), @intCast(c.GLuint, last_blend_dst_rgb), @intCast(c.GLuint, last_blend_src_alpha), @intCast(c.GLuint, last_blend_dst_alpha));
307 if (last_enable_blend == c.GL_TRUE) {
308 c.glEnable(c.GL_BLEND);
309 } else {
310 c.glDisable(c.GL_BLEND);
311 }
312 if (last_enable_cull_face == c.GL_TRUE) {
313 c.glEnable(c.GL_CULL_FACE);
314 } else {
315 c.glDisable(c.GL_CULL_FACE);
316 }
317 if (last_enable_depth_test == c.GL_TRUE) {
318 c.glEnable(c.GL_DEPTH_TEST);
319 } else {
320 c.glDisable(c.GL_DEPTH_TEST);
321 }
322 if (last_enable_scissor_test == c.GL_TRUE) {
323 c.glEnable(c.GL_SCISSOR_TEST);
324 } else {
325 c.glDisable(c.GL_SCISSOR_TEST);
326 }
327 if (@hasField(c, "GL_POLYGON_MODE"))
328 c.glPolygonMode(c.GL_FRONT_AND_BACK, @intCast(c.GLenum, last_polygon_mode[0]));
329 c.glViewport(last_viewport[0], last_viewport[1], @intCast(c.GLsizei, last_viewport[2]), @intCast(c.GLsizei, last_viewport[3]));
330 c.glScissor(last_scissor_box[0], last_scissor_box[1], @intCast(c.GLsizei, last_scissor_box[2]), @intCast(c.GLsizei, last_scissor_box[3]));
331 }
332
333 // Setup desired GL state
334 // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
335 // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
336 var vertex_array_object: c.GLuint = 0;
303337 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
304 c.glBindVertexArray(@intCast(c.GLuint, last_vertex_array_object));
305 c.glBindBuffer(c.GL_ARRAY_BUFFER, @intCast(c.GLuint, last_array_buffer));
306 c.glBlendEquationSeparate(@intCast(c.GLuint, last_blend_equation_rgb), @intCast(c.GLuint, last_blend_equation_alpha));
307 c.glBlendFuncSeparate(@intCast(c.GLuint, last_blend_src_rgb),
308 @intCast(c.GLuint, last_blend_dst_rgb),
309 @intCast(c.GLuint, last_blend_src_alpha),
310 @intCast(c.GLuint, last_blend_dst_alpha));
311 if (last_enable_blend == c.GL_TRUE) { c.glEnable(c.GL_BLEND); }
312 else { c.glDisable(c.GL_BLEND); }
313 if (last_enable_cull_face == c.GL_TRUE) { c.glEnable(c.GL_CULL_FACE); }
314 else { c.glDisable(c.GL_CULL_FACE); }
315 if (last_enable_depth_test == c.GL_TRUE) { c.glEnable(c.GL_DEPTH_TEST); }
316 else { c.glDisable(c.GL_DEPTH_TEST); }
317 if (last_enable_scissor_test == c.GL_TRUE) { c.glEnable(c.GL_SCISSOR_TEST); }
318 else { c.glDisable(c.GL_SCISSOR_TEST); }
338 c.glGenVertexArrays(1, &vertex_array_object);
339 defer if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
340 c.glDeleteVertexArrays(1, &vertex_array_object);
341
342 SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
343
344 // Will project scissor/clipping rectangles into framebuffer space
345 const clip_off = draw_data.*.DisplayPos; // (0,0) unless using multi-viewports
346 const clip_scale = draw_data.*.FramebufferScale; // (1,1) unless using retina display which are often (2,2)
347
348 // Render command lists
349 var n: usize = 0;
350 while (n < @intCast(usize, draw_data.*.CmdListsCount)) : (n += 1) {
351 const cmd_list = draw_data.*.CmdLists[n];
352
353 // Upload vertex/index buffers
354 c.glBufferData(c.GL_ARRAY_BUFFER, cmd_list.*.VtxBuffer.Size * @sizeOf(c.ImDrawVert), @ptrCast(?*c.GLvoid, cmd_list.*.VtxBuffer.Data), c.GL_STREAM_DRAW);
355 c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, cmd_list.*.IdxBuffer.Size * @sizeOf(c.ImDrawIdx), @ptrCast(*c.GLvoid, cmd_list.*.IdxBuffer.Data), c.GL_STREAM_DRAW);
356
357 var cmd_i: usize = 0;
358 while (cmd_i < @intCast(usize, cmd_list.*.CmdBuffer.Size)) : (cmd_i += 1) {
359 const pcmd = &cmd_list.*.CmdBuffer.Data[cmd_i];
360
361 if (pcmd.*.UserCallback != null) {
362 // User callback, registered via ImDrawList::AddCallback()
363 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
364 const ImDrawCallback_ResetRenderState = @intToPtr(c.ImDrawCallback, math.maxInt(usize));
365 if (pcmd.*.UserCallback == ImDrawCallback_ResetRenderState) {
366 SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
367 } else {
368 if (pcmd.*.UserCallback) |callback| {
369 callback(cmd_list, pcmd);
370 } else {
371 unreachable;
372 }
373 }
374 } else {
375 // Project scissor/clipping rectangles into framebuffer space
376 var clip_rect: c.ImVec4 = undefined;
377 clip_rect.x = (pcmd.*.ClipRect.x - clip_off.x) * clip_scale.x;
378 clip_rect.y = (pcmd.*.ClipRect.y - clip_off.y) * clip_scale.y;
379 clip_rect.z = (pcmd.*.ClipRect.z - clip_off.x) * clip_scale.x;
380 clip_rect.w = (pcmd.*.ClipRect.w - clip_off.y) * clip_scale.y;
381
382 if (clip_rect.x < @intToFloat(f32, fb_width) and clip_rect.y < @intToFloat(f32, fb_height) and clip_rect.z >= 0.0 and clip_rect.w >= 0.0) {
383 // Apply scissor/clipping rectangle
384 if (clip_origin_lower_left) {
385 c.glScissor(@floatToInt(c.GLint, clip_rect.x), fb_height - @floatToInt(c.GLint, clip_rect.w), @floatToInt(c.GLint, clip_rect.z - clip_rect.x), @floatToInt(c.GLint, clip_rect.w - clip_rect.y));
386 } else {
387 // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
388 c.glScissor(@floatToInt(c.GLint, clip_rect.x), @floatToInt(c.GLint, clip_rect.y), @floatToInt(c.GLint, clip_rect.z), @floatToInt(c.GLint, clip_rect.w));
389 }
390
391 // Bind texture, Draw
392 c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, @ptrToInt(pcmd.*.TextureId)));
393 const drawIndexSize = @sizeOf(c.ImDrawIdx);
394 const drawIndexType = if (drawIndexSize == 2) c.GL_UNSIGNED_SHORT else c.GL_UNSIGNED_INT;
395 const offset = @intToPtr(?*c.GLvoid, pcmd.*.IdxOffset * drawIndexSize);
396 if (@hasField(c, "IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX")) {
397 c.glDrawElementsBaseVertex(c.GL_TRIANGLES, @intCast(c.GLsizei, pcmd.*.ElemCount), drawIndexType, offset, @intCast(c.GLint, pcmd.*.VtxOffset));
398 } else {
399 c.glDrawElements(c.GL_TRIANGLES, @intCast(c.GLsizei, pcmd.*.ElemCount), drawIndexType, offset);
400 }
401 }
402 }
403 }
404 }
405 }
406
407 fn SetupRenderState(draw_data: *c.ImDrawData, fb_width: i32, fb_height: i32, vertex_array_object: c.GLuint) void {
408 // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
409 c.glEnable(c.GL_BLEND);
410 c.glBlendEquation(c.GL_FUNC_ADD);
411 c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA);
412 c.glDisable(c.GL_CULL_FACE);
413 c.glDisable(c.GL_DEPTH_TEST);
414 c.glEnable(c.GL_SCISSOR_TEST);
319415 if (@hasField(c, "GL_POLYGON_MODE"))
320 c.glPolygonMode(c.GL_FRONT_AND_BACK, @intCast(c.GLenum, last_polygon_mode[0]));
321 c.glViewport(last_viewport[0], last_viewport[1], @intCast(c.GLsizei, last_viewport[2]), @intCast(c.GLsizei, last_viewport[3]));
322 c.glScissor(last_scissor_box[0], last_scissor_box[1], @intCast(c.GLsizei, last_scissor_box[2]), @intCast(c.GLsizei, last_scissor_box[3]));
323 }
324
325 // Setup desired GL state
326 // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
327 // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
328 var vertex_array_object : c.GLuint = 0;
329 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
330 c.glGenVertexArrays(1, &vertex_array_object);
331 defer if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
332 c.glDeleteVertexArrays(1, &vertex_array_object);
333
334 SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
335
336 // Will project scissor/clipping rectangles into framebuffer space
337 const clip_off = draw_data.*.DisplayPos; // (0,0) unless using multi-viewports
338 const clip_scale = draw_data.*.FramebufferScale; // (1,1) unless using retina display which are often (2,2)
339
340 // Render command lists
341 var n : usize = 0;
342 while (n < @intCast(usize, draw_data.*.CmdListsCount)) : (n += 1) {
343 const cmd_list = draw_data.*.CmdLists[n];
344
345 // Upload vertex/index buffers
346 c.glBufferData(c.GL_ARRAY_BUFFER, cmd_list.*.VtxBuffer.Size * @sizeOf(c.ImDrawVert), @ptrCast(?*c.GLvoid, cmd_list.*.VtxBuffer.Data), c.GL_STREAM_DRAW);
347 c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, cmd_list.*.IdxBuffer.Size * @sizeOf(c.ImDrawIdx), @ptrCast(*c.GLvoid, cmd_list.*.IdxBuffer.Data), c.GL_STREAM_DRAW);
348
349 var cmd_i : usize = 0;
350 while (cmd_i < @intCast(usize, cmd_list.*.CmdBuffer.Size)) : (cmd_i += 1) {
351 const pcmd = &cmd_list.*.CmdBuffer.Data[cmd_i];
352
353 if (pcmd.*.UserCallback != null) {
354 // User callback, registered via ImDrawList::AddCallback()
355 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
356 const ImDrawCallback_ResetRenderState = @intToPtr(c.ImDrawCallback, math.maxInt(usize));
357 if (pcmd.*.UserCallback == ImDrawCallback_ResetRenderState) {
358 SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
359 } else {
360 if (pcmd.*.UserCallback) |callback| {
361 callback(cmd_list, pcmd);
362 } else {
363 unreachable;
364 }
365 }
366 } else {
367 // Project scissor/clipping rectangles into framebuffer space
368 var clip_rect : c.ImVec4 = undefined;
369 clip_rect.x = (pcmd.*.ClipRect.x - clip_off.x) * clip_scale.x;
370 clip_rect.y = (pcmd.*.ClipRect.y - clip_off.y) * clip_scale.y;
371 clip_rect.z = (pcmd.*.ClipRect.z - clip_off.x) * clip_scale.x;
372 clip_rect.w = (pcmd.*.ClipRect.w - clip_off.y) * clip_scale.y;
373
374 if (clip_rect.x < @intToFloat(f32, fb_width) and clip_rect.y < @intToFloat(f32, fb_height)
375 and clip_rect.z >= 0.0 and clip_rect.w >= 0.0) {
376 // Apply scissor/clipping rectangle
377 if (clip_origin_lower_left) {
378 c.glScissor(@floatToInt(c.GLint, clip_rect.x), fb_height - @floatToInt(c.GLint, clip_rect.w),
379 @floatToInt(c.GLint, clip_rect.z - clip_rect.x), @floatToInt(c.GLint, clip_rect.w - clip_rect.y));
380 } else {
381 // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
382 c.glScissor(@floatToInt(c.GLint, clip_rect.x), @floatToInt(c.GLint, clip_rect.y),
383 @floatToInt(c.GLint, clip_rect.z), @floatToInt(c.GLint, clip_rect.w));
384 }
385
386 // Bind texture, Draw
387 c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, @ptrToInt(pcmd.*.TextureId)));
388 const drawIndexSize = @sizeOf(c.ImDrawIdx);
389 const drawIndexType = if (drawIndexSize == 2) c.GL_UNSIGNED_SHORT else c.GL_UNSIGNED_INT;
390 const offset = @intToPtr(?*c.GLvoid, pcmd.*.IdxOffset * drawIndexSize);
391 if (@hasField(c, "IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX")) {
392 c.glDrawElementsBaseVertex(c.GL_TRIANGLES, @intCast(c.GLsizei, pcmd.*.ElemCount), drawIndexType, offset, @intCast(c.GLint, pcmd.*.VtxOffset));
393 } else {
394 c.glDrawElements(c.GL_TRIANGLES, @intCast(c.GLsizei, pcmd.*.ElemCount), drawIndexType, offset);
395 }
396 }
397 }
398 }
399 }
400 }
401
402 fn SetupRenderState(draw_data: *c.ImDrawData, fb_width: i32, fb_height: i32, vertex_array_object: c.GLuint) void {
403 // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
404 c.glEnable(c.GL_BLEND);
405 c.glBlendEquation(c.GL_FUNC_ADD);
406 c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA);
407 c.glDisable(c.GL_CULL_FACE);
408 c.glDisable(c.GL_DEPTH_TEST);
409 c.glEnable(c.GL_SCISSOR_TEST);
410 if (@hasField(c, "GL_POLYGON_MODE"))
411 c.glPolygonMode(c.GL_FRONT_AND_BACK, c.GL_FILL);
412
413 // Setup viewport, orthographic projection matrix
414 // 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.
415 c.glViewport(0, 0, @intCast(c.GLsizei, fb_width), @intCast(c.GLsizei, fb_height));
416 const L = draw_data.*.DisplayPos.x;
417 const R = draw_data.*.DisplayPos.x + draw_data.*.DisplaySize.x;
418 const T = draw_data.*.DisplayPos.y;
419 const B = draw_data.*.DisplayPos.y + draw_data.*.DisplaySize.y;
420 const ortho_projection = [4][4]f32{
421 [_]f32{ 2.0/(R-L), 0.0, 0.0, 0.0 },
422 [_]f32{ 0.0, 2.0/(T-B), 0.0, 0.0 },
423 [_]f32{ 0.0, 0.0, -1.0, 0.0 },
424 [_]f32{ (R+L)/(L-R), (T+B)/(B-T), 0.0, 1.0 },
425 };
426 c.glUseProgram(g_ShaderHandle);
427 c.glUniform1i(g_AttribLocationTex, 0);
428 c.glUniformMatrix4fv(g_AttribLocationProjMtx, 1, c.GL_FALSE, &ortho_projection[0][0]);
429 if (@hasField(c, "GL_SAMPLER_BINDING"))
430 c.glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
431
432 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
433 c.glBindVertexArray(vertex_array_object);
434
435 // Bind vertex/index buffers and setup attributes for ImDrawVert
436 c.glBindBuffer(c.GL_ARRAY_BUFFER, g_VboHandle);
437 c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
438 c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxPos));
439 c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxUV));
440 c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxColor));
441 c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxPos), 2, c.GL_FLOAT, c.GL_FALSE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "pos")));
442 c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxUV), 2, c.GL_FLOAT, c.GL_FALSE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "uv")));
443 c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxColor), 4, c.GL_UNSIGNED_BYTE, c.GL_TRUE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "col")));
444 }
416 c.glPolygonMode(c.GL_FRONT_AND_BACK, c.GL_FILL);
417
418 // Setup viewport, orthographic projection matrix
419 // 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.
420 c.glViewport(0, 0, @intCast(c.GLsizei, fb_width), @intCast(c.GLsizei, fb_height));
421 const L = draw_data.*.DisplayPos.x;
422 const R = draw_data.*.DisplayPos.x + draw_data.*.DisplaySize.x;
423 const T = draw_data.*.DisplayPos.y;
424 const B = draw_data.*.DisplayPos.y + draw_data.*.DisplaySize.y;
425 const ortho_projection = [4][4]f32{
426 [_]f32{ 2.0 / (R - L), 0.0, 0.0, 0.0 },
427 [_]f32{ 0.0, 2.0 / (T - B), 0.0, 0.0 },
428 [_]f32{ 0.0, 0.0, -1.0, 0.0 },
429 [_]f32{ (R + L) / (L - R), (T + B) / (B - T), 0.0, 1.0 },
430 };
431 c.glUseProgram(g_ShaderHandle);
432 c.glUniform1i(g_AttribLocationTex, 0);
433 c.glUniformMatrix4fv(g_AttribLocationProjMtx, 1, c.GL_FALSE, &ortho_projection[0][0]);
434 if (@hasField(c, "GL_SAMPLER_BINDING"))
435 c.glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
436
437 if (!@hasField(c, "IMGUI_IMPL_OPENGL_ES2"))
438 c.glBindVertexArray(vertex_array_object);
439
440 // Bind vertex/index buffers and setup attributes for ImDrawVert
441 c.glBindBuffer(c.GL_ARRAY_BUFFER, g_VboHandle);
442 c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
443 c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxPos));
444 c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxUV));
445 c.glEnableVertexAttribArray(@intCast(c.GLuint, g_AttribLocationVtxColor));
446 c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxPos), 2, c.GL_FLOAT, c.GL_FALSE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "pos")));
447 c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxUV), 2, c.GL_FLOAT, c.GL_FALSE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "uv")));
448 c.glVertexAttribPointer(@intCast(c.GLuint, g_AttribLocationVtxColor), 4, c.GL_UNSIGNED_BYTE, c.GL_TRUE, @sizeOf(c.ImDrawVert), @intToPtr(?*c.GLvoid, @byteOffsetOf(c.ImDrawVert, "col")));
449 }
1 /// this is a port of cimgui/imgui/examples/imgui_impl_glfw.cpp
12 const c = @import("c.zig");
23 const builtin = @import("builtin");
34 const debug = @import("std").debug;
45 const math = @import("std").math;
56
67 pub const ClientApi = enum {
7 Unknown,
8 OpenGL,
9 Vulkan,
8 Unknown,
9 OpenGL,
10 Vulkan,
1011 };
1112
1213 // Data
1314 var g_Window: ?*c.GLFWwindow = null;
1415 var g_ClientApi: ClientApi = .Unknown;
1516 var g_Time: f64 = 0.0;
16 var g_MouseJustPressed = [_]bool{ false } ** 5;
17 var g_MouseCursors = [_]?*c.GLFWcursor{ null } ** @enumToInt(c.ImGuiMouseCursor_COUNT);
17 var g_MouseJustPressed = [_]bool{false} ** 5;
18 var g_MouseCursors = [_]?*c.GLFWcursor{null} ** @enumToInt(c.ImGuiMouseCursor_COUNT);
1819 var g_WantUpdateMonitors = true;
1920
2021 // Chain GLFW callbacks for main viewport:
2526 var g_PrevUserCallbackChar: c.GLFWcharfun = null;
2627
2728 pub fn Init(window: *c.GLFWwindow, install_callbacks: bool, client_api: ClientApi) void {
28 g_Window = window;
29 g_Time = 0.0;
30
31 // Setup back-end capabilities flags
32 const io = c.igGetIO();
33 io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_HasMouseCursors); // We can honor GetMouseCursor() values (optional)
34 io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_HasSetMousePos); // We can honor io.WantSetMousePos requests (optional, rarely used)
35 if (false) io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_PlatformHasViewports); // We can create multi-viewports on the Platform side (optional)
36 if (false and @hasField(c, "GLFW_HAS_GLFW_HOVERED") and builtin.os == builtin.Os.windows) {
37 io.*.BackendFlags |= @enumToInt(ImGuiBackendFlags_HasMouseHoveredViewport); // We can set io.MouseHoveredViewport correctly (optional, not easy)
38 }
39 io.*.BackendPlatformName = c"imgui_impl_glfw.zig";
40
41 // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
42 io.*.KeyMap[@enumToInt(c.ImGuiKey_Tab)] = c.GLFW_KEY_TAB;
43 io.*.KeyMap[@enumToInt(c.ImGuiKey_LeftArrow)] = c.GLFW_KEY_LEFT;
44 io.*.KeyMap[@enumToInt(c.ImGuiKey_RightArrow)] = c.GLFW_KEY_RIGHT;
45 io.*.KeyMap[@enumToInt(c.ImGuiKey_UpArrow)] = c.GLFW_KEY_UP;
46 io.*.KeyMap[@enumToInt(c.ImGuiKey_DownArrow)] = c.GLFW_KEY_DOWN;
47 io.*.KeyMap[@enumToInt(c.ImGuiKey_PageUp)] = c.GLFW_KEY_PAGE_UP;
48 io.*.KeyMap[@enumToInt(c.ImGuiKey_PageDown)] = c.GLFW_KEY_PAGE_DOWN;
49 io.*.KeyMap[@enumToInt(c.ImGuiKey_Home)] = c.GLFW_KEY_HOME;
50 io.*.KeyMap[@enumToInt(c.ImGuiKey_End)] = c.GLFW_KEY_END;
51 io.*.KeyMap[@enumToInt(c.ImGuiKey_Insert)] = c.GLFW_KEY_INSERT;
52 io.*.KeyMap[@enumToInt(c.ImGuiKey_Delete)] = c.GLFW_KEY_DELETE;
53 io.*.KeyMap[@enumToInt(c.ImGuiKey_Backspace)] = c.GLFW_KEY_BACKSPACE;
54 io.*.KeyMap[@enumToInt(c.ImGuiKey_Space)] = c.GLFW_KEY_SPACE;
55 io.*.KeyMap[@enumToInt(c.ImGuiKey_Enter)] = c.GLFW_KEY_ENTER;
56 io.*.KeyMap[@enumToInt(c.ImGuiKey_Escape)] = c.GLFW_KEY_ESCAPE;
57 io.*.KeyMap[@enumToInt(c.ImGuiKey_KeyPadEnter)] = c.GLFW_KEY_KP_ENTER;
58 io.*.KeyMap[@enumToInt(c.ImGuiKey_A)] = c.GLFW_KEY_A;
59 io.*.KeyMap[@enumToInt(c.ImGuiKey_C)] = c.GLFW_KEY_C;
60 io.*.KeyMap[@enumToInt(c.ImGuiKey_V)] = c.GLFW_KEY_V;
61 io.*.KeyMap[@enumToInt(c.ImGuiKey_X)] = c.GLFW_KEY_X;
62 io.*.KeyMap[@enumToInt(c.ImGuiKey_Y)] = c.GLFW_KEY_Y;
63 io.*.KeyMap[@enumToInt(c.ImGuiKey_Z)] = c.GLFW_KEY_Z;
64
65 // @TODO: Clipboard
66 // io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
67 // io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
68 io.*.ClipboardUserData = g_Window;
69
70 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_Arrow)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR);
71 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_TextInput)] = c.glfwCreateStandardCursor(c.GLFW_IBEAM_CURSOR);
72 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeAll)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
73 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeNS)] = c.glfwCreateStandardCursor(c.GLFW_VRESIZE_CURSOR);
74 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeEW)] = c.glfwCreateStandardCursor(c.GLFW_HRESIZE_CURSOR);
75 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeNESW)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
76 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeNWSE)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
77 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_Hand)] = c.glfwCreateStandardCursor(c.GLFW_HAND_CURSOR);
78
79 // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
80 g_PrevUserCallbackMousebutton = null;
81 g_PrevUserCallbackScroll = null;
82 g_PrevUserCallbackKey = null;
83 g_PrevUserCallbackChar = null;
84 if (install_callbacks) {
85 g_PrevUserCallbackMousebutton = c.glfwSetMouseButtonCallback(window, Callback_MouseButton);
86 g_PrevUserCallbackScroll = c.glfwSetScrollCallback(window, Callback_Scroll);
87 g_PrevUserCallbackKey = c.glfwSetKeyCallback(window, Callback_Key);
88 g_PrevUserCallbackChar = c.glfwSetCharCallback(window, Callback_Char);
89 }
90
91 // Our mouse update function expect PlatformHandle to be filled for the main viewport
92 const main_viewport = c.igGetMainViewport();
93 main_viewport.*.PlatformHandle = g_Window;
94 if (builtin.os == builtin.Os.windows)
95 main_viewport.*.PlatformHandleRaw = c.glfwGetWin32Window(g_Window);
96
97 // @TODO: Platform Interface (Viewport)
98 if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0)
99 unreachable;
29 g_Window = window;
30 g_Time = 0.0;
31
32 // Setup back-end capabilities flags
33 const io = c.igGetIO();
34 io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_HasMouseCursors); // We can honor GetMouseCursor() values (optional)
35 io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_HasSetMousePos); // We can honor io.WantSetMousePos requests (optional, rarely used)
36 if (false) io.*.BackendFlags |= @enumToInt(c.ImGuiBackendFlags_PlatformHasViewports); // We can create multi-viewports on the Platform side (optional)
37 if (false and @hasField(c, "GLFW_HAS_GLFW_HOVERED") and builtin.os == builtin.Os.windows) {
38 io.*.BackendFlags |= @enumToInt(ImGuiBackendFlags_HasMouseHoveredViewport); // We can set io.MouseHoveredViewport correctly (optional, not easy)
39 }
40 io.*.BackendPlatformName = c"imgui_impl_glfw.zig";
41
42 // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
43 io.*.KeyMap[@enumToInt(c.ImGuiKey_Tab)] = c.GLFW_KEY_TAB;
44 io.*.KeyMap[@enumToInt(c.ImGuiKey_LeftArrow)] = c.GLFW_KEY_LEFT;
45 io.*.KeyMap[@enumToInt(c.ImGuiKey_RightArrow)] = c.GLFW_KEY_RIGHT;
46 io.*.KeyMap[@enumToInt(c.ImGuiKey_UpArrow)] = c.GLFW_KEY_UP;
47 io.*.KeyMap[@enumToInt(c.ImGuiKey_DownArrow)] = c.GLFW_KEY_DOWN;
48 io.*.KeyMap[@enumToInt(c.ImGuiKey_PageUp)] = c.GLFW_KEY_PAGE_UP;
49 io.*.KeyMap[@enumToInt(c.ImGuiKey_PageDown)] = c.GLFW_KEY_PAGE_DOWN;
50 io.*.KeyMap[@enumToInt(c.ImGuiKey_Home)] = c.GLFW_KEY_HOME;
51 io.*.KeyMap[@enumToInt(c.ImGuiKey_End)] = c.GLFW_KEY_END;
52 io.*.KeyMap[@enumToInt(c.ImGuiKey_Insert)] = c.GLFW_KEY_INSERT;
53 io.*.KeyMap[@enumToInt(c.ImGuiKey_Delete)] = c.GLFW_KEY_DELETE;
54 io.*.KeyMap[@enumToInt(c.ImGuiKey_Backspace)] = c.GLFW_KEY_BACKSPACE;
55 io.*.KeyMap[@enumToInt(c.ImGuiKey_Space)] = c.GLFW_KEY_SPACE;
56 io.*.KeyMap[@enumToInt(c.ImGuiKey_Enter)] = c.GLFW_KEY_ENTER;
57 io.*.KeyMap[@enumToInt(c.ImGuiKey_Escape)] = c.GLFW_KEY_ESCAPE;
58 io.*.KeyMap[@enumToInt(c.ImGuiKey_KeyPadEnter)] = c.GLFW_KEY_KP_ENTER;
59 io.*.KeyMap[@enumToInt(c.ImGuiKey_A)] = c.GLFW_KEY_A;
60 io.*.KeyMap[@enumToInt(c.ImGuiKey_C)] = c.GLFW_KEY_C;
61 io.*.KeyMap[@enumToInt(c.ImGuiKey_V)] = c.GLFW_KEY_V;
62 io.*.KeyMap[@enumToInt(c.ImGuiKey_X)] = c.GLFW_KEY_X;
63 io.*.KeyMap[@enumToInt(c.ImGuiKey_Y)] = c.GLFW_KEY_Y;
64 io.*.KeyMap[@enumToInt(c.ImGuiKey_Z)] = c.GLFW_KEY_Z;
65
66 // @TODO: Clipboard
67 // io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
68 // io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
69 io.*.ClipboardUserData = g_Window;
70
71 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_Arrow)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR);
72 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_TextInput)] = c.glfwCreateStandardCursor(c.GLFW_IBEAM_CURSOR);
73 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeAll)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
74 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeNS)] = c.glfwCreateStandardCursor(c.GLFW_VRESIZE_CURSOR);
75 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeEW)] = c.glfwCreateStandardCursor(c.GLFW_HRESIZE_CURSOR);
76 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeNESW)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
77 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_ResizeNWSE)] = c.glfwCreateStandardCursor(c.GLFW_ARROW_CURSOR); // FIXME: GLFW doesn't have this.
78 g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_Hand)] = c.glfwCreateStandardCursor(c.GLFW_HAND_CURSOR);
79
80 // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
81 g_PrevUserCallbackMousebutton = null;
82 g_PrevUserCallbackScroll = null;
83 g_PrevUserCallbackKey = null;
84 g_PrevUserCallbackChar = null;
85 if (install_callbacks) {
86 g_PrevUserCallbackMousebutton = c.glfwSetMouseButtonCallback(window, Callback_MouseButton);
87 g_PrevUserCallbackScroll = c.glfwSetScrollCallback(window, Callback_Scroll);
88 g_PrevUserCallbackKey = c.glfwSetKeyCallback(window, Callback_Key);
89 g_PrevUserCallbackChar = c.glfwSetCharCallback(window, Callback_Char);
90 }
91
92 // Our mouse update function expect PlatformHandle to be filled for the main viewport
93 const main_viewport = c.igGetMainViewport();
94 main_viewport.*.PlatformHandle = g_Window;
95 if (builtin.os == builtin.Os.windows)
96 main_viewport.*.PlatformHandleRaw = c.glfwGetWin32Window(g_Window);
97
98 // @TODO: Platform Interface (Viewport)
99 if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0)
100 unreachable;
100101 // ImGui_ImplGlfw_InitPlatformInterface();
101102
102 g_ClientApi = client_api;
103 g_ClientApi = client_api;
103104 }
104105
105106 pub fn Shutdown() void {
106 // @TODO: Platform Interface (Viewport)
107 // ImGui_ImplGlfw_ShutdownPlatformInterface();
108
109 for (g_MouseCursors) |*cursor| {
110 c.glfwDestroyCursor(cursor.*);
111 cursor.* = null;
112 }
113 g_ClientApi = .Unknown;
107 // @TODO: Platform Interface (Viewport)
108 // ImGui_ImplGlfw_ShutdownPlatformInterface();
109 for (g_MouseCursors) |*cursor| {
110 c.glfwDestroyCursor(cursor.*);
111 cursor.* = null;
112 }
113 g_ClientApi = .Unknown;
114114 }
115115
116116 pub fn NewFrame() void {
117 const io = c.igGetIO();
118 debug.assert(c.ImFontAtlas_IsBuilt(io.*.Fonts));
119
120 var w : c_int = undefined;
121 var h : c_int = undefined;
122 var display_w : c_int = undefined;
123 var display_h : c_int = undefined;
124 c.glfwGetWindowSize(g_Window, &w, &h);
125 c.glfwGetFramebufferSize(g_Window, &display_w, &display_h);
126 io.*.DisplaySize = c.ImVec2{ .x = @intToFloat(f32, w), .y = @intToFloat(f32, h) };
127
128 if (w > 0 and h > 0)
129 io.*.DisplayFramebufferScale = c.ImVec2{
130 .x = @intToFloat(f32, display_w) / @intToFloat(f32, w),
131 .y = @intToFloat(f32, display_h) / @intToFloat(f32, h),
132 };
133 if (g_WantUpdateMonitors)
134 UpdateMonitors();
135
136 // Setup time step
137 const current_time = c.glfwGetTime();
138 io.*.DeltaTime = if (g_Time > 0.0) @floatCast(f32, current_time - g_Time) else 1.0 / 60.0;
139 g_Time = current_time;
140
141 UpdateMousePosAndButtons();
142 UpdateMouseCursor();
143
144 UpdateGamepads();
117 const io = c.igGetIO();
118 debug.assert(c.ImFontAtlas_IsBuilt(io.*.Fonts));
119
120 var w: c_int = undefined;
121 var h: c_int = undefined;
122 var display_w: c_int = undefined;
123 var display_h: c_int = undefined;
124 c.glfwGetWindowSize(g_Window, &w, &h);
125 c.glfwGetFramebufferSize(g_Window, &display_w, &display_h);
126 io.*.DisplaySize = c.ImVec2{ .x = @intToFloat(f32, w), .y = @intToFloat(f32, h) };
127
128 if (w > 0 and h > 0)
129 io.*.DisplayFramebufferScale = c.ImVec2{
130 .x = @intToFloat(f32, display_w) / @intToFloat(f32, w),
131 .y = @intToFloat(f32, display_h) / @intToFloat(f32, h),
132 };
133 if (g_WantUpdateMonitors)
134 UpdateMonitors();
135
136 // Setup time step
137 const current_time = c.glfwGetTime();
138 io.*.DeltaTime = if (g_Time > 0.0) @floatCast(f32, current_time - g_Time) else 1.0 / 60.0;
139 g_Time = current_time;
140
141 UpdateMousePosAndButtons();
142 UpdateMouseCursor();
143
144 UpdateGamepads();
145145 }
146146
147147 fn UpdateMonitors() void {
148 const platform_io = c.igGetPlatformIO();
149 var monitors_count : c_int = 0;
150 const glfw_monitors = c.glfwGetMonitors(&monitors_count)[0..@intCast(usize, monitors_count)];
151
152 c.ImVector_ImGuiPlatformMonitor_Resize(&platform_io.*.Monitors, monitors_count);
153 for (glfw_monitors) |glfw_monitor, n| {
154 var monitor = &platform_io.*.Monitors.Data[n];
155 var x : c_int = undefined;
156 var y : c_int = undefined;
157 c.glfwGetMonitorPos(glfw_monitor, &x, &y);
158 const vid_mode = c.glfwGetVideoMode(glfw_monitor); // glfw_monitors[n]);
159
160 monitor.*.MainPos = c.ImVec2{ .x = @intToFloat(f32, x), .y = @intToFloat(f32, y) };
161 monitor.*.MainSize = c.ImVec2{
162 .x = @intToFloat(f32, vid_mode.*.width),
163 .y = @intToFloat(f32, vid_mode.*.height),
164 };
165 if (false and c.GLFW_HAS_MONITOR_WORK_AREA) {
166 var w : c_int = undefined;
167 var h : c_int = undefined;
168 c.glfwGetMonitorWorkarea(glfw_monitor, &x, &y, &w, &h);
169 monitor.*.WorkPos = ImVec2{ .x = @intToFloat(f32, x), .y = @intToFloat(f32, y) };
170 monitor.*.WorkSize = ImVec2{ .x = @intToFloat(f32, w), .y = @intToFloat(f32, h) };
171 }
172 if (false and c.GLFW_HAS_PER_MONITOR_DPI) {
173 // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings,
174 // which generally needs to be set in the manifest or at runtime.
175 var x_scale : f32 = undefined;
176 var y_scale : f32 = undefined;
177 c.glfwGetMonitorContentScale(glfw_monitor, &x_scale, &y_scale);
178 monitor.*.DpiScale = x_scale;
179 }
180 }
181 g_WantUpdateMonitors = false;
148 const platform_io = c.igGetPlatformIO();
149 var monitors_count: c_int = 0;
150 const glfw_monitors = c.glfwGetMonitors(&monitors_count)[0..@intCast(usize, monitors_count)];
151
152 c.ImVector_ImGuiPlatformMonitor_Resize(&platform_io.*.Monitors, monitors_count);
153 for (glfw_monitors) |glfw_monitor, n| {
154 var monitor = &platform_io.*.Monitors.Data[n];
155 var x: c_int = undefined;
156 var y: c_int = undefined;
157 c.glfwGetMonitorPos(glfw_monitor, &x, &y);
158 const vid_mode = c.glfwGetVideoMode(glfw_monitor); // glfw_monitors[n]);
159
160 monitor.*.MainPos = c.ImVec2{ .x = @intToFloat(f32, x), .y = @intToFloat(f32, y) };
161 monitor.*.MainSize = c.ImVec2{
162 .x = @intToFloat(f32, vid_mode.*.width),
163 .y = @intToFloat(f32, vid_mode.*.height),
164 };
165 if (false and c.GLFW_HAS_MONITOR_WORK_AREA) {
166 var w: c_int = undefined;
167 var h: c_int = undefined;
168 c.glfwGetMonitorWorkarea(glfw_monitor, &x, &y, &w, &h);
169 monitor.*.WorkPos = ImVec2{ .x = @intToFloat(f32, x), .y = @intToFloat(f32, y) };
170 monitor.*.WorkSize = ImVec2{ .x = @intToFloat(f32, w), .y = @intToFloat(f32, h) };
171 }
172 if (false and c.GLFW_HAS_PER_MONITOR_DPI) {
173 // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings,
174 // which generally needs to be set in the manifest or at runtime.
175 var x_scale: f32 = undefined;
176 var y_scale: f32 = undefined;
177 c.glfwGetMonitorContentScale(glfw_monitor, &x_scale, &y_scale);
178 monitor.*.DpiScale = x_scale;
179 }
180 }
181 g_WantUpdateMonitors = false;
182182 }
183183
184184 fn UpdateMousePosAndButtons() void {
185 // Update buttons
186 const io = c.igGetIO();
187 for (io.*.MouseDown) |*isDown, i| {
188 // 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.
189 isDown.* = g_MouseJustPressed[i] or c.glfwGetMouseButton(g_Window, @intCast(c_int, i)) != 0;
190 g_MouseJustPressed[i] = false;
191 }
192
193 // Update mouse position
194 const mouse_pos_backup = io.*.MousePos;
195 io.*.MousePos = c.ImVec2{ .x = math.f32_min, .y = math.f32_min };
196 io.*.MouseHoveredViewport = 0;
197 const platform_io = c.igGetPlatformIO();
198 var n : usize = 0;
199 while (n < @intCast(usize, platform_io.*.Viewports.Size)) : (n += 1) {
200 const viewport = platform_io.*.Viewports.Data[n];
201 const window = @ptrCast(*c.GLFWwindow, viewport.*.PlatformHandle);
202 const focused = c.glfwGetWindowAttrib(window, c.GLFW_FOCUSED) != 0;
203 if (focused) {
204 if (io.*.WantSetMousePos) {
205 c.glfwSetCursorPos(window, mouse_pos_backup.x - viewport.*.Pos.x, mouse_pos_backup.y - viewport.*.Pos.y);
206 } else {
207 var mouse_x : f64 = undefined;
208 var mouse_y : f64 = undefined;
209 c.glfwGetCursorPos(window, &mouse_x, &mouse_y);
210 if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0) {
211 // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
212 var window_x : c_int = undefined;
213 var window_y : c_int = undefined;
214 c.glfwGetWindowPos(window, &window_x, &window_y);
215 io.*.MousePos = c.ImVec2{
216 .x = @floatCast(f32, mouse_x) + @intToFloat(f32, window_x),
217 .y = @floatCast(f32, mouse_y) + @intToFloat(f32, window_y),
218 };
185 // Update buttons
186 const io = c.igGetIO();
187 for (io.*.MouseDown) |*isDown, i| {
188 // 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.
189 isDown.* = g_MouseJustPressed[i] or c.glfwGetMouseButton(g_Window, @intCast(c_int, i)) != 0;
190 g_MouseJustPressed[i] = false;
191 }
192
193 // Update mouse position
194 const mouse_pos_backup = io.*.MousePos;
195 io.*.MousePos = c.ImVec2{ .x = math.f32_min, .y = math.f32_min };
196 io.*.MouseHoveredViewport = 0;
197 const platform_io = c.igGetPlatformIO();
198 var n: usize = 0;
199 while (n < @intCast(usize, platform_io.*.Viewports.Size)) : (n += 1) {
200 const viewport = platform_io.*.Viewports.Data[n];
201 const window = @ptrCast(*c.GLFWwindow, viewport.*.PlatformHandle);
202 const focused = c.glfwGetWindowAttrib(window, c.GLFW_FOCUSED) != 0;
203 if (focused) {
204 if (io.*.WantSetMousePos) {
205 c.glfwSetCursorPos(window, mouse_pos_backup.x - viewport.*.Pos.x, mouse_pos_backup.y - viewport.*.Pos.y);
206 } else {
207 var mouse_x: f64 = undefined;
208 var mouse_y: f64 = undefined;
209 c.glfwGetCursorPos(window, &mouse_x, &mouse_y);
210 if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0) {
211 // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
212 var window_x: c_int = undefined;
213 var window_y: c_int = undefined;
214 c.glfwGetWindowPos(window, &window_x, &window_y);
215 io.*.MousePos = c.ImVec2{
216 .x = @floatCast(f32, mouse_x) + @intToFloat(f32, window_x),
217 .y = @floatCast(f32, mouse_y) + @intToFloat(f32, window_y),
218 };
219 } else {
220 // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
221 io.*.MousePos = c.ImVec2{ .x = @floatCast(f32, mouse_x), .y = @floatCast(f32, mouse_y) };
222 }
223 }
224
225 for (io.*.MouseDown) |*isDown, i|
226 isDown.* = isDown.* or c.glfwGetMouseButton(window, @intCast(c_int, i)) != 0;
227 }
228 }
229 }
230
231 fn UpdateMouseCursor() void {
232 const io = c.igGetIO();
233 if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_NoMouseCursorChange) != 0 or c.glfwGetInputMode(g_Window, c.GLFW_CURSOR) == c.GLFW_CURSOR_DISABLED)
234 return;
235
236 const imgui_cursor = c.igGetMouseCursor();
237 const platform_io = c.igGetPlatformIO();
238 var n: usize = 0;
239 while (n < @intCast(usize, platform_io.*.Viewports.Size)) : (n += 1) {
240 const window = @ptrCast(*c.GLFWwindow, platform_io.*.Viewports.Data[n].*.PlatformHandle);
241 if (imgui_cursor == @enumToInt(c.ImGuiMouseCursor_None) or io.*.MouseDrawCursor) {
242 // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
243 c.glfwSetInputMode(window, c.GLFW_CURSOR, c.GLFW_CURSOR_HIDDEN);
219244 } else {
220 // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
221 io.*.MousePos = c.ImVec2{ .x = @floatCast(f32, mouse_x), .y = @floatCast(f32, mouse_y) };
245 // Show OS mouse cursor
246 // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
247 c.glfwSetCursor(window, if (g_MouseCursors[@intCast(usize, imgui_cursor)]) |cursor| cursor else g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_Arrow)]);
248 c.glfwSetInputMode(window, c.GLFW_CURSOR, c.GLFW_CURSOR_NORMAL);
222249 }
223 }
224
225 for (io.*.MouseDown) |*isDown, i|
226 isDown.* = isDown.* or c.glfwGetMouseButton(window, @intCast(c_int, i)) != 0;
227 }
228 }
229 }
230
231 fn UpdateMouseCursor() void {
232 const io = c.igGetIO();
233 if (io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_NoMouseCursorChange) != 0
234 or c.glfwGetInputMode(g_Window, c.GLFW_CURSOR) == c.GLFW_CURSOR_DISABLED)
235 return;
236
237 const imgui_cursor = c.igGetMouseCursor();
238 const platform_io = c.igGetPlatformIO();
239 var n : usize = 0;
240 while (n < @intCast(usize, platform_io.*.Viewports.Size)) : (n += 1) {
241 const window = @ptrCast(*c.GLFWwindow, platform_io.*.Viewports.Data[n].*.PlatformHandle);
242 if (imgui_cursor == @enumToInt(c.ImGuiMouseCursor_None) or io.*.MouseDrawCursor) {
243 // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
244 c.glfwSetInputMode(window, c.GLFW_CURSOR, c.GLFW_CURSOR_HIDDEN);
245 } else {
246 // Show OS mouse cursor
247 // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
248 c.glfwSetCursor(window,
249 if (g_MouseCursors[@intCast(usize, imgui_cursor)]) |cursor| cursor
250 else g_MouseCursors[@enumToInt(c.ImGuiMouseCursor_Arrow)]);
251 c.glfwSetInputMode(window, c.GLFW_CURSOR, c.GLFW_CURSOR_NORMAL);
252 }
253 }
250 }
254251 }
255252
256253 fn UpdateGamepads() void {
257 // @TODO
254 // @TODO
258255 }
259256
260257 // GLFW Callbacks
261258 extern fn Callback_MouseButton(window: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) void {
262 if (g_PrevUserCallbackMousebutton) |prev| {
263 prev(window, button, action, mods);
264 }
265
266 if (button < 0)
267 return;
268
269 const button_u = @intCast(usize, button);
270 if (action == c.GLFW_PRESS and button_u < g_MouseJustPressed.len)
271 g_MouseJustPressed[button_u] = true;
259 if (g_PrevUserCallbackMousebutton) |prev| {
260 prev(window, button, action, mods);
261 }
262
263 if (button < 0)
264 return;
265
266 const button_u = @intCast(usize, button);
267 if (action == c.GLFW_PRESS and button_u < g_MouseJustPressed.len)
268 g_MouseJustPressed[button_u] = true;
272269 }
273270
274271 extern fn Callback_Scroll(window: ?*c.GLFWwindow, dx: f64, dy: f64) void {
275 if (g_PrevUserCallbackScroll) |prev| {
276 prev(window, dx, dy);
277 }
278
279 const io = c.igGetIO();
280 io.*.MouseWheelH += @floatCast(f32, dx);
281 io.*.MouseWheel += @floatCast(f32, dy);
272 if (g_PrevUserCallbackScroll) |prev| {
273 prev(window, dx, dy);
274 }
275
276 const io = c.igGetIO();
277 io.*.MouseWheelH += @floatCast(f32, dx);
278 io.*.MouseWheel += @floatCast(f32, dy);
282279 }
283280
284281 extern fn Callback_Key(window: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, modifiers: c_int) void {
285 if (g_PrevUserCallbackKey) |prev| {
286 prev(window, key, scancode, action, modifiers);
287 }
288
289 if (key < 0)
290 unreachable;
291
292 const key_u = @intCast(usize, key);
293
294 const io = c.igGetIO();
295 if (action == c.GLFW_PRESS)
296 io.*.KeysDown[key_u] = true;
297 if (action == c.GLFW_RELEASE)
298 io.*.KeysDown[key_u] = false;
299
300 // Modifiers are not reliable across systems
301 io.*.KeyCtrl = io.*.KeysDown[c.GLFW_KEY_LEFT_CONTROL] or io.*.KeysDown[c.GLFW_KEY_RIGHT_CONTROL];
302 io.*.KeyShift = io.*.KeysDown[c.GLFW_KEY_LEFT_SHIFT] or io.*.KeysDown[c.GLFW_KEY_RIGHT_SHIFT];
303 io.*.KeyAlt = io.*.KeysDown[c.GLFW_KEY_LEFT_ALT] or io.*.KeysDown[c.GLFW_KEY_RIGHT_ALT];
304 io.*.KeySuper = io.*.KeysDown[c.GLFW_KEY_LEFT_SUPER] or io.*.KeysDown[c.GLFW_KEY_RIGHT_SUPER];
282 if (g_PrevUserCallbackKey) |prev| {
283 prev(window, key, scancode, action, modifiers);
284 }
285
286 if (key < 0)
287 unreachable;
288
289 const key_u = @intCast(usize, key);
290
291 const io = c.igGetIO();
292 if (action == c.GLFW_PRESS)
293 io.*.KeysDown[key_u] = true;
294 if (action == c.GLFW_RELEASE)
295 io.*.KeysDown[key_u] = false;
296
297 // Modifiers are not reliable across systems
298 io.*.KeyCtrl = io.*.KeysDown[c.GLFW_KEY_LEFT_CONTROL] or io.*.KeysDown[c.GLFW_KEY_RIGHT_CONTROL];
299 io.*.KeyShift = io.*.KeysDown[c.GLFW_KEY_LEFT_SHIFT] or io.*.KeysDown[c.GLFW_KEY_RIGHT_SHIFT];
300 io.*.KeyAlt = io.*.KeysDown[c.GLFW_KEY_LEFT_ALT] or io.*.KeysDown[c.GLFW_KEY_RIGHT_ALT];
301 io.*.KeySuper = io.*.KeysDown[c.GLFW_KEY_LEFT_SUPER] or io.*.KeysDown[c.GLFW_KEY_RIGHT_SUPER];
305302 }
306303
307304 extern fn Callback_Char(window: ?*c.GLFWwindow, char: c_uint) void {
308 if (g_PrevUserCallbackChar) |prev| {
309 prev(window, char);
310 }
311
312 const io = c.igGetIO();
313 c.ImGuiIO_AddInputCharacter(io, char);
314 }
305 if (g_PrevUserCallbackChar) |prev| {
306 prev(window, char);
307 }
308
309 const io = c.igGetIO();
310 c.ImGuiIO_AddInputCharacter(io, char);
311 }
1 /// this is a port of cimgui/imgui/examples/example_glfw_opengl3/main.cpp
12 const c = @import("c.zig");
23 const std = @import("std");
34 const panic = std.debug.panic;
67 const gl3_impl = @import("gl3_impl.zig");
78
89 extern fn errorCallback(err: c_int, description: [*c]const u8) void {
9 panic("Error: {}\n", description);
10 panic("Error: {}\n", description);
1011 }
1112
1213 var window: *c.GLFWwindow = undefined;
1314
1415 pub fn main() !void {
15 _ = c.glfwSetErrorCallback(errorCallback);
16 _ = c.glfwSetErrorCallback(errorCallback);
1617
17 if (c.glfwInit() == c.GL_FALSE) {
18 panic("GLFW init failure\n");
19 }
20 defer c.glfwTerminate();
18 if (c.glfwInit() == c.GL_FALSE) {
19 panic("GLFW init failure\n");
20 }
21 defer c.glfwTerminate();
2122
22 c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
23 c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2);
24 c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE);
25 c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, debug_gl.is_on);
26 c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
27 // c.glfwWindowHint(c.GLFW_DEPTH_BITS, 0);
28 // c.glfwWindowHint(c.GLFW_STENCIL_BITS, 8);
29 c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_TRUE);
23 c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
24 c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2);
25 c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE);
26 c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, debug_gl.is_on);
27 c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
28 // c.glfwWindowHint(c.GLFW_DEPTH_BITS, 0);
29 // c.glfwWindowHint(c.GLFW_STENCIL_BITS, 8);
30 c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_TRUE);
3031
31 const window_width = 640;
32 const window_height = 480;
33 window = c.glfwCreateWindow(window_width, window_height, c"ImGUI Test", null, null) orelse {
34 panic("unable to create window\n");
35 };
36 defer c.glfwDestroyWindow(window);
32 const window_width = 640;
33 const window_height = 480;
34 window = c.glfwCreateWindow(window_width, window_height, c"ImGUI Test", null, null) orelse {
35 panic("unable to create window\n");
36 };
37 defer c.glfwDestroyWindow(window);
3738
38 c.glfwMakeContextCurrent(window);
39 c.glfwSwapInterval(1);
39 c.glfwMakeContextCurrent(window);
40 c.glfwSwapInterval(1);
4041
41 const context = c.igCreateContext(null);
42 defer c.igDestroyContext(context);
42 const context = c.igCreateContext(null);
43 defer c.igDestroyContext(context);
4344
44 const io = c.igGetIO();
45 io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_NavEnableKeyboard);
46 // io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_DockingEnable);
47 // io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_ViewportsEnable);
45 const io = c.igGetIO();
46 io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_NavEnableKeyboard);
47 // io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_DockingEnable);
48 // io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_ViewportsEnable);
4849
49 const style = c.igGetStyle();
50 c.igStyleColorsDark(style);
50 const style = c.igGetStyle();
51 c.igStyleColorsDark(style);
5152
52 if (false and io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0) {
53 style.*.WindowRounding = 0.0;
54 style.*.Colors[@enumToInt(c.ImGuiCol_WindowBg)].w = 1.0;
55 }
53 if (false and io.*.ConfigFlags & @enumToInt(c.ImGuiConfigFlags_ViewportsEnable) != 0) {
54 style.*.WindowRounding = 0.0;
55 style.*.Colors[@enumToInt(c.ImGuiCol_WindowBg)].w = 1.0;
56 }
5657
57 glfw_impl.Init(window, true, glfw_impl.ClientApi.OpenGL);
58 defer glfw_impl.Shutdown();
58 glfw_impl.Init(window, true, glfw_impl.ClientApi.OpenGL);
59 defer glfw_impl.Shutdown();
5960
60 gl3_impl.Init(); // #version 150
61 defer gl3_impl.Shutdown();
61 gl3_impl.Init(); // #version 150
62 defer gl3_impl.Shutdown();
6263
63 const start_time = c.glfwGetTime();
64 var prev_time = start_time;
64 const start_time = c.glfwGetTime();
65 var prev_time = start_time;
6566
66 while (c.glfwWindowShouldClose(window) == c.GL_FALSE) {
67 c.glfwPollEvents();
67 while (c.glfwWindowShouldClose(window) == c.GL_FALSE) {
68 c.glfwPollEvents();
6869
69 try gl3_impl.NewFrame();
70 glfw_impl.NewFrame();
71 c.igNewFrame();
70 try gl3_impl.NewFrame();
71 glfw_impl.NewFrame();
72 c.igNewFrame();
7273
73 // main part
74 c.igShowDemoWindow(null);
74 // main part
75 c.igShowDemoWindow(null);
7576
76 c.igRender();
77 var w: c_int = undefined;
78 var h: c_int = undefined;
79 c.glfwGetFramebufferSize(window, &w, &h);
80 c.glViewport(0, 0, w, h);
81 c.glClearColor(0.0, 0.0, 0.0, 0.0);
82 c.glClear(c.GL_COLOR_BUFFER_BIT);
83 gl3_impl.RenderDrawData(c.igGetDrawData());
77 c.igRender();
78 var w: c_int = undefined;
79 var h: c_int = undefined;
80 c.glfwGetFramebufferSize(window, &w, &h);
81 c.glViewport(0, 0, w, h);
82 c.glClearColor(0.0, 0.0, 0.0, 0.0);
83 c.glClear(c.GL_COLOR_BUFFER_BIT);
84 gl3_impl.RenderDrawData(c.igGetDrawData());
8485
85 // const now_time = c.glfwGetTime();
86 // const elapsed = now_time - prev_time;
87 // prev_time = now_time;
88 // nextFrame(t, elapsed);
89 // draw(t, @This());
90
91 c.glfwSwapBuffers(window);
92 }
86 // const now_time = c.glfwGetTime();
87 // const elapsed = now_time - prev_time;
88 // prev_time = now_time;
89 // nextFrame(t, elapsed);
90 // draw(t, @This());
91
92 c.glfwSwapBuffers(window);
93 }
9394 }