siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Zero-dependency OpenGL shared library loader and function dispatch table.
//!
//! Resolves OpenGL 3.3–4.6 Core entry points either from a user-provided loader
//! closure (for integration with `winit`/`glutin`, `glfw`, `sdl2`, etc.) or via
//! the native OS OpenGL library (`opengl32.dll` on Windows, `libGL.so.1` on
//! Linux, `OpenGL.framework` on macOS).

use std::ffi::{c_char, c_void, CString};
use std::fmt;
use std::mem;

use crate::error::{GlError, Result};
use crate::sys;

// ---------------------------------------------------------------------------
// OS-native shared library loading (zero third-party dependencies)
// ---------------------------------------------------------------------------

#[cfg(windows)]
pub(crate) mod os {
    use std::ffi::{c_char, c_void};

    type PfnWglGetProcAddress = unsafe extern "system" fn(*const c_char) -> *const c_void;

    #[link(name = "kernel32")]
    extern "system" {
        fn LoadLibraryA(lpLibFileName: *const c_char) -> *mut c_void;
        fn GetProcAddress(hModule: *mut c_void, lpProcName: *const c_char) -> *const c_void;
        fn FreeLibrary(hLibModule: *mut c_void) -> i32;
    }

    pub(crate) struct SystemGlLibrary {
        handle: *mut c_void,
        wgl_get_proc_address: Option<PfnWglGetProcAddress>,
    }

    impl SystemGlLibrary {
        pub(crate) fn load() -> Result<Self, String> {
            // SAFETY: `"opengl32.dll\0"` is a valid NUL-terminated static string.
            let handle = unsafe { LoadLibraryA(b"opengl32.dll\0".as_ptr().cast()) };
            if handle.is_null() {
                return Err("LoadLibraryA(\"opengl32.dll\") returned null".to_owned());
            }

            // SAFETY: `handle` is valid and `"wglGetProcAddress\0"` is NUL-terminated.
            let raw = unsafe { GetProcAddress(handle, b"wglGetProcAddress\0".as_ptr().cast()) };
            let wgl_get_proc_address = if raw.is_null() {
                None
            } else {
                // SAFETY: `wglGetProcAddress` has the exact `extern "system"` signature.
                Some(unsafe { std::mem::transmute::<*const c_void, PfnWglGetProcAddress>(raw) })
            };

            Ok(Self {
                handle,
                wgl_get_proc_address,
            })
        }

        pub(crate) fn get_proc_address(&self, name_nul: &[u8]) -> *const c_void {
            if let Some(wgl_gpa) = self.wgl_get_proc_address {
                // SAFETY: `name_nul` is NUL-terminated; `wglGetProcAddress` requires an active context.
                let ptr = unsafe { wgl_gpa(name_nul.as_ptr().cast()) };
                if is_valid_gl_proc_ptr(ptr) {
                    return ptr;
                }
            }
            // Fallback to `opengl32.dll` exports for OpenGL 1.1 core functions.
            // SAFETY: `self.handle` is valid and `name_nul` is NUL-terminated.
            let fallback = unsafe { GetProcAddress(self.handle, name_nul.as_ptr().cast()) };
            if is_valid_gl_proc_ptr(fallback) {
                fallback
            } else {
                std::ptr::null()
            }
        }
    }

    impl Drop for SystemGlLibrary {
        fn drop(&mut self) {
            if !self.handle.is_null() {
                // SAFETY: `self.handle` was returned by `LoadLibraryA` and is exclusively owned.
                let _ = unsafe { FreeLibrary(self.handle) };
            }
        }
    }

    /// Khronos WGL specification: `wglGetProcAddress` may return `0`, `1`, `2`, `3`, or `-1`
    /// as error sentinel values on certain Windows ICD drivers.
    #[inline]
    pub(crate) fn is_valid_gl_proc_ptr(ptr: *const c_void) -> bool {
        let addr = ptr as usize;
        addr != 0 && addr != 1 && addr != 2 && addr != 3 && addr != usize::MAX
    }
}

#[cfg(unix)]
pub(crate) mod os {
    use std::ffi::{c_char, c_int, c_void};

    type PfnGlxGetProcAddress = unsafe extern "C" fn(*const u8) -> *const c_void;

    const RTLD_NOW: c_int = 0x0002;
    const RTLD_LOCAL: c_int = 0x0000;

