[go: up one dir, main page]

glium 0.6.3

High-level and safe OpenGL wrapper.
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
/*!
Contains everything related to the internal handling of framebuffer objects.

*/
/*
Here are the rules taken from the official wiki:

Attachment Completeness

Each attachment point itctxt.framebuffer_objects must be complete according to these rules. Empty attachments
(attachments with no image attached) are complete by default. If an image is attached, it must
adhere to the following rules:

The source object for the image still exists and has the same type it was attached with.
The image has a non-zero width and height (the height of a 1D image is assumed to be 1). The
  width/height must also be less than GL_MAX_FRAMEBUFFER_WIDTH and GL_MAX_FRAMEBUFFER_HEIGHT
  respectively (if GL 4.3/ARB_framebuffer_no_attachments).
The layer for 3D or array textures attachments is less than the depth of the texture. It must
  also be less than GL_MAX_FRAMEBUFFER_LAYERS (if GL 4.3/ARB_framebuffer_no_attachments).
The number of samples must be less than GL_MAX_FRAMEBUFFER_SAMPLES (if
  GL 4.3/ARB_framebuffer_no_attachments).
The image's format must match the attachment point's requirements, as defined above.
  Color-renderable formats for color attachments, etc.

Completeness Rules

These are the rules for framebuffer completeness. The order of these rules matters.

If the target​ of glCheckFramebufferStatus references the Default Framebuffer (ie: FBO object
  number 0 is bound), and the default framebuffer does not exist, then you will get
  GL_FRAMEBUFFER_UNDEFINEZ. If the default framebuffer exists, then you always get
  GL_FRAMEBUFFER_COMPLETE. The rest of the rules apply when an FBO is bound.
All attachments must be attachment complete. (GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT when false).
There must be at least one image attached to the FBO, or if OpenGL 4.3 or
  ARB_framebuffer_no_attachment is available, the GL_FRAMEBUFFER_DEFAULT_WIDTH and
  GL_FRAMEBUFFER_DEFAULT_HEIGHT parameters of the framebuffer must both be non-zero.
  (GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT when false).
Each draw buffers must either specify color attachment points that have images attached or
  must be GL_NONE. (GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER when false). Note that this test is
  not performed if OpenGL 4.1 or ARB_ES2_compatibility is available.
If the read buffer is set, then it must specify an attachment point that has an image
  attached. (GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER when false). Note that this test is not
  performed if OpenGL 4.1 or ARB_ES2_compatibility is available.
All images must have the same number of multisample samples.
  (GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE when false).
If a layered image is attached to one attachment, then all attachments must be layered
  attachments. The attached layers do not have to have the same number of layers, nor do the
  layers have to come from the same kind of texture (a cubemap color texture can be paired
  with an array depth texture) (GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS when false).

*/
use std::collections::HashMap;
use std::cmp;
use std::mem;
use std::cell::RefCell;
use std::marker::PhantomData;

use GlObject;
use TextureExt;

use texture::TextureAny;
use framebuffer::RenderBufferAny;

use gl;
use context::CommandContext;
use version::Version;
use version::Api;

/// Represents the attachments to use for an OpenGL framebuffer.
#[derive(Clone)]
pub struct FramebufferAttachments<'a> {
    /// List of color attachments. The first parameter of the tuple is the index, and the
    /// second element is the attachment.
    pub colors: Vec<(u32, Attachment<'a>)>,

    /// The depth and/or stencil attachment to use.
    pub depth_stencil: FramebufferDepthStencilAttachments<'a>,
}

