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
//! This module provides texture features.

use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

use pixel::Pixel;

/// How to wrap texture coordinates while sampling textures?
#[derive(Clone, Copy, Debug)]
pub enum Wrap {
  /// If textures coordinates lay outside of *[0;1]*, they will be clamped to either *0* or *1* for
  /// every components.
  ClampToEdge,
  /// Textures coordinates are repeated if they lay outside of *[0;1]*. Picture this as:
  ///
  /// ```
  /// // given the frac function returning the fractional part of a floating number:
  /// coord_ith = frac(coord_ith); // always between [0;1]
  /// ```
  Repeat,
  /// Same as `Repeat` but it will alternatively repeat between *[0;1]* and *[1;0]*.
  MirroredRepeat
}

/// Minification and magnification filter.
#[derive(Clone, Copy, Debug)]
pub enum Filter {
  /// Clamp to nearest pixel.
  Nearest,
  /// Linear interpolation with surrounding pixels.
  Linear
}

/// Depth comparison to perform while depth test. `a` is the incoming fragment’s depth and b is the
/// fragment’s depth that is already stored.
#[derive(Clone, Copy, Debug)]
pub enum DepthComparison {
  /// Depth test never succeeds.
  Never,
  /// Depth test always succeeds.
  Always,
  /// Depth test succeeds if `a == b`.
  Equal,
  /// Depth test succeeds if `a != b`.
  NotEqual,
  /// Depth test succeeds if `a < b`.
  Less,
  /// Depth test succeeds if `a <= b`.
  LessOrEqual,
  /// Depth test succeeds if `a > b`.
  Greater,
  /// Depth test succeeds if `a >= b`.
  GreaterOrEqual
}

/// Reify a type into a `Dim`.
pub trait Dimensionable {
  type Size;
  type Offset;

  /// Dimension.
  fn dim() -> Dim;
  /// Width of the associated `Size`.
  fn width(size: Self::Size) -> u32 where Self::Size: Copy;
  /// Height of the associated `Size`. If it doesn’t have one, set it to 1.
  fn height(_: Self::Size) -> u32 where Self::Size: Copy { 1 }
  /// Depth of the associated `Size`. If it doesn’t have one, set it to 1.
  fn depth(_: Self::Size) -> u32 where Self::Size: Copy { 1 }
  /// X offset.
  fn x_offset(offset: Self::Offset) -> u32 where Self::Offset: Copy;
  /// Y offset. If it doesn’t have one, set it to 0.
  fn y_offset(_: Self::Offset) -> u32 where Self::Offset: Copy { 1 }
  /// Z offset. If it doesn’t have one, set it to 0.
  fn z_offset(_: Self::Offset) -> u32 where Self::Offset: Copy { 1 }
  /// Zero offset.
  fn zero_offset() -> Self::Offset;
}

/// Capacity of the dimension, which is the product of the width, height and depth.
pub fn dim_capacity<D>(size: D::Size) -> u32 where D: Dimensionable, D::Size: Copy {
  D::width(size) * D::height(size) * D::depth(size)
}

/// Dimension of a texture.
#[derive(Clone, Copy, Debug)]
pub enum Dim {
  Dim1,
  Dim2,
  Dim3,
  Cubemap
}

/// 1D dimension.
#[derive(Clone, Copy, Debug)]
pub struct Dim1;

impl Dimensionable for Dim1 {
  type Size = u32;
  type Offset = u32;

  fn dim() -> Dim { Dim::Dim1 }

  fn width(w: Self::Size) -> u32 { w }

  fn x_offset(off: Self::Offset) -> u32 { off }

  fn zero_offset() -> Self::Offset { 0 }
}

/// 2D dimension.
#[derive(Clone, Copy, Debug)]
pub struct Dim2;

impl Dimensionable for Dim2 {
  type Size = (u32, u32);
  type Offset = (u32, u32);

  fn dim() -> Dim { Dim::Dim2 }

  fn width(size: Self::Size) -> u32 { size.0 }