    #[cfg_attr(target_os = "linux", link(name = "dl"))]
    extern "C" {
        fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void;
        fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
        fn dlclose(handle: *mut c_void) -> c_int;
    }

    #[cfg(target_os = "macos")]
    const CANDIDATES: &[&[u8]] = &[b"/System/Library/Frameworks/OpenGL.framework/OpenGL\0"];

    #[cfg(not(target_os = "macos"))]
    const CANDIDATES: &[&[u8]] = &[b"libGL.so.1\0", b"libGL.so\0"];

    pub(crate) struct SystemGlLibrary {
        handle: *mut c_void,
        glx_get_proc_address: Option<PfnGlxGetProcAddress>,
    }

    impl SystemGlLibrary {
        pub(crate) fn load() -> Result<Self, String> {
            let mut handle = std::ptr::null_mut();
            for candidate in CANDIDATES {
                // SAFETY: `candidate` is a NUL-terminated static byte slice.
                handle = unsafe { dlopen(candidate.as_ptr().cast(), RTLD_NOW | RTLD_LOCAL) };
                if !handle.is_null() {
                    break;
                }
            }
            if handle.is_null() {
                return Err("dlopen failed to load system OpenGL library".to_owned());
            }

            // SAFETY: `handle` is non-null and symbol names are NUL-terminated.
            let raw = unsafe {
                let p = dlsym(handle, b"glXGetProcAddressARB\0".as_ptr().cast());
                if !p.is_null() {
                    p
                } else {
                    dlsym(handle, b"glXGetProcAddress\0".as_ptr().cast())
                }
            };

            let glx_get_proc_address = if raw.is_null() {
                None
            } else {
                // SAFETY: `glXGetProcAddress[ARB]` uses the C calling convention.
                Some(unsafe { std::mem::transmute::<*mut c_void, PfnGlxGetProcAddress>(raw) })
            };

            Ok(Self {
                handle,
                glx_get_proc_address,
            })
        }

        pub(crate) fn get_proc_address(&self, name_nul: &[u8]) -> *const c_void {
            if let Some(glx_gpa) = self.glx_get_proc_address {
                // SAFETY: `name_nul` is NUL-terminated.
                let ptr = unsafe { glx_gpa(name_nul.as_ptr()) };
                if is_valid_gl_proc_ptr(ptr) {
                    return ptr;
                }
            }
            // SAFETY: `self.handle` is valid and `name_nul` is NUL-terminated.
            let ptr = unsafe { dlsym(self.handle, name_nul.as_ptr().cast()) as *const c_void };
            if is_valid_gl_proc_ptr(ptr) {
                ptr
            } else {
                std::ptr::null()
            }
        }
    }

    impl Drop for SystemGlLibrary {
        fn drop(&mut self) {
            if !self.handle.is_null() {
                // SAFETY: `self.handle` was returned by `dlopen` and is exclusively owned.
                let _ = unsafe { dlclose(self.handle) };
            }
        }
    }

    #[inline]
    pub(crate) fn is_valid_gl_proc_ptr(ptr: *const c_void) -> bool {
        !ptr.is_null()
    }
}

/// Keeps the OS OpenGL library loaded for as long as the [`crate::GlContext`] exists.
pub(crate) struct SystemLibraryGuard {
    _inner: os::SystemGlLibrary,
}

impl SystemLibraryGuard {
    pub(crate) fn new(lib: os::SystemGlLibrary) -> Self {
        Self { _inner: lib }
    }
}

/// Resolved OpenGL 3.3–4.6 Core function pointer table.
///
/// Core 3.3 symbols are required at load time; newer 4.x / extension symbols
/// (such as `glBufferStorage`, `glDispatchCompute`, `glMemoryBarrier`, and
/// `glDebugMessageCallback`) are stored as `Option<PFN_...>` and checked before
/// every call so missing symbols cleanly return [`GlError::MissingFunction`].
pub(crate) struct GlFnTable {
    // Core queries & synchronization
    pub(crate) get_error: sys::PFN_glGetError,
    pub(crate) get_string: sys::PFN_glGetString,
    pub(crate) get_stringi: Option<sys::PFN_glGetStringi>,
    pub(crate) get_integerv: sys::PFN_glGetIntegerv,
    pub(crate) get_floatv: sys::PFN_glGetFloatv,
    pub(crate) flush: sys::PFN_glFlush,
    pub(crate) finish: sys::PFN_glFinish,
    pub(crate) pixel_storei: sys::PFN_glPixelStorei,
    pub(crate) read_pixels: sys::PFN_glReadPixels,

