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
//! Api config picking and creating utils.
#![allow(unreachable_patterns)]

use std::num::NonZeroU32;

use bitflags::bitflags;
use raw_window_handle::RawWindowHandle;

use crate::display::{Display, GetGlDisplay};
use crate::private::{gl_api_dispatch, Sealed};

#[cfg(x11_platform)]
use crate::platform::x11::{X11GlConfigExt, X11VisualInfo};

#[cfg(cgl_backend)]
use crate::api::cgl::config::Config as CglConfig;
#[cfg(egl_backend)]
use crate::api::egl::config::Config as EglConfig;
#[cfg(glx_backend)]
use crate::api::glx::config::Config as GlxConfig;
#[cfg(wgl_backend)]
use crate::api::wgl::config::Config as WglConfig;

/// The trait to group all common config option.
pub trait GlConfig: Sealed {
    /// The type of the underlying color buffer.
    ///
    /// `None` is returned when the format can not be identified.
    fn color_buffer_type(&self) -> Option<ColorBufferType>;

    /// Whether the config uses floating pixels.
    fn float_pixels(&self) -> bool;

    /// The size of the alpha.
    fn alpha_size(&self) -> u8;

    /// The size of the depth buffer.
    fn depth_size(&self) -> u8;

    /// The size of the stencil buffer.
    fn stencil_size(&self) -> u8;

    /// The number of samples in multisample buffer.
    ///
    /// Zero would mean that there're no samples.
    fn num_samples(&self) -> u8;

    /// Whether the config supports creating srgb capable [`Surface`].
    ///
    /// [`Surface`]: crate::surface::Surface
    fn srgb_capable(&self) -> bool;

    /// Whether the config supports creating transparent surfaces.
    ///
    /// This function will return `None` when the property couldn't be
    /// identified, in that case transparent window could still work.
    fn supports_transparency(&self) -> Option<bool>;

    /// The type of the surfaces that can be created with this config.
    fn config_surface_types(&self) -> ConfigSurfaceTypes;

    /// The [`crate::config::Api`] supported by the configuration.
    fn api(&self) -> Api;
}

/// The trait to
pub trait GetGlConfig: Sealed {
    /// The config type.
    type Target: GlConfig;

    /// Get the GL config used to create a particular GL object.
    fn config(&self) -> Self::Target;
}

/// Get the raw config.
pub trait AsRawConfig {
    /// Obtain the [`RawConfig`] of the underlying Api.
    fn raw_config(&self) -> RawConfig;
}

/// Builder for the [`ConfigTemplate`].
#[derive(Debug, Default, Clone)]
pub struct ConfigTemplateBuilder {
    template: ConfigTemplate,
}

impl ConfigTemplateBuilder {
    /// Create a new configuration template builder.
    #[inline]
    pub fn new() -> Self {
        Default::default()
    }

    /// Number of alpha bits in the color buffer.
    ///
    /// By default `8` is requested.
    #[inline]
    pub fn with_alpha_size(mut self, alpha_size: u8) -> Self {
        self.template.alpha_size = alpha_size;
        self
    }

    /// Wether the floating pixel formats should be used.
    ///
    /// By default `false` is requested.
    #[inline]
    pub fn with_float_pixels(mut self, float_pixels: bool) -> Self {
        self.template.float_pixels = float_pixels;
        self
    }

    /// Number of bits in the stencil buffer.
    ///
    /// By default `0` is requested.
    #[inline]
    pub fn with_stencil_size(mut self, stencil_size: u8) -> Self {
        self.template.stencil_size = stencil_size;
        self
    }

    /// Number of bits in the depth buffer.
    ///
    /// By default `0` is requested.
    #[inline]
    pub fn with_depth_size(mut self, depth_size: u8) -> Self {
        self.template.depth_size = depth_size;
        self
    }

    /// Whether multisampling configurations should be picked. The `num_samples`
    /// must be a power of two.
    ///
    /// By default multisampling is not specified.
    #[inline]
    pub fn with_multisampling(mut self, num_samples: u8) -> Self {
        debug_assert!(num_samples.is_power_of_two());
        self.template.num_samples = Some(num_samples);
        self
    }

    /// The types of the surfaces that must be supported by the configuration.
    ///
    /// By default only the `WINDOW` bit is set.
    #[inline]
    pub fn with_surface_type(mut self, config_surface_types: ConfigSurfaceTypes) -> Self {
        self.template.config_surface_types = config_surface_types;
        self
    }

    /// The type of the color buffer.
    ///
    /// By default `RGB` buffer with all components sizes of `8` is requested.
    #[inline]
    pub fn with_buffer_type(mut self, color_buffer_type: ColorBufferType) -> Self {
        self.template.color_buffer_type = color_buffer_type;
        self
    }

