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

// Copyright 2017 The gltf Library Developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate gltf;

use std::{fmt, marker, mem};

use gltf::accessor::{DataType, Dimensions};

/// Helper trait for denormalizing integer types.
///
/// # Examples
///
/// Denormalize a single `u16`.
///
/// ```rust
/// use gltf_utils::Denormalize;
/// let x: u16 = 65535;
/// assert_eq!(1.0, x.denormalize());
/// ```
///
/// Denormalize an array of integers.
///
/// ```rust
/// use gltf_utils::Denormalize;
/// let rgb: [u8; 3] = [0, 120, 255];
/// assert_eq!([0.0, 120.0 / 255.0, 1.0], rgb.denormalize());
/// ```
pub trait Denormalize {
    /// The denormalized version of this type.
    type Denormalized;

    /// Returns the denormalized equivalent of the value.
    fn denormalize(&self) -> Self::Denormalized;
}

/// Represents sources of buffer data.
///
/// See the `Buffers` type in the `gltf-importer` crate for the reference
/// implementation.
pub trait Source: fmt::Debug {
    /// Return the buffer data referenced by the given `Buffer`.
    ///
    /// This method must not fail.
    fn source_buffer(&self, buffer: &gltf::Buffer) -> &[u8];
}

/// Extra methods for working with `gltf::Primitive`.
pub trait PrimitiveIterators<'a> {
    /// Visits the vertex positions of a primitive.
    fn positions<S>(&'a self, source: &'a S) -> Option<Positions<'a>>
        where S: Source;

    /// Visits the vertex normals of a primitive.
    fn normals<S>(&'a self, source: &'a S) -> Option<Normals<'a>>
        where S: Source;
    
    /// Visits the vertex tangents of a primitive.
    fn tangents<S>(&'a self, source: &'a S) -> Option<Tangents<'a>>
        where S: Source;
    
    /// Visits the vertex texture co-ordinates of a primitive.
    fn tex_coords_f32<S>(
        &'a self,
        set: u32,
        source: &'a S,
    ) -> Option<TexCoordsF32<'a>>
        where S: Source;
    
    /// Visits the vertex colors of a primitive.
    fn colors_rgba_f32<S>(
        &'a self,
        set: u32,
        default_alpha: f32,
        source: &'a S,
    ) -> Option<ColorsRgbaF32<'a>>
        where S: Source;

    /// Visits the vertex draw sequence of a primitive.
    fn indices_u32<S>(&'a self, source: &'a S) -> Option<IndicesU32<'a>>
        where S: Source;

    /// Visits the joint indices of the primitive.
    fn joints_u16<S: Source>(&'a self, set: u32, source: &'a S) -> Option<JointsU16<'a>>
        where S: Source;

    /// Visits the joint weights of the primitive.
    fn weights_f32<S: Source>(&'a self, set: u32, source: &'a S) -> Option<WeightsF32<'a>>
        where S: Source;
}

impl<'a> PrimitiveIterators<'a> for gltf::Primitive<'a> {
    fn positions<S>(&'a self, source: &'a S) -> Option<Positions<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::Positions)
            .map(|accessor| Positions(AccessorIter::new(accessor, source)))
    }

    fn normals<S>(&'a self, source: &'a S) -> Option<Normals<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::Normals)
            .map(|accessor| Normals(AccessorIter::new(accessor, source)))
    }

    fn tangents<S>(&'a self, source: &'a S) -> Option<Tangents<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::Tangents)
            .map(|accessor| Tangents(AccessorIter::new(accessor, source)))
    }

    fn tex_coords_f32<S>(&'a self, set: u32, source: &'a S) -> Option<TexCoordsF32<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::TexCoords(set))
            .map(|accessor| TexCoordsF32(TexCoords::new(accessor, source)))
    }

    fn colors_rgba_f32<S>(
        &'a self,
        set: u32,
        default_alpha: f32,
        source: &'a S,
    ) -> Option<ColorsRgbaF32<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::Colors(set))
            .map(|accessor| {
                ColorsRgbaF32 {
                    iter: Colors::new(accessor, source),
                    default_alpha,
                }
            })
    }

    fn indices_u32<S>(&'a self, source: &'a S) -> Option<IndicesU32<'a>>
        where S: Source
    {
        self.indices().map(|accessor| IndicesU32(Indices::new(accessor, source)))
    }
    
    fn joints_u16<S>(&'a self, set: u32, source: &'a S) -> Option<JointsU16<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::Joints(set))
            .map(|accessor| JointsU16(Joints::new(accessor, source)))
    }

    fn weights_f32<S>(&'a self, set: u32, source: &'a S) -> Option<WeightsF32<'a>>
        where S: Source
    {
        self.get(&gltf::Semantic::Weights(set))
            .map(|accessor| WeightsF32(Weights::new(accessor, source)))
    }
}

