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
use super::*;

/// # Safety
/// Don't implement yourself
pub unsafe trait TexturePixel {
    const INTERNAL_FORMAT: raw::Enum;
    const FORMAT: raw::Enum;
    const TYPE: raw::Enum;
}

unsafe impl TexturePixel for Rgba<f32> {
    const INTERNAL_FORMAT: raw::Enum = raw::RGBA;
    const FORMAT: raw::Enum = raw::RGBA;
    const TYPE: raw::Enum = raw::UNSIGNED_BYTE;
}

unsafe impl TexturePixel for u8 {
    #[cfg(target_arch = "wasm32")]
    const INTERNAL_FORMAT: raw::Enum = raw::ALPHA;
    #[cfg(not(target_arch = "wasm32"))]
    const INTERNAL_FORMAT: raw::Enum = raw::RGBA;
    const FORMAT: raw::Enum = raw::ALPHA;
    const TYPE: raw::Enum = raw::UNSIGNED_BYTE;
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
pub enum WrapMode {
    Repeat = raw::REPEAT as _,
    Clamp = raw::CLAMP_TO_EDGE as _,
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
pub enum Filter {
    Nearest = raw::NEAREST as _,
    Linear = raw::LINEAR as _,
}

pub struct Texture2d<P: TexturePixel> {
    pub(crate) ugli: Ugli,
    pub(crate) handle: raw::Texture,
    size: Cell<vec2<usize>>,
    phantom_data: PhantomData<*mut P>,
}

impl<P: TexturePixel> Drop for Texture2d<P> {
    fn drop(&mut self) {
        let gl = &self.ugli.inner.raw;
        gl.delete_texture(&self.handle);
    }
}

pub type Texture = Texture2d<Rgba<f32>>;

impl<P: TexturePixel> Texture2d<P> {
    fn new_raw(ugli: &Ugli, size: vec2<usize>) -> Self {
        let gl = &ugli.inner.raw;
        let handle = gl.create_texture().unwrap();
        gl.bind_texture(raw::TEXTURE_2D, &handle);
        gl.tex_parameteri(
            raw::TEXTURE_2D,
            raw::TEXTURE_MIN_FILTER,
            raw::LINEAR as raw::Int,
        );
        let mut texture = Self {
            ugli: ugli.clone(),
            handle,
            size: Cell::new(size),
            phantom_data: PhantomData,
        };
        texture.set_filter(Filter::Linear);
        texture.set_wrap_mode(WrapMode::Clamp);
        ugli.debug_check();
        texture
    }

    pub fn is_pot(&self) -> bool {
        let size = self.size.get();
        size.x & (size.x - 1) == 0 && size.y & (size.y - 1) == 0
    }

    pub fn new_uninitialized(ugli: &Ugli, size: vec2<usize>) -> Self {
        let texture = Self::new_raw(ugli, size);
        let gl = &ugli.inner.raw;
        gl.tex_image_2d::<u8>(
            raw::TEXTURE_2D,
            0,
            P::INTERNAL_FORMAT as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            0,
            P::FORMAT,
            P::TYPE,
            None,
        );
        ugli.debug_check();
        texture
    }
    pub fn set_wrap_mode(&mut self, wrap_mode: WrapMode) {
        self.set_wrap_mode_separate(wrap_mode, wrap_mode);
    }

    pub fn set_wrap_mode_separate(&mut self, wrap_mode_x: WrapMode, wrap_mode_y: WrapMode) {
        if wrap_mode_x == WrapMode::Repeat || wrap_mode_y == WrapMode::Repeat {
            assert!(
                self.is_pot(),
                "Repeat wrap mode only supported for power of two textures"
            ); // Because of webgl
        }
        let gl = &self.ugli.inner.raw;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.tex_parameteri(
            raw::TEXTURE_2D,
            raw::TEXTURE_WRAP_S,
            wrap_mode_x as raw::Int,
        );
        gl.tex_parameteri(
            raw::TEXTURE_2D,
            raw::TEXTURE_WRAP_T,
            wrap_mode_y as raw::Int,
        );
        self.ugli.debug_check();
    }

