collada 0.17.0

A library for parsing COLLADA documents for mesh, skeletal and animation data
Documentation
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
use crate::obj::*;
use crate::utils::*;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::str::FromStr;
use xml::Element;
use xml::Xml::CharacterNode;

use vecmath;
use xml;

use crate::{
    Animation, BindData, BindDataSet, Joint, JointIndex, Skeleton, VertexWeight,
    ROOT_JOINT_PARENT_INDEX,
};

enum GeometryBindingType {
    Polylist,
    Triangles,
    // TODO types below are not implemented
    // Lines,
    // Linestrips,
    // Polygons,
    // Trifans,
    // Tristrips,
}

impl GeometryBindingType {
    fn name(&self) -> &'static str {
        match *self {
            GeometryBindingType::Polylist => "polylist",
            GeometryBindingType::Triangles => "triangles",
        }
    }
}

///
/// Commonly used shading techniques
/// Holds a description of the textures, samplers, shaders, parameters, and
/// passes necessary for rendering this effect using one method.
///
#[derive(Clone, Debug, PartialEq)]
pub struct PhongEffect {
    pub emission: [f32; 4],
    pub ambient: [f32; 4],
    pub diffuse: Diffuse,
    pub specular: Specular,
    pub shininess: f32,
}

///
/// Can be a plain color or point to a texture in the images library
///
#[derive(Clone, Debug, PartialEq)]
pub enum Diffuse {
    Color([f32; 4]),
    Texture(String),
}

type Specular = Diffuse;

#[derive(Clone, Debug, PartialEq)]
pub struct LambertEffect {
    pub emission: [f32; 4],
    pub diffuse: Diffuse,
    pub index_of_refraction: f32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum MaterialEffect {
    Phong(PhongEffect),
    Lambert(LambertEffect),
}

// TODO: Add more effect types and then unify them under a technique enum.
// Lambert
// Blinn
// Constant
//

pub struct ColladaDocument {
    pub root_element: xml::Element, // TODO figure out how to cache skeletal and skinning data, as we need to
                                    // access them multiple times
}

impl ColladaDocument {
    ///
    /// Construct a ColladaDocument for the XML document at the given path
    ///
    pub fn from_path(path: &Path) -> Result<ColladaDocument, &'static str> {
        let file_result = File::open(path);

        let mut file = match file_result {
            Ok(file) => file,
            Err(_) => return Err("Failed to open COLLADA file at path."),
        };

        let mut xml_string = String::new();
        match file.read_to_string(&mut xml_string) {
            Ok(_) => {}
            Err(_) => return Err("Failed to read COLLADA file."),
        };

        ColladaDocument::from_str(&xml_string)
    }

    ///
    /// Construct a ColladaDocument from an XML string
    ///
    pub fn from_str(xml_string: &str) -> Result<ColladaDocument, &'static str> {
        match xml_string.parse() {
            Ok(root_element) => Ok(ColladaDocument { root_element }),
            Err(_) => Err("Error while parsing COLLADA document."),
        }
    }

    fn get_color(el: &Element) -> Option<[f32; 4]> {
        let v: Vec<f32> = parse_string_to_vector(el.content_str().as_str());
        if v.len() == 4 {
            Some([v[0], v[1], v[2], v[3]])
        } else {
            None
        }
    }

    fn get_lambert(&self, lamb: &Element, ns: Option<&str>) -> LambertEffect {
        let emission_color = lamb
            .get_child("emission", ns)
            .expect("lambert is missing emission")
            .get_child("color", ns)
            .expect("emission is missing color");
        let emission =
            ColladaDocument::get_color(emission_color).expect("could not get emission color.");
        let diffuse_element = lamb
            .get_child("diffuse", ns)
            .expect("lambert is missing diffuse");

        let diffuse_texture = diffuse_element.get_child("texture", ns);

        let diffuse;
        if let Some(texture) = diffuse_texture {
            diffuse = Diffuse::Texture(
                texture
                    .get_attribute("texture", None)
                    .expect("No texture attribute on texture")
                    .to_string(),
            );
        } else {
            let diffuse_element_color = diffuse_element
                .get_child("color", ns)
                .expect("diffuse is missing color");
            let diffuse_color = ColladaDocument::get_color(diffuse_element_color)
                .expect("could not get diffuse color.");
            diffuse = Diffuse::Color(diffuse_color);
        }

        let index_of_refraction: f32 = lamb
            .get_child("index_of_refraction", ns)
            .expect("lambert is missing index_of_refraction")
            .get_child("float", ns)
            .expect("index_of_refraction is missing float")
            .content_str()
            .as_str()
            .parse()
            .ok()
            .expect("could not parse index_of_refraction");

        LambertEffect {
            diffuse,
            emission,
            index_of_refraction,
        }
    }

    fn get_phong(&self, phong: &Element, ns: Option<&str>) -> PhongEffect {
        let emission_color = phong
            .get_child("emission", ns)
            .expect("phong is missing emission")
            .get_child("color", ns)
            .expect("emission is missing color");
        let emission =
            ColladaDocument::get_color(emission_color).expect("could not get emission color.");
        let ambient_color = phong
            .get_child("ambient", ns)
            .expect("phong is missing ambient")
            .get_child("color", ns)
            .expect("ambient is missing color");
        let ambient =
            ColladaDocument::get_color(ambient_color).expect("could not get ambient color.");
        
        let diffuse_element = phong
            .get_child("diffuse", ns)
            .expect("phong is missing diffuse");

        let diffuse_texture = diffuse_element.get_child("texture", ns);

        let diffuse;
        if let Some(texture) = diffuse_texture {
            diffuse = Diffuse::Texture(
                texture
                    .get_attribute("texture", None)
                    .expect("No texture attribute on texture")
                    .to_string(),
            );
        } else {
            let diffuse_element_color = diffuse_element
                .get_child("color", ns)
                .expect("diffuse is missing color");
            let diffuse_color = ColladaDocument::get_color(diffuse_element_color)
                .expect("could not get diffuse color.");
            diffuse = Diffuse::Color(diffuse_color);
        }


    let specular_element = phong
        .get_child("specular", ns)
        .expect("phong is missing specular");

    let specular_texture = specular_element.get_child("texture", ns);

    let specular;
    if let Some(texture) = specular_texture {
        specular = Specular::Texture(
            texture
                .get_attribute("texture", None)
                .expect("No texture attribute on texture")
                .to_string(),
        );
    } else {
        let specular_element_color = specular_element
            .get_child("color", ns)
            .expect("specular is missing color");
        let specular_color = ColladaDocument::get_color(specular_element_color)
            .expect("could not get specular color.");
        specular = Specular::Color(specular_color);
    }

        let shininess: f32 = phong
            .get_child("shininess", ns)
            .expect("phong is missing shininess")
            .get_child("float", ns)
            .expect("shininess is missing float")
            .content_str()
            .as_str()
            .parse()
            .ok()
            .expect("could not parse shininess");
        
        PhongEffect {
            ambient,
            diffuse,
            emission,
            // index_of_refraction,
            shininess,
            specular,
        }
    }

    ///
    /// Returns the library of effects.
    /// Current only supports Phong shading.
    ///
    pub fn get_effect_library(&self) -> HashMap<String, MaterialEffect> {
        let ns = self.get_ns();
        let lib_effs = self
            .root_element
            .get_child("library_effects", ns)
            .expect("Could not get library_effects from the document.");
        lib_effs
            .get_children("effect", ns)
            .flat_map(|el: &Element| -> Option<(String, MaterialEffect)> {
                let id = el
                    .get_attribute("id", None)
                    .unwrap_or_else(|| panic!("effect is missing its id. {:#?}", el));
                let prof = el.get_child("profile_COMMON", ns)?;
                let tech = prof.get_child("technique", ns)?;
                let phong = tech.get_child("phong", ns);
                if let Some(p) = phong {
                    let phong_effect = self.get_phong(p, ns);
                    return Some((id.to_string(), MaterialEffect::Phong(phong_effect)));
                };
                let lambert = tech.get_child("lambert", ns);
                if let Some(lam) = lambert {
                    let lambert_effect = self.get_lambert(lam, ns);
                    return Some((id.to_string(), MaterialEffect::Lambert(lambert_effect)));
                };

                None
            })
            .collect()
    }

    pub fn get_material_to_effect(&self) -> HashMap<String, String> {
        let ns = self.get_ns();
        let lib_mats = self
            .root_element
            .get_child("library_materials", ns)
            .expect("Could not get library_materials from the document");
        lib_mats
            .get_children("material", ns)
            .flat_map(|el| {
                let id = el
                    .get_attribute("id", None)
                    .unwrap_or_else(|| panic!("material is missing its id. {:#?}", el));
                let mut url: String = el
                    .get_child("instance_effect", ns)
                    .expect("could not get material instance_effect")
                    .get_attribute("url", None)
                    .expect("could not get material instance_effect url attribute")
                    .to_string();
                if url.remove(0) == '#' {
                    Some((id.to_string(), url))
                } else {
                    None
                }
            })
            .collect()
    }

    ///
    /// Returns a hashmap of <imageid, filename>
    ///
    pub fn get_images(&self) -> HashMap<String, String> {
        let ns = self.get_ns();
        let lib_images = self
            .root_element
            .get_child("library_images", ns)
            .expect("Could not get library_images from the document");
        lib_images
            .get_children("image", ns)
            .flat_map(|el| {
                let id = el
                    .get_attribute("id", None)
                    .expect(&format!("image is missing its id. {:#?}", el))
                    .to_string();
                let file_name = el
                    .get_child("init_from", ns)
                    .expect("Could not get image from the element")
                    .content_str();
                Some((id, file_name))
            })
            .collect()
    }

    ///
    /// Return a vector of all Animations in the Collada document
    ///
    pub fn get_animations(&self) -> Option<Vec<Animation>> {
        match self
            .root_element
            .get_child("library_animations", self.get_ns())
        {
            Some(library_animations) => {
                let animations = library_animations.get_children("animation", self.get_ns());
                Some(animations.filter_map(|a| self.get_animation(a)).collect())
            }
            None => None,
        }
    }

    ///
    /// Construct an Animation struct for the given <animation> element if possible
    ///
    fn get_animation(&self, animation_element: &Element) -> Option<Animation> {
        let channel_element = animation_element
            .get_child("channel", self.get_ns())
            .expect("Missing channel element in animation element");

        let target = channel_element
            .get_attribute("target", None)
            .expect("Missing target attribute in animation channel element");

        let sampler_element = animation_element
            .get_child("sampler", self.get_ns())
            .expect("Missing sampler element in animation element");

        // Note: Assuming INPUT for animation is 'time'
        let time_input = self
            .get_input(sampler_element, "INPUT")
            .expect("Missing input element for animation INPUT (sample time)");

        let sample_times = self
            .get_array_for_input(animation_element, time_input)
            .expect("Missing / invalid source for animation INPUT");

        // Note: Assuming OUTPUT for animation is a pose matrix
        let pose_input = self
            .get_input(sampler_element, "OUTPUT")
            .expect("Missing input element for animation OUTPUT (pose transform)");

        let sample_poses_flat = self
            .get_array_for_input(animation_element, pose_input)
            .expect("Missing / invalid source for animation OUTPUT");

        // Convert flat array of floats into array of matrices
        let sample_poses = to_matrix_array(sample_poses_flat);

        Some(Animation {
            target: target.to_string(),
            sample_times,
            sample_poses,
        })
    }

    ///
    /// Populate and return an ObjSet for the meshes in the Collada document
    ///
    pub fn get_obj_set(&self) -> Option<ObjSet> {
        let library_geometries = (self
            .root_element
            .get_child("library_geometries", self.get_ns()))?;
        let geometries = library_geometries.get_children("geometry", self.get_ns());
        let objects = geometries.filter_map(|g| self.get_object(g)).collect();

        Some(ObjSet {
            material_library: None,
            objects,
        })
    }

    ///
    /// Populate and return a BindDataSet from the Collada document
    ///
    pub fn get_bind_data_set(&self) -> Option<BindDataSet> {
        let library_controllers = (self
            .root_element
            .get_child("library_controllers", self.get_ns()))?;
        let controllers = library_controllers.get_children("controller", self.get_ns());
        let bind_data = controllers.filter_map(|c| self.get_bind_data(c)).collect();
        Some(BindDataSet { bind_data })
    }

    ///
    ///
    ///
    pub fn get_skeletons(&self) -> Option<Vec<Skeleton>> {
        let library_visual_scenes = (self
            .root_element
            .get_child("library_visual_scenes", self.get_ns()))?;
        let visual_scene = (library_visual_scenes.get_child("visual_scene", self.get_ns()))?;

        let bind_data_set = (self.get_bind_data_set())?;

        let skeleton_ids: Vec<&str> = pre_order_iter(visual_scene)
            .filter(|e| e.name == "skeleton")
            .filter_map(|s| {
                if let CharacterNode(ref id) = s.children[0] {
                    Some(&id[..])
                } else {
                    None
                }
            })
            .map(|id| id.trim_start_matches('#'))
            .collect();

        if skeleton_ids.is_empty() {
            return None;
        }

        let skeletons = pre_order_iter(visual_scene)
            .filter(|e| e.name == "node")
            .filter(|e| has_attribute_with_value(e, "id", skeleton_ids[0]))
            .filter_map(|e| self.get_skeleton(e, &bind_data_set.bind_data[0]))
            .collect();

        Some(skeletons)
    }

    fn get_skeleton(&self, root_element: &Element, bind_data: &BindData) -> Option<Skeleton> {
        let mut parent_index_stack: Vec<JointIndex> = vec![ROOT_JOINT_PARENT_INDEX];
        let mut joints = Vec::new();
        let mut bind_poses = Vec::new();
        for (joint_index, (joint_element, depth)) in pre_order_with_depth_iter(root_element)
            .filter(|&(e, _)| e.name == "node" && has_attribute_with_value(e, "type", "JOINT"))
            .enumerate()
        {
            // If our depth decreases after visiting a leaf node, pop indices off the stack
            // until it matches our depth
            while depth < parent_index_stack.len() - 1 {
                parent_index_stack.pop();
            }

            let joint_name = joint_element.get_attribute("id", None).unwrap().to_string();

            let mut joint_names_with_bind_pose = bind_data
                .joint_names
                .iter()
                .zip(bind_data.inverse_bind_poses.iter());
            let inverse_bind_pose =
                match joint_names_with_bind_pose.find(|&(name, _)| *name == joint_name) {
                    Some((_, pose)) => *pose,
                    _ => vecmath::mat4_id(),
                };

            joints.push(Joint {
                inverse_bind_pose,
                name: joint_name,
                parent_index: *parent_index_stack.last().unwrap(),
            });

            let pose_matrix_element = (joint_element.get_child("matrix", self.get_ns()))?;
            let pose_matrix_array = (get_array_content(pose_matrix_element))?;
            let mut pose_matrix = vecmath::mat4_id();
            for (&array_value, matrix_value) in pose_matrix_array
                .iter()
                .zip(pose_matrix.iter_mut().flat_map(|n| n.iter_mut()))
            {
                *matrix_value = array_value;
            }

            bind_poses.push(pose_matrix);

            parent_index_stack.push(joint_index as JointIndex);
        }

        Some(Skeleton { joints, bind_poses })
    }

    fn get_bind_data(&self, controller_element: &xml::Element) -> Option<BindData> {
        let skeleton_name = controller_element.get_attribute("name", None);
        let skin_element = controller_element.get_child("skin", self.get_ns())?;
        let object_name = skin_element
            .get_attribute("source", None)?
            .trim_start_matches('#');

        let vertex_weights_element = (skin_element.get_child("vertex_weights", self.get_ns()))?;
        let vertex_weights = (self.get_vertex_weights(vertex_weights_element))?;

        let joints_element = (skin_element.get_child("joints", self.get_ns()))?;

        let joint_input = (self.get_input(joints_element, "JOINT"))?;
        let joint_names = (self.get_array_for_input(skin_element, joint_input))?;

        let weights_input = (self.get_input(vertex_weights_element, "WEIGHT"))?;
        let weights = (self.get_array_for_input(skin_element, weights_input))?;

        let inv_bind_matrix_input = (self.get_input(joints_element, "INV_BIND_MATRIX"))?;

        let inverse_bind_poses =
            to_matrix_array((self.get_array_for_input(skin_element, inv_bind_matrix_input))?);

        Some(BindData {
            object_name: object_name.to_string(),
            skeleton_name: skeleton_name.map(|s| s.to_string()),
            joint_names,
            inverse_bind_poses,
            weights,
            vertex_weights,
        })
    }

    fn get_vertex_weights(
        &self,
        vertex_weights_element: &xml::Element,
    ) -> Option<Vec<VertexWeight>> {
        let joint_index_offset = (self.get_input_offset(vertex_weights_element, "JOINT"))?;
        let weight_index_offset = (self.get_input_offset(vertex_weights_element, "WEIGHT"))?;

        let vcount_element = (vertex_weights_element.get_child("vcount", self.get_ns()))?;
        let weights_per_vertex: Vec<usize> = (get_array_content(vcount_element))?;
        let input_count = vertex_weights_element
            .get_children("input", self.get_ns())
            .count();

        let v_element = (vertex_weights_element.get_child("v", self.get_ns()))?;
        let joint_weight_indices: Vec<usize> = (get_array_content(v_element))?;
        let mut joint_weight_iter = joint_weight_indices.chunks(input_count);

        let mut vertex_indices: Vec<usize> = Vec::new();
        for (index, n) in weights_per_vertex.iter().enumerate() {
            for _ in 0..*n {
                vertex_indices.push(index);
            }
        }

        let vertex_weights = vertex_indices
            .iter()
            .filter_map(|vertex_index| {
                joint_weight_iter.next().map(|joint_weight| VertexWeight {
                    vertex: *vertex_index,
                    joint: joint_weight[joint_index_offset] as JointIndex,
                    weight: joint_weight[weight_index_offset],
                })
            })
            .collect();

        Some(vertex_weights)
    }

    fn get_object(&self, geometry_element: &xml::Element) -> Option<Object> {
        let id = (geometry_element.get_attribute("id", None))?;
        let name = (geometry_element.get_attribute("name", None))?;
        let mesh_element = (geometry_element.get_child("mesh", self.get_ns()))?;
        let mesh = (self.get_mesh_elements(mesh_element))?;

        let mut first_primitive_element = None;
        'find_primitive: for t in [
            GeometryBindingType::Polylist,
            GeometryBindingType::Triangles,
        ]
        .iter()
        {
            first_primitive_element = mesh_element.get_child(t.name(), self.get_ns());
            if first_primitive_element.is_some() {
                break 'find_primitive;
            }
        }
        let first_primitive_element = first_primitive_element?;

        let positions_input = (self.get_input(first_primitive_element, "VERTEX"))?;
        let positions_array = (self.get_array_for_input(mesh_element, positions_input))?;
        let positions: Vec<_> = positions_array
            .chunks(3)
            .map(|coords| Vertex {
                x: coords[0],
                y: coords[1],
                z: coords[2],
            })
            .collect();

        let normals = {
            match self.get_input(first_primitive_element, "NORMAL") {
                Some(normals_input) => {
                    let normals_array = (self.get_array_for_input(mesh_element, normals_input))?;
                    normals_array
                        .chunks(3)
                        .map(|coords| Normal {
                            x: coords[0],
                            y: coords[1],
                            z: coords[2],
                        })
                        .collect()
                }
                None => Vec::new(),
            }
        };

        let texcoords = {
            match self.get_input(first_primitive_element, "TEXCOORD") {
                Some(texcoords_input) => {
                    let texcoords_array =
                        (self.get_array_for_input(mesh_element, texcoords_input))?;
                    texcoords_array
                        .chunks(2)
                        .map(|coords| TVertex {
                            x: coords[0],
                            y: coords[1],
                        })
                        .collect()
                }
                None => Vec::new(),
            }
        };

        // TODO cache! also only if any skeleton

        let joint_weights = match self.get_skeletons() {
            Some(skeletons) => {
                let skeleton = &skeletons[0];
                // TODO cache bind_data_set
                let bind_data_set = (self.get_bind_data_set())?;
                let bind_data_opt = bind_data_set
                    .bind_data
                    .iter()
                    .find(|bind_data| bind_data.object_name == id);

                if let Some(bind_data) = bind_data_opt {
                    // Build an array of joint weights for each vertex
                    // Initialize joint weights array with no weights for any vertex
                    let mut joint_weights = vec![
                        JointWeights {
                            joints: [0; 4],
                            weights: [0.0; 4]
                        };
                        positions.len()
                    ];

                    for vertex_weight in bind_data.vertex_weights.iter() {
                        let joint_name = &bind_data.joint_names[vertex_weight.joint as usize];
                        let vertex_joint_weights: &mut JointWeights =
                            &mut joint_weights[vertex_weight.vertex];

                        if let Some((next_index, _)) = vertex_joint_weights
                            .weights
                            .iter()
                            .enumerate()
                            .find(|&(_, weight)| *weight == 0.0)
                        {
                            if let Some((joint_index, _)) = skeleton
                                .joints
                                .iter()
                                .enumerate()
                                .find(|&(_, j)| &j.name == joint_name)
                            {
                                vertex_joint_weights.joints[next_index] = joint_index;
                                vertex_joint_weights.weights[next_index] =
                                    bind_data.weights[vertex_weight.weight];
                            } else {
                                error!("Couldn't find joint: {}", joint_name);
                            }
                        } else {
                            error!("Too many joint influences for vertex");
                        }
                    }
                    joint_weights
                } else {
                    Vec::new()
                }
            }
            None => Vec::new(),
        };

        Some(Object {
            id: id.to_string(),
            name: name.to_string(),
            vertices: positions,
            tex_vertices: texcoords,
            normals,
            joint_weights,
            geometry: vec![Geometry {
                smooth_shading_group: 0,
                mesh,
            }],
        })
    }

    fn get_ns(&self) -> Option<&str> {
        match self.root_element.ns {
            Some(ref ns) => Some(&ns[..]),
            None => None,
        }
    }

    fn get_input_offset(&self, parent_element: &xml::Element, semantic: &str) -> Option<usize> {
        let mut inputs = parent_element.get_children("input", self.get_ns());
        let input: &Element = inputs.find(|i| {
            if let Some(s) = i.get_attribute("semantic", None) {
                s == semantic
            } else {
                false
            }
        })?;
        input
            .get_attribute("offset", None)
            .expect("input is missing offest")
            .parse::<usize>()
            .ok()
    }

    ///
    fn get_input<'a>(&'a self, parent: &'a Element, semantic: &str) -> Option<&'a Element> {
        let mut inputs = parent.get_children("input", self.get_ns());
        match inputs.find(|i| {
            if let Some(s) = i.get_attribute("semantic", None) {
                s == semantic
            } else {
                false
            }
        }) {
            Some(e) => Some(e),
            None => None,
        }
    }

    fn get_input_source<'a>(
        &'a self,
        parent_element: &'a xml::Element,
        input_element: &'a xml::Element,
    ) -> Option<&'a xml::Element> {
        let source_id = (input_element.get_attribute("source", None))?;

        if let Some(element) = parent_element
            .children
            .iter()
            .filter_map(|node| {
                if let xml::Xml::ElementNode(ref e) = node {
                    Some(e)
                } else {
                    None
                }
            })
            .find(|e| {
                if let Some(id) = e.get_attribute("id", None) {
                    let id = "#".to_string() + id;
                    id == source_id
                } else {
                    false
                }
            })
        {
            if element.name == "source" {
                return Some(element);
            } else {
                let input = (element.get_child("input", self.get_ns()))?;
                return self.get_input_source(parent_element, input);
            }
        }
        None
    }

    fn get_array_for_input<T: FromStr>(&self, parent: &Element, input: &Element) -> Option<Vec<T>> {
        let source = (self.get_input_source(parent, input))?;
        let array_element =
            (if let Some(float_array) = source.get_child("float_array", self.get_ns()) {
                Some(float_array)
            } else {
                source.get_child("Name_array", self.get_ns())
            })?;
        get_array_content(array_element)
    }

    fn get_vertex_indices(&self, prim_element: &xml::Element) -> Option<Vec<VertexIndex>> {
        let p_element = (prim_element.get_child("p", self.get_ns()))?;
        let indices: Vec<usize> = (get_array_content(p_element))?;

        let input_count = prim_element
            .get_children("input", self.get_ns())
            .filter(|c| {
                if let Some(set) = c.get_attribute("set", None) {
                    set == "0"
                } else {
                    true
                }
            })
            .count();

        let vertex_offset = (self.get_input_offset(prim_element, "VERTEX"))?;
        let vertex_indices = indices
            .chunks(input_count)
            .map(|indices| indices[vertex_offset])
            .collect();

        Some(vertex_indices)
    }

    fn get_normal_indices(&self, prim_element: &xml::Element) -> Option<Vec<NormalIndex>> {
        let p_element = (prim_element.get_child("p", self.get_ns()))?;
        let indices: Vec<usize> = (get_array_content(p_element))?;

        let input_count = prim_element
            .get_children("input", self.get_ns())
            .filter(|c| {
                if let Some(set) = c.get_attribute("set", None) {
                    set == "0"
                } else {
                    true
                }
            })
            .count();

        self.get_input_offset(prim_element, "NORMAL")
            .map(|normal_offset| {
                indices
                    .chunks(input_count)
                    .map(|indices| indices[normal_offset])
                    .collect()
            })
    }

    fn get_texcoord_indices(&self, prim_element: &xml::Element) -> Option<Vec<TextureIndex>> {
        let p_element = (prim_element.get_child("p", self.get_ns()))?;
        let indices: Vec<usize> = (get_array_content(p_element))?;

        let input_count = prim_element
            .get_children("input", self.get_ns())
            .filter(|c| {
                if let Some(set) = c.get_attribute("set", None) {
                    set == "0"
                } else {
                    true
                }
            })
            .count();

        self.get_input_offset(prim_element, "TEXCOORD")
            .map(|texcoord_offset| {
                indices
                    .chunks(input_count)
                    .map(|indices| indices[texcoord_offset])
                    .collect()
            })
    }

    fn get_vtn_indices(&self, prim_element: &xml::Element) -> Option<Vec<VTNIndex>> {
        let p_element = (prim_element.get_child("p", self.get_ns()))?;
        let indices: Vec<usize> = (get_array_content(p_element))?;

        let input_count = prim_element
            .get_children("input", self.get_ns())
            .filter(|c| {
                if let Some(set) = c.get_attribute("set", None) {
                    set == "0"
                } else {
                    true
                }
            })
            .count();

        let position_offset = (self.get_input_offset(prim_element, "VERTEX"))?;

        let normal_offset_opt = self.get_input_offset(prim_element, "NORMAL");
        let texcoord_offset_opt = self.get_input_offset(prim_element, "TEXCOORD");

        let vtn_indices: Vec<VTNIndex> = indices
            .chunks(input_count)
            .map(|indices| {
                let position_index = indices[position_offset];

                let normal_index_opt =
                    normal_offset_opt.map(|normal_offset| indices[normal_offset]);

                let texcoord_index_opt =
                    texcoord_offset_opt.map(|texcoord_offset| indices[texcoord_offset]);

                (position_index, texcoord_index_opt, normal_index_opt)
            })
            .collect();

        Some(vtn_indices)
    }

    fn get_material(&self, primitive_el: &xml::Element) -> Option<String> {
        primitive_el
            .get_attribute("material", None)
            .map(|s| s.to_string())
    }

    fn get_mesh_elements(&self, mesh_element: &xml::Element) -> Option<Vec<PrimitiveElement>> {
        let mut prims = vec![];
        for child in &mesh_element.children {
            match child {
                xml::Xml::ElementNode(el) => {
                    if el.name == GeometryBindingType::Polylist.name() {
                        let shapes = self
                            .get_polylist_shape(el)
                            .expect("Polylist had no shapes.");
                        let material = self.get_material(el);
                        let polylist = Polylist { shapes, material };
                        prims.push(PrimitiveElement::Polylist(polylist))
                    } else if el.name == GeometryBindingType::Triangles.name() {
                        let material = self.get_material(el);
                        let triangles = self
                            .get_triangles(el, material)
                            .expect("Triangles had no indices.");
                        prims.push(PrimitiveElement::Triangles(triangles))
                    }
                }
                _ => {}
            }
        }

        if prims.is_empty() {
            None
        } else {
            Some(prims)
        }
    }

    fn get_triangles(
        &self,
        triangles: &xml::Element,
        material: Option<String>,
    ) -> Option<Triangles> {
        let count_str: &str = triangles.get_attribute("count", None)?;
        let count = count_str.parse::<usize>().ok().unwrap();

        let vertices = self.get_vertex_indices(triangles).map(|vertex_indices| {
            let mut vertex_iter = vertex_indices.iter();
            (0..count)
                .map(|_| {
                    (
                        *vertex_iter.next().unwrap(),
                        *vertex_iter.next().unwrap(),
                        *vertex_iter.next().unwrap(),
                    )
                })
                .collect()
        })?;

        let tex_vertices = self
            .get_texcoord_indices(triangles)
            .map(|texcoord_indices| {
                let mut texcoord_iter = texcoord_indices.iter();
                (0..count)
                    .map(|_| {
                        (
                            *texcoord_iter.next().unwrap(),
                            *texcoord_iter.next().unwrap(),
                            *texcoord_iter.next().unwrap(),
                        )
                    })
                    .collect()
            });

        let normals = self.get_normal_indices(triangles).map(|normal_indices| {
            let mut normal_iter = normal_indices.iter();
            (0..count)
                .map(|_| {
                    (
                        *normal_iter.next().unwrap(),
                        *normal_iter.next().unwrap(),
                        *normal_iter.next().unwrap(),
                    )
                })
                .collect()
        });

        Some(Triangles {
            vertices,
            tex_vertices,
            normals,
            material,
        })
    }

    fn get_polylist_shape(&self, polylist_element: &xml::Element) -> Option<Vec<Shape>> {
        let vtn_indices = (self.get_vtn_indices(polylist_element))?;

        let vcount_element = (polylist_element.get_child("vcount", self.get_ns()))?;
        let vertex_counts: Vec<usize> = (get_array_content(vcount_element))?;

        let mut vtn_iter = vtn_indices.iter();
        let shapes = vertex_counts
            .iter()
            .map(|vertex_count| {
                match *vertex_count {
                    1 => Shape::Point(*vtn_iter.next().unwrap()),
                    2 => Shape::Line(*vtn_iter.next().unwrap(), *vtn_iter.next().unwrap()),
                    3 => Shape::Triangle(
                        *vtn_iter.next().unwrap(),
                        *vtn_iter.next().unwrap(),
                        *vtn_iter.next().unwrap(),
                    ),
                    n => {
                        // Polys with more than 3 vertices not supported - try to advance and continue
                        // TODO attempt to triangle-fy? (take a look at wavefront_obj)
                        for _ in 0..n {
                            vtn_iter.next();
                        }
                        Shape::Point((0, None, None))
                    }
                }
            })
            .collect();

        Some(shapes)
    }
}