    // Pipeline state
    pub(crate) viewport: sys::PFN_glViewport,
    pub(crate) scissor: sys::PFN_glScissor,
    pub(crate) clear_color: sys::PFN_glClearColor,
    pub(crate) clear_depth: sys::PFN_glClearDepth,
    pub(crate) clear: sys::PFN_glClear,
    pub(crate) enable: sys::PFN_glEnable,
    pub(crate) disable: sys::PFN_glDisable,
    pub(crate) is_enabled: sys::PFN_glIsEnabled,
    pub(crate) blend_func: sys::PFN_glBlendFunc,
    pub(crate) blend_func_separate: sys::PFN_glBlendFuncSeparate,
    pub(crate) blend_equation: sys::PFN_glBlendEquation,
    pub(crate) depth_func: sys::PFN_glDepthFunc,
    pub(crate) depth_mask: sys::PFN_glDepthMask,
    pub(crate) color_mask: sys::PFN_glColorMask,
    pub(crate) cull_face: sys::PFN_glCullFace,
    pub(crate) front_face: sys::PFN_glFrontFace,
    pub(crate) polygon_mode: sys::PFN_glPolygonMode,

    // Draw & compute
    pub(crate) draw_arrays: sys::PFN_glDrawArrays,
    pub(crate) draw_elements: sys::PFN_glDrawElements,
    pub(crate) draw_arrays_instanced: sys::PFN_glDrawArraysInstanced,
    pub(crate) draw_elements_instanced: sys::PFN_glDrawElementsInstanced,
    pub(crate) dispatch_compute: Option<sys::PFN_glDispatchCompute>,
    pub(crate) memory_barrier: Option<sys::PFN_glMemoryBarrier>,

    // Buffers
    pub(crate) gen_buffers: sys::PFN_glGenBuffers,
    pub(crate) delete_buffers: sys::PFN_glDeleteBuffers,
    pub(crate) bind_buffer: sys::PFN_glBindBuffer,
    pub(crate) bind_buffer_base: sys::PFN_glBindBufferBase,
    pub(crate) bind_buffer_range: sys::PFN_glBindBufferRange,
    pub(crate) buffer_data: sys::PFN_glBufferData,
    pub(crate) buffer_sub_data: sys::PFN_glBufferSubData,
    pub(crate) get_buffer_sub_data: sys::PFN_glGetBufferSubData,
    pub(crate) copy_buffer_sub_data: sys::PFN_glCopyBufferSubData,
    pub(crate) map_buffer_range: sys::PFN_glMapBufferRange,
    pub(crate) unmap_buffer: sys::PFN_glUnmapBuffer,
    pub(crate) buffer_storage: Option<sys::PFN_glBufferStorage>,

    // Vertex arrays
    pub(crate) gen_vertex_arrays: sys::PFN_glGenVertexArrays,
    pub(crate) delete_vertex_arrays: sys::PFN_glDeleteVertexArrays,
    pub(crate) bind_vertex_array: sys::PFN_glBindVertexArray,
    pub(crate) enable_vertex_attrib_array: sys::PFN_glEnableVertexAttribArray,
    pub(crate) disable_vertex_attrib_array: sys::PFN_glDisableVertexAttribArray,
    pub(crate) vertex_attrib_pointer: sys::PFN_glVertexAttribPointer,
    pub(crate) vertex_attrib_ipointer: sys::PFN_glVertexAttribIPointer,
    pub(crate) vertex_attrib_divisor: sys::PFN_glVertexAttribDivisor,

    // Shaders & programs
    pub(crate) create_shader: sys::PFN_glCreateShader,
    pub(crate) delete_shader: sys::PFN_glDeleteShader,
    pub(crate) shader_source: sys::PFN_glShaderSource,
    pub(crate) compile_shader: sys::PFN_glCompileShader,
    pub(crate) get_shaderiv: sys::PFN_glGetShaderiv,
    pub(crate) get_shader_info_log: sys::PFN_glGetShaderInfoLog,