/// Visits the items in an `Accessor`.
#[derive(Clone, Debug)]
pub struct AccessorIter<'a, T> {
    /// The total number of iterations left.
    count: usize,

    /// The index of the next iteration.
    index: usize,

    /// The number of bytes between each item.
    stride: usize,

    /// Byte offset into the buffer view where the items begin.
    offset: usize,
    
    /// The data we're iterating over.
    data: &'a [u8],

    /// The accessor we're iterating over.
    accessor: gltf::Accessor<'a>,
    
    /// Consumes the data type we're returning at each iteration.
    _marker: marker::PhantomData<T>,
}

impl<'a, T> AccessorIter<'a, T> {
    pub fn new<S>(accessor: gltf::Accessor<'a>, source: &'a S) -> AccessorIter<'a, T>
        where S: Source
    {
        assert_eq!(mem::size_of::<T>(), accessor.size());
        let view = accessor.view();
        let buffer = view.buffer();
        let buffer_data = source.source_buffer(&buffer);
        let view_data = &buffer_data[view.offset()..(view.offset() + view.length())];
        AccessorIter {
            index: 0,
            stride: view.stride().unwrap_or(mem::size_of::<T>()),
            offset: accessor.offset(),
            count: accessor.count(),
            accessor: accessor,
            data: view_data,
            _marker: marker::PhantomData,
        }
    }
}

/// XYZ vertex normals of type `[f32; 3]`.
#[derive(Clone, Debug)]
pub struct Normals<'a>(AccessorIter<'a, [f32; 3]>);

/// XYZ vertex positions of type `[f32; 3]`.
#[derive(Clone, Debug)]
pub struct Positions<'a>(AccessorIter<'a, [f32; 3]>);

/// XYZW vertex tangents of type `[f32; 4]` where the `w` component is a
/// sign value (-1 or +1) indicating the handedness of the tangent basis.
#[derive(Clone, Debug)]
pub struct Tangents<'a>(AccessorIter<'a, [f32; 4]>);

