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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
use crate::{mat::MaterialList, LoadResult};
use glam::*;
use rayon::prelude::*;
use rtbvh::{Aabb, Bounds};
use std::{fmt::{Debug, Display}, path::{Path, PathBuf}};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

pub mod gltf;
// pub mod glb;
pub mod obj;

pub trait Loader: Debug {
    fn name(&self) -> &'static str;
    fn file_extensions(&self) -> Vec<String>;
    fn load(&self, options: LoadOptions) -> LoadResult;
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LoadSource<'a> {
    /// Loads an object by reading a file from the given path.
    Path(PathBuf),
    /// Loads an object by parsing the given source. To load materials and textures, a basedir can be passed
    /// to load e.g. materials and/or textures.
    String {
        /// The source of the file.
        source: &'a [u8],
        /// Which file loader to use. Loaders for the extension must exist.
        /// Extensions must be passed without a '.', e.g. 'obj' or 'gltf'.
        extension: &'a str,
        /// The base directory to be used to load extras like textures and materials.
        basedir: &'a str,
    },
}

impl<T: AsRef<Path>> From<T> for LoadSource<'_> {
    fn from(source: T) -> Self {
        Self::Path(source.as_ref().to_path_buf())
    }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LoadOptions<'a> {
    pub source: LoadSource<'a>,
    /// Whether to load/generate normals if they are not part of the 3D file
    pub with_normals: bool,
    /// Whether to load/generate tangents if they are not part of the 3D file
    pub with_tangents: bool,
    /// Whether to load materials
    pub with_materials: bool,
}

impl<'a> Default for LoadOptions<'a> {
    fn default() -> Self {
        Self {
            source: LoadSource::Path(PathBuf::new()),
            with_normals: true,
            with_tangents: true,
            with_materials: true,
        }
    }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone)]
pub struct VertexMesh {
    pub first: u32,
    pub last: u32,
    pub mat_id: i32,
    pub bounds: Aabb,
}

