doxygen: add newline after \file
[blender.git] / source / blender / collada / ArmatureImporter.cpp
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16
17 /** \file
18  * \ingroup collada
19  */
20
21
22 /* COLLADABU_ASSERT, may be able to remove later */
23 #include "COLLADABUPlatform.h"
24
25 #include <algorithm>
26
27 #include "COLLADAFWUniqueId.h"
28
29 extern "C" {
30 #include "BKE_action.h"
31 #include "BKE_object.h"
32 #include "BKE_armature.h"
33 #include "BLI_string.h"
34 #include "BLI_listbase.h"
35 #include "ED_armature.h"
36 }
37
38 #include "DEG_depsgraph.h"
39
40 #include "collada_utils.h"
41 #include "ArmatureImporter.h"
42
43 // use node name, or fall back to original id if not present (name is optional)
44 template<class T>
45 static const char *bc_get_joint_name(T *node)
46 {
47         const std::string& id = node->getName();
48         return id.size() ? id.c_str() : node->getOriginalId().c_str();
49 }
50
51
52 ArmatureImporter::ArmatureImporter(
53         UnitConverter *conv, MeshImporterBase *mesh, Main *bmain, Scene *sce, ViewLayer *view_layer, const ImportSettings *import_settings) :
54         TransformReader(conv),
55         m_bmain(bmain),
56         scene(sce),
57         view_layer(view_layer),
58         unit_converter(conv),
59         import_settings(import_settings),
60         empty(NULL),
61         mesh_importer(mesh) {
62 }
63
64 ArmatureImporter::~ArmatureImporter()
65 {
66         // free skin controller data if we forget to do this earlier
67         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
68         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
69                 it->second.free();
70         }
71 }
72
73 #if 0
74 JointData *ArmatureImporter::get_joint_data(COLLADAFW::Node *node);
75 {
76         const COLLADAFW::UniqueId& joint_id = node->getUniqueId();
77
78         if (joint_id_to_joint_index_map.find(joint_id) == joint_id_to_joint_index_map.end()) {
79                 fprintf(stderr, "Cannot find a joint index by joint id for %s.\n",
80                         node->getOriginalId().c_str());
81                 return NULL;
82         }
83
84         int joint_index = joint_id_to_joint_index_map[joint_id];
85
86         return &joint_index_to_joint_info_map[joint_index];
87 }
88 #endif
89
90 int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
91         float parent_mat[4][4], bArmature *arm, std::vector<std::string> &layer_labels)
92 {
93         float mat[4][4];
94         float joint_inv_bind_mat[4][4];
95         float joint_bind_mat[4][4];
96         int chain_length = 0;
97
98         //Checking if bone is already made.
99         std::vector<COLLADAFW::Node *>::iterator it;
100         it = std::find(finished_joints.begin(), finished_joints.end(), node);
101         if (it != finished_joints.end()) return chain_length;
102
103         EditBone *bone = ED_armature_ebone_add(arm, bc_get_joint_name(node));
104         totbone++;
105
106         /*
107          * We use the inv_bind_shape matrix to apply the armature bind pose as its rest pose.
108          */
109
110         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator skin_it;
111         bool bone_is_skinned = false;
112         for (skin_it = skin_by_data_uid.begin(); skin_it != skin_by_data_uid.end(); skin_it++) {
113
114                 SkinInfo *b = &skin_it->second;
115                 if (b->get_joint_inv_bind_matrix(joint_inv_bind_mat, node)) {
116
117                         // get original world-space matrix
118                         invert_m4_m4(mat, joint_inv_bind_mat);
119                         copy_m4_m4(joint_bind_mat, mat);
120                         // And make local to armature
121                         Object *ob_arm = skin->BKE_armature_from_object();
122                         if (ob_arm) {
123                                 float invmat[4][4];
124                                 invert_m4_m4(invmat, ob_arm->obmat);
125                                 mul_m4_m4m4(mat, invmat, mat);
126                         }
127
128                         bone_is_skinned = true;
129                         break;
130                 }
131         }
132
133         // create a bone even if there's no joint data for it (i.e. it has no influence)
134         if (!bone_is_skinned) {
135                 get_node_mat(mat, node, NULL, NULL, parent_mat);
136         }
137
138         if (parent) bone->parent = parent;
139
140         float loc[3], size[3], rot[3][3];
141         BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(arm);
142         BoneExtended &be = add_bone_extended(bone, node, totchild, layer_labels, extended_bones);
143         int layer = be.get_bone_layers();
144         if (layer) bone->layer = layer;
145         arm->layer |= layer; // ensure that all populated bone layers are visible after import
146
147         float *tail = be.get_tail();
148         int use_connect = be.get_use_connect();
149
150         switch (use_connect) {
151                 case 1: bone->flag |= BONE_CONNECTED;
152                         break;
153                 case -1:/* Connect type not specified */
154                 case 0: bone->flag &= ~BONE_CONNECTED;
155                         break;
156         }
157
158         if (be.has_roll()) {
159                 bone->roll = be.get_roll();
160         }
161         else {
162                 float angle;
163                 mat4_to_loc_rot_size(loc, rot, size, mat);
164                 mat3_to_vec_roll(rot, NULL, &angle);
165                 bone->roll = angle;
166         }
167         copy_v3_v3(bone->head, mat[3]);
168
169         if (bone_is_skinned && this->import_settings->keep_bind_info)
170         {
171                 float rest_mat[4][4];
172                 get_node_mat(rest_mat, node, NULL, NULL, NULL);
173                 bc_set_IDPropertyMatrix(bone, "bind_mat", joint_bind_mat);
174                 bc_set_IDPropertyMatrix(bone, "rest_mat", rest_mat);
175         }
176
177         add_v3_v3v3(bone->tail, bone->head, tail); //tail must be non zero
178
179         /* find smallest bone length in armature (used later for leaf bone length) */
180         if (parent) {
181
182                 if (use_connect == 1) {
183                         copy_v3_v3(parent->tail, bone->head);
184                 }
185
186                 /* guess reasonable leaf bone length */
187                 float length = len_v3v3(parent->head, bone->head);
188                 if ((length < leaf_bone_length || totbone == 0) && length > MINIMUM_BONE_LENGTH) {
189                         leaf_bone_length = length;
190                 }
191         }
192
193         COLLADAFW::NodePointerArray& children = node->getChildNodes();
194
195         for (unsigned int i = 0; i < children.getCount(); i++) {
196                 int cl = create_bone(skin, children[i], bone, children.getCount(), mat, arm, layer_labels);
197                 if (cl > chain_length)
198                         chain_length = cl;
199         }
200
201         bone->length = len_v3v3(bone->head, bone->tail);
202         joint_by_uid[node->getUniqueId()] = node;
203         finished_joints.push_back(node);
204
205         be.set_chain_length(chain_length + 1);
206
207         return chain_length + 1;
208 }
209
210 /**
211   * Collada only knows Joints, hence bones at the end of a bone chain
212   * don't have a defined length. This function guesses reasonable
213   * tail locations for the affected bones (nodes which don't have any connected child)
214   * Hint: The extended_bones set gets populated in ArmatureImporter::create_bone
215 **/
216 void ArmatureImporter::fix_leaf_bone_hierarchy(bArmature *armature, Bone *bone, bool fix_orientation)
217 {
218         if (bone == NULL)
219                 return;
220
221         if (bc_is_leaf_bone(bone)) {
222                 BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(armature);
223                 BoneExtended *be = extended_bones[bone->name];
224                 EditBone *ebone = bc_get_edit_bone(armature, bone->name);
225                 fix_leaf_bone(armature, ebone, be, fix_orientation);
226         }
227
228         for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
229                 fix_leaf_bone_hierarchy(armature, child, fix_orientation);
230         }
231 }
232
233 void ArmatureImporter::fix_leaf_bone(bArmature *armature, EditBone *ebone, BoneExtended *be , bool fix_orientation)
234 {
235         if (be == NULL || !be->has_tail()) {
236
237                 /* Collada only knows Joints, Here we guess a reasonable leaf bone length */
238                 float leaf_length = (leaf_bone_length == FLT_MAX) ? 1.0 : leaf_bone_length;
239
240
241                 float vec[3];
242
243                 if (fix_orientation && ebone->parent != NULL) {
244                         EditBone *parent = ebone->parent;
245                         sub_v3_v3v3(vec, ebone->head, parent->head);
246                         if (len_squared_v3(vec) < MINIMUM_BONE_LENGTH)
247                         {
248                                 sub_v3_v3v3(vec, parent->tail, parent->head);
249                         }
250                 }
251                 else {
252                         vec[2] = 0.1f;
253                         sub_v3_v3v3(vec, ebone->tail, ebone->head);
254                 }
255
256                 normalize_v3_v3(vec, vec);
257                 mul_v3_fl(vec, leaf_length);
258                 add_v3_v3v3(ebone->tail, ebone->head, vec);
259         }
260 }
261
262 void ArmatureImporter::fix_parent_connect(bArmature *armature, Bone *bone)
263 {
264         /* armature has no bones */
265         if (bone == NULL)
266                 return;
267
268         if (bone->parent && bone->flag & BONE_CONNECTED) {
269                 copy_v3_v3(bone->parent->tail, bone->head);
270         }
271
272         for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
273                 fix_parent_connect(armature, child);
274         }
275
276 }
277
278 void ArmatureImporter::connect_bone_chains(bArmature *armature, Bone *parentbone, int clip)
279 {
280         BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(armature);
281         BoneExtended *dominant_child = NULL;
282         int maxlen = 0;
283
284         if (parentbone == NULL)
285                 return;
286
287         Bone *child = (Bone *)parentbone->childbase.first;
288         if (child && (import_settings->find_chains || child->next==NULL)) {
289                 for (; child; child = child->next) {
290                         BoneExtended *be = extended_bones[child->name];
291                         if (be != NULL) {
292                                 int chain_len = be->get_chain_length();
293                                 if (chain_len <= clip) {
294                                         if (chain_len > maxlen) {
295                                                 dominant_child = be;
296                                                 maxlen = chain_len;
297                                         }
298                                         else if (chain_len == maxlen) {
299                                                 dominant_child = NULL;
300                                         }
301                                 }
302                         }
303                 }
304         }
305
306         BoneExtended *pbe = extended_bones[parentbone->name];
307         if (dominant_child != NULL) {
308                 /* Found a valid chain. Now connect current bone with that chain.*/
309                 EditBone *pebone = bc_get_edit_bone(armature, parentbone->name);
310                 EditBone *cebone = bc_get_edit_bone(armature, dominant_child->get_name());
311                 if (pebone && !(cebone->flag & BONE_CONNECTED)) {
312                         float vec[3];
313                         sub_v3_v3v3(vec, cebone->head, pebone->head);
314
315                         /*
316                          * It is possible that the child's head is located on the parents head.
317                          * When this happens, then moving the parent's tail to the child's head
318                          * would result in a zero sized bone and Blender would  silently remove the bone.
319                          * So we move the tail only when the resulting bone has a minimum length:
320                          */
321
322                         if (len_squared_v3(vec) > MINIMUM_BONE_LENGTH)
323                         {
324                                 copy_v3_v3(pebone->tail, cebone->head);
325                                 pbe->set_tail(pebone->tail); /* to make fix_leafbone happy ...*/
326                                 if (pbe && pbe->get_chain_length() >= this->import_settings->min_chain_length) {
327
328                                         BoneExtended *cbe = extended_bones[cebone->name];
329                                         cbe->set_use_connect(true);
330
331                                         cebone->flag |= BONE_CONNECTED;
332                                         pbe->set_leaf_bone(false);
333                                         printf("Connect Bone chain: parent (%s --> %s) child)\n", pebone->name, cebone->name);
334                                 }
335                         }
336                 }
337                 for (Bone *ch = (Bone *)parentbone->childbase.first; ch; ch = ch->next) {
338                         ArmatureImporter::connect_bone_chains(armature, ch, UNLIMITED_CHAIN_MAX);
339                 }
340         }
341         else if (maxlen>1 && maxlen > this->import_settings->min_chain_length) {
342                 /* Try again with smaller chain length */
343                 ArmatureImporter::connect_bone_chains(armature, parentbone, maxlen - 1);
344         }
345         else {
346                 /* can't connect this Bone. Proceed with children ... */
347                 if (pbe) pbe->set_leaf_bone(true);
348                 for (Bone *ch = (Bone *)parentbone->childbase.first; ch; ch = ch->next) {
349                         ArmatureImporter::connect_bone_chains(armature, ch, UNLIMITED_CHAIN_MAX);
350                 }
351         }
352
353 }
354
355 #if 0
356 void ArmatureImporter::set_leaf_bone_shapes(Object *ob_arm)
357 {
358         bPose *pose = ob_arm->pose;
359
360         std::vector<LeafBone>::iterator it;
361         for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
362                 LeafBone& leaf = *it;
363
364                 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, leaf.name);
365                 if (pchan) {
366                         pchan->custom = get_empty_for_leaves();
367                 }
368                 else {
369                         fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
370                 }
371         }
372 }
373
374 void ArmatureImporter::set_euler_rotmode()
375 {
376         // just set rotmode = ROT_MODE_EUL on pose channel for each joint
377
378         std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>::iterator it;
379
380         for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
381
382                 COLLADAFW::Node *joint = it->second;
383
384                 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
385
386                 for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
387                         SkinInfo& skin = sit->second;
388
389                         if (skin.uses_joint_or_descendant(joint)) {
390                                 bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
391
392                                 if (pchan) {
393                                         pchan->rotmode = ROT_MODE_EUL;
394                                 }
395                                 else {
396                                         fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
397                                 }
398
399                                 break;
400                         }
401                 }
402         }
403 }
404 #endif
405
406 Object *ArmatureImporter::get_empty_for_leaves()
407 {
408         if (empty) return empty;
409
410         empty = bc_add_object(m_bmain, scene, view_layer, OB_EMPTY, NULL);
411         empty->empty_drawtype = OB_EMPTY_SPHERE;
412
413         return empty;
414 }
415
416 #if 0
417 Object *ArmatureImporter::find_armature(COLLADAFW::Node *node)
418 {
419         JointData *jd = get_joint_data(node);
420         if (jd) return jd->ob_arm;
421
422         COLLADAFW::NodePointerArray& children = node->getChildNodes();
423         for (int i = 0; i < children.getCount(); i++) {
424                 Object *ob_arm = find_armature(children[i]);
425                 if (ob_arm) return ob_arm;
426         }
427
428         return NULL;
429 }
430
431 ArmatureJoints& ArmatureImporter::get_armature_joints(Object *ob_arm)
432 {
433         // try finding it
434         std::vector<ArmatureJoints>::iterator it;
435         for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
436                 if ((*it).ob_arm == ob_arm) return *it;
437         }
438
439         // not found, create one
440         ArmatureJoints aj;
441         aj.ob_arm = ob_arm;
442         armature_joints.push_back(aj);
443
444         return armature_joints.back();
445 }
446 #endif
447 void ArmatureImporter::create_armature_bones(Main *bmain, std::vector<Object *> &ob_arms)
448 {
449         std::vector<COLLADAFW::Node *>::iterator ri;
450         std::vector<std::string> layer_labels;
451
452         //if there is an armature created for root_joint next root_joint
453         for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
454                 if (get_armature_for_joint(*ri) != NULL) continue;
455
456                 Object *ob_arm = joint_parent_map[(*ri)->getUniqueId()];
457                 if (!ob_arm)
458                         continue;
459
460                 bArmature *armature = (bArmature *)ob_arm->data;
461                 if (!armature)
462                         continue;
463
464                 char *bone_name = (char *)bc_get_joint_name(*ri);
465                 Bone *bone = BKE_armature_find_bone_name(armature, bone_name);
466                 if (bone) {
467                         fprintf(stderr, "Reuse of child bone [%s] as root bone in same Armature is not supported.\n", bone_name);
468                         continue;
469                 }
470
471                 ED_armature_to_edit(armature);
472                 armature->layer = 0; // layer is set according to imported bone set in create_bone()
473
474                 create_bone(NULL, *ri , NULL, (*ri)->getChildNodes().getCount(), NULL, armature, layer_labels);
475                 if (this->import_settings->find_chains) {
476                         connect_bone_chains(armature, (Bone *)armature->bonebase.first, UNLIMITED_CHAIN_MAX);
477                 }
478
479                 /* exit armature edit mode to populate the Armature object */
480                 ED_armature_from_edit(bmain, armature);
481                 ED_armature_edit_free(armature);
482
483                 ED_armature_to_edit(armature);
484
485                 fix_leaf_bone_hierarchy(armature, (Bone *)armature->bonebase.first, this->import_settings->fix_orientation);
486                 unskinned_armature_map[(*ri)->getUniqueId()] = ob_arm;
487
488                 ED_armature_from_edit(bmain, armature);
489                 ED_armature_edit_free(armature);
490
491                 int index = std::find(ob_arms.begin(), ob_arms.end(), ob_arm) - ob_arms.begin();
492                 if (index == 0) {
493                         ob_arms.push_back(ob_arm);
494                 }
495
496                 DEG_id_tag_update(&ob_arm->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
497         }
498 }
499
500 Object *ArmatureImporter::create_armature_bones(Main *bmain, SkinInfo& skin)
501 {
502         // just do like so:
503         // - get armature
504         // - enter editmode
505         // - add edit bones and head/tail properties using matrices and parent-child info
506         // - exit edit mode
507         // - set a sphere shape to leaf bones
508
509         Object *ob_arm = NULL;
510
511         /*
512          * find if there's another skin sharing at least one bone with this skin
513          * if so, use that skin's armature
514          */
515
516         /**
517          * Pseudocode:
518          *
519          * find_node_in_tree(node, root_joint)
520          *
521          * skin::find_root_joints(root_joints):
522          *     std::vector root_joints;
523          *     for each root in root_joints:
524          *         for each joint in joints:
525          *             if find_node_in_tree(joint, root):
526          *                 if (std::find(root_joints.begin(), root_joints.end(), root) == root_joints.end())
527          *                     root_joints.push_back(root);
528          *
529          * for (each skin B with armature) {
530          *     find all root joints for skin B
531          *
532          *     for each joint X in skin A:
533          *         for each root joint R in skin B:
534          *             if (find_node_in_tree(X, R)) {
535          *                 shared = 1;
536          *                 goto endloop;
537          *             }
538          * }
539          *
540          * endloop:
541          */
542
543         SkinInfo *a = &skin;
544         Object *shared = NULL;
545         std::vector<COLLADAFW::Node *> skin_root_joints;
546         std::vector<std::string> layer_labels;
547
548         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
549         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
550                 SkinInfo *b = &it->second;
551                 if (b == a || b->BKE_armature_from_object() == NULL)
552                         continue;
553
554                 skin_root_joints.clear();
555
556                 b->find_root_joints(root_joints, joint_by_uid, skin_root_joints);
557
558                 std::vector<COLLADAFW::Node *>::iterator ri;
559                 for (ri = skin_root_joints.begin(); ri != skin_root_joints.end(); ri++) {
560                         if (a->uses_joint_or_descendant(*ri)) {
561                                 shared = b->BKE_armature_from_object();
562                                 break;
563                         }
564                 }
565
566                 if (shared != NULL)
567                         break;
568         }
569
570         if (!shared && this->joint_parent_map.size() > 0) {
571                 // All armatures have been created while creating the Node tree.
572                 // The Collada exporter currently does not create a
573                 // strict relationship between geometries and armatures
574                 // So when we reimport a Blender collada file, then we have
575                 // to guess what is meant.
576                 // XXX This is not safe when we have more than one armatures
577                 // in the import.
578                 shared = this->joint_parent_map.begin()->second;
579         }
580
581         if (shared) {
582                 ob_arm = skin.set_armature(shared);
583         }
584         else {
585                 ob_arm = skin.create_armature(m_bmain, scene, view_layer);  //once for every armature
586         }
587
588         // enter armature edit mode
589         bArmature *armature = (bArmature *)ob_arm->data;
590         ED_armature_to_edit(armature);
591
592         totbone = 0;
593         // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
594
595         // create bones
596         /*
597            TODO:
598            check if bones have already been created for a given joint
599          */
600
601         std::vector<COLLADAFW::Node *>::iterator ri;
602         for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
603                 // for shared armature check if bone tree is already created
604                 if (shared && std::find(skin_root_joints.begin(), skin_root_joints.end(), *ri) != skin_root_joints.end())
605                         continue;
606
607                 // since root_joints may contain joints for multiple controllers, we need to filter
608                 if (skin.uses_joint_or_descendant(*ri)) {
609
610                         create_bone(&skin, *ri, NULL, (*ri)->getChildNodes().getCount(), NULL, armature, layer_labels);
611
612                         if (joint_parent_map.find((*ri)->getUniqueId()) != joint_parent_map.end() && !skin.get_parent())
613                                 skin.set_parent(joint_parent_map[(*ri)->getUniqueId()]);
614                 }
615         }
616
617         /* exit armature edit mode to populate the Armature object */
618         ED_armature_from_edit(bmain, armature);
619         ED_armature_edit_free(armature);
620
621         ED_armature_to_edit(armature);
622         if (this->import_settings->find_chains) {
623                 connect_bone_chains(armature, (Bone *)armature->bonebase.first, UNLIMITED_CHAIN_MAX);
624         }
625         fix_leaf_bone_hierarchy(armature, (Bone *)armature->bonebase.first, this->import_settings->fix_orientation);
626         ED_armature_from_edit(bmain, armature);
627         ED_armature_edit_free(armature);
628
629         DEG_id_tag_update(&ob_arm->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
630
631         return ob_arm;
632 }
633
634 void ArmatureImporter::set_pose(Object *ob_arm,  COLLADAFW::Node *root_node, const char *parentname, float parent_mat[4][4])
635 {
636         const char *bone_name = bc_get_joint_name(root_node);
637         float mat[4][4];
638         float obmat[4][4];
639
640         // object-space
641         get_node_mat(obmat, root_node, NULL, NULL);
642
643         //if (*edbone)
644         bPoseChannel *pchan  = BKE_pose_channel_find_name(ob_arm->pose, bone_name);
645         //else fprintf ( "",
646
647         // get world-space
648         if (parentname) {
649                 mul_m4_m4m4(mat, parent_mat, obmat);
650                 bPoseChannel *parchan = BKE_pose_channel_find_name(ob_arm->pose, parentname);
651
652                 mul_m4_m4m4(pchan->pose_mat, parchan->pose_mat, mat);
653
654         }
655         else {
656
657                 copy_m4_m4(mat, obmat);
658                 float invObmat[4][4];
659                 invert_m4_m4(invObmat, ob_arm->obmat);
660                 mul_m4_m4m4(pchan->pose_mat, invObmat, mat);
661
662         }
663
664         //float angle = 0.0f;
665         ///*mat4_to_axis_angle(ax, &angle, mat);
666         //pchan->bone->roll = angle;*/
667
668
669         COLLADAFW::NodePointerArray& children = root_node->getChildNodes();
670         for (unsigned int i = 0; i < children.getCount(); i++) {
671                 set_pose(ob_arm, children[i], bone_name, mat);
672         }
673
674 }
675
676 /**
677   * root - if this joint is the top joint in hierarchy, if a joint
678   * is a child of a node (not joint), root should be true since
679   * this is where we build armature bones from
680   **/
681 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node, Object *parent)
682 {
683         root_joints.push_back(node);
684         if (parent) {
685                 joint_parent_map[node->getUniqueId()] = parent;
686         }
687 }
688
689 #if 0
690 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node)
691 {
692         // root_joints.push_back(node);
693         Object *ob_arm = find_armature(node);
694         if (ob_arm) {
695                 get_armature_joints(ob_arm).root_joints.push_back(node);
696         }
697 #ifdef COLLADA_DEBUG
698         else {
699                 fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
700         }
701 #endif
702 }
703 #endif
704
705 // here we add bones to armatures, having armatures previously created in write_controller
706 void ArmatureImporter::make_armatures(bContext *C, std::vector<Object *> &objects_to_scale)
707 {
708         Main *bmain = CTX_data_main(C);
709         std::vector<Object *> ob_arms;
710         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
711
712         leaf_bone_length = FLT_MAX; /*TODO: Make this work for more than one armature in the import file*/
713
714         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
715
716                 SkinInfo& skin = it->second;
717
718                 Object *ob_arm = create_armature_bones(bmain, skin);
719
720                 // link armature with a mesh object
721                 const COLLADAFW::UniqueId &uid = skin.get_controller_uid();
722                 const COLLADAFW::UniqueId *guid = get_geometry_uid(uid);
723                 if (guid != NULL) {
724                         Object *ob = mesh_importer->get_object_by_geom_uid(*guid);
725                         if (ob) {
726                                 skin.link_armature(C, ob, joint_by_uid, this);
727
728                                 std::vector<Object *>::iterator ob_it = std::find(objects_to_scale.begin(), objects_to_scale.end(), ob);
729
730                                 if (ob_it != objects_to_scale.end()) {
731                                         int index = ob_it - objects_to_scale.begin();
732                                         objects_to_scale.erase(objects_to_scale.begin() + index);
733                                 }
734
735                                 if (std::find(objects_to_scale.begin(), objects_to_scale.end(), ob_arm) == objects_to_scale.end()) {
736                                         objects_to_scale.push_back(ob_arm);
737                                 }
738
739                                 if (std::find(ob_arms.begin(), ob_arms.end(), ob_arm) == ob_arms.end()) {
740                                         ob_arms.push_back(ob_arm);
741                                 }
742                         }
743                         else
744                                 fprintf(stderr, "Cannot find object to link armature with.\n");
745                 }
746                 else
747                         fprintf(stderr, "Cannot find geometry to link armature with.\n");
748
749                 // set armature parent if any
750                 Object *par = skin.get_parent();
751                 if (par)
752                         bc_set_parent(skin.BKE_armature_from_object(), par, C, false);
753
754                 // free memory stolen from SkinControllerData
755                 skin.free();
756         }
757
758         //for bones without skins
759         create_armature_bones(bmain, ob_arms);
760
761         // Fix bone relations
762         std::vector<Object *>::iterator ob_arm_it;
763         for (ob_arm_it = ob_arms.begin(); ob_arm_it != ob_arms.end(); ob_arm_it++) {
764
765                 Object *ob_arm = *ob_arm_it;
766                 bArmature *armature = (bArmature *)ob_arm->data;
767
768                 /* and step back to edit mode to fix the leaf nodes */
769                 ED_armature_to_edit(armature);
770
771                 fix_parent_connect(armature, (Bone *)armature->bonebase.first);
772
773                 ED_armature_from_edit(bmain, armature);
774                 ED_armature_edit_free(armature);
775         }
776 }
777
778 #if 0
779 // link with meshes, create vertex groups, assign weights
780 void ArmatureImporter::link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
781 {
782         Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
783
784         if (!ob) {
785                 fprintf(stderr, "Cannot find object by geometry UID.\n");
786                 return;
787         }
788
789         if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
790                 fprintf(stderr, "Cannot find skin info by controller data UID.\n");
791                 return;
792         }
793
794         SkinInfo& skin = skin_by_data_uid[conroller_data_id];
795
796         // create vertex groups
797 }
798 #endif
799
800 bool ArmatureImporter::write_skin_controller_data(const COLLADAFW::SkinControllerData *data)
801 {
802         // at this stage we get vertex influence info that should go into me->verts and ob->defbase
803         // there's no info to which object this should be long so we associate it with skin controller data UID
804
805         // don't forget to call defgroup_unique_name before we copy
806
807         // controller data uid -> [armature] -> joint data,
808         // [mesh object]
809         //
810
811         SkinInfo skin(unit_converter);
812         skin.borrow_skin_controller_data(data);
813
814         // store join inv bind matrix to use it later in armature construction
815         const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
816         for (unsigned int i = 0; i < data->getJointsCount(); i++) {
817                 skin.add_joint(inv_bind_mats[i]);
818         }
819
820         skin_by_data_uid[data->getUniqueId()] = skin;
821
822         return true;
823 }
824
825 bool ArmatureImporter::write_controller(const COLLADAFW::Controller *controller)
826 {
827         // - create and store armature object
828         const COLLADAFW::UniqueId& con_id = controller->getUniqueId();
829
830         if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
831                 COLLADAFW::SkinController *co = (COLLADAFW::SkinController *)controller;
832                 // to be able to find geom id by controller id
833                 geom_uid_by_controller_uid[con_id] = co->getSource();
834
835                 const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
836                 if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
837                         fprintf(stderr, "Cannot find skin by controller data UID.\n");
838                         return true;
839                 }
840
841                 skin_by_data_uid[data_uid].set_controller(co);
842         }
843         // morph controller
844         else if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_MORPH) {
845                 COLLADAFW::MorphController *co = (COLLADAFW::MorphController *)controller;
846                 // to be able to find geom id by controller id
847                 geom_uid_by_controller_uid[con_id] = co->getSource();
848                 //Shape keys are applied in DocumentImporter->finish()
849                 morph_controllers.push_back(co);
850         }
851
852         return true;
853 }
854
855 void ArmatureImporter::make_shape_keys(bContext *C)
856 {
857         Main *bmain = CTX_data_main(C);
858         std::vector<COLLADAFW::MorphController *>::iterator mc;
859         float weight;
860
861         for (mc = morph_controllers.begin(); mc != morph_controllers.end(); mc++) {
862                 //Controller data
863                 COLLADAFW::UniqueIdArray& morphTargetIds = (*mc)->getMorphTargets();
864                 COLLADAFW::FloatOrDoubleArray& morphWeights = (*mc)->getMorphWeights();
865
866                 //Prereq: all the geometries must be imported and mesh objects must be made
867                 Object *source_ob = this->mesh_importer->get_object_by_geom_uid((*mc)->getSource());
868
869                 if (source_ob) {
870
871                         Mesh *source_me = (Mesh *)source_ob->data;
872                         //insert key to source mesh
873                         Key *key = source_me->key = BKE_key_add(bmain, (ID *)source_me);
874                         key->type = KEY_RELATIVE;
875                         KeyBlock *kb;
876
877                         //insert basis key
878                         kb = BKE_keyblock_add_ctime(key, "Basis", false);
879                         BKE_keyblock_convert_from_mesh(source_me, key, kb);
880
881                         //insert other shape keys
882                         for (int i = 0 ; i < morphTargetIds.getCount() ; i++ ) {
883                                 //better to have a separate map of morph objects,
884                                 //This'll do for now since only mesh morphing is imported
885
886                                 Mesh *me = this->mesh_importer->get_mesh_by_geom_uid(morphTargetIds[i]);
887
888                                 if (me) {
889                                         me->key = key;
890                                         std::string morph_name = *this->mesh_importer->get_geometry_name(me->id.name);
891
892                                         kb = BKE_keyblock_add_ctime(key, morph_name.c_str(), false);
893                                         BKE_keyblock_convert_from_mesh(me, key, kb);
894
895                                         //apply weights
896                                         weight =  morphWeights.getFloatValues()->getData()[i];
897                                         kb->curval = weight;
898                                 }
899                                 else {
900                                         fprintf(stderr, "Morph target geometry not found.\n");
901                                 }
902                         }
903                 }
904                 else {
905                         fprintf(stderr, "Morph target object not found.\n");
906                 }
907         }
908 }
909
910
911 COLLADAFW::UniqueId *ArmatureImporter::get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
912 {
913         if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
914                 return NULL;
915
916         return &geom_uid_by_controller_uid[controller_uid];
917 }
918
919 Object *ArmatureImporter::get_armature_for_joint(COLLADAFW::Node *node)
920 {
921         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
922         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
923                 SkinInfo& skin = it->second;
924
925                 if (skin.uses_joint_or_descendant(node))
926                         return skin.BKE_armature_from_object();
927         }
928
929         std::map<COLLADAFW::UniqueId, Object *>::iterator arm;
930         for (arm = unskinned_armature_map.begin(); arm != unskinned_armature_map.end(); arm++) {
931                 if (arm->first == node->getUniqueId() )
932                         return arm->second;
933         }
934         return NULL;
935 }
936
937 void ArmatureImporter::set_tags_map(TagsMap & tagsMap)
938 {
939         this->uid_tags_map = tagsMap;
940 }
941
942 void ArmatureImporter::get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
943 {
944         BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", bc_get_joint_name(node));
945 }
946
947 // gives a world-space mat
948 bool ArmatureImporter::get_joint_bind_mat(float m[4][4], COLLADAFW::Node *joint)
949 {
950         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
951         bool found = false;
952         for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
953                 SkinInfo& skin = it->second;
954                 if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {
955                         invert_m4(m);
956                         break;
957                 }
958         }
959
960         return found;
961 }
962
963 BoneExtended &ArmatureImporter::add_bone_extended(EditBone *bone, COLLADAFW::Node *node, int sibcount, std::vector<std::string> &layer_labels, BoneExtensionMap &extended_bones)
964 {
965         BoneExtended *be = new BoneExtended(bone);
966         extended_bones[bone->name] = be;
967
968         TagsMap::iterator etit;
969         ExtraTags *et = 0;
970         etit = uid_tags_map.find(node->getUniqueId().toAscii());
971
972         bool has_connect = false;
973         int connect_type = -1;
974
975         if (etit != uid_tags_map.end()) {
976
977                 float tail[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
978                 float roll = 0;
979                 std::string layers;
980
981                 et = etit->second;
982
983                 bool has_tail = false;
984                 has_tail |= et->setData("tip_x", &tail[0]);
985                 has_tail |= et->setData("tip_y", &tail[1]);
986                 has_tail |= et->setData("tip_z", &tail[2]);
987
988                 has_connect   = et->setData("connect", &connect_type);
989                 bool has_roll = et->setData("roll", &roll);
990
991                 layers = et->setData("layer", layers);
992
993                 if (has_tail && !has_connect)
994                 {
995                         /* got a bone tail definition but no connect info -> bone is not connected */
996                         has_connect  = true;
997                         connect_type = 0;
998                 }
999
1000                 be->set_bone_layers(layers, layer_labels);
1001                 if (has_tail) be->set_tail(tail);
1002                 if (has_roll) be->set_roll(roll);
1003         }
1004
1005         if (!has_connect && this->import_settings->auto_connect) {
1006                 /* auto connect only whyen parent has exactly one child*/
1007                 connect_type = sibcount == 1;
1008         }
1009
1010         be->set_use_connect(connect_type);
1011         be->set_leaf_bone(true);
1012
1013         return *be;
1014 }