2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory, Sukhitha jayathilake.
20 * ***** END GPL LICENSE BLOCK *****
23 /** \file blender/collada/ArmatureImporter.cpp
28 /* COLLADABU_ASSERT, may be able to remove later */
29 #include "COLLADABUPlatform.h"
33 #include "COLLADAFWUniqueId.h"
35 #include "BKE_action.h"
36 #include "BKE_depsgraph.h"
37 #include "BKE_object.h"
38 #include "BKE_armature.h"
39 #include "BLI_string.h"
40 #include "ED_armature.h"
42 #include "ArmatureImporter.h"
44 // use node name, or fall back to original id if not present (name is optional)
46 static const char *bc_get_joint_name(T *node)
48 const std::string& id = node->getName();
49 return id.size() ? id.c_str() : node->getOriginalId().c_str();
52 ArmatureImporter::ArmatureImporter(UnitConverter *conv, MeshImporterBase *mesh, AnimationImporterBase *anim, Scene *sce) :
53 TransformReader(conv), scene(sce), empty(NULL), mesh_importer(mesh), anim_importer(anim) {}
55 ArmatureImporter::~ArmatureImporter()
57 // free skin controller data if we forget to do this earlier
58 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
59 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
65 JointData *ArmatureImporter::get_joint_data(COLLADAFW::Node *node);
67 const COLLADAFW::UniqueId& joint_id = node->getUniqueId();
69 if (joint_id_to_joint_index_map.find(joint_id) == joint_id_to_joint_index_map.end()) {
70 fprintf(stderr, "Cannot find a joint index by joint id for %s.\n",
71 node->getOriginalId().c_str());
75 int joint_index = joint_id_to_joint_index_map[joint_id];
77 return &joint_index_to_joint_info_map[joint_index];
80 void ArmatureImporter::create_unskinned_bone( COLLADAFW::Node *node, EditBone *parent, int totchild,
81 float parent_mat[][4], Object * ob_arm)
83 std::vector<COLLADAFW::Node*>::iterator it;
84 it = std::find(finished_joints.begin(),finished_joints.end(),node);
85 if ( it != finished_joints.end()) return;
91 get_node_mat(obmat, node, NULL, NULL);
93 EditBone *bone = ED_armature_edit_bone_add((bArmature*)ob_arm->data, (char*)bc_get_joint_name(node));
96 if (parent) bone->parent = parent;
102 mul_m4_m4m4(mat, obmat, parent_mat);
106 copy_m4_m4(mat, obmat);
109 float loc[3], size[3], rot[3][3];
110 mat4_to_loc_rot_size( loc, rot, size, obmat);
111 mat3_to_vec_roll(rot, NULL, &angle );
114 copy_v3_v3(bone->head, mat[3]);
117 // set tail, don't set it to head because 0-length bones are not allowed
118 float vec[3] = {0.0f, 0.5f, 0.0f};
119 add_v3_v3v3(bone->tail, bone->head, vec);
122 if (parent && totchild == 1) {
123 copy_v3_v3(parent->tail, bone->head);
125 // not setting BONE_CONNECTED because this would lock child bone location with respect to parent
126 // bone->flag |= BONE_CONNECTED;
128 // XXX increase this to prevent "very" small bones?
129 const float epsilon = 0.000001f;
131 // derive leaf bone length
132 float length = len_v3v3(parent->head, parent->tail);
133 if ((length < leaf_bone_length || totbone == 0) && length > epsilon) {
134 leaf_bone_length = length;
137 // treat zero-sized bone like a leaf bone
138 if (length <= epsilon) {
139 add_leaf_bone(parent_mat, parent, node);
144 COLLADAFW::NodePointerArray& children = node->getChildNodes();
145 for (unsigned int i = 0; i < children.getCount(); i++) {
146 create_unskinned_bone( children[i], bone, children.getCount(), mat, ob_arm);
149 // in second case it's not a leaf bone, but we handle it the same way
150 if (!children.getCount() || children.getCount() > 1) {
151 add_leaf_bone(mat, bone, node);
154 finished_joints.push_back(node);
158 void ArmatureImporter::create_bone(SkinInfo& skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
159 float parent_mat[][4], bArmature *arm)
161 //Checking if bone is already made.
162 std::vector<COLLADAFW::Node*>::iterator it;
163 it = std::find(finished_joints.begin(),finished_joints.end(),node);
164 if ( it != finished_joints.end()) return;
166 float joint_inv_bind_mat[4][4];
168 // JointData* jd = get_joint_data(node);
172 // TODO rename from Node "name" attrs later
173 EditBone *bone = ED_armature_edit_bone_add(arm, (char*)bc_get_joint_name(node));
176 if (skin.get_joint_inv_bind_matrix(joint_inv_bind_mat, node)) {
177 // get original world-space matrix
178 invert_m4_m4(mat, joint_inv_bind_mat);
180 // create a bone even if there's no joint data for it (i.e. it has no influence)
185 get_node_mat(obmat, node, NULL, NULL);
189 mul_m4_m4m4(mat, obmat, parent_mat);
191 copy_m4_m4(mat, obmat);
193 float loc[3], size[3], rot[3][3] , angle;
194 mat4_to_loc_rot_size( loc, rot, size, obmat);
195 mat3_to_vec_roll(rot, NULL, &angle );
200 if (parent) bone->parent = parent;
203 copy_v3_v3(bone->head, mat[3]);
205 // set tail, don't set it to head because 0-length bones are not allowed
206 float vec[3] = {0.0f, 0.5f, 0.0f};
207 add_v3_v3v3(bone->tail, bone->head, vec);
210 if (parent && totchild == 1) {
211 copy_v3_v3(parent->tail, bone->head);
213 // not setting BONE_CONNECTED because this would lock child bone location with respect to parent
214 // bone->flag |= BONE_CONNECTED;
216 // XXX increase this to prevent "very" small bones?
217 const float epsilon = 0.000001f;
219 // derive leaf bone length
220 float length = len_v3v3(parent->head, parent->tail);
221 if ((length < leaf_bone_length || totbone == 0) && length > epsilon) {
222 leaf_bone_length = length;
225 // treat zero-sized bone like a leaf bone
226 if (length <= epsilon) {
227 add_leaf_bone(parent_mat, parent, node);
232 // and which row in mat is bone direction
234 sub_v3_v3v3(vec, parent->tail, parent->head);
236 print_v3("tail - head", vec);
237 print_m4("matrix", parent_mat);
239 for (int i = 0; i < 3; i++) {
241 char *axis_names[] = {"X", "Y", "Z"};
242 printf("%s-axis length is %f\n", axis_names[i], len_v3(parent_mat[i]));
244 float angle = angle_v2v2(vec, parent_mat[i]);
245 if (angle < min_angle) {
247 print_v3("picking", parent_mat[i]);
248 printf("^ %s axis of %s's matrix\n", axis_names[i], get_dae_name(node));
250 bone_direction_row = i;
258 COLLADAFW::NodePointerArray& children = node->getChildNodes();
259 for (unsigned int i = 0; i < children.getCount(); i++) {
260 create_bone(skin, children[i], bone, children.getCount(), mat, arm);
263 // in second case it's not a leaf bone, but we handle it the same way
264 if (!children.getCount() || children.getCount() > 1) {
265 add_leaf_bone(mat, bone , node);
268 finished_joints.push_back(node);
271 void ArmatureImporter::add_leaf_bone(float mat[][4], EditBone *bone, COLLADAFW::Node * node)
276 copy_m4_m4(leaf.mat, mat);
277 BLI_strncpy(leaf.name, bone->name, sizeof(leaf.name));
279 TagsMap::iterator etit;
281 etit = uid_tags_map.find(node->getUniqueId().toAscii());
282 if(etit != uid_tags_map.end())
288 et->setData("tip_x",&x);
289 et->setData("tip_y",&y);
290 et->setData("tip_z",&z);
291 float vec[3] = {x,y,z};
292 copy_v3_v3(leaf.bone->tail, leaf.bone->head);
293 add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
295 leaf_bones.push_back(leaf);
298 void ArmatureImporter::fix_leaf_bones( )
300 // just setting tail for leaf bones here
302 std::vector<LeafBone>::iterator it;
303 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
304 LeafBone& leaf = *it;
307 float vec[3] = {0.0f, 0.0f, 0.1f};
309 // if parent: take parent length and direction
310 if(leaf.bone->parent) sub_v3_v3v3(vec, leaf.bone->parent->tail, leaf.bone->parent->head);
312 copy_v3_v3(leaf.bone->tail, leaf.bone->head);
313 add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
318 void ArmatureImporter::set_leaf_bone_shapes(Object *ob_arm)
320 bPose *pose = ob_arm->pose;
322 std::vector<LeafBone>::iterator it;
323 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
324 LeafBone& leaf = *it;
326 bPoseChannel *pchan = get_pose_channel(pose, leaf.name);
328 pchan->custom = get_empty_for_leaves();
331 fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
336 void ArmatureImporter::set_euler_rotmode()
338 // just set rotmode = ROT_MODE_EUL on pose channel for each joint
340 std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>::iterator it;
342 for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
344 COLLADAFW::Node *joint = it->second;
346 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
348 for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
349 SkinInfo& skin = sit->second;
351 if (skin.uses_joint_or_descendant(joint)) {
352 bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
355 pchan->rotmode = ROT_MODE_EUL;
358 fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
368 Object *ArmatureImporter::get_empty_for_leaves()
370 if (empty) return empty;
372 empty = add_object(scene, OB_EMPTY);
373 empty->empty_drawtype = OB_EMPTY_SPHERE;
379 Object *ArmatureImporter::find_armature(COLLADAFW::Node *node)
381 JointData* jd = get_joint_data(node);
382 if (jd) return jd->ob_arm;
384 COLLADAFW::NodePointerArray& children = node->getChildNodes();
385 for (int i = 0; i < children.getCount(); i++) {
386 Object *ob_arm = find_armature(children[i]);
387 if (ob_arm) return ob_arm;
393 ArmatureJoints& ArmatureImporter::get_armature_joints(Object *ob_arm)
396 std::vector<ArmatureJoints>::iterator it;
397 for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
398 if ((*it).ob_arm == ob_arm) return *it;
401 // not found, create one
404 armature_joints.push_back(aj);
406 return armature_joints.back();
409 void ArmatureImporter::create_armature_bones( )
411 std::vector<COLLADAFW::Node*>::iterator ri;
412 //if there is an armature created for root_joint next root_joint
413 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
414 if ( get_armature_for_joint(*ri) != NULL ) continue;
416 //add armature object for current joint
417 //Object *ob_arm = add_object(scene, OB_ARMATURE);
419 Object *ob_arm = joint_parent_map[(*ri)->getUniqueId()];
420 //ob_arm->type = OB_ARMATURE;
421 ED_armature_to_edit(ob_arm);
423 // min_angle = 360.0f; // minimum angle between bone head-tail and a row of bone matrix
425 // create unskinned bones
428 check if bones have already been created for a given joint
430 leaf_bone_length = FLT_MAX;
431 create_unskinned_bone(*ri, NULL, (*ri)->getChildNodes().getCount(), NULL, ob_arm);
435 // exit armature edit mode
437 unskinned_armature_map[(*ri)->getUniqueId()] = ob_arm;
439 ED_armature_from_edit(ob_arm);
441 set_pose(ob_arm , *ri, NULL, NULL );
443 ED_armature_edit_free(ob_arm);
444 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
450 void ArmatureImporter::create_armature_bones(SkinInfo& skin)
455 // - add edit bones and head/tail properties using matrices and parent-child info
457 // - set a sphere shape to leaf bones
459 Object *ob_arm = NULL;
462 * find if there's another skin sharing at least one bone with this skin
463 * if so, use that skin's armature
469 find_node_in_tree(node, root_joint)
471 skin::find_root_joints(root_joints):
472 std::vector root_joints;
473 for each root in root_joints:
474 for each joint in joints:
475 if find_node_in_tree(joint, root):
476 if (std::find(root_joints.begin(), root_joints.end(), root) == root_joints.end())
477 root_joints.push_back(root);
479 for (each skin B with armature) {
480 find all root joints for skin B
482 for each joint X in skin A:
483 for each root joint R in skin B:
484 if (find_node_in_tree(X, R)) {
494 Object *shared = NULL;
495 std::vector<COLLADAFW::Node*> skin_root_joints;
497 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
498 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
499 SkinInfo *b = &it->second;
500 if (b == a || b->get_armature() == NULL)
503 skin_root_joints.clear();
505 b->find_root_joints(root_joints, joint_by_uid, skin_root_joints);
507 std::vector<COLLADAFW::Node*>::iterator ri;
508 for (ri = skin_root_joints.begin(); ri != skin_root_joints.end(); ri++) {
509 if (a->uses_joint_or_descendant(*ri)) {
510 shared = b->get_armature();
520 ob_arm = skin.set_armature(shared);
522 ob_arm = skin.create_armature(scene); //once for every armature
524 // enter armature edit mode
525 ED_armature_to_edit(ob_arm);
529 // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
530 leaf_bone_length = FLT_MAX;
531 // min_angle = 360.0f; // minimum angle between bone head-tail and a row of bone matrix
536 check if bones have already been created for a given joint
539 std::vector<COLLADAFW::Node*>::iterator ri;
540 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
541 // for shared armature check if bone tree is already created
542 if (shared && std::find(skin_root_joints.begin(), skin_root_joints.end(), *ri) != skin_root_joints.end())
545 // since root_joints may contain joints for multiple controllers, we need to filter
546 if (skin.uses_joint_or_descendant(*ri)) {
547 create_bone(skin, *ri, NULL, (*ri)->getChildNodes().getCount(), NULL, (bArmature*)ob_arm->data);
549 if (joint_parent_map.find((*ri)->getUniqueId()) != joint_parent_map.end() && !skin.get_parent())
550 skin.set_parent(joint_parent_map[(*ri)->getUniqueId()]);
556 // exit armature edit mode
557 ED_armature_from_edit(ob_arm);
558 ED_armature_edit_free(ob_arm);
559 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
561 // set_leaf_bone_shapes(ob_arm);
562 // set_euler_rotmode();
566 // root - if this joint is the top joint in hierarchy, if a joint
567 // is a child of a node (not joint), root should be true since
568 // this is where we build armature bones from
570 void ArmatureImporter::set_pose ( Object * ob_arm , COLLADAFW::Node * root_node , const char *parentname, float parent_mat[][4])
572 char * bone_name = (char *) bc_get_joint_name ( root_node);
580 get_node_mat(obmat, root_node, NULL, NULL);
583 bPoseChannel * pchan = get_pose_channel(ob_arm -> pose , bone_name);
588 mul_m4_m4m4(mat, obmat, parent_mat);
589 bPoseChannel *parchan = get_pose_channel(ob_arm->pose, parentname);
591 mul_m4_m4m4(pchan->pose_mat, mat , parchan->pose_mat);
595 copy_m4_m4(mat, obmat);
596 float invObmat[4][4];
597 invert_m4_m4(invObmat, ob_arm->obmat);
598 mul_m4_m4m4(pchan->pose_mat, mat, invObmat);
602 mat4_to_axis_angle(ax,&angle,mat);
603 pchan->bone->roll = angle;
606 COLLADAFW::NodePointerArray& children = root_node->getChildNodes();
607 for (unsigned int i = 0; i < children.getCount(); i++) {
608 set_pose(ob_arm, children[i], bone_name, mat);
613 void ArmatureImporter::add_joint(COLLADAFW::Node *node, bool root, Object *parent, Scene *sce)
615 joint_by_uid[node->getUniqueId()] = node;
617 root_joints.push_back(node);
621 joint_parent_map[node->getUniqueId()] = parent;
627 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node)
629 // root_joints.push_back(node);
630 Object *ob_arm = find_armature(node);
632 get_armature_joints(ob_arm).root_joints.push_back(node);
636 fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
642 // here we add bones to armatures, having armatures previously created in write_controller
643 void ArmatureImporter::make_armatures(bContext *C)
645 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
646 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
648 SkinInfo& skin = it->second;
650 create_armature_bones(skin);
652 // link armature with a mesh object
653 Object *ob = mesh_importer->get_object_by_geom_uid(*get_geometry_uid(skin.get_controller_uid()));
655 skin.link_armature(C, ob, joint_by_uid, this);
657 fprintf(stderr, "Cannot find object to link armature with.\n");
659 // set armature parent if any
660 Object *par = skin.get_parent();
662 bc_set_parent(skin.get_armature(), par, C, false);
664 // free memory stolen from SkinControllerData
668 //for bones without skins
669 create_armature_bones();
673 // link with meshes, create vertex groups, assign weights
674 void ArmatureImporter::link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
676 Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
679 fprintf(stderr, "Cannot find object by geometry UID.\n");
683 if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
684 fprintf(stderr, "Cannot find skin info by controller data UID.\n");
688 SkinInfo& skin = skin_by_data_uid[conroller_data_id];
690 // create vertex groups
694 bool ArmatureImporter::write_skin_controller_data(const COLLADAFW::SkinControllerData* data)
696 // at this stage we get vertex influence info that should go into me->verts and ob->defbase
697 // there's no info to which object this should be long so we associate it with skin controller data UID
699 // don't forget to call defgroup_unique_name before we copy
701 // controller data uid -> [armature] -> joint data,
705 SkinInfo skin(unit_converter);
706 skin.borrow_skin_controller_data(data);
708 // store join inv bind matrix to use it later in armature construction
709 const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
710 for (unsigned int i = 0; i < data->getJointsCount(); i++) {
711 skin.add_joint(inv_bind_mats[i]);
714 skin_by_data_uid[data->getUniqueId()] = skin;
719 bool ArmatureImporter::write_controller(const COLLADAFW::Controller* controller)
721 // - create and store armature object
723 const COLLADAFW::UniqueId& skin_id = controller->getUniqueId();
725 if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
726 COLLADAFW::SkinController *co = (COLLADAFW::SkinController*)controller;
727 // to be able to find geom id by controller id
728 geom_uid_by_controller_uid[skin_id] = co->getSource();
730 const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
731 if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
732 fprintf(stderr, "Cannot find skin by controller data UID.\n");
736 skin_by_data_uid[data_uid].set_controller(co);
741 fprintf(stderr, "Morph controller is not supported yet.\n");
748 COLLADAFW::UniqueId *ArmatureImporter::get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
750 if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
753 return &geom_uid_by_controller_uid[controller_uid];
756 Object *ArmatureImporter::get_armature_for_joint(COLLADAFW::Node *node)
758 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
759 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
760 SkinInfo& skin = it->second;
762 if (skin.uses_joint_or_descendant(node))
763 return skin.get_armature();
766 std::map<COLLADAFW::UniqueId, Object*>::iterator arm;
767 for (arm = unskinned_armature_map.begin(); arm != unskinned_armature_map.end(); arm++) {
768 if(arm->first == node->getUniqueId() )
774 void ArmatureImporter::set_tags_map(TagsMap & tagsMap)
776 this->uid_tags_map = tagsMap;
779 void ArmatureImporter::get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
781 BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", bc_get_joint_name(node));
784 // gives a world-space mat
785 bool ArmatureImporter::get_joint_bind_mat(float m[][4], COLLADAFW::Node *joint)
787 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
789 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
790 SkinInfo& skin = it->second;
791 if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {