summaryrefslogtreecommitdiffstats
path: root/third_party/rust/wgpu-hal/src/gles/wgl.rs
blob: aae70478b481a26455b0456541718d30c7861e4d (plain)
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
use glow::HasContext;
use glutin_wgl_sys::wgl_extra::{
    Wgl, CONTEXT_CORE_PROFILE_BIT_ARB, CONTEXT_DEBUG_BIT_ARB, CONTEXT_FLAGS_ARB,
    CONTEXT_PROFILE_MASK_ARB,
};
use once_cell::sync::Lazy;
use parking_lot::{Mutex, MutexGuard, RwLock};
use raw_window_handle::{RawDisplayHandle, RawWindowHandle};
use std::{
    collections::HashSet,
    ffi::{c_void, CStr, CString},
    io::Error,
    mem,
    os::raw::c_int,
    ptr,
    sync::{
        mpsc::{sync_channel, SyncSender},
        Arc,
    },
    thread,
    time::Duration,
};
use wgt::InstanceFlags;
use winapi::{
    shared::{
        minwindef::{FALSE, HMODULE, LPARAM, LRESULT, UINT, WPARAM},
        windef::{HDC, HGLRC, HWND},
    },
    um::{
        libloaderapi::{GetModuleHandleA, GetProcAddress, LoadLibraryA},
        wingdi::{
            wglCreateContext, wglDeleteContext, wglGetCurrentContext, wglGetProcAddress,
            wglMakeCurrent, ChoosePixelFormat, DescribePixelFormat, GetPixelFormat, SetPixelFormat,
            SwapBuffers, PFD_DOUBLEBUFFER, PFD_DRAW_TO_WINDOW, PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA,
            PIXELFORMATDESCRIPTOR,
        },
        winuser::{
            CreateWindowExA, DefWindowProcA, DestroyWindow, GetDC, RegisterClassExA, ReleaseDC,
            CS_OWNDC, WNDCLASSEXA,
        },
    },
};

/// The amount of time to wait while trying to obtain a lock to the adapter context
const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 1;

/// A wrapper around a `[`glow::Context`]` and the required WGL context that uses locking to
/// guarantee exclusive access when shared with multiple threads.
pub struct AdapterContext {
    inner: Arc<Mutex<Inner>>,
}

unsafe impl Sync for AdapterContext {}
unsafe impl Send for AdapterContext {}

impl AdapterContext {
    pub fn is_owned(&self) -> bool {
        true
    }

    pub fn raw_context(&self) -> *mut c_void {
        self.inner.lock().context.context as *mut _
    }

    /// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to
    /// do rendering.
    #[track_caller]
    pub fn lock(&self) -> AdapterContextLock<'_> {
        let inner = self
            .inner
            // Don't lock forever. If it takes longer than 1 second to get the lock we've got a
            // deadlock and should panic to show where we got stuck
            .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
            .expect("Could not lock adapter context. This is most-likely a deadlock.");

        inner.context.make_current(inner.device.dc).unwrap();

        AdapterContextLock { inner }
    }

    /// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to
    /// do rendering.
    ///
    /// Unlike [`lock`](Self::lock), this accepts a device to pass to `make_current` and exposes the error
    /// when `make_current` fails.
    #[track_caller]
    fn lock_with_dc(&self, device: HDC) -> Result<AdapterContextLock<'_>, Error> {
        let inner = self
            .inner
            .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
            .expect("Could not lock adapter context. This is most-likely a deadlock.");

        inner
            .context
            .make_current(device)
            .map(|()| AdapterContextLock { inner })
    }
}

/// A guard containing a lock to an [`AdapterContext`]
pub struct AdapterContextLock<'a> {
    inner: MutexGuard<'a, Inner>,
}

impl<'a> std::ops::Deref for AdapterContextLock<'a> {
    type Target = glow::Context;

    fn deref(&self) -> &Self::Target {
        &self.inner.gl
    }
}

impl<'a> Drop for AdapterContextLock<'a> {
    fn drop(&mut self) {
        self.inner.context.unmake_current().unwrap();
    }
}

struct WglContext {
    context: HGLRC,
}

