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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::platform::opengl;
use opengl::context::bindings::types::*;
use opengl::context::bindings::{
    ALPHA, CLAMP_TO_EDGE, LINEAR, NEAREST, REPEAT, RGB, RGBA, TEXTURE_2D,
    TEXTURE_MAG_FILTER, TEXTURE_MIN_FILTER, TEXTURE_WRAP_S, TEXTURE_WRAP_T,
    UNPACK_ALIGNMENT, UNSIGNED_BYTE,
};
use opengl::context::OpenGlBindings;

use super::TextureSize;

static DEFAULT_POPULATE_DEBUG: DefaultPopulateDebug = DefaultPopulateDebug;

struct DefaultPopulateDebug;

impl std::fmt::Debug for DefaultPopulateDebug {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        f.write_str("dyn PopulateTexture")
    }
}

/// A trait which allows cloning a PopulateTexture trait object.
pub trait PopulateTextureDynClone {
    /// Create a clone of this texture populator, as a boxed trait object.
    fn clone_boxed(&self) -> Box<dyn PopulateTexture>;
}

impl<T> PopulateTextureDynClone for T
where
    T: 'static + PopulateTexture + Clone,
{
    fn clone_boxed(&self) -> Box<dyn PopulateTexture> {
        Box::new(self.clone())
    }
}

/// A trait which describes how to populate a texture.
///
/// This is automatically implemented for closures which match the signature
/// of the `populate` method, which may be considered the simplest type of
/// texture populator.
pub trait PopulateTexture: PopulateTextureDynClone {
    /// Execute the necesary opengl commands to populate a texture.
    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()>;

    /// This function should return Some, if the populator can perfectly
    /// determine the size the texture will be without loading it.
    fn get_known_size(&self) -> Option<(f32, f32)> {
        None
    }

    /// An implementation may override this with a better debug implementation.
    fn debug(&self) -> &dyn std::fmt::Debug {
        &DEFAULT_POPULATE_DEBUG
    }
}

impl<F> PopulateTexture for F
where
    F: 'static + Clone,
    F: for<'a> Fn(&'a OpenGlBindings) -> Result<TextureSize, ()>,
{
    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()> {
        (self)(gl)
    }
}

impl Clone for Box<dyn PopulateTexture> {
    fn clone(&self) -> Self {
        self.clone_boxed()
    }
}

impl std::fmt::Debug for Box<dyn PopulateTexture> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.debug().fmt(f)
    }
}

/// This type provides some helper functions for common texture populator
/// needs.
pub struct PopulateTextureUtil;

impl PopulateTextureUtil {
    /// Set the default texture parameters for magnification and wrapping.
    pub fn default_params(gl: &OpenGlBindings) {
        unsafe {
            gl.TexParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, LINEAR as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, LINEAR as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_WRAP_S, CLAMP_TO_EDGE as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_WRAP_T, CLAMP_TO_EDGE as _);
        }
    }

    fn populate_format(
        gl: &OpenGlBindings,
        format: GLint,
        width: u16,
        height: u16,
        alignment: u16,
        pixels: &[u8],
    ) -> Result<TextureSize, ()> {
        unsafe {
            gl.PixelStorei(UNPACK_ALIGNMENT, alignment.into());
        }
        if width.is_power_of_two() && height.is_power_of_two() {
            unsafe {
                gl.TexImage2D(
                    TEXTURE_2D,
                    0,
                    format,
                    width.into(),
                    height.into(),
                    0,
                    format as GLenum,
                    UNSIGNED_BYTE,
                    pixels.as_ptr() as *const _,
                );
            }
            Ok(TextureSize {
                image_width: width as f32,
                image_height: height as f32,
                texture_width: width as f32,
                texture_height: height as f32,
            })
        } else {
            let texture_width = width.next_power_of_two().into();
            let texture_height = height.next_power_of_two().into();
            let width: GLsizei = width.into();
            let height: GLsizei = height.into();
            unsafe {
                gl.TexImage2D(
                    TEXTURE_2D,
                    0,
                    format,
                    texture_width,
                    texture_height,
                    0,
                    format as GLenum,
                    UNSIGNED_BYTE,
                    std::ptr::null(),
                );
                gl.TexSubImage2D(
                    TEXTURE_2D,
                    0,
                    0,
                    0,
                    width,
                    height,
                    format as GLenum,
                    UNSIGNED_BYTE,
                    pixels.as_ptr() as *const _,
                );
            }
            Ok(TextureSize {
                image_width: width as f32,
                image_height: height as f32,
                texture_width: texture_width as f32,
                texture_height: texture_height as f32,
            })
        }
    }

    #[doc(hidden)]
    pub fn data_len(
        width: u16,
        height: u16,
        alignment: u16,
        channels: u16,
    ) -> usize {
        assert!(matches!(alignment, 1 | 2 | 4));
        let pixel_row_len = width * channels;
        let padding = (alignment - (pixel_row_len % alignment)) % alignment;
        let full_row_len = pixel_row_len + padding;
        (full_row_len as usize) * (height as usize)
    }

    /// Populate an image with a single channel.
    pub fn populate_alpha(
        gl: &OpenGlBindings,
        width: u16,
        height: u16,
        alignment: u16,
        pixels: &[u8],
    ) -> Result<TextureSize, ()> {
        assert_eq!(pixels.len(), Self::data_len(width, height, alignment, 1));
        Self::populate_format(gl, ALPHA as _, width, height, alignment, pixels)
    }

    /// Populate an texture with three channels.
    pub fn populate_rgb(
        gl: &OpenGlBindings,
        width: u16,
        height: u16,
        alignment: u16,
        pixels: &[u8],
    ) -> Result<TextureSize, ()> {
        assert_eq!(pixels.len(), Self::data_len(width, height, alignment, 3));
        Self::populate_format(gl, RGB as _, width, height, alignment, pixels)
    }

    /// Populate an texture with four channels.
    pub fn populate_rgba(
        gl: &OpenGlBindings,
        width: u16,
        height: u16,
        alignment: u16,
        pixels: &[u8],
    ) -> Result<TextureSize, ()> {
        assert_eq!(pixels.len(), Self::data_len(width, height, alignment, 4));
        Self::populate_format(gl, RGBA as _, width, height, alignment, pixels)
    }
}

#[derive(Clone, Copy, Default, PartialEq)]
pub(super) struct DefaultTexturePopulator;

impl PopulateTexture for DefaultTexturePopulator {
    fn get_known_size(&self) -> Option<(f32, f32)> {
        Some((2.0, 2.0))
    }

    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()> {
        let pixels: [u8; 12] = [0xff; 12];
        unsafe {
            gl.PixelStorei(UNPACK_ALIGNMENT, 1);
        }
        let size = PopulateTextureUtil::populate_rgb(gl, 2, 2, 1, &pixels);
        unsafe {
            gl.TexParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, NEAREST as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, NEAREST as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_WRAP_S, CLAMP_TO_EDGE as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_WRAP_T, CLAMP_TO_EDGE as _);
        }
        size
    }
}

#[derive(Clone, Copy, Default, PartialEq)]
pub(super) struct ErrorTexturePopulator;

const ERRTEX_SIDE: u16 = 16;
const ERRTEX: &[u8] = include_bytes!("errtex.data");

impl PopulateTexture for ErrorTexturePopulator {
    fn get_known_size(&self) -> Option<(f32, f32)> {
        Some((16.0, 16.0))
    }

    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()> {
        unsafe {
            gl.PixelStorei(UNPACK_ALIGNMENT, 1);
        }
        let size = PopulateTextureUtil::populate_rgb(
            gl,
            ERRTEX_SIDE,
            ERRTEX_SIDE,
            1,
            ERRTEX,
        );
        unsafe {
            gl.TexParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, NEAREST as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, NEAREST as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_WRAP_S, REPEAT as _);
            gl.TexParameteri(TEXTURE_2D, TEXTURE_WRAP_T, REPEAT as _);
        }
        size
    }
}

#[derive(Clone, Debug)]
pub(super) struct AlphaTexturePopulator {
    pub(super) width: u16,
    pub(super) height: u16,
    pub(super) alignment: u16,
    pub(super) pixels: std::borrow::Cow<'static, [u8]>,
}

impl PopulateTexture for AlphaTexturePopulator {
    fn get_known_size(&self) -> Option<(f32, f32)> {
        Some((self.width as f32, self.height as f32))
    }

    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()> {
        unsafe {
            gl.PixelStorei(UNPACK_ALIGNMENT, self.alignment.into());
        }
        let size = PopulateTextureUtil::populate_alpha(
            gl,
            self.width,
            self.height,
            self.alignment,
            &self.pixels,
        );
        PopulateTextureUtil::default_params(gl);
        size
    }
}

#[derive(Clone, Debug)]
pub(super) struct RGBTexturePopulator {
    pub(super) width: u16,
    pub(super) height: u16,
    pub(super) alignment: u16,
    pub(super) pixels: std::borrow::Cow<'static, [u8]>,
}

impl PopulateTexture for RGBTexturePopulator {
    fn get_known_size(&self) -> Option<(f32, f32)> {
        Some((self.width as f32, self.height as f32))
    }

    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()> {
        unsafe {
            gl.PixelStorei(UNPACK_ALIGNMENT, self.alignment.into());
        }
        let size = PopulateTextureUtil::populate_rgb(
            gl,
            self.width,
            self.height,
            self.alignment,
            &self.pixels,
        );
        PopulateTextureUtil::default_params(gl);
        size
    }
}

#[derive(Clone, Debug)]
pub(super) struct RGBATexturePopulator {
    pub(super) width: u16,
    pub(super) height: u16,
    pub(super) alignment: u16,
    pub(super) pixels: std::borrow::Cow<'static, [u8]>,
}

impl PopulateTexture for RGBATexturePopulator {
    fn get_known_size(&self) -> Option<(f32, f32)> {
        Some((self.width as f32, self.height as f32))
    }

    fn populate(&self, gl: &OpenGlBindings) -> Result<TextureSize, ()> {
        let size = PopulateTextureUtil::populate_rgba(
            gl,
            self.width,
            self.height,
            self.alignment,
            &self.pixels,
        );
        PopulateTextureUtil::default_params(gl);
        size
    }
}