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
use crate::gl;
use crate::gl::types::GLuint;
use image::{self, DynamicImage, RgbaImage};

use std::path::Path;

use crate::{ops, ImageSize, CreateTexture, UpdateTexture, TextureSettings, Format, Filter};

trait GlSettings {
    fn get_gl_mag(&self) -> gl::types::GLenum;
    fn get_gl_min(&self) -> gl::types::GLenum;
    fn get_gl_mipmap(&self) -> gl::types::GLenum;
}

impl GlSettings for TextureSettings {
    fn get_gl_mag(&self) -> gl::types::GLenum {
        match self.get_mag() {
            Filter::Linear => gl::LINEAR,
            Filter::Nearest => gl::NEAREST,
        }
    }

    fn get_gl_min(&self) -> gl::types::GLenum {
        match self.get_min() {
            Filter::Linear => {
                if self.get_generate_mipmap() {
                    match self.get_mipmap() {
                        Filter::Linear => gl::LINEAR_MIPMAP_LINEAR,
                        Filter::Nearest => gl::LINEAR_MIPMAP_NEAREST,
                    }
                } else {
                    gl::LINEAR
                }
            }
            Filter::Nearest => {
                if self.get_generate_mipmap() {
                    match self.get_mipmap() {
                        Filter::Linear => gl::NEAREST_MIPMAP_LINEAR,
                        Filter::Nearest => gl::NEAREST_MIPMAP_NEAREST,
                    }
                } else {
                    gl::NEAREST
                }
            }
        }
    }

    fn get_gl_mipmap(&self) -> gl::types::GLenum {
        match self.get_mipmap() {
            Filter::Linear => gl::LINEAR,
            Filter::Nearest => gl::NEAREST,
        }
    }
}

/// Wraps OpenGL texture data.
/// The texture gets deleted when running out of scope.
///
/// In order to create a texture the function `GenTextures` must be loaded.
/// This is done automatically by the window back-ends in Piston.
pub struct Texture {
    id: GLuint,
    width: u32,
    height: u32,
}

impl Texture {
    /// Creates a new texture.
    #[inline(always)]
    pub fn new(id: GLuint, width: u32, height: u32) -> Self {
        Texture {
            id: id,
            width: width,
            height: height,
        }
    }

    /// Gets the OpenGL id of the texture.
    #[inline(always)]
    pub fn get_id(&self) -> GLuint {
        self.id
    }

    /// Returns empty texture.
    pub fn empty() -> Result<Self, String> {
        CreateTexture::create(&mut (),
                              Format::Rgba8,
                              &[0u8; 4],
                              [1, 1],
                              &TextureSettings::new())
    }

    /// Loads image from memory, the format is 8-bit greyscale.
    pub fn from_memory_alpha(buf: &[u8],
                             width: u32,
                             height: u32,
                             settings: &TextureSettings)
                             -> Result<Self, String> {
        let size = [width, height];
        let buffer = ops::alpha_to_rgba8(buf, size);
        CreateTexture::create(&mut (), Format::Rgba8, &buffer, size, settings)
    }

    /// Loads image by relative file name to the asset root.
    pub fn from_path<P>(path: P) -> Result<Self, String>
        where P: AsRef<Path>
    {
        let path = path.as_ref();

        let img = match image::open(path) {
            Ok(img) => img,
            Err(e) => {
                return Err(format!("Could not load '{:?}': {:?}", path.file_name().unwrap(), e))
            }
        };

        let img = match img {
            DynamicImage::ImageRgba8(img) => img,
            x => x.to_rgba(),
        };

        Ok(Texture::from_image(&img, &TextureSettings::new()))
    }

    /// Creates a texture from image.
    pub fn from_image(img: &RgbaImage, settings: &TextureSettings) -> Self {
        let (width, height) = img.dimensions();
        CreateTexture::create(&mut (), Format::Rgba8, img, [width, height], settings).unwrap()
    }

    /// Updates image with a new one.
    pub fn update(&mut self, img: &RgbaImage) {
        let (width, height) = img.dimensions();

        UpdateTexture::update(self, &mut (), Format::Rgba8, img, [0, 0], [width, height]).unwrap();
    }
}

impl Drop for Texture {
    fn drop(&mut self) {
        unsafe {
            let ids = [self.id];
            gl::DeleteTextures(1, ids.as_ptr());
            drop(ids);
        }
    }
}

impl ImageSize for Texture {
    fn get_size(&self) -> (u32, u32) {
        (self.width, self.height)
    }
}

impl CreateTexture<()> for Texture {
    type Error = String;

    fn create<S: Into<[u32; 2]>>(_factory: &mut (),
                                 _format: Format,
                                 memory: &[u8],
                                 size: S,
                                 settings: &TextureSettings)
                                 -> Result<Self, Self::Error> {
        let size = size.into();
        let mut id: GLuint = 0;
        unsafe {
            gl::GenTextures(1, &mut id);
            gl::BindTexture(gl::TEXTURE_2D, id);
            gl::TexParameteri(gl::TEXTURE_2D,
                              gl::TEXTURE_MIN_FILTER,
                              settings.get_gl_min() as i32);
            gl::TexParameteri(gl::TEXTURE_2D,
                              gl::TEXTURE_MAG_FILTER,
                              settings.get_gl_mag() as i32);
            gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32);
            gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32);
            if settings.get_generate_mipmap() {
                gl::GenerateMipmap(gl::TEXTURE_2D);
            }
            gl::TexImage2D(gl::TEXTURE_2D,
                           0,
                           gl::RGBA as i32,
                           size[0] as i32,
                           size[1] as i32,
                           0,
                           gl::RGBA,
                           gl::UNSIGNED_BYTE,
                           memory.as_ptr() as *const _);
        }

        Ok(Texture::new(id, size[0], size[1]))
    }
}

impl UpdateTexture<()> for Texture {
    type Error = String;

    fn update<O: Into<[u32; 2]>, S: Into<[u32; 2]>>(&mut self,
                                                    _factory: &mut (),
                                                    _format: Format,
                                                    memory: &[u8],
                                                    offset: O,
                                                    size: S)
                                                    -> Result<(), Self::Error> {
        let offset = offset.into();
        let size = size.into();
        unsafe {
            gl::BindTexture(gl::TEXTURE_2D, self.id);
            gl::TexSubImage2D(gl::TEXTURE_2D,
                              0,
                              offset[0] as i32,
                              offset[1] as i32,
                              size[0] as i32,
                              size[1] as i32,
                              gl::RGBA,
                              gl::UNSIGNED_BYTE,
                              memory.as_ptr() as *const _);
        }

        Ok(())
    }
}

impl graphics::ImageSize for Texture {
    fn get_size(&self) -> (u32, u32) {
        (self.width, self.height)
    }
}