/// Depth and/or stencil attachment to use.
#[derive(Copy, Clone)]
pub enum FramebufferDepthStencilAttachments<'a> {
    /// No depth or stencil buffer.
    None,

    /// A depth attachment.
    DepthAttachment(Attachment<'a>),

    /// A stencil attachment.
    StencilAttachment(Attachment<'a>),

    /// A depth attachment and a stencil attachment.
    DepthAndStencilAttachments(Attachment<'a>, Attachment<'a>),

    /// A single attachment that serves as both depth and stencil buffer.
    DepthStencilAttachment(Attachment<'a>),
}

/// Describes a single framebuffer attachment.
#[derive(Copy, Clone)]
pub enum Attachment<'a> {
    /// An entire texture.
    Texture {
        /// The texture.
        texture: &'a TextureAny,
        /// Mipmap level to use. The main texture is level 0.
        level: u32,
    },
    /// A layer of a texture. Layers are in texture arrays or in 3D textures.
    TextureLayer {
        /// The texture.
        texture: &'a TextureAny,
        /// The layer.
        layer: u32,
        /// Mipmap level to use. The main texture is level 0.
        level: u32,
    },
    /// A renderbuffer.
    RenderBuffer(&'a RenderBufferAny),
}

impl<'a> FramebufferAttachments<'a> {
    /// After building a `FramebufferAttachments` struct, you must use this function
    /// to "compile" the attachments and make sure that they are valid together.
    pub fn validate(self)
                    -> Result<ValidatedAttachments<'a>, ValidationError>
    {
        // turning the attachments into raw attachments
        let (raw_attachments, dimensions, depth_bits, stencil_bits) = {
            fn handle_attachment(a: &Attachment, dim: &mut Option<(u32, u32)>,
                                 num_bits: Option<&mut Option<u16>>)
                                 -> RawAttachment
            {
                match a {
                    &Attachment::Texture { ref texture, level } => {
                        if let Some(num_bits) = num_bits {
                            *num_bits = Some(texture.get_internal_format_if_supported()
                                               .map(|f| f.get_total_bits()).unwrap_or(24) as u16);     // TODO: how to handle this?
                        }

                        match dim {
                            d @ &mut None => *d = Some((texture.get_width(), texture.get_height().unwrap_or(1))),
                            &mut Some((ref mut x, ref mut y)) => {
                                *x = cmp::min(*x, texture.get_width());
                                *y = cmp::min(*y, texture.get_height().unwrap_or(1));
                            }
                        }

                        RawAttachment::Texture {
                            texture: texture.get_id(),
                            bind_point: texture.get_bind_point(),
                            layer: 0,
                            level: level,       // TODO: check validity
                        }
                    },
                    &Attachment::TextureLayer { ref texture, level, layer } => {
                        if let Some(num_bits) = num_bits {
                            *num_bits = Some(texture.get_internal_format_if_supported()
                                               .map(|f| f.get_total_bits()).unwrap_or(24) as u16);     // TODO: how to handle this?
                        }

                        match dim {
                            d @ &mut None => *d = Some((texture.get_width(), texture.get_height().unwrap_or(1))),
                            &mut Some((ref mut x, ref mut y)) => {
                                *x = cmp::min(*x, texture.get_width());
                                *y = cmp::min(*y, texture.get_height().unwrap_or(1));
                            }
                        }

                        RawAttachment::Texture {
                            texture: texture.get_id(),
                            bind_point: texture.get_bind_point(),
                            layer: layer,       // TODO: check validity
                            level: level,       // TODO: check validity
                        }
                    },
                    &Attachment::RenderBuffer(ref buffer) => {
                        if let Some(num_bits) = num_bits {
                            *num_bits = Some(24);    // FIXME: totally random
                        }

                        match dim {
                            d @ &mut None => *d = Some(buffer.get_dimensions()),
                            &mut Some((ref mut x, ref mut y)) => {
                                let curr = buffer.get_dimensions();
                                *x = cmp::min(*x, curr.0);
                                *y = cmp::min(*y, curr.1);
                            }
                        }

                        RawAttachment::RenderBuffer(buffer.get_id())
                    },
                }
            }

            // TODO: check number of samples
            // TODO: check layering

            // the dimensions of the framebuffer object
            let mut dimensions = None;
            // number of depth bits
            let mut depth_bits = None;
            // number of stencil bits
            let mut stencil_bits = None;

            let mut raw_attachments = RawAttachments {
                color: Vec::with_capacity(self.colors.len()),
                depth: None,
                stencil: None,
                depth_stencil: None,
            };

            for &(index, ref a) in &self.colors {
                raw_attachments.color.push((index, handle_attachment(a, &mut dimensions, None)));
            }

            match self.depth_stencil {
                FramebufferDepthStencilAttachments::None => (),
                FramebufferDepthStencilAttachments::DepthAttachment(ref a) => {
                    raw_attachments.depth = Some(handle_attachment(a, &mut dimensions, Some(&mut depth_bits)));
                },
                FramebufferDepthStencilAttachments::StencilAttachment(ref a) => {
                    raw_attachments.stencil = Some(handle_attachment(a, &mut dimensions, Some(&mut stencil_bits)));
                },
                FramebufferDepthStencilAttachments::DepthAndStencilAttachments(ref d, ref s) => {
                    raw_attachments.depth = Some(handle_attachment(d, &mut dimensions, Some(&mut depth_bits)));
                    raw_attachments.stencil = Some(handle_attachment(s, &mut dimensions, Some(&mut stencil_bits)));
                },
                FramebufferDepthStencilAttachments::DepthStencilAttachment(ref a) => {
                    raw_attachments.depth_stencil = Some(handle_attachment(a, &mut dimensions, None));      // FIXME: bit counts
                },
            }

            let dimensions = match dimensions {
                Some(d) => d,
                None => return Err(ValidationError::EmptyFramebufferObjectsNotSupported)
            };

            (raw_attachments, dimensions, depth_bits, stencil_bits)
        };

        Ok(ValidatedAttachments {
            raw: raw_attachments,
            marker: PhantomData,
            dimensions: dimensions,
            depth_buffer_bits: depth_bits,
            stencil_buffer_bits: stencil_bits,
        })
    }
}

/// Represents attachments that have been validated and are usable.
#[derive(Clone)]
pub struct ValidatedAttachments<'a> {
    marker: PhantomData<&'a ()>,
    raw: RawAttachments,
    dimensions: (u32, u32),
    depth_buffer_bits: Option<u16>,
    stencil_buffer_bits: Option<u16>,
}

impl<'a> ValidatedAttachments<'a> {
    /// Returns the dimensions that the framebuffer will have if you use these attachments.
    pub fn get_dimensions(&self) -> (u32, u32) {
        self.dimensions
    }

    /// Returns the number of bits of precision of the depth buffer, or `None` if there is no
    /// depth buffer. Also works for depth-stencil buffers.
    pub fn get_depth_buffer_bits(&self) -> Option<u16> {
        self.depth_buffer_bits
    }

    /// Returns the number of bits of precision of the stencil buffer, or `None` if there is no
    /// stencil buffer. Also works for depth-stencil buffers.
    pub fn get_stencil_buffer_bits(&self) -> Option<u16> {
        self.stencil_buffer_bits
    }
}

/// An error that can happen while validating attachments.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ValidationError {
    EmptyFramebufferObjectsNotSupported,
}

