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
use crate::platform::NativeGLContextMethods;
use crate::gl_context::GLContextDispatcher;
use crate::GLVersion;
use sparkle::gl;
use std::ffi::CString;
use std::os::raw::c_void;
use std::ptr;
use std::sync::mpsc;

use winapi::shared::windef::{HDC, HGLRC};
use winapi::shared::minwindef::HMODULE;
use winapi::um::libloaderapi::{LoadLibraryA, GetProcAddress};
use winapi::um::winuser::{WindowFromDC, ReleaseDC, DestroyWindow};
use super::wgl;
use super::wgl_attributes::*;
use super::utils;

// Wrappers to satisfy `Sync`.
struct HMODULEWrapper(HMODULE);
unsafe impl Sync for HMODULEWrapper {}

lazy_static! {
    static ref GL_LIB: Option<HMODULEWrapper>  = {
        let p = unsafe { LoadLibraryA(b"opengl32.dll\0".as_ptr() as *const _) };
        if p.is_null() {
            error!("WGL: opengl32.dll not found!");
            None
        } else {
            debug!("WGL: opengl32.dll loaded!");
            Some(HMODULEWrapper(p))
        }
    };

    static ref PROC_ADDR_CTX: Option<NativeGLContext> = {
        match unsafe { utils::create_offscreen(ptr::null_mut(), &WGLAttributes::default()) } {
            Ok(ref res) => {
                let ctx = NativeGLContext {
                    render_ctx: res.0,
                    device_ctx: res.1,
                    weak: false,
                };
                Some(ctx)
            }
            Err(s) => {
                error!("Error creating GetProcAddress helper context: {}", s);
                None
            }
        }
    };
}

pub struct NativeGLContext {
    render_ctx: HGLRC,
    device_ctx: HDC,
    weak: bool,
}

impl Drop for NativeGLContext {
    fn drop(&mut self) {
        unsafe {
            if !self.weak {
                // the context to be deleted needs to be unbound
                self.unbind().unwrap();
                wgl::DeleteContext(self.render_ctx as *const _);
                let window = WindowFromDC(self.device_ctx);
                debug_assert!(!window.is_null());
                ReleaseDC(window, self.device_ctx);
                DestroyWindow(window);
            }
        }
    }
}

unsafe impl Send for NativeGLContext {}
unsafe impl Sync for NativeGLContext {}

pub struct NativeGLContextHandle(HGLRC, HDC);
unsafe impl Send for NativeGLContextHandle {}
unsafe impl Sync for NativeGLContextHandle {}

impl NativeGLContextMethods for NativeGLContext {
    type Handle = NativeGLContextHandle;

    fn get_proc_address(addr: &str) -> *const () {
        let addr = CString::new(addr.as_bytes()).unwrap();
        let addr = addr.as_ptr();
        unsafe {
            if wgl::GetCurrentContext().is_null() {
                // wglGetProcAddress only works in the presence of a valid GL context
                // We use a dummy ctx when the caller calls this function without a valid GL context
                if let Some(ref ctx) = *PROC_ADDR_CTX {
                    if ctx.make_current().is_err() {
                        return ptr::null_mut();
                    }
                } else {
                    return ptr::null_mut();
                }
            }

            let p = wgl::GetProcAddress(addr) as *const ();
            if !p.is_null() {
                return p;
            }
            // wglGetProcAddress​ doesn't return function pointers for some legacy functions,
            // (the ones coming from OpenGL 1.1)
            // These functions are exported by the opengl32.dll itself,
            // so we have to fallback to kernel32 getProcAddress if wglGetProcAddress​ return null
            match *GL_LIB {
                Some(ref lib) => GetProcAddress(lib.0, addr) as *const _,
                None => ptr::null_mut(),
            }
        }
    }