    pub(crate) create_program: sys::PFN_glCreateProgram,
    pub(crate) delete_program: sys::PFN_glDeleteProgram,
    pub(crate) attach_shader: sys::PFN_glAttachShader,
    pub(crate) detach_shader: sys::PFN_glDetachShader,
    pub(crate) link_program: sys::PFN_glLinkProgram,
    pub(crate) validate_program: sys::PFN_glValidateProgram,
    pub(crate) use_program: sys::PFN_glUseProgram,
    pub(crate) get_programiv: sys::PFN_glGetProgramiv,
    pub(crate) get_program_info_log: sys::PFN_glGetProgramInfoLog,
    pub(crate) get_uniform_location: sys::PFN_glGetUniformLocation,
    pub(crate) get_attrib_location: sys::PFN_glGetAttribLocation,
    pub(crate) get_uniform_block_index: sys::PFN_glGetUniformBlockIndex,
    pub(crate) uniform_block_binding: sys::PFN_glUniformBlockBinding,
    pub(crate) get_active_uniform: sys::PFN_glGetActiveUniform,
    pub(crate) get_active_attrib: sys::PFN_glGetActiveAttrib,

    pub(crate) uniform1i: sys::PFN_glUniform1i,
    pub(crate) uniform1ui: sys::PFN_glUniform1ui,
    pub(crate) uniform1f: sys::PFN_glUniform1f,
    pub(crate) uniform2f: sys::PFN_glUniform2f,
    pub(crate) uniform3f: sys::PFN_glUniform3f,
    pub(crate) uniform4f: sys::PFN_glUniform4f,
    pub(crate) uniform_matrix3fv: sys::PFN_glUniformMatrix3fv,
    pub(crate) uniform_matrix4fv: sys::PFN_glUniformMatrix4fv,

    // Textures & samplers
    pub(crate) gen_textures: sys::PFN_glGenTextures,
    pub(crate) delete_textures: sys::PFN_glDeleteTextures,
    pub(crate) bind_texture: sys::PFN_glBindTexture,
    pub(crate) active_texture: sys::PFN_glActiveTexture,
    pub(crate) tex_image_2d: sys::PFN_glTexImage2D,
    pub(crate) tex_sub_image_2d: sys::PFN_glTexSubImage2D,
    pub(crate) tex_parameteri: sys::PFN_glTexParameteri,
    pub(crate) generate_mipmap: sys::PFN_glGenerateMipmap,

    pub(crate) gen_samplers: sys::PFN_glGenSamplers,
    pub(crate) delete_samplers: sys::PFN_glDeleteSamplers,
    pub(crate) bind_sampler: sys::PFN_glBindSampler,
    pub(crate) sampler_parameteri: sys::PFN_glSamplerParameteri,
    pub(crate) sampler_parameterf: sys::PFN_glSamplerParameterf,

    // Framebuffers & renderbuffers
    pub(crate) gen_framebuffers: sys::PFN_glGenFramebuffers,
    pub(crate) delete_framebuffers: sys::PFN_glDeleteFramebuffers,
    pub(crate) bind_framebuffer: sys::PFN_glBindFramebuffer,
    pub(crate) framebuffer_texture_2d: sys::PFN_glFramebufferTexture2D,
    pub(crate) framebuffer_renderbuffer: sys::PFN_glFramebufferRenderbuffer,
    pub(crate) check_framebuffer_status: sys::PFN_glCheckFramebufferStatus,
    pub(crate) draw_buffers: sys::PFN_glDrawBuffers,
    pub(crate) blit_framebuffer: sys::PFN_glBlitFramebuffer,

    pub(crate) gen_renderbuffers: sys::PFN_glGenRenderbuffers,
    pub(crate) delete_renderbuffers: sys::PFN_glDeleteRenderbuffers,
    pub(crate) bind_renderbuffer: sys::PFN_glBindRenderbuffer,
    pub(crate) renderbuffer_storage: sys::PFN_glRenderbufferStorage,
    pub(crate) renderbuffer_storage_multisample: sys::PFN_glRenderbufferStorageMultisample,

    // Sync & queries
    pub(crate) fence_sync: sys::PFN_glFenceSync,
    pub(crate) delete_sync: sys::PFN_glDeleteSync,
    pub(crate) client_wait_sync: sys::PFN_glClientWaitSync,
    pub(crate) wait_sync: sys::PFN_glWaitSync,