impl WglContext {
    fn make_current(&self, device: HDC) -> Result<(), Error> {
        if unsafe { wglMakeCurrent(device, self.context) } == FALSE {
            Err(Error::last_os_error())
        } else {
            Ok(())
        }
    }

    fn unmake_current(&self) -> Result<(), Error> {
        if unsafe { wglGetCurrentContext().is_null() } {
            return Ok(());
        }
        if unsafe { wglMakeCurrent(ptr::null_mut(), ptr::null_mut()) } == FALSE {
            Err(Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

impl Drop for WglContext {
    fn drop(&mut self) {
        unsafe {
            if wglDeleteContext(self.context) == FALSE {
                log::error!("failed to delete WGL context {}", Error::last_os_error());
            }
        };
    }
}

unsafe impl Send for WglContext {}
unsafe impl Sync for WglContext {}

struct Inner {
    gl: glow::Context,
    device: InstanceDevice,
    context: WglContext,
}

unsafe impl Send for Inner {}
unsafe impl Sync for Inner {}

pub struct Instance {
    srgb_capable: bool,
    inner: Arc<Mutex<Inner>>,
}

unsafe impl Send for Instance {}
unsafe impl Sync for Instance {}

fn load_gl_func(name: &str, module: Option<HMODULE>) -> *const c_void {
    let addr = CString::new(name.as_bytes()).unwrap();
    let mut ptr = unsafe { wglGetProcAddress(addr.as_ptr()) };
    if ptr.is_null() {
        if let Some(module) = module {
            ptr = unsafe { GetProcAddress(module, addr.as_ptr()) };
        }
    }
    ptr.cast()
}

fn get_extensions(extra: &Wgl, dc: HDC) -> HashSet<String> {
    if extra.GetExtensionsStringARB.is_loaded() {
        unsafe { CStr::from_ptr(extra.GetExtensionsStringARB(dc as *const _)) }
            .to_str()
            .unwrap_or("")
    } else {
        ""
    }
    .split(' ')
    .map(|s| s.to_owned())
    .collect()
}

unsafe fn setup_pixel_format(dc: HDC) -> Result<(), crate::InstanceError> {
    let mut format: PIXELFORMATDESCRIPTOR = unsafe { mem::zeroed() };
    format.nVersion = 1;
    format.nSize = mem::size_of_val(&format) as u16;
    format.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    format.iPixelType = PFD_TYPE_RGBA;
    format.cColorBits = 8;

    let index = unsafe { ChoosePixelFormat(dc, &format) };
    if index == 0 {
        return Err(crate::InstanceError::with_source(
            String::from("unable to choose pixel format"),
            Error::last_os_error(),
        ));
    }

    let current = unsafe { GetPixelFormat(dc) };

    if index != current && unsafe { SetPixelFormat(dc, index, &format) } == FALSE {
        return Err(crate::InstanceError::with_source(
            String::from("unable to set pixel format"),
            Error::last_os_error(),
        ));
    }

    let index = unsafe { GetPixelFormat(dc) };
    if index == 0 {
        return Err(crate::InstanceError::with_source(
            String::from("unable to get pixel format index"),
            Error::last_os_error(),
        ));
    }
    if unsafe { DescribePixelFormat(dc, index, mem::size_of_val(&format) as UINT, &mut format) }
        == 0
    {
        return Err(crate::InstanceError::with_source(
            String::from("unable to read pixel format"),
            Error::last_os_error(),
        ));
    }

    if format.dwFlags & PFD_SUPPORT_OPENGL == 0 || format.iPixelType != PFD_TYPE_RGBA {
        return Err(crate::InstanceError::new(String::from(
            "unsuitable pixel format",
        )));
    }
    Ok(())
}

fn create_global_window_class() -> Result<CString, crate::InstanceError> {
    let instance = unsafe { GetModuleHandleA(ptr::null()) };
    if instance.is_null() {
        return Err(crate::InstanceError::with_source(
            String::from("unable to get executable instance"),
            Error::last_os_error(),
        ));
    }

    // Use the address of `UNIQUE` as part of the window class name to ensure different
    // `wgpu` versions use different names.
    static UNIQUE: Mutex<u8> = Mutex::new(0);
    let class_addr: *const _ = &UNIQUE;
    let name = format!("wgpu Device Class {:x}\0", class_addr as usize);
    let name = CString::from_vec_with_nul(name.into_bytes()).unwrap();

    // Use a wrapper function for compatibility with `windows-rs`.
    unsafe extern "system" fn wnd_proc(
        window: HWND,
        msg: UINT,
        wparam: WPARAM,
        lparam: LPARAM,
    ) -> LRESULT {
        unsafe { DefWindowProcA(window, msg, wparam, lparam) }
    }

    let window_class = WNDCLASSEXA {
        cbSize: mem::size_of::<WNDCLASSEXA>() as u32,
        style: CS_OWNDC,
        lpfnWndProc: Some(wnd_proc),
        cbClsExtra: 0,
        cbWndExtra: 0,
        hInstance: instance,
        hIcon: ptr::null_mut(),
        hCursor: ptr::null_mut(),
        hbrBackground: ptr::null_mut(),
        lpszMenuName: ptr::null_mut(),
        lpszClassName: name.as_ptr(),
        hIconSm: ptr::null_mut(),
    };

    let atom = unsafe { RegisterClassExA(&window_class) };

    if atom == 0 {
        return Err(crate::InstanceError::with_source(
            String::from("unable to register window class"),
            Error::last_os_error(),
        ));
    }

    // We intentionally leak the window class as we only need one per process.

    Ok(name)
}

fn get_global_window_class() -> Result<CString, crate::InstanceError> {
    static GLOBAL: Lazy<Result<CString, crate::InstanceError>> =
        Lazy::new(create_global_window_class);
    GLOBAL.clone()
}

struct InstanceDevice {
    dc: HDC,

    /// This is used to keep the thread owning `dc` alive until this struct is dropped.
    _tx: SyncSender<()>,
}

fn create_instance_device() -> Result<InstanceDevice, crate::InstanceError> {
    #[derive(Clone, Copy)]
    struct SendDc(HDC);
    unsafe impl Sync for SendDc {}
    unsafe impl Send for SendDc {}

    struct Window {
        window: HWND,
    }
    impl Drop for Window {
        fn drop(&mut self) {
            unsafe {
                if DestroyWindow(self.window) == FALSE {
                    log::error!("failed to destroy window {}", Error::last_os_error());
                }
            };
        }
    }
    struct DeviceContextHandle {
        dc: HDC,
        window: HWND,
    }
    impl Drop for DeviceContextHandle {
        fn drop(&mut self) {
            unsafe {
                ReleaseDC(self.window, self.dc);
            };
        }
    }

    let window_class = get_global_window_class()?;

    let (drop_tx, drop_rx) = sync_channel(0);
    let (setup_tx, setup_rx) = sync_channel(0);

    // We spawn a thread which owns the hidden window for this instance.
    thread::Builder::new()
        .stack_size(256 * 1024)
        .name("wgpu-hal WGL Instance Thread".to_owned())
        .spawn(move || {
            let setup = (|| {
                let instance = unsafe { GetModuleHandleA(ptr::null()) };
                if instance.is_null() {
                    return Err(crate::InstanceError::with_source(
                        String::from("unable to get executable instance"),
                        Error::last_os_error(),
                    ));
                }

                // Create a hidden window since we don't pass `WS_VISIBLE`.
                let window = unsafe {
                    CreateWindowExA(
                        0,
                        window_class.as_ptr(),
                        window_class.as_ptr(),
                        0,
                        0,
                        0,
                        1,
                        1,
                        ptr::null_mut(),
                        ptr::null_mut(),
                        instance,
                        ptr::null_mut(),
                    )
                };
                if window.is_null() {
                    return Err(crate::InstanceError::with_source(
                        String::from("unable to create hidden instance window"),
                        Error::last_os_error(),
                    ));
                }
                let window = Window { window };

                let dc = unsafe { GetDC(window.window) };
                if dc.is_null() {
                    return Err(crate::InstanceError::with_source(
                        String::from("unable to create memory device"),
                        Error::last_os_error(),
                    ));
                }
                let dc = DeviceContextHandle {
                    dc,
                    window: window.window,
                };
                unsafe { setup_pixel_format(dc.dc)? };

                Ok((window, dc))
            })();

            match setup {
                Ok((_window, dc)) => {
                    setup_tx.send(Ok(SendDc(dc.dc))).unwrap();
                    // Wait for the shutdown event to free the window and device context handle.
                    drop_rx.recv().ok();
                }
                Err(err) => {
                    setup_tx.send(Err(err)).unwrap();
                }
            }
        })
        .map_err(|e| {
            crate::InstanceError::with_source(String::from("unable to create instance thread"), e)
        })?;

    let dc = setup_rx.recv().unwrap()?.0;

    Ok(InstanceDevice { dc, _tx: drop_tx })
}

impl crate::Instance for Instance {
    type A = super::Api;

    unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
        profiling::scope!("Init OpenGL (WGL) Backend");
        let opengl_module = unsafe { LoadLibraryA("opengl32.dll\0".as_ptr() as *const _) };
        if opengl_module.is_null() {
            return Err(crate::InstanceError::with_source(
                String::from("unable to load the OpenGL library"),
                Error::last_os_error(),
            ));
        }

        let device = create_instance_device()?;
        let dc = device.dc;

        let context = unsafe { wglCreateContext(dc) };
        if context.is_null() {
            return Err(crate::InstanceError::with_source(
                String::from("unable to create initial OpenGL context"),
                Error::last_os_error(),
            ));
        }
        let context = WglContext { context };
        context.make_current(dc).map_err(|e| {
            crate::InstanceError::with_source(
                String::from("unable to set initial OpenGL context as current"),
                e,
            )
        })?;

        let extra = Wgl::load_with(|name| load_gl_func(name, None));
        let extensions = get_extensions(&extra, dc);

        let can_use_profile = extensions.contains("WGL_ARB_create_context_profile")
            && extra.CreateContextAttribsARB.is_loaded();

        let context = if can_use_profile {
            let attributes = [
                CONTEXT_PROFILE_MASK_ARB as c_int,
                CONTEXT_CORE_PROFILE_BIT_ARB as c_int,
                CONTEXT_FLAGS_ARB as c_int,
                if desc.flags.contains(InstanceFlags::DEBUG) {
                    CONTEXT_DEBUG_BIT_ARB as c_int
                } else {
                    0
                },
                0, // End of list
            ];
            let context = unsafe {
                extra.CreateContextAttribsARB(dc as *const _, ptr::null(), attributes.as_ptr())
            };
            if context.is_null() {
                return Err(crate::InstanceError::with_source(
                    String::from("unable to create OpenGL context"),
                    Error::last_os_error(),
                ));
            }
            WglContext {
                context: context as *mut _,
            }
        } else {
            context
        };

        context.make_current(dc).map_err(|e| {
            crate::InstanceError::with_source(
                String::from("unable to set OpenGL context as current"),
                e,
            )
        })?;

        let mut gl = unsafe {
            glow::Context::from_loader_function(|name| load_gl_func(name, Some(opengl_module)))
        };

        let extra = Wgl::load_with(|name| load_gl_func(name, None));
        let extensions = get_extensions(&extra, dc);

        let srgb_capable = extensions.contains("WGL_EXT_framebuffer_sRGB")
            || extensions.contains("WGL_ARB_framebuffer_sRGB")
            || gl
                .supported_extensions()
                .contains("GL_ARB_framebuffer_sRGB");

        // In contrast to OpenGL ES, OpenGL requires explicitly enabling sRGB conversions,
        // as otherwise the user has to do the sRGB conversion.
        if srgb_capable {
            unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
        }

        if desc.flags.contains(InstanceFlags::VALIDATION) && gl.supports_debug() {
            log::debug!("Enabling GL debug output");
            unsafe { gl.enable(glow::DEBUG_OUTPUT) };
            unsafe { gl.debug_message_callback(super::gl_debug_message_callback) };
        }

        context.unmake_current().map_err(|e| {
            crate::InstanceError::with_source(
                String::from("unable to unset the current WGL context"),
                e,
            )
        })?;

        Ok(Instance {
            inner: Arc::new(Mutex::new(Inner {
                device,
                gl,
                context,
            })),
            srgb_capable,
        })
    }

    #[cfg_attr(target_os = "macos", allow(unused, unused_mut, unreachable_code))]
    unsafe fn create_surface(
        &self,
        _display_handle: RawDisplayHandle,
        window_handle: RawWindowHandle,
    ) -> Result<Surface, crate::InstanceError> {
        let window = if let RawWindowHandle::Win32(handle) = window_handle {
            handle
        } else {
            return Err(crate::InstanceError::new(format!(
                "unsupported window: {window_handle:?}"
            )));
        };
        Ok(Surface {
            window: window.hwnd.get() as *mut _,
            presentable: true,
            swapchain: RwLock::new(None),
            srgb_capable: self.srgb_capable,
        })
    }
    unsafe fn destroy_surface(&self, _surface: Surface) {}

    unsafe fn enumerate_adapters(&self) -> Vec<crate::ExposedAdapter<super::Api>> {
        unsafe {
            super::Adapter::expose(AdapterContext {
                inner: self.inner.clone(),
            })
        }
        .into_iter()
        .collect()
    }
}

struct DeviceContextHandle {
    device: HDC,
    window: HWND,
}

impl Drop for DeviceContextHandle {
    fn drop(&mut self) {
        unsafe {
            ReleaseDC(self.window, self.device);
        };
    }
}

pub struct Swapchain {
    framebuffer: glow::Framebuffer,
    renderbuffer: glow::Renderbuffer,

    /// Extent because the window lies
    extent: wgt::Extent3d,

    format: wgt::TextureFormat,
    format_desc: super::TextureFormatDesc,
    #[allow(unused)]
    sample_type: wgt::TextureSampleType,
}

pub struct Surface {
    window: HWND,
    pub(super) presentable: bool,
    swapchain: RwLock<Option<Swapchain>>,
    srgb_capable: bool,
}

unsafe impl Send for Surface {}
unsafe impl Sync for Surface {}

impl Surface {
    pub(super) unsafe fn present(
        &self,
        _suf_texture: super::Texture,
        context: &AdapterContext,
    ) -> Result<(), crate::SurfaceError> {
        let swapchain = self.swapchain.read();
        let sc = swapchain.as_ref().unwrap();
        let dc = unsafe { GetDC(self.window) };
        if dc.is_null() {
            log::error!(
                "unable to get the device context from window: {}",
                Error::last_os_error()
            );
            return Err(crate::SurfaceError::Other(
                "unable to get the device context from window",
            ));
        }
        let dc = DeviceContextHandle {
            device: dc,
            window: self.window,
        };

        let gl = context.lock_with_dc(dc.device).map_err(|e| {
            log::error!("unable to make the OpenGL context current for surface: {e}",);
            crate::SurfaceError::Other("unable to make the OpenGL context current for surface")
        })?;

        unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) };

        if self.srgb_capable {
            // Disable sRGB conversions for `glBlitFramebuffer` as behavior does diverge between
            // drivers and formats otherwise and we want to ensure no sRGB conversions happen.
            unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) };
        }

