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

// 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.

use std::collections::hash_map;
use std::{iter, slice};
use {accessor, extensions, json, material};

use accessor::{Accessor, DataType, Dimensions, Iter};
use Gltf;

pub use json::mesh::{Mode, Semantic};

/// XYZ vertex normals of type `[f32; 3]`.
#[derive(Debug)]
pub struct Normals(Iter<[f32; 3]>);

/// XYZ vertex normal displacements of type `[f32; 3]`.
#[derive(Debug)]
pub struct NormalDisplacements(Iter<[f32; 3]>);

/// XYZ vertex positions of type `[f32; 3]`.
#[derive(Debug)]
pub struct Positions(Iter<[f32; 3]>);

/// XYZ vertex position displacements of type `[f32; 3]`.
#[derive(Debug)]
pub struct PositionDisplacements(Iter<[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(Debug)]
pub struct Tangents(Iter<[f32; 4]>);

/// XYZ vertex tangent displacements of type `[f32; 3]`.
#[derive(Debug)]
pub struct TangentDisplacements(Iter<[f32; 3]>);

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

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

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

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

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

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

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

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

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

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

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

/// Weights,
/// Refer to the documentation on morph targets for more information.
#[derive(Debug)]
pub enum Weights {
    /// Weights of type `[f32; 4]`.
    F32(Iter<[f32; 4]>),

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

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

/// Vertex attribute data.
#[derive(Debug)]
pub enum Attribute {
    /// Vertex colors.
    Colors(u32, Colors),

    // TODO: Handle extras (needs to be handled elsewhere to avoid taking lifetime)
    // #[cfg(feature = "extras")]
    // Extras(&'a str, accessor::Accessor),

    /// Vertex joints.
    /// Refer to the documentation on morph targets and skins for more
    /// information.
    Joints(u32, Joints),

    /// XYZ vertex positions of type `[f32; 3]`.
    Positions(Positions),

    /// XYZ vertex normals of type `[f32; 3]`.
    Normals(Normals),

    /// 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.
    Tangents(Tangents),

    /// UV texture co-ordinates.
    TexCoords(u32, TexCoords),

    /// Weights.
    /// Refer to the documentation on morph targets for more information.
    Weights(u32, Weights),
}

/// Morph targets.
#[derive(Debug)]
pub struct MorphTarget {
    /// XYZ vertex position displacements.
    positions: Option<PositionDisplacements>,

    /// XYZ vertex normal displacements.
    normals: Option<NormalDisplacements>,

    /// XYZ vertex tangent displacements.
    tangents: Option<TangentDisplacements>,
}

/// A set of primitives to be rendered.  A node can contain one or more meshes and
/// its transform places the meshes in the scene.
#[derive(Clone, Debug)]
pub struct Mesh<'a>  {
    /// The parent `Gltf` struct.
    gltf: &'a Gltf,

    /// The corresponding JSON index.
    index: usize,

    /// The corresponding JSON struct.
    json: &'a json::mesh::Mesh,
}

/// Geometry to be rendered with the given material.
#[derive(Clone, Debug)]
pub struct Primitive<'a>  {
    /// The parent `Mesh` struct.
    mesh: &'a Mesh<'a>,

    /// The corresponding JSON index.
    index: usize,

    /// The corresponding JSON struct.
    json: &'a json::mesh::Primitive,
}

/// An `Iterator` that visits the attributes of a `Primitive`.
#[derive(Clone, Debug)]
pub struct Attributes<'a> {
    /// The parent `Primitive` struct.
    prim: &'a Primitive<'a>,

    /// The internal attribute iterIterator.
    iter: hash_map::Iter<'a, json::mesh::Semantic, json::Index<json::accessor::Accessor>>,
}

/// An `Iterator` that visits the primitives of a `Mesh`.
#[derive(Clone, Debug)]
pub struct Primitives<'a>  {
    /// The parent `Mesh` struct.
    mesh: &'a Mesh<'a>,

    /// The internal JSON primitive iterIterator.
    iter: iter::Enumerate<slice::Iter<'a, json::mesh::Primitive>>,
}