    pub(crate) gen_queries: sys::PFN_glGenQueries,
    pub(crate) delete_queries: sys::PFN_glDeleteQueries,
    pub(crate) begin_query: sys::PFN_glBeginQuery,
    pub(crate) end_query: sys::PFN_glEndQuery,
    pub(crate) get_query_objectuiv: sys::PFN_glGetQueryObjectuiv,
    pub(crate) get_query_objectui64v: Option<sys::PFN_glGetQueryObjectui64v>,
    pub(crate) query_counter: Option<sys::PFN_glQueryCounter>,

    // Debug output (GL 4.3 / KHR_debug)
    pub(crate) debug_message_callback: Option<sys::PFN_glDebugMessageCallback>,
    pub(crate) debug_message_control: Option<sys::PFN_glDebugMessageControl>,
}

impl fmt::Debug for GlFnTable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlFnTable")
            .field("has_compute", &self.dispatch_compute.is_some())
            .field("has_buffer_storage", &self.buffer_storage.is_some())
            .field("has_debug_callback", &self.debug_message_callback.is_some())
            .finish()
    }
}

/// Loads a required OpenGL function pointer and transmutes it to `T`.
///
/// # Safety
/// `T` must be a `Copy` `unsafe extern "system" fn(...)` matching the exact OpenGL
/// ABI signature of `name`.
unsafe fn load_required<T: Copy>(
    loader: &mut dyn FnMut(&str) -> *const c_void,
    name: &'static str,
) -> Result<T> {
    debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<*const c_void>());
    let ptr = loader(name);
    if !os::is_valid_gl_proc_ptr(ptr) {
        return Err(GlError::MissingFunction { name });
    }
    // SAFETY: Caller guarantees `T` matches the exact C ABI signature of `name`,
    // and `ptr` has been validated as non-null / non-sentinel.
    Ok(unsafe { mem::transmute_copy(&ptr) })
}

/// Loads an optional OpenGL function pointer (GL 4.x / extension).
///
/// # Safety
/// `T` must be a `Copy` `unsafe extern "system" fn(...)` matching the exact OpenGL
/// ABI signature of `name`.
unsafe fn load_optional<T: Copy>(
    loader: &mut dyn FnMut(&str) -> *const c_void,
    name: &'static str,
) -> Option<T> {
    debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<*const c_void>());
    let ptr = loader(name);
    if !os::is_valid_gl_proc_ptr(ptr) {
        return None;
    }
    // SAFETY: Caller guarantees `T` matches the exact C ABI signature of `name`,
    // and `ptr` has been validated as non-null / non-sentinel.
    Some(unsafe { mem::transmute_copy(&ptr) })
}

