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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
use gl;
use gl::types::*;

use texture::{self, Texture};
use features::traits::{ScanLines, Image, CubemapImage};

use std::mem;
use std::ops::Index;

use ::Result;
use ::Error;
use ::ErrorKind;
use sampler::Sampler;
use state::StateRef;

/// Wrapper for a `Texture` allocated as a CubeMap
#[derive(Debug, Eq, PartialEq)]
pub struct CubeMap{
    texture: Texture,
    gl: StateRef,
}

/// Use to allocate a new texture
#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
pub struct Format{
    pub internal_format: GLenum,
    pub width: u32,
    pub height: u32,
    pub levels: u32,
}

/// Used to allocate a `Cubemap` from a set of images
#[derive(Clone)]
pub struct Faces<I: Image>{
    pub positive_x: I,
    pub negative_x: I,
    pub positive_y: I,
    pub negative_y: I,
    pub positive_z: I,
    pub negative_z: I,
}

/// Iterator over the elements of a `Faces` struct
pub struct FacesIter<'a, I:Image + 'a>{
    face: GLenum,
    faces: &'a Faces<I>,
}

impl<I: Image> Faces<I>{
    pub fn iter(&self) -> FacesIter<I>{
        FacesIter{
            face: gl::TEXTURE_CUBE_MAP_POSITIVE_X,
            faces: self
        }
    }
}

impl<'a, I: Image> Iterator for FacesIter<'a, I>{
    type Item = (GLenum,  &'a I);

    fn next(&mut self) -> Option<(GLenum,  &'a I)>{
        if self.face > gl::TEXTURE_CUBE_MAP_NEGATIVE_Z{
            None
        }else{
            let curr_face = self.face;
            self.face += 1;

            Some((curr_face, self.faces.index(curr_face)))
        }
    }
}

impl<I: Image> Index<GLenum> for Faces<I>{
    type Output = I;

    /// returns the image corresponding to the GLenum for each face
    fn index(&self, index: GLenum) -> &I{
        match index{
            gl::TEXTURE_CUBE_MAP_POSITIVE_X => &self.positive_x,
            gl::TEXTURE_CUBE_MAP_NEGATIVE_X => &self.negative_x,
            gl::TEXTURE_CUBE_MAP_POSITIVE_Y => &self.positive_y,
            gl::TEXTURE_CUBE_MAP_NEGATIVE_Y => &self.negative_y,
            gl::TEXTURE_CUBE_MAP_POSITIVE_Z => &self.positive_z,
            gl::TEXTURE_CUBE_MAP_NEGATIVE_Z => &self.negative_z,
            _ => panic!("Trying to access innexisting cubemap face")
        }
    }

}

impl Format{
    fn to_texture_format(self) -> ::texture::Format{
        texture::Format::Custom{
            target: gl::TEXTURE_CUBE_MAP,
            internal_format: self.internal_format,
            width: self.width,
            height: self.height,
            depth: 0,
            levels: self.levels,
            samples: 0,
        }
    }
}

pub struct Builder<'a>(pub(crate) &'a StateRef);

impl<'a> Builder<'a>{
    /// Creates a new cubemap using the specified format
    pub fn from_format(&self, format: Format) -> Result<CubeMap>{
        let mut tex = texture::Builder(self.0).from_format(format.to_texture_format())?;
        tex.set_wrap_s(gl::CLAMP_TO_EDGE);
        tex.set_wrap_t(gl::CLAMP_TO_EDGE);
        tex.set_wrap_r(gl::CLAMP_TO_EDGE);
        if format.levels > 1 {
            tex.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
            // cubemap.texture.set_min_mag_filters(gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR);
        }else{
            tex.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
        }
        tex.set_max_level(format.levels as i32 - 1);
        Ok(CubeMap{
            texture: tex,
            gl : self.0.clone(),
        })
    }


    /// allocate a cubemap from a set of images in a Faces struct
    pub fn from_faces<I: ::Image>(&self, faces: &Faces<I>) -> Result<CubeMap>{
        let img0 = &faces.positive_x;
        let internal_format = img0.gl_internal().ok_or(ErrorKind::FormatNotSupported)?;
        let w = img0.width(0);
        let h = img0.height(0);
        let mipcount = img0.levels();

        let mut cubemap = self.from_format(Format{
            internal_format,
            width: w as u32,
            height: h as u32,
            levels: mipcount as u32,
        })?;

        cubemap.load_faces(faces)?;
        cubemap.texture.set_wrap_s(gl::CLAMP_TO_EDGE);
        cubemap.texture.set_wrap_t(gl::CLAMP_TO_EDGE);
        cubemap.texture.set_wrap_r(gl::CLAMP_TO_EDGE);
        if mipcount > 1 {
            cubemap.texture.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
        }else{
            cubemap.texture.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
        }
        Ok(cubemap)
    }