/// Data structure stored in the hashmap.
#[derive(Hash, Clone, Eq, PartialEq)]
struct RawAttachments {
    color: Vec<(u32, RawAttachment)>,
    depth: Option<RawAttachment>,
    stencil: Option<RawAttachment>,
    depth_stencil: Option<RawAttachment>,
}

/// Single attachment.
#[derive(Hash, Copy, Clone, Eq, PartialEq)]
enum RawAttachment {
    Texture {
        bind_point: gl::types::GLenum,
        texture: gl::types::GLuint,
        layer: u32,
        level: u32,
    },
    RenderBuffer(gl::types::GLuint),
}

/// Manages all the framebuffer objects.
///
/// `cleanup` **must** be called when destroying the container, otherwise `Drop` will panic.
pub struct FramebuffersContainer {
    framebuffers: RefCell<HashMap<RawAttachments, FrameBufferObject>>,
}

/// Frame buffer.
struct FrameBufferObject {
    id: gl::types::GLuint,
    current_read_buffer: gl::types::GLenum,
}

impl FramebuffersContainer {
    /// Initializes the container.
    pub fn new() -> FramebuffersContainer {
        FramebuffersContainer {
            framebuffers: RefCell::new(HashMap::new()),
        }
    }

    /// Destroys all framebuffer objects. This is used when using a new context for example.
    pub fn purge_all(ctxt: &mut CommandContext) {
        let mut other = HashMap::new();
        mem::swap(&mut *ctxt.framebuffer_objects.framebuffers.borrow_mut(), &mut other);

        for (_, obj) in other.into_iter() {
            obj.destroy(ctxt);
        }
    }