impl<'a> Mesh<'a>  {
    /// Constructs a `Mesh`.
    pub fn new(gltf: &'a Gltf, index: usize, json: &'a json::mesh::Mesh) -> Self {
        Self {
            gltf: gltf,
            index: index,
            json: json,
        }
    }

    /// Returns the internal JSON index.
    pub fn index(&self) -> usize {
        self.index
    }

    /// Returns the internal JSON item.
    pub fn as_json(&self) ->  &json::mesh::Mesh {
        self.json
    }

    /// Extension specific data.
    pub fn extensions(&self) -> extensions::mesh::Mesh<'a> {
        extensions::mesh::Mesh::new(
            self.gltf,
            &self.json.extensions,
        )
    }

    /// Optional application specific data.
    pub fn extras(&self) -> &json::Extras {
        &self.json.extras
    }

    /// Optional user-defined name for this object.
    #[cfg(feature = "names")]
    pub fn name(&self) -> Option<&str> {
        self.json.name.as_ref().map(String::as_str)
    }

    /// Defines the geometry to be renderered with a material.
    pub fn primitives(&'a self) -> Primitives<'a> {
        Primitives {
            mesh: self,
            iter: self.json.primitives.iter().enumerate(),
        }
    }

    /// Defines the weights to be applied to the morph targets.
    pub fn weights(&self) -> Option<&[f32]> {
        self.json.weights.as_ref().map(Vec::as_slice)
    }
}

impl Colors {
    fn from_accessor<'a>(accessor: Accessor<'a>) -> Colors {
        unsafe {
            match (accessor.dimensions(), accessor.data_type()) {
                (Dimensions::Vec3, DataType::U8) => {
                    Colors::RgbU8(accessor.iter())
                },
                (Dimensions::Vec4, DataType::U8) => {
                    Colors::RgbaU8(accessor.iter())
                },
                (Dimensions::Vec3, DataType::U16) => {
                    Colors::RgbU16(accessor.iter())
                },
                (Dimensions::Vec4, DataType::U16) => {
                    Colors::RgbaU16(accessor.iter())
                },
                (Dimensions::Vec3, DataType::F32) => {
                    Colors::RgbF32(accessor.iter())
                },
                (Dimensions::Vec4, DataType::F32) => {
                    Colors::RgbaF32(accessor.iter())
                },
                _ => unreachable!(),
            }
        }
    }
}

impl TexCoords {
    fn from_accessor<'a>(accessor: Accessor<'a>) -> TexCoords {
        unsafe {
            match accessor.data_type() {
                DataType::U8 => TexCoords::U8(accessor.iter()),
                DataType::U16 => TexCoords::U16(accessor.iter()),
                DataType::F32 => TexCoords::F32(accessor.iter()),
                _ => unreachable!(),
            }
        }
    }
}

impl Indices {
    fn from_accessor<'a>(accessor: Accessor) -> Indices {
        unsafe {
            match accessor.data_type() {
                DataType::U8 => Indices::U8(accessor.iter()),
                DataType::U16 => Indices::U16(accessor.iter()),
                DataType::U32 => Indices::U32(accessor.iter()),
                _ => unreachable!(),
            }
        }
    }
}

impl Joints {
    fn from_accessor<'a>(accessor: Accessor<'a>) -> Joints {
        unsafe {
            match accessor.data_type() {
                DataType::U8 => Joints::U8(accessor.iter()),
                DataType::U16 => Joints::U16(accessor.iter()),
                _ => unreachable!(),
            }
        }
    }
}

impl Weights {
    fn from_accessor<'a>(accessor: Accessor<'a>) -> Weights {
        unsafe {
            match accessor.data_type() {
                DataType::U8 => Weights::U8(accessor.iter()),
                DataType::U16 => Weights::U16(accessor.iter()),
                DataType::F32 => Weights::F32(accessor.iter()),
                _ => unreachable!(),
            }
        }
    }
}