#[test]
fn test_get_obj_set() {
    let collada_document = ColladaDocument::from_path(Path::new("test_assets/test.dae")).unwrap();
    let obj_set = collada_document.get_obj_set().unwrap();
    assert_eq!(obj_set.objects.len(), 1);

    let object = &obj_set.objects[0];
    assert_eq!(object.id, "BoxyWorm-mesh");
    assert_eq!(object.name, "BoxyWorm");
    assert_eq!(object.vertices.len(), 16);
    assert_eq!(object.tex_vertices.len(), 84);
    assert_eq!(object.normals.len(), 28);
    assert_eq!(object.geometry.len(), 1);

    let geometry = &object.geometry[0];

    let prim = &geometry.mesh[0];
    if let PrimitiveElement::Polylist(polylist) = prim {
        assert_eq!(polylist.shapes.len(), 28);
        let shape = polylist.shapes[1];
        if let Shape::Triangle((position_index, Some(texture_index), Some(normal_index)), _, _) =
            shape
        {
            assert_eq!(position_index, 7);
            assert_eq!(texture_index, 3);
            assert_eq!(normal_index, 1);
        } else {
            assert!(false);
        }
    }
}

#[test]
fn test_get_obj_set_triangles_geometry() {
    let collada_document =
        ColladaDocument::from_path(Path::new("test_assets/test_cube_triangles_geometry.dae"))
            .unwrap();
    let obj_set = collada_document.get_obj_set().unwrap();
    assert_eq!(obj_set.objects.len(), 1);

    let object = &obj_set.objects[0];
    assert_eq!(object.id, "Cube-mesh");
    assert_eq!(object.name, "Cube");
    assert_eq!(object.vertices.len(), 8);
    assert_eq!(object.normals.len(), 12);
    assert_eq!(object.geometry.len(), 1);

    let geometry = &object.geometry[0];

    let prim = &geometry.mesh[0];
    match prim {
        PrimitiveElement::Triangles(triangles) => {
            assert_eq!(triangles.vertices.len(), 12);

            let position_index = triangles.vertices[1].0;
            assert_eq!(position_index, 7);

            if let Some(ref normals) = triangles.normals {
                assert_eq!(normals.len(), 12);

                let normal_index = normals[1].0;
                assert_eq!(normal_index, 1);
            } else {
                assert!(false, "Triangle is missing a normal.");
            }
        }
        x => {
            assert!(false, "Not a polylist: {:#?}", x);
        }
    }
}

