siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Strongly-typed OpenGL 3.3–4.6 Core value types, enums, and bitflags.

use std::fmt;
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign};

use crate::sys;

// ---------------------------------------------------------------------------
// OpenGL Version & Profile
// ---------------------------------------------------------------------------

/// Semantic OpenGL version (`major.minor`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GlVersion {
    /// Major version number (e.g. `4`).
    pub major: u32,
    /// Minor version number (e.g. `6`).
    pub minor: u32,
}

impl GlVersion {
    /// OpenGL 3.3 Core.
    pub const V3_3: Self = Self::new(3, 3);
    /// OpenGL 4.0 Core.
    pub const V4_0: Self = Self::new(4, 0);
    /// OpenGL 4.1 Core.
    pub const V4_1: Self = Self::new(4, 1);
    /// OpenGL 4.2 Core.
    pub const V4_2: Self = Self::new(4, 2);
    /// OpenGL 4.3 Core (Compute shaders, KHR_debug).
    pub const V4_3: Self = Self::new(4, 3);
    /// OpenGL 4.4 Core (Immutable buffer storage).
    pub const V4_4: Self = Self::new(4, 4);
    /// OpenGL 4.5 Core (Direct State Access).
    pub const V4_5: Self = Self::new(4, 5);
    /// OpenGL 4.6 Core (SPIR-V, anisotropy core).
    pub const V4_6: Self = Self::new(4, 6);

    /// Creates a new OpenGL version descriptor.
    #[inline]
    pub const fn new(major: u32, minor: u32) -> Self {
        Self { major, minor }
    }
}

impl fmt::Display for GlVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

/// Active OpenGL context profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GlProfile {
    /// Core profile (modern OpenGL without deprecated fixed-function pipeline).
    Core,
    /// Compatibility profile.
    Compatibility,
    /// Profile mask was not reported or unknown.
    Unknown,
}

/// Metadata queried from an active OpenGL context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextInfo {
    /// Parsed OpenGL version (`major.minor`).
    pub version: GlVersion,
    /// Active context profile.
    pub profile: GlProfile,
    /// `GL_VENDOR` string.
    pub vendor: String,
    /// `GL_RENDERER` string.
    pub renderer: String,
    /// Raw `GL_VERSION` string.
    pub version_string: String,
    /// `GL_SHADING_LANGUAGE_VERSION` string.
    pub glsl_version: String,
}

// ---------------------------------------------------------------------------
// Data types & primitives
// ---------------------------------------------------------------------------

/// OpenGL scalar data types for vertex attributes and index buffers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum DataType {
    /// Signed 8-bit integer (`GL_BYTE`).
    I8 = sys::GL_BYTE,
    /// Unsigned 8-bit integer (`GL_UNSIGNED_BYTE`).
    U8 = sys::GL_UNSIGNED_BYTE,
    /// Signed 16-bit integer (`GL_SHORT`).
    I16 = sys::GL_SHORT,
    /// Unsigned 16-bit integer (`GL_UNSIGNED_SHORT`).
    U16 = sys::GL_UNSIGNED_SHORT,
    /// Signed 32-bit integer (`GL_INT`).
    I32 = sys::GL_INT,
    /// Unsigned 32-bit integer (`GL_UNSIGNED_INT`).
    U32 = sys::GL_UNSIGNED_INT,
    /// IEEE 754 16-bit half-float (`GL_HALF_FLOAT`).
    F16 = sys::GL_HALF_FLOAT,
    /// IEEE 754 32-bit float (`GL_FLOAT`).
    F32 = sys::GL_FLOAT,
    /// IEEE 754 64-bit double (`GL_DOUBLE`).
    F64 = sys::GL_DOUBLE,
}

impl DataType {
    /// Returns the size in bytes of one element of this type.
    #[inline]
    pub const fn byte_size(self) -> usize {
        match self {
            Self::I8 | Self::U8 => 1,
            Self::I16 | Self::U16 | Self::F16 => 2,
            Self::I32 | Self::U32 | Self::F32 => 4,
            Self::F64 => 8,
        }
    }

    /// Returns `true` if this type is an integer type (valid for `glVertexAttribIPointer`).
    #[inline]
    pub const fn is_integer(self) -> bool {
        matches!(
            self,
            Self::I8 | Self::U8 | Self::I16 | Self::U16 | Self::I32 | Self::U32
        )
    }
}

/// Index buffer element type for indexed draw calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum IndexType {
    /// 8-bit unsigned index (`GL_UNSIGNED_BYTE`).
    U8 = sys::GL_UNSIGNED_BYTE,
    /// 16-bit unsigned index (`GL_UNSIGNED_SHORT`).
    U16 = sys::GL_UNSIGNED_SHORT,
    /// 32-bit unsigned index (`GL_UNSIGNED_INT`).
    U32 = sys::GL_UNSIGNED_INT,
}

impl IndexType {
    /// Returns the byte size of one index element.
    #[inline]
    pub const fn byte_size(self) -> usize {
        match self {
            Self::U8 => 1,
            Self::U16 => 2,
            Self::U32 => 4,
        }
    }
}