    /// Destroys all framebuffer objects that contain a precise texture.
    pub fn purge_texture(ctxt: &mut CommandContext, texture: gl::types::GLuint) {
        FramebuffersContainer::purge_if(ctxt, |a| {
            match a {
                &RawAttachment::Texture { texture: id, .. } if id == texture => true,
                _ => false 
            }
        });
    }

    /// Destroys all framebuffer objects that contain a precise renderbuffer.
    pub fn purge_renderbuffer(ctxt: &mut CommandContext, renderbuffer: gl::types::GLuint) {
        FramebuffersContainer::purge_if(ctxt, |a| a == &RawAttachment::RenderBuffer(renderbuffer));
    }

    /// Destroys all framebuffer objects that match a certain condition.
    fn purge_if<F>(mut ctxt: &mut CommandContext, condition: F)
                   where F: Fn(&RawAttachment) -> bool
    {
        let mut framebuffers = ctxt.framebuffer_objects.framebuffers.borrow_mut();

        let mut attachments = Vec::with_capacity(0);
        for (key, _) in framebuffers.iter() {
            if key.color.iter().find(|&&(_, ref id)| condition(id)).is_some() {
                attachments.push(key.clone());
                continue;
            }

            if let Some(ref atch) = key.depth {
                if condition(atch) {
                    attachments.push(key.clone());
                    continue;
                }
            }

            if let Some(ref atch) = key.stencil {
                if condition(atch) {
                    attachments.push(key.clone());
                    continue;
                }
            }

            if let Some(ref atch) = key.depth_stencil {
                if condition(atch) {
                    attachments.push(key.clone());
                    continue;
                }
            }
        }

        for atch in attachments.into_iter() {
            framebuffers.remove(&atch).unwrap().destroy(ctxt);
        }
    }

    /// Destroys all framebuffer objects.
    ///
    /// This is very similar to `purge_all`, but optimized for when the container will soon
    /// be destroyed.
    pub fn cleanup(ctxt: &mut CommandContext) {
        let mut other = HashMap::with_capacity(0);
        mem::swap(&mut *ctxt.framebuffer_objects.framebuffers.borrow_mut(), &mut other);

        for (_, obj) in other.into_iter() {
            obj.destroy(ctxt);
        }
    }

    ///
    /// # Unsafety
    ///
    /// After calling this function, you **must** make sure to call `purge_texture`
    /// and/or `purge_renderbuffer` when one of the attachment is destroyed.
    pub fn get_framebuffer_for_drawing(ctxt: &mut CommandContext,
                                       attachments: Option<&ValidatedAttachments>)
                                       -> gl::types::GLuint
    {
        if let Some(attachments) = attachments {
            FramebuffersContainer::get_framebuffer(ctxt, attachments)
        } else {
            0
        }
    }

    /// Binds the default framebuffer to `GL_READ_FRAMEBUFFER` or `GL_FRAMEBUFFER` so that it
    /// becomes the target of `glReadPixels`, `glCopyTexImage2D`, etc.
    // TODO: use an enum for the read buffer instead
    pub fn bind_default_framebuffer_for_reading(ctxt: &mut CommandContext,
                                                read_buffer: gl::types::GLenum)
    {
        bind_framebuffer(ctxt, 0, false, true);
        unsafe { ctxt.gl.ReadBuffer(read_buffer) };     // TODO: cache
    }