  fn height(size: Self::Size) -> u32 { size.1 }

  fn x_offset(off: Self::Offset) -> u32 { off.0 }

  fn y_offset(off: Self::Offset) -> u32 { off.1 }

  fn zero_offset() -> Self::Offset { (0, 0) }
}

/// 3D dimension.
#[derive(Clone, Copy, Debug)]
pub struct Dim3;

impl Dimensionable for Dim3 {
  type Size = (u32, u32, u32);
  type Offset = (u32, u32, u32);

  fn dim() -> Dim { Dim::Dim3 }

  fn width(size: Self::Size) -> u32 { size.0 }

  fn height(size: Self::Size) -> u32 { size.1 }

  fn depth(size: Self::Size) -> u32 { size.2 }

  fn x_offset(off: Self::Offset) -> u32 { off.0 }

  fn y_offset(off: Self::Offset) -> u32 { off.1 }

  fn z_offset(off: Self::Offset) -> u32 { off.2 }

  fn zero_offset() -> Self::Offset { (0, 0, 0) }
}

/// Cubemap dimension.
#[derive(Clone, Copy, Debug)]
pub struct Cubemap;

impl Dimensionable for Cubemap {
  type Size = u32;
  type Offset = (u32, u32, CubeFace);

  fn dim() -> Dim { Dim::Cubemap }

  fn width(s: Self::Size) -> u32 { s }

  fn height(s: Self::Size) -> u32 { s }

  fn depth(_: Self::Size) -> u32 { 6 }

  fn x_offset(off: Self::Offset) -> u32 { off.0 }

  fn y_offset(off: Self::Offset) -> u32 { off.1 }

  fn z_offset(off: Self::Offset) -> u32 {
    match off.2 {
      CubeFace::PositiveX => 0,
      CubeFace::NegativeX => 1,
      CubeFace::PositiveY => 2,
      CubeFace::NegativeY => 3,
      CubeFace::PositiveZ => 4,
      CubeFace::NegativeZ => 5
    }
  }

  fn zero_offset() -> Self::Offset { (0, 0, CubeFace::PositiveX) }
}

/// Faces of a cubemap.
#[derive(Clone, Copy, Debug)]
pub enum CubeFace {
  PositiveX,
  NegativeX,
  PositiveY,
  NegativeY,
  PositiveZ,
  NegativeZ
}

/// Trait used to reify a type into a `Layering`.
pub trait Layerable {
  /// Reify to `Layering`.
  fn layering() -> Layering;
}

/// Texture layering. If a texture is layered, it has an extra coordinate to access the layer.
#[derive(Clone, Copy, Debug)]
pub enum Layering {
  /// Non-layered.
  Flat,
  /// Layered.
  Layered
}

/// Flat texture hint.
///
/// A flat texture means it doesn’t have the concept of layers.
#[derive(Clone, Copy, Debug)]
pub struct Flat;

impl Layerable for Flat { fn layering() -> Layering { Layering::Flat } }

/// Layered texture hint.
///
/// A layered texture has an extra coordinate to access the layer and can be thought of as an array
/// of textures.
#[derive(Clone, Copy, Debug)]
pub struct Layered;

impl Layerable for Layered { fn layering() -> Layering { Layering::Layered } }

/// Trait to implement to provide texture features.
pub trait HasTexture {
  type ATexture;

