1
//! OpenGL context wrappers, texture cache management, shader compilation,
2
//! vertex buffer abstractions, and FFI-safe GL type aliases for the C/Python API.
3

            
4
#![allow(unused_variables)]
5
use alloc::{
6
    boxed::Box,
7
    rc::Rc,
8
    string::{String, ToString},
9
    vec::Vec,
10
};
11
use core::{
12
    ffi, fmt,
13
    hash::{Hash, Hasher},
14
    mem::ManuallyDrop,
15
    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
16
};
17

            
18
use azul_css::{
19
    props::{
20
        basic::{ColorF, ColorU},
21
        style::StyleTransformVec,
22
    },
23
    AzString, OptionI32, OptionU32, OptionUsize, StringVec, U8Vec,
24
};
25
pub use gl_context_loader::{
26
    ctypes::*, gl, GLeglImageOES, GLsync, GLvoid, GenericGlContext, GlType as GlContextGlType,
27
};
28

            
29
pub use crate::glconst::*;
30
use crate::{
31
    geom::PhysicalSizeU32,
32
    hit_test::DocumentId,
33
    resources::{
34
        Brush, Epoch, ExternalImageId, ImageDescriptor, ImageDescriptorFlags, RawImage,
35
        RawImageData, RawImageFormat,
36
    },
37
    svg::{TessellatedGPUSvgNode, TessellatedSvgNode},
38
    window::RendererType,
39
    OrderedMap,
40
};
41

            
42
pub type GLuint = u32;
43
pub type GLint = i32;
44
pub type GLint64 = i64;
45
pub type GLuint64 = u64;
46
pub type GLenum = u32;
47
pub type GLintptr = isize;
48
pub type GLboolean = u8;
49
pub type GLsizeiptr = isize;
50
pub type GLbitfield = u32;
51
pub type GLsizei = i32;
52
pub type GLclampf = f32;
53
pub type GLfloat = f32;
54

            
55
pub const GL_RESTART_INDEX: u32 = core::u32::MAX;
56

            
57
/// Passing *const `c_void` is not easily possible when generating APIs,
58
/// so this wrapper struct is for easier API generation
59
#[repr(C)]
60
#[derive(Debug)]
61
pub struct GlVoidPtrConst {
62
    pub ptr: *const GLvoid,
63
    pub run_destructor: bool,
64
}
65

            
66
impl Clone for GlVoidPtrConst {
67
    fn clone(&self) -> Self {
68
        Self {
69
            ptr: self.ptr,
70
            run_destructor: true,
71
        }
72
    }
73
}
74

            
75
impl Drop for GlVoidPtrConst {
76
17
    fn drop(&mut self) {
77
17
        self.run_destructor = false;
78
17
    }
79
}
80

            
81
/// Struct returned from the C API
82
///
83
/// Because of Python, every object has to be clone-able,
84
/// so yes there may exist more than one mutable reference
85
#[repr(C)]
86
#[derive(Debug, Clone, Copy)]
87
pub struct GlVoidPtrMut {
88
    pub ptr: *mut GLvoid,
89
}
90

            
91
/// FFI-safe wrapper for `&str`.
92
#[repr(C)]
93
pub struct Refstr {
94
    pub ptr: *const u8,
95
    pub len: usize,
96
}
97

            
98
impl Clone for Refstr {
99
1
    fn clone(&self) -> Self {
100
1
        Self {
101
1
            ptr: self.ptr,
102
1
            len: self.len,
103
1
        }
104
1
    }
105
}
106

            
107
impl fmt::Debug for Refstr {
108
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109
1
        self.as_str().fmt(f)
110
1
    }
111
}
112

            
113
impl Refstr {
114
    #[must_use]
115
21
    pub const fn as_str(&self) -> &str {
116
        // AUDIT: `from_raw_parts`/`from_utf8_unchecked` are UB on a null ptr
117
        // (even with len==0). FFI callers can hand us a null/empty Refstr, so
118
        // return an empty `&str` instead of forming a slice over null.
119
21
        if self.ptr.is_null() || self.len == 0 {
120
5
            return "";
121
16
        }
122
16
        unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(self.ptr, self.len)) }
123
21
    }
124
}
125

            
126
impl From<&str> for Refstr {
127
11
    fn from(s: &str) -> Self {
128
11
        Self {
129
11
            ptr: s.as_ptr(),
130
11
            len: s.len(),
131
11
        }
132
11
    }
133
}
134

            
135
/// FFI-safe wrapper for `&[&str]`.
136
#[repr(C)]
137
pub struct RefstrVecRef {
138
    pub ptr: *const Refstr,
139
    pub len: usize,
140
}
141

            
142
impl Clone for RefstrVecRef {
143
    fn clone(&self) -> Self {
144
        Self {
145
            ptr: self.ptr,
146
            len: self.len,
147
        }
148
    }
149
}
150

            
151
impl fmt::Debug for RefstrVecRef {
152
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153
        self.as_slice().fmt(f)
154
    }
155
}
156

            
157
impl RefstrVecRef {
158
    #[must_use]
159
5
    pub const fn as_slice(&self) -> &[Refstr] {
160
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
161
5
        if self.ptr.is_null() || self.len == 0 {
162
4
            return &[];
163
1
        }
164
1
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
165
5
    }
166
}
167

            
168
impl From<&[Refstr]> for RefstrVecRef {
169
2
    fn from(s: &[Refstr]) -> Self {
170
2
        Self {
171
2
            ptr: s.as_ptr(),
172
2
            len: s.len(),
173
2
        }
174
2
    }
175
}
176

            
177
/// FFI-safe wrapper for `&mut [GLint64]`.
178
#[repr(C)]
179
pub struct GLint64VecRefMut {
180
    pub ptr: *mut i64,
181
    pub len: usize,
182
}
183

            
184
impl Clone for GLint64VecRefMut {
185
    fn clone(&self) -> Self {
186
        Self {
187
            ptr: self.ptr,
188
            len: self.len,
189
        }
190
    }
191
}
192

            
193
impl fmt::Debug for GLint64VecRefMut {
194
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195
        self.as_slice().fmt(f)
196
    }
197
}
198

            
199
impl From<&mut [GLint64]> for GLint64VecRefMut {
200
1
    fn from(s: &mut [GLint64]) -> Self {
201
1
        Self {
202
1
            ptr: s.as_mut_ptr(),
203
1
            len: s.len(),
204
1
        }
205
1
    }
206
}
207

            
208
impl GLint64VecRefMut {
209
    #[must_use]
210
2
    pub const fn as_slice(&self) -> &[GLint64] {
211
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
212
2
        if self.ptr.is_null() || self.len == 0 {
213
1
            return &[];
214
1
        }
215
1
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
216
2
    }
217
3
    const fn as_mut_slice(&mut self) -> &mut [GLint64] {
218
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
219
3
        if self.ptr.is_null() || self.len == 0 {
220
1
            return &mut [];
221
2
        }
222
2
        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
223
3
    }
224
}
225

            
226
/// FFI-safe wrapper for `&mut [GLfloat]`.
227
#[repr(C)]
228
pub struct GLfloatVecRefMut {
229
    pub ptr: *mut f32,
230
    pub len: usize,
231
}
232

            
233
impl Clone for GLfloatVecRefMut {
234
    fn clone(&self) -> Self {
235
        Self {
236
            ptr: self.ptr,
237
            len: self.len,
238
        }
239
    }
240
}
241

            
242
impl fmt::Debug for GLfloatVecRefMut {
243
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244
        self.as_slice().fmt(f)
245
    }
246
}
247

            
248
impl From<&mut [GLfloat]> for GLfloatVecRefMut {
249
2
    fn from(s: &mut [GLfloat]) -> Self {
250
2
        Self {
251
2
            ptr: s.as_mut_ptr(),
252
2
            len: s.len(),
253
2
        }
254
2
    }
255
}
256

            
257
impl GLfloatVecRefMut {
258
    #[must_use]
259
1
    pub const fn as_slice(&self) -> &[GLfloat] {
260
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
261
1
        if self.ptr.is_null() || self.len == 0 {
262
1
            return &[];
263
        }
264
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
265
1
    }
266
4
    const fn as_mut_slice(&mut self) -> &mut [GLfloat] {
267
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
268
4
        if self.ptr.is_null() || self.len == 0 {
269
2
            return &mut [];
270
2
        }
271
2
        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
272
4
    }
273
}
274

            
275
/// FFI-safe wrapper for `&mut [GLint]`.
276
#[repr(C)]
277
pub struct GLintVecRefMut {
278
    pub ptr: *mut i32,
279
    pub len: usize,
280
}
281

            
282
impl Clone for GLintVecRefMut {
283
    fn clone(&self) -> Self {
284
        Self {
285
            ptr: self.ptr,
286
            len: self.len,
287
        }
288
    }
289
}
290

            
291
impl fmt::Debug for GLintVecRefMut {
292
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293
        self.as_slice().fmt(f)
294
    }
295
}
296

            
297
impl From<&mut [GLint]> for GLintVecRefMut {
298
10
    fn from(s: &mut [GLint]) -> Self {
299
10
        Self {
300
10
            ptr: s.as_mut_ptr(),
301
10
            len: s.len(),
302
10
        }
303
10
    }
304
}
305

            
306
impl GLintVecRefMut {
307
    #[must_use]
308
1
    pub const fn as_slice(&self) -> &[GLint] {
309
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
310
1
        if self.ptr.is_null() || self.len == 0 {
311
1
            return &[];
312
        }
313
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
314
1
    }
315
12
    const fn as_mut_slice(&mut self) -> &mut [GLint] {
316
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
317
12
        if self.ptr.is_null() || self.len == 0 {
318
2
            return &mut [];
319
10
        }
320
10
        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
321
12
    }
322
}
323

            
324
/// FFI-safe wrapper for `&[GLuint]`.
325
#[repr(C)]
326
pub struct GLuintVecRef {
327
    pub ptr: *const u32,
328
    pub len: usize,
329
}
330

            
331
impl Clone for GLuintVecRef {
332
    fn clone(&self) -> Self {
333
        Self {
334
            ptr: self.ptr,
335
            len: self.len,
336
        }
337
    }
338
}
339

            
340
impl fmt::Debug for GLuintVecRef {
341
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342
        self.as_slice().fmt(f)
343
    }
344
}
345

            
346
impl From<&[GLuint]> for GLuintVecRef {
347
36
    fn from(s: &[GLuint]) -> Self {
348
36
        Self {
349
36
            ptr: s.as_ptr(),
350
36
            len: s.len(),
351
36
        }
352
36
    }
353
}
354

            
355
impl GLuintVecRef {
356
    #[must_use]
357
43
    pub const fn as_slice(&self) -> &[GLuint] {
358
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
359
43
        if self.ptr.is_null() || self.len == 0 {
360
13
            return &[];
361
30
        }
362
30
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
363
43
    }
364
}
365

            
366
/// FFI-safe wrapper for `&[GLenum]`.
367
#[repr(C)]
368
pub struct GLenumVecRef {
369
    pub ptr: *const u32,
370
    pub len: usize,
371
}
372

            
373
impl Clone for GLenumVecRef {
374
    fn clone(&self) -> Self {
375
        Self {
376
            ptr: self.ptr,
377
            len: self.len,
378
        }
379
    }
380
}
381

            
382
impl fmt::Debug for GLenumVecRef {
383
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384
        self.as_slice().fmt(f)
385
    }
386
}
387

            
388
impl From<&[GLenum]> for GLenumVecRef {
389
2
    fn from(s: &[GLenum]) -> Self {
390
2
        Self {
391
2
            ptr: s.as_ptr(),
392
2
            len: s.len(),
393
2
        }
394
2
    }
395
}
396

            
397
impl GLenumVecRef {
398
    #[must_use]
399
4
    pub const fn as_slice(&self) -> &[GLenum] {
400
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
401
4
        if self.ptr.is_null() || self.len == 0 {
402
3
            return &[];
403
1
        }
404
1
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
405
4
    }
406
}
407

            
408
/// FFI-safe wrapper for `&[u8]`.
409
#[repr(C)]
410
pub struct U8VecRef {
411
    pub ptr: *const u8,
412
    pub len: usize,
413
}
414

            
415
impl Clone for U8VecRef {
416
1
    fn clone(&self) -> Self {
417
1
        Self {
418
1
            ptr: self.ptr,
419
1
            len: self.len,
420
1
        }
421
1
    }
422
}
423

            
424
impl From<&[u8]> for U8VecRef {
425
142
    fn from(s: &[u8]) -> Self {
426
142
        Self {
427
142
            ptr: s.as_ptr(),
428
142
            len: s.len(),
429
142
        }
430
142
    }
431
}
432

            
433
impl U8VecRef {
434
    #[must_use]
435
165
    pub const fn as_slice(&self) -> &[u8] {
436
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
437
165
        if self.ptr.is_null() || self.len == 0 {
438
91
            return &[];
439
74
        }
440
74
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
441
165
    }
442
}
443

            
444
impl fmt::Debug for U8VecRef {
445
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446
        self.as_slice().fmt(f)
447
    }
448
}
449

            
450
impl PartialOrd for U8VecRef {
451
1
    fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
452
1
        self.as_slice().partial_cmp(rhs.as_slice())
453
1
    }
454
}
455

            
456
impl Ord for U8VecRef {
457
3
    fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
458
3
        self.as_slice().cmp(rhs.as_slice())
459
3
    }
460
}
461

            
462
impl PartialEq for U8VecRef {
463
2
    fn eq(&self, rhs: &Self) -> bool {
464
2
        self.as_slice().eq(rhs.as_slice())
465
2
    }
466
}
467

            
468
impl Eq for U8VecRef {}
469

            
470
impl Hash for U8VecRef {
471
4
    fn hash<H>(&self, state: &mut H)
472
4
    where
473
4
        H: Hasher,
474
    {
475
4
        self.as_slice().hash(state);
476
4
    }
477
}
478

            
479
/// FFI-safe wrapper for `&[f32]`.
480
#[repr(C)]
481
pub struct F32VecRef {
482
    pub ptr: *const f32,
483
    pub len: usize,
484
}
485

            
486
impl Clone for F32VecRef {
487
    fn clone(&self) -> Self {
488
        Self {
489
            ptr: self.ptr,
490
            len: self.len,
491
        }
492
    }
493
}
494

            
495
impl fmt::Debug for F32VecRef {
496
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497
        self.as_slice().fmt(f)
498
    }
499
}
500

            
501
impl From<&[f32]> for F32VecRef {
502
1
    fn from(s: &[f32]) -> Self {
503
1
        Self {
504
1
            ptr: s.as_ptr(),
505
1
            len: s.len(),
506
1
        }
507
1
    }
508
}
509

            
510
impl F32VecRef {
511
    #[must_use]
512
2
    pub const fn as_slice(&self) -> &[f32] {
513
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
514
2
        if self.ptr.is_null() || self.len == 0 {
515
1
            return &[];
516
1
        }
517
1
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
518
2
    }
519
}
520

            
521
/// FFI-safe wrapper for `&[i32]`.
522
#[repr(C)]
523
pub struct I32VecRef {
524
    pub ptr: *const i32,
525
    pub len: usize,
526
}
527

            
528
impl Clone for I32VecRef {
529
    fn clone(&self) -> Self {
530
        Self {
531
            ptr: self.ptr,
532
            len: self.len,
533
        }
534
    }
535
}
536

            
537
impl fmt::Debug for I32VecRef {
538
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539
        self.as_slice().fmt(f)
540
    }
541
}
542

            
543
impl From<&[i32]> for I32VecRef {
544
1
    fn from(s: &[i32]) -> Self {
545
1
        Self {
546
1
            ptr: s.as_ptr(),
547
1
            len: s.len(),
548
1
        }
549
1
    }
550
}
551

            
552
impl I32VecRef {
553
    #[must_use]
554
2
    pub const fn as_slice(&self) -> &[i32] {
555
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
556
2
        if self.ptr.is_null() || self.len == 0 {
557
1
            return &[];
558
1
        }
559
1
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
560
2
    }
561
}
562

            
563
/// FFI-safe wrapper for `&mut [GLboolean]` (i.e. `&mut [u8]`).
564
#[repr(C)]
565
pub struct GLbooleanVecRefMut {
566
    pub ptr: *mut u8,
567
    pub len: usize,
568
}
569

            
570
impl Clone for GLbooleanVecRefMut {
571
    fn clone(&self) -> Self {
572
        Self {
573
            ptr: self.ptr,
574
            len: self.len,
575
        }
576
    }
577
}
578

            
579
impl fmt::Debug for GLbooleanVecRefMut {
580
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581
        self.as_slice().fmt(f)
582
    }
583
}
584

            
585
impl From<&mut [GLboolean]> for GLbooleanVecRefMut {
586
7
    fn from(s: &mut [GLboolean]) -> Self {
587
7
        Self {
588
7
            ptr: s.as_mut_ptr(),
589
7
            len: s.len(),
590
7
        }
591
7
    }
592
}
593

            
594
impl GLbooleanVecRefMut {
595
    #[must_use]
596
1
    pub const fn as_slice(&self) -> &[GLboolean] {
597
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
598
1
        if self.ptr.is_null() || self.len == 0 {
599
1
            return &[];
600
        }
601
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
602
1
    }
603
8
    const fn as_mut_slice(&mut self) -> &mut [GLboolean] {
604
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
605
8
        if self.ptr.is_null() || self.len == 0 {
606
1
            return &mut [];
607
7
        }
608
7
        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
609
8
    }
610
}
611

            
612
/// FFI-safe wrapper for `&mut [u8]`.
613
#[repr(C)]
614
pub struct U8VecRefMut {
615
    pub ptr: *mut u8,
616
    pub len: usize,
617
}
618

            
619
impl Clone for U8VecRefMut {
620
    fn clone(&self) -> Self {
621
        Self {
622
            ptr: self.ptr,
623
            len: self.len,
624
        }
625
    }
626
}
627

            
628
impl fmt::Debug for U8VecRefMut {
629
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630
        self.as_slice().fmt(f)
631
    }
