metaverse_mesh 0.2.1

mesh handling for the open metaverse
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
use benthic_protocol::render_data::{AvatarObject, JointWeight, RenderObject};
use benthic_protocol::skeleton::JointName;
use glam::{Quat, Vec3, usize};
use gltf_json::animation::{Channel, Interpolation, Property, Sampler, Target as ChannelTarget};
use gltf_json::{
    Accessor, Index, Material, Mesh, Node, Scene, Skin, Value,
    accessor::{ComponentType, GenericComponentType},
    buffer::{Stride, Target, View},
    image::MimeType,
    material::{PbrMetallicRoughness, StrengthFactor},
    mesh::{Mode, Primitive, Semantic},
    scene::UnitQuaternion,
    texture,
    validation::{
        Checked::{self, Valid},
        USize64,
    },
};
use rgb::bytemuck;
use std::f32::consts::FRAC_PI_2;
use std::{
    borrow::Cow,
    collections::{BTreeSet, HashMap},
    fs::{self, File},
    path::PathBuf,
    vec,
};

use crate::errors::MetaverseMeshError;

struct GltfBuilder {
    root: gltf_json::Root,
    buffer_index: gltf_json::Index<gltf_json::Buffer>,
    combined_buffer: Vec<u8>,
    nodes: Vec<Index<Node>>,
}

impl GltfBuilder {
    // create a new GLTFBuilder, initialized to default values.
    fn new(buffer_name: &str) -> Self {
        let mut root = gltf_json::Root::default();
        let buffer_index = root.push(gltf_json::Buffer {
            byte_length: gltf_json::validation::USize64::from(0_usize),
            name: Some(buffer_name.to_string()),
            uri: None,
            extensions: Default::default(),
            extras: Default::default(),
        });
        Self {
            root,
            buffer_index,
            combined_buffer: Vec::new(),
            nodes: Vec::new(),
        }
    }

    // GLTFs expect every buffer to be aligned to 4. For some values that are not aligned to 4, this
    // function adds 0 to the end of the buffer which is not used and never read.
    fn align_4(&mut self) {
        while !self.combined_buffer.len().is_multiple_of(4) {
            self.combined_buffer.push(0);
        }
    }

    fn push_view(
        &mut self,
        byte_length: usize,
        byte_stride: Option<usize>,
        target: Option<gltf_json::validation::Checked<gltf_json::buffer::Target>>,
        name: String,
    ) -> gltf_json::Index<gltf_json::buffer::View> {
        let offset = self.combined_buffer.len();
        self.root.push(View {
            buffer: self.buffer_index,
            byte_length: USize64::from(byte_length),
            byte_offset: Some(USize64::from(offset)),
            byte_stride: byte_stride.map(Stride),
            target,
            extensions: Default::default(),
            extras: Default::default(),
            name: Some(name.to_string()),
        })
    }