  /// Create a new texture.
  ///
  /// `size` is a value used to specify the dimension of the texture. `mipmaps` is the number of
  /// extra *mipmaps* you want to have. If you set this value to `0`, you end up with only one level
  /// (the base level) of texture storage.
  fn new_texture<L, D, P>(size: D::Size, mipmaps: usize, sampler: &Sampler) -> Self::ATexture
    where L: Layerable,
          D: Dimensionable,
          D::Size: Copy,
          P: Pixel;
  /// Destroy a texture.
  fn free(tex: &mut Self::ATexture);
  /// Clear the texture’s texels by setting them all to the same value.
  fn clear_part<L, D, P>(tex: &Self::ATexture, gen_mimpmaps: bool, offset: D::Offset, size: D::Size, pixel: P::Encoding)
    where L: Layerable, D: Dimensionable, D::Offset: Copy, D::Size: Copy, P: Pixel, P::Encoding: Copy;
  /// Upload texels to the texture’s memory.
  fn upload_part<L, D, P>(tex: &Self::ATexture, gen_mipmaps: bool, offset: D::Offset, size: D::Size, texels: &[P::Encoding])
    where L: Layerable, D::Offset: Copy, D::Size: Copy, D: Dimensionable, P: Pixel;
  /// Upload raw texels to the texture’s memory.
  fn upload_part_raw<L, D, P>(tex: &Self::ATexture, gen_mipmaps: bool, offset: D::Offset, size: D::Size, texels: &[P::RawEncoding])
    where L: Layerable, D::Offset: Copy, D::Size: Copy, D: Dimensionable, P: Pixel;
  /// Retrieve the texels as a collection of P::RawEncoding.
  fn get_raw_texels<P>(tex: &Self::ATexture) -> Vec<P::RawEncoding> where P: Pixel, P::RawEncoding: Copy;
}

/// Texture.
///
/// `L` refers to the layering type; `D` refers to the dimension; `P` is the pixel format for the
/// texels.
#[derive(Debug)]
pub struct Texture<C, L, D, P> where C: HasTexture, L: Layerable, D: Dimensionable, P: Pixel {
  pub repr: C::ATexture,
  pub size: D::Size,
  pub mipmaps: usize,
  _l: PhantomData<L>,
  _c: PhantomData<C>,
  _p: PhantomData<P>
}

impl<C, L, D, P> Drop for Texture<C, L, D, P> where C: HasTexture, L: Layerable, D: Dimensionable, P: Pixel {
  fn drop(&mut self) {
    C::free(&mut self.repr)
  }
}

impl<C, L, D, P> Texture<C, L, D, P>
    where C: HasTexture,
          L: Layerable,
          D: Dimensionable,
          D::Size: Copy,
          P: Pixel {
  pub fn new(size: D::Size, mipmaps: usize, sampler: &Sampler) -> Self {
    let mipmaps = mipmaps + 1; // + 1 prevent having 0 mipmaps
    let tex = C::new_texture::<L, D, P>(size, mipmaps, sampler);

    Texture {
      repr: tex,
      size: size,
      mipmaps: mipmaps,
      _c: PhantomData,
      _l: PhantomData,
      _p: PhantomData
    }
  }

  /// Create a texture from its backend representation.
  pub fn from_raw(texture: C::ATexture, size: D::Size, mipmaps: usize) -> Self {
    Texture {
      repr: texture,
      size: size,
      mipmaps: mipmaps + 1,
      _c: PhantomData,
      _l: PhantomData,
      _p: PhantomData
    }
  }

  /// Clear a part of a texture.
  ///
  /// The part being cleared is defined by a rectangle in which the `offset` represents the
  /// left-upper corner and the `size` gives the dimension of the rectangle. All the covered texels
  /// by this rectangle will be cleared to the `pixel` value.
  pub fn clear_part(&self, gen_mipmaps: bool, offset: D::Offset, size: D::Size, pixel: P::Encoding)
      where D::Offset: Copy,
            D::Size: Copy,
            P::Encoding: Copy {
    C::clear_part::<L, D, P>(&self.repr, gen_mipmaps, offset, size, pixel)
  }

  /// Clear a whole texture with a `pixel` value.
  pub fn clear(&self, gen_mipmaps: bool, pixel: P::Encoding)
      where D::Offset: Copy,
            D::Size: Copy,
            P::Encoding: Copy {
    self.clear_part(gen_mipmaps, D::zero_offset(), self.size, pixel)
  }

  /// Upload texels to a part of a texture.
  ///
  /// The part being updated is defined by a rectangle in which the `offset` represents the
  /// left-upper corner and the `size` gives the dimension of the rectangle. All the covered texels
  /// by this rectangle will be updated by the `texels` slice.
  pub fn upload_part(&self, gen_mipmaps: bool, offset: D::Offset, size: D::Size, texels: &[P::Encoding])
      where D::Offset: Copy,
            D::Size: Copy {
    C::upload_part::<L, D, P>(&self.repr, gen_mipmaps, offset, size, texels)
  }

  /// Upload `texels` to the whole texture.
  pub fn upload(&self, gen_mipmaps: bool, texels: &[P::Encoding])
      where D::Offset: Copy,
            D::Size: Copy {
    self.upload_part(gen_mipmaps, D::zero_offset(), self.size, texels)
  }

  /// Upload raw `texels` to a part of a texture.
  ///
  /// This function is similar to `upload_part` but it works on `P::RawEncoding` instead of
  /// `P::Encoding`. This useful when the texels are represented as a contiguous array of raw
  /// components of the texels.
  pub fn upload_part_raw(&self, gen_mipmaps: bool, offset: D::Offset, size: D::Size, texels: &[P::RawEncoding])
      where D::Offset: Copy,
            D::Size: Copy {
    C::upload_part_raw::<L, D, P>(&self.repr, gen_mipmaps, offset, size, texels)
  }

  /// Upload raw `texels` to the whole texture.
  pub fn upload_raw(&self, gen_mipmaps: bool, texels: &[P::RawEncoding])
      where D::Offset: Copy,
            D::Size: Copy {
    self.upload_part_raw(gen_mipmaps, D::zero_offset(), self.size, texels)
  }

  /// Get the raw texels associated with this texture.
  pub fn get_raw_texels(&self) -> Vec<P::RawEncoding> where P: Pixel, P::RawEncoding: Copy {
    C::get_raw_texels::<P>(&self.repr)
  }
}