    /// Allocate a cubemap from a CubemapImage that contains all the faces
    pub fn from_cubemap_image<I: CubemapImage>(&self, dds: &I) -> Result<CubeMap>
    where <I as Image>::DataType: Copy
    {
        //if !dds.is_cubemap_allfaces() { return Err("Cubemap doens't contain all faces".to_string()) }
        let internal_format = dds.gl_internal().ok_or(ErrorKind::FormatNotSupported)?;
        let mipcount = dds.levels();
        let w = dds.width(0);
        let h = dds.height(0);
        let mut cubemap = self.from_format(Format{
            internal_format,
            width: w as u32,
            height: h as u32,
            levels: mipcount as u32})?;

        cubemap.load_image(dds)?;
        cubemap.texture.set_wrap_r(gl::CLAMP_TO_EDGE);
        if mipcount > 1{
            cubemap.texture.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
            // cubemap.texture.set_min_mag_filters(gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR);
        }else{
            cubemap.texture.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
        }
        cubemap.set_max_level(mipcount as i32 - 1);
        Ok(cubemap)
    }

    fn from_cubemap_image_level_levels<I: CubemapImage>(&self, dds: &I, level: usize, allocate_levels: bool) -> Result<CubeMap>
    where <I as Image>::DataType: Copy
    {
        //if !dds.is_cubemap_allfaces() { return Err("Cubemap doens't contain all faces".to_string()) }
        let (internal, format, ty) = dds.gl_internal_format_type()
            .ok_or(ErrorKind::FormatNotSupported)?;
        let compressed = dds.is_gpu_compressed();
        let w = dds.width(level);
        let h = dds.height(level);
        let levels = if allocate_levels { dds.max_levels() } else { 1 };
        if w != h { return Err(Error::new(ErrorKind::NotSquareImage, None)) };

        let mut cubemap = self.from_format(Format{
            internal_format: internal,
            width: w as u32,
            height: h as u32,
            levels: levels as u32})?;

        for face in 0..6{
            let data = dds.mipmap_face(level, face)
                .ok_or_else(|| Error::new(ErrorKind::FormatNotSupported,
                    format!("Couldn't get level {} face {}", level, face).as_ref()))?;
            // TODO: this probably belongs better on Dds crate or image feature?
            let linewidth = w * dds.bytes_per_pixel() / std::mem::size_of::<<I as Image>::DataType>();
            let data = data
                .chunks(linewidth)
                .rev()
                .flat_map(|line| line.iter().copied())
                .collect::<Vec<<I as Image>::DataType>>();
            let side = gl::TEXTURE_CUBE_MAP_POSITIVE_X + face as u32;
            if compressed{
                cubemap.load_compressed_data(&data, side, 0, internal, w as GLint, h as GLint);
            }else{
                cubemap.load_data(data.as_ptr(), side, 0, w as GLint, h as GLint, format, ty);
            }
        }

        cubemap.texture.set_wrap_r(gl::CLAMP_TO_EDGE);
        cubemap.texture.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
        cubemap.set_max_level(levels as i32 - 1);
        Ok(cubemap)
    }

    /// Allocate a cubemap from a CubemapImage that contains all the faces
    ///
    /// Reads only one specific level from the cubemap image
    pub fn from_cubemap_image_level<I: CubemapImage>(&self, dds: &I, level: usize) -> Result<CubeMap>
    where <I as Image>::DataType: Copy
    {
        self.from_cubemap_image_level_levels(dds, level, false)
    }

    /// Allocate a cubemap from a CubemapImage that contains all the faces
    ///
    /// Reads only one specific level from the cubemap image and allocates
    /// the texture with the max number of mips possible for the base
    /// level size
    pub fn from_cubemap_image_level_allocate_mips<I: CubemapImage>(&self, dds: &I, level: usize) -> Result<CubeMap>
    where <I as Image>::DataType: Copy
    {
        self.from_cubemap_image_level_levels(dds, level, true)
    }
}