impl<'a> Primitive<'a> {
    /// Constructs a `Primitive`.
    pub fn new(mesh: &'a Mesh<'a>, index: usize, json: &'a json::mesh::Primitive) -> Self {
        Self {
            mesh: mesh,
            index: index,
            json: json,
        }
    }

    /// Returns the internal JSON item.
    pub fn as_json(&self) ->  &json::mesh::Primitive {
        self.json
    }

    /// Returns the vertex colors of the given set.
    pub fn colors(&self, set: u32) -> Option<Colors> {
        self.find_accessor_with_semantic(Semantic::Colors(set))
            .map(|accessor| Colors::from_accessor(accessor))
    }

    /// Returns the vertex texture co-ordinates of the given set.
    pub fn tex_coords(&self, set: u32) -> Option<TexCoords> {
        self.find_accessor_with_semantic(Semantic::TexCoords(set))
            .map(|accessor| TexCoords::from_accessor(accessor))
    }

    /// Returns the joint indices of the given set.
    pub fn joints(&self, set: u32) -> Option<Joints> {
        self.find_accessor_with_semantic(Semantic::Joints(set))
            .map(|accessor| Joints::from_accessor(accessor))
    }
    
    /// Returns the joint weights of the given set.
    pub fn weights(&self, set: u32) -> Option<Weights> {
        self.find_accessor_with_semantic(Semantic::Weights(set))
            .map(|accessor| Weights::from_accessor(accessor))
    }

    /// Returns the primitive indices.
    pub fn indices(&self) -> Option<Indices> {
        self.json.indices.as_ref().map(|index| {
            let accessor = self.mesh.gltf.accessors().nth(index.value()).unwrap();
            Indices::from_accessor(accessor)
        })
    }
    
    /// Returns the primitive positions.
    pub fn positions(&self) -> Option<Positions> {
        self.find_accessor_with_semantic(Semantic::Positions)
            .map(|accessor| unsafe {
                Positions(accessor.iter())
            })
    }

    /// Returns the primitive normals.
    pub fn normals(&self) -> Option<Normals> {
        self.find_accessor_with_semantic(Semantic::Normals)
            .map(|accessor| unsafe {
                Normals(accessor.iter())
            })
    }

    /// Returns the primitive tangents.
    pub fn tangents(&self) -> Option<Tangents> {
        self.find_accessor_with_semantic(Semantic::Tangents)
            .map(|accessor| unsafe {
                Tangents(accessor.iter())
            })
    }

    /// Returns the attribute with the given semantic value.
    fn find_accessor_with_semantic(
        &self,
        semantic: Semantic,
    ) -> Option<accessor::Accessor<'a>> {
        self.json.attributes
            .iter()
            .find(|&(ref key, _)| key.as_ref().unwrap() == &semantic)
            .map(|(_, index)| self.mesh.gltf.accessors().nth(index.value()).unwrap())
    }

    /// Extension specific data.
    pub fn extensions(&self) -> extensions::mesh::Primitive<'a> {
        extensions::mesh::Primitive::new(
            self.mesh,
            &self.json.extensions,
        )
    }

    /// Optional application specific data.
    pub fn extras(&self) -> &json::Extras {
        &self.json.extras
    }

    /// The material to apply to this primitive when rendering
    pub fn material(&self) -> Option<material::Material<'a>> {
        self.json.material.as_ref().map(|index| {
            self.mesh.gltf.materials().nth(index.value()).unwrap()
        })
    }

    /// The type of primitives to render.
    pub fn mode(&self) -> Mode {
        self.json.mode.unwrap()
    }
}

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

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

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

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

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

impl<'a> Iterator for Primitives<'a> {
    type Item = Primitive<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|(index, json)| Primitive::new(self.mesh, index, json))
    }
}