/// Vertex colors.
#[derive(Clone, Debug)]
enum Colors<'a> {
    /// RGB vertex color of type `[u8; 3]>`.
    RgbU8(AccessorIter<'a, [u8; 3]>),

    /// RGBA vertex color of type `[u8; 4]>`.
    RgbaU8(AccessorIter<'a, [u8; 4]>),

    /// RGB vertex color of type `[u16; 3]>`.
    RgbU16(AccessorIter<'a, [u16; 3]>),

    /// RGBA vertex color of type `[u16; 4]>`.
    RgbaU16(AccessorIter<'a, [u16; 4]>),

    /// RGB vertex color of type `[f32; 3]`.
    RgbF32(AccessorIter<'a, [f32; 3]>),

    /// RGBA vertex color of type `[f32; 4]`.
    RgbaF32(AccessorIter<'a, [f32; 4]>),
}

/// Index data.
#[derive(Clone, Debug)]
enum Indices<'a> {
    /// Index data of type U8
    U8(AccessorIter<'a, u8>),
    /// Index data of type U16
    U16(AccessorIter<'a, u16>),
    /// Index data of type U32
    U32(AccessorIter<'a, u32>),
}

/// Vertex joints.
#[derive(Clone, Debug)]
enum Joints<'a> {
    /// Joints of type `[u8; 4]`.
    /// Refer to the documentation on morph targets and skins for more
    /// information.
    U8(AccessorIter<'a, [u8; 4]>),
    
    /// Joints of type `[u16; 4]`.
    /// Refer to the documentation on morph targets and skins for more
    /// information.
    U16(AccessorIter<'a, [u16; 4]>),
}

/// UV texture co-ordinates.
#[derive(Clone, Debug)]
enum TexCoords<'a> {
    /// UV texture co-ordinates of type `[f32; 2]`.
    F32(AccessorIter<'a, [f32; 2]>),

    /// UV texture co-ordinates of type `[u8; 2]>`.
    U8(AccessorIter<'a, [u8; 2]>),

    /// UV texture co-ordinates of type `[u16; 2]>`.
    U16(AccessorIter<'a, [u16; 2]>),
}

/// Weights,
#[derive(Clone, Debug)]
enum Weights<'a> {
    /// Weights of type `[f32; 4]`.
    F32(AccessorIter<'a, [f32; 4]>),

    /// Weights of type `[u8; 4]`.
    U8(AccessorIter<'a, [u8; 4]>),

    /// Weights of type `[u16; 4]`.
    U16(AccessorIter<'a, [u16; 4]>),
}

/// Index data coerced into `u32` values.
#[derive(Clone, Debug)]
pub struct IndicesU32<'a>(Indices<'a>);

/// Texture co-ordinates coerced into `[f32; 2]` values.
#[derive(Clone, Debug)]
pub struct TexCoordsF32<'a>(TexCoords<'a>);

/// Joint indices co-coerced into `[u16; 4]` values.
#[derive(Clone, Debug)]
pub struct JointsU16<'a>(Joints<'a>);

/// Joint weights co-coerced into `[f32; 4]` values.
#[derive(Clone, Debug)]
pub struct WeightsF32<'a>(Weights<'a>);

/// Vertex colors coerced into `[f32; 4]` (RGBA) values.
#[derive(Clone, Debug)]
pub struct ColorsRgbaF32<'a> {
    /// Internal iterator type.
    iter: Colors<'a>,

    /// Default alpha value.
    default_alpha: f32,
}

impl<'a, T: Copy> ExactSizeIterator for AccessorIter<'a, T> {}
impl<'a, T: Copy> Iterator for AccessorIter<'a, T> {
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let offset = self.offset + self.index * self.stride;
            let ptr = unsafe { self.data.as_ptr().offset(offset as isize) };
            let value: T = unsafe { mem::transmute_copy(&*ptr) };
            self.index += 1;
            Some(value)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let hint = self.count - self.index;
        (hint, Some(hint))
    }
}

impl<'a> Colors<'a> {
    fn new<S: Source>(accessor: gltf::Accessor<'a>, source: &'a S) -> Colors<'a> {
        match (accessor.dimensions(), accessor.data_type()) {
            (Dimensions::Vec3, DataType::U8) => {
                Colors::RgbU8(AccessorIter::new(accessor, source))
            },
            (Dimensions::Vec4, DataType::U8) => {
                Colors::RgbaU8(AccessorIter::new(accessor, source))
            },
            (Dimensions::Vec3, DataType::U16) => {
                Colors::RgbU16(AccessorIter::new(accessor, source))
            },
            (Dimensions::Vec4, DataType::U16) => {
                Colors::RgbaU16(AccessorIter::new(accessor, source))
            },
            (Dimensions::Vec3, DataType::F32) => {
                Colors::RgbF32(AccessorIter::new(accessor, source))
            },
            (Dimensions::Vec4, DataType::F32) => {
                Colors::RgbaF32(AccessorIter::new(accessor, source))
            },
            _ => unreachable!(),
        }
    }
}
impl<'a> TexCoords<'a> {
    fn new<S: Source>(accessor: gltf::Accessor<'a>, source: &'a S) -> TexCoords<'a> {
        match accessor.data_type() {
            DataType::U8 => TexCoords::U8(AccessorIter::new(accessor, source)),
            DataType::U16 => TexCoords::U16(AccessorIter::new(accessor, source)),
            DataType::F32 => TexCoords::F32(AccessorIter::new(accessor, source)),
            _ => unreachable!(),
        }
    }
}

impl<'a> Indices<'a> {
    fn new<S: Source>(accessor: gltf::Accessor<'a>, source: &'a S) -> Indices<'a> {
        match accessor.data_type() {
            DataType::U8 => Indices::U8(AccessorIter::new(accessor, source)),
            DataType::U16 => Indices::U16(AccessorIter::new(accessor, source)),
            DataType::U32 => Indices::U32(AccessorIter::new(accessor, source)),
            _ => unreachable!(),
        }
    }
}

impl<'a> Joints<'a> {
    fn new<S: Source>(accessor: gltf::Accessor<'a>, source: &'a S) -> Joints<'a> {
        match accessor.data_type() {
            DataType::U8 => Joints::U8(AccessorIter::new(accessor, source)),
            DataType::U16 => Joints::U16(AccessorIter::new(accessor, source)),
            _ => unreachable!(),
        }
    }
}

impl<'a> Weights<'a> {
    fn new<S: Source>(accessor: gltf::Accessor<'a>, source: &'a S) -> Weights<'a> {
        match accessor.data_type() {
            DataType::U8 => Weights::U8(AccessorIter::new(accessor, source)),
            DataType::U16 => Weights::U16(AccessorIter::new(accessor, source)),
            DataType::F32 => Weights::F32(AccessorIter::new(accessor, source)),
            _ => unreachable!(),
        }
    }
}

impl<'a> ExactSizeIterator for IndicesU32<'a> {}
impl<'a> Iterator for IndicesU32<'a> {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> {
        match self.0 {
            Indices::U8(ref mut i) => i.next().map(|x| x as u32),
            Indices::U16(ref mut i) => i.next().map(|x| x as u32),
            Indices::U32(ref mut i) => i.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.0 {
            Indices::U8(ref i) => i.size_hint(),
            Indices::U16(ref i) => i.size_hint(),
            Indices::U32(ref i) => i.size_hint(),
        }
    }
}

impl<'a> ExactSizeIterator for JointsU16<'a> {}
impl<'a> Iterator for JointsU16<'a> {
    type Item = [u16; 4];
    fn next(&mut self) -> Option<Self::Item> {
        match self.0 {
            Joints::U8(ref mut i) => {
                i.next()
                    .map(|x| [x[0] as u16, x[1] as u16, x[2] as u16, x[3] as u16])
            },
            Joints::U16(ref mut i) => i.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.0 {
            Joints::U8(ref i) => i.size_hint(),
            Joints::U16(ref i) => i.size_hint(),
        }
    }
}

impl<'a> ExactSizeIterator for ColorsRgbaF32<'a> {}
impl<'a> Iterator for ColorsRgbaF32<'a> {
    type Item = [f32; 4];
    fn next(&mut self) -> Option<Self::Item> {
        let default_alpha = self.default_alpha;
        match self.iter {
            Colors::RgbU8(ref mut i) => {
                i.next().map(|x| {
                    let rgb = x.denormalize();
                    [rgb[0], rgb[1], rgb[2], default_alpha]
                })
            },
            Colors::RgbU16(ref mut i) => {
                i.next().map(|x| {
                    let rgb = x.denormalize();
                    [rgb[0], rgb[1], rgb[2], default_alpha]
                })
            },
            Colors::RgbF32(ref mut i) => {
                i.next().map(|rgb| [rgb[0], rgb[1], rgb[2], default_alpha])
            },
            Colors::RgbaU8(ref mut i) => i.next().map(|x| x.denormalize()),
            Colors::RgbaU16(ref mut i) => i.next().map(|x| x.denormalize()),
            Colors::RgbaF32(ref mut i) => i.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.iter {
            Colors::RgbU8(ref i) => i.size_hint(),
            Colors::RgbU16(ref i) => i.size_hint(),
            Colors::RgbF32(ref i) => i.size_hint(),
            Colors::RgbaU8(ref i) => i.size_hint(),
            Colors::RgbaU16(ref i) => i.size_hint(),
            Colors::RgbaF32(ref i) => i.size_hint(),
        }
    }
}

impl<'a> ExactSizeIterator for TexCoordsF32<'a> {}
impl<'a> Iterator for TexCoordsF32<'a> {
    type Item = [f32; 2];
    fn next(&mut self) -> Option<Self::Item> {
        match self.0 {
            TexCoords::U8(ref mut i) => i.next().map(|x| x.denormalize()),
            TexCoords::U16(ref mut i) => i.next().map(|x| x.denormalize()),
            TexCoords::F32(ref mut i) => i.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.0 {
            TexCoords::U8(ref i) => i.size_hint(),
            TexCoords::U16(ref i) => i.size_hint(),
            TexCoords::F32(ref i) => i.size_hint(),
        }
    }
}

impl<'a> ExactSizeIterator for WeightsF32<'a> {}
impl<'a> Iterator for WeightsF32<'a> {
    type Item = [f32; 4];
    fn next(&mut self) -> Option<Self::Item> {
        match self.0 {
            Weights::U8(ref mut i) => i.next().map(|x| x.denormalize()),
            Weights::U16(ref mut i) => i.next().map(|x| x.denormalize()),
            Weights::F32(ref mut i) => i.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.0 {
            Weights::U8(ref i) => i.size_hint(),
            Weights::U16(ref i) => i.size_hint(),
            Weights::F32(ref i) => i.size_hint(),
        }
    }
}

impl<'a> ExactSizeIterator for Positions<'a> {}
impl<'a> Iterator for Positions<'a> {
    type Item = [f32; 3];
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<'a> ExactSizeIterator for Normals<'a> {}
impl<'a> Iterator for Normals<'a> {
    type Item = [f32; 3];
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}
 
impl<'a> ExactSizeIterator for Tangents<'a> {}
impl<'a> Iterator for Tangents<'a> {
    type Item = [f32; 4];
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl Denormalize for u8 {
    type Denormalized = f32;
    fn denormalize(&self) -> Self::Denormalized {
        *self as f32 / 255.0
    }
}

impl Denormalize for u16 {
    type Denormalized = f32;
    fn denormalize(&self) -> Self::Denormalized {
        *self as f32 / 65535.0
    }
}

impl<T: Copy + Denormalize> Denormalize for [T; 2] {
    type Denormalized = [T::Denormalized; 2];
    fn denormalize(&self) -> Self::Denormalized {
        [
            self[0].denormalize(),
            self[1].denormalize(),
        ]
    }
}

impl<T: Copy + Denormalize> Denormalize for [T; 3] {
    type Denormalized = [T::Denormalized; 3];
    fn denormalize(&self) -> Self::Denormalized {
        [
            self[0].denormalize(),
            self[1].denormalize(),
            self[2].denormalize(),
        ]
    }
}

impl<T: Copy + Denormalize> Denormalize for [T; 4] {
    type Denormalized = [T::Denormalized; 4];
    fn denormalize(&self) -> Self::Denormalized {
        [
            self[0].denormalize(),
            self[1].denormalize(),
            self[2].denormalize(),
            self[3].denormalize(),
        ]
    }
}