impl CubeMap{
    // /// Reallocate the cubemap using the specified format
    // pub fn reallocate_from_format(&mut self, format: Format) -> Result<()>{
    //     self.texture.reallocate_from_format(format.to_texture_format())?;
    //     self.texture.set_wrap_s(gl::CLAMP_TO_EDGE);
    //     self.texture.set_wrap_t(gl::CLAMP_TO_EDGE);
    //     self.texture.set_wrap_r(gl::CLAMP_TO_EDGE);
    //     if format.levels > 1 {
    //         self.texture.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
    //         // cubemap.texture.set_min_mag_filters(gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR);
    //     }else{
    //         self.texture.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
    //     }
    //     self.texture.set_max_level(format.levels as i32 - 1);
    //     Ok(())
    // }


    // /// Reallocate the cubemap from a CubemapImage that contains all the faces
    // pub fn reallocate_from_cubemap_image<I: CubemapImage>(&mut self, dds: &I) -> Result<()>{
    //     //if !dds.is_cubemap_allfaces() { return Err("Cubemap doens't contain all faces".to_string()) }
    //     let internal_format = dds.gl_internal().ok_or(ErrorKind::FormatNotSupported)?;
    //     let w = dds.width(0);
    //     let h = dds.height(0);
    //     let mipcount = dds.levels();
    //     if w != h { return Err(Error::new(ErrorKind::NotSquareImage, None)) };

    //     let format = Format{
    //         internal_format,
    //         width: w as u32,
    //         height: h as u32,
    //         levels: mipcount as u32};
    //     dbg!(format);
    //     self.reallocate_from_format(format)?;

    //     self.load_image(dds)?;
    //     if mipcount > 1{
    //         self.texture.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
    //     }else{
    //         self.texture.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
    //     }
    //     self.set_max_level(mipcount as i32 - 1);
    //     Ok(())
    // }

    // /// Reallocate the cubemap from a set of images in a Faces struct
    // pub fn reallocate_from_faces<I: ::Image>(&mut self, faces: &Faces<I>) -> Result<()>{
    //     let img0 = &faces.positive_x;
    //     let internal_format = img0.gl_internal().ok_or(ErrorKind::FormatNotSupported)?;
    //     let w = img0.width(0);
    //     let h = img0.height(0);
    //     let mipcount = img0.levels();

    //     self.reallocate_from_format(Format{
    //         internal_format,
    //         width: w as u32,
    //         height: h as u32,
    //         levels: mipcount as u32,
    //     })?;

    //     self.load_faces(faces)?;
    //     if mipcount > 1 {
    //         self.texture.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
    //     }else{
    //         self.texture.set_min_mag_filters(gl::LINEAR, gl::LINEAR);
    //     }
    //     Ok(())
    // }

    /// glGenerateMipmaps
    ///
    /// Also automatically sets the filters to use the mipmaps
    pub fn generate_mipmaps(&mut self){
        self.texture.generate_mipmaps();
    }

    /// A cubemap face width
    pub fn width(&self) -> u32{
        self.texture.width()
    }

    /// A cubemap face height
    pub fn height(&self) -> u32{
        self.texture.height()
    }

    /// Number of levels the cubemap was allocated with
    pub fn levels(&self) -> u32{
        self.texture.levels()
    }

    /// GL id
    pub fn id(&self) -> GLuint{
        self.texture.id()
    }