/// Geometry primitive topology for draw calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum PrimitiveMode {
    /// Individual points (`GL_POINTS`).
    Points = sys::GL_POINTS,
    /// Independent line segments (`GL_LINES`).
    Lines = sys::GL_LINES,
    /// Connected closed line loop (`GL_LINE_LOOP`).
    LineLoop = sys::GL_LINE_LOOP,
    /// Connected line strip (`GL_LINE_STRIP`).
    LineStrip = sys::GL_LINE_STRIP,
    /// Independent triangles (`GL_TRIANGLES`).
    Triangles = sys::GL_TRIANGLES,
    /// Connected triangle strip (`GL_TRIANGLE_STRIP`).
    TriangleStrip = sys::GL_TRIANGLE_STRIP,
    /// Connected triangle fan (`GL_TRIANGLE_FAN`).
    TriangleFan = sys::GL_TRIANGLE_FAN,
    /// Tessellation patches (`GL_PATCHES`).
    Patches = sys::GL_PATCHES,
}

// ---------------------------------------------------------------------------
// Buffer enums
// ---------------------------------------------------------------------------

/// OpenGL buffer binding targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum BufferTarget {
    /// Vertex attribute buffer (`GL_ARRAY_BUFFER`).
    Array = sys::GL_ARRAY_BUFFER,
    /// Index buffer (`GL_ELEMENT_ARRAY_BUFFER`).
    ElementArray = sys::GL_ELEMENT_ARRAY_BUFFER,
    /// Uniform buffer object (`GL_UNIFORM_BUFFER`).
    Uniform = sys::GL_UNIFORM_BUFFER,
    /// Shader storage buffer object (`GL_SHADER_STORAGE_BUFFER`, GL 4.3+).
    ShaderStorage = sys::GL_SHADER_STORAGE_BUFFER,
    /// Copy source buffer (`GL_COPY_READ_BUFFER`).
    CopyRead = sys::GL_COPY_READ_BUFFER,
    /// Copy destination buffer (`GL_COPY_WRITE_BUFFER`).
    CopyWrite = sys::GL_COPY_WRITE_BUFFER,
    /// Pixel readback buffer (`GL_PIXEL_PACK_BUFFER`).
    PixelPack = sys::GL_PIXEL_PACK_BUFFER,
    /// Pixel upload buffer (`GL_PIXEL_UNPACK_BUFFER`).
    PixelUnpack = sys::GL_PIXEL_UNPACK_BUFFER,
    /// Indirect draw command buffer (`GL_DRAW_INDIRECT_BUFFER`).
    DrawIndirect = sys::GL_DRAW_INDIRECT_BUFFER,
    /// Indirect compute dispatch buffer (`GL_DISPATCH_INDIRECT_BUFFER`, GL 4.3+).
    DispatchIndirect = sys::GL_DISPATCH_INDIRECT_BUFFER,
    /// Atomic counter buffer (`GL_ATOMIC_COUNTER_BUFFER`, GL 4.2+).
    AtomicCounter = sys::GL_ATOMIC_COUNTER_BUFFER,
}

impl BufferTarget {
    /// Returns `true` if this target supports indexed binding (`glBindBufferBase` / `glBindBufferRange`).
    #[inline]
    pub const fn is_indexed(self) -> bool {
        matches!(
            self,
            Self::Uniform | Self::ShaderStorage | Self::AtomicCounter
        )
    }
}

/// OpenGL buffer usage hint for mutable buffer stores (`glBufferData`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum BufferUsage {
    /// Modified once, used a few times for drawing (`GL_STREAM_DRAW`).
    StreamDraw = sys::GL_STREAM_DRAW,
    /// Modified once, read back a few times (`GL_STREAM_READ`).
    StreamRead = sys::GL_STREAM_READ,
    /// Modified once, copied a few times (`GL_STREAM_COPY`).
    StreamCopy = sys::GL_STREAM_COPY,
    /// Modified once, used many times for drawing (`GL_STATIC_DRAW`).
    StaticDraw = sys::GL_STATIC_DRAW,
    /// Modified once, read back many times (`GL_STATIC_READ`).
    StaticRead = sys::GL_STATIC_READ,
    /// Modified once, copied many times (`GL_STATIC_COPY`).
    StaticCopy = sys::GL_STATIC_COPY,
    /// Modified repeatedly, used many times for drawing (`GL_DYNAMIC_DRAW`).
    DynamicDraw = sys::GL_DYNAMIC_DRAW,
    /// Modified repeatedly, read back many times (`GL_DYNAMIC_READ`).
    DynamicRead = sys::GL_DYNAMIC_READ,
    /// Modified repeatedly, copied many times (`GL_DYNAMIC_COPY`).
    DynamicCopy = sys::GL_DYNAMIC_COPY,
}

// ---------------------------------------------------------------------------
// Shader & program enums
// ---------------------------------------------------------------------------