    /// The set of apis that are supported by configuration.
    ///
    /// By default api isn't specified when requesting the configuration.
    #[inline]
    pub fn with_api(mut self, api: Api) -> Self {
        self.template.api = Some(api);
        self
    }

    /// Wether the stereo pairs should be present.
    ///
    /// By default it isn't specified.
    #[inline]
    pub fn with_stereoscopy(mut self, stereoscopy: Option<bool>) -> Self {
        self.template.stereoscopy = stereoscopy;
        self
    }

    /// Wether the single buffer should be used.
    ///
    /// By default `false` is requested.
    #[inline]
    pub fn with_single_buffering(mut self, single_buffering: bool) -> Self {
        self.template.single_buffering = single_buffering;
        self
    }

    /// Wether the configuration should support transparency.
    ///
    /// The default is `false`.
    ///
    /// # Api-specific
    ///
    /// EGL on X11 doesn't provide a way to create a transparent surface at the
    /// time of writing. Use GLX for that instead.
    #[inline]
    pub fn with_transparency(mut self, transparency: bool) -> Self {
        self.template.transparency = transparency;
        self
    }

    /// With the maximum sizes of pbuffer.
    #[inline]
    pub fn with_pbuffer_sizes(mut self, width: NonZeroU32, height: NonZeroU32) -> Self {
        self.template.max_pbuffer_width = Some(width.into());
        self.template.max_pbuffer_height = Some(height.into());
        self
    }

    /// Wether the configuration should prefer hardware accelerated formats or
    /// not.
    ///
    /// By default hardware acceleration or its absence is not requested.
    pub fn prefer_hardware_accelerated(mut self, hardware_accerelated: Option<bool>) -> Self {
        self.template.hardware_accelerated = hardware_accerelated;
        self
    }

    /// Request config that can render to a particular native window.
    ///
    /// # Platform-specific
    ///
    /// This will use native window when matching the config to get the best one
    /// suitable for rendering into that window.
    ///
    /// When using WGL it's the most reliable way to get a working
    /// configuration. With GLX it'll use the visual passed in
    /// `native_window` to match the config.
    pub fn compatible_with_native_window(mut self, native_window: RawWindowHandle) -> Self {
        self.template.native_window = Some(native_window);
        self
    }

    /// With supported swap intervals.
    ///
    /// By default the value isn't specified.
    ////
    /// # Api-specific
    ///
    /// Only supported with `EGL`.
    #[inline]
    pub fn with_swap_interval(
        mut self,
        min_swap_interval: Option<u16>,
        max_swap_interval: Option<u16>,
    ) -> Self {
        self.template.min_swap_interval = min_swap_interval;
        self.template.max_swap_interval = max_swap_interval;
        self
    }

    /// Build the template to match the configs against.
    #[must_use]
    pub fn build(self) -> ConfigTemplate {
        self.template
    }
}

/// The context configuration template that is used to find desired config.
#[derive(Debug, Clone)]
pub struct ConfigTemplate {
    /// The type of the backing buffer and ancillary buffers.
    pub(crate) color_buffer_type: ColorBufferType,

    /// Bits of alpha in the color buffer.
    pub(crate) alpha_size: u8,

    /// Bits of depth in the depth buffer.
    pub(crate) depth_size: u8,

    /// Bits of stencil in the stencil buffer.
    pub(crate) stencil_size: u8,

    /// The amount of samples in multisample buffer.
    pub(crate) num_samples: Option<u8>,

    /// The minimum swap interval supported by the configuration.
    pub(crate) min_swap_interval: Option<u16>,

    /// The maximum swap interval supported by the configuration.
    pub(crate) max_swap_interval: Option<u16>,

    /// The types of the surfaces supported by the configuration.
    pub(crate) config_surface_types: ConfigSurfaceTypes,

    /// The rendering Api's supported by the configuration.
    pub(crate) api: Option<Api>,

    /// The config should support transparency.
    pub(crate) transparency: bool,

    /// The config should prefer single buffering.
    pub(crate) single_buffering: bool,

    /// The config supports stereoscopy.
    pub(crate) stereoscopy: Option<bool>,

    /// The config uses floating pixels.
    pub(crate) float_pixels: bool,

    /// The maximum width of the pbuffer.
    pub(crate) max_pbuffer_width: Option<u32>,

    /// The config should prefer hardware accelerated formats.
    pub(crate) hardware_accelerated: Option<bool>,

    /// The maximum height of the pbuffer.
    pub(crate) max_pbuffer_height: Option<u32>,

    /// The native window config should support rendering into.
    pub(crate) native_window: Option<RawWindowHandle>,
}

impl Default for ConfigTemplate {
    fn default() -> Self {
        ConfigTemplate {
            color_buffer_type: ColorBufferType::Rgb { r_size: 8, g_size: 8, b_size: 8 },

            alpha_size: 8,

            depth_size: 24,

            stencil_size: 8,

            num_samples: None,

            transparency: false,

            stereoscopy: None,

            min_swap_interval: None,

            max_swap_interval: None,

            single_buffering: false,

            float_pixels: false,

            config_surface_types: ConfigSurfaceTypes::WINDOW,

            max_pbuffer_width: None,
            max_pbuffer_height: None,

            native_window: None,
            hardware_accelerated: None,

            api: None,
        }
    }
}

