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
use euclid::Size2D;
use gleam::gl;
use gleam::gl::types::{GLuint};
use std::rc::Rc;

use NativeGLContextMethods;
use GLContextAttributes;
use GLContextCapabilities;
use GLFormats;
use GLLimits;
use DrawBuffer;
use ColorAttachmentType;

/// This is a wrapper over a native headless GL context
pub struct GLContext<Native> {
    gl_: Rc<gl::Gl>,
    native_context: Native,
    /// This an abstraction over a custom framebuffer
    /// with attachments according to WebGLContextAttributes
    // TODO(ecoal95): Ideally we may want a read and a draw
    // framebuffer, but this is not supported in GLES2, review
    // when we have better support
    draw_buffer: Option<DrawBuffer>,
    attributes: GLContextAttributes,
    capabilities: GLContextCapabilities,
    formats: GLFormats,
    limits: GLLimits,
    extensions: Vec<String>
}

impl<Native> GLContext<Native>
    where Native: NativeGLContextMethods,
{
    pub fn create(api_type: gl::GlType,
                  api_version: GLVersion,
                  shared_with: Option<&Native::Handle>)
                  -> Result<Self, &'static str> {
        Self::create_shared_with_dispatcher(api_type, api_version, shared_with, None)
    }

    pub fn create_shared_with_dispatcher(api_type: gl::GlType,
                                         api_version: GLVersion,
                                         shared_with: Option<&Native::Handle>,
                                         dispatcher: Option<Box<GLContextDispatcher>>)
        -> Result<Self, &'static str> {
        let native_context = try!(Native::create_shared_with_dispatcher(shared_with,
                                                                        &api_type,
                                                                        api_version,
                                                                        dispatcher));
        let gl_ = match api_type {
            gl::GlType::Gl => unsafe { gl::GlFns::load_with(|s| Self::get_proc_address(s) as *const _) },
            gl::GlType::Gles => unsafe { gl::GlesFns::load_with(|s| Self::get_proc_address(s) as *const _) },
        };

        try!(native_context.make_current());
        let extensions = Self::query_extensions(&gl_, api_version);
        let attributes = GLContextAttributes::any();
        let formats = GLFormats::detect(&attributes, &extensions[..], api_version);
        let limits = GLLimits::detect(&*gl_);

        Ok(GLContext {
            gl_: gl_,
            native_context: native_context,
            draw_buffer: None,
            attributes: attributes,
            capabilities: GLContextCapabilities::detect(),
            formats: formats,
            limits: limits,
            extensions: extensions
        })
    }

    #[inline(always)]
    pub fn get_proc_address(addr: &str) -> *const () {
        Native::get_proc_address(addr)
    }

    #[inline(always)]
    pub fn current_handle() -> Option<Native::Handle> {
        Native::current_handle()
    }

    pub fn new(size: Size2D<i32>,
               attributes: GLContextAttributes,
               color_attachment_type: ColorAttachmentType,
               api_type: gl::GlType,
               api_version: GLVersion,
               shared_with: Option<&Native::Handle>)
        -> Result<Self, &'static str> {
        Self::new_shared_with_dispatcher(size,
                                         attributes,
                                         color_attachment_type,
                                         api_type,
                                         api_version,
                                         shared_with,
                                         None)
    }

    pub fn new_shared_with_dispatcher(size: Size2D<i32>,
                                      attributes: GLContextAttributes,
                                      color_attachment_type: ColorAttachmentType,
                                      api_type: gl::GlType,
                                      api_version: GLVersion,
                                      shared_with: Option<&Native::Handle>,
                                      dispatcher: Option<Box<GLContextDispatcher>>)
        -> Result<Self, &'static str> {
        // We create a headless context with a dummy size, we're painting to the
        // draw_buffer's framebuffer anyways.
        let mut context =
            try!(Self::create_shared_with_dispatcher(api_type,
                                                     api_version,
                                                     shared_with,
                                                     dispatcher));

        context.formats = GLFormats::detect(&attributes, &context.extensions[..], api_version);
        context.attributes = attributes;

        try!(context.init_offscreen(size, color_attachment_type));

        Ok(context)
    }

    #[inline(always)]
    pub fn with_default_color_attachment(size: Size2D<i32>,
                                         attributes: GLContextAttributes,
                                         api_type: gl::GlType,
                                         api_version: GLVersion,
                                         shared_with: Option<&Native::Handle>)
        -> Result<Self, &'static str> {
        Self::new(size, attributes, ColorAttachmentType::default(), api_type, api_version, shared_with)
    }

    #[inline(always)]
    pub fn make_current(&self) -> Result<(), &'static str> {
        self.native_context.make_current()
    }

    #[inline(always)]
    pub fn unbind(&self) -> Result<(), &'static str> {
        let ret = self.native_context.unbind();

        // OSMesa doesn't allow any API to unbind a context before [1], and just
        // bails out on null context, buffer, or whatever, so not much we can do
        // here. Thus, ignore the failure and just flush the context if we're
        // using an old OSMesa version.
        //
        // [1]: https://www.mail-archive.com/mesa-dev@lists.freedesktop.org/msg128408.html
        if self.native_context.is_osmesa() && ret.is_err() {
            self.gl().flush();
            return Ok(())
        }

        ret
    }

    #[inline(always)]
    pub fn is_current(&self) -> bool {
        self.native_context.is_current()
    }

    #[inline(always)]
    pub fn handle(&self) -> Native::Handle {
        self.native_context.handle()
    }

    pub fn gl(&self) -> &gl::Gl {
        &*self.gl_
    }

    pub fn clone_gl(&self) -> Rc<gl::Gl> {
        self.gl_.clone()
    }

    // Allow borrowing these unmutably
    pub fn borrow_attributes(&self) -> &GLContextAttributes {
        &self.attributes
    }

    pub fn borrow_capabilities(&self) -> &GLContextCapabilities {
        &self.capabilities
    }

    pub fn borrow_formats(&self) -> &GLFormats {
        &self.formats
    }

    pub fn borrow_limits(&self) -> &GLLimits {
        &self.limits
    }

    pub fn borrow_draw_buffer(&self) -> Option<&DrawBuffer> {
        self.draw_buffer.as_ref()
    }

    pub fn get_framebuffer(&self) -> GLuint {
        if let Some(ref db) = self.draw_buffer {
            return db.get_framebuffer();
        }

        let ret = self.gl().get_integer_v(gl::FRAMEBUFFER_BINDING);
        ret as GLuint
    }

    pub fn draw_buffer_size(&self) -> Option<Size2D<i32>> {
        self.draw_buffer.as_ref().map(|db| db.size())
    }

    // We resize just replacing the draw buffer, we don't perform size optimizations
    // in order to keep this generic
    pub fn resize(&mut self, size: Size2D<i32>) -> Result<(), &'static str> {
        if self.draw_buffer.is_some() {
            let color_attachment_type =
                self.borrow_draw_buffer().unwrap().color_attachment_type();
            self.init_offscreen(size, color_attachment_type)
        } else {
            Err("No DrawBuffer found")
        }
    }

    pub fn get_extensions(&self) -> Vec<String> {
        self.extensions.clone()
    }

    fn init_offscreen(&mut self, size: Size2D<i32>, color_attachment_type: ColorAttachmentType) -> Result<(), &'static str> {
        try!(self.create_draw_buffer(size, color_attachment_type));

        debug_assert!(self.is_current());

        self.gl().clear_color(0.0, 0.0, 0.0, 0.0);
        self.gl().clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT);
        self.gl().scissor(0, 0, size.width, size.height);
        self.gl().viewport(0, 0, size.width, size.height);

        Ok(())
    }

    fn create_draw_buffer(&mut self, size: Size2D<i32>, color_attachment_type: ColorAttachmentType) -> Result<(), &'static str> {
        self.draw_buffer = Some(try!(DrawBuffer::new(self, size, color_attachment_type)));
        Ok(())
    }

    fn query_extensions(gl_: &Rc<gl::Gl>, api_version: GLVersion) -> Vec<String> {
        if api_version.major_version() >=3 {
            // glGetString(GL_EXTENSIONS) is deprecated on OpenGL >= 3.x.
            // Some GL backends such as CGL generate INVALID_ENUM error when used.
            // Use the new way to query extensions on OpenGL 3.x (glStringi)
            let n = gl_.get_integer_v(gl::NUM_EXTENSIONS) as usize;
            let mut extensions = Vec::with_capacity(n);
            for index in 0..n {
                extensions.push(gl_.get_string_i(gl::EXTENSIONS, index as u32))
            }
            extensions
        } else {
            let extensions = gl_.get_string(gl::EXTENSIONS);
            extensions.split(&[',',' '][..]).map(|s| s.into()).collect()
        }
    }
}

/// Describes the OpenGL version that is requested when a context is created.
#[derive(Debug, Clone, Copy)]
pub enum GLVersion {
    /// Request a specific major version
    /// The minor version is automatically selected.
    Major(u8),

    /// Request a specific major and minor version version.
    MajorMinor(u8, u8),
}

impl GLVersion {
    // Helper method to get the major version
    pub fn major_version(&self) -> u8 {
        match *self {
            GLVersion::Major(major) => major,
            GLVersion::MajorMinor(major, _) => major,
        }
    }
}

// Dispatches functions to the thread where a NativeGLContext is bound.
// Right now it's used in the WGL implementation to dispatch functions to the thread
// where the context we share from is bound. See the WGL implementation for more details.
pub trait GLContextDispatcher {
    fn dispatch(&self, Box<Fn() + Send>);
}