/// Programmable OpenGL shader stages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum ShaderStage {
    /// Vertex shader (`GL_VERTEX_SHADER`).
    Vertex = sys::GL_VERTEX_SHADER,
    /// Fragment shader (`GL_FRAGMENT_SHADER`).
    Fragment = sys::GL_FRAGMENT_SHADER,
    /// Geometry shader (`GL_GEOMETRY_SHADER`).
    Geometry = sys::GL_GEOMETRY_SHADER,
    /// Tessellation control shader (`GL_TESS_CONTROL_SHADER`, GL 4.0+).
    TessControl = sys::GL_TESS_CONTROL_SHADER,
    /// Tessellation evaluation shader (`GL_TESS_EVALUATION_SHADER`, GL 4.0+).
    TessEvaluation = sys::GL_TESS_EVALUATION_SHADER,
    /// Compute shader (`GL_COMPUTE_SHADER`, GL 4.3+).
    Compute = sys::GL_COMPUTE_SHADER,
}

/// Strongly-typed uniform location returned by [`crate::Program::uniform_location`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UniformLocation(pub(crate) i32);

impl UniformLocation {
    /// Returns the raw OpenGL uniform location integer.
    #[inline]
    pub const fn raw(self) -> i32 {
        self.0
    }
}

/// Strongly-typed vertex attribute location returned by [`crate::Program::attrib_location`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AttribLocation(pub(crate) u32);

impl AttribLocation {
    /// Returns the raw OpenGL attribute index.
    #[inline]
    pub const fn raw(self) -> u32 {
        self.0
    }
}

// ---------------------------------------------------------------------------
// Texture & sampler enums
// ---------------------------------------------------------------------------

/// OpenGL texture binding targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum TextureTarget {
    /// 2D texture (`GL_TEXTURE_2D`).
    Texture2D = sys::GL_TEXTURE_2D,
    /// 3D texture (`GL_TEXTURE_3D`).
    Texture3D = sys::GL_TEXTURE_3D,
    /// Cubemap texture (`GL_TEXTURE_CUBE_MAP`).
    CubeMap = sys::GL_TEXTURE_CUBE_MAP,
    /// 2D texture array (`GL_TEXTURE_2D_ARRAY`).
    Texture2DArray = sys::GL_TEXTURE_2D_ARRAY,
    /// Multisampled 2D texture (`GL_TEXTURE_2D_MULTISAMPLE`).
    Texture2DMultisample = sys::GL_TEXTURE_2D_MULTISAMPLE,
}

/// Sized internal texture / renderbuffer storage format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum InternalFormat {
    /// 8-bit normalized red (`GL_R8`).
    R8 = sys::GL_R8,
    /// 8-bit normalized red-green (`GL_RG8`).
    Rg8 = sys::GL_RG8,
    /// 8-bit normalized RGB (`GL_RGB8`).
    Rgb8 = sys::GL_RGB8,
    /// 8-bit normalized RGBA (`GL_RGBA8`).
    Rgba8 = sys::GL_RGBA8,
    /// sRGB 8-bit RGB (`GL_SRGB8`).
    Srgb8 = sys::GL_SRGB8,
    /// sRGB 8-bit RGB + linear alpha (`GL_SRGB8_ALPHA8`).
    Srgb8Alpha8 = sys::GL_SRGB8_ALPHA8,
    /// 16-bit float red (`GL_R16F`).
    R16f = sys::GL_R16F,
    /// 16-bit float red-green (`GL_RG16F`).
    Rg16f = sys::GL_RG16F,
    /// 16-bit float RGB (`GL_RGB16F`).
    Rgb16f = sys::GL_RGB16F,
    /// 16-bit float RGBA (`GL_RGBA16F`).
    Rgba16f = sys::GL_RGBA16F,
    /// 32-bit float red (`GL_R32F`).
    R32f = sys::GL_R32F,
    /// 32-bit float red-green (`GL_RG32F`).
    Rg32f = sys::GL_RG32F,
    /// 32-bit float RGB (`GL_RGB32F`).
    Rgb32f = sys::GL_RGB32F,
    /// 32-bit float RGBA (`GL_RGBA32F`).
    Rgba32f = sys::GL_RGBA32F,
    /// 32-bit unsigned int red (`GL_R32UI`).
    R32ui = sys::GL_R32UI,
    /// 32-bit unsigned int RGBA (`GL_RGBA32UI`).
    Rgba32ui = sys::GL_RGBA32UI,
    /// 16-bit depth (`GL_DEPTH_COMPONENT16`).
    Depth16 = sys::GL_DEPTH_COMPONENT16,
    /// 24-bit depth (`GL_DEPTH_COMPONENT24`).
    Depth24 = sys::GL_DEPTH_COMPONENT24,
    /// 32-bit float depth (`GL_DEPTH_COMPONENT32F`).
    Depth32f = sys::GL_DEPTH_COMPONENT32F,
    /// Packed 24-bit depth + 8-bit stencil (`GL_DEPTH24_STENCIL8`).
    Depth24Stencil8 = sys::GL_DEPTH24_STENCIL8,
    /// Packed 32-bit float depth + 8-bit stencil (`GL_DEPTH32F_STENCIL8`).
    Depth32fStencil8 = sys::GL_DEPTH32F_STENCIL8,
}