    /// Binds a framebuffer to `GL_READ_FRAMEBUFFER` or `GL_FRAMEBUFFER` so that it becomes the
    /// target of `glReadPixels`, `glCopyTexImage2D`, etc.
    ///
    /// # Unsafety
    ///
    /// After calling this function, you **must** make sure to call `purge_texture`
    /// and/or `purge_renderbuffer` when one of the attachment is destroyed.
    pub unsafe fn bind_framebuffer_for_reading(ctxt: &mut CommandContext, attachment: &Attachment) {
        // TODO: restore this optimisation
        /*for (attachments, fbo) in ctxt.framebuffer_objects.framebuffers.borrow_mut().iter() {
            for &(key, ref atc) in attachments.color.iter() {
                if atc == attachment {
                    return (fbo.get_id(), gl::COLOR_ATTACHMENT0 + key);
                }
            }
        }*/

        let attachments = FramebufferAttachments {
            colors: vec![(0, attachment.clone())],
            depth_stencil: FramebufferDepthStencilAttachments::None,
        }.validate().unwrap();

        let framebuffer = FramebuffersContainer::get_framebuffer_for_drawing(ctxt, Some(&attachments));
        bind_framebuffer(ctxt, framebuffer, false, true);
        ctxt.gl.ReadBuffer(gl::COLOR_ATTACHMENT0);     // TODO: cache
    }

    ///
    /// # Unsafety
    ///
    /// After calling this function, you **must** make sure to call `purge_texture`
    /// and/or `purge_renderbuffer` when one of the attachment is destroyed.
    fn get_framebuffer(ctxt: &mut CommandContext, attachments: &ValidatedAttachments)
                       -> gl::types::GLuint
    {
        // TODO: use entries API
        let mut framebuffers = ctxt.framebuffer_objects.framebuffers.borrow_mut();
        if let Some(value) = framebuffers.get(&attachments.raw) {
            return value.id;
        }

        let new_fbo = FrameBufferObject::new(ctxt, &attachments.raw);
        let new_fbo_id = new_fbo.id.clone();
        framebuffers.insert(attachments.raw.clone(), new_fbo);
        new_fbo_id
    }
}

impl Drop for FramebuffersContainer {
    fn drop(&mut self) {
        if self.framebuffers.borrow().len() != 0 {
            panic!()
        }
    }
}

impl FrameBufferObject {
    /// Builds a new FBO.
    fn new(mut ctxt: &mut CommandContext, attachments: &RawAttachments) -> FrameBufferObject {
        if attachments.color.len() > ctxt.capabilities.max_draw_buffers as usize {
            panic!("Trying to attach {} color buffers, but the hardware only supports {}",
                   attachments.color.len(), ctxt.capabilities.max_draw_buffers);
        }

        let id = unsafe {
            let mut id = mem::uninitialized();

            if ctxt.version >= &Version(Api::Gl, 4, 5) ||
                ctxt.extensions.gl_arb_direct_state_access
            {
                ctxt.gl.CreateFramebuffers(1, &mut id);
            } else if ctxt.version >= &Version(Api::Gl, 3, 0) ||
                ctxt.version >= &Version(Api::GlEs, 2, 0)
            {
                ctxt.gl.GenFramebuffers(1, &mut id);
                bind_framebuffer(&mut ctxt, id, true, false);
            } else {
                ctxt.gl.GenFramebuffersEXT(1, &mut id);
                bind_framebuffer(&mut ctxt, id, true, false);
            }

            let mut raw_attachments: Vec<gl::types::GLenum> = Vec::new();

            for &(slot, atchmnt) in attachments.color.iter() {
                attach(&mut ctxt, gl::COLOR_ATTACHMENT0 + slot as u32, id, atchmnt);
                raw_attachments.push(gl::COLOR_ATTACHMENT0 + slot as u32);
            }

            if let Some(depth) = attachments.depth {
                attach(&mut ctxt, gl::DEPTH_ATTACHMENT, id, depth);
            }
            if let Some(stencil) = attachments.stencil {
                attach(&mut ctxt, gl::STENCIL_ATTACHMENT, id, stencil);
            }
            if let Some(depth_stencil) = attachments.depth_stencil {
                attach(&mut ctxt, gl::DEPTH_STENCIL_ATTACHMENT, id, depth_stencil);
            }

            if ctxt.version >= &Version(Api::Gl, 4, 5) ||
               ctxt.extensions.gl_arb_direct_state_access
            {
                ctxt.gl.NamedFramebufferDrawBuffers(id, raw_attachments.len()
                                                    as gl::types::GLsizei,
                                                    raw_attachments.as_ptr());

            } else if ctxt.version >= &Version(Api::Gl, 2, 0) ||
                      ctxt.version >= &Version(Api::GlEs, 3, 0)
            {
                bind_framebuffer(&mut ctxt, id, true, false);
                ctxt.gl.DrawBuffers(raw_attachments.len() as gl::types::GLsizei,
                                    raw_attachments.as_ptr());

            } else if ctxt.version >= &Version(Api::GlEs, 2, 0) {
                assert_eq!(raw_attachments, &[gl::COLOR_ATTACHMENT0]);

            } else {
                unimplemented!();       // FIXME: use an extension
            }

            id
        };

        FrameBufferObject {
            id: id,
            current_read_buffer: gl::BACK,
        }
    }