    fn create_shared(with: Option<&Self::Handle>,
                     api_type: &gl::GlType,
                     api_version: GLVersion) -> Result<Self, &'static str> {
        Self::create_shared_with_dispatcher(with, api_type, api_version, None)
    }

    fn create_shared_with_dispatcher(with: Option<&Self::Handle>,
                                     api_type: &gl::GlType,
                                     api_version: GLVersion,
                                     dispatcher: Option<Box<GLContextDispatcher>>)
        -> Result<NativeGLContext, &'static str> {
        let (render_ctx, device_ctx) = match with {
            Some(ref handle) => (handle.0, handle.1),
            None => (ptr::null_mut(), ptr::null_mut())
        };

        if let Some(ref dispatcher) = dispatcher {
            // wglShareLists fails if the context to share is current in a different thread.
            // Additionally wglMakeCurrent cannot 'steal' a context that is current in other thread, so
            // we have to unbind the shared context in its own thread, call wglShareLists in this thread
            // and bind the original share context again when the wglShareList is completed.
            let (tx, rx) = mpsc::channel();
            dispatcher.dispatch(Box::new(move || {
                let result = unsafe {
                    if wgl::MakeCurrent(ptr::null_mut(), ptr::null_mut()) == 0 {
                        Err(())
                    } else {
                        Ok(())
                    }
                };
                tx.send(result).unwrap();
            }));
            // Wait until wglMakeCurrent operation is completed in the thread of the shared context
            if rx.recv().unwrap().is_err() {
                return Err("Error creating WGL context: WGL::MakeCurrent failed in shared context")
            }
        }

        let mut attributes = WGLAttributes::default();
        attributes.opengl_es = match *api_type {
            gl::GlType::Gles => true,
            _ => false,
        };

        match api_version {
            GLVersion::Major(major) => {
                attributes.major_version = major as u32;
                attributes.minor_version = if attributes.opengl_es {
                    0
                } else {
                    1
                };
            },
            GLVersion::MajorMinor(major, minor) => { 
                attributes.major_version = major as u32;
                attributes.minor_version = minor as u32;
            }
        }

        let result = match unsafe { utils::create_offscreen(render_ctx, &attributes) } {
            Ok(ref res) => {
                let ctx = NativeGLContext {
                    render_ctx: res.0,
                    device_ctx: res.1,
                    weak: false,
                };
                Ok(ctx)
            }
            Err(s) => {
                error!("WGL: {}", s);
                Err("Error creating WGL context")
            }
        };

        // Restore shared context
        if let Some(ref dispatcher) = dispatcher {
            let (tx, rx) = mpsc::channel();
            let handle = NativeGLContextHandle(render_ctx, device_ctx);
            dispatcher.dispatch(Box::new(move || {
                unsafe { 
                    if wgl::MakeCurrent(handle.1 as *const _, handle.0 as *const _) == 0 {
                        error!("Error restoring WGL shared context: WGL MakeCurrent failed");
                    } 
                };
                tx.send(()).unwrap();
            }));
            // Wait until wglMakeCurrent operation is completed in the thread of the shared context
            rx.recv().unwrap();
        }

        result
    }

    fn is_current(&self) -> bool {
        unsafe { wgl::GetCurrentContext() == self.render_ctx as *const c_void }
    }

    fn current() -> Option<Self> {
        if let Some(handle) = Self::current_handle() {
            Some(NativeGLContext {
                render_ctx: handle.0,
                device_ctx: handle.1,
                weak: true,
            })
        } else {
            None
        }
    }

    fn current_handle() -> Option<Self::Handle> {
        let ctx = unsafe { wgl::GetCurrentContext() };
        let hdc = unsafe { wgl::GetCurrentDC() };
        if ctx.is_null() || hdc.is_null() {
            None
        } else {
            Some(NativeGLContextHandle(ctx as HGLRC, hdc as HDC))
        }
    }

    fn make_current(&self) -> Result<(), &'static str> {
        unsafe {
            if wgl::MakeCurrent(self.device_ctx as *const _, self.render_ctx as *const _) != 0 {
                Ok(())
            } else {
                Err("WGL::makeCurrent failed")
            }
        }
    }

    fn unbind(&self) -> Result<(), &'static str> {
        unsafe {
            if self.is_current() && wgl::MakeCurrent(ptr::null_mut(), ptr::null_mut()) == 0 {
                Err("WGL::MakeCurrent (on unbind)")
            } else {
                Ok(())
            }
        }
    }

    fn handle(&self) -> Self::Handle {
        NativeGLContextHandle(self.render_ctx, self.device_ctx)
    }
}