/// Client pixel transfer channel layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum PixelFormat {
    /// Single red channel (`GL_RED`).
    Red = sys::GL_RED,
    /// Two channels (`GL_RG`).
    Rg = sys::GL_RG,
    /// Three RGB channels (`GL_RGB`).
    Rgb = sys::GL_RGB,
    /// Four RGBA channels (`GL_RGBA`).
    Rgba = sys::GL_RGBA,
    /// Three BGR channels (`GL_BGR`).
    Bgr = sys::GL_BGR,
    /// Four BGRA channels (`GL_BGRA`).
    Bgra = sys::GL_BGRA,
    /// Depth component (`GL_DEPTH_COMPONENT`).
    DepthComponent = sys::GL_DEPTH_COMPONENT,
}

impl PixelFormat {
    /// Number of color/depth components per pixel for this format.
    #[inline]
    pub const fn channel_count(self) -> usize {
        match self {
            Self::Red | Self::DepthComponent => 1,
            Self::Rg => 2,
            Self::Rgb | Self::Bgr => 3,
            Self::Rgba | Self::Bgra => 4,
        }
    }
}

/// Client pixel transfer component data type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum PixelType {
    /// Unsigned 8-bit per component (`GL_UNSIGNED_BYTE`).
    U8 = sys::GL_UNSIGNED_BYTE,
    /// Unsigned 16-bit per component (`GL_UNSIGNED_SHORT`).
    U16 = sys::GL_UNSIGNED_SHORT,
    /// Unsigned 32-bit per component (`GL_UNSIGNED_INT`).
    U32 = sys::GL_UNSIGNED_INT,
    /// 16-bit half-float per component (`GL_HALF_FLOAT`).
    F16 = sys::GL_HALF_FLOAT,
    /// 32-bit float per component (`GL_FLOAT`).
    F32 = sys::GL_FLOAT,
}

impl PixelType {
    /// Byte size per component.
    #[inline]
    pub const fn component_bytes(self) -> usize {
        match self {
            Self::U8 => 1,
            Self::U16 | Self::F16 => 2,
            Self::U32 | Self::F32 => 4,
        }
    }
}

/// Texture minification/magnification filter mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum TextureFilter {
    /// Nearest-neighbor (`GL_NEAREST`).
    Nearest = sys::GL_NEAREST,
    /// Bilinear interpolation (`GL_LINEAR`).
    Linear = sys::GL_LINEAR,
    /// Nearest texel, nearest mip level (`GL_NEAREST_MIPMAP_NEAREST`).
    NearestMipmapNearest = sys::GL_NEAREST_MIPMAP_NEAREST,
    /// Linear texel, nearest mip level (`GL_LINEAR_MIPMAP_NEAREST`).
    LinearMipmapNearest = sys::GL_LINEAR_MIPMAP_NEAREST,
    /// Nearest texel, linear mip blend (`GL_NEAREST_MIPMAP_LINEAR`).
    NearestMipmapLinear = sys::GL_NEAREST_MIPMAP_LINEAR,
    /// Trilinear filtering (`GL_LINEAR_MIPMAP_LINEAR`).
    LinearMipmapLinear = sys::GL_LINEAR_MIPMAP_LINEAR,
}

impl TextureFilter {
    /// Returns `true` if valid as a magnification filter (`Nearest` or `Linear`).
    #[inline]
    pub const fn is_valid_mag_filter(self) -> bool {
        matches!(self, Self::Nearest | Self::Linear)
    }
}

/// Texture coordinate wrap mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum TextureWrap {
    /// Tile texture (`GL_REPEAT`).
    Repeat = sys::GL_REPEAT,
    /// Clamp coordinates to `[0, 1]` edge (`GL_CLAMP_TO_EDGE`).
    ClampToEdge = sys::GL_CLAMP_TO_EDGE,
    /// Clamp to border color (`GL_CLAMP_TO_BORDER`).
    ClampToBorder = sys::GL_CLAMP_TO_BORDER,
    /// Mirror and tile (`GL_MIRRORED_REPEAT`).
    MirroredRepeat = sys::GL_MIRRORED_REPEAT,
}

// ---------------------------------------------------------------------------
// Framebuffer enums
// ---------------------------------------------------------------------------

/// Framebuffer binding target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum FramebufferTarget {
    /// Both read and draw framebuffer (`GL_FRAMEBUFFER`).
    Both = sys::GL_FRAMEBUFFER,
    /// Read framebuffer (`GL_READ_FRAMEBUFFER`).
    Read = sys::GL_READ_FRAMEBUFFER,
    /// Draw framebuffer (`GL_DRAW_FRAMEBUFFER`).
    Draw = sys::GL_DRAW_FRAMEBUFFER,
}

