4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory, Sukhitha jayathilake.
22 * ***** END GPL LICENSE BLOCK *****
25 /** \file blender/collada/ArmatureImporter.cpp
30 /* COLLADABU_ASSERT, may be able to remove later */
31 #include "COLLADABUPlatform.h"
35 #include "COLLADAFWUniqueId.h"
37 #include "BKE_action.h"
38 #include "BKE_depsgraph.h"
39 #include "BKE_object.h"
40 #include "BKE_armature.h"
41 #include "BLI_string.h"
42 #include "ED_armature.h"
44 #include "ArmatureImporter.h"
46 // use node name, or fall back to original id if not present (name is optional)
48 static const char *bc_get_joint_name(T *node)
50 const std::string& id = node->getName();
51 return id.size() ? id.c_str() : node->getOriginalId().c_str();
54 ArmatureImporter::ArmatureImporter(UnitConverter *conv, MeshImporterBase *mesh, AnimationImporterBase *anim, Scene *sce) :
55 TransformReader(conv), scene(sce), empty(NULL), mesh_importer(mesh), anim_importer(anim) {}
57 ArmatureImporter::~ArmatureImporter()
59 // free skin controller data if we forget to do this earlier
60 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
61 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
67 JointData *ArmatureImporter::get_joint_data(COLLADAFW::Node *node);
69 const COLLADAFW::UniqueId& joint_id = node->getUniqueId();
71 if (joint_id_to_joint_index_map.find(joint_id) == joint_id_to_joint_index_map.end()) {
72 fprintf(stderr, "Cannot find a joint index by joint id for %s.\n",
73 node->getOriginalId().c_str());
77 int joint_index = joint_id_to_joint_index_map[joint_id];
79 return &joint_index_to_joint_info_map[joint_index];
82 void ArmatureImporter::create_unskinned_bone( COLLADAFW::Node *node, EditBone *parent, int totchild,
83 float parent_mat[][4], Object * ob_arm)
85 std::vector<COLLADAFW::Node*>::iterator it;
86 it = std::find(finished_joints.begin(),finished_joints.end(),node);
87 if ( it != finished_joints.end()) return;
93 get_node_mat(obmat, node, NULL, NULL);
95 EditBone *bone = ED_armature_edit_bone_add((bArmature*)ob_arm->data, (char*)bc_get_joint_name(node));
98 bPoseChannel *pchan = get_pose_channel(ob_arm->pose, (char*)bc_get_joint_name(node));
100 if (parent) bone->parent = parent;
106 mul_m4_m4m4(mat, obmat, parent_mat);
110 copy_m4_m4(mat, obmat);
113 float loc[3], size[3], rot[3][3];
114 mat4_to_loc_rot_size( loc, rot, size, obmat);
115 mat3_to_vec_roll(rot, NULL, &angle );
118 copy_v3_v3(bone->head, mat[3]);
121 // set tail, don't set it to head because 0-length bones are not allowed
122 float vec[3] = {0.0f, 0.5f, 0.0f};
123 add_v3_v3v3(bone->tail, bone->head, vec);
126 if (parent && totchild == 1) {
127 copy_v3_v3(parent->tail, bone->head);
129 // not setting BONE_CONNECTED because this would lock child bone location with respect to parent
130 // bone->flag |= BONE_CONNECTED;
132 // XXX increase this to prevent "very" small bones?
133 const float epsilon = 0.000001f;
135 // derive leaf bone length
136 float length = len_v3v3(parent->head, parent->tail);
137 if ((length < leaf_bone_length || totbone == 0) && length > epsilon) {
138 leaf_bone_length = length;
141 // treat zero-sized bone like a leaf bone
142 if (length <= epsilon) {
143 add_leaf_bone(parent_mat, parent, node);
148 COLLADAFW::NodePointerArray& children = node->getChildNodes();
149 for (unsigned int i = 0; i < children.getCount(); i++) {
150 create_unskinned_bone( children[i], bone, children.getCount(), mat, ob_arm);
153 // in second case it's not a leaf bone, but we handle it the same way
154 if (!children.getCount() || children.getCount() > 1) {
155 add_leaf_bone(mat, bone, node);
158 finished_joints.push_back(node);
162 void ArmatureImporter::create_bone(SkinInfo& skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
163 float parent_mat[][4], bArmature *arm)
165 //Checking if bone is already made.
166 std::vector<COLLADAFW::Node*>::iterator it;
167 it = std::find(finished_joints.begin(),finished_joints.end(),node);
168 if ( it != finished_joints.end()) return;
170 float joint_inv_bind_mat[4][4];
172 // JointData* jd = get_joint_data(node);
176 // TODO rename from Node "name" attrs later
177 EditBone *bone = ED_armature_edit_bone_add(arm, (char*)bc_get_joint_name(node));
180 if (skin.get_joint_inv_bind_matrix(joint_inv_bind_mat, node)) {
181 // get original world-space matrix
182 invert_m4_m4(mat, joint_inv_bind_mat);
184 // create a bone even if there's no joint data for it (i.e. it has no influence)
189 get_node_mat(obmat, node, NULL, NULL);
193 mul_m4_m4m4(mat, obmat, parent_mat);
195 copy_m4_m4(mat, obmat);
197 float loc[3], size[3], rot[3][3] , angle;
198 mat4_to_loc_rot_size( loc, rot, size, obmat);
199 mat3_to_vec_roll(rot, NULL, &angle );
204 if (parent) bone->parent = parent;
207 copy_v3_v3(bone->head, mat[3]);
209 // set tail, don't set it to head because 0-length bones are not allowed
210 float vec[3] = {0.0f, 0.5f, 0.0f};
211 add_v3_v3v3(bone->tail, bone->head, vec);
214 if (parent && totchild == 1) {
215 copy_v3_v3(parent->tail, bone->head);
217 // not setting BONE_CONNECTED because this would lock child bone location with respect to parent
218 // bone->flag |= BONE_CONNECTED;
220 // XXX increase this to prevent "very" small bones?
221 const float epsilon = 0.000001f;
223 // derive leaf bone length
224 float length = len_v3v3(parent->head, parent->tail);
225 if ((length < leaf_bone_length || totbone == 0) && length > epsilon) {
226 leaf_bone_length = length;
229 // treat zero-sized bone like a leaf bone
230 if (length <= epsilon) {
231 add_leaf_bone(parent_mat, parent, node);
236 // and which row in mat is bone direction
238 sub_v3_v3v3(vec, parent->tail, parent->head);
240 print_v3("tail - head", vec);
241 print_m4("matrix", parent_mat);
243 for (int i = 0; i < 3; i++) {
245 char *axis_names[] = {"X", "Y", "Z"};
246 printf("%s-axis length is %f\n", axis_names[i], len_v3(parent_mat[i]));
248 float angle = angle_v2v2(vec, parent_mat[i]);
249 if (angle < min_angle) {
251 print_v3("picking", parent_mat[i]);
252 printf("^ %s axis of %s's matrix\n", axis_names[i], get_dae_name(node));
254 bone_direction_row = i;
262 COLLADAFW::NodePointerArray& children = node->getChildNodes();
263 for (unsigned int i = 0; i < children.getCount(); i++) {
264 create_bone(skin, children[i], bone, children.getCount(), mat, arm);
267 // in second case it's not a leaf bone, but we handle it the same way
268 if (!children.getCount() || children.getCount() > 1) {
269 add_leaf_bone(mat, bone , node);
272 finished_joints.push_back(node);
275 void ArmatureImporter::add_leaf_bone(float mat[][4], EditBone *bone, COLLADAFW::Node * node)
280 copy_m4_m4(leaf.mat, mat);
281 BLI_strncpy(leaf.name, bone->name, sizeof(leaf.name));
285 TagsMap::iterator etit;
287 etit = uid_tags_map.find(node->getUniqueId().toAscii());
288 if(etit != uid_tags_map.end())
294 et->setData("tip_x",&x);
295 et->setData("tip_y",&y);
296 et->setData("tip_z",&z);
297 float vec[3] = {x,y,z};
298 copy_v3_v3(leaf.bone->tail, leaf.bone->head);
299 add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
301 leaf_bones.push_back(leaf);
304 void ArmatureImporter::fix_leaf_bones( )
306 // just setting tail for leaf bones here
308 std::vector<LeafBone>::iterator it;
309 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
310 LeafBone& leaf = *it;
313 float vec[3] = {0.0f, 0.0f, 0.1f};
315 // if parent: take parent length and direction
316 if(leaf.bone->parent) sub_v3_v3v3(vec, leaf.bone->parent->tail, leaf.bone->parent->head);
318 copy_v3_v3(leaf.bone->tail, leaf.bone->head);
319 add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
324 void ArmatureImporter::set_leaf_bone_shapes(Object *ob_arm)
326 bPose *pose = ob_arm->pose;
328 std::vector<LeafBone>::iterator it;
329 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
330 LeafBone& leaf = *it;
332 bPoseChannel *pchan = get_pose_channel(pose, leaf.name);
334 pchan->custom = get_empty_for_leaves();
337 fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
342 void ArmatureImporter::set_euler_rotmode()
344 // just set rotmode = ROT_MODE_EUL on pose channel for each joint
346 std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>::iterator it;
348 for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
350 COLLADAFW::Node *joint = it->second;
352 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
354 for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
355 SkinInfo& skin = sit->second;
357 if (skin.uses_joint_or_descendant(joint)) {
358 bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
361 pchan->rotmode = ROT_MODE_EUL;
364 fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
374 Object *ArmatureImporter::get_empty_for_leaves()
376 if (empty) return empty;
378 empty = add_object(scene, OB_EMPTY);
379 empty->empty_drawtype = OB_EMPTY_SPHERE;
385 Object *ArmatureImporter::find_armature(COLLADAFW::Node *node)
387 JointData* jd = get_joint_data(node);
388 if (jd) return jd->ob_arm;
390 COLLADAFW::NodePointerArray& children = node->getChildNodes();
391 for (int i = 0; i < children.getCount(); i++) {
392 Object *ob_arm = find_armature(children[i]);
393 if (ob_arm) return ob_arm;
399 ArmatureJoints& ArmatureImporter::get_armature_joints(Object *ob_arm)
402 std::vector<ArmatureJoints>::iterator it;
403 for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
404 if ((*it).ob_arm == ob_arm) return *it;
407 // not found, create one
410 armature_joints.push_back(aj);
412 return armature_joints.back();
415 void ArmatureImporter::create_armature_bones( )
417 std::vector<COLLADAFW::Node*>::iterator ri;
418 //if there is an armature created for root_joint next root_joint
419 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
420 if ( get_armature_for_joint(*ri) != NULL ) continue;
422 //add armature object for current joint
423 //Object *ob_arm = add_object(scene, OB_ARMATURE);
425 Object *ob_arm = joint_parent_map[(*ri)->getUniqueId()];
426 //ob_arm->type = OB_ARMATURE;
427 ED_armature_to_edit(ob_arm);
429 // min_angle = 360.0f; // minimum angle between bone head-tail and a row of bone matrix
431 // create unskinned bones
434 check if bones have already been created for a given joint
436 leaf_bone_length = FLT_MAX;
437 create_unskinned_bone(*ri, NULL, (*ri)->getChildNodes().getCount(), NULL, ob_arm);
441 // exit armature edit mode
443 unskinned_armature_map[(*ri)->getUniqueId()] = ob_arm;
445 ED_armature_from_edit(ob_arm);
447 set_pose(ob_arm , *ri, NULL, NULL );
449 ED_armature_edit_free(ob_arm);
450 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
456 void ArmatureImporter::create_armature_bones(SkinInfo& skin)
461 // - add edit bones and head/tail properties using matrices and parent-child info
463 // - set a sphere shape to leaf bones
465 Object *ob_arm = NULL;
468 * find if there's another skin sharing at least one bone with this skin
469 * if so, use that skin's armature
475 find_node_in_tree(node, root_joint)
477 skin::find_root_joints(root_joints):
478 std::vector root_joints;
479 for each root in root_joints:
480 for each joint in joints:
481 if find_node_in_tree(joint, root):
482 if (std::find(root_joints.begin(), root_joints.end(), root) == root_joints.end())
483 root_joints.push_back(root);
485 for (each skin B with armature) {
486 find all root joints for skin B
488 for each joint X in skin A:
489 for each root joint R in skin B:
490 if (find_node_in_tree(X, R)) {
500 Object *shared = NULL;
501 std::vector<COLLADAFW::Node*> skin_root_joints;
503 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
504 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
505 SkinInfo *b = &it->second;
506 if (b == a || b->get_armature() == NULL)
509 skin_root_joints.clear();
511 b->find_root_joints(root_joints, joint_by_uid, skin_root_joints);
513 std::vector<COLLADAFW::Node*>::iterator ri;
514 for (ri = skin_root_joints.begin(); ri != skin_root_joints.end(); ri++) {
515 if (a->uses_joint_or_descendant(*ri)) {
516 shared = b->get_armature();
526 ob_arm = skin.set_armature(shared);
528 ob_arm = skin.create_armature(scene); //once for every armature
530 // enter armature edit mode
531 ED_armature_to_edit(ob_arm);
535 // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
536 leaf_bone_length = FLT_MAX;
537 // min_angle = 360.0f; // minimum angle between bone head-tail and a row of bone matrix
542 check if bones have already been created for a given joint
545 std::vector<COLLADAFW::Node*>::iterator ri;
546 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
547 // for shared armature check if bone tree is already created
548 if (shared && std::find(skin_root_joints.begin(), skin_root_joints.end(), *ri) != skin_root_joints.end())
551 // since root_joints may contain joints for multiple controllers, we need to filter
552 if (skin.uses_joint_or_descendant(*ri)) {
553 create_bone(skin, *ri, NULL, (*ri)->getChildNodes().getCount(), NULL, (bArmature*)ob_arm->data);
555 if (joint_parent_map.find((*ri)->getUniqueId()) != joint_parent_map.end() && !skin.get_parent())
556 skin.set_parent(joint_parent_map[(*ri)->getUniqueId()]);
562 // exit armature edit mode
563 ED_armature_from_edit(ob_arm);
564 ED_armature_edit_free(ob_arm);
565 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
567 // set_leaf_bone_shapes(ob_arm);
568 // set_euler_rotmode();
572 // root - if this joint is the top joint in hierarchy, if a joint
573 // is a child of a node (not joint), root should be true since
574 // this is where we build armature bones from
576 void ArmatureImporter::set_pose ( Object * ob_arm , COLLADAFW::Node * root_node , char *parentname, float parent_mat[][4])
578 char * bone_name = (char *) bc_get_joint_name ( root_node);
582 bArmature * arm = (bArmature * ) ob_arm-> data ;
587 get_node_mat(obmat, root_node, NULL, NULL);
590 bPoseChannel * pchan = get_pose_channel(ob_arm -> pose , bone_name);
595 mul_m4_m4m4(mat, obmat, parent_mat);
596 bPoseChannel *parchan = get_pose_channel(ob_arm->pose, parentname);
598 mul_m4_m4m4(pchan->pose_mat, mat , parchan->pose_mat);
602 copy_m4_m4(mat, obmat);
603 float invObmat[4][4];
604 invert_m4_m4(invObmat, ob_arm->obmat);
605 mul_m4_m4m4(pchan->pose_mat, mat, invObmat);
609 mat4_to_axis_angle(ax,&angle,mat);
610 pchan->bone->roll = angle;
613 COLLADAFW::NodePointerArray& children = root_node->getChildNodes();
614 for (unsigned int i = 0; i < children.getCount(); i++) {
615 set_pose(ob_arm, children[i], bone_name, mat);
620 void ArmatureImporter::add_joint(COLLADAFW::Node *node, bool root, Object *parent, Scene *sce)
622 joint_by_uid[node->getUniqueId()] = node;
624 root_joints.push_back(node);
628 joint_parent_map[node->getUniqueId()] = parent;
634 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node)
636 // root_joints.push_back(node);
637 Object *ob_arm = find_armature(node);
639 get_armature_joints(ob_arm).root_joints.push_back(node);
643 fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
649 // here we add bones to armatures, having armatures previously created in write_controller
650 void ArmatureImporter::make_armatures(bContext *C)
652 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
653 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
655 SkinInfo& skin = it->second;
657 create_armature_bones(skin);
659 // link armature with a mesh object
660 Object *ob = mesh_importer->get_object_by_geom_uid(*get_geometry_uid(skin.get_controller_uid()));
662 skin.link_armature(C, ob, joint_by_uid, this);
664 fprintf(stderr, "Cannot find object to link armature with.\n");
666 // set armature parent if any
667 Object *par = skin.get_parent();
669 bc_set_parent(skin.get_armature(), par, C, false);
671 // free memory stolen from SkinControllerData
675 //for bones without skins
676 create_armature_bones();
680 // link with meshes, create vertex groups, assign weights
681 void ArmatureImporter::link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
683 Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
686 fprintf(stderr, "Cannot find object by geometry UID.\n");
690 if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
691 fprintf(stderr, "Cannot find skin info by controller data UID.\n");
695 SkinInfo& skin = skin_by_data_uid[conroller_data_id];
697 // create vertex groups
701 bool ArmatureImporter::write_skin_controller_data(const COLLADAFW::SkinControllerData* data)
703 // at this stage we get vertex influence info that should go into me->verts and ob->defbase
704 // there's no info to which object this should be long so we associate it with skin controller data UID
706 // don't forget to call defgroup_unique_name before we copy
708 // controller data uid -> [armature] -> joint data,
712 SkinInfo skin(unit_converter);
713 skin.borrow_skin_controller_data(data);
715 // store join inv bind matrix to use it later in armature construction
716 const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
717 for (unsigned int i = 0; i < data->getJointsCount(); i++) {
718 skin.add_joint(inv_bind_mats[i]);
721 skin_by_data_uid[data->getUniqueId()] = skin;
726 bool ArmatureImporter::write_controller(const COLLADAFW::Controller* controller)
728 // - create and store armature object
730 const COLLADAFW::UniqueId& skin_id = controller->getUniqueId();
732 if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
733 COLLADAFW::SkinController *co = (COLLADAFW::SkinController*)controller;
734 // to be able to find geom id by controller id
735 geom_uid_by_controller_uid[skin_id] = co->getSource();
737 const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
738 if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
739 fprintf(stderr, "Cannot find skin by controller data UID.\n");
743 skin_by_data_uid[data_uid].set_controller(co);
748 fprintf(stderr, "Morph controller is not supported yet.\n");
755 COLLADAFW::UniqueId *ArmatureImporter::get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
757 if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
760 return &geom_uid_by_controller_uid[controller_uid];
763 Object *ArmatureImporter::get_armature_for_joint(COLLADAFW::Node *node)
765 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
766 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
767 SkinInfo& skin = it->second;
769 if (skin.uses_joint_or_descendant(node))
770 return skin.get_armature();
773 std::map<COLLADAFW::UniqueId, Object*>::iterator arm;
774 for (arm = unskinned_armature_map.begin(); arm != unskinned_armature_map.end(); arm++) {
775 if(arm->first == node->getUniqueId() )
781 void ArmatureImporter::set_tags_map(TagsMap & tagsMap)
783 this->uid_tags_map = tagsMap;
786 void ArmatureImporter::get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
788 BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", bc_get_joint_name(node));
791 // gives a world-space mat
792 bool ArmatureImporter::get_joint_bind_mat(float m[][4], COLLADAFW::Node *joint)
794 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
796 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
797 SkinInfo& skin = it->second;
798 if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {