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