bitflags! {
    /// The types of the surface supported by the config.
    pub struct ConfigSurfaceTypes: u8 {
        /// Context must support windows.
        const WINDOW  = 0b00000001;

        /// Context must support pixmaps.
        const PIXMAP  = 0b00000010;

        /// Context must support pbuffers.
        const PBUFFER = 0b00000100;
    }
}

bitflags! {
    /// The Api supported by the config.
    pub struct Api : u8 {
        /// Context supports OpenGL API.
        const OPENGL = 0b00000001;

        /// Context supports OpenGL ES 1 API.
        const GLES1  = 0b00000010;

        /// Context supports OpenGL ES 2 API.
        const GLES2  = 0b00000100;

        /// Context supports OpenGL ES 3 API.
        const GLES3  = 0b00001000;
    }
}

/// The buffer type baked by the config.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorBufferType {
    /// The backing buffer is using RGB format.
    Rgb {
        /// Size of the red component in bits.
        r_size: u8,
        /// Size of the green component in bits.
        g_size: u8,
        /// Size of the blue component in bits.
        b_size: u8,
    },

    /// The backing buffer is using Luminance.
    Luminance(u8),
}

/// The GL configuration used to create [`Surface`] and [`Context`] in a cross
/// platform way.
///
/// The config could be accessed from any thread.
///
/// ```no_run
/// fn test_send<T: Send>() {}
/// fn test_sync<T: Sync>() {}
/// test_send::<glutin::config::Config>();
/// test_sync::<glutin::config::Config>();
/// ```
///
/// [`Surface`]: crate::surface::Surface
/// [`Context`]: crate::context::NotCurrentContext
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Config {
    /// The EGL config.
    #[cfg(egl_backend)]
    Egl(EglConfig),

    /// The GLX config.
    #[cfg(glx_backend)]
    Glx(GlxConfig),

    /// The WGL config.
    #[cfg(wgl_backend)]
    Wgl(WglConfig),

    /// The CGL config.
    #[cfg(cgl_backend)]
    Cgl(CglConfig),
}

impl GlConfig for Config {
    fn color_buffer_type(&self) -> Option<ColorBufferType> {
        gl_api_dispatch!(self; Self(config) => config.color_buffer_type())
    }

    fn float_pixels(&self) -> bool {
        gl_api_dispatch!(self; Self(config) => config.float_pixels())
    }

    fn alpha_size(&self) -> u8 {
        gl_api_dispatch!(self; Self(config) => config.alpha_size())
    }

    fn depth_size(&self) -> u8 {
        gl_api_dispatch!(self; Self(config) => config.depth_size())
    }

    fn stencil_size(&self) -> u8 {
        gl_api_dispatch!(self; Self(config) => config.stencil_size())
    }

    fn num_samples(&self) -> u8 {
        gl_api_dispatch!(self; Self(config) => config.num_samples())
    }

    fn srgb_capable(&self) -> bool {
        gl_api_dispatch!(self; Self(config) => config.srgb_capable())
    }

    fn config_surface_types(&self) -> ConfigSurfaceTypes {
        gl_api_dispatch!(self; Self(config) => config.config_surface_types())
    }

    fn supports_transparency(&self) -> Option<bool> {
        gl_api_dispatch!(self; Self(config) => config.supports_transparency())
    }

    fn api(&self) -> Api {
        gl_api_dispatch!(self; Self(config) => config.api())
    }
}

impl GetGlDisplay for Config {
    type Target = Display;

    fn display(&self) -> Self::Target {
        gl_api_dispatch!(self; Self(config) => config.display(); as Display)
    }
}

#[cfg(x11_platform)]
impl X11GlConfigExt for Config {
    fn x11_visual(&self) -> Option<X11VisualInfo> {
        gl_api_dispatch!(self; Self(config) => config.x11_visual())
    }
}

impl Sealed for Config {}

/// Raw config.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawConfig {
    /// Raw EGL config.
    #[cfg(egl_backend)]
    Egl(*const std::ffi::c_void),

    /// Raw GLX config.
    #[cfg(glx_backend)]
    Glx(*const std::ffi::c_void),

    /// WGL pixel format index.
    #[cfg(wgl_backend)]
    Wgl(i32),

    /// NSOpenGLPixelFormat.
    #[cfg(cgl_backend)]
    Cgl(*const std::ffi::c_void),
}

impl AsRawConfig for Config {
    fn raw_config(&self) -> RawConfig {
        gl_api_dispatch!(self; Self(config) => config.raw_config())
    }
}