#[test]
fn test_get_bind_data_set() {
    let collada_document = ColladaDocument::from_path(Path::new("test_assets/test.dae")).unwrap();
    let bind_data_set = collada_document.get_bind_data_set().unwrap();
    let bind_data = &bind_data_set.bind_data[0];

    assert_eq!(bind_data.object_name, "BoxyWorm-mesh");
    assert!(bind_data.skeleton_name.is_some());
    assert_eq!(bind_data.skeleton_name.as_ref().unwrap(), "BoxWormRoot");
    assert_eq!(bind_data.joint_names, ["Root", "UpperArm", "LowerArm"]);
    assert_eq!(bind_data.vertex_weights.len(), 29);
    assert_eq!(bind_data.weights.len(), 29);
    assert_eq!(bind_data.inverse_bind_poses.len(), 3);
}

#[test]
fn test_get_skeletons() {
    let collada_document = ColladaDocument::from_path(Path::new("test_assets/test.dae")).unwrap();
    let skeletons = collada_document.get_skeletons().unwrap();
    assert_eq!(skeletons.len(), 1);

    let skeleton = &skeletons[0];
    assert_eq!(skeleton.joints.len(), 4);
    assert_eq!(skeleton.bind_poses.len(), 4);

    assert_eq!(skeleton.joints[0].name, "Root");
    assert_eq!(skeleton.joints[0].parent_index, ROOT_JOINT_PARENT_INDEX);
    assert!(skeleton.joints[0].inverse_bind_pose != vecmath::mat4_id());

    assert_eq!(skeleton.joints[1].name, "UpperArm");
    assert_eq!(skeleton.joints[1].parent_index, 0);
    assert!(skeleton.joints[1].inverse_bind_pose != vecmath::mat4_id());

    assert_eq!(skeleton.joints[2].name, "UpperArmDanglyBit");
    assert_eq!(skeleton.joints[2].parent_index, 1);
    assert_eq!(skeleton.joints[2].inverse_bind_pose, vecmath::mat4_id());

    assert_eq!(skeleton.joints[3].name, "LowerArm");
    assert_eq!(skeleton.joints[3].parent_index, 0);
    assert!(skeleton.joints[3].inverse_bind_pose != vecmath::mat4_id());
}

#[test]
fn test_get_animations() {
    let collada_document = ColladaDocument::from_path(Path::new("test_assets/test.dae")).unwrap();
    let animations = collada_document.get_animations().unwrap();
    assert_eq!(animations.len(), 4);

    let animation = &animations[1];
    assert_eq!(animation.target, "UpperArm/transform");
    assert_eq!(animation.sample_times.len(), 4);
    assert_eq!(animation.sample_poses.len(), 4);

    let animation = &animations[3];
    assert_eq!(animation.target, "LowerArm/transform");
    assert_eq!(animation.sample_times.len(), 4);
    assert_eq!(animation.sample_poses.len(), 4);
}

#[test]
fn test_get_obj_set_noskeleton() {
    let collada_document =
        ColladaDocument::from_path(Path::new("test_assets/test_noskeleton.dae")).unwrap();
    collada_document.get_obj_set().unwrap();
}