impl Display for VertexMesh {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "VertexMesh {{ first: {}, last: {}, mat_id: {}, bounds: {} }}",
            self.first, self.last, self.mat_id, self.bounds
        )
    }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct SkinDescriptor {
    pub name: String,
    pub inverse_bind_matrices: Vec<[f32; 16]>,
    // Joint node descriptor IDs (NodeDescriptor::id)
    pub joint_nodes: Vec<u32>,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct AnimationDescriptor {
    pub name: String,
    // (node descriptor ID, animation channel)
    pub channels: Vec<(u32, Channel)>,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Method {
    Linear,
    Spline,
    Step,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Target {
    Translation,
    Rotation,
    Scale,
    MorphWeights,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone)]
pub struct Orthographic {
    pub x_mag: f32,
    pub y_mag: f32,
    pub z_near: f32,
    pub z_far: f32,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone)]
pub struct Perspective {
    pub aspect_ratio: Option<f32>,
    pub y_fov: f32,
    pub z_near: f32,
    pub z_far: Option<f32>,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub enum Projection {
    Orthographic(Orthographic),
    Perspective(Perspective),
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct CameraDescriptor {
    projection: Projection,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct NodeDescriptor {
    pub name: String,
    pub child_nodes: Vec<NodeDescriptor>,
    pub camera: Option<CameraDescriptor>,

    pub translation: [f32; 3],
    pub rotation: [f32; 4],
    pub scale: [f32; 3],

    pub meshes: Vec<u32>,
    pub skin: Option<SkinDescriptor>,
    pub weights: Vec<f32>,

    /// An ID that is guaranteed to be unique within the scene descriptor this
    /// node descriptor belongs to.
    pub id: u32,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct Channel {
    pub targets: Vec<Target>,
    pub key_frames: Vec<f32>,

    pub sampler: Method,
    pub vec3s: Vec<[f32; 3]>,
    /// xyzw quaternion rotations
    pub rotations: Vec<[f32; 4]>,
    pub weights: Vec<f32>,

    pub duration: f32,
}

impl Default for Channel {
    fn default() -> Self {
        Self {
            targets: Vec::new(),
            key_frames: Vec::new(),

            sampler: Method::Linear,
            vec3s: Vec::new(),
            rotations: Vec::new(),
            weights: Vec::new(),

            duration: 0.0,
        }
    }
}

impl Channel {
    pub fn sample_translation(&self, time: f32, k: usize) -> [f32; 3] {
        let t0 = self.key_frames[k];
        let t1 = self.key_frames[k + 1];
        let f = (time - t0) / (t1 - t0);

        match self.sampler {
            Method::Linear => {
                ((1.0 - f) * Vec3::from(self.vec3s[k]) + f * Vec3::from(self.vec3s[k + 1])).into()
            }
            Method::Spline => {
                let t = f;
                let t2 = t * t;
                let t3 = t2 * t;
                let dt = t1 - t0;
                let p0 = Vec3::from(self.vec3s[k * 3 + 1]);
                let m0 = dt * Vec3::from(self.vec3s[k * 3 + 2]);
                let p1 = Vec3::from(self.vec3s[(k + 1) * 3 + 1]);
                let m1 = dt * Vec3::from(self.vec3s[(k + 1) * 3]);

                let result: Vec3 = m0 * (t3 - 2.0 * t2 + t)
                    + p0 * (2.0 * t3 - 3.0 * t2 + 1.0)
                    + p1 * (-2.0 * t3 + 3.0 * t2)
                    + m1 * (t3 - t2);
                result.into()
            }
            Method::Step => self.vec3s[k],
        }
    }

    pub fn sample_scale(&self, time: f32, k: usize) -> [f32; 3] {
        let t0 = self.key_frames[k];
        let t1 = self.key_frames[k + 1];
        let f = (time - t0) / (t1 - t0);

        match self.sampler {
            Method::Linear => {
                ((1.0 - f) * Vec3::from(self.vec3s[k]) + f * Vec3::from(self.vec3s[k + 1])).into()
            }
            Method::Spline => {
                let t = f;
                let t2 = t * t;
                let t3 = t2 * t;
                let dt = t1 - t0;
                let p0 = Vec3::from(self.vec3s[k * 3 + 1]);
                let m0 = dt * Vec3::from(self.vec3s[k * 3 + 2]);
                let p1 = Vec3::from(self.vec3s[(k + 1) * 3 + 1]);
                let m1 = dt * Vec3::from(self.vec3s[(k + 1) * 3]);
                let result = m0 * (t3 - 2.0 * t2 + t)
                    + p0 * (2.0 * t3 - 3.0 * t2 + 1.0)
                    + p1 * (-2.0 * t3 + 3.0 * t2)
                    + m1 * (t3 - t2);
                result.into()
            }
            Method::Step => self.vec3s[k],
        }
    }

    pub fn sample_weight(&self, time: f32, k: usize, i: usize, count: usize) -> f32 {
        let t0 = self.key_frames[k];
        let t1 = self.key_frames[k + 1];
        let f = (time - t0) / (t1 - t0);

        match self.sampler {
            Method::Linear => {
                (1.0 - f) * self.weights[k * count + i] + f * self.weights[(k + 1) * count + i]
            }
            Method::Spline => {
                let t = f;
                let t2 = t * t;
                let t3 = t2 * t;
                let p0 = self.weights[(k * count + i) * 3 + 1];
                let m0 = (t1 - t0) * self.weights[(k * count + i) * 3 + 2];
                let p1 = self.weights[((k + 1) * count + i) * 3 + 1];
                let m1 = (t1 - t0) * self.weights[((k + 1) * count + i) * 3];
                m0 * (t3 - 2.0 * t2 + t)
                    + p0 * (2.0 * t3 - 3.0 * t2 + 1.0)
                    + p1 * (-2.0 * t3 + 3.0 * t2)
                    + m1 * (t3 - t2)
            }
            Method::Step => self.weights[k],
        }
    }

    pub fn sample_rotation(&self, time: f32, k: usize) -> [f32; 4] {
        let t0 = self.key_frames[k];
        let t1 = self.key_frames[k + 1];
        let f = (time - t0) / (t1 - t0);

        match self.sampler {
            Method::Linear => ((Vec4::from(self.rotations[k]) * (1.0 - f))
                + (Vec4::from(self.rotations[k + 1]) * f))
                .into(),
            Method::Spline => {
                let t = f;
                let t2 = t * t;
                let t3 = t2 * t;
                let dt = t1 - t0;

                let p0 = Vec4::from(self.rotations[k * 3 + 1]);
                let m0 = Vec4::from(self.rotations[k * 3 + 2]) * dt;
                let p1 = Vec4::from(self.rotations[(k + 1) * 3 + 1]);
                let m1 = Vec4::from(self.rotations[(k + 1) * 3]) * dt;
                let result = m0 * (t3 - 2.0 * t2 + t)
                    + p0 * (2.0 * t3 - 3.0 * t2 + 1.0)
                    + p1 * (-2.0 * t3 + 3.0 * t2)
                    + m1 * (t3 - t2);
                result.into()
            }
            Method::Step => self.rotations[k],
        }
    }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct Animation {
    pub name: String,
    pub affected_roots: Vec<u32>,
    pub channels: Vec<(u32, Channel)>, // Vec<(node id, channel)>
}

impl Default for Animation {
    fn default() -> Self {
        Self {
            name: String::new(),
            affected_roots: Vec::new(),
            channels: Vec::new(),
        }
    }
}

pub trait AnimationNode {
    fn set_translation(&mut self, translation: [f32; 3]);
    fn set_rotation(&mut self, rotation: [f32; 4]);
    fn set_scale(&mut self, scale: [f32; 3]);
    fn set_weights(&mut self, weights: &[f32]);
    fn update_matrix(&mut self);
}

impl Animation {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn set_time<T: AnimationNode>(&mut self, time: f32, nodes: &mut [T]) {
        let channels = &mut self.channels;

        channels.iter_mut().for_each(|(node_id, c)| {
            let current_time = time % c.duration;
            let node_id = *node_id as usize;
            c.targets.iter().for_each(|t| {
                let mut key = 0;
                while current_time > c.key_frames[key as usize + 1] {
                    key += 1;
                }

                if let Some(node) = nodes.get_mut(node_id) {
                    match t {
                        Target::Translation => {
                            node.set_translation(c.sample_translation(current_time, key));
                        }
                        Target::Rotation => {
                            node.set_rotation(c.sample_rotation(current_time, key));
                        }
                        Target::Scale => {
                            node.set_scale(c.sample_scale(current_time, key));
                        }
                        Target::MorphWeights => {
                            let num_weights = c.weights.len();
                            let mw = (0..num_weights)
                                .into_iter()
                                .map(|i| c.sample_weight(current_time, key, i, num_weights))
                                .collect::<Vec<f32>>();

                            node.set_weights(mw.as_slice());
                        }
                    }
                }
            });

            if let Some(node) = nodes.get_mut(node_id) {
                node.update_matrix();
            }
        });
    }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct SceneDescriptor {
    pub materials: MaterialList,
    pub meshes: Vec<MeshDescriptor>,
    pub nodes: Vec<NodeDescriptor>,
    pub animations: Vec<AnimationDescriptor>,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct SkeletonDescriptor {
    pub joints: Vec<Vec<[u16; 4]>>,
    pub weights: Vec<Vec<[f32; 4]>>,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct MeshDescriptor {
    pub vertices: Vec<[f32; 4]>,
    pub normals: Vec<[f32; 3]>,
    pub uvs: Vec<[f32; 2]>,
    pub tangents: Vec<[f32; 4]>,
    pub material_ids: Vec<i32>,
    /// Mesh descriptors do not have a material list when they are part of a scene
    pub materials: Option<MaterialList>,
    pub meshes: Vec<VertexMesh>,
    pub skeleton: Option<SkeletonDescriptor>,
    pub bounds: Aabb,
    pub name: String,
}

impl Display for MeshDescriptor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Mesh {{ vertices: {}, materials: {}, meshes: {}, bounds: {}, name: {} }}",
            self.vertices.len(),
            if let Some(m) = self.materials.as_ref() {
                m.len()
            } else {
                0
            },
            self.meshes.len(),
            self.bounds,
            self.name.as_str()
        )
    }
}

impl Default for MeshDescriptor {
    fn default() -> Self {
        MeshDescriptor::empty()
    }
}

impl MeshDescriptor {
    #[allow(clippy::too_many_arguments)]
    pub fn new_indexed(
        indices: Vec<[u32; 3]>,
        original_vertices: Vec<[f32; 4]>,
        original_normals: Vec<[f32; 3]>,
        original_uvs: Vec<[f32; 2]>,
        skeleton: Option<SkeletonDescriptor>,
        material_ids: Vec<i32>,
        materials: Option<MaterialList>,
        name: Option<String>,
    ) -> Self {
        let mut vertices: Vec<[f32; 4]> = Vec::with_capacity(indices.len() * 3);
        let mut normals: Vec<[f32; 3]> = Vec::with_capacity(indices.len() * 3);
        let mut uvs: Vec<[f32; 2]> = Vec::with_capacity(indices.len() * 3);
        let mut material_indices: Vec<i32> = Vec::with_capacity(indices.len() * 3);

        let (mut joints, org_joints, mut weights, org_weights) = if let Some(skeleton) = skeleton {
            let mut joints = Vec::with_capacity(skeleton.joints.len());
            let mut weights = Vec::with_capacity(skeleton.weights.len());

            for j in skeleton.joints.iter() {
                joints.push(Vec::with_capacity(j.len()));
            }
            for w in skeleton.weights.iter() {
                weights.push(Vec::with_capacity(w.len()));
            }

            (joints, skeleton.joints, weights, skeleton.weights)
        } else {
            (Vec::new(), Vec::new(), Vec::new(), Vec::new())
        };

        indices.into_iter().enumerate().for_each(|(j, i)| {
            let i0 = i[0] as usize;
            let i1 = i[1] as usize;
            let i2 = i[2] as usize;

            vertices.push([
                original_vertices[i0][0],
                original_vertices[i0][1],
                original_vertices[i0][2],
                1.0,
            ]);
            vertices.push([
                original_vertices[i1][0],
                original_vertices[i1][1],
                original_vertices[i1][2],
                1.0,
            ]);
            vertices.push([
                original_vertices[i2][0],
                original_vertices[i2][1],
                original_vertices[i2][2],
                1.0,
            ]);

            normals.push([
                original_normals[i0][0],
                original_normals[i0][1],
                original_normals[i0][2],
            ]);
            normals.push([
                original_normals[i1][0],
                original_normals[i1][1],
                original_normals[i1][2],
            ]);
            normals.push([
                original_normals[i2][0],
                original_normals[i2][1],
                original_normals[i2][2],
            ]);

            uvs.push([original_uvs[i0][0], original_uvs[i0][1]]);
            uvs.push([original_uvs[i1][0], original_uvs[i1][1]]);
            uvs.push([original_uvs[i2][0], original_uvs[i2][1]]);

            joints.iter_mut().enumerate().for_each(|(i, v)| {
                v.push(org_joints[i][i0]);
                v.push(org_joints[i][i1]);
                v.push(org_joints[i][i2]);
            });

            weights.iter_mut().enumerate().for_each(|(i, v)| {
                v.push(org_weights[i][i0]);
                v.push(org_weights[i][i1]);
                v.push(org_weights[i][i2]);
            });

            material_indices.push(material_ids[j]);
            material_indices.push(material_ids[j + 1]);
            material_indices.push(material_ids[j + 2]);
        });

        let skeleton = if !joints.is_empty() && !weights.is_empty() {
            Some(SkeletonDescriptor { joints, weights })
        } else {
            None
        };

        debug_assert_eq!(vertices.len(), normals.len());
        debug_assert_eq!(vertices.len(), uvs.len());
        debug_assert_eq!(uvs.len(), material_ids.len());
        debug_assert_eq!(vertices.len() % 3, 0);

        Self::new(
            vertices,
            normals,
            uvs,
            skeleton,
            material_indices,
            materials,
            name,
        )
    }

    pub fn new(
        vertices: Vec<[f32; 4]>,
        normals: Vec<[f32; 3]>,
        uvs: Vec<[f32; 2]>,
        skeleton: Option<SkeletonDescriptor>,
        material_ids: Vec<i32>,
        materials: Option<MaterialList>,
        name: Option<String>,
    ) -> Self {
        debug_assert_eq!(vertices.len(), normals.len());
        debug_assert_eq!(vertices.len(), uvs.len());
        debug_assert_eq!(uvs.len(), material_ids.len());
        debug_assert_eq!(vertices.len() % 3, 0);

        let mut bounds = Aabb::new();

        // Generate normals
        let normals: Vec<[f32; 3]> = if Vec3::from(normals[0]).cmpeq(Vec3::ZERO).all() {
            let mut normals = vec![[0.0_f32; 3]; vertices.len()];
            for i in (0..vertices.len()).step_by(3) {
                let v0 = Vec3::new(vertices[i][0], vertices[i][1], vertices[i][2]);
                let v1 = Vec3::new(vertices[i + 1][0], vertices[i + 1][1], vertices[i + 1][2]);
                let v2 = Vec3::new(vertices[i + 2][0], vertices[i + 2][1], vertices[i + 2][2]);

                let e1: Vec3 = v1 - v0;
                let e2: Vec3 = v2 - v0;

                let normal = e1.cross(e2).normalize();

                let a = (v1 - v0).length();
                let b = (v2 - v1).length();
                let c = (v0 - v2).length();
                let s = (a + b + c) * 0.5;
                let area = (s * (s - a) * (s - b) * (s - c)).sqrt();
                let normal: Vec3 = normal * area;

                for j in 0..3 {
                    normals[i][j] += normal[j];
                    normals[i + 1][j] += normal[j];
                    normals[i + 2][j] += normal[j];
                }
            }

            normals
                .par_iter_mut()
                .for_each(|n| *n = Vec3::from(*n).normalize().into());
            normals
        } else {
            normals
        };

        // Generate tangents
        let mut tangents: Vec<[f32; 4]> = vec![[0.0_f32; 4]; vertices.len()];
        let mut bitangents: Vec<[f32; 3]> = vec![[0.0_f32; 3]; vertices.len()];

        for i in (0..vertices.len()).step_by(3) {
            let v0: Vec3 = Vec3::new(vertices[i][0], vertices[i][1], vertices[i][2]);
            let v1: Vec3 = Vec3::new(vertices[i + 1][0], vertices[i + 1][1], vertices[i + 1][2]);
            let v2: Vec3 = Vec3::new(vertices[i + 2][0], vertices[i + 2][1], vertices[i + 2][2]);

            bounds.grow(v0);
            bounds.grow(v1);
            bounds.grow(v2);

            let e1: Vec3 = v1 - v0;
            let e2: Vec3 = v2 - v0;

            let tex0: Vec2 = Vec2::from(uvs[i]);
            let tex1: Vec2 = Vec2::from(uvs[i + 1]);
            let tex2: Vec2 = Vec2::from(uvs[i + 2]);

            let uv1: Vec2 = tex1 - tex0;
            let uv2: Vec2 = tex2 - tex0;

            let n = e1.cross(e2).normalize();

            let (t, b) = if uv1.dot(uv1) == 0.0 || uv2.dot(uv2) == 0.0 {
                let tangent: Vec3 = e1.normalize();
                let bitangent: Vec3 = n.cross(tangent).normalize();
                (tangent.extend(0.0), bitangent)
            } else {
                let r = 1.0 / (uv1.x * uv2.y - uv1.y * uv2.x);
                let tangent: Vec3 = (e1 * uv2.y - e2 * uv1.y) * r;
                let bitangent: Vec3 = (e1 * uv2.x - e2 * uv1.x) * r;
                (tangent.extend(0.0), bitangent)
            };

            for i in 0..3 {
                tangents[i][i] += t[i];
                tangents[i + 1][i] += t[i];
                tangents[i + 2][i] += t[i];

                bitangents[i][i] += b[i];
                bitangents[i + 1][i] += b[i];
                bitangents[i + 2][i] += b[i];
            }
        }

        let bounds = bounds;

        for i in 0..vertices.len() {
            let n: Vec3 = Vec3::from(normals[i]);
            let tangent = Vec4::from(tangents[i]).truncate().normalize();
            let bitangent = Vec3::from(bitangents[i]).normalize();

            let t: Vec3 = (tangent - (n * n.dot(tangent))).normalize();
            let c: Vec3 = n.cross(t);

            let w = c.dot(bitangent).signum();
            let t = tangent.normalize().extend(w);
            for j in 0..4 {
                tangents[i][j] = t[j];
            }
        }

        let mut last_id = material_ids[0];
        let mut start = 0;
        let mut range = 0;
        let mut meshes: Vec<VertexMesh> = Vec::new();
        let mut v_bounds = Aabb::new();

        for i in 0..material_ids.len() {
            range += 1;
            v_bounds.grow(vec3(vertices[i][0], vertices[i][1], vertices[i][2]));

            if last_id != material_ids[i] {
                meshes.push(VertexMesh {
                    first: start,
                    last: (start + range),
                    mat_id: last_id as i32,
                    bounds: v_bounds,
                });

                v_bounds = Aabb::new();
                last_id = material_ids[i];
                start = i as u32;
                range = 1;
            }
        }

        if meshes.is_empty() {
            // There only is 1 mesh available
            meshes.push(VertexMesh {
                first: 0,
                last: vertices.len() as u32,
                mat_id: material_ids[0] as i32,
                bounds,
            });
        } else if (start + range) != (material_ids.len() as u32 - 1) {
            // Add last mesh to list
            meshes.push(VertexMesh {
                first: start,
                last: (start + range),
                mat_id: last_id as i32,
                bounds: v_bounds,
            })
        }

        Self {
            vertices,
            normals,
            uvs,
            tangents,
            material_ids,
            materials,
            meshes,
            skeleton,
            bounds,
            name: name.unwrap_or_default(),
        }
    }

    pub fn scale(&self, scaling: f32) -> Self {
        let mut new_self = self.clone();

        let scaling = Mat4::from_scale(Vec3::splat(scaling));
        new_self.vertices.par_iter_mut().for_each(|t| {
            let mut v = Vec4::from(*t);
            v[3] = 1.0;
            let v = scaling * v;
            *t = [v.x, v.y, v.z, 1.0];
        });

        new_self
    }

    pub fn len(&self) -> usize {
        self.vertices.len()
    }

    pub fn is_empty(&self) -> bool {
        self.vertices.is_empty()
    }

    pub fn empty() -> Self {
        Self {
            vertices: Vec::new(),
            normals: Vec::new(),
            uvs: Vec::new(),
            tangents: Vec::new(),
            material_ids: Vec::new(),
            materials: None,
            meshes: Vec::new(),
            skeleton: None,
            bounds: Aabb::new(),
            name: String::new(),
        }
    }

    /// Number of bytes required to store vertices, normals, uvs and tangents
    pub fn buffer_size(&self) -> usize {
        let f32_size = std::mem::size_of::<f32>();
        self.vertices.len() * 4
            + self.normals.len() * 3
            + self.uvs.len() * 2
            + self.tangents.len() * 4 * f32_size
    }

    pub fn as_bytes(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(self.vertices.as_ptr() as *const u8, self.buffer_size())
        }
    }
}

impl Bounds for MeshDescriptor {
    fn bounds(&self) -> Aabb {
        self.bounds
    }
}