632
}
633

            
634
impl From<&mut [u8]> for U8VecRefMut {
635
2
    fn from(s: &mut [u8]) -> Self {
636
2
        Self {
637
2
            ptr: s.as_mut_ptr(),
638
2
            len: s.len(),
639
2
        }
640
2
    }
641
}
642

            
643
impl U8VecRefMut {
644
    #[must_use]
645
1
    pub const fn as_slice(&self) -> &[u8] {
646
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
647
1
        if self.ptr.is_null() || self.len == 0 {
648
1
            return &[];
649
        }
650
        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
651
1
    }
652
4
    const fn as_mut_slice(&mut self) -> &mut [u8] {
653
        // AUDIT: `from_raw_parts` is UB on a null ptr; guard FFI null/empty.
654
4
        if self.ptr.is_null() || self.len == 0 {
655
2
            return &mut [];
656
2
        }
657
2
        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
658
4
    }
659
}
660

            
661
impl_option!(
662
    U8VecRef,
663
    OptionU8VecRef,
664
    copy = false,
665
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
666
);
667

            
668
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
669
#[repr(C)]
670
pub struct DebugMessage {
671
    pub message: AzString,
672
    pub source: GLenum,
673
    pub ty: GLenum,
674
    pub id: GLenum,
675
    pub severity: GLenum,
676
}
677

            
678
impl_option!(
679
    DebugMessage,
680
    OptionDebugMessage,
681
    copy = false,
682
    [Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash]
683
);
684

            
685
impl_vec!(
686
    DebugMessage,
687
    DebugMessageVec,
688
    DebugMessageVecDestructor,
689
    DebugMessageVecDestructorType,
690
    DebugMessageVecSlice,
691
    OptionDebugMessage
692
);
693
impl_vec_debug!(DebugMessage, DebugMessageVec);
694
impl_vec_partialord!(DebugMessage, DebugMessageVec);
695
impl_vec_ord!(DebugMessage, DebugMessageVec);
696
impl_vec_clone!(DebugMessage, DebugMessageVec, DebugMessageVecDestructor);
697
impl_vec_partialeq!(DebugMessage, DebugMessageVec);
698
impl_vec_eq!(DebugMessage, DebugMessageVec);
699
impl_vec_hash!(DebugMessage, DebugMessageVec);
700

            
701
impl_vec!(
702
    GLint,
703
    GLintVec,
704
    GLintVecDestructor,
705
    GLintVecDestructorType,
706
    GLintVecSlice,
707
    OptionI32
708
);
709
impl_vec_debug!(GLint, GLintVec);
710
impl_vec_partialord!(GLint, GLintVec);
711
impl_vec_ord!(GLint, GLintVec);
712
impl_vec_clone!(GLint, GLintVec, GLintVecDestructor);
713
impl_vec_partialeq!(GLint, GLintVec);
714
impl_vec_eq!(GLint, GLintVec);
715
impl_vec_hash!(GLint, GLintVec);
716

            
717
impl_vec!(
718
    GLuint,
719
    GLuintVec,
720
    GLuintVecDestructor,
721
    GLuintVecDestructorType,
722
    GLuintVecSlice,
723
    OptionU32
724
);
725
impl_vec_debug!(GLuint, GLuintVec);
726
impl_vec_partialord!(GLuint, GLuintVec);
727
impl_vec_ord!(GLuint, GLuintVec);
728
impl_vec_clone!(GLuint, GLuintVec, GLuintVecDestructor);
729
impl_vec_partialeq!(GLuint, GLuintVec);
730
impl_vec_eq!(GLuint, GLuintVec);
731
impl_vec_hash!(GLuint, GLuintVec);
732

            
733
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
734
#[repr(C)]
735
pub enum GlType {
736
    Gl,
737
    Gles,
738
}
739

            
740
impl From<GlContextGlType> for GlType {
741
4
    fn from(a: GlContextGlType) -> Self {
742
4
        match a {
743
3
            GlContextGlType::Gl => Self::Gl,
744
1
            GlContextGlType::GlEs => Self::Gles,
745
        }
746
4
    }
747
}
748

            
749
// (U8Vec, u32)
750
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
751
#[repr(C)]
752
// `_0`/`_1`… are C-ABI tuple-payload field names exposed in api.json; cannot rename.
753
#[allow(clippy::pub_underscore_fields)]
754
pub struct GetProgramBinaryReturn {
755
    pub _0: U8Vec,
756
    pub _1: u32,
757
}
758

            
759
// (i32, u32, AzString)
760
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
761
#[repr(C)]
762
// `_0`/`_1`… are C-ABI tuple-payload field names exposed in api.json; cannot rename.
763
#[allow(clippy::pub_underscore_fields)]
764
pub struct GetActiveAttribReturn {
765
    pub _0: i32,
766
    pub _1: u32,
767
    pub _2: AzString,
768
}
769

            
770
// (i32, u32, AzString)
771
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
772
#[repr(C)]
773
// `_0`/`_1`… are C-ABI tuple-payload field names exposed in api.json; cannot rename.
774
#[allow(clippy::pub_underscore_fields)]
775
pub struct GetActiveUniformReturn {
776
    pub _0: i32,
777
    pub _1: u32,
778
    pub _2: AzString,
779
}
780

            
781
#[repr(C)]
782
pub struct GLsyncPtr {
783
    pub ptr: *const c_void, /* *const __GLsync */
784
    pub run_destructor: bool,
785
}
786

            
787
impl Clone for GLsyncPtr {
788
2
    fn clone(&self) -> Self {
789
2
        Self {
790
2
            ptr: self.ptr,
791
2
            run_destructor: true,
792
2
        }
793
2
    }
794
}
795

            
796
impl fmt::Debug for GLsyncPtr {
797
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798
1
        write!(f, "0x{:0x}", self.ptr as usize)
799
1
    }
800
}
801

            
802
impl GLsyncPtr {
803
    #[must_use]
804
2
    pub const fn new(p: GLsync) -> Self {
805
2
        Self {
806
2
            ptr: p,
807
2
            run_destructor: true,
808
2
        }
809
2
    }
810
    #[must_use]
811
2
    pub fn get(self) -> GLsync {
812
2
        self.ptr as GLsync
813
2
    }
814
}
815

            
816
impl Drop for GLsyncPtr {
817
4
    fn drop(&mut self) {
818
4
        self.run_destructor = false;
819
4
    }
820
}
821

            
822
/// Each pipeline (window) has its own OpenGL textures. GL Textures can technically
823
/// be shared across pipelines, however this turns out to be very difficult in practice.
824
pub type GlTextureStorage = OrderedMap<Epoch, OrderedMap<ExternalImageId, Texture>>;
825

            
826
/// Non-cleaned up textures. When a `GlTexture` is registered, it has to stay active as long
827
/// as `WebRender` needs it for drawing. To transparently do this, we store the epoch that the
828
/// texture was originally created with, and check, **after we have drawn the frame**,
829
/// if there are any textures that need cleanup.
830
///
831
/// Because the Texture2d is wrapped in an Rc, the destructor (which cleans up the OpenGL
832
/// texture) does not run until we remove the textures
833
///
834
/// Note: Because textures could be used after the current draw call (ex. for scrolling),
835
/// the `ACTIVE_GL_TEXTURES` are indexed by their epoch. Use `renderer.flush_pipeline_info()`
836
/// to see which textures are still active and which ones can be safely removed.
837
///
838
/// See: <https://github.com/servo/webrender/issues/2940>
839
///
840
/// WARNING: Not thread-safe (however, the Texture itself is thread-unsafe, so it's unlikely to ever
841
/// be misused)
842
static mut ACTIVE_GL_TEXTURES: Option<OrderedMap<DocumentId, GlTextureStorage>> = None;
843

            
844
/// Sound accessor for the process-global GL texture table.
845
///
846
/// AUDIT: GL access is single-threaded by design (see the WARNING above — the
847
/// `Texture` itself is thread-unsafe), so no lock is used. The soundness fix
848
/// here is to never form an *implicit* reference to the `static mut` (the
849
/// edition-2024 `static_mut_refs` hard error + `&mut`-aliasing UB that
850
/// `ACTIVE_GL_TEXTURES.as_mut()` / `.as_ref()` triggered). Deriving the
851
/// reference from `&raw mut` gives it correct provenance without ever naming
852
/// the static as an auto-ref place. Callers must not hold two of these at once
853
/// (they don't — every use is a single non-reentrant scope).
854
#[inline]
855
#[allow(clippy::deref_addrof)] // the `&raw mut` deref is deliberate: it avoids naming the static as
856
                               // an auto-ref place (edition-2024 `static_mut_refs`)
857
33
fn active_gl_textures() -> &'static mut Option<OrderedMap<DocumentId, GlTextureStorage>> {
858
    // SAFETY: `&raw mut` avoids an intermediate `&mut ACTIVE_GL_TEXTURES`; the
859
    // static is valid for the whole program. Single-threaded access (GL thread).
860
33
    unsafe { &mut *(&raw mut ACTIVE_GL_TEXTURES) }
861
33
}
862

            
863
/// Inserts a new texture into the OpenGL texture cache, returns a new image ID
864
/// for the inserted texture
865
///
866
/// This function exists so azul doesn't have to use `lazy_static` as a dependency
867
///
868
/// # Panics
869
///
870
/// Panics if the global active-GL-texture table has not been initialized.
871
#[must_use]
872
5
pub fn insert_into_active_gl_textures(
873
5
    document_id: DocumentId,
874
5
    epoch: Epoch,
875
5
    texture: Texture,
876
5
) -> ExternalImageId {
877
5
    let external_image_id = ExternalImageId::new();
878

            
879
5
    let active = active_gl_textures();
880
5
    if active.is_none() {
881
1
        *active = Some(OrderedMap::new());
882
4
    }
883
5
    let active_textures = active.as_mut().unwrap();
884
5
    let active_epochs = active_textures.entry(document_id).or_default();
885
5
    let active_textures_for_epoch = active_epochs.entry(epoch).or_default();
886
5
    active_textures_for_epoch.insert(external_image_id, texture);
887

            
888
5
    external_image_id
889
5
}
890

            
891
/// Destroys all textures from the given `document_id`
892
/// where the texture is **older** than the given `epoch`.
893
3
pub fn gl_textures_remove_epochs_from_pipeline(document_id: &DocumentId, epoch: Epoch) {
894
    // TODO: Handle overflow of Epochs correctly (low priority)
895
3
    let Some(active_textures) = active_gl_textures().as_mut() else {
896
1
        return;
897
    };
898

            
899
2
    let Some(active_epochs) = active_textures.get_mut(document_id) else {
900
1
        return;
901
    };
902

            
903
    // NOTE: original code used retain() but that
904
    // doesn't work on no_std
905
1
    let mut epochs_to_remove = Vec::new();
906

            
907
2
    for (gl_texture_epoch, _) in active_epochs.iter() {
908
2
        if *gl_texture_epoch < epoch {
909
1
            epochs_to_remove.push(*gl_texture_epoch);
910
1
        }
911
    }
912

            
913
2
    for epoch in epochs_to_remove {
914
1
        active_epochs.remove(&epoch);
915
1
    }
916
3
}
917

            
918
// document_id, epoch, external_image_id
919
#[must_use]
920
5
pub fn remove_single_texture_from_active_gl_textures(
921
5
    document_id: &DocumentId,
922
5
    epoch: &Epoch,
923
5
    external_image_id: &ExternalImageId,
924
5
) -> Option<()> {
925
5
    let active_textures = active_gl_textures().as_mut()?;
926
4
    let epochs = active_textures.get_mut(document_id)?;
927
3
    let images_in_epoch = epochs.get_mut(epoch)?;
928
2
    images_in_epoch.remove(external_image_id);
929
2
    Some(())
930
5
}
931

            
932
/// Removes a `DocumentId` from the active epochs
933
2
pub fn gl_textures_remove_active_pipeline(document_id: &DocumentId) {
934
2
    let Some(active_textures) = active_gl_textures().as_mut() else {
935
1
        return;
936
    };
937
1
    active_textures.remove(document_id);
938
2
}
939

            
940
/// Destroys all textures, usually done before destroying the OpenGL context
941
#[allow(clippy::cast_precision_loss)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
942
                                      // types
943
4
pub fn gl_textures_clear_opengl_cache() {
944
4
    *active_gl_textures() = None;
945
4
}
946

            
947
// Search all epoch hash maps for the given key
948
// There does not seem to be a way to get the epoch for the key,
949
// so we simply have to search all active epochs
950
//
951
// NOTE: Invalid textures can be generated on minimize / maximize
952
// Luckily, webrender simply ignores an invalid texture, so we don't
953
// need to check whether a window is maximized or minimized - if
954
// we encounter an invalid ID, webrender simply won't draw anything,
955
// but at least it won't crash. Usually invalid textures are also 0x0
956
// pixels large - so it's not like we had anything to draw anyway.
957
#[allow(clippy::cast_precision_loss)] // OpenGL/graphics binding: GL-bounded numeric casts
958
#[must_use]
959
14
pub fn get_opengl_texture(image_key: &ExternalImageId) -> Option<(GLuint, (f32, f32))> {
960
14
    let active_textures = active_gl_textures().as_ref()?;
961
12
    active_textures
962
12
        .values()
963
12
        .flat_map(|active_document| active_document.values())
964
14
        .find_map(|active_epoch| active_epoch.get(image_key))
965
12
        .map(|tex| {
966
7
            (
967
7
                tex.texture_id,
968
7
                (tex.size.width as f32, tex.size.height as f32),
969
7
            )
970
7
        })
971
14
}
972

            
973
/// For .`get_gl_precision_format()`, but ABI-safe - returning an array or a tuple is not ABI-safe
974
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
975
#[repr(C)]
976
// `_0`/`_1`… are C-ABI tuple-payload field names exposed in api.json; cannot rename.
977
#[allow(clippy::pub_underscore_fields)]
978
pub struct GlShaderPrecisionFormatReturn {
979
    pub _0: GLint,
980
    pub _1: GLint,
981
    pub _2: GLint,
982
}
983

            
984
#[repr(C)]
985
pub struct GlContextPtr {
986
    /// `ManuallyDrop` so the owned `Box` is freed ONLY when `run_destructor` is
987
    /// still set (see `Drop`). The codegen FFI wrappers (`AzTexture` etc.) embed
988
    /// this by value AND have their own `Drop` that `drop_in_place`s the real
989
    /// type first; Rust's drop glue would then drop this field a SECOND time on
990
    /// the same bytes. Gating the `Box` free on `run_destructor` (which the first
991
    /// drop clears in the shared memory) makes that second drop a safe no-op.
992
    /// Layout is unchanged: `ManuallyDrop<Box<T>>` is a single pointer, identical
993
    /// to the old `Box<T>` and to the FFI `*mut c_void`.
994
    pub ptr: ManuallyDrop<Box<Rc<GlContextPtrInner>>>,
995
    /// Whether to force a hardware or software renderer
996
    pub renderer_type: RendererType,
997
    pub run_destructor: bool,
998
}
999

            
impl Clone for GlContextPtr {
53
    fn clone(&self) -> Self {
53
        Self {
53
            ptr: ManuallyDrop::new((*self.ptr).clone()),
53
            renderer_type: self.renderer_type,
53
            run_destructor: true,
53
        }
53
    }
}
impl Drop for GlContextPtr {
275
    fn drop(&mut self) {
        // Only free the owned Box if this instance still owns it. The FFI wrapper
        // double-drop (see the struct doc) hits these same bytes a second time
        // with `run_destructor` already cleared by the first drop -> no-op, no
        // double-free.
275
        if self.run_destructor {
275
            self.run_destructor = false;
275
            unsafe {
275
                ManuallyDrop::drop(&mut self.ptr);
275
            }
        }
275
    }
}
impl GlContextPtr {
    #[must_use]
2
    pub fn get_svg_shader(&self) -> GLuint {
2
        self.ptr.svg_shader
2
    }
    /// Whether this hardware GL context proved usable at construction (the SVG
    /// shaders compiled+linked at some GLSL version). `false` means context
    /// creation succeeded but the driver can't run our shaders -- the caller
    /// should fall back to CPU rendering. Always `false` for a Software context
    /// (which never compiles these shaders); only meaningful on the GPU path.
    #[must_use]
2
    pub fn is_gl_usable(&self) -> bool {
2
        self.ptr.svg_shader != 0
2
    }
    /// The GLSL `#version` the driver accepted at construction (e.g. "150" or
    /// "300 es"), discovered by the probe. Empty string if the context is
    /// unusable / software. Exposed in the API so apps can report/branch on it.
    #[must_use]
2
    pub fn get_usable_glsl_version(&self) -> AzString {
2
        self.ptr.glsl_version.clone()
2
    }
    /// Soft-brush shader program for the GPU painting API (0 if unusable).
    #[must_use]
16
    pub fn get_brush_shader(&self) -> GLuint {
16
        self.ptr.brush_shader
16
    }
    #[must_use]
2
    pub fn get_fxaa_shader(&self) -> GLuint {
2
        self.ptr.fxaa_shader
2
    }
}
#[repr(C)]
pub struct GlContextPtrInner {
    pub ptr: Rc<GenericGlContext>,
    /// SVG shader program (library-internal use)
    pub svg_shader: GLuint,
    /// SVG multicolor shader program (library-internal use)
    pub svg_multicolor_shader: GLuint,
    /// FXAA shader program (library-internal use)
    pub fxaa_shader: GLuint,
    /// Soft-brush shader program for the GPU painting API (0 if unusable).
    pub brush_shader: GLuint,
    /// The GLSL `#version` directive that compiled (e.g. "150" or "300 es"),
    /// discovered by the probe in `new()`. Empty if the context is unusable.
    pub glsl_version: AzString,
}
impl fmt::Debug for GlContextPtrInner {
    // `ptr` wraps the external GL context (not Debug); show the rest.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlContextPtrInner")
            .field("svg_shader", &self.svg_shader)
            .field("svg_multicolor_shader", &self.svg_multicolor_shader)
            .field("fxaa_shader", &self.fxaa_shader)
            .field("brush_shader", &self.brush_shader)
            .field("glsl_version", &self.glsl_version)
            .finish_non_exhaustive()
    }
}
impl Drop for GlContextPtrInner {
222
    fn drop(&mut self) {
222
        self.ptr.delete_program(self.svg_shader);
222
        self.ptr.delete_program(self.svg_multicolor_shader);
222
        self.ptr.delete_program(self.fxaa_shader);
222
        if self.brush_shader != 0 {
            self.ptr.delete_program(self.brush_shader);
222
        }
222
    }
}
impl_option!(
    GlContextPtr,
    OptionGlContextPtr,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord]
);
impl fmt::Debug for GlContextPtr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{:0x}", self.as_usize())
    }
}
static SVG_VERTEX_SHADER: &[u8] = b"#version 150
#if __VERSION__ != 100
    #define varying out
    #define attribute in
#endif
uniform vec2 vBboxSize;
uniform mat4 vTransformMatrix;
attribute vec2 vAttrXY;
void main() {
    vec4 vTransposed = vec4(vAttrXY, 1.0, 1.0) * vTransformMatrix;
    vec2 vTransposedInScreen = vTransposed.xy / vBboxSize;
    vec2 vCalcFinal = (vTransposedInScreen * vec2(2.0)) - vec2(1.0);
    gl_Position = vec4(vCalcFinal, 1.0, 1.0);
}";
static SVG_FRAGMENT_SHADER: &[u8] = b"#version 150
precision highp float;
uniform vec4 fDrawColor;
#if __VERSION__ == 100
    #define oFragColor gl_FragColor
#else
    out vec4 oFragColor;
#endif
void main() {
    oFragColor = fDrawColor;
}";
static SVG_MULTICOLOR_VERTEX_SHADER: &[u8] = b"#version 150
#if __VERSION__ != 100
    #define varying out
    #define attribute in
#endif
uniform vec2 vBboxSize;
uniform mat4 vTransformMatrix;
attribute vec3 vAttrXY;
attribute vec4 vColor;
varying vec4 fColor;
void main() {
    vec4 vTransposed = vec4(vAttrXY.xy, 1.0, 1.0) * vTransformMatrix;
    vec2 vTransposedInScreen = vTransposed.xy / vBboxSize;
    vec2 vCalcFinal = (vTransposedInScreen * vec2(2.0)) - vec2(1.0);
    gl_Position = vec4(vCalcFinal, vAttrXY.z, 1.0);
    fColor = vColor;
}";
static SVG_MULTICOLOR_FRAGMENT_SHADER: &[u8] = b"#version 150
precision highp float;
#if __VERSION__ != 100
    #define varying in
#endif
#if __VERSION__ == 100
    #define oFragColor gl_FragColor
#else
    out vec4 oFragColor;
#endif
varying vec4 fColor;
void main() {
    oFragColor = fColor;
}";
// Soft-brush shaders for the GPU painting API. A unit quad [-1,1]^2 (aUv) is
// positioned in NDC (aPos); the fragment computes the same radial falloff as
// the CPU `brush_dab_coverage` (1 - smoothstep(hardness, 1, dist)) so GPU and
// CPU strokes match. Version-agnostic via `__VERSION__` like the SVG shaders.
static BRUSH_VERTEX_SHADER: &[u8] = b"#version 150
#if __VERSION__ != 100
    #define varying out
    #define attribute in
#endif
attribute vec2 aPos;
attribute vec2 aUv;
varying vec2 vUv;
void main() {
    vUv = aUv;
    gl_Position = vec4(aPos, 0.0, 1.0);
}";
static BRUSH_FRAGMENT_SHADER: &[u8] = b"#version 150
precision highp float;
#if __VERSION__ != 100
    #define varying in
#endif
#if __VERSION__ == 100
    #define oFragColor gl_FragColor
#else
    out vec4 oFragColor;
#endif
uniform vec4 uColor;     // rgb + alpha (alpha already folds in flow * color.a)
uniform float uHardness; // 0 = soft .. 1 = hard edge
varying vec2 vUv;
void main() {
    float d = length(vUv);
    if (d > 1.0) { discard; }
    float edge0 = clamp(uHardness, 0.0, 1.0);
    float x = clamp((d - edge0) / max(1.0 - edge0, 1.0e-4), 0.0, 1.0);
    float cov = 1.0 - (x * x * (3.0 - 2.0 * x));
    oFragColor = vec4(uColor.rgb, uColor.a * cov);
}";
/// Checks if a shader compiled successfully. Logs an error under `std`.
/// (Retained for diagnostics; the version probe in `GlContextPtr::new` now does
/// its own status checks.)
#[allow(dead_code)]
#[allow(clippy::used_underscore_binding)] // intentional `_`-prefix (FFI/api.json pub field, or cfg-gated binding); access is deliberate
#[allow(clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
                                     // types
fn check_shader_compile(gl_context: &GenericGlContext, shader: GLuint, _label: &str) {
    let mut status = [0_i32];
    unsafe { gl_context.get_shader_iv(shader, gl::COMPILE_STATUS, &mut status) };
    if status[0] != gl::TRUE as i32 {
        #[cfg(feature = "std")]
        {
            let log = gl_context.get_shader_info_log(shader);
            eprintln!("azul: {_label} shader compile error: {log}");
        }
    }
}
/// Checks if a program linked successfully. Logs an error under `std`.
#[allow(dead_code)]
#[allow(clippy::used_underscore_binding)] // intentional `_`-prefix (FFI/api.json pub field, or cfg-gated binding); access is deliberate
#[allow(clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
                                     // types
fn check_program_link(gl_context: &GenericGlContext, program: GLuint, _label: &str) {
    let mut status = [0_i32];
    unsafe { gl_context.get_program_iv(program, gl::LINK_STATUS, &mut status) };
    if status[0] != gl::TRUE as i32 {
        #[cfg(feature = "std")]
        {
            let log = gl_context.get_program_info_log(program);
            eprintln!("azul: {_label} program link error: {log}");
        }
    }
}
/// Swap the leading `#version ...` line of a bundled shader for `version_line`
/// (which must include the trailing newline). The shader bodies branch on
/// `__VERSION__`, so only the directive needs to change between GL and GLES.
#[cfg(feature = "std")]
15
fn shader_with_glsl_version(src: &[u8], version_line: &[u8]) -> Vec<u8> {
147
    let body_start = src.iter().position(|&b| b == b'\n').map_or(0, |i| i + 1);
15
    let mut out = Vec::with_capacity(version_line.len() + src.len() - body_start);
15
    out.extend_from_slice(version_line);
15
    out.extend_from_slice(&src[body_start..]);
15
    out
15
}
/// Try to compile+link a vertex+fragment program at a specific GLSL `#version`.
/// Returns the linked program id, or `None` (after cleanup) on ANY compile or
/// link failure. This is how we PROVE a GL context is actually usable and which
/// `#version` its driver accepts -- creating a context can succeed yet leave it
/// unable to compile our shaders (broken driver, or a GLES context that rejects
/// the desktop `#version 150`).
#[cfg(feature = "std")]
// OpenGL binding: gl::* enum constants passed to the gl API as GLint/GLenum.
#[allow(clippy::cast_possible_wrap)]
3
fn try_compile_program(
3
    gl_context: &GenericGlContext,
3
    vert_src: &[u8],
3
    frag_src: &[u8],
3
    version_line: &[u8],
3
    attribs: &[(u32, &str)],
3
) -> Option<GLuint> {
3
    let vs = gl_context.create_shader(gl::VERTEX_SHADER);
3
    gl_context.shader_source(
3
        vs,
3
        &[shader_with_glsl_version(vert_src, version_line).as_slice()],
    );
3
    gl_context.compile_shader(vs);
3
    let fs = gl_context.create_shader(gl::FRAGMENT_SHADER);
3
    gl_context.shader_source(
3
        fs,
3
        &[shader_with_glsl_version(frag_src, version_line).as_slice()],
    );
3
    gl_context.compile_shader(fs);
3
    let mut s = [0_i32];
3
    unsafe { gl_context.get_shader_iv(vs, gl::COMPILE_STATUS, &mut s) };
3
    let vs_ok = s[0] == gl::TRUE as i32;
3
    unsafe { gl_context.get_shader_iv(fs, gl::COMPILE_STATUS, &mut s) };
3
    let fs_ok = s[0] == gl::TRUE as i32;
3
    if !vs_ok || !fs_ok {
3
        gl_context.delete_shader(vs);
3
        gl_context.delete_shader(fs);
3
        return None;
    }
    let prog = gl_context.create_program();
    gl_context.attach_shader(prog, vs);
    gl_context.attach_shader(prog, fs);
    for (loc, name) in attribs {
        gl_context.bind_attrib_location(prog, *loc, name);
    }
    gl_context.link_program(prog);
    gl_context.delete_shader(vs);
    gl_context.delete_shader(fs);
    let mut l = [0_i32];
    unsafe { gl_context.get_program_iv(prog, gl::LINK_STATUS, &mut l) };
    if l[0] == gl::TRUE as i32 {
        Some(prog)
    } else {
        gl_context.delete_program(prog);
        None
    }
3
}
/// GLSL `#version` directives to try, in preference order, per context type.
/// The first that compiles+links the SVG shaders is used for every program.
9
const fn glsl_version_candidates(gl_type: GlType) -> &'static [&'static [u8]] {
9
    match gl_type {
4
        GlType::Gl => &[b"#version 150\n", b"#version 330\n", b"#version 140\n"],
5
        GlType::Gles => &[b"#version 300 es\n", b"#version 100\n"],
    }
9
}
impl GlContextPtr {
    #[must_use]
222
    pub fn new(renderer_type: RendererType, gl_context: Rc<GenericGlContext>) -> Self {
        // Only attempt the SVG/FXAA GL shaders for a real GPU. In Software/CPU
        // mode nothing composites through them.
        //
        // PROVE the context is usable rather than trusting context creation: try
        // compiling the SVG program at each candidate `#version` for this context
        // type (desktop GL 1.50/3.30/1.40, or GLES 3.00/1.00) and use the first
        // that compiles+links for ALL programs. A GLES GPU (mobile) rejects the
        // desktop `#version 150`, and a broken driver rejects everything -- in the
        // latter case all program IDs stay 0 and `is_gl_usable()` returns false so
        // the window can fall back to CPU rendering.
        #[cfg(feature = "std")]
        let (
222
            svg_program_id,
222
            svg_multicolor_program_id,
222
            fxaa_program_id,
222
            brush_program_id,
222
            glsl_version,
222
        ) = if matches!(renderer_type, RendererType::Hardware) {
            use crate::gl_fxaa::{FXAA_FRAGMENT_SHADER, FXAA_VERTEX_SHADER};
1
            let gl_type: GlType = gl_context.get_type().into();
            // Probe via the SVG program; the first version that links wins.
1
            let mut svg = 0;
1
            let mut chosen: Option<&'static [u8]> = None;
3
            for ver in glsl_version_candidates(gl_type) {
3
                if let Some(p) = try_compile_program(
3
                    &gl_context,
3
                    SVG_VERTEX_SHADER,
3
                    SVG_FRAGMENT_SHADER,
3
                    ver,
3
                    &[(0, "vAttrXY")],
3
                ) {
                    svg = p;
                    chosen = Some(ver);
                    break;
3
                }
            }
1
            chosen.map_or_else(
1
                || {
1
                    eprintln!(
1
                        "azul: GL context UNUSABLE -- no GLSL version ({gl_type:?}) compiled the \
1
                         SVG shaders; the window should fall back to CPU rendering \
1
                         (is_gl_usable()=false)"
                    );
1
                    (0, 0, 0, 0, AzString::from_const_str(""))
1
                },
                |ver| {
                    // "150" / "300 es": the directive minus "#version " and newline.
                    let ver_str: AzString = core::str::from_utf8(ver)
                        .unwrap_or("")
                        .trim()
                        .trim_start_matches("#version ")
                        .into();
                    eprintln!(
                        "azul: GL usable -- shaders compiled at GLSL {} ({:?})",
                        ver_str.as_str(),
                        gl_type
                    );
                    let mc = try_compile_program(
                        &gl_context,
                        SVG_MULTICOLOR_VERTEX_SHADER,
                        SVG_MULTICOLOR_FRAGMENT_SHADER,
                        ver,
                        &[(0, "vAttrXY"), (1, "vColor")],
                    )
                    .unwrap_or(0);
                    let fxaa = try_compile_program(
                        &gl_context,
                        FXAA_VERTEX_SHADER,
                        FXAA_FRAGMENT_SHADER,
                        ver,
                        &[(0, "vAttrXY")],
                    )
                    .unwrap_or(0);
                    let brush = try_compile_program(
                        &gl_context,
                        BRUSH_VERTEX_SHADER,
                        BRUSH_FRAGMENT_SHADER,
                        ver,
                        &[(0, "aPos"), (1, "aUv")],
                    )
                    .unwrap_or(0);
                    (svg, mc, fxaa, brush, ver_str)
                },
            )
        } else {
221
            (0, 0, 0, 0, AzString::from_const_str(""))
        };
        // no_std build keeps the original behavior (no probe / no shaders).
        #[cfg(not(feature = "std"))]
        let (
            svg_program_id,
            svg_multicolor_program_id,
            fxaa_program_id,
            brush_program_id,
            glsl_version,
        ) = (0u32, 0u32, 0u32, 0u32, AzString::from_const_str(""));
222
        Self {
222
            ptr: ManuallyDrop::new(Box::new(Rc::new(GlContextPtrInner {
222
                svg_shader: svg_program_id,
222
                svg_multicolor_shader: svg_multicolor_program_id,
222
                fxaa_shader: fxaa_program_id,
222
                brush_shader: brush_program_id,
222
                glsl_version,
222
                ptr: gl_context,
222
            }))),
222
            renderer_type,
222
            run_destructor: true,
222
        }
222
    }
    #[must_use]
458
    pub fn get(&self) -> &Rc<GenericGlContext> {
458
        &self.ptr.ptr
458
    }
18
    fn as_usize(&self) -> usize {
18
        (Rc::as_ptr(&self.ptr.ptr) as *const c_void) as usize
18
    }
}
// This impl is the OpenGL API wrapper: every method mirrors a C/gleam GL call and
// takes the C-ABI argument types (GlVoidPtrConst, *VecRef, …) BY VALUE to match that
// ABI/FFI calling convention. Switching them to references would break the contract,
// so needless_pass_by_value is allowed for the whole GL-binding impl.
#[allow(clippy::needless_pass_by_value)]
impl GlContextPtr {
    #[must_use]
1
    pub fn get_type(&self) -> GlType {
1
        self.get().get_type().into()
1
    }
1
    pub fn buffer_data_untyped(
1
        &self,
1
        target: GLenum,
1
        size: GLsizeiptr,
1
        data: GlVoidPtrConst,
1
        usage: GLenum,
1
    ) {
1
        self.get()
1
            .buffer_data_untyped(target, size, data.ptr, usage);
1
    }
16
    pub fn buffer_sub_data_untyped(
16
        &self,
16
        target: GLenum,
16
        offset: isize,
16
        size: GLsizeiptr,
16
        data: GlVoidPtrConst,
16
    ) {
16
        self.get()
16
            .buffer_sub_data_untyped(target, offset, size, data.ptr);
16
    }
    #[must_use]
    pub fn map_buffer(&self, target: GLenum, access: GLbitfield) -> GlVoidPtrMut {
        GlVoidPtrMut {
            ptr: self.get().map_buffer(target, access),
        }
    }
    #[must_use]
16
    pub fn map_buffer_range(
16
        &self,
16
        target: GLenum,
16
        offset: GLintptr,
16
        length: GLsizeiptr,
16
        access: GLbitfield,
16
    ) -> GlVoidPtrMut {
16
        GlVoidPtrMut {
16
            ptr: self.get().map_buffer_range(target, offset, length, access),
16
        }
16
    }
    #[must_use]
1
    pub fn unmap_buffer(&self, target: GLenum) -> GLboolean {
1
        self.get().unmap_buffer(target)
1
    }
    pub fn tex_buffer(&self, target: GLenum, internal_format: GLenum, buffer: GLuint) {
        self.get().tex_buffer(target, internal_format, buffer);
    }
2
    pub fn shader_source(&self, shader: GLuint, strings: StringVec) {
4
        fn str_to_bytes(input: &str) -> Vec<u8> {
4
            let mut v: Vec<u8> = input.into();
4
            v.push(0);
4
            v
4
        }
2
        let shaders_as_bytes = strings
2
            .iter()
4
            .map(|s| str_to_bytes(s.as_str()))
2
            .collect::<Vec<_>>();
2
        let shaders_as_bytes = shaders_as_bytes
2
            .iter()
2
            .map(AsRef::as_ref)
2
            .collect::<Vec<_>>();
2
        self.get().shader_source(shader, &shaders_as_bytes);
2
    }
    pub fn read_buffer(&self, mode: GLenum) {
        self.get().read_buffer(mode);
    }
2
    pub fn read_pixels_into_buffer(
2
        &self,
2
        x: GLint,
2
        y: GLint,
2
        width: GLsizei,
2
        height: GLsizei,
2
        format: GLenum,
2
        pixel_type: GLenum,
2
        mut dst_buffer: U8VecRefMut,
2
    ) {
2
        self.get().read_pixels_into_buffer(
2
            x,
2
            y,
2
            width,
2
            height,
2
            format,
2
            pixel_type,
2
            dst_buffer.as_mut_slice(),
2
        );
2
    }
    #[must_use]
2
    pub fn read_pixels(
2
        &self,
2
        x: GLint,
2
        y: GLint,
2
        width: GLsizei,
2
        height: GLsizei,
2
        format: GLenum,
2
        pixel_type: GLenum,
2
    ) -> U8Vec {
        // gl-context-loader's own read_pixels sizes the buffer as
        // width*height*bytes_per_component and OMITS the format's channel count, so a
        // 2x3 RGBA/UNSIGNED_BYTE read allocates 6 bytes instead of 24 — a heap overflow
        // once a real driver writes the pixels. Size it correctly from format + type and
        // read into our own buffer. (Raw GL enum values so this doesn't depend on which
        // constants the gl module happens to re-export.)
2
        let channels: usize = match format {
            // RED, ALPHA, LUMINANCE, DEPTH_COMPONENT, STENCIL_INDEX, RED_INTEGER
            0x1903 | 0x1906 | 0x1909 | 0x1902 | 0x1901 | 0x8D94 => 1,
            // RG, LUMINANCE_ALPHA, RG_INTEGER, DEPTH_STENCIL
            0x8227 | 0x190A | 0x8228 | 0x84F9 => 2,
            // RGB, BGR, RGB_INTEGER
            0x1907 | 0x80E0 | 0x8D98 => 3,
            // RGBA, BGRA, RGBA_INTEGER, and a conservative default
2
            _ => 4,
        };
2
        let bytes_per_component: usize = match pixel_type {
2
            0x1400 | 0x1401 => 1,          // BYTE, UNSIGNED_BYTE
            0x1402 | 0x1403 | 0x140B => 2, // SHORT, UNSIGNED_SHORT, HALF_FLOAT
            _ => 4,                        // INT, UNSIGNED_INT, FLOAT, and default
        };
        // width/height are clamped to >= 0 before the cast, so no sign is lost.
        #[allow(clippy::cast_sign_loss)]
2
        let len = (width.max(0) as usize)
2
            .saturating_mul(height.max(0) as usize)
2
            .saturating_mul(channels)
2
            .saturating_mul(bytes_per_component);
2
        let mut buf = vec![0u8; len];
2
        self.get().read_pixels_into_buffer(
2
            x,
2
            y,
2
            width,
2
            height,
2
            format,
2
            pixel_type,
2
            buf.as_mut_slice(),
2
        );
2
        buf.into()
2
    }
    pub fn read_pixels_into_pbo(
        &self,
        x: GLint,
        y: GLint,
        width: GLsizei,
        height: GLsizei,
        format: GLenum,
        pixel_type: GLenum,
    ) {
        unsafe {
            self.get()
                .read_pixels_into_pbo(x, y, width, height, format, pixel_type);
        }
    }
16
    pub fn sample_coverage(&self, value: GLclampf, invert: bool) {
16
        self.get().sample_coverage(value, invert);
16
    }
8
    pub fn polygon_offset(&self, factor: GLfloat, units: GLfloat) {
8
        self.get().polygon_offset(factor, units);
8
    }
2
    pub fn pixel_store_i(&self, name: GLenum, param: GLint) {
2
        self.get().pixel_store_i(name, param);
2
    }
    #[must_use]
5
    pub fn gen_buffers(&self, n: GLsizei) -> GLuintVec {
5
        self.get().gen_buffers(n).into()
5
    }
    #[must_use]
5
    pub fn gen_renderbuffers(&self, n: GLsizei) -> GLuintVec {
5
        self.get().gen_renderbuffers(n).into()
5
    }
    #[must_use]
7
    pub fn gen_framebuffers(&self, n: GLsizei) -> GLuintVec {
7
        self.get().gen_framebuffers(n).into()
7
    }
    #[must_use]
5
    pub fn gen_textures(&self, n: GLsizei) -> GLuintVec {
5
        self.get().gen_textures(n).into()
5
    }
    #[must_use]
6
    pub fn gen_vertex_arrays(&self, n: GLsizei) -> GLuintVec {
6
        self.get().gen_vertex_arrays(n).into()
6
    }
    #[must_use]
5
    pub fn gen_queries(&self, n: GLsizei) -> GLuintVec {
5
        self.get().gen_queries(n).into()
5
    }
    pub fn begin_query(&self, target: GLenum, id: GLuint) {
        self.get().begin_query(target, id);
    }
    pub fn end_query(&self, target: GLenum) {
        self.get().end_query(target);
    }
    pub fn query_counter(&self, id: GLuint, target: GLenum) {
        self.get().query_counter(id, target);
    }
    #[must_use]
    pub fn get_query_object_iv(&self, id: GLuint, pname: GLenum) -> i32 {
        self.get().get_query_object_iv(id, pname)
    }
    #[must_use]
    pub fn get_query_object_uiv(&self, id: GLuint, pname: GLenum) -> u32 {
        self.get().get_query_object_uiv(id, pname)
    }
    #[must_use]
    pub fn get_query_object_i64v(&self, id: GLuint, pname: GLenum) -> i64 {
        self.get().get_query_object_i64v(id, pname)
    }
    #[must_use]
    pub fn get_query_object_ui64v(&self, id: GLuint, pname: GLenum) -> u64 {
        self.get().get_query_object_ui64v(id, pname)
    }
2
    pub fn delete_queries(&self, queries: GLuintVecRef) {
2
        self.get().delete_queries(queries.as_slice());
2
    }
5
    pub fn delete_vertex_arrays(&self, vertex_arrays: GLuintVecRef) {
5
        self.get().delete_vertex_arrays(vertex_arrays.as_slice());
5
    }
5
    pub fn delete_buffers(&self, buffers: GLuintVecRef) {
5
        self.get().delete_buffers(buffers.as_slice());
5
    }
2
    pub fn delete_renderbuffers(&self, renderbuffers: GLuintVecRef) {
2
        self.get().delete_renderbuffers(renderbuffers.as_slice());
2
    }
2
    pub fn delete_framebuffers(&self, framebuffers: GLuintVecRef) {
2
        self.get().delete_framebuffers(framebuffers.as_slice());
2
    }
25
    pub fn delete_textures(&self, textures: GLuintVecRef) {
25
        self.get().delete_textures(textures.as_slice());
25
    }
    pub fn framebuffer_renderbuffer(
        &self,
        target: GLenum,
        attachment: GLenum,
        renderbuffertarget: GLenum,
        renderbuffer: GLuint,
    ) {
        self.get()
            .framebuffer_renderbuffer(target, attachment, renderbuffertarget, renderbuffer);
    }
    pub fn renderbuffer_storage(
        &self,
        target: GLenum,
        internalformat: GLenum,
        width: GLsizei,
        height: GLsizei,
    ) {
        self.get()
            .renderbuffer_storage(target, internalformat, width, height);
    }
    pub fn depth_func(&self, func: GLenum) {
        self.get().depth_func(func);
    }
    pub fn active_texture(&self, texture: GLenum) {
        self.get().active_texture(texture);
    }
    pub fn attach_shader(&self, program: GLuint, shader: GLuint) {
        self.get().attach_shader(program, shader);
    }
    pub fn bind_attrib_location(&self, program: GLuint, index: GLuint, name: &str) {
        self.get().bind_attrib_location(program, index, name);
    }
2
    pub fn get_uniform_iv(&self, program: GLuint, location: GLint, mut result: GLintVecRefMut) {
2
        unsafe {
2
            self.get()
2
                .get_uniform_iv(program, location, result.as_mut_slice());
2
        }
2
    }
2
    pub fn get_uniform_fv(&self, program: GLuint, location: GLint, mut result: GLfloatVecRefMut) {
2
        unsafe {
2
            self.get()
2
                .get_uniform_fv(program, location, result.as_mut_slice());
2
        }
2
    }
    #[must_use]
    pub fn get_uniform_block_index(&self, program: GLuint, name: &str) -> GLuint {
        self.get().get_uniform_block_index(program, name)
    }
    #[must_use]
2
    pub fn get_uniform_indices(&self, program: GLuint, names: RefstrVecRef) -> GLuintVec {
2
        let names_vec = names
2
            .as_slice()
2
            .iter()
2
            .map(Refstr::as_str)
2
            .collect::<Vec<_>>();
2
        self.get().get_uniform_indices(program, &names_vec).into()
2
    }
    pub fn bind_buffer_base(&self, target: GLenum, index: GLuint, buffer: GLuint) {
        self.get().bind_buffer_base(target, index, buffer);
    }
    pub fn bind_buffer_range(
        &self,
        target: GLenum,
        index: GLuint,
        buffer: GLuint,
        offset: GLintptr,
        size: GLsizeiptr,
    ) {
        self.get()
            .bind_buffer_range(target, index, buffer, offset, size);
    }
    pub fn uniform_block_binding(
        &self,
        program: GLuint,
        uniform_block_index: GLuint,
        uniform_block_binding: GLuint,
    ) {
        self.get()
            .uniform_block_binding(program, uniform_block_index, uniform_block_binding);
    }
    pub fn bind_buffer(&self, target: GLenum, buffer: GLuint) {
        self.get().bind_buffer(target, buffer);
    }
    pub fn bind_vertex_array(&self, vao: GLuint) {
        self.get().bind_vertex_array(vao);
    }
    pub fn bind_renderbuffer(&self, target: GLenum, renderbuffer: GLuint) {
        self.get().bind_renderbuffer(target, renderbuffer);
    }
    pub fn bind_framebuffer(&self, target: GLenum, framebuffer: GLuint) {
        self.get().bind_framebuffer(target, framebuffer);
    }
144
    pub fn bind_texture(&self, target: GLenum, texture: GLuint) {
144
        self.get().bind_texture(target, texture);
144
    }
2
    pub fn draw_buffers(&self, bufs: GLenumVecRef) {
2
        self.get().draw_buffers(bufs.as_slice());
2
    }
144
    pub fn tex_image_2d(
144
        &self,
144
        target: GLenum,
144
        level: GLint,
144
        internal_format: GLint,
144
        width: GLsizei,
144
        height: GLsizei,
144
        border: GLint,
144
        format: GLenum,
144
        ty: GLenum,
144
        opt_data: OptionU8VecRef,
144
    ) {
144
        let opt_data = opt_data.as_option();
144
        let opt_data: Option<&[u8]> = opt_data.map(U8VecRef::as_slice);
144
        self.get().tex_image_2d(
144
            target,
144
            level,
144
            internal_format,
144
            width,
144
            height,
144
            border,
144
            format,
144
            ty,
144
            opt_data,
144
        );
144
    }
    pub fn compressed_tex_image_2d(
        &self,
        target: GLenum,
        level: GLint,
        internal_format: GLenum,
        width: GLsizei,
        height: GLsizei,
        border: GLint,
        data: U8VecRef,
    ) {
        self.get().compressed_tex_image_2d(
            target,
            level,
            internal_format,
            width,
            height,
            border,
            data.as_slice(),
        );
    }
    pub fn compressed_tex_sub_image_2d(
        &self,
        target: GLenum,
        level: GLint,
        xoffset: GLint,
        yoffset: GLint,
        width: GLsizei,
        height: GLsizei,
        format: GLenum,
        data: U8VecRef,
    ) {
        self.get().compressed_tex_sub_image_2d(
            target,
            level,
            xoffset,
            yoffset,
            width,
            height,
            format,
            data.as_slice(),
        );
    }
    pub fn tex_image_3d(
        &self,
        target: GLenum,
        level: GLint,
        internal_format: GLint,
        width: GLsizei,
        height: GLsizei,
        depth: GLsizei,
        border: GLint,
        format: GLenum,
        ty: GLenum,
        opt_data: OptionU8VecRef,
    ) {
        let opt_data = opt_data.as_option();
        let opt_data: Option<&[u8]> = opt_data.map(U8VecRef::as_slice);
        self.get().tex_image_3d(
            target,
            level,
            internal_format,
            width,
            height,
            depth,
            border,
            format,
            ty,
            opt_data,
        );
    }
    pub fn copy_tex_image_2d(
        &self,
        target: GLenum,
        level: GLint,
        internal_format: GLenum,
        x: GLint,
        y: GLint,
        width: GLsizei,
        height: GLsizei,
        border: GLint,
    ) {
        self.get()
            .copy_tex_image_2d(target, level, internal_format, x, y, width, height, border);
    }
    pub fn copy_tex_sub_image_2d(
        &self,
        target: GLenum,
        level: GLint,
        xoffset: GLint,
        yoffset: GLint,
        x: GLint,
        y: GLint,
        width: GLsizei,
        height: GLsizei,
    ) {
        self.get()
            .copy_tex_sub_image_2d(target, level, xoffset, yoffset, x, y, width, height);
    }
    pub fn copy_tex_sub_image_3d(
        &self,
        target: GLenum,
        level: GLint,
        xoffset: GLint,
        yoffset: GLint,
        zoffset: GLint,
        x: GLint,
        y: GLint,
        width: GLsizei,
        height: GLsizei,
    ) {
        self.get().copy_tex_sub_image_3d(
            target, level, xoffset, yoffset, zoffset, x, y, width, height,
        );
    }
    pub fn tex_sub_image_2d(
        &self,
        target: GLenum,
        level: GLint,
        xoffset: GLint,
        yoffset: GLint,
        width: GLsizei,
        height: GLsizei,
        format: GLenum,
        ty: GLenum,
        data: U8VecRef,
    ) {
        self.get().tex_sub_image_2d(
            target,
            level,
            xoffset,
            yoffset,
            width,
            height,
            format,
            ty,
            data.as_slice(),
        );
    }
3
    pub fn tex_sub_image_2d_pbo(
3
        &self,
3
        target: GLenum,
3
        level: GLint,
3
        xoffset: GLint,
3
        yoffset: GLint,
3
        width: GLsizei,
3
        height: GLsizei,
3
        format: GLenum,
3
        ty: GLenum,
3
        offset: usize,
3
    ) {
3
        self.get().tex_sub_image_2d_pbo(
3
            target, level, xoffset, yoffset, width, height, format, ty, offset,
3
        );
3
    }
    pub fn tex_sub_image_3d(
        &self,
        target: GLenum,
        level: GLint,
        xoffset: GLint,
        yoffset: GLint,
        zoffset: GLint,
        width: GLsizei,
        height: GLsizei,
        depth: GLsizei,
        format: GLenum,
        ty: GLenum,
        data: U8VecRef,
    ) {
        self.get().tex_sub_image_3d(
            target,
            level,
            xoffset,
            yoffset,
            zoffset,
            width,
            height,
            depth,
            format,
            ty,
            data.as_slice(),
        );
    }
    pub fn tex_sub_image_3d_pbo(
        &self,
        target: GLenum,
        level: GLint,
        xoffset: GLint,
        yoffset: GLint,
        zoffset: GLint,
        width: GLsizei,
        height: GLsizei,
        depth: GLsizei,
        format: GLenum,
        ty: GLenum,
        offset: usize,
    ) {
        self.get().tex_sub_image_3d_pbo(
            target, level, xoffset, yoffset, zoffset, width, height, depth, format, ty, offset,
        );
    }
    pub fn tex_storage_2d(
        &self,
        target: GLenum,
        levels: GLint,
        internal_format: GLenum,
        width: GLsizei,
        height: GLsizei,
    ) {
        self.get()
            .tex_storage_2d(target, levels, internal_format, width, height);
    }
    pub fn tex_storage_3d(
        &self,
        target: GLenum,
        levels: GLint,
        internal_format: GLenum,
        width: GLsizei,
        height: GLsizei,
        depth: GLsizei,
    ) {
        self.get()
            .tex_storage_3d(target, levels, internal_format, width, height, depth);
    }
    pub fn get_tex_image_into_buffer(
        &self,
        target: GLenum,
        level: GLint,
        format: GLenum,
        ty: GLenum,
        mut output: U8VecRefMut,
    ) {
        self.get()
            .get_tex_image_into_buffer(target, level, format, ty, output.as_mut_slice());
    }
    pub fn copy_image_sub_data(
        &self,
        src_name: GLuint,
        src_target: GLenum,
        src_level: GLint,
        src_x: GLint,
        src_y: GLint,
        src_z: GLint,
        dst_name: GLuint,
        dst_target: GLenum,
        dst_level: GLint,
        dst_x: GLint,
        dst_y: GLint,
        dst_z: GLint,
        src_width: GLsizei,
        src_height: GLsizei,
        src_depth: GLsizei,
    ) {
        unsafe {
            self.get().copy_image_sub_data(
                src_name, src_target, src_level, src_x, src_y, src_z, dst_name, dst_target,
                dst_level, dst_x, dst_y, dst_z, src_width, src_height, src_depth,
            );
        }
    }
    pub fn invalidate_framebuffer(&self, target: GLenum, attachments: GLenumVecRef) {
        self.get()
            .invalidate_framebuffer(target, attachments.as_slice());
    }
    pub fn invalidate_sub_framebuffer(
        &self,
        target: GLenum,
        attachments: GLenumVecRef,
        xoffset: GLint,
        yoffset: GLint,
        width: GLsizei,
        height: GLsizei,
    ) {
        self.get().invalidate_sub_framebuffer(
            target,
            attachments.as_slice(),
            xoffset,
            yoffset,
            width,
            height,
        );
    }
8
    pub fn get_integer_v(&self, name: GLenum, mut result: GLintVecRefMut) {
8
        unsafe { self.get().get_integer_v(name, result.as_mut_slice()) }
8
    }
    pub fn get_integer_64v(&self, name: GLenum, mut result: GLint64VecRefMut) {
        unsafe { self.get().get_integer_64v(name, result.as_mut_slice()) }
    }
    pub fn get_integer_iv(&self, name: GLenum, index: GLuint, mut result: GLintVecRefMut) {
        unsafe {
            self.get()
                .get_integer_iv(name, index, result.as_mut_slice());
        }
    }
    pub fn get_integer_64iv(&self, name: GLenum, index: GLuint, mut result: GLint64VecRefMut) {
        unsafe {
            self.get()
                .get_integer_64iv(name, index, result.as_mut_slice());
        }
    }
6
    pub fn get_boolean_v(&self, name: GLenum, mut result: GLbooleanVecRefMut) {
6
        unsafe { self.get().get_boolean_v(name, result.as_mut_slice()) }
6
    }
    pub fn get_float_v(&self, name: GLenum, mut result: GLfloatVecRefMut) {
        unsafe { self.get().get_float_v(name, result.as_mut_slice()) }
    }
    #[must_use]
    pub fn get_framebuffer_attachment_parameter_iv(
        &self,
        target: GLenum,
        attachment: GLenum,
        pname: GLenum,
    ) -> GLint {
        self.get()
            .get_framebuffer_attachment_parameter_iv(target, attachment, pname)
    }
    #[must_use]
    pub fn get_renderbuffer_parameter_iv(&self, target: GLenum, pname: GLenum) -> GLint {
        self.get().get_renderbuffer_parameter_iv(target, pname)
    }
    #[must_use]
    pub fn get_tex_parameter_iv(&self, target: GLenum, name: GLenum) -> GLint {
        self.get().get_tex_parameter_iv(target, name)
    }
    #[must_use]
    pub fn get_tex_parameter_fv(&self, target: GLenum, name: GLenum) -> GLfloat {
        self.get().get_tex_parameter_fv(target, name)
    }
    pub fn tex_parameter_i(&self, target: GLenum, pname: GLenum, param: GLint) {
        self.get().tex_parameter_i(target, pname, param);
    }
    pub fn tex_parameter_f(&self, target: GLenum, pname: GLenum, param: GLfloat) {
        self.get().tex_parameter_f(target, pname, param);
    }
    pub fn framebuffer_texture_2d(
        &self,
        target: GLenum,
        attachment: GLenum,
        textarget: GLenum,
        texture: GLuint,
        level: GLint,
    ) {
        self.get()
            .framebuffer_texture_2d(target, attachment, textarget, texture, level);
    }
    pub fn framebuffer_texture_layer(
        &self,
        target: GLenum,
        attachment: GLenum,
        texture: GLuint,
        level: GLint,
        layer: GLint,
    ) {
        self.get()
            .framebuffer_texture_layer(target, attachment, texture, level, layer);
    }
    #[allow(clippy::similar_names)] // domain-standard coordinate/control-point names
    pub fn blit_framebuffer(
        &self,
        src_x0: GLint,
        src_y0: GLint,
        src_x1: GLint,
        src_y1: GLint,
        dst_x0: GLint,
        dst_y0: GLint,
        dst_x1: GLint,
        dst_y1: GLint,
        mask: GLbitfield,
        filter: GLenum,
    ) {
        self.get().blit_framebuffer(
            src_x0, src_y0, src_x1, src_y1, dst_x0, dst_y0, dst_x1, dst_y1, mask, filter,
        );
    }
    pub fn vertex_attrib_4f(&self, index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {
        self.get().vertex_attrib_4f(index, x, y, z, w);
    }
    pub fn vertex_attrib_pointer_f32(
        &self,
        index: GLuint,
        size: GLint,
        normalized: bool,
        stride: GLsizei,
        offset: GLuint,
    ) {
        self.get()
            .vertex_attrib_pointer_f32(index, size, normalized, stride, offset);
    }
    pub fn vertex_attrib_pointer(
        &self,
        index: GLuint,
        size: GLint,
        type_: GLenum,
        normalized: bool,
        stride: GLsizei,
        offset: GLuint,
    ) {
        self.get()
            .vertex_attrib_pointer(index, size, type_, normalized, stride, offset);
    }
    pub fn vertex_attrib_i_pointer(
        &self,
        index: GLuint,
        size: GLint,
        type_: GLenum,
        stride: GLsizei,
        offset: GLuint,
    ) {
        self.get()
            .vertex_attrib_i_pointer(index, size, type_, stride, offset);
    }
    pub fn vertex_attrib_divisor(&self, index: GLuint, divisor: GLuint) {
        self.get().vertex_attrib_divisor(index, divisor);
    }
    pub fn viewport(&self, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {
        self.get().viewport(x, y, width, height);
    }
    pub fn scissor(&self, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {
        self.get().scissor(x, y, width, height);
    }
    pub fn line_width(&self, width: GLfloat) {
        self.get().line_width(width);
    }
    pub fn use_program(&self, program: GLuint) {
        self.get().use_program(program);
    }
    pub fn validate_program(&self, program: GLuint) {
        self.get().validate_program(program);
    }
    pub fn draw_arrays(&self, mode: GLenum, first: GLint, count: GLsizei) {
        self.get().draw_arrays(mode, first, count);
    }
    pub fn draw_arrays_instanced(
        &self,
        mode: GLenum,
        first: GLint,
        count: GLsizei,
        primcount: GLsizei,
    ) {
        self.get()
            .draw_arrays_instanced(mode, first, count, primcount);
    }
    pub fn draw_elements(
        &self,
        mode: GLenum,
        count: GLsizei,
        element_type: GLenum,
        indices_offset: GLuint,
    ) {
        self.get()
            .draw_elements(mode, count, element_type, indices_offset);
    }
    pub fn draw_elements_instanced(
        &self,
        mode: GLenum,
        count: GLsizei,
        element_type: GLenum,
        indices_offset: GLuint,
        primcount: GLsizei,
    ) {
        self.get()
            .draw_elements_instanced(mode, count, element_type, indices_offset, primcount);
    }
    pub fn blend_color(&self, r: f32, g: f32, b: f32, a: f32) {
        self.get().blend_color(r, g, b, a);
    }
    pub fn blend_func(&self, sfactor: GLenum, dfactor: GLenum) {
        self.get().blend_func(sfactor, dfactor);
    }
    pub fn blend_func_separate(
        &self,
        src_rgb: GLenum,
        dest_rgb: GLenum,
        src_alpha: GLenum,
        dest_alpha: GLenum,
    ) {
        self.get()
            .blend_func_separate(src_rgb, dest_rgb, src_alpha, dest_alpha);
    }
    pub fn blend_equation(&self, mode: GLenum) {
        self.get().blend_equation(mode);
    }
    pub fn blend_equation_separate(&self, mode_rgb: GLenum, mode_alpha: GLenum) {
        self.get().blend_equation_separate(mode_rgb, mode_alpha);
    }
    // mirrors glColorMask(GLboolean, GLboolean, GLboolean, GLboolean) — the four
    // RGBA write-mask flags are the GL API, not a refactorable bool soup.
    #[allow(clippy::fn_params_excessive_bools)]
    pub fn color_mask(&self, r: bool, g: bool, b: bool, a: bool) {
        self.get().color_mask(r, g, b, a);
    }
    pub fn cull_face(&self, mode: GLenum) {
        self.get().cull_face(mode);
    }
    pub fn front_face(&self, mode: GLenum) {
        self.get().front_face(mode);
    }
    pub fn enable(&self, cap: GLenum) {
        self.get().enable(cap);
    }
    pub fn disable(&self, cap: GLenum) {
        self.get().disable(cap);
    }
    pub fn hint(&self, param_name: GLenum, param_val: GLenum) {
        self.get().hint(param_name, param_val);
    }
    #[must_use]
    pub fn is_enabled(&self, cap: GLenum) -> GLboolean {
        self.get().is_enabled(cap)
    }
    #[must_use]
    pub fn is_shader(&self, shader: GLuint) -> GLboolean {
        self.get().is_shader(shader)
    }
    #[must_use]
    pub fn is_texture(&self, texture: GLenum) -> GLboolean {
        self.get().is_texture(texture)
    }
    #[must_use]
    pub fn is_framebuffer(&self, framebuffer: GLenum) -> GLboolean {
        self.get().is_framebuffer(framebuffer)
    }
    #[must_use]
    pub fn is_renderbuffer(&self, renderbuffer: GLenum) -> GLboolean {
        self.get().is_renderbuffer(renderbuffer)
    }
    #[must_use]
    pub fn check_frame_buffer_status(&self, target: GLenum) -> GLenum {
        self.get().check_frame_buffer_status(target)
    }
    pub fn enable_vertex_attrib_array(&self, index: GLuint) {
        self.get().enable_vertex_attrib_array(index);
    }
    pub fn disable_vertex_attrib_array(&self, index: GLuint) {
        self.get().disable_vertex_attrib_array(index);
    }
    pub fn uniform_1f(&self, location: GLint, v0: GLfloat) {
        self.get().uniform_1f(location, v0);
    }
    pub fn uniform_1fv(&self, location: GLint, values: F32VecRef) {
        self.get().uniform_1fv(location, values.as_slice());
    }
    pub fn uniform_1i(&self, location: GLint, v0: GLint) {
        self.get().uniform_1i(location, v0);
    }
    pub fn uniform_1iv(&self, location: GLint, values: I32VecRef) {
        self.get().uniform_1iv(location, values.as_slice());
    }
    pub fn uniform_1ui(&self, location: GLint, v0: GLuint) {
        self.get().uniform_1ui(location, v0);
    }
    pub fn uniform_2f(&self, location: GLint, v0: GLfloat, v1: GLfloat) {
        self.get().uniform_2f(location, v0, v1);
    }
    pub fn uniform_2fv(&self, location: GLint, values: F32VecRef) {
        self.get().uniform_2fv(location, values.as_slice());
    }
    pub fn uniform_2i(&self, location: GLint, v0: GLint, v1: GLint) {
        self.get().uniform_2i(location, v0, v1);
    }
    pub fn uniform_2iv(&self, location: GLint, values: I32VecRef) {
        self.get().uniform_2iv(location, values.as_slice());
    }
    pub fn uniform_2ui(&self, location: GLint, v0: GLuint, v1: GLuint) {
        self.get().uniform_2ui(location, v0, v1);
    }
    pub fn uniform_3f(&self, location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat) {
        self.get().uniform_3f(location, v0, v1, v2);
    }
    pub fn uniform_3fv(&self, location: GLint, values: F32VecRef) {
        self.get().uniform_3fv(location, values.as_slice());
    }
    pub fn uniform_3i(&self, location: GLint, v0: GLint, v1: GLint, v2: GLint) {
        self.get().uniform_3i(location, v0, v1, v2);
    }
    pub fn uniform_3iv(&self, location: GLint, values: I32VecRef) {
        self.get().uniform_3iv(location, values.as_slice());
    }
    pub fn uniform_3ui(&self, location: GLint, v0: GLuint, v1: GLuint, v2: GLuint) {
        self.get().uniform_3ui(location, v0, v1, v2);
    }
    pub fn uniform_4f(&self, location: GLint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {
        self.get().uniform_4f(location, x, y, z, w);
    }
    pub fn uniform_4i(&self, location: GLint, x: GLint, y: GLint, z: GLint, w: GLint) {
        self.get().uniform_4i(location, x, y, z, w);
    }
    pub fn uniform_4iv(&self, location: GLint, values: I32VecRef) {
        self.get().uniform_4iv(location, values.as_slice());
    }
    pub fn uniform_4ui(&self, location: GLint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) {
        self.get().uniform_4ui(location, x, y, z, w);
    }
    pub fn uniform_4fv(&self, location: GLint, values: F32VecRef) {
        self.get().uniform_4fv(location, values.as_slice());
    }
    pub fn uniform_matrix_2fv(&self, location: GLint, transpose: bool, value: F32VecRef) {
        self.get()
            .uniform_matrix_2fv(location, transpose, value.as_slice());
    }
    pub fn uniform_matrix_3fv(&self, location: GLint, transpose: bool, value: F32VecRef) {
        self.get()
            .uniform_matrix_3fv(location, transpose, value.as_slice());
    }
    pub fn uniform_matrix_4fv(&self, location: GLint, transpose: bool, value: F32VecRef) {
        self.get()
            .uniform_matrix_4fv(location, transpose, value.as_slice());
    }
    pub fn depth_mask(&self, flag: bool) {
        self.get().depth_mask(flag);
    }
    pub fn depth_range(&self, near: f64, far: f64) {
        self.get().depth_range(near, far);
    }
    #[must_use]
    pub fn get_active_attrib(&self, program: GLuint, index: GLuint) -> GetActiveAttribReturn {
        let r = self.get().get_active_attrib(program, index);
        GetActiveAttribReturn {
            _0: r.0,
            _1: r.1,
            _2: r.2.into(),
        }
    }
    #[must_use]
    pub fn get_active_uniform(&self, program: GLuint, index: GLuint) -> GetActiveUniformReturn {
        let r = self.get().get_active_uniform(program, index);
        GetActiveUniformReturn {
            _0: r.0,
            _1: r.1,
            _2: r.2.into(),
        }
    }
    #[must_use]
    pub fn get_active_uniforms_iv(
        &self,
        program: GLuint,
        indices: GLuintVec,
        pname: GLenum,
    ) -> GLintVec {
        self.get()
            .get_active_uniforms_iv(program, indices.into_library_owned_vec(), pname)
            .into()
    }
    #[must_use]
    pub fn get_active_uniform_block_i(
        &self,
        program: GLuint,
        index: GLuint,
        pname: GLenum,
    ) -> GLint {
        self.get().get_active_uniform_block_i(program, index, pname)
    }
    #[must_use]
    pub fn get_active_uniform_block_iv(
        &self,
        program: GLuint,
        index: GLuint,
        pname: GLenum,
    ) -> GLintVec {
        self.get()
            .get_active_uniform_block_iv(program, index, pname)
            .into()
    }
    #[must_use]
    pub fn get_active_uniform_block_name(&self, program: GLuint, index: GLuint) -> AzString {
        self.get()
            .get_active_uniform_block_name(program, index)
            .into()
    }
    #[must_use]
    pub fn get_attrib_location(&self, program: GLuint, name: &str) -> c_int {
        self.get().get_attrib_location(program, name)
    }
    #[must_use]
    pub fn get_frag_data_location(&self, program: GLuint, name: &str) -> c_int {
        self.get().get_frag_data_location(program, name)
    }
    #[must_use]
    pub fn get_uniform_location(&self, program: GLuint, name: &str) -> c_int {
        self.get().get_uniform_location(program, name)
    }
    #[must_use]
    pub fn get_program_info_log(&self, program: GLuint) -> AzString {
        self.get().get_program_info_log(program).into()
    }
    pub fn get_program_iv(&self, program: GLuint, pname: GLenum, mut result: GLintVecRefMut) {
        unsafe {
            self.get()
                .get_program_iv(program, pname, result.as_mut_slice());
        }
    }
    #[must_use]
    pub fn get_program_binary(&self, program: GLuint) -> GetProgramBinaryReturn {
        let r = self.get().get_program_binary(program);
        GetProgramBinaryReturn {
            _0: r.0.into(),
            _1: r.1,
        }
    }
    pub fn program_binary(&self, program: GLuint, format: GLenum, binary: U8VecRef) {
        self.get()
            .program_binary(program, format, binary.as_slice());
    }
    pub fn program_parameter_i(&self, program: GLuint, pname: GLenum, value: GLint) {
        self.get().program_parameter_i(program, pname, value);
    }
    pub fn get_vertex_attrib_iv(&self, index: GLuint, pname: GLenum, mut result: GLintVecRefMut) {
        unsafe {
            self.get()
                .get_vertex_attrib_iv(index, pname, result.as_mut_slice());
        }
    }
    pub fn get_vertex_attrib_fv(&self, index: GLuint, pname: GLenum, mut result: GLfloatVecRefMut) {
        unsafe {
            self.get()
                .get_vertex_attrib_fv(index, pname, result.as_mut_slice());
        }
    }
    #[must_use]
    pub fn get_vertex_attrib_pointer_v(&self, index: GLuint, pname: GLenum) -> GLsizeiptr {
        self.get().get_vertex_attrib_pointer_v(index, pname)
    }
    #[must_use]
    pub fn get_buffer_parameter_iv(&self, target: GLuint, pname: GLenum) -> GLint {
        self.get().get_buffer_parameter_iv(target, pname)
    }
    #[must_use]
    pub fn get_shader_info_log(&self, shader: GLuint) -> AzString {
        self.get().get_shader_info_log(shader).into()
    }
    #[must_use]
    pub fn get_string(&self, which: GLenum) -> AzString {
        self.get().get_string(which).into()
    }
    #[must_use]
    pub fn get_string_i(&self, which: GLenum, index: GLuint) -> AzString {
        self.get().get_string_i(which, index).into()
    }
    pub fn get_shader_iv(&self, shader: GLuint, pname: GLenum, mut result: GLintVecRefMut) {
        unsafe {
            self.get()
                .get_shader_iv(shader, pname, result.as_mut_slice());
        }
    }
    #[must_use]
    pub fn get_shader_precision_format(
        &self,
        shader_type: GLuint,
        precision_type: GLuint,
    ) -> GlShaderPrecisionFormatReturn {
        let r = self
            .get()
            .get_shader_precision_format(shader_type, precision_type);
        GlShaderPrecisionFormatReturn {
            _0: r.0,
            _1: r.1,
            _2: r.2,
        }
    }
    pub fn compile_shader(&self, shader: GLuint) {
        self.get().compile_shader(shader);
    }
    #[must_use]
    pub fn create_program(&self) -> GLuint {
        self.get().create_program()
    }
    pub fn delete_program(&self, program: GLuint) {
        self.get().delete_program(program);
    }
    #[must_use]
    pub fn create_shader(&self, shader_type: GLenum) -> GLuint {
        self.get().create_shader(shader_type)
    }
    pub fn delete_shader(&self, shader: GLuint) {
        self.get().delete_shader(shader);
    }
    pub fn detach_shader(&self, program: GLuint, shader: GLuint) {
        self.get().detach_shader(program, shader);
    }
    pub fn link_program(&self, program: GLuint) {
        self.get().link_program(program);
    }
    pub fn clear_color(&self, r: f32, g: f32, b: f32, a: f32) {
        self.get().clear_color(r, g, b, a);
    }
    pub fn clear(&self, buffer_mask: GLbitfield) {
        self.get().clear(buffer_mask);
    }
    pub fn clear_depth(&self, depth: f64) {
        self.get().clear_depth(depth);
    }
    pub fn clear_stencil(&self, s: GLint) {
        self.get().clear_stencil(s);
    }
    pub fn flush(&self) {
        self.get().flush();
    }
    pub fn finish(&self) {
        self.get().finish();
    }
    #[must_use]
    pub fn get_error(&self) -> GLenum {
        self.get().get_error()
    }
    pub fn stencil_mask(&self, mask: GLuint) {
        self.get().stencil_mask(mask);
    }
    pub fn stencil_mask_separate(&self, face: GLenum, mask: GLuint) {
        self.get().stencil_mask_separate(face, mask);
    }
    pub fn stencil_func(&self, func: GLenum, ref_: GLint, mask: GLuint) {
        self.get().stencil_func(func, ref_, mask);
    }
    pub fn stencil_func_separate(&self, face: GLenum, func: GLenum, ref_: GLint, mask: GLuint) {
        self.get().stencil_func_separate(face, func, ref_, mask);
    }
    pub fn stencil_op(&self, sfail: GLenum, dpfail: GLenum, dppass: GLenum) {
        self.get().stencil_op(sfail, dpfail, dppass);
    }
    pub fn stencil_op_separate(&self, face: GLenum, sfail: GLenum, dpfail: GLenum, dppass: GLenum) {
        self.get().stencil_op_separate(face, sfail, dpfail, dppass);
    }
    pub fn egl_image_target_texture2d_oes(&self, target: GLenum, image: GlVoidPtrConst) {
        self.get()
            .egl_image_target_texture2d_oes(target, image.ptr as *const c_void);
    }
    pub fn generate_mipmap(&self, target: GLenum) {
        self.get().generate_mipmap(target);
    }
    pub fn insert_event_marker_ext(&self, message: &str) {
        self.get().insert_event_marker_ext(message);
    }
    pub fn push_group_marker_ext(&self, message: &str) {
        self.get().push_group_marker_ext(message);
    }
    pub fn pop_group_marker_ext(&self) {
        self.get().pop_group_marker_ext();
    }
    pub fn debug_message_insert_khr(
        &self,
        source: GLenum,
        type_: GLenum,
        id: GLuint,
        severity: GLenum,
        message: &str,
    ) {
        self.get()
            .debug_message_insert_khr(source, type_, id, severity, message);
    }
    pub fn push_debug_group_khr(&self, source: GLenum, id: GLuint, message: &str) {
        self.get().push_debug_group_khr(source, id, message);
    }
    pub fn pop_debug_group_khr(&self) {
        self.get().pop_debug_group_khr();
    }
    #[must_use]
    pub fn fence_sync(&self, condition: GLenum, flags: GLbitfield) -> GLsyncPtr {
        GLsyncPtr::new(self.get().fence_sync(condition, flags))
    }
    #[must_use]
    pub fn client_wait_sync(&self, sync: GLsyncPtr, flags: GLbitfield, timeout: GLuint64) -> u32 {
        self.get().client_wait_sync(sync.get(), flags, timeout)
    }
    pub fn wait_sync(&self, sync: GLsyncPtr, flags: GLbitfield, timeout: GLuint64) {
        self.get().wait_sync(sync.get(), flags, timeout);
    }
    pub fn delete_sync(&self, sync: GLsyncPtr) {
        self.get().delete_sync(sync.get());
    }
    pub fn texture_range_apple(&self, target: GLenum, data: U8VecRef) {
        self.get().texture_range_apple(target, data.as_slice());
    }
    #[must_use]
    pub fn gen_fences_apple(&self, n: GLsizei) -> GLuintVec {
        self.get().gen_fences_apple(n).into()
    }
    pub fn delete_fences_apple(&self, fences: GLuintVecRef) {
        self.get().delete_fences_apple(fences.as_slice());
    }
    pub fn set_fence_apple(&self, fence: GLuint) {
        self.get().set_fence_apple(fence);
    }
    pub fn finish_fence_apple(&self, fence: GLuint) {
        self.get().finish_fence_apple(fence);
    }
    pub fn test_fence_apple(&self, fence: GLuint) {
        self.get().test_fence_apple(fence);
    }
    #[must_use]
    pub fn test_object_apple(&self, object: GLenum, name: GLuint) -> GLboolean {
        self.get().test_object_apple(object, name)
    }
    pub fn finish_object_apple(&self, object: GLenum, name: GLuint) {
        self.get().finish_object_apple(object, name);
    }
    #[must_use]
    pub fn get_frag_data_index(&self, program: GLuint, name: &str) -> GLint {
        self.get().get_frag_data_index(program, name)
    }
    pub fn blend_barrier_khr(&self) {
        self.get().blend_barrier_khr();
    }
    pub fn bind_frag_data_location_indexed(
        &self,
        program: GLuint,
        color_number: GLuint,
        index: GLuint,
        name: &str,
    ) {
        self.get()
            .bind_frag_data_location_indexed(program, color_number, index, name);
    }
    #[must_use]
    pub fn get_debug_messages(&self) -> DebugMessageVec {
        let dmv: Vec<DebugMessage> = self
            .get()
            .get_debug_messages()
            .into_iter()
            .map(|d| DebugMessage {
                message: d.message.into(),
                source: d.source,
                ty: d.ty,
                id: d.id,
                severity: d.severity,
            })
            .collect();
        dmv.into()
    }
    pub fn provoking_vertex_angle(&self, mode: GLenum) {
        self.get().provoking_vertex_angle(mode);
    }
    #[must_use]
    pub fn gen_vertex_arrays_apple(&self, n: GLsizei) -> GLuintVec {
        self.get().gen_vertex_arrays_apple(n).into()
    }
    pub fn bind_vertex_array_apple(&self, vao: GLuint) {
        self.get().bind_vertex_array_apple(vao);
    }
    pub fn delete_vertex_arrays_apple(&self, vertex_arrays: GLuintVecRef) {
        self.get()
            .delete_vertex_arrays_apple(vertex_arrays.as_slice());
    }
    pub fn copy_texture_chromium(
        &self,
        source_id: GLuint,
        source_level: GLint,
        dest_target: GLenum,
        dest_id: GLuint,
        dest_level: GLint,
        internal_format: GLint,
        dest_type: GLenum,
        unpack_flip_y: GLboolean,
        unpack_premultiply_alpha: GLboolean,
        unpack_unmultiply_alpha: GLboolean,
    ) {
        self.get().copy_texture_chromium(
            source_id,
            source_level,
            dest_target,
            dest_id,
            dest_level,
            internal_format,
            dest_type,
            unpack_flip_y,
            unpack_premultiply_alpha,
            unpack_unmultiply_alpha,
        );
    }
    pub fn copy_sub_texture_chromium(
        &self,
        source_id: GLuint,
        source_level: GLint,
        dest_target: GLenum,
        dest_id: GLuint,
        dest_level: GLint,
        x_offset: GLint,
        y_offset: GLint,
        x: GLint,
        y: GLint,
        width: GLsizei,
        height: GLsizei,
        unpack_flip_y: GLboolean,
        unpack_premultiply_alpha: GLboolean,
        unpack_unmultiply_alpha: GLboolean,
    ) {
        self.get().copy_sub_texture_chromium(
            source_id,
            source_level,
            dest_target,
            dest_id,
            dest_level,
            x_offset,
            y_offset,
            x,
            y,
            width,
            height,
            unpack_flip_y,
            unpack_premultiply_alpha,
            unpack_unmultiply_alpha,
        );
    }
    pub fn egl_image_target_renderbuffer_storage_oes(&self, target: u32, image: GlVoidPtrConst) {
        self.get()
            .egl_image_target_renderbuffer_storage_oes(target, image.ptr as *const c_void);
    }
    pub fn copy_texture_3d_angle(
        &self,
        source_id: GLuint,
        source_level: GLint,
        dest_target: GLenum,
        dest_id: GLuint,
        dest_level: GLint,
        internal_format: GLint,
        dest_type: GLenum,
        unpack_flip_y: GLboolean,
        unpack_premultiply_alpha: GLboolean,
        unpack_unmultiply_alpha: GLboolean,
    ) {
        self.get().copy_texture_3d_angle(
            source_id,
            source_level,
            dest_target,
            dest_id,
            dest_level,
            internal_format,
            dest_type,
            unpack_flip_y,
            unpack_premultiply_alpha,
            unpack_unmultiply_alpha,
        );
    }
    pub fn copy_sub_texture_3d_angle(
        &self,
        source_id: GLuint,
        source_level: GLint,
        dest_target: GLenum,
        dest_id: GLuint,
        dest_level: GLint,
        x_offset: GLint,
        y_offset: GLint,
        z_offset: GLint,
        x: GLint,
        y: GLint,
        z: GLint,
        width: GLsizei,
        height: GLsizei,
        depth: GLsizei,
        unpack_flip_y: GLboolean,
        unpack_premultiply_alpha: GLboolean,
        unpack_unmultiply_alpha: GLboolean,
    ) {
        self.get().copy_sub_texture_3d_angle(
            source_id,
            source_level,
            dest_target,
            dest_id,
            dest_level,
            x_offset,
            y_offset,
            z_offset,
            x,
            y,
            z,
            width,
            height,
            depth,
            unpack_flip_y,
            unpack_premultiply_alpha,
            unpack_unmultiply_alpha,
        );
    }
    pub fn buffer_storage(
        &self,
        target: GLenum,
        size: GLsizeiptr,
        data: GlVoidPtrConst,
        flags: GLbitfield,
    ) {
        self.get().buffer_storage(target, size, data.ptr, flags);
    }
    pub fn flush_mapped_buffer_range(&self, target: GLenum, offset: GLintptr, length: GLsizeiptr) {
        self.get().flush_mapped_buffer_range(target, offset, length);
    }
}
impl PartialEq for GlContextPtr {
3
    fn eq(&self, rhs: &Self) -> bool {
3
        self.as_usize().eq(&rhs.as_usize())
3
    }
}
impl Eq for GlContextPtr {}
impl PartialOrd for GlContextPtr {
2
    fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
2
        self.as_usize().partial_cmp(&rhs.as_usize())
2
    }
}
impl Ord for GlContextPtr {
4
    fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
4
        self.as_usize().cmp(&rhs.as_usize())
4
    }
}
/// Saved OpenGL state for save/restore around framebuffer operations.
/// Used by `Texture::clear()` and `GlShader::draw()` to avoid corrupting
/// the caller's GL state.
// the `current_` prefix is intentional: each field holds the saved CURRENT GL
// binding captured at save() to be restored in restore().
#[allow(clippy::struct_field_names)]
struct GlStateSave {
    current_multisample: [u8; 1],
    current_index_buffer: [i32; 1],
    current_vertex_buffer: [i32; 1],
    current_vertex_array_object: [i32; 1],
    current_program: [i32; 1],
    current_framebuffers: [i32; 1],
    current_renderbuffers: [i32; 1],
    current_texture_2d: [i32; 1],
}
impl GlStateSave {
1
    fn save(gl_context: &GlContextPtr) -> Self {
1
        let mut s = Self {
1
            current_multisample: [0],
1
            current_index_buffer: [0],
1
            current_vertex_buffer: [0],
1
            current_vertex_array_object: [0],
1
            current_program: [0],
1
            current_framebuffers: [0],
1
            current_renderbuffers: [0],
1
            current_texture_2d: [0],
1
        };
1
        gl_context.get_boolean_v(gl::MULTISAMPLE, (&mut s.current_multisample[..]).into());
1
        gl_context.get_integer_v(
            gl::ARRAY_BUFFER_BINDING,
1
            (&mut s.current_vertex_buffer[..]).into(),
        );
1
        gl_context.get_integer_v(
            gl::ELEMENT_ARRAY_BUFFER_BINDING,
1
            (&mut s.current_index_buffer[..]).into(),
        );
1
        gl_context.get_integer_v(gl::CURRENT_PROGRAM, (&mut s.current_program[..]).into());
1
        gl_context.get_integer_v(
            gl::VERTEX_ARRAY_BINDING,
1
            (&mut s.current_vertex_array_object[..]).into(),
        );
1
        gl_context.get_integer_v(gl::RENDERBUFFER, (&mut s.current_renderbuffers[..]).into());
1
        gl_context.get_integer_v(gl::FRAMEBUFFER, (&mut s.current_framebuffers[..]).into());
1
        gl_context.get_integer_v(gl::TEXTURE_2D, (&mut s.current_texture_2d[..]).into());
1
        s
1
    }
    // OpenGL binding: state values passed to the gl API as GLuint/GLsizei.
    #[allow(clippy::cast_sign_loss)]
    fn restore(&self, gl_context: &GlContextPtr) {
        if u32::from(self.current_multisample[0]) == gl::TRUE {
            gl_context.enable(gl::MULTISAMPLE);
        }
        gl_context.bind_framebuffer(gl::FRAMEBUFFER, self.current_framebuffers[0] as u32);
        gl_context.bind_texture(gl::TEXTURE_2D, self.current_texture_2d[0] as u32);
        gl_context.bind_buffer(gl::RENDERBUFFER, self.current_renderbuffers[0] as u32);
        gl_context.bind_vertex_array(self.current_vertex_array_object[0] as u32);
        gl_context.bind_buffer(
            gl::ELEMENT_ARRAY_BUFFER,
            self.current_index_buffer[0] as u32,
        );
        gl_context.bind_buffer(gl::ARRAY_BUFFER, self.current_vertex_buffer[0] as u32);
        gl_context.use_program(self.current_program[0] as u32);
    }
}
/// AUDIT: RAII guard that deletes a transient framebuffer + renderbuffer on
/// scope exit. Used by `Texture::clear` and `GlShader::draw` so that a panic
/// mid-path (e.g. an `.unwrap()` on an empty gen-list, or any GL step that
/// panics) can't leak the FBO/RBO. Ids of `0` are skipped (GL treats delete-0
/// as a no-op anyway, but this keeps intent explicit).
struct FboRboGuard<'a> {
    gl_context: &'a GlContextPtr,
    framebuffer_id: GLuint,
    renderbuffer_id: GLuint,
}
impl Drop for FboRboGuard<'_> {
    fn drop(&mut self) {
        if self.framebuffer_id != 0 {
            self.gl_context
                .delete_framebuffers((&[self.framebuffer_id])[..].into());
        }
        if self.renderbuffer_id != 0 {
            self.gl_context
                .delete_renderbuffers((&[self.renderbuffer_id])[..].into());
        }
    }
}
/// OpenGL texture, use `ReadOnlyWindow::create_texture` to create a texture
#[repr(C)]
pub struct Texture {
    /// A reference-counted pointer to the OpenGL context (so that the texture can be deleted in
    /// the destructor)
    pub gl_context: GlContextPtr,
    /// Raw OpenGL texture ID
    pub texture_id: GLuint,
    /// Reference count, shared across
    pub refcount: *const AtomicUsize,
    /// Size of this texture (in pixels)
    pub size: PhysicalSizeU32,
    /// Format of the texture (rgba8, brga8, etc.)
    pub format: RawImageFormat,
    /// Background color of this texture
    pub background_color: ColorU,
    /// Hints and flags for optimization purposes
    pub flags: TextureFlags,
    pub run_destructor: bool,
}
impl Clone for Texture {
    #[allow(clippy::cast_sign_loss)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
                                     // types
16
    fn clone(&self) -> Self {
16
        unsafe {
16
            (*self.refcount).fetch_add(1, AtomicOrdering::SeqCst);
16
        }
16
        Self {
16
            gl_context: self.gl_context.clone(),
16
            texture_id: self.texture_id,
16
            refcount: self.refcount,
16
            size: self.size,
16
            format: self.format,
16
            background_color: self.background_color,
16
            flags: self.flags,
16
            run_destructor: true,
16
        }
16
    }
}
impl_option!(
    Texture,
    OptionTexture,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl Texture {
    #[must_use]
22
    pub fn create(
22
        texture_id: GLuint,
22
        flags: TextureFlags,
22
        size: PhysicalSizeU32,
22
        background_color: ColorU,
22
        gl_context: GlContextPtr,
22
        format: RawImageFormat,
22
    ) -> Self {
22
        Self {
22
            texture_id,
22
            flags,
22
            size,
22
            background_color,
22
            gl_context,
22
            format,
22
            refcount: Box::into_raw(Box::new(AtomicUsize::new(1))),
22
            run_destructor: true,
22
        }
22
    }
    // OpenGL binding: gl::* enum constants and texture dimensions are passed as
    // GLint/GLsizei (i32); the values are GL-bounded and the `as i32` casts are the
    // idiomatic form for the gl API.
    #[allow(clippy::cast_possible_wrap)]
    #[allow(clippy::cast_sign_loss)] // OpenGL/graphics binding: GL-bounded numeric casts
    #[must_use]
    pub fn allocate_rgba8(
        gl_context: GlContextPtr,
        size: PhysicalSizeU32,
        background: ColorU,
    ) -> Self {
        let textures = gl_context.gen_textures(1);
        let texture_id = textures.as_ref()[0];
        let mut current_texture_2d = [0_i32];
        gl_context.get_integer_v(gl::TEXTURE_2D, (&mut current_texture_2d[..]).into());
        gl_context.bind_texture(gl::TEXTURE_2D, texture_id);
        gl_context.tex_image_2d(
            gl::TEXTURE_2D,
            0,
            gl::RGBA as i32,
            size.width as i32,
            size.height as i32,
            0,
            gl::RGBA,
            gl::UNSIGNED_BYTE,
            None.into(),
        );
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32);
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as i32);
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32);
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32);
        gl_context.bind_texture(gl::TEXTURE_2D, current_texture_2d[0] as u32);
        Self::create(
            texture_id,
            TextureFlags {
                is_opaque: false,
                is_video_texture: false,
            },
            size,
            background,
            gl_context,
            // Format is BGRA8 for WebRender integration, despite the GL upload using RGBA
            RawImageFormat::BGRA8,
        )
    }
    /// # Panics
    ///
    /// Panics if no framebuffer/depthbuffer was allocated (the GL object lists are empty).
    // OpenGL binding: gl::* enum constants and texture dimensions passed as
    // GLint/GLsizei (i32); values are GL-bounded, `as i32` is the idiomatic form.
    #[allow(clippy::cast_possible_wrap)]
1
    pub fn clear(&mut self) {
1
        let saved = GlStateSave::save(&self.gl_context);
1
        let framebuffers = self.gl_context.gen_framebuffers(1);
1
        let framebuffer_id = *framebuffers.get(0).unwrap();
        // AUDIT: register the FBO for cleanup BEFORE the next fallible step so a
        // panic in `gen_renderbuffers().get(0).unwrap()` can't leak it.
1
        let mut fbo_rbo_guard = FboRboGuard {
1
            gl_context: &self.gl_context,
1
            framebuffer_id,
1
            renderbuffer_id: 0,
1
        };
1
        self.gl_context
1
            .bind_framebuffer(gl::FRAMEBUFFER, framebuffer_id);
1
        let depthbuffers = self.gl_context.gen_renderbuffers(1);
1
        let depthbuffer_id = *depthbuffers.get(0).unwrap();
1
        fbo_rbo_guard.renderbuffer_id = depthbuffer_id;
1
        self.gl_context
1
            .bind_texture(gl::TEXTURE_2D, self.texture_id);
1
        self.gl_context.tex_image_2d(
            gl::TEXTURE_2D,
            0,
1
            gl::RGBA as i32, // NOT RGBA8 - will generate INVALID_ENUM!
1
            self.size.width as i32,
1
            self.size.height as i32,
            0,
            gl::RGBA, // gl::BGRA?
            gl::UNSIGNED_BYTE,
1
            None.into(),
        );
1
        self.gl_context
1
            .tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32);
1
        self.gl_context
1
            .tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as i32);
1
        self.gl_context.tex_parameter_i(
            gl::TEXTURE_2D,
            gl::TEXTURE_WRAP_S,
1
            gl::CLAMP_TO_EDGE as i32,
        );
1
        self.gl_context.tex_parameter_i(
            gl::TEXTURE_2D,
            gl::TEXTURE_WRAP_T,
1
            gl::CLAMP_TO_EDGE as i32,
        );
1
        self.gl_context
1
            .bind_renderbuffer(gl::RENDERBUFFER, depthbuffer_id);
1
        self.gl_context.renderbuffer_storage(
            gl::RENDERBUFFER,
            gl::DEPTH_COMPONENT,
1
            self.size.width as i32,
1
            self.size.height as i32,
        );
1
        self.gl_context.framebuffer_renderbuffer(
            gl::FRAMEBUFFER,
            gl::DEPTH_ATTACHMENT,
            gl::RENDERBUFFER,
1
            depthbuffer_id,
        );
1
        self.gl_context.framebuffer_texture_2d(
            gl::FRAMEBUFFER,
            gl::COLOR_ATTACHMENT0,
            gl::TEXTURE_2D,
1
            self.texture_id,
            0,
        );
1
        self.gl_context
1
            .draw_buffers([gl::COLOR_ATTACHMENT0][..].into());
1
        let clear_color: ColorF = self.background_color.into();
1
        self.gl_context
1
            .clear_color(clear_color.r, clear_color.g, clear_color.b, clear_color.a);
1
        self.gl_context.clear_depth(0.0);
1
        self.gl_context
1
            .clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
        // AUDIT: FBO/RBO deletion is handled by `fbo_rbo_guard`'s Drop (which
        // also runs on an unwinding panic), so we restore state and let the
        // guard reclaim the GL objects at scope exit.
1
        saved.restore(&self.gl_context);
1
        drop(fbo_rbo_guard);
1
    }
    #[must_use]
7
    pub fn get_descriptor(&self) -> ImageDescriptor {
7
        ImageDescriptor {
7
            format: self.format,
7
            width: self.size.width as usize,
7
            height: self.size.height as usize,
7
            stride: None.into(),
7
            offset: 0,
7
            flags: ImageDescriptorFlags {
7
                is_opaque: self.flags.is_opaque,
7
                // The texture gets mapped 1:1 onto the display, so there is no need for mipmaps
7
                allow_mipmaps: false,
7
            },
7
        }
7
    }
    /// Draws a `TessellatedGPUSvgNode` with the given color to the texture
    pub fn draw_tesselated_svg_gpu_node(
        &mut self,
        node: &TessellatedGPUSvgNode,
        size: PhysicalSizeU32,
        color: ColorU,
        transforms: StyleTransformVec,
    ) -> bool {
        node.draw(self, size, color, transforms)
    }
    /// Draws a `TessellatedColoredGPUSvgNode` to the texture
    pub fn draw_tesselated_colored_svg_gpu_node(
        &mut self,
        node: &crate::svg::TessellatedColoredGPUSvgNode,
        size: PhysicalSizeU32,
        transforms: StyleTransformVec,
    ) -> bool {
        node.draw(self, size, transforms)
    }
}
#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub struct TextureFlags {
    /// Whether this texture contains an alpha component
    pub is_opaque: bool,
    /// Optimization: use the compositor instead of OpenGL for energy optimization
    pub is_video_texture: bool,
}
impl ::core::fmt::Display for Texture {
3
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
3
        write!(
3
            f,
3
            "Texture {{ id: {}, {}x{} }}",
            self.texture_id, self.size.width, self.size.height
        )
3
    }
}
macro_rules! impl_traits_for_gl_object {
    ($struct_name:ident, $gl_id_field:ident) => {
        impl ::core::fmt::Debug for $struct_name {
1
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1
                write!(f, "{}", self)
1
            }
        }
        impl Hash for $struct_name {
            fn hash<H: Hasher>(&self, state: &mut H) {
                self.$gl_id_field.hash(state);
            }
        }
        impl PartialEq for $struct_name {
4
            fn eq(&self, other: &$struct_name) -> bool {
4
                self.$gl_id_field == other.$gl_id_field
4
            }
        }
        impl Eq for $struct_name {}
        impl PartialOrd for $struct_name {
            fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
                Some((self.$gl_id_field).cmp(&(other.$gl_id_field)))
            }
        }
        impl Ord for $struct_name {
            fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
                (self.$gl_id_field).cmp(&(other.$gl_id_field))
            }
        }
    };
}
impl Texture {
    /// GPU painting: stamp one soft-brush dab centered at (`cx`, `cy`) in texture
    /// pixel coordinates (origin top-left, matching [`RawImage::paint_dot`]).
    /// No-op if the GL context is unusable -- the caller should then use the CPU
    /// `RawImage` path (`GlContextPtr::is_gl_usable`).
7
    pub fn paint_dot(&mut self, cx: f32, cy: f32, brush: Brush) {
7
        self.paint_stroke(cx, cy, cx, cy, brush);
7
    }
    /// GPU painting: stamp dabs along (`x0`,`y0`)->(`x1`,`y1`) into this texture
    /// via an FBO + the soft-brush shader, alpha-over blended. Same spacing +
    /// falloff as the CPU `RawImage::paint_stroke`. No-op if GL is unusable.
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        clippy::cast_precision_loss,
        clippy::cast_sign_loss
    )] // OpenGL/graphics binding: GL-bounded numeric casts to GL* types
    #[allow(clippy::many_single_char_names)] // domain-standard colour/coordinate component names
13
    pub fn paint_stroke(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, brush: Brush) {
13
        let gl = self.gl_context.clone();
13
        let prog = gl.get_brush_shader();
13
        let (tw, th) = (self.size.width as f32, self.size.height as f32);
        // `!(radius > 0.0)` intentionally also rejects NaN (`radius <= 0.0` would not).
        #[allow(clippy::neg_cmp_op_on_partial_ord)]
13
        if prog == 0 || self.texture_id == 0 || !(brush.radius > 0.0) || tw <= 0.0 || th <= 0.0 {
13
            return;
        }
        let fbo = gl.gen_framebuffers(1).get(0).copied().unwrap_or(0);
        let vbo = gl.gen_buffers(1).get(0).copied().unwrap_or(0);
        if fbo == 0 || vbo == 0 {
            if fbo != 0 {
                gl.delete_framebuffers((&[fbo][..]).into());
            }
            if vbo != 0 {
                gl.delete_buffers((&[vbo][..]).into());
            }
            return;
        }
        gl.bind_framebuffer(gl::FRAMEBUFFER, fbo);
        gl.framebuffer_texture_2d(
            gl::FRAMEBUFFER,
            gl::COLOR_ATTACHMENT0,
            gl::TEXTURE_2D,
            self.texture_id,
            0,
        );
        gl.viewport(0, 0, self.size.width as i32, self.size.height as i32);
        gl.enable(gl::BLEND);
        gl.blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
        gl.use_program(prog);
        let a = (f32::from(brush.color.a) / 255.0) * brush.flow.clamp(0.0, 1.0);
        gl.uniform_4f(
            gl.get_uniform_location(prog, "uColor"),
            f32::from(brush.color.r) / 255.0,
            f32::from(brush.color.g) / 255.0,
            f32::from(brush.color.b) / 255.0,
            a,
        );
        gl.uniform_1f(gl.get_uniform_location(prog, "uHardness"), brush.hardness);
        gl.bind_buffer(gl::ARRAY_BUFFER, vbo);
        gl.enable_vertex_attrib_array(0);
        gl.enable_vertex_attrib_array(1);
        gl.vertex_attrib_pointer_f32(0, 2, false, 16, 0);
        gl.vertex_attrib_pointer_f32(1, 2, false, 16, 8);
        let dx = x1 - x0;
        let dy = y1 - y0;
        let len = dx.hypot(dy);
        let step = (brush.radius * brush.spacing.max(0.01)).max(0.5);
        let n = ((len / step).floor() as i32).max(0);
        let r = brush.radius;
        for i in 0..=n {
            let t = if n == 0 { 1.0 } else { i as f32 / n as f32 };
            let px = x0 + dx * t;
            let py = y0 + dy * t;
            // dab bbox -> NDC; y is flipped so (0,0) is top-left like the CPU path.
            let nx = |x: f32| (x / tw) * 2.0 - 1.0;
            let ny = |y: f32| 1.0 - (y / th) * 2.0;
            let (l, rr, tp, bt) = (nx(px - r), nx(px + r), ny(py - r), ny(py + r));
            // TRIANGLE_STRIP: TL, BL, TR, BR -- interleaved (pos.x, pos.y, uv.x, uv.y).
            let verts: [f32; 16] = [
                l, tp, -1.0, -1.0, l, bt, -1.0, 1.0, rr, tp, 1.0, -1.0, rr, bt, 1.0, 1.0,
            ];
            gl.buffer_data_untyped(
                gl::ARRAY_BUFFER,
                (verts.len() * size_of::<f32>()) as isize,
                GlVoidPtrConst {
                    ptr: verts.as_ptr() as *const GLvoid,
                    run_destructor: false,
                },
                gl::STREAM_DRAW,
            );
            gl.draw_arrays(gl::TRIANGLE_STRIP, 0, 4);
        }
        gl.disable_vertex_attrib_array(0);
        gl.disable_vertex_attrib_array(1);
        gl.bind_buffer(gl::ARRAY_BUFFER, 0);
        gl.disable(gl::BLEND);
        gl.bind_framebuffer(gl::FRAMEBUFFER, 0);
        gl.delete_buffers((&[vbo][..]).into());
        gl.delete_framebuffers((&[fbo][..]).into());
13
    }
    /// Read this texture's pixels back into an RGBA8 `RawImage` (top-left origin)
    /// -- for exporting the painted canvas to disk. Binds an FBO + glReadPixels.
    #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] // OpenGL/graphics binding: GL-bounded numeric casts
    #[must_use]
7
    pub fn copy_to_raw_image(&self) -> RawImage {
7
        let gl = self.gl_context.clone();
7
        let (w, h) = (self.size.width as i32, self.size.height as i32);
7
        if self.texture_id == 0 || w <= 0 || h <= 0 {
6
            return RawImage::null_image();
1
        }
1
        let fbo = gl.gen_framebuffers(1).get(0).copied().unwrap_or(0);
1
        if fbo == 0 {
1
            return RawImage::null_image();
        }
        gl.bind_framebuffer(gl::FRAMEBUFFER, fbo);
        gl.framebuffer_texture_2d(
            gl::FRAMEBUFFER,
            gl::COLOR_ATTACHMENT0,
            gl::TEXTURE_2D,
            self.texture_id,
            0,
        );
        let pixels = gl.read_pixels(0, 0, w, h, gl::RGBA, gl::UNSIGNED_BYTE);
        gl.bind_framebuffer(gl::FRAMEBUFFER, 0);
        gl.delete_framebuffers((&[fbo][..]).into());
        // glReadPixels uses a bottom-left origin; flip rows to top-left for saving.
        let mut bytes = pixels.into_library_owned_vec();
        let row = (w as usize) * 4;
        let hh = h as usize;
        if row > 0 && bytes.len() >= row * hh {
            for y in 0..hh / 2 {
                let yi = y * row;
                let yo = (hh - 1 - y) * row;
                for k in 0..row {
                    bytes.swap(yi + k, yo + k);
                }
            }
        }
        RawImage {
            pixels: RawImageData::U8(bytes.into()),
            width: w as usize,
            height: h as usize,
            premultiplied_alpha: true,
            data_format: RawImageFormat::RGBA8,
            tag: Vec::new().into(),
        }
7
    }
}
impl_traits_for_gl_object!(Texture, texture_id);
impl Drop for Texture {
38
    fn drop(&mut self) {
        // AUDIT: mirror `GlContextPtr::drop`. Without this guard a C-ABI
        // double-drop (drop_in_place run twice on the same byte-copied struct)
        // does a second `fetch_sub` on the already-freed refcount box (UAF) and
        // a second `delete_textures`. The first drop clears `run_destructor`, so
        // the second is a no-op.
38
        if !self.run_destructor {
            return;
38
        }
38
        self.run_destructor = false;
38
        let copies = unsafe { (*self.refcount).fetch_sub(1, AtomicOrdering::SeqCst) };
38
        if copies == 1 {
22
            drop(unsafe { Box::from_raw(self.refcount.cast_mut()) });
22
            self.gl_context
22
                .delete_textures((&[self.texture_id])[..].into());
22
        }
38
    }
}
/// Describes the vertex layout and offsets
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct VertexLayout {
    pub fields: VertexAttributeVec,
}
impl_vec!(
    VertexAttribute,
    VertexAttributeVec,
    VertexAttributeVecDestructor,
    VertexAttributeVecDestructorType,
    VertexAttributeVecSlice,
    OptionVertexAttribute
);
impl_vec_debug!(VertexAttribute, VertexAttributeVec);
impl_vec_partialord!(VertexAttribute, VertexAttributeVec);
impl_vec_ord!(VertexAttribute, VertexAttributeVec);
impl_vec_clone!(
    VertexAttribute,
    VertexAttributeVec,
    VertexAttributeVecDestructor
);
impl_vec_partialeq!(VertexAttribute, VertexAttributeVec);
impl_vec_eq!(VertexAttribute, VertexAttributeVec);
impl_vec_hash!(VertexAttribute, VertexAttributeVec);
impl VertexLayout {
    /// Submits the vertex buffer description to OpenGL
    // OpenGL binding: vertex-attribute layout (locations, item counts, strides,
    // offsets) passed to the gl API as GLuint/GLint/GLsizei; values are GL-bounded.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    #[allow(clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
                                         // types
    pub fn bind(&self, gl_context: &Rc<GenericGlContext>, program_id: GLuint) {
        const VERTICES_ARE_NORMALIZED: bool = false;
        let mut offset = 0;
        let stride_between_vertices: usize =
            self.fields.iter().map(VertexAttribute::get_stride).sum();
        for vertex_attribute in &self.fields {
            let attribute_location = vertex_attribute.layout_location.as_option().map_or_else(
                || gl_context.get_attrib_location(program_id, vertex_attribute.va_name.as_str()),
                |ll| *ll as i32,
            );
            gl_context.vertex_attrib_pointer(
                attribute_location as u32,
                vertex_attribute.item_count as i32,
                vertex_attribute.attribute_type.get_gl_id(),
                VERTICES_ARE_NORMALIZED,
                stride_between_vertices as i32,
                offset as u32,
            );
            gl_context.enable_vertex_attrib_array(attribute_location as u32);
            offset += vertex_attribute.get_stride();
        }
    }
    /// Unsets the vertex buffer description
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // OpenGL/graphics binding: GL-bounded numeric casts to GL* types
    #[allow(clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts
    pub fn unbind(&self, gl_context: &Rc<GenericGlContext>, program_id: GLuint) {
        for vertex_attribute in &self.fields {
            let attribute_location = vertex_attribute.layout_location.as_option().map_or_else(
                || gl_context.get_attrib_location(program_id, vertex_attribute.va_name.as_str()),
                |ll| *ll as i32,
            );
            gl_context.disable_vertex_attrib_array(attribute_location as u32);
        }
    }
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct VertexAttribute {
    /// Attribute name of the vertex attribute in the vertex shader, i.e. `"vAttrXY"`
    pub va_name: AzString,
    /// If the vertex shader has a specific location, (like `layout(location = 2) vAttrXY`),
    /// use this instead of the name to look up the uniform location.
    pub layout_location: OptionUsize,
    /// Type of items of this attribute (i.e. for a `FloatVec2`, would be
    /// `VertexAttributeType::Float`)
    pub attribute_type: VertexAttributeType,
    /// Number of items of this attribute (i.e. for a `FloatVec2`, would be `2` (= 2 consecutive
    /// f32 values))
    pub item_count: usize,
}
impl_option!(
    VertexAttribute,
    OptionVertexAttribute,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl VertexAttribute {
    #[must_use]
15
    pub const fn get_stride(&self) -> usize {
15
        self.attribute_type.get_mem_size() * self.item_count
15
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum VertexAttributeType {
    /// Vertex attribute has type `f32`
    Float,
    /// Vertex attribute has type `f64`
    Double,
    /// Vertex attribute has type `u8`
    UnsignedByte,
    /// Vertex attribute has type `u16`
    UnsignedShort,
    /// Vertex attribute has type `u32`
    UnsignedInt,
}
impl VertexAttributeType {
    /// Returns the OpenGL id for the vertex attribute type, ex. `gl::UNSIGNED_BYTE` for
    /// `VertexAttributeType::UnsignedByte`.
    #[must_use]
27
    pub const fn get_gl_id(&self) -> GLuint {
        use self::VertexAttributeType::{Double, Float, UnsignedByte, UnsignedInt, UnsignedShort};
27
        match self {
6
            Float => gl::FLOAT,
5
            Double => gl::DOUBLE,
6
            UnsignedByte => gl::UNSIGNED_BYTE,
5
            UnsignedShort => gl::UNSIGNED_SHORT,
5
            UnsignedInt => gl::UNSIGNED_INT,
        }
27
    }
    #[must_use]
35
    pub const fn get_mem_size(&self) -> usize {
        use core::mem;
        use self::VertexAttributeType::{Double, Float, UnsignedByte, UnsignedInt, UnsignedShort};
35
        match self {
8
            Float => size_of::<f32>(),
7
            Double => size_of::<f64>(),
8
            UnsignedByte => size_of::<u8>(),
6
            UnsignedShort => size_of::<u16>(),
6
            UnsignedInt => size_of::<u32>(),
        }
35
    }
}
pub trait VertexLayoutDescription {
    fn get_description() -> VertexLayout;
}
#[derive(Debug, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct VertexArrayObject {
    pub vertex_layout: VertexLayout,
    pub vao_id: GLuint,
    pub gl_context: GlContextPtr,
    pub refcount: *const AtomicUsize,
    pub run_destructor: bool,
}
impl VertexArrayObject {
    #[must_use]
3
    pub fn new(vertex_layout: VertexLayout, vao_id: GLuint, gl_context: GlContextPtr) -> Self {
3
        Self {
3
            vertex_layout,
3
            vao_id,
3
            gl_context,
3
            refcount: Box::into_raw(Box::new(AtomicUsize::new(1))),
3
            run_destructor: true,
3
        }
3
    }
}
impl Clone for VertexArrayObject {
16
    fn clone(&self) -> Self {
16
        unsafe { (*self.refcount).fetch_add(1, AtomicOrdering::SeqCst) };
16
        Self {
16
            vertex_layout: self.vertex_layout.clone(),
16
            vao_id: self.vao_id,
16
            gl_context: self.gl_context.clone(),
16
            refcount: self.refcount,
16
            run_destructor: true,
16
        }
16
    }
}
impl Drop for VertexArrayObject {
19
    fn drop(&mut self) {
        // AUDIT: mirror `GlContextPtr::drop` — guard against a C-ABI double-drop
        // freeing the refcount box twice (use-after-free) + double delete.
19
        if !self.run_destructor {
            return;
19
        }
19
        self.run_destructor = false;
19
        let copies = unsafe { (*self.refcount).fetch_sub(1, AtomicOrdering::SeqCst) };
19
        if copies == 1 {
3
            drop(unsafe { Box::from_raw(self.refcount.cast_mut()) });
3
            self.gl_context
3
                .delete_vertex_arrays((&[self.vao_id])[..].into());
16
        }
19
    }
}
#[repr(C)]
pub struct VertexBuffer {
    pub vao: VertexArrayObject,
    pub vertex_buffer_id: GLuint,
    pub vertex_buffer_len: usize,
    pub index_buffer_id: GLuint,
    pub index_buffer_len: usize,
    pub refcount: *const AtomicUsize,
    pub index_buffer_format: IndexBufferFormat,
    pub run_destructor: bool,
}
impl fmt::Display for VertexBuffer {
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1
        write!(
1
            f,
1
            "VertexBuffer {{ buffer: {} (length: {}) }}",
            self.vertex_buffer_id, self.vertex_buffer_len
        )
1
    }
}
impl_traits_for_gl_object!(VertexBuffer, vertex_buffer_id);
impl Clone for VertexBuffer {
8
    fn clone(&self) -> Self {
8
        unsafe { (*self.refcount).fetch_add(1, AtomicOrdering::SeqCst) };
8
        Self {
8
            vao: self.vao.clone(),
8
            vertex_buffer_id: self.vertex_buffer_id,
8
            vertex_buffer_len: self.vertex_buffer_len,
8
            index_buffer_id: self.index_buffer_id,
8
            index_buffer_len: self.index_buffer_len,
8
            refcount: self.refcount,
8
            index_buffer_format: self.index_buffer_format,
8
            run_destructor: true,
8
        }
8
    }
}
impl Drop for VertexBuffer {
10
    fn drop(&mut self) {
        // AUDIT: mirror `GlContextPtr::drop` — guard against a C-ABI double-drop
        // freeing the refcount box twice (use-after-free) + double delete.
10
        if !self.run_destructor {
            return;
10
        }
10
        self.run_destructor = false;
10
        let copies = unsafe { (*self.refcount).fetch_sub(1, AtomicOrdering::SeqCst) };
10
        if copies == 1 {
2
            self.vao.vertex_layout = VertexLayout {
2
                fields: VertexAttributeVec::from_const_slice(&[]),
2
            };
2
            drop(unsafe { Box::from_raw(self.refcount.cast_mut()) });
2
            self.vao
2
                .gl_context
2
                .delete_buffers((&[self.vertex_buffer_id, self.index_buffer_id])[..].into());
8
        }
10
    }
}
impl VertexBuffer {
    /// # Panics
    ///
    /// Panics if the GL driver failed to create the vertex-array/buffer objects
    /// (the returned id lists are empty).
    // OpenGL binding: buffer sizes / vertex counts passed to the gl API as
    // GLsizeiptr/GLint; values are GL-bounded.
    #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
    #[allow(clippy::cast_possible_truncation)] // OpenGL/graphics binding: GL-bounded numeric casts
                                               // to GL* types
1
    pub fn new<T: VertexLayoutDescription>(
1
        gl_context: GlContextPtr,
1
        shader_program_id: GLuint,
1
        vertices: &[T],
1
        indices: &[u32],
1
        index_buffer_format: IndexBufferFormat,
1
    ) -> Self {
        use core::mem;
        // Save the OpenGL state
1
        let mut current_vertex_array = [0_i32];
1
        gl_context.get_integer_v(gl::VERTEX_ARRAY, (&mut current_vertex_array[..]).into());
1
        let vertex_array_object = gl_context.gen_vertex_arrays(1);
1
        let vertex_array_object = vertex_array_object.get(0).unwrap();
1
        let vertex_buffer_id = gl_context.gen_buffers(1);
1
        let vertex_buffer_id = vertex_buffer_id.get(0).unwrap();
1
        let index_buffer_id = gl_context.gen_buffers(1);
1
        let index_buffer_id = index_buffer_id.get(0).unwrap();
1
        gl_context.bind_vertex_array(*vertex_array_object);
        // Upload vertex data to GPU
1
        gl_context.bind_buffer(gl::ARRAY_BUFFER, *vertex_buffer_id);
1
        gl_context.buffer_data_untyped(
            gl::ARRAY_BUFFER,
1
            size_of_val(vertices) as isize,
1
            GlVoidPtrConst {
1
                ptr: vertices.as_ptr() as *const core::ffi::c_void,
1
                run_destructor: true,
1
            },
            gl::STATIC_DRAW,
        );
        // Generate the index buffer + upload data
1
        gl_context.bind_buffer(gl::ELEMENT_ARRAY_BUFFER, *index_buffer_id);
1
        gl_context.buffer_data_untyped(
            gl::ELEMENT_ARRAY_BUFFER,
1
            size_of_val(indices) as isize,
1
            GlVoidPtrConst {
1
                ptr: indices.as_ptr() as *const core::ffi::c_void,
1
                run_destructor: true,
1
            },
            gl::STATIC_DRAW,
        );
1
        let vertex_description = T::get_description();
1
        vertex_description.bind(&gl_context.ptr.ptr, shader_program_id);
        // Reset the OpenGL state
1
        gl_context.bind_vertex_array(current_vertex_array[0] as u32);
1
        Self::new_raw(
1
            *vertex_buffer_id,
1
            vertices.len(),
1
            VertexArrayObject::new(vertex_description, *vertex_array_object, gl_context),
1
            *index_buffer_id,
1
            indices.len(),
1
            index_buffer_format,
        )
1
    }
    #[must_use]
2
    pub fn new_raw(
2
        vertex_buffer_id: GLuint,
2
        vertex_buffer_len: usize,
2
        vao: VertexArrayObject,
2
        index_buffer_id: GLuint,
2
        index_buffer_len: usize,
2
        index_buffer_format: IndexBufferFormat,
2
    ) -> Self {
2
        Self {
2
            vertex_buffer_id,
2
            vertex_buffer_len,
2
            vao,
2
            index_buffer_id,
2
            index_buffer_len,
2
            index_buffer_format,
2
            refcount: Box::into_raw(Box::new(AtomicUsize::new(1))),
2
            run_destructor: true,
2
        }
2
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GlApiVersion {
    Gl { major: usize, minor: usize },
    GlEs { major: usize, minor: usize },
}
impl GlApiVersion {
    /// Returns the OpenGL version of the context
    #[allow(clippy::cast_sign_loss)] // OpenGL/graphics binding: GL-bounded numeric casts
    #[must_use]
    pub fn get(gl_context: &GlContextPtr) -> Self {
        let mut major = [0];
        gl_context.get_integer_v(gl::MAJOR_VERSION, (&mut major[..]).into());
        let mut minor = [0];
        gl_context.get_integer_v(gl::MINOR_VERSION, (&mut minor[..]).into());
        let major = major[0] as usize;
        let minor = minor[0] as usize;
        match gl_context.get_type() {
            GlType::Gl => Self::Gl { major, minor },
            GlType::Gles => Self::GlEs { major, minor },
        }
    }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum IndexBufferFormat {
    Points,
    Lines,
    LineStrip,
    Triangles,
    TriangleStrip,
    TriangleFan,
}
impl IndexBufferFormat {
    /// Returns the `gl::TRIANGLE_STRIP` / `gl::POINTS`, etc.
    #[must_use]
32
    pub const fn get_gl_id(&self) -> GLuint {
        use self::IndexBufferFormat::{
            LineStrip, Lines, Points, TriangleFan, TriangleStrip, Triangles,
        };
32
        match self {
6
            Points => gl::POINTS,
5
            Lines => gl::LINES,
5
            LineStrip => gl::LINE_STRIP,
5
            Triangles => gl::TRIANGLES,
6
            TriangleStrip => gl::TRIANGLE_STRIP,
5
            TriangleFan => gl::TRIANGLE_FAN,
        }
32
    }
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct Uniform {
    pub uniform_name: AzString,
    pub uniform_type: UniformType,
}
impl Uniform {
5
    pub fn create<S: Into<AzString>>(name: S, uniform_type: UniformType) -> Self {
5
        Self {
5
            uniform_name: name.into(),
5
            uniform_type,
5
        }
5
    }
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[repr(C, u8)]
pub enum UniformType {
    Float(f32),
    FloatVec2([f32; 2]),
    FloatVec3([f32; 3]),
    FloatVec4([f32; 4]),
    Int(i32),
    IntVec2([i32; 2]),
    IntVec3([i32; 3]),
    IntVec4([i32; 4]),
    UnsignedInt(u32),
    UnsignedIntVec2([u32; 2]),
    UnsignedIntVec3([u32; 3]),
    UnsignedIntVec4([u32; 4]),
    Matrix2 {
        transpose: bool,
        matrix: [f32; 2 * 2],
    },
    Matrix3 {
        transpose: bool,
        matrix: [f32; 3 * 3],
    },
    Matrix4 {
        transpose: bool,
        matrix: [f32; 4 * 4],
    },
}
impl UniformType {
    /// Set a specific uniform
    pub fn set(self, gl_context: &Rc<GenericGlContext>, location: GLint) {
        use self::UniformType::{
            Float, FloatVec2, FloatVec3, FloatVec4, Int, IntVec2, IntVec3, IntVec4, Matrix2,
            Matrix3, Matrix4, UnsignedInt, UnsignedIntVec2, UnsignedIntVec3, UnsignedIntVec4,
        };
        match self {
            Float(r) => gl_context.uniform_1f(location, r),
            FloatVec2([r, g]) => gl_context.uniform_2f(location, r, g),
            FloatVec3([r, g, b]) => gl_context.uniform_3f(location, r, g, b),
            FloatVec4([r, g, b, a]) => gl_context.uniform_4f(location, r, g, b, a),
            Int(r) => gl_context.uniform_1i(location, r),
            IntVec2([r, g]) => gl_context.uniform_2i(location, r, g),
            IntVec3([r, g, b]) => gl_context.uniform_3i(location, r, g, b),
            IntVec4([r, g, b, a]) => gl_context.uniform_4i(location, r, g, b, a),
            UnsignedInt(r) => gl_context.uniform_1ui(location, r),
            UnsignedIntVec2([r, g]) => gl_context.uniform_2ui(location, r, g),
            UnsignedIntVec3([r, g, b]) => gl_context.uniform_3ui(location, r, g, b),
            UnsignedIntVec4([r, g, b, a]) => gl_context.uniform_4ui(location, r, g, b, a),
            Matrix2 { transpose, matrix } => {
                gl_context.uniform_matrix_2fv(location, transpose, &matrix[..]);
            }
            Matrix3 { transpose, matrix } => {
                gl_context.uniform_matrix_3fv(location, transpose, &matrix[..]);
            }
            Matrix4 { transpose, matrix } => {
                gl_context.uniform_matrix_4fv(location, transpose, &matrix[..]);
            }
        }
    }
}
#[repr(C)]
pub struct GlShader {
    pub program_id: GLuint,
    pub gl_context: GlContextPtr,
    /// AUDIT: guards against a double-drop deleting the same GL program twice
    /// (`drop_in_place` run twice on a byte-copied struct). Set `true` on
    /// construction; the first drop clears it so a second drop is a no-op.
    pub run_destructor: bool,
}
impl ::core::fmt::Display for GlShader {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        write!(f, "GlShader {{ program_id: {} }}", self.program_id)
    }
}
impl_traits_for_gl_object!(GlShader, program_id);
impl Drop for GlShader {
    fn drop(&mut self) {
        // AUDIT: mirror `GlContextPtr::drop` — a C-ABI double-drop would call
        // `delete_program` on the same id twice. The first drop clears the flag.
        if !self.run_destructor {
            return;
        }
        self.run_destructor = false;
        self.gl_context.delete_program(self.program_id);
    }
}
#[repr(C)]
#[derive(Clone)]
pub struct VertexShaderCompileError {
    pub error_id: i32,
    pub info_log: AzString,
}
impl_traits_for_gl_object!(VertexShaderCompileError, error_id);
impl ::core::fmt::Display for VertexShaderCompileError {
5
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
5
        write!(f, "E{}: {}", self.error_id, self.info_log)
5
    }
}
#[repr(C)]
#[derive(Clone)]
pub struct FragmentShaderCompileError {
    pub error_id: i32,
    pub info_log: AzString,
}
impl_traits_for_gl_object!(FragmentShaderCompileError, error_id);
impl ::core::fmt::Display for FragmentShaderCompileError {
2
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
2
        write!(f, "E{}: {}", self.error_id, self.info_log)
2
    }
}
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum GlShaderCompileError {
    Vertex(VertexShaderCompileError),
    Fragment(FragmentShaderCompileError),
}
impl ::core::fmt::Display for GlShaderCompileError {
4
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        use self::GlShaderCompileError::{Fragment, Vertex};
4
        match self {
3
            Vertex(vert_err) => write!(f, "Failed to compile vertex shader: {vert_err}"),
1
            Fragment(frag_err) => write!(f, "Failed to compile fragment shader: {frag_err}"),
        }
4
    }
}
impl ::core::fmt::Debug for GlShaderCompileError {
1
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1
        write!(f, "{self}")
1
    }
}
#[repr(C)]
#[derive(Clone)]
pub struct GlShaderLinkError {
    pub error_id: i32,
    pub info_log: AzString,
}
impl_traits_for_gl_object!(GlShaderLinkError, error_id);
impl ::core::fmt::Display for GlShaderLinkError {
3
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
3
        write!(f, "E{}: {}", self.error_id, self.info_log)
3
    }
}
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum GlShaderCreateError {
    Compile(GlShaderCompileError),
    Link(GlShaderLinkError),
    NoShaderCompiler,
}
impl ::core::fmt::Display for GlShaderCreateError {
4
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        use self::GlShaderCreateError::{Compile, Link, NoShaderCompiler};
4
        match self {
            Compile(compile_err) => write!(f, "Shader compile error: {compile_err}"),
3
            Link(link_err) => write!(f, "Shader linking error: {link_err}"),
            NoShaderCompiler => {
1
                write!(f, "OpenGL implementation doesn't include a shader compiler")
            }
        }
4
    }
}
impl ::core::fmt::Debug for GlShaderCreateError {
1
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1
        write!(f, "{self}")
1
    }
}
impl GlShader {
    /// Compiles and creates a new OpenGL shader, created from a vertex and a fragment shader
    /// string.
    ///
    /// If the shader fails to compile, the shader object gets automatically deleted, no cleanup
    /// necessary.
    #[allow(clippy::cast_possible_truncation)] // OpenGL/graphics binding: GL-bounded numeric casts to GL* types
    /// # Errors
    ///
    /// Returns an error if the OpenGL implementation has no shader compiler, or if the
    /// vertex/fragment shader fails to compile or link.
5
    pub fn new(
5
        gl_context: &GlContextPtr,
5
        vertex_shader: &str,
5
        fragment_shader: &str,
5
    ) -> Result<Self, GlShaderCreateError> {
        // Check whether the OpenGL implementation supports a shader compiler...
5
        let mut shader_compiler_supported = [gl::FALSE as u8];
5
        gl_context.get_boolean_v(
            gl::SHADER_COMPILER,
5
            (&mut shader_compiler_supported[..]).into(),
        );
5
        if u32::from(shader_compiler_supported[0]) == gl::FALSE {
            // Implementation only supports binary shaders
5
            return Err(GlShaderCreateError::NoShaderCompiler);
        }
        // Compile vertex shader
        let vertex_shader_object = gl_context.create_shader(gl::VERTEX_SHADER);
        gl_context.shader_source(
            vertex_shader_object,
            vec![AzString::from(vertex_shader.to_string())].into(),
        );
        gl_context.compile_shader(vertex_shader_object);
        if let Some(error_id) = get_gl_shader_error(gl_context, vertex_shader_object) {
            let info_log = gl_context.get_shader_info_log(vertex_shader_object);
            gl_context.delete_shader(vertex_shader_object);
            return Err(GlShaderCreateError::Compile(GlShaderCompileError::Vertex(
                VertexShaderCompileError { error_id, info_log },
            )));
        }
        // Compile fragment shader
        let fragment_shader_object = gl_context.create_shader(gl::FRAGMENT_SHADER);
        gl_context.shader_source(
            fragment_shader_object,
            vec![AzString::from(fragment_shader.to_string())].into(),
        );
        gl_context.compile_shader(fragment_shader_object);
        if let Some(error_id) = get_gl_shader_error(gl_context, fragment_shader_object) {
            let info_log = gl_context.get_shader_info_log(fragment_shader_object);
            gl_context.delete_shader(vertex_shader_object);
            gl_context.delete_shader(fragment_shader_object);
            return Err(GlShaderCreateError::Compile(
                GlShaderCompileError::Fragment(FragmentShaderCompileError { error_id, info_log }),
            ));
        }
        // Link program
        let program_id = gl_context.create_program();
        gl_context.attach_shader(program_id, vertex_shader_object);
        gl_context.attach_shader(program_id, fragment_shader_object);
        gl_context.link_program(program_id);
        if let Some(error_id) = get_gl_program_error(gl_context, program_id) {
            let info_log = gl_context.get_program_info_log(program_id);
            gl_context.delete_shader(vertex_shader_object);
            gl_context.delete_shader(fragment_shader_object);
            gl_context.delete_program(program_id);
            return Err(GlShaderCreateError::Link(GlShaderLinkError {
                error_id,
                info_log,
            }));
        }
        gl_context.delete_shader(vertex_shader_object);
        gl_context.delete_shader(fragment_shader_object);
        Ok(Self {
            program_id,
            gl_context: gl_context.clone(),
            run_destructor: true,
        })
5
    }
    /// Draws vertex buffers, index buffers + uniforms to the texture
    ///
    /// # Panics
    ///
    /// Panics if no framebuffer/depthbuffer was allocated (the GL object lists are empty).
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts to GL* types
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch
                                     // (one branch per input variant)
    pub fn draw(
        // shader to use for drawing
        shader_program_id: GLuint,
        // note: texture is &mut so the texture is reusable -
        texture: &mut Texture,
        // buffers + uniforms to draw
        buffers: &[(&VertexBuffer, &[Uniform])],
    ) {
        use alloc::collections::btree_map::BTreeMap;
        const INDEX_TYPE: GLuint = gl::UNSIGNED_INT;
        let texture_size = texture.size;
        let gl_context = &texture.gl_context;
        let saved = GlStateSave::save(gl_context);
        // save draw()-specific state not covered by GlStateSave
        let mut current_blend_enabled = [0_u8];
        let mut current_primitive_restart_enabled = [0_u8];
        gl_context.get_boolean_v(gl::BLEND, (&mut current_blend_enabled[..]).into());
        gl_context.get_boolean_v(
            gl::PRIMITIVE_RESTART,
            (&mut current_primitive_restart_enabled[..]).into(),
        );
        // 1. Create the framebuffer
        let framebuffers = gl_context.gen_framebuffers(1);
        let framebuffer_id = *framebuffers.get(0).unwrap();
        // AUDIT: register the FBO for cleanup BEFORE the next fallible step so a
        // panic anywhere below (incl. `gen_renderbuffers().get(0).unwrap()`)
        // can't leak the FBO/RBO. Guard's Drop runs on unwind too.
        let mut fbo_rbo_guard = FboRboGuard {
            gl_context,
            framebuffer_id,
            renderbuffer_id: 0,
        };
        gl_context.bind_framebuffer(gl::FRAMEBUFFER, framebuffer_id);
        let depthbuffers = gl_context.gen_renderbuffers(1);
        let depthbuffer_id = *depthbuffers.get(0).unwrap();
        fbo_rbo_guard.renderbuffer_id = depthbuffer_id;
        gl_context.bind_texture(gl::TEXTURE_2D, texture.texture_id);
        gl_context.tex_image_2d(
            gl::TEXTURE_2D,
            0,
            gl::RGBA as i32, // NOT RGBA8 - will generate INVALID_ENUM!
            texture_size.width as i32,
            texture_size.height as i32,
            0,
            gl::RGBA, // gl::BGRA?
            gl::UNSIGNED_BYTE,
            None.into(),
        );
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32);
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as i32);
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32);
        gl_context.tex_parameter_i(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32);
        gl_context.bind_renderbuffer(gl::RENDERBUFFER, depthbuffer_id);
        gl_context.renderbuffer_storage(
            gl::RENDERBUFFER,
            gl::DEPTH_COMPONENT,
            texture_size.width as i32,
            texture_size.height as i32,
        );
        gl_context.framebuffer_renderbuffer(
            gl::FRAMEBUFFER,
            gl::DEPTH_ATTACHMENT,
            gl::RENDERBUFFER,
            depthbuffer_id,
        );
        gl_context.framebuffer_texture_2d(
            gl::FRAMEBUFFER,
            gl::COLOR_ATTACHMENT0,
            gl::TEXTURE_2D,
            texture.texture_id,
            0,
        );
        gl_context.draw_buffers([gl::COLOR_ATTACHMENT0][..].into());
        #[cfg(feature = "std")]
        {
            let fb_check = gl_context.check_frame_buffer_status(gl::FRAMEBUFFER);
            match fb_check {
                gl::FRAMEBUFFER_COMPLETE => {}
                gl::FRAMEBUFFER_UNDEFINED => {
                    println!("GL_FRAMEBUFFER_UNDEFINED");
                }
                gl::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => {
                    println!("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
                }
                gl::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => {
                    println!("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
                }
                gl::FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER => {
                    println!("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER");
                }
                gl::FRAMEBUFFER_INCOMPLETE_READ_BUFFER => {
                    println!("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER");
                }
                gl::FRAMEBUFFER_UNSUPPORTED => {
                    println!("GL_FRAMEBUFFER_UNSUPPORTED");
                }
                gl::FRAMEBUFFER_INCOMPLETE_MULTISAMPLE => {
                    println!("GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE");
                }
                gl::FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS => {
                    println!("GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS");
                }
                o => {
                    println!("glFramebufferStatus returned unknown return code: {o}");
                }
            }
        }
        gl_context.viewport(0, 0, texture_size.width as i32, texture_size.height as i32);
        gl_context.enable(gl::BLEND);
        // Use GL_PRIMITIVE_RESTART (OpenGL 3.1+) instead of
        // GL_PRIMITIVE_RESTART_FIXED_INDEX (4.3+) for macOS compatibility.
        gl_context.enable(gl::PRIMITIVE_RESTART);
        unsafe {
            let gl = gl_context.get();
            if !gl.glPrimitiveRestartIndex.is_null() {
                let func: extern "system" fn(u32) =
                    core::mem::transmute(gl.glPrimitiveRestartIndex);
                func(GL_RESTART_INDEX); // u32::MAX
            }
        }
        gl_context.disable(gl::MULTISAMPLE);
        gl_context.blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); // TODO: enable / disable
        gl_context.use_program(shader_program_id);
        // Avoid multiple calls to get_uniform_location by caching the uniform locations
        let mut uniform_locations: BTreeMap<AzString, i32> = BTreeMap::new();
        let mut max_uniform_len = 0;
        for (_, uniforms) in buffers {
            for uniform in *uniforms {
                if !uniform_locations.contains_key(&uniform.uniform_name) {
                    uniform_locations.insert(
                        uniform.uniform_name.clone(),
                        gl_context
                            .get_uniform_location(shader_program_id, uniform.uniform_name.as_str()),
                    );
                }
            }
            max_uniform_len = max_uniform_len.max(uniforms.len());
        }
        let mut current_uniforms = vec![None; max_uniform_len];
        // Since the description of the vertex buffers is always the same,
        // only the first layer needs to bind its VAO
        // Draw the actual layers
        for (vertex_index_buffer, uniforms) in buffers {
            gl_context.bind_vertex_array(vertex_index_buffer.vao.vao_id);
            gl_context.bind_buffer(gl::ARRAY_BUFFER, vertex_index_buffer.vertex_buffer_id);
            gl_context.bind_buffer(
                gl::ELEMENT_ARRAY_BUFFER,
                vertex_index_buffer.index_buffer_id,
            );
            // Only set the uniform if the value has changed
            for (uniform_index, uniform) in uniforms.iter().enumerate() {
                if current_uniforms[uniform_index] != Some(uniform.uniform_type) {
                    let uniform_location = uniform_locations[&uniform.uniform_name];
                    uniform.uniform_type.set(gl_context.get(), uniform_location);
                    current_uniforms[uniform_index] = Some(uniform.uniform_type);
                }
            }
            gl_context.draw_elements(
                vertex_index_buffer.index_buffer_format.get_gl_id(),
                vertex_index_buffer.index_buffer_len as i32,
                INDEX_TYPE,
                0,
            );
        }
        // Reset draw()-specific state
        if u32::from(current_blend_enabled[0]) == gl::FALSE {
            gl_context.disable(gl::BLEND);
        }
        if u32::from(current_primitive_restart_enabled[0]) == gl::FALSE {
            gl_context.disable(gl::PRIMITIVE_RESTART);
        }
        // AUDIT: FBO/RBO deletion is handled by `fbo_rbo_guard`'s Drop (which
        // also runs on an unwinding panic) — reclaim them explicitly here so
        // the deletion order matches the original (delete before texture
        // metadata writes / after state restore).
        // Reset common GL state
        saved.restore(gl_context);
        drop(fbo_rbo_guard);
        texture.format = RawImageFormat::RGBA8;
        texture.flags = TextureFlags {
            is_opaque: false,
            is_video_texture: false,
        };
    }
}
#[allow(clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
                                     // types
fn get_gl_shader_error(context: &GlContextPtr, shader_object: GLuint) -> Option<i32> {
    let mut err = [0];
    context.get_shader_iv(shader_object, gl::COMPILE_STATUS, (&mut err[..]).into());
    let err_code = err[0];
    if err_code == gl::TRUE as i32 {
        None
    } else {
        Some(err_code)
    }
}
#[allow(clippy::cast_possible_wrap)] // OpenGL/graphics binding: GL-bounded numeric casts to GL*
                                     // types
fn get_gl_program_error(context: &GlContextPtr, shader_object: GLuint) -> Option<i32> {
    let mut err = [0];
    context.get_program_iv(shader_object, gl::LINK_STATUS, (&mut err[..]).into());
    let err_code = err[0];
    if err_code == gl::TRUE as i32 {
        None
    } else {
        Some(err_code)
    }
}
#[cfg(test)]
#[path = "gl_test.rs"]
mod gl_test;