    fn add_vertex_positions(&mut self, vertices: &[Vec3]) -> gltf_json::Index<gltf_json::Accessor> {
        let (min, max) = bounding_coords(vertices);
        let vertex_bytes = to_padded_byte_vector(vertices);
        self.align_4();

        let view = self.push_view(
            vertex_bytes.len(),
            Some(std::mem::size_of::<Vec3>()),
            Some(Valid(Target::ArrayBuffer)),
            "vertex_positions".to_string(),
        );
        self.combined_buffer.extend_from_slice(&vertex_bytes);

        self.root.push(gltf_json::Accessor {
            buffer_view: Some(view),
            byte_offset: Some(USize64(0)),
            count: USize64::from(vertices.len()),
            component_type: Valid(GenericComponentType(ComponentType::F32)),
            type_: Valid(gltf_json::accessor::Type::Vec3),
            min: Some(Value::from(Vec::from(min))),
            max: Some(Value::from(Vec::from(max))),
            normalized: false,
            sparse: None,
            name: Some("POSITION".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        })
    }

    fn add_indices(&mut self, indices: &[u16]) -> gltf_json::Index<gltf_json::Accessor> {
        let mut bytes = Vec::with_capacity(indices.len() * 2);
        for index in indices {
            bytes.extend_from_slice(&index.to_le_bytes());
        }
        self.align_4();

        let view = self.push_view(
            bytes.len(),
            None,
            Some(Valid(Target::ElementArrayBuffer)),
            "indices".to_string(),
        );
        self.combined_buffer.extend_from_slice(&bytes);

        self.root.push(gltf_json::Accessor {
            buffer_view: Some(view),
            byte_offset: Some(USize64(0)),
            count: USize64::from(indices.len()),
            component_type: Valid(GenericComponentType(ComponentType::U16)),
            type_: Valid(gltf_json::accessor::Type::Scalar),
            normalized: false,
            sparse: None,
            name: Some("INDICES".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
            min: None,
            max: None,
        })
    }

    // This generates a single animation frame of the bind pose and applies it to the skeleton.
    // This allows some engines to register that this model should be animated.
    pub fn add_bind_pose_animation(
        &mut self,
        avatar: &AvatarObject,
        bones: &BTreeSet<JointName>,
        joint_to_node: &HashMap<JointName, Index<Node>>,
        effective_parents: &HashMap<JointName, Option<JointName>>,
    ) {
        use gltf_json::*;

        let mut input_bytes = Vec::new();
        input_bytes.extend_from_slice(&0.0f32.to_le_bytes());

        self.align_4();
        let input_offset = self.combined_buffer.len();
        self.combined_buffer.extend_from_slice(&input_bytes);

        let input_view = self.root.push(View {
            buffer: self.buffer_index,
            byte_length: input_bytes.len().into(),
            byte_offset: Some(USize64(input_offset as u64)),
            byte_stride: None,
            target: None,
            name: Some("animation_input".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        });

        let input_accessor = self.root.push(Accessor {
            buffer_view: Some(input_view),
            byte_offset: Some(USize64(0)),
            count: USize64(1),
            component_type: Checked::Valid(GenericComponentType(ComponentType::F32)),
            type_: Checked::Valid(accessor::Type::Scalar),
            normalized: false,
            min: Some(Value::from(vec![0.0])),
            max: Some(Value::from(vec![0.0])),
            sparse: None,
            name: Some("time_0".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        });

        let mut channels = Vec::new();
        let mut samplers = Vec::new();

        for joint_name in bones {
            let node_index = joint_to_node[joint_name];
            let joint = &avatar.global_skeleton.joints[joint_name];

            let global_transform = joint.global_transforms.last().unwrap().transform;

            let local_transform = match effective_parents[joint_name] {
                Some(parent_name) => {
                    let parent_global = avatar
                        .global_skeleton
                        .joints
                        .get(&parent_name)
                        .unwrap()
                        .global_transforms
                        .last()
                        .unwrap()
                        .transform;

                    parent_global.inverse() * global_transform
                }
                None => global_transform,
            };

            let (scale, rotation, translation) = local_transform.to_scale_rotation_translation();

            let push_accessor_vec3 =
                |builder: &mut GltfBuilder, vec: Vec3, name: &str| -> Index<Accessor> {
                    let bytes: Vec<u8> = bytemuck::cast_slice(&[[vec.x, vec.y, vec.z]]).to_vec();

                    builder.align_4();
                    let offset = builder.combined_buffer.len();
                    builder.combined_buffer.extend_from_slice(&bytes);

                    let view = builder.root.push(View {
                        buffer: builder.buffer_index,
                        byte_length: bytes.len().into(),
                        byte_offset: Some(USize64(offset as u64)),
                        byte_stride: None,
                        target: None,
                        name: Some(name.to_string()),
                        extensions: Default::default(),
                        extras: Default::default(),
                    });

                    builder.root.push(Accessor {
                        buffer_view: Some(view),
                        byte_offset: Some(USize64(0)),
                        count: USize64(1),
                        component_type: Checked::Valid(GenericComponentType(ComponentType::F32)),
                        type_: Checked::Valid(accessor::Type::Vec3),
                        normalized: false,
                        min: Some(Value::from([vec.x, vec.y, vec.z])),
                        max: Some(Value::from([vec.x, vec.y, vec.z])),
                        sparse: None,
                        name: Some(name.to_string()),
                        extensions: Default::default(),
                        extras: Default::default(),
                    })
                };

            let push_accessor_quat =
                |builder: &mut GltfBuilder, q: Quat, name: &str| -> Index<Accessor> {
                    let bytes: Vec<u8> = bytemuck::cast_slice(&[[q.x, q.y, q.z, q.w]]).to_vec();

                    builder.align_4();
                    let offset = builder.combined_buffer.len();
                    builder.combined_buffer.extend_from_slice(&bytes);

                    let view = builder.root.push(View {
                        buffer: builder.buffer_index,
                        byte_length: bytes.len().into(),
                        byte_offset: Some(USize64(offset as u64)),
                        byte_stride: None,
                        target: None,
                        name: Some(name.to_string()),
                        extensions: Default::default(),
                        extras: Default::default(),
                    });

                    builder.root.push(Accessor {
                        buffer_view: Some(view),
                        byte_offset: Some(USize64(0)),
                        count: USize64(1),
                        component_type: Checked::Valid(GenericComponentType(ComponentType::F32)),
                        type_: Checked::Valid(accessor::Type::Vec4),
                        normalized: false,
                        min: Some(Value::from([q.x, q.y, q.z, q.w])),
                        max: Some(Value::from([q.x, q.y, q.z, q.w])),
                        sparse: None,
                        name: Some(name.to_string()),
                        extensions: Default::default(),
                        extras: Default::default(),
                    })
                };

            let t_acc = push_accessor_vec3(self, translation, &format!("{}_T", joint_name));
            let r_acc = push_accessor_quat(self, rotation, &format!("{}_R", joint_name));
            let s_acc = push_accessor_vec3(self, scale, &format!("{}_S", joint_name));

            for (path_str, acc) in &[
                ("translation", t_acc),
                ("rotation", r_acc),
                ("scale", s_acc),
            ] {
                let sampler_index = samplers.len();

                samplers.push(Sampler {
                    input: input_accessor,
                    interpolation: Valid(Interpolation::Step),
                    output: *acc,
                    extensions: Default::default(),
                    extras: Default::default(),
                });

                channels.push(Channel {
                    sampler: Index::new(sampler_index as u32),
                    target: ChannelTarget {
                        node: node_index,
                        path: match *path_str {
                            "translation" => Valid(Property::Translation),
                            "rotation" => Valid(Property::Rotation),
                            "scale" => Valid(Property::Scale),
                            _ => panic!("invalid path"),
                        },
                        extensions: Default::default(),
                        extras: Default::default(),
                    },
                    extensions: Default::default(),
                    extras: Default::default(),
                });
            }
        }

        self.root.push(Animation {
            name: Some("BindPose".to_string()),
            channels,
            samplers,
            extensions: Default::default(),
            extras: Default::default(),
        });
    }
    fn add_joint_data(
        &mut self,
        skin_weights: Vec<JointWeight>,
        bones: &BTreeSet<JointName>,
    ) -> (Option<Index<Accessor>>, Option<Index<Accessor>>) {
        if skin_weights.is_empty() {
            return (None, None);
        }

        let bone_index: HashMap<JointName, u8> = bones
            .iter()
            .enumerate()
            .map(|(i, j)| (*j, i as u8))
            .collect();

        let mut joint_indices_bytes = Vec::new();
        let mut joint_weights_bytes = Vec::new();

        for vw in &skin_weights {
            let mut joints = [0u8; 4];
            let mut weights = [0.0f32; 4];

            for i in 0..4 {
                if let (Some(joint_name), Some(&weight)) = (vw.joint_name.get(i), vw.weights.get(i))
                    && weight > 0.0
                    && let Some(&idx) = bone_index.get(joint_name)
                {
                    joints[i] = idx;
                    weights[i] = weight;
                }
            }

            let sum: f32 = weights.iter().sum();
            if sum > 0.0 {
                for w in &mut weights {
                    *w /= sum;
                }
            }

            joint_indices_bytes.extend_from_slice(&joints);
            for w in &weights {
                joint_weights_bytes.extend_from_slice(&w.to_le_bytes());
            }
        }

        self.align_4();
        let indices_offset = self.combined_buffer.len();
        self.combined_buffer.extend_from_slice(&joint_indices_bytes);

        let indices_view = self.root.push(View {
            buffer: self.buffer_index,
            byte_length: USize64::from(joint_indices_bytes.len()),
            byte_offset: Some(USize64::from(indices_offset)),
            byte_stride: Some(Stride(4)),
            target: Some(Checked::Valid(Target::ArrayBuffer)),
            extensions: None,
            extras: Default::default(),
            name: Some("joint_indices".into()),
        });

        let indices_accessor = self.root.push(Accessor {
            buffer_view: Some(indices_view),
            byte_offset: Some(USize64(0)),
            count: USize64::from(skin_weights.len()),
            component_type: Checked::Valid(GenericComponentType(ComponentType::U8)),
            type_: Checked::Valid(gltf_json::accessor::Type::Vec4),
            normalized: false,
            sparse: None,
            extensions: None,
            extras: Default::default(),
            name: Some("JOINTS_0".into()),
            min: None,
            max: None,
        });

        self.align_4();
        let weights_offset = self.combined_buffer.len();
        self.combined_buffer.extend_from_slice(&joint_weights_bytes);

        let weights_view = self.root.push(View {
            buffer: self.buffer_index,
            byte_length: USize64::from(joint_weights_bytes.len()),
            byte_offset: Some(USize64::from(weights_offset)),
            byte_stride: Some(Stride(16)),
            target: Some(Checked::Valid(Target::ArrayBuffer)),
            extensions: None,
            extras: Default::default(),
            name: Some("joint_weights".into()),
        });

        let weights_accessor = self.root.push(Accessor {
            buffer_view: Some(weights_view),
            byte_offset: Some(USize64(0)),
            count: USize64::from(skin_weights.len()),
            component_type: Checked::Valid(GenericComponentType(ComponentType::F32)),
            type_: Checked::Valid(gltf_json::accessor::Type::Vec4),
            normalized: false,
            sparse: None,
            extensions: None,
            extras: Default::default(),
            name: Some("WEIGHTS_0".into()),
            min: None,
            max: None,
        });

        (Some(indices_accessor), Some(weights_accessor))
    }

    pub fn add_inverse_bind_matrices(&mut self, ibm_matrices: &[[f32; 16]]) -> Index<Accessor> {
        let offset = self.combined_buffer.len();
        for mat in ibm_matrices {
            for f in mat.iter() {
                self.combined_buffer.extend_from_slice(&f.to_le_bytes());
            }
        }

        let view = self.root.push(View {
            buffer: self.buffer_index,
            byte_length: USize64::from(ibm_matrices.len() * 16 * std::mem::size_of::<f32>()),
            byte_offset: Some(USize64::from(offset)),
            byte_stride: None,
            target: None,
            name: Some("inverse_bind_matrices_view".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        });

        self.root.push(Accessor {
            buffer_view: Some(view),
            byte_offset: Some(USize64(0)),
            count: USize64::from(ibm_matrices.len()),
            component_type: Checked::Valid(GenericComponentType(ComponentType::F32)),
            type_: Checked::Valid(gltf_json::accessor::Type::Mat4),
            normalized: false,
            sparse: None,
            extensions: None,
            extras: Default::default(),
            name: Some("inverse_bind_matrices_accessor".to_string()),
            min: None,
            max: None,
        })
    }

    pub fn add_mesh(
        &mut self,
        name: &str,
        positions: &[Vec3],
        indices: &[u16],
        uvs: Option<&[[f32; 2]]>,
        material: Option<Index<Material>>,
        joint_indices: Option<Index<Accessor>>,
        joint_weights: Option<Index<Accessor>>,
    ) -> gltf_json::Index<gltf_json::Mesh> {
        let pos_accessor = self.add_vertex_positions(positions);
        let index_accessor = self.add_indices(indices);

        let mut attributes: std::collections::BTreeMap<_, _> =
            [(Valid(Semantic::Positions), pos_accessor)]
                .into_iter()
                .collect();

        if let Some(uvs) = uvs {
            let uv_accessor = self.add_uvs(uvs);
            attributes.insert(Valid(Semantic::TexCoords(0)), uv_accessor);
        }

        if let Some(joints) = joint_indices {
            attributes.insert(Valid(Semantic::Joints(0)), joints);
        }
        if let Some(weights) = joint_weights {
            attributes.insert(Valid(Semantic::Weights(0)), weights);
        }

        let primitive = Primitive {
            attributes,
            indices: Some(index_accessor),
            material,
            mode: Valid(Mode::Triangles),
            targets: None,
            extensions: Default::default(),
            extras: Default::default(),
        };

        self.root.push(Mesh {
            primitives: vec![primitive],
            weights: None,
            extensions: Default::default(),
            extras: Default::default(),
            name: Some(name.to_string()),
        })
    }

    pub fn add_node_with_mesh(
        &mut self,
        mesh_index: gltf_json::Index<gltf_json::Mesh>,
        name: &str,
    ) -> Index<Node> {
        let node_index = self.root.push(Node {
            mesh: Some(mesh_index),
            name: Some(name.to_string()),
            ..Default::default()
        });
        self.nodes.push(node_index);
        node_index
    }
    pub fn add_uvs(&mut self, uvs: &[[f32; 2]]) -> Index<Accessor> {
        let bytes: Vec<u8> = bytemuck::cast_slice(uvs).to_vec();
        self.align_4();

        let view = self.push_view(
            bytes.len(),
            Some(std::mem::size_of::<[f32; 2]>()),
            Some(Checked::Valid(Target::ArrayBuffer)),
            "uvs".to_string(),
        );
        self.combined_buffer.extend_from_slice(&bytes);

        self.root.push(gltf_json::Accessor {
            buffer_view: Some(view),
            byte_offset: Some(USize64(0)),
            count: USize64::from(uvs.len()),
            component_type: Checked::Valid(GenericComponentType(ComponentType::F32)),
            type_: Checked::Valid(gltf_json::accessor::Type::Vec2),
            min: None,
            max: None,
            normalized: false,
            sparse: None,
            name: Some("TEXCOORD_0".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        })
    }

    pub fn add_texture(
        &mut self,
        image_path: &PathBuf,
    ) -> (
        Index<gltf_json::Image>,
        Index<gltf_json::Texture>,
        Index<gltf_json::Material>,
    ) {
        let image_data = fs::read(image_path).unwrap_or_else(|e| {
            panic!("Failed to read image file {}: {}", image_path.display(), e);
        });

        self.align_4();
        let buffer_byte_offset = self.combined_buffer.len() as u64;
        self.combined_buffer.extend_from_slice(&image_data);

        let buffer_view_index = self.root.push(View {
            buffer: Index::new(0),
            byte_length: image_data.len().into(),
            byte_offset: Some(USize64(buffer_byte_offset)),
            byte_stride: None,
            target: None,
            name: Some("image_buffer_view".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        });

        let mime_type = if image_path.extension().and_then(|s| s.to_str()) == Some("png") {
            MimeType("image/png".to_string())
        } else {
            MimeType("image/jpeg".to_string())
        };

        let image_index = self.root.push(gltf_json::Image {
            uri: None,
            mime_type: Some(mime_type),
            buffer_view: Some(buffer_view_index),
            name: Some("diffuse".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        });

        let texture_index = self.root.push(gltf_json::Texture {
            sampler: None,
            source: image_index,
            name: Some("diffuse_texture".to_string()),
            extensions: Default::default(),
            extras: Default::default(),
        });

        let material_index = self.root.push(Material {
            pbr_metallic_roughness: PbrMetallicRoughness {
                base_color_texture: Some(texture::Info {
                    index: texture_index,
                    tex_coord: 0,
                    extensions: Default::default(),
                    extras: Default::default(),
                }),
                metallic_factor: StrengthFactor(0.0),
                roughness_factor: StrengthFactor(1.0),
                ..Default::default()
            },
            name: Some("material_with_texture".to_string()),
            ..Default::default()
        });

        (image_index, texture_index, material_index)
    }

    pub fn rotated_finalize_scene(&mut self, name: &str) {
        let rotation = Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2);

        // Wrap existing nodes under this rotated root
        let rotated_root_index = self.root.push(Node {
            children: Some(self.nodes.clone()),
            name: Some("RotatedRoot".to_string()),
            rotation: Some(UnitQuaternion([
                rotation.x, rotation.y, rotation.z, rotation.w,
            ])),
            ..Default::default()
        });

        // Create scene referencing rotated root
        self.root.push(Scene {
            nodes: vec![rotated_root_index],
            name: Some(format!("{}_rotated_scene", name)),
            extensions: Default::default(),
            extras: Default::default(),
        });

        self.nodes.clear();
    }

    pub fn finalize_scene(&mut self, name: &str) {
        // Root node containing all scene nodes
        let root_node_index = self.root.push(Node {
            children: Some(self.nodes.clone()),
            name: Some(format!("{name}_root")),
            ..Default::default()
        });

        // Push the scene referencing that root node
        self.root.push(Scene {
            extensions: Default::default(),
            extras: Default::default(),
            name: Some(name.to_string()),
            nodes: vec![root_node_index],
        });

        // clear for potential next scene
        self.nodes.clear();
    }

    fn finalize(mut self, path: &PathBuf) -> Result<PathBuf, Box<dyn std::error::Error>> {
        self.root.buffers[self.buffer_index.value()].byte_length =
            gltf_json::validation::USize64::from(self.combined_buffer.len());

        let json_string = gltf_json::serialize::to_string(&self.root)?;
        let glb = gltf::binary::Glb {
            header: gltf::binary::Header {
                magic: *b"glTF",
                version: 2,
                length: (json_string.len() + self.combined_buffer.len()).try_into()?,
            },
            json: Cow::Owned(json_string.into_bytes()),
            bin: Some(Cow::Owned(self.combined_buffer)),
        };
        let file = File::create(path).map_err(|e| {
            format!("File::create failed:\n  path: {:?}\n  exists: {}\n  parent: {:?}\n  parent_exists: {}\n  error: {:?}",
                path,
                path.exists(),
                path.parent(),
                path.parent().map(|p| p.exists()).unwrap_or(false),
                e,
            )
        })?;

        glb.to_writer(file)?;
        Ok(path.clone())
    }
}

pub fn build_mesh_gltf(
    object: RenderObject,
    path: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut builder = GltfBuilder::new("Combined Avatar");
    let mesh_index = builder.add_mesh(
        &object.name,
        &object.vertices,
        &object.indices,
        None,
        None,
        None,
        None,
    );
    builder.add_node_with_mesh(mesh_index, &object.name);
    builder.finalize_scene("Scene");
    builder.finalize(&path)?;
    Ok(())
}

pub fn build_mesh_y_up(
    object: RenderObject,
    path: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut builder = GltfBuilder::new("Combined Avatar");
    let mesh_index = builder.add_mesh(
        &object.name,
        &object.vertices,
        &object.indices,
        None,
        None,
        None,
        None,
    );
    builder.add_node_with_mesh(mesh_index, &object.name);
    builder.rotated_finalize_scene("Scene");
    builder.finalize(&path)?;
    Ok(())
}

pub fn build_mesh_scene_gltf(
    objects: Vec<RenderObject>,
    path: PathBuf,
) -> Result<(), MetaverseMeshError> {
    let mut builder = GltfBuilder::new("Combined Avatar");
    for object in objects {
        let (uvs, _texture, material) =
            if let (Some(uv), Some(tex)) = (object.uv.as_ref(), object.texture.as_ref()) {
                let uv_accessor = uv.clone();
                let (_image_index, texture_index, material_index) = builder.add_texture(tex);
                (Some(uv_accessor), Some(texture_index), Some(material_index))
            } else {
                (None, None, None)
            };
        builder.add_uvs(&object.uv.unwrap());
        builder.add_texture(&object.texture.unwrap());
        let mesh_index = builder.add_mesh(
            &object.name,
            &object.vertices,
            &object.indices,
            uvs.as_deref(),
            material,
            None,
            None,
        );

        builder.add_node_with_mesh(mesh_index, &object.name);
    }
    builder.finalize_scene("Scene");
    builder.finalize(&path)?;
    Ok(())
}

pub fn build_skinned_mesh_gltf(
    avatar: AvatarObject,
    path: PathBuf,
) -> Result<(), MetaverseMeshError> {
    let mut builder = GltfBuilder::new("Combined Avatar");
    let bones: BTreeSet<JointName> = avatar.used_joints.clone();

    let mut mesh_nodes = Vec::new();
    let mut skinned_nodes = Vec::new();

    // Add mesh objects
    for object in &avatar.objects {
        let json_str = fs::read_to_string(object).map_err(|e| {
            eprintln!("Failed to read object: {:?}: {:?}", object, e);
            e
        })?;
        let parts: Vec<RenderObject> = serde_json::from_str(&json_str)?;

        for part in parts {
            // Handle texture & UVs
            let (uvs, _texture, material) =
                if let (Some(uv), Some(tex)) = (part.uv.as_ref(), part.texture.as_ref()) {
                    let (_image_index, _texture_index, material_index) = builder.add_texture(tex);
                    (Some(uv), Some(_texture_index), Some(material_index))
                } else {
                    (None, None, None)
                };

            // Handle skin/joint data if present
            let (joint_indices_accessor, joint_weights_accessor) = if let Some(skin) = &part.skin {
                builder.add_joint_data(skin.weights.clone(), &bones)
            } else {
                (None, None)
            };

            // Add mesh
            let mesh_index = builder.add_mesh(
                &part.name,
                &part.vertices,
                &part.indices,
                uvs.map(|v| v.as_slice()),
                material,
                joint_indices_accessor,
                joint_weights_accessor,
            );

            // Add node
            let node_index = builder.add_node_with_mesh(mesh_index, &part.name);
            mesh_nodes.push(node_index);

            if joint_indices_accessor.is_some() || joint_weights_accessor.is_some() {
                skinned_nodes.push(node_index);
            }
        }
    }

    // 3️⃣ If there are no skinned meshes, just finalize scene normally
    if bones.is_empty() {
        let scene_root_index = builder.root.push(Node {
            name: Some("SceneRoot".to_string()),
            children: Some(mesh_nodes.clone()),
            ..Default::default()
        });

        builder.root.push(Scene {
            name: Some("AvatarScene".to_string()),
            nodes: vec![scene_root_index],
            extensions: Default::default(),
            extras: Default::default(),
        });

        builder.finalize(&path)?;
        return Ok(());
    }

    // For skinned meshes: add joint nodes and inverse bind matrices
    let mut joint_to_node: HashMap<JointName, Index<Node>> = HashMap::new();
    let mut skeleton_nodes = Vec::new();
    let mut ibm_matrices = Vec::new();
    let mut effective_parents: HashMap<JointName, Option<JointName>> = HashMap::new();

    // First determine the nearest used ancestor for every joint.
    for joint_name in &bones {
        let Some(joint) = avatar.global_skeleton.joints.get(joint_name) else {
            continue;
        };

        let mut parent = joint.parent;

        while let Some(parent_name) = parent {
            if bones.contains(&parent_name) {
                effective_parents.insert(*joint_name, Some(parent_name));
                break;
            }

            parent = avatar
                .global_skeleton
                .joints
                .get(&parent_name)
                .and_then(|j| j.parent);
        }

        effective_parents.entry(*joint_name).or_insert(None);
    }

    // Create the nodes using transforms relative to their effective parent.
    for joint_name in &bones {
        let Some(joint) = avatar.global_skeleton.joints.get(joint_name) else {
            continue;
        };

        let global_transform = joint.global_transforms.last().unwrap().transform;

        let local_transform = match effective_parents[joint_name] {
            Some(parent_name) => {
                let parent_global = avatar
                    .global_skeleton
                    .joints
                    .get(&parent_name)
                    .unwrap()
                    .global_transforms
                    .last()
                    .unwrap()
                    .transform;

                parent_global.inverse() * global_transform
            }
            None => global_transform,
        };

        let (scale, rotation, translation) = local_transform.to_scale_rotation_translation();

        let joint_node_index = builder.root.push(Node {
            name: Some(joint_name.to_string()),
            scale: Some(scale.into()),
            rotation: Some(UnitQuaternion([
                rotation.x, rotation.y, rotation.z, rotation.w,
            ])),
            translation: Some(translation.into()),
            ..Default::default()
        });

        joint_to_node.insert(*joint_name, joint_node_index);
        skeleton_nodes.push(joint_node_index);

        ibm_matrices.push(global_transform.inverse().to_cols_array());
    }

    // Wire the nodes together using the nearest used ancestor.
    for joint_name in &bones {
        let child_index = joint_to_node[joint_name];

        if let Some(Some(parent_name)) = effective_parents.get(joint_name) {
            let parent_index = joint_to_node[parent_name];

            builder.root.nodes[parent_index.value()]
                .children
                .get_or_insert_with(Vec::new)
                .push(child_index);
        }
    }

    let ibm_accessor_index = builder.add_inverse_bind_matrices(&ibm_matrices);

    let root_joints: Vec<Index<Node>> = skeleton_nodes
        .iter()
        .filter(|&&node_index| {
            let joint_name = bones
                .iter()
                .find(|&&j| joint_to_node[&j] == node_index)
                .unwrap();
            avatar.global_skeleton.joints[joint_name].parent.is_none()
        })
        .cloned()
        .collect();

    let skin_index = builder.root.push(Skin {
        joints: skeleton_nodes.clone(),
        inverse_bind_matrices: Some(ibm_accessor_index),
        skeleton: root_joints.first().cloned(),
        extensions: Default::default(),
        extras: Default::default(),
        name: Some("AvatarSkin".to_string()),
    });

    for node_index in skinned_nodes.iter() {
        builder.root.nodes[node_index.value()].skin = Some(skin_index);
    }

    let skeleton_root_index = builder.root.push(Node {
        name: Some("SkeletonRoot".to_string()),
        children: Some(root_joints), // joints go under SkeletonRoot
        ..Default::default()
    });

    builder.add_bind_pose_animation(&avatar, &bones, &joint_to_node, &effective_parents);

    let non_skinned_mesh_nodes: Vec<Index<Node>> = mesh_nodes
        .into_iter()
        .filter(|idx| !skinned_nodes.contains(idx))
        .collect();

    let scene_root_index = builder.root.push(Node {
        name: Some("SceneRoot".to_string()),
        children: Some(
            skinned_nodes
                .iter()
                .cloned() // skinned meshes go directly under scene root
                .chain(non_skinned_mesh_nodes)
                .chain(std::iter::once(skeleton_root_index)) // skeleton root last
                .collect(),
        ),
        ..Default::default()
    });

    let rotation = Quat::from_rotation_y(-FRAC_PI_2)
        * Quat::from_rotation_z(FRAC_PI_2)
        * Quat::from_rotation_x(-FRAC_PI_2);
    builder.root.nodes[scene_root_index.value()].rotation = Some(UnitQuaternion([
        rotation.x, rotation.y, rotation.z, rotation.w,
    ]));

    builder.root.push(Scene {
        name: Some("AvatarScene".to_string()),
        nodes: vec![scene_root_index],
        extensions: Default::default(),
        extras: Default::default(),
    });
    builder.finalize(&path)?;
    Ok(())
}

/// Converts a byte vector to a vector aligned to a mutiple of 4
fn to_padded_byte_vector(data: &[Vec3]) -> Vec<u8> {
    let flat: Vec<[f32; 3]> = data.iter().map(|v| [v.x, v.y, v.z]).collect();
    let byte_slice: &[u8] = bytemuck::cast_slice(&flat);
    let mut new_vec: Vec<u8> = byte_slice.to_owned();

    while !new_vec.len().is_multiple_of(4) {
        new_vec.push(0); // pad to multiple of four bytes
    }

    new_vec
}

/// determines the highest and lowest points on the mesh to store as min and max
///fn bounding_coords(points: &[Vec3]) -> ([f32; 3], [f32; 3]) {
fn bounding_coords(points: &[Vec3]) -> ([f32; 3], [f32; 3]) {
    let mut min = [f32::MAX, f32::MAX, f32::MAX];
    let mut max = [f32::MIN, f32::MIN, f32::MIN];

    for p in points {
        for i in 0..3 {
            min[i] = f32::min(min[i], p[i]);
            max[i] = f32::max(max[i], p[i]);
        }
    }
    (min, max)
}