/// A `Sampler` object gives hint on how a `Texture` should be sampled.
#[derive(Clone, Copy, Debug)]
pub struct Sampler {
  /// How should we wrap around the *r* sampling coordinate?
  pub wrap_r: Wrap,
  /// How should we wrap around the *s* sampling coordinate?
  pub wrap_s: Wrap,
  /// How should we wrap around the *t* sampling coordinate?
  pub wrap_t: Wrap,
  /// Minification filter.
  pub minification: Filter,
  /// Magnification filter.
  pub magnification: Filter,
  /// For depth textures, should we perform depth comparison and if so, how?
  pub depth_comparison: Option<DepthComparison>
}

/// Default value is as following:
///
/// ```
/// Sampler {
///   wrap_r: Wrap::ClampToEdge,
///   wrap_s: Wrap::ClampToEdge,
///   wrap_t: Wrap::ClampToEdge,
///   minification: Filter::Linear,
///   magnification: Filter::Linear,
///   depth_comparison: None
/// }
/// ```
impl Default for Sampler {
  fn default() -> Self {
    Sampler {
      wrap_r: Wrap::ClampToEdge,
      wrap_s: Wrap::ClampToEdge,
      wrap_t: Wrap::ClampToEdge,
      minification: Filter::Linear,
      magnification: Filter::Linear,
      depth_comparison: None
    }
  }
}

/// Texture unit.
pub struct Unit {
  unit: u32
}

impl Unit {
  pub fn new(unit: u32) -> Self {
    Unit {
      unit: unit
    }
  }
}

impl Deref for Unit {
  type Target = u32;

  fn deref(&self) -> &Self::Target {
    &self.unit
  }
}

impl DerefMut for Unit {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.unit
  }
}

/// An opaque type representing any texture.
pub struct TextureProxy<'a, C> where C: HasTexture + 'a {
  pub repr: &'a C::ATexture
}

impl<'a, C, L, D, P> From<&'a Texture<C, L, D, P>> for TextureProxy<'a, C>
    where C: HasTexture,
          L: Layerable,
          D: Dimensionable,
          D::Size: Copy,
          P: Pixel {
  fn from(texture: &'a Texture<C, L, D, P>) -> Self {
    TextureProxy {
      repr: &texture.repr
    }
  }
}