/// Framebuffer attachment point.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FramebufferAttachment {
    /// Color attachment index `0..31` (`GL_COLOR_ATTACHMENT0 + index`).
    Color(u32),
    /// Depth attachment (`GL_DEPTH_ATTACHMENT`).
    Depth,
    /// Stencil attachment (`GL_STENCIL_ATTACHMENT`).
    Stencil,
    /// Combined depth-stencil attachment (`GL_DEPTH_STENCIL_ATTACHMENT`).
    DepthStencil,
}

impl FramebufferAttachment {
    /// Converts to the raw `GLenum` attachment constant, checking color index bounds.
    pub(crate) const fn to_gl(self) -> Option<sys::GLenum> {
        match self {
            Self::Color(idx) if idx < 32 => Some(sys::GL_COLOR_ATTACHMENT0 + idx),
            Self::Color(_) => None,
            Self::Depth => Some(sys::GL_DEPTH_ATTACHMENT),
            Self::Stencil => Some(sys::GL_STENCIL_ATTACHMENT),
            Self::DepthStencil => Some(sys::GL_DEPTH_STENCIL_ATTACHMENT),
        }
    }
}

/// Framebuffer completeness status returned by `glCheckFramebufferStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FramebufferStatus {
    /// `GL_FRAMEBUFFER_COMPLETE`
    Complete,
    /// `GL_FRAMEBUFFER_UNDEFINED`
    Undefined,
    /// `GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT`
    IncompleteAttachment,
    /// `GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT`
    IncompleteMissingAttachment,
    /// `GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER`
    IncompleteDrawBuffer,
    /// `GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER`
    IncompleteReadBuffer,
    /// `GL_FRAMEBUFFER_UNSUPPORTED`
    Unsupported,
    /// `GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE`
    IncompleteMultisample,
    /// `GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS`
    IncompleteLayerTargets,
    /// Any unrecognized driver status code.
    Unknown(u32),
}

impl FramebufferStatus {
    /// Converts a raw `GLenum` from `glCheckFramebufferStatus` into [`FramebufferStatus`].
    #[inline]
    pub const fn from_raw(raw: u32) -> Self {
        match raw {
            sys::GL_FRAMEBUFFER_COMPLETE => Self::Complete,
            sys::GL_FRAMEBUFFER_UNDEFINED => Self::Undefined,
            sys::GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT => Self::IncompleteAttachment,
            sys::GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => Self::IncompleteMissingAttachment,
            sys::GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER => Self::IncompleteDrawBuffer,
            sys::GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER => Self::IncompleteReadBuffer,
            sys::GL_FRAMEBUFFER_UNSUPPORTED => Self::Unsupported,
            sys::GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE => Self::IncompleteMultisample,
            sys::GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS => Self::IncompleteLayerTargets,
            other => Self::Unknown(other),
        }
    }

    /// Returns `true` if the framebuffer is complete and ready for rendering.
    #[inline]
    pub const fn is_complete(self) -> bool {
        matches!(self, Self::Complete)
    }
}

// ---------------------------------------------------------------------------
// Pipeline state enums
// ---------------------------------------------------------------------------

/// Toggleable OpenGL pipeline capabilities (`glEnable` / `glDisable`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum Capability {
    /// Alpha/color blending (`GL_BLEND`).
    Blend = sys::GL_BLEND,
    /// Face culling (`GL_CULL_FACE`).
    CullFace = sys::GL_CULL_FACE,
    /// Depth testing (`GL_DEPTH_TEST`).
    DepthTest = sys::GL_DEPTH_TEST,
    /// Scissor rectangle clipping (`GL_SCISSOR_TEST`).
    ScissorTest = sys::GL_SCISSOR_TEST,
    /// Stencil testing (`GL_STENCIL_TEST`).
    StencilTest = sys::GL_STENCIL_TEST,
    /// Multisample anti-aliasing (`GL_MULTISAMPLE`).
    Multisample = sys::GL_MULTISAMPLE,
    /// Automatic linear-to-sRGB framebuffer conversion (`GL_FRAMEBUFFER_SRGB`).
    FramebufferSrgb = sys::GL_FRAMEBUFFER_SRGB,
    /// Vertex shader writes `gl_PointSize` (`GL_PROGRAM_POINT_SIZE`).
    ProgramPointSize = sys::GL_PROGRAM_POINT_SIZE,
    /// Seamless cubemap filtering (`GL_TEXTURE_CUBE_MAP_SEAMLESS`).
    TextureCubeMapSeamless = sys::GL_TEXTURE_CUBE_MAP_SEAMLESS,
}