impl GlFnTable {
    /// Resolves all required OpenGL 3.3 Core and optional OpenGL 4.x entry points.
    pub(crate) fn load(loader: &mut dyn FnMut(&str) -> *const c_void) -> Result<Self> {
        // SAFETY: Every symbol name below matches its exact `PFN_gl*` typedef in `crate::sys`.
        unsafe {
            Ok(Self {
                get_error: load_required(loader, "glGetError")?,
                get_string: load_required(loader, "glGetString")?,
                get_stringi: load_optional(loader, "glGetStringi"),
                get_integerv: load_required(loader, "glGetIntegerv")?,
                get_floatv: load_required(loader, "glGetFloatv")?,
                flush: load_required(loader, "glFlush")?,
                finish: load_required(loader, "glFinish")?,
                pixel_storei: load_required(loader, "glPixelStorei")?,
                read_pixels: load_required(loader, "glReadPixels")?,

                viewport: load_required(loader, "glViewport")?,
                scissor: load_required(loader, "glScissor")?,
                clear_color: load_required(loader, "glClearColor")?,
                clear_depth: load_required(loader, "glClearDepth")?,
                clear: load_required(loader, "glClear")?,
                enable: load_required(loader, "glEnable")?,
                disable: load_required(loader, "glDisable")?,
                is_enabled: load_required(loader, "glIsEnabled")?,
                blend_func: load_required(loader, "glBlendFunc")?,
                blend_func_separate: load_required(loader, "glBlendFuncSeparate")?,
                blend_equation: load_required(loader, "glBlendEquation")?,
                depth_func: load_required(loader, "glDepthFunc")?,
                depth_mask: load_required(loader, "glDepthMask")?,
                color_mask: load_required(loader, "glColorMask")?,
                cull_face: load_required(loader, "glCullFace")?,
                front_face: load_required(loader, "glFrontFace")?,
                polygon_mode: load_required(loader, "glPolygonMode")?,

                draw_arrays: load_required(loader, "glDrawArrays")?,
                draw_elements: load_required(loader, "glDrawElements")?,
                draw_arrays_instanced: load_required(loader, "glDrawArraysInstanced")?,
                draw_elements_instanced: load_required(loader, "glDrawElementsInstanced")?,
                dispatch_compute: load_optional(loader, "glDispatchCompute"),
                memory_barrier: load_optional(loader, "glMemoryBarrier"),

                gen_buffers: load_required(loader, "glGenBuffers")?,
                delete_buffers: load_required(loader, "glDeleteBuffers")?,
                bind_buffer: load_required(loader, "glBindBuffer")?,
                bind_buffer_base: load_required(loader, "glBindBufferBase")?,
                bind_buffer_range: load_required(loader, "glBindBufferRange")?,
                buffer_data: load_required(loader, "glBufferData")?,
                buffer_sub_data: load_required(loader, "glBufferSubData")?,
                get_buffer_sub_data: load_required(loader, "glGetBufferSubData")?,
                copy_buffer_sub_data: load_required(loader, "glCopyBufferSubData")?,
                map_buffer_range: load_required(loader, "glMapBufferRange")?,
                unmap_buffer: load_required(loader, "glUnmapBuffer")?,
                buffer_storage: load_optional(loader, "glBufferStorage"),

                gen_vertex_arrays: load_required(loader, "glGenVertexArrays")?,
                delete_vertex_arrays: load_required(loader, "glDeleteVertexArrays")?,
                bind_vertex_array: load_required(loader, "glBindVertexArray")?,
                enable_vertex_attrib_array: load_required(loader, "glEnableVertexAttribArray")?,
                disable_vertex_attrib_array: load_required(loader, "glDisableVertexAttribArray")?,
                vertex_attrib_pointer: load_required(loader, "glVertexAttribPointer")?,
                vertex_attrib_ipointer: load_required(loader, "glVertexAttribIPointer")?,
                vertex_attrib_divisor: load_required(loader, "glVertexAttribDivisor")?,

                create_shader: load_required(loader, "glCreateShader")?,
                delete_shader: load_required(loader, "glDeleteShader")?,
                shader_source: load_required(loader, "glShaderSource")?,
                compile_shader: load_required(loader, "glCompileShader")?,
                get_shaderiv: load_required(loader, "glGetShaderiv")?,
                get_shader_info_log: load_required(loader, "glGetShaderInfoLog")?,

                create_program: load_required(loader, "glCreateProgram")?,
                delete_program: load_required(loader, "glDeleteProgram")?,
                attach_shader: load_required(loader, "glAttachShader")?,
                detach_shader: load_required(loader, "glDetachShader")?,
                link_program: load_required(loader, "glLinkProgram")?,
                validate_program: load_required(loader, "glValidateProgram")?,
                use_program: load_required(loader, "glUseProgram")?,
                get_programiv: load_required(loader, "glGetProgramiv")?,
                get_program_info_log: load_required(loader, "glGetProgramInfoLog")?,
                get_uniform_location: load_required(loader, "glGetUniformLocation")?,
                get_attrib_location: load_required(loader, "glGetAttribLocation")?,
                get_uniform_block_index: load_required(loader, "glGetUniformBlockIndex")?,
                uniform_block_binding: load_required(loader, "glUniformBlockBinding")?,
                get_active_uniform: load_required(loader, "glGetActiveUniform")?,
                get_active_attrib: load_required(loader, "glGetActiveAttrib")?,

                uniform1i: load_required(loader, "glUniform1i")?,
                uniform1ui: load_required(loader, "glUniform1ui")?,
                uniform1f: load_required(loader, "glUniform1f")?,
                uniform2f: load_required(loader, "glUniform2f")?,
                uniform3f: load_required(loader, "glUniform3f")?,
                uniform4f: load_required(loader, "glUniform4f")?,
                uniform_matrix3fv: load_required(loader, "glUniformMatrix3fv")?,
                uniform_matrix4fv: load_required(loader, "glUniformMatrix4fv")?,

                gen_textures: load_required(loader, "glGenTextures")?,
                delete_textures: load_required(loader, "glDeleteTextures")?,
                bind_texture: load_required(loader, "glBindTexture")?,
                active_texture: load_required(loader, "glActiveTexture")?,
                tex_image_2d: load_required(loader, "glTexImage2D")?,
                tex_sub_image_2d: load_required(loader, "glTexSubImage2D")?,
                tex_parameteri: load_required(loader, "glTexParameteri")?,
                generate_mipmap: load_required(loader, "glGenerateMipmap")?,

                gen_samplers: load_required(loader, "glGenSamplers")?,
                delete_samplers: load_required(loader, "glDeleteSamplers")?,
                bind_sampler: load_required(loader, "glBindSampler")?,
                sampler_parameteri: load_required(loader, "glSamplerParameteri")?,
                sampler_parameterf: load_required(loader, "glSamplerParameterf")?,

                gen_framebuffers: load_required(loader, "glGenFramebuffers")?,
                delete_framebuffers: load_required(loader, "glDeleteFramebuffers")?,
                bind_framebuffer: load_required(loader, "glBindFramebuffer")?,
                framebuffer_texture_2d: load_required(loader, "glFramebufferTexture2D")?,
                framebuffer_renderbuffer: load_required(loader, "glFramebufferRenderbuffer")?,
                check_framebuffer_status: load_required(loader, "glCheckFramebufferStatus")?,
                draw_buffers: load_required(loader, "glDrawBuffers")?,
                blit_framebuffer: load_required(loader, "glBlitFramebuffer")?,

                gen_renderbuffers: load_required(loader, "glGenRenderbuffers")?,
                delete_renderbuffers: load_required(loader, "glDeleteRenderbuffers")?,
                bind_renderbuffer: load_required(loader, "glBindRenderbuffer")?,
                renderbuffer_storage: load_required(loader, "glRenderbufferStorage")?,
                renderbuffer_storage_multisample: load_required(
                    loader,
                    "glRenderbufferStorageMultisample",
                )?,

                fence_sync: load_required(loader, "glFenceSync")?,
                delete_sync: load_required(loader, "glDeleteSync")?,
                client_wait_sync: load_required(loader, "glClientWaitSync")?,
                wait_sync: load_required(loader, "glWaitSync")?,

                gen_queries: load_required(loader, "glGenQueries")?,
                delete_queries: load_required(loader, "glDeleteQueries")?,
                begin_query: load_required(loader, "glBeginQuery")?,
                end_query: load_required(loader, "glEndQuery")?,
                get_query_objectuiv: load_required(loader, "glGetQueryObjectuiv")?,
                get_query_objectui64v: load_optional(loader, "glGetQueryObjectui64v"),
                query_counter: load_optional(loader, "glQueryCounter"),

                debug_message_callback: load_optional(loader, "glDebugMessageCallback")
                    .or_else(|| load_optional(loader, "glDebugMessageCallbackKHR")),
                debug_message_control: load_optional(loader, "glDebugMessageControl")
                    .or_else(|| load_optional(loader, "glDebugMessageControlKHR")),
            })
        }
    }
}

/// Converts a Rust string into a NUL-terminated `CString`, rejecting interior NUL bytes.
pub(crate) fn to_cstring(s: &str, parameter: &'static str) -> Result<CString> {
    CString::new(s).map_err(|_| GlError::InvalidString { parameter })
}

/// Reads a static NUL-terminated C string returned by OpenGL (`glGetString` / `glGetStringi`).
///
/// # Safety
/// `ptr` must be either null or point to a valid NUL-terminated C string that remains
/// alive for the duration of the call.
pub(crate) unsafe fn gl_ptr_to_string(ptr: *const sys::GLubyte) -> String {
    if ptr.is_null() {
        return String::new();
    }
    // SAFETY: Caller guarantees `ptr` points to a valid NUL-terminated C string.
    let cstr = unsafe { std::ffi::CStr::from_ptr(ptr.cast::<c_char>()) };
    cstr.to_string_lossy().into_owned()
}