    fn destroy(self, mut ctxt: &mut CommandContext) {
        unsafe {
            // unbinding framebuffer
            if ctxt.version >= &Version(Api::Gl, 3, 0) {
                if ctxt.state.draw_framebuffer == self.id && ctxt.state.read_framebuffer == self.id {
                    ctxt.gl.BindFramebuffer(gl::FRAMEBUFFER, 0);
                    ctxt.state.draw_framebuffer = 0;
                    ctxt.state.read_framebuffer = 0;

                } else if ctxt.state.draw_framebuffer == self.id {
                    ctxt.gl.BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0);
                    ctxt.state.draw_framebuffer = 0;

                } else if ctxt.state.read_framebuffer == self.id {
                    ctxt.gl.BindFramebuffer(gl::READ_FRAMEBUFFER, 0);
                    ctxt.state.read_framebuffer = 0;
                }

            } else if ctxt.version >= &Version(Api::GlEs, 2, 0) {
                if ctxt.state.draw_framebuffer == self.id || ctxt.state.read_framebuffer == self.id {
                    ctxt.gl.BindFramebuffer(gl::FRAMEBUFFER, 0);
                    ctxt.state.draw_framebuffer = 0;
                    ctxt.state.read_framebuffer = 0;
                }

            } else if ctxt.extensions.gl_ext_framebuffer_object {
                if ctxt.state.draw_framebuffer == self.id || ctxt.state.read_framebuffer == self.id {
                    ctxt.gl.BindFramebufferEXT(gl::FRAMEBUFFER_EXT, 0);
                    ctxt.state.draw_framebuffer = 0;
                    ctxt.state.read_framebuffer = 0;
                }

            } else {
                unreachable!();
            }

            // deleting
            if ctxt.version >= &Version(Api::Gl, 3, 0) ||
                ctxt.version >= &Version(Api::GlEs, 2, 0)
            {
                ctxt.gl.DeleteFramebuffers(1, [ self.id ].as_ptr());
            } else if ctxt.extensions.gl_ext_framebuffer_object {
                ctxt.gl.DeleteFramebuffersEXT(1, [ self.id ].as_ptr());
            } else {
                unreachable!();
            }
        }
    }
}

impl GlObject for FrameBufferObject {
    type Id = gl::types::GLuint;
    fn get_id(&self) -> gl::types::GLuint {
        self.id
    }
}