    pub fn set_filter(&mut self, filter: Filter) {
        assert!(self.is_pot() || filter == Filter::Nearest || filter == Filter::Linear);
        let gl = &self.ugli.inner.raw;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.tex_parameteri(raw::TEXTURE_2D, raw::TEXTURE_MAG_FILTER, filter as raw::Int);
        gl.tex_parameteri(raw::TEXTURE_2D, raw::TEXTURE_MIN_FILTER, filter as raw::Int);
        self.ugli.debug_check();
    }

    pub fn size(&self) -> vec2<usize> {
        self.size.get()
    }

    // TODO: use like Matrix<Color>?
    pub fn sub_image(&mut self, pos: vec2<usize>, size: vec2<usize>, data: &[u8]) {
        assert_eq!(
            size.x
                * size.y
                * match P::FORMAT {
                    raw::RGBA => 4,
                    raw::ALPHA => 1,
                    _ => unreachable!(),
                },
            data.len()
        );
        let gl = &self.ugli.inner.raw;
        gl.pixel_store_flip_y(false);
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.tex_sub_image_2d(
            raw::TEXTURE_2D,
            0,
            pos.x as raw::Int,
            pos.y as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            P::FORMAT,
            P::TYPE,
            data,
        );
        self.ugli.debug_check();
    }
}

impl Texture {
    pub fn gen_mipmaps(&mut self) {
        assert!(self.is_pot());
        let gl = &self.ugli.inner.raw;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.generate_mipmap(raw::TEXTURE_2D);
        gl.tex_parameteri(
            raw::TEXTURE_2D,
            raw::TEXTURE_MIN_FILTER,
            raw::LINEAR_MIPMAP_LINEAR as raw::Int,
        );
        self.ugli.debug_check();
    }

    pub fn new_with<F: FnMut(vec2<usize>) -> Rgba<f32>>(
        ugli: &Ugli,
        size: vec2<usize>,
        mut f: F,
    ) -> Self {
        let texture = Texture2d::new_raw(ugli, size);
        let mut data: Vec<u8> = Vec::with_capacity(size.x * size.y * 4);
        for y in 0..size.y {
            for x in 0..size.x {
                let color = f(vec2(x, y));
                data.push((color.r * 255.0) as u8);
                data.push((color.g * 255.0) as u8);
                data.push((color.b * 255.0) as u8);
                data.push((color.a * 255.0) as u8);
            }
        }
        let gl = &ugli.inner.raw;
        gl.pixel_store_flip_y(false);
        gl.tex_image_2d(
            raw::TEXTURE_2D,
            0,
            raw::RGBA as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            0,
            raw::RGBA as raw::Enum,
            raw::UNSIGNED_BYTE,
            Some(&data),
        );
        ugli.debug_check();
        texture
    }

    pub fn from_image_image(ugli: &Ugli, mut image: image::RgbaImage) -> Self {
        let size = vec2(image.width() as usize, image.height() as usize);
        let mut texture = Texture2d::new_raw(ugli, size);
        let gl = &ugli.inner.raw;
        image::imageops::flip_vertical_in_place(&mut image);
        gl.pixel_store_flip_y(false);
        gl.tex_image_2d(
            raw::TEXTURE_2D,
            0,
            raw::RGBA as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            0,
            raw::RGBA as raw::Enum,
            raw::UNSIGNED_BYTE,
            Some(&image.into_raw()),
        );
        if texture.is_pot() {
            texture.gen_mipmaps();
        }
        ugli.debug_check();
        texture
    }

    #[cfg(target_arch = "wasm32")]
    pub fn from_html_image_element(
        ugli: &Ugli,
        image: &web_sys::HtmlImageElement,
        premultiply_alpha: bool,
    ) -> Self {
        let mut texture =
            Texture2d::new_raw(ugli, vec2(image.width() as usize, image.height() as usize));
        let gl = &ugli.inner.raw;
        gl.pixel_store_flip_y(true);
        gl.pixel_store_premultiply_alpha(premultiply_alpha);
        gl.tex_image_2d_image(
            raw::TEXTURE_2D,
            0,
            raw::RGBA as raw::Int,
            raw::RGBA,
            raw::UNSIGNED_BYTE,
            image,
        );
        if texture.is_pot() {
            texture.gen_mipmaps();
        }
        ugli.debug_check();
        texture
    }
}