/// Depth / stencil / shadow comparison function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum CompareFunc {
    /// Never passes (`GL_NEVER`).
    Never = sys::GL_NEVER,
    /// Passes if incoming `<` stored (`GL_LESS`).
    Less = sys::GL_LESS,
    /// Passes if incoming `==` stored (`GL_EQUAL`).
    Equal = sys::GL_EQUAL,
    /// Passes if incoming `<=` stored (`GL_LEQUAL`).
    LessOrEqual = sys::GL_LEQUAL,
    /// Passes if incoming `>` stored (`GL_GREATER`).
    Greater = sys::GL_GREATER,
    /// Passes if incoming `!=` stored (`GL_NOTEQUAL`).
    NotEqual = sys::GL_NOTEQUAL,
    /// Passes if incoming `>=` stored (`GL_GEQUAL`).
    GreaterOrEqual = sys::GL_GEQUAL,
    /// Always passes (`GL_ALWAYS`).
    Always = sys::GL_ALWAYS,
}

/// Blending factor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum BlendFactor {
    /// `0` (`GL_ZERO`).
    Zero = sys::GL_ZERO,
    /// `1` (`GL_ONE`).
    One = sys::GL_ONE,
    /// Source color (`GL_SRC_COLOR`).
    SrcColor = sys::GL_SRC_COLOR,
    /// `1 - src_color` (`GL_ONE_MINUS_SRC_COLOR`).
    OneMinusSrcColor = sys::GL_ONE_MINUS_SRC_COLOR,
    /// Source alpha (`GL_SRC_ALPHA`).
    SrcAlpha = sys::GL_SRC_ALPHA,
    /// `1 - src_alpha` (`GL_ONE_MINUS_SRC_ALPHA`).
    OneMinusSrcAlpha = sys::GL_ONE_MINUS_SRC_ALPHA,
    /// Destination alpha (`GL_DST_ALPHA`).
    DstAlpha = sys::GL_DST_ALPHA,
    /// `1 - dst_alpha` (`GL_ONE_MINUS_DST_ALPHA`).
    OneMinusDstAlpha = sys::GL_ONE_MINUS_DST_ALPHA,
    /// Destination color (`GL_DST_COLOR`).
    DstColor = sys::GL_DST_COLOR,
    /// `1 - dst_color` (`GL_ONE_MINUS_DST_COLOR`).
    OneMinusDstColor = sys::GL_ONE_MINUS_DST_COLOR,
    /// `min(src_alpha, 1 - dst_alpha)` (`GL_SRC_ALPHA_SATURATE`).
    SrcAlphaSaturate = sys::GL_SRC_ALPHA_SATURATE,
}

/// Blending equation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum BlendEquation {
    /// `src + dst` (`GL_FUNC_ADD`).
    Add = sys::GL_FUNC_ADD,
    /// `src - dst` (`GL_FUNC_SUBTRACT`).
    Subtract = sys::GL_FUNC_SUBTRACT,
    /// `dst - src` (`GL_FUNC_REVERSE_SUBTRACT`).
    ReverseSubtract = sys::GL_FUNC_REVERSE_SUBTRACT,
    /// `min(src, dst)` (`GL_MIN`).
    Min = sys::GL_MIN,
    /// `max(src, dst)` (`GL_MAX`).
    Max = sys::GL_MAX,
}

/// Face culling selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum CullFace {
    /// Cull front-facing polygons (`GL_FRONT`).
    Front = sys::GL_FRONT,
    /// Cull back-facing polygons (`GL_BACK`).
    Back = sys::GL_BACK,
    /// Cull both front and back faces (`GL_FRONT_AND_BACK`).
    FrontAndBack = sys::GL_FRONT_AND_BACK,
}

/// Front-face winding order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum FrontFace {
    /// Clockwise winding (`GL_CW`).
    Clockwise = sys::GL_CW,
    /// Counter-clockwise winding (`GL_CCW`, OpenGL default).
    CounterClockwise = sys::GL_CCW,
}

/// Polygon rasterization mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum PolygonMode {
    /// Vertices drawn as points (`GL_POINT`).
    Point = sys::GL_POINT,
    /// Wireframe edges (`GL_LINE`).
    Line = sys::GL_LINE,
    /// Filled polygons (`GL_FILL`).
    Fill = sys::GL_FILL,
}

// ---------------------------------------------------------------------------
// Geometry structs
// ---------------------------------------------------------------------------

/// Screen-space viewport rectangle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Viewport {
    /// Left origin in pixels.
    pub x: i32,
    /// Bottom origin in pixels.
    pub y: i32,
    /// Viewport width in pixels.
    pub width: u32,
    /// Viewport height in pixels.
    pub height: u32,
}

impl Viewport {
    /// Creates a new viewport rectangle.
    #[inline]
    pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

/// Screen-space scissor clip rectangle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ScissorRect {
    /// Left origin in pixels.
    pub x: i32,
    /// Bottom origin in pixels.
    pub y: i32,
    /// Scissor width in pixels.
    pub width: u32,
    /// Scissor height in pixels.
    pub height: u32,
}

impl ScissorRect {
    /// Creates a new scissor rectangle.
    #[inline]
    pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

/// Linear RGBA clear color.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClearColor {
    /// Red channel `[0.0, 1.0]`.
    pub r: f32,
    /// Green channel `[0.0, 1.0]`.
    pub g: f32,
    /// Blue channel `[0.0, 1.0]`.
    pub b: f32,
    /// Alpha channel `[0.0, 1.0]`.
    pub a: f32,
}