pub fn bind_framebuffer(ctxt: &mut CommandContext, fbo_id: gl::types::GLuint,
                        draw: bool, read: bool)
{
    if draw && ctxt.state.draw_framebuffer != fbo_id {
        unsafe {
            if ctxt.version >= &Version(Api::Gl, 3, 0) {
                ctxt.gl.BindFramebuffer(gl::DRAW_FRAMEBUFFER, fbo_id);
                ctxt.state.draw_framebuffer = fbo_id;
            } else if ctxt.version >= &Version(Api::GlEs, 2, 0) {
                ctxt.gl.BindFramebuffer(gl::FRAMEBUFFER, fbo_id);
                ctxt.state.draw_framebuffer = fbo_id;
                ctxt.state.read_framebuffer = fbo_id;
            } else {
                ctxt.gl.BindFramebufferEXT(gl::FRAMEBUFFER_EXT, fbo_id);
                ctxt.state.draw_framebuffer = fbo_id;
                ctxt.state.read_framebuffer = fbo_id;
            }
        }
    }

    if read && ctxt.state.read_framebuffer != fbo_id {
        unsafe {
            if ctxt.version >= &Version(Api::Gl, 3, 0) {
                ctxt.gl.BindFramebuffer(gl::READ_FRAMEBUFFER, fbo_id);
                ctxt.state.read_framebuffer = fbo_id;
            } else if ctxt.version >= &Version(Api::GlEs, 2, 0) {
                ctxt.gl.BindFramebuffer(gl::FRAMEBUFFER, fbo_id);
                ctxt.state.draw_framebuffer = fbo_id;
                ctxt.state.read_framebuffer = fbo_id;
            } else {
                ctxt.gl.BindFramebufferEXT(gl::FRAMEBUFFER_EXT, fbo_id);
                ctxt.state.draw_framebuffer = fbo_id;
                ctxt.state.read_framebuffer = fbo_id;
            }
        }
    }
}