    /// The internal format of the cubemap
    pub fn internal_format(&self) -> GLenum{
        self.texture.internal_format()
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    fn load_data<T>(&mut self, data: *const T, side: GLenum, level: i32, w: GLint, h: GLint, format: GLenum, ty: GLenum){
        unsafe{
            self.gl.GetError();
            if self.texture.is_dsa(){
                let face = side - gl::TEXTURE_CUBE_MAP_POSITIVE_X;
                self.gl.TextureSubImage3D(self.texture.id(), level, 0, 0, face as GLsizei, w, h, 1, format, ty, mem::transmute(data));
            }else{
                self.gl.BindTexture(gl::TEXTURE_CUBE_MAP, self.texture.id());
                self.gl.TexSubImage2D(side, level, 0, 0, w, h, format, ty, mem::transmute(data));
            }
            let err = self.gl.GetError();
            if err > 0{
                let mut max = 0;
                self.gl.GetIntegerv(gl::MAX_TEXTURE_SIZE, &mut max);
                error!("error loading cubemap data {}, w: {}, h: {}, side: {}, level: {}, format: {}, ty: {}", err, w, h, side, level, format, ty);
            }
        }
    }

    #[cfg(any(feature = "gles", feature="webgl"))]
    fn load_data<T>(&mut self, data: *const T, side: GLenum, level: i32, w: GLint, h: GLint, format: GLenum, ty: GLenum){
        unsafe{
            self.gl.GetError();
            self.gl.BindTexture(gl::TEXTURE_CUBE_MAP, self.texture.id());
            self.gl.TexSubImage2D(side, level, 0, 0, w, h, format, ty, mem::transmute(data));
            // gl::TexImage2D(side, level, self.texture.internal_format() as i32, w, h, 0, format, ty, mem::transmute(data));

            let err = self.gl.GetError();
            if err > 0{
                error!("error loading cubemap data {}, w: {}, h: {}, side: {}, level: {}, format: {}, ty: {}", err, w, h, side, level, format, ty);
            }
        }
    }

    fn load_compressed_data<T>(&mut self, data: &[T], side: GLenum, level: i32, internal: GLenum, w: GLint, h: GLint){
        unsafe{
            self.gl.GetError();
            self.gl.CompressedTexImage2D(side, level, internal, w, h, 0, data.len() as i32, mem::transmute(data.as_ptr()));
            let err = self.gl.GetError();
            if err > 0{
                error!("error loading compressed cubemap data {}, w: {}, h: {}, side: {}, level: {}, internal: {}", err, w, h, side, level, internal);
            }
        }
    }

    fn load_img_data<I: ::Image>(&mut self, img: &I, target: GLenum, level: GLint) -> Result<()>{
        let bytes_pp = img.bytes_per_pixel();
        let (_internal,format,ty) = img.gl_internal_format_type()
            .ok_or(ErrorKind::FormatNotSupported)?;
        unsafe{
            self.gl.state().set_pixel_store((img.width(0)*bytes_pp) as i32);
        }
        let w = img.width(0) as i32;
        let h = img.height(0) as i32;
        if img.pitch_bytes(0) != img.width(0)*bytes_pp{
            let mut pixels = Vec::new();
            let scanlines = ScanLines::new(img, 0);
            for line in scanlines{
                pixels.extend(line.iter());
            }
            self.load_data(pixels.as_ptr(), target, level, w, h, format, ty);
        }else{
	        self.load_data(img.data().as_ptr(), target, level, w, h, format, ty);
        }
        unsafe{
			self.gl.PixelStorei (gl::UNPACK_ALIGNMENT, 4);
		}
        Ok(())
    }

    /// Upload data for all the faces of the specified level of the cubemap
    pub fn load_level_from_faces<I: Image>(&mut self, faces: &Faces<I>, level: GLint) -> Result<()>{
        let img0 = &faces.positive_x;
        let bpp = img0.bytes_per_pixel();
        let ift = img0.gl_internal_format_type().ok_or(ErrorKind::FormatNotSupported)?;
        let w = img0.width(0);
        let h = img0.height(0);
        if w != h { return Err(Error::new(ErrorKind::NotSquareImage, None)) };
        if !faces.iter().all(|(_side, img)|
            img.bytes_per_pixel()==bpp &&
            img.gl_internal_format_type().is_some() &&  //TODO: match this so we don't call twice
            img.gl_internal_format_type().unwrap()==ift) {
                return Err(Error::new(ErrorKind::DifferentFormatsPerImage, None))
        };

        if !faces.iter().all(|(_side, img)| img.width(0)==w && img.height(0)==h){
            return Err(Error::new(ErrorKind::DifferentDimensionsPerImage, None))
        };

        for (side, img) in faces.iter(){
            self.load_img_data(img, side, level)?;
        }
        Ok(())
    }

    pub fn load_faces<I: Image>(&mut self, faces: &Faces<I>) -> Result<()>{
        let img0 = &faces.positive_x;
        let (internal, format, ty) = img0.gl_internal_format_type()
            .ok_or(ErrorKind::FormatNotSupported)?;
        let compressed = img0.is_gpu_compressed();
        let w = img0.width(0);
        let h = img0.height(0);
        let mipcount = img0.levels();
        if w != h { return Err(Error::new(ErrorKind::NotSquareImage, None)) };
        if !faces.iter().all(|(_side, img)|
            img.gl_internal().is_some() &&
            img.gl_internal().unwrap()==internal){  //TODO: match this so we don't call twice
                return Err(Error::new(ErrorKind::DifferentFormatsPerImage,
                    "All images need to have the same format"))
        };
        if !faces.iter().all(|(_side, img)| img.width(0)==w && img.height(0)==h){
            return Err(Error::new(ErrorKind::DifferentDimensionsPerImage,
                "All images need to have the same dimensions"))
        };

        for (side, img) in faces.iter(){
            for level in 0..mipcount{
                let data = img.mipmap(level)
                    .ok_or_else(|| Error::new(ErrorKind::FormatNotSupported,
                        format!("Error retrieving mipmap, reports {} but got None for {}", mipcount, level)
                        .as_ref()))?;
                let w = img.width(level);
                let h = img.height(level);

                if compressed{
                    self.load_compressed_data(data, side, level as GLint, internal, w as GLint, h as GLint);
                }else{
                    self.load_data(data.as_ptr(), side, level as GLint, w as GLint, h as GLint, format, ty);
                }
            }
        }
        self.set_max_level(mipcount as i32 - 1);
        Ok(())
    }

    /// Upload data for all the faces of the specified level of the cubemap
    pub fn load_level_from_cubemap_image<I: CubemapImage>(&mut self, dds: &I, level: GLint) -> Result<()>{
        //if !dds.is_cubemap_allfaces() { return Err("Cubemap doens't contain all faces".to_string()) }
        let (internal, format, ty) = dds.gl_internal_format_type()
            .ok_or(ErrorKind::FormatNotSupported)?;
        let compressed = dds.is_gpu_compressed();
        let w = dds.width(0);
        let h = dds.height(0);
        if w != h { return Err(Error::new(ErrorKind::NotSquareImage, None)) };
        for face in 0..6{
            let data = dds.mipmap_face(0, face)
                .ok_or_else(|| Error::new(ErrorKind::FormatNotSupported,
                    format!("Couldn't get level {} face {}", level, face).as_ref()))?;
            let side = gl::TEXTURE_CUBE_MAP_POSITIVE_X + face as u32;
            if compressed{
                self.load_compressed_data(data, side, level as GLint, internal, w as GLint, h as GLint);
            }else{
                self.load_data(data.as_ptr(), side, level as GLint, w as GLint, h as GLint, format, ty);
            }
        }
        self.texture.set_wrap_r(gl::CLAMP_TO_EDGE);
        // if mipcount > 1{
        //     self.texture.set_min_mag_filters(gl::NEAREST_MIPMAP_NEAREST, gl::NEAREST);
        //     // cubemap.texture.set_min_mag_filters(gl::LINEAR_MIPMAP_LINEAR, gl::LINEAR);
        // }else{
        //     self.texture.set_min_mag_filters(gl::NEAREST, gl::NEAREST);
        // }
        // self.set_max_level(mipcount as i32 - 1);
        Ok(())
    }

    pub fn load_image<I: CubemapImage>(&mut self, dds: &I) -> Result<()>
    where <I as Image>::DataType: Copy
    {
        let (internal, format, ty) = dds.gl_internal_format_type()
            .ok_or(ErrorKind::FormatNotSupported)?;
        let compressed = dds.is_gpu_compressed();
        let mut w = dds.width(0);
        let mut h = dds.height(0);
        if w != h { return Err(Error::new(ErrorKind::NotSquareImage, None)) };
        let mipcount = dds.levels();
        for level in 0..mipcount{
            for face in 0..6{
                let data = dds.mipmap_face(level, face)
                    .ok_or_else(|| Error::new(ErrorKind::FormatNotSupported,
                        format!("Couldn't get level {} face {}", level, face).as_ref()))?;

                // TODO: this probably belongs better on Dds crate or image feature?
                let linewidth = w * dds.bytes_per_pixel() / std::mem::size_of::<<I as Image>::DataType>();
                let data = data
                    .chunks(linewidth)
                    .rev()
                    .flat_map(|line| line.iter().copied())
                    .collect::<Vec<<I as Image>::DataType>>();
                let side = gl::TEXTURE_CUBE_MAP_POSITIVE_X + face as u32;
                if compressed{
                    self.load_compressed_data(&data, side, level as GLint, internal, w as GLint, h as GLint);
                }else{
                    self.load_data(data.as_ptr(), side, level as GLint, w as GLint, h as GLint, format, ty);
                }
            }
            w /= 2;
            h /= 2;
        }
        Ok(())
    }

    #[cfg(not(feature="webgl"))]
    pub fn set_anisotropy_level(&mut self, level: f32){
        self.texture.set_anisotropy_level(level)
    }

    pub fn set_base_level(&mut self, level: GLint){
        self.texture.set_base_level(level);
    }

    pub fn set_max_level(&mut self, level: GLint){
        self.texture.set_max_level(level);
    }

    pub fn set_min_lod(&mut self, level: GLint){
        self.texture.set_min_lod(level);
    }

    pub fn set_max_lod(&mut self, level: GLint){
        self.texture.set_max_lod(level);
    }

    pub fn set_min_mag_filters(&mut self, min: GLuint, max: GLuint){
		self.texture.set_min_mag_filters(min, max);
    }

    pub fn set_wrap_s(&mut self, wrap: GLenum){
		self.texture.set_wrap_s(wrap);
    }

    pub fn set_wrap_t(&mut self, wrap: GLenum){
		self.texture.set_wrap_t(wrap);
    }

    pub fn set_wrap_r(&mut self, wrap: GLenum){
		self.texture.set_wrap_r(wrap);
    }

    pub fn set_compare_mode(&mut self, mode: GLenum){
        self.texture.set_compare_mode(mode)
    }

    pub fn set_compare_func(&mut self, mode: GLenum){
        self.texture.set_compare_func(mode)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_width(&self, level: u32) -> u32{
        self.texture.level_width(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_height(&self, level: u32) -> u32{
        self.texture.level_height(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_internal_format(&self, level: u32) -> GLenum{
        self.texture.level_internal_format(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_red_type(&self, level: u32) -> GLenum{
        self.texture.level_red_type(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_green_type(&self, level: u32) -> GLenum{
        self.texture.level_green_type(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_blue_type(&self, level: u32) -> GLenum{
        self.texture.level_blue_type(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_alpha_type(&self, level: u32) -> GLenum{
        self.texture.level_alpha_type(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn is_level_compressed(&self, level: u32) -> bool{
        self.texture.is_level_compressed(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_compressed_image_len(&self, level: u32) -> usize{
        self.texture.level_compressed_image_len(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_red_size(&self, level: u32) -> usize{
        self.texture.level_red_size(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_green_size(&self, level: u32) -> usize{
        self.texture.level_green_size(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_blue_size(&self, level: u32) -> usize{
        self.texture.level_blue_size(level)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn level_alpha_size(&self, level: u32) -> usize{
        self.texture.level_alpha_size(level)
    }

    #[cfg(not(feature="webgl"))]
    pub fn depth_stencil_texture_mode(&self) -> GLenum{
        self.texture.depth_stencil_texture_mode()
    }

    pub fn mag_filter(&self) -> GLenum{
        self.texture.mag_filter()
    }

    pub fn min_filter(&self) -> GLenum{
        self.texture.min_filter()
    }

    pub fn min_lod(&self) -> i32{
        self.texture.min_lod()
    }

    pub fn max_lod(&self) -> i32{
        self.texture.max_lod()
    }

    pub fn base_level(&self) -> i32{
        self.texture.base_level()
    }

    pub fn max_level(&self) -> i32{
        self.texture.max_level()
    }

    #[cfg(not(feature = "webgl"))]
    pub fn swizzle_r(&self) -> texture::Component{
        self.texture.swizzle_r()
    }

    #[cfg(not(feature = "webgl"))]
    pub fn swizzle_g(&self) -> texture::Component{
        self.texture.swizzle_g()
    }

    #[cfg(not(feature = "webgl"))]
    pub fn swizzle_b(&self) -> texture::Component{
        self.texture.swizzle_b()
    }

    #[cfg(not(feature = "webgl"))]
    pub fn swizzle_a(&self) -> texture::Component{
        self.texture.swizzle_a()
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn swizzles(&self) -> texture::Swizzles{
        self.texture.swizzles()
    }

    pub fn wrap_s(&self) -> GLenum{
        self.texture.wrap_s()
    }

    pub fn wrap_t(&self) -> GLenum{
        self.texture.wrap_t()
    }

    pub fn wrap_r(&self) -> GLenum{
        self.texture.wrap_r()
    }

    #[cfg(not(feature = "webgl"))]
    pub fn border_color(&self) -> [f32;4]{
        self.texture.border_color()
    }

    pub fn compare_mode(&self) -> GLenum{
        self.texture.compare_mode()
    }

    pub fn compare_func(&self) -> GLenum{
        self.texture.compare_func()
    }

    #[cfg(not(feature = "webgl"))]
    pub fn image_format_compatibility_type(&self) -> GLenum{
        self.texture.image_format_compatibility_type()
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn seamless(&self) -> bool {
        unsafe{
            self.texture.get_parameteri(gl::TEXTURE_CUBE_MAP_SEAMLESS) != 0
        }
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn set_seamless(&mut self, seamless: bool) {
        unsafe{
            self.texture.set_parameteri(gl::TEXTURE_CUBE_MAP_SEAMLESS, seamless as u8 as i32)
        }
    }

    pub unsafe fn set_parameteri(&mut self, parameter: GLenum, value: GLint){
        self.texture.set_parameteri(parameter, value);
    }

    pub unsafe fn set_parameterf(&mut self, parameter: GLenum, value: GLfloat){
        self.texture.set_parameterf(parameter, value);
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub unsafe fn get_level_parameteriv(&self, parameter: GLenum, level: u32) -> GLint{
        self.texture.get_level_parameteriv(parameter, level)
    }

    pub unsafe fn get_parameteri(&self, parameter: GLenum) -> GLint{
        self.texture.get_parameteri(parameter)
    }

    pub unsafe fn get_parameterf(&self, parameter: GLenum) -> GLfloat{
        self.texture.get_parameterf(parameter)
    }

    /*pub fn face(&self, f: usize, render_pos: &Pnt2<f32>, render_size:f32, coordinate_origin: graphics::CoordinateOrigin) -> (gl::Vao, Material){
        let face = CubeMap::face_mesh(gl::TEXTURE_CUBE_MAP_POSITIVE_X + f as u32, render_pos, render_size, coordinate_origin);
        let mesh = graphics::mesh::mesh(face, graphics::PrimitiveType::Triangles);
        let geometry = gl::Vao::new_from_mesh(&mesh, gl::STATIC_DRAW);
        let material = Material::new(self);
        (geometry, material)
    }*/

    /*fn tex_coords(face: GLenum) -> Vec<[f32;3]>{
        let l = 1.0 / 3.0f32.sqrt();
        match face{
            gl::TEXTURE_CUBE_MAP_NEGATIVE_X => vec![
                [-l,-l,-l],
                [-l,-l,l],
                [-l,l,l],

                [-l,l,l],
                [-l,l,-l],
                [-l,-l,-l],
            ],

            gl::TEXTURE_CUBE_MAP_POSITIVE_Z => vec![
                [-l,-l,l],
                [l,-l,l],
                [l,l,l],

                [l,l,l],
                [-l,l,l],
                [-l,-l,l],
            ],

            gl::TEXTURE_CUBE_MAP_POSITIVE_X => vec![
                [l,-l,l],
                [l,-l,-l],
                [l,l,-l],

                [l,l,-l],
                [l,l,l],
                [l,-l,l],
            ],

            gl::TEXTURE_CUBE_MAP_NEGATIVE_Z => vec![
                [l,-l,-l],
                [-l,-l,-l],
                [-l,l,-l],

                [-l,l,-l],
                [l,l,-l],
                [l,-l,-l],
            ],

            gl::TEXTURE_CUBE_MAP_POSITIVE_Y => vec![
                [-l,l,l],
                [l,l,l],
                [l,l,-l],

                [l,l,-l],
                [-l,l,-l],
                [-l,l,l],
            ],

            gl::TEXTURE_CUBE_MAP_NEGATIVE_Y => vec![
                [-l,-l,-l],
                [l,-l,-l],
                [l,-l,l],

                [l,-l,l],
                [-l,-l,l],
                [-l,-l,-l],
            ],

            _ => panic!("Wrong face!!")
        }
    }

    fn face_mesh(face: GLenum, pos: &Pnt2<f32>, size: f32, coordinate_origin: graphics::CoordinateOrigin) -> Vec<graphics::Vertex2DTexture3D>{
        let pos = pos.to_vec();
        let size = vec2(size, size);
        let tex_coords = CubeMap::tex_coords(face);
        match coordinate_origin{
            graphics::CoordinateOrigin::BottomLeft | graphics::CoordinateOrigin::CenterUp=> vec![
                graphics::vertex2dtex3d(vec2(pos.x, pos.y), tex_coords[0]),
                graphics::vertex2dtex3d(vec2(pos.x + size.x, pos.y), tex_coords[1]),
                graphics::vertex2dtex3d(vec2(pos.x + size.x, pos.y + size.y), tex_coords[2]),

                graphics::vertex2dtex3d(vec2(pos.x + size.x, pos.y + size.y), tex_coords[3]),
                graphics::vertex2dtex3d(vec2(pos.x, pos.y + size.y), tex_coords[4]),
                graphics::vertex2dtex3d(vec2(pos.x, pos.y), tex_coords[5]),
            ],

            graphics::CoordinateOrigin::TopLeft | graphics::CoordinateOrigin::CenterDown => vec![
                graphics::vertex2dtex3d(vec2(pos.x, pos.y + size.y), tex_coords[0]),
                graphics::vertex2dtex3d(vec2(pos.x + size.x, pos.y + size.y), tex_coords[1]),
                graphics::vertex2dtex3d(vec2(pos.x + size.x, pos.y), tex_coords[2]),

                graphics::vertex2dtex3d(vec2(pos.x + size.x, pos.y), tex_coords[3]),
                graphics::vertex2dtex3d(vec2(pos.x, pos.y), tex_coords[4]),
                graphics::vertex2dtex3d(vec2(pos.x, pos.y + size.y), tex_coords[5]),
            ],
        }

    }

    fn unwraped_mesh(pos: &Pnt2<f32>, size: &Pnt2<f32>, orig: graphics::CoordinateOrigin) -> graphics::Mesh<graphics::Vertex2DTexture3D>{
        let faces = match orig{
            graphics::CoordinateOrigin::BottomLeft | graphics::CoordinateOrigin::CenterUp => [
                (gl::TEXTURE_CUBE_MAP_NEGATIVE_X, vec2(0., size.y)),
                (gl::TEXTURE_CUBE_MAP_POSITIVE_Z, vec2(size.x, size.y)),
                (gl::TEXTURE_CUBE_MAP_POSITIVE_X, vec2(size.x * 2., size.y)),
                (gl::TEXTURE_CUBE_MAP_NEGATIVE_Z, vec2(size.x * 3., size.y)),
                (gl::TEXTURE_CUBE_MAP_POSITIVE_Y, vec2(size.x, size.y * 2.)),
                (gl::TEXTURE_CUBE_MAP_NEGATIVE_Y, vec2(size.x, 0.)),
            ],

            graphics::CoordinateOrigin::TopLeft | graphics::CoordinateOrigin::CenterDown => [
                (gl::TEXTURE_CUBE_MAP_NEGATIVE_X, vec2(0., size.y)),
                (gl::TEXTURE_CUBE_MAP_POSITIVE_Z, vec2(size.x, size.y)),
                (gl::TEXTURE_CUBE_MAP_POSITIVE_X, vec2(size.x * 2., size.y)),
                (gl::TEXTURE_CUBE_MAP_NEGATIVE_Z, vec2(size.x * 3., size.y)),
                (gl::TEXTURE_CUBE_MAP_POSITIVE_Y, vec2(size.x, 0.)),
                (gl::TEXTURE_CUBE_MAP_NEGATIVE_Y, vec2(size.x, size.y * 2.)),
            ],
        };

        let faces = faces.into_iter().flat_map(|&(face, offset)|{
             CubeMap::face_mesh(face, pos, size.x, orig)
                .into_iter()
                .map(move |vertex| graphics::vertex2dtex3d(vertex.position + offset, vertex.texcoord))
        }).collect();

        graphics::mesh::mesh(faces, graphics::PrimitiveType::Triangles)
    }*/

    /// Returns a Sampler over this CubeMap
    pub fn cubemap_sampler<'a>(&'a self, sampler: &'a Sampler) -> CubeMapSampler<'a>{
        CubeMapSampler{
            cubemap: self,
            sampler
        }
    }
}

#[derive(Clone, Copy)]
pub struct CubeMapSampler<'a>{
    cubemap: &'a CubeMap,
    sampler: &'a Sampler,
}

impl<'a> CubeMapSampler<'a>{
        /// Returns the width of the allocated texture
    pub fn width(&self) -> u32{
        self.cubemap.width()
    }

    /// Returns the height of the allocated texture
    pub fn height(&self) -> u32{
        self.cubemap.height()
    }

    /// Returns the number of allocated levels
    pub fn levels(&self) -> u32{
        self.cubemap.levels()
    }

    /// Returns the cubemap GL id
    pub fn cubemap_id(&self) -> GLuint{
        self.cubemap.id()
    }

    /// Returns the sampler GL id
    pub fn sampler_id(&self) -> GLuint{
        self.sampler.id()
    }

    /// Returns the internal format
    pub fn internal_format(&self) -> GLenum{
        self.cubemap.internal_format()
    }
}