impl ClearColor {
    /// Opaque black `(0, 0, 0, 1)`.
    pub const BLACK: Self = Self::new(0.0, 0.0, 0.0, 1.0);
    /// Opaque white `(1, 1, 1, 1)`.
    pub const WHITE: Self = Self::new(1.0, 1.0, 1.0, 1.0);
    /// Transparent black `(0, 0, 0, 0)`.
    pub const TRANSPARENT: Self = Self::new(0.0, 0.0, 0.0, 0.0);

    /// Creates a new RGBA clear color.
    #[inline]
    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }
}

// ---------------------------------------------------------------------------
// Zero-dependency typed bitflags macro
// ---------------------------------------------------------------------------

macro_rules! define_bitflags {
    (
        $(#[$meta:meta])*
        pub struct $name:ident(u32);
        $(
            $(#[$const_meta:meta])*
            pub const $const_name:ident = $val:expr;
        )*
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
        #[repr(transparent)]
        pub struct $name(u32);

        impl $name {
            /// Empty flag set (`0`).
            pub const EMPTY: Self = Self(0);

            $(
                $(#[$const_meta])*
                pub const $const_name: Self = Self($val);
            )*

            /// Creates flags from a raw bitmask.
            #[inline]
            pub const fn from_bits(bits: u32) -> Self {
                Self(bits)
            }

            /// Returns the raw bitmask.
            #[inline]
            pub const fn bits(self) -> u32 {
                self.0
            }

            /// Returns `true` if no bits are set.
            #[inline]
            pub const fn is_empty(self) -> bool {
                self.0 == 0
            }

            /// Returns `true` if all bits in `other` are set in `self`.
            #[inline]
            pub const fn contains(self, other: Self) -> bool {
                (self.0 & other.0) == other.0
            }

            /// Bitwise union (`const`-compatible).
            #[inline]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0)
            }
        }

        impl BitOr for $name {
            type Output = Self;
            #[inline]
            fn bitor(self, rhs: Self) -> Self {
                Self(self.0 | rhs.0)
            }
        }

        impl BitOrAssign for $name {
            #[inline]
            fn bitor_assign(&mut self, rhs: Self) {
                self.0 |= rhs.0;
            }
        }

        impl BitAnd for $name {
            type Output = Self;
            #[inline]
            fn bitand(self, rhs: Self) -> Self {
                Self(self.0 & rhs.0)
            }
        }

        impl BitAndAssign for $name {
            #[inline]
            fn bitand_assign(&mut self, rhs: Self) {
                self.0 &= rhs.0;
            }
        }
    };
}

define_bitflags! {
    /// Bitmask of framebuffer attachments to clear (`glClear`) or blit (`glBlitFramebuffer`).
    pub struct ClearMask(u32);
    /// Color buffer (`GL_COLOR_BUFFER_BIT`).
    pub const COLOR = sys::GL_COLOR_BUFFER_BIT;
    /// Depth buffer (`GL_DEPTH_BUFFER_BIT`).
    pub const DEPTH = sys::GL_DEPTH_BUFFER_BIT;
    /// Stencil buffer (`GL_STENCIL_BUFFER_BIT`).
    pub const STENCIL = sys::GL_STENCIL_BUFFER_BIT;
}

define_bitflags! {
    /// Immutable buffer storage flags (`glBufferStorage`, GL 4.4+).
    pub struct BufferStorageFlags(u32);
    /// Allow `glBufferSubData` updates (`GL_DYNAMIC_STORAGE_BIT`).
    pub const DYNAMIC_STORAGE = sys::GL_DYNAMIC_STORAGE_BIT;
    /// Allow mapping for read (`GL_MAP_READ_BIT`).
    pub const MAP_READ = sys::GL_MAP_READ_BIT;
    /// Allow mapping for write (`GL_MAP_WRITE_BIT`).
    pub const MAP_WRITE = sys::GL_MAP_WRITE_BIT;
    /// Allow persistent mapping (`GL_MAP_PERSISTENT_BIT`).
    pub const MAP_PERSISTENT = sys::GL_MAP_PERSISTENT_BIT;
    /// Coherent persistent mapping (`GL_MAP_COHERENT_BIT`).
    pub const MAP_COHERENT = sys::GL_MAP_COHERENT_BIT;
    /// Hint to place storage in client/host memory (`GL_CLIENT_STORAGE_BIT`).
    pub const CLIENT_STORAGE = sys::GL_CLIENT_STORAGE_BIT;
}

define_bitflags! {
    /// Memory barrier bitmask (`glMemoryBarrier`, GL 4.2+).
    pub struct MemoryBarrierFlags(u32);
    /// Vertex attribute fetches (`GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT`).
    pub const VERTEX_ATTRIB_ARRAY = sys::GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
    /// Index buffer fetches (`GL_ELEMENT_ARRAY_BARRIER_BIT`).
    pub const ELEMENT_ARRAY = sys::GL_ELEMENT_ARRAY_BARRIER_BIT;
    /// Uniform buffer fetches (`GL_UNIFORM_BARRIER_BIT`).
    pub const UNIFORM = sys::GL_UNIFORM_BARRIER_BIT;
    /// Texture fetches (`GL_TEXTURE_FETCH_BARRIER_BIT`).
    pub const TEXTURE_FETCH = sys::GL_TEXTURE_FETCH_BARRIER_BIT;
    /// Shader image load/store (`GL_SHADER_IMAGE_ACCESS_BARRIER_BIT`).
    pub const SHADER_IMAGE_ACCESS = sys::GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
    /// Indirect draw/dispatch command reads (`GL_COMMAND_BARRIER_BIT`).
    pub const COMMAND = sys::GL_COMMAND_BARRIER_BIT;
    /// Pixel buffer operations (`GL_PIXEL_BUFFER_BARRIER_BIT`).
    pub const PIXEL_BUFFER = sys::GL_PIXEL_BUFFER_BARRIER_BIT;
    /// Texture upload/download (`GL_TEXTURE_UPDATE_BARRIER_BIT`).
    pub const TEXTURE_UPDATE = sys::GL_TEXTURE_UPDATE_BARRIER_BIT;
    /// Buffer upload/download (`GL_BUFFER_UPDATE_BARRIER_BIT`).
    pub const BUFFER_UPDATE = sys::GL_BUFFER_UPDATE_BARRIER_BIT;
    /// Framebuffer reads/writes (`GL_FRAMEBUFFER_BARRIER_BIT`).
    pub const FRAMEBUFFER = sys::GL_FRAMEBUFFER_BARRIER_BIT;
    /// Shader storage buffer reads/writes (`GL_SHADER_STORAGE_BARRIER_BIT`).
    pub const SHADER_STORAGE = sys::GL_SHADER_STORAGE_BARRIER_BIT;
    /// All memory barriers (`GL_ALL_BARRIER_BITS`).
    pub const ALL = sys::GL_ALL_BARRIER_BITS;
}

// ---------------------------------------------------------------------------
// Debug output enums (GL 4.3 / KHR_debug)
// ---------------------------------------------------------------------------

/// Origin of an OpenGL debug message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DebugSource {
    /// Core OpenGL API call.
    Api,
    /// Window system (WGL/GLX/EGL).
    WindowSystem,
    /// GLSL shader compiler.
    ShaderCompiler,
    /// Third-party tool or layer.
    ThirdParty,
    /// Application-generated message.
    Application,
    /// Other source.
    Other(u32),
}

impl DebugSource {
    pub(crate) const fn from_raw(raw: u32) -> Self {
        match raw {
            sys::GL_DEBUG_SOURCE_API => Self::Api,
            sys::GL_DEBUG_SOURCE_WINDOW_SYSTEM => Self::WindowSystem,
            sys::GL_DEBUG_SOURCE_SHADER_COMPILER => Self::ShaderCompiler,
            sys::GL_DEBUG_SOURCE_THIRD_PARTY => Self::ThirdParty,
            sys::GL_DEBUG_SOURCE_APPLICATION => Self::Application,
            other => Self::Other(other),
        }
    }
}

/// Category of an OpenGL debug message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DebugType {
    /// API error.
    Error,
    /// Deprecated functionality used.
    DeprecatedBehavior,
    /// Undefined behavior detected.
    UndefinedBehavior,
    /// Portability warning.
    Portability,
    /// Performance warning.
    Performance,
    /// Command stream marker.
    Marker,
    /// Other category.
    Other(u32),
}

