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