unsafe fn attach(ctxt: &mut CommandContext, slot: gl::types::GLenum,
                 id: gl::types::GLuint, attachment: RawAttachment)
{
    if ctxt.version >= &Version(Api::Gl, 4, 5) || ctxt.extensions.gl_arb_direct_state_access {
        match attachment {
            RawAttachment::Texture { texture: tex_id, level, layer, .. } => {
                if layer == 0 {
                    ctxt.gl.NamedFramebufferTexture(id, slot, tex_id,
                                                    level as gl::types::GLint);
                } else {
                    ctxt.gl.NamedFramebufferTextureLayer(id, slot, tex_id,
                                                         level as gl::types::GLint,
                                                         layer as gl::types::GLint);
                }
            },
            RawAttachment::RenderBuffer(buf_id) => {
                ctxt.gl.NamedFramebufferRenderbuffer(id, slot, gl::RENDERBUFFER,
                                                     buf_id);
            },
        }

    } else if ctxt.extensions.gl_ext_direct_state_access &&
              ctxt.extensions.gl_ext_geometry_shader4
    {
        match attachment {
            RawAttachment::Texture { texture: tex_id, level, layer, .. } => {
                if layer == 0 {
                    ctxt.gl.NamedFramebufferTextureEXT(id, slot, tex_id,
                                                       level as gl::types::GLint);
                } else {
                    ctxt.gl.NamedFramebufferTextureLayerEXT(id, slot, tex_id,
                                                            level as gl::types::GLint,
                                                            layer as gl::types::GLint);
                }
            },
            RawAttachment::RenderBuffer(buf_id) => {
                ctxt.gl.NamedFramebufferRenderbufferEXT(id, slot, gl::RENDERBUFFER,
                                                        buf_id);
            },
        }

    } else if ctxt.version >= &Version(Api::Gl, 3, 2) {
        bind_framebuffer(ctxt, id, true, false);

        match attachment {
            RawAttachment::Texture { texture: tex_id, level, layer, .. } => {
                if layer == 0 {
                    ctxt.gl.FramebufferTexture(gl::DRAW_FRAMEBUFFER,
                                               slot, tex_id, level as gl::types::GLint);
                } else {
                    ctxt.gl.FramebufferTextureLayer(gl::DRAW_FRAMEBUFFER,
                                                    slot, tex_id,
                                                    level as gl::types::GLint,
                                                    layer as gl::types::GLint);
                }
            },
            RawAttachment::RenderBuffer(buf_id) => {
                ctxt.gl.FramebufferRenderbuffer(gl::DRAW_FRAMEBUFFER, slot,
                                                gl::RENDERBUFFER, buf_id);
            },
        }

    } else if ctxt.version >= &Version(Api::Gl, 3, 0) {
        bind_framebuffer(ctxt, id, true, false);

        match attachment {
            RawAttachment::Texture { bind_point, texture: tex_id, level, layer } => {
                match bind_point {
                    gl::TEXTURE_1D | gl::TEXTURE_RECTANGLE => {
                        assert!(layer == 0);
                        ctxt.gl.FramebufferTexture1D(gl::DRAW_FRAMEBUFFER,
                                                     slot, bind_point, tex_id,
                                                     level as gl::types::GLint);
                    },
                    gl::TEXTURE_2D | gl::TEXTURE_2D_MULTISAMPLE | gl::TEXTURE_1D_ARRAY => {
                        assert!(layer == 0);
                        ctxt.gl.FramebufferTexture2D(gl::DRAW_FRAMEBUFFER,
                                                     slot, bind_point, tex_id,
                                                     level as gl::types::GLint);
                    },
                    gl::TEXTURE_3D | gl::TEXTURE_2D_ARRAY | gl::TEXTURE_2D_MULTISAMPLE_ARRAY => {
                        ctxt.gl.FramebufferTextureLayer(gl::DRAW_FRAMEBUFFER,
                                                        slot, tex_id,
                                                        level as gl::types::GLint,
                                                        layer as gl::types::GLint);
                    },
                    _ => unreachable!()
                }
            },
            RawAttachment::RenderBuffer(buf_id) => {
                ctxt.gl.FramebufferRenderbuffer(gl::DRAW_FRAMEBUFFER, slot,
                                                gl::RENDERBUFFER, buf_id);
            },
        }

    } else if ctxt.version >= &Version(Api::GlEs, 2, 0) {
        bind_framebuffer(ctxt, id, true, true);

        match attachment {
            RawAttachment::Texture { bind_point, texture: tex_id, level, layer } => {
                match bind_point {
                    gl::TEXTURE_2D => {
                        assert!(layer == 0);
                        ctxt.gl.FramebufferTexture2D(gl::FRAMEBUFFER,
                                                     slot, bind_point, tex_id,
                                                     level as gl::types::GLint);
                    },
                    _ => unreachable!()
                }
            },
            RawAttachment::RenderBuffer(buf_id) => {
                ctxt.gl.FramebufferRenderbuffer(gl::DRAW_FRAMEBUFFER, slot,
                                                gl::RENDERBUFFER, buf_id);
            },
        }

    } else if ctxt.extensions.gl_ext_framebuffer_object {
        bind_framebuffer(ctxt, id, true, true);

        match attachment {
            RawAttachment::Texture { bind_point, texture: tex_id, level, layer } => {
                match bind_point {
                    gl::TEXTURE_1D | gl::TEXTURE_RECTANGLE => {
                        assert!(layer == 0);
                        ctxt.gl.FramebufferTexture1DEXT(gl::FRAMEBUFFER_EXT,
                                                        slot, bind_point, tex_id,
                                                        level as gl::types::GLint);
                    },
                    gl::TEXTURE_2D | gl::TEXTURE_2D_MULTISAMPLE | gl::TEXTURE_1D_ARRAY => {
                        assert!(layer == 0);
                        ctxt.gl.FramebufferTexture2DEXT(gl::FRAMEBUFFER_EXT,
                                                        slot, bind_point, tex_id,
                                                        level as gl::types::GLint);
                    },
                    gl::TEXTURE_3D | gl::TEXTURE_2D_ARRAY | gl::TEXTURE_2D_MULTISAMPLE_ARRAY => {
                        ctxt.gl.FramebufferTexture3DEXT(gl::FRAMEBUFFER_EXT,
                                                        slot, bind_point, tex_id,
                                                        level as gl::types::GLint,
                                                        layer as gl::types::GLint);
                    },
                    _ => unreachable!()
                }
            },
            RawAttachment::RenderBuffer(buf_id) => {
                ctxt.gl.FramebufferRenderbufferEXT(gl::DRAW_FRAMEBUFFER, slot,
                                                   gl::RENDERBUFFER, buf_id);
            },
        }

    } else {
        unreachable!();
    }
}