impl DebugType {
    pub(crate) const fn from_raw(raw: u32) -> Self {
        match raw {
            sys::GL_DEBUG_TYPE_ERROR => Self::Error,
            sys::GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR => Self::DeprecatedBehavior,
            sys::GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR => Self::UndefinedBehavior,
            sys::GL_DEBUG_TYPE_PORTABILITY => Self::Portability,
            sys::GL_DEBUG_TYPE_PERFORMANCE => Self::Performance,
            sys::GL_DEBUG_TYPE_MARKER => Self::Marker,
            other => Self::Other(other),
        }
    }
}

/// Severity level of an OpenGL debug message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DebugSeverity {
    /// Critical error or dangerous undefined behavior.
    High,
    /// Major performance warning or shader compilation warning.
    Medium,
    /// Redundant state change or minor warning.
    Low,
    /// Informational notification.
    Notification,
    /// Unknown severity.
    Unknown(u32),
}

impl DebugSeverity {
    pub(crate) const fn from_raw(raw: u32) -> Self {
        match raw {
            sys::GL_DEBUG_SEVERITY_HIGH => Self::High,
            sys::GL_DEBUG_SEVERITY_MEDIUM => Self::Medium,
            sys::GL_DEBUG_SEVERITY_LOW => Self::Low,
            sys::GL_DEBUG_SEVERITY_NOTIFICATION => Self::Notification,
            other => Self::Unknown(other),
        }
    }
}