        // Note the Y-flipping here. GL's presentation is not flipped,
        // but main rendering is. Therefore, we Y-flip the output positions
        // in the shader, and also this blit.
        unsafe {
            gl.blit_framebuffer(
                0,
                sc.extent.height as i32,
                sc.extent.width as i32,
                0,
                0,
                0,
                sc.extent.width as i32,
                sc.extent.height as i32,
                glow::COLOR_BUFFER_BIT,
                glow::NEAREST,
            )
        };

        if self.srgb_capable {
            unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
        }

        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };

        if unsafe { SwapBuffers(dc.device) } == FALSE {
            log::error!("unable to swap buffers: {}", Error::last_os_error());
            return Err(crate::SurfaceError::Other("unable to swap buffers"));
        }

        Ok(())
    }

    pub fn supports_srgb(&self) -> bool {
        self.srgb_capable
    }
}

impl crate::Surface for Surface {
    type A = super::Api;

    unsafe fn configure(
        &self,
        device: &super::Device,
        config: &crate::SurfaceConfiguration,
    ) -> Result<(), crate::SurfaceError> {
        // Remove the old configuration.
        unsafe { self.unconfigure(device) };

        let dc = unsafe { GetDC(self.window) };
        if dc.is_null() {
            log::error!(
                "unable to get the device context from window: {}",
                Error::last_os_error()
            );
            return Err(crate::SurfaceError::Other(
                "unable to get the device context from window",
            ));
        }
        let dc = DeviceContextHandle {
            device: dc,
            window: self.window,
        };

        if let Err(e) = unsafe { setup_pixel_format(dc.device) } {
            log::error!("unable to setup surface pixel format: {e}",);
            return Err(crate::SurfaceError::Other(
                "unable to setup surface pixel format",
            ));
        }

        let format_desc = device.shared.describe_texture_format(config.format);
        let gl = &device.shared.context.lock_with_dc(dc.device).map_err(|e| {
            log::error!("unable to make the OpenGL context current for surface: {e}",);
            crate::SurfaceError::Other("unable to make the OpenGL context current for surface")
        })?;

        let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| {
            log::error!("Internal swapchain renderbuffer creation failed: {error}");
            crate::DeviceError::OutOfMemory
        })?;
        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) };
        unsafe {
            gl.renderbuffer_storage(
                glow::RENDERBUFFER,
                format_desc.internal,
                config.extent.width as _,
                config.extent.height as _,
            )
        };

        let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| {
            log::error!("Internal swapchain framebuffer creation failed: {error}");
            crate::DeviceError::OutOfMemory
        })?;
        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) };
        unsafe {
            gl.framebuffer_renderbuffer(
                glow::READ_FRAMEBUFFER,
                glow::COLOR_ATTACHMENT0,
                glow::RENDERBUFFER,
                Some(renderbuffer),
            )
        };
        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };

        // Setup presentation mode
        let extra = Wgl::load_with(|name| load_gl_func(name, None));
        let extensions = get_extensions(&extra, dc.device);
        if !(extensions.contains("WGL_EXT_swap_control") && extra.SwapIntervalEXT.is_loaded()) {
            log::error!("WGL_EXT_swap_control is unsupported");
            return Err(crate::SurfaceError::Other(
                "WGL_EXT_swap_control is unsupported",
            ));
        }

        let vsync = match config.present_mode {
            wgt::PresentMode::Immediate => false,
            wgt::PresentMode::Fifo => true,
            _ => {
                log::error!("unsupported present mode: {:?}", config.present_mode);
                return Err(crate::SurfaceError::Other("unsupported present mode"));
            }
        };

        if unsafe { extra.SwapIntervalEXT(if vsync { 1 } else { 0 }) } == FALSE {
            log::error!("unable to set swap interval: {}", Error::last_os_error());
            return Err(crate::SurfaceError::Other("unable to set swap interval"));
        }

        self.swapchain.write().replace(Swapchain {
            renderbuffer,
            framebuffer,
            extent: config.extent,
            format: config.format,
            format_desc,
            sample_type: wgt::TextureSampleType::Float { filterable: false },
        });

        Ok(())
    }

    unsafe fn unconfigure(&self, device: &super::Device) {
        let gl = &device.shared.context.lock();
        if let Some(sc) = self.swapchain.write().take() {
            unsafe {
                gl.delete_renderbuffer(sc.renderbuffer);
                gl.delete_framebuffer(sc.framebuffer)
            };
        }
    }

    unsafe fn acquire_texture(
        &self,
        _timeout_ms: Option<Duration>,
    ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
        let swapchain = self.swapchain.read();
        let sc = swapchain.as_ref().unwrap();
        let texture = super::Texture {
            inner: super::TextureInner::Renderbuffer {
                raw: sc.renderbuffer,
            },
            drop_guard: None,
            array_layer_count: 1,
            mip_level_count: 1,
            format: sc.format,
            format_desc: sc.format_desc.clone(),
            copy_size: crate::CopyExtent {
                width: sc.extent.width,
                height: sc.extent.height,
                depth: 1,
            },
        };
        Ok(Some(crate::AcquiredSurfaceTexture {
            texture,
            suboptimal: false,
        }))
    }
    unsafe fn discard_texture(&self, _texture: super::Texture) {}
}