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, 1.0f};
315 //mul_v3_fl(vec, leaf_bone_length);
317 copy_v3_v3(leaf.bone->tail, leaf.bone->head);
318 add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
323 void ArmatureImporter::set_leaf_bone_shapes(Object *ob_arm)
325 bPose *pose = ob_arm->pose;
327 std::vector<LeafBone>::iterator it;
328 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
329 LeafBone& leaf = *it;
331 bPoseChannel *pchan = get_pose_channel(pose, leaf.name);
333 pchan->custom = get_empty_for_leaves();
336 fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
341 void ArmatureImporter::set_euler_rotmode()
343 // just set rotmode = ROT_MODE_EUL on pose channel for each joint
345 std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>::iterator it;
347 for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
349 COLLADAFW::Node *joint = it->second;
351 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
353 for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
354 SkinInfo& skin = sit->second;
356 if (skin.uses_joint_or_descendant(joint)) {
357 bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
360 pchan->rotmode = ROT_MODE_EUL;
363 fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
373 Object *ArmatureImporter::get_empty_for_leaves()
375 if (empty) return empty;
377 empty = add_object(scene, OB_EMPTY);
378 empty->empty_drawtype = OB_EMPTY_SPHERE;
384 Object *ArmatureImporter::find_armature(COLLADAFW::Node *node)
386 JointData* jd = get_joint_data(node);
387 if (jd) return jd->ob_arm;
389 COLLADAFW::NodePointerArray& children = node->getChildNodes();
390 for (int i = 0; i < children.getCount(); i++) {
391 Object *ob_arm = find_armature(children[i]);
392 if (ob_arm) return ob_arm;
398 ArmatureJoints& ArmatureImporter::get_armature_joints(Object *ob_arm)
401 std::vector<ArmatureJoints>::iterator it;
402 for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
403 if ((*it).ob_arm == ob_arm) return *it;
406 // not found, create one
409 armature_joints.push_back(aj);
411 return armature_joints.back();
414 void ArmatureImporter::create_armature_bones( )
416 std::vector<COLLADAFW::Node*>::iterator ri;
417 //if there is an armature created for root_joint next root_joint
418 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
419 if ( get_armature_for_joint(*ri) != NULL ) continue;
421 //add armature object for current joint
422 //Object *ob_arm = add_object(scene, OB_ARMATURE);
424 Object *ob_arm = joint_parent_map[(*ri)->getUniqueId()];
425 //ob_arm->type = OB_ARMATURE;
426 ED_armature_to_edit(ob_arm);
428 // min_angle = 360.0f; // minimum angle between bone head-tail and a row of bone matrix
430 // create unskinned bones
433 check if bones have already been created for a given joint
435 leaf_bone_length = FLT_MAX;
436 create_unskinned_bone(*ri, NULL, (*ri)->getChildNodes().getCount(), NULL, ob_arm);
440 // exit armature edit mode
442 unskinned_armature_map[(*ri)->getUniqueId()] = ob_arm;
444 ED_armature_from_edit(ob_arm);
446 set_pose(ob_arm , *ri, NULL, NULL );
448 ED_armature_edit_free(ob_arm);
449 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
455 void ArmatureImporter::create_armature_bones(SkinInfo& skin)
460 // - add edit bones and head/tail properties using matrices and parent-child info
462 // - set a sphere shape to leaf bones
464 Object *ob_arm = NULL;
467 * find if there's another skin sharing at least one bone with this skin
468 * if so, use that skin's armature
474 find_node_in_tree(node, root_joint)
476 skin::find_root_joints(root_joints):
477 std::vector root_joints;
478 for each root in root_joints:
479 for each joint in joints:
480 if find_node_in_tree(joint, root):
481 if (std::find(root_joints.begin(), root_joints.end(), root) == root_joints.end())
482 root_joints.push_back(root);
484 for (each skin B with armature) {
485 find all root joints for skin B
487 for each joint X in skin A:
488 for each root joint R in skin B:
489 if (find_node_in_tree(X, R)) {
499 Object *shared = NULL;
500 std::vector<COLLADAFW::Node*> skin_root_joints;
502 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
503 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
504 SkinInfo *b = &it->second;
505 if (b == a || b->get_armature() == NULL)
508 skin_root_joints.clear();
510 b->find_root_joints(root_joints, joint_by_uid, skin_root_joints);
512 std::vector<COLLADAFW::Node*>::iterator ri;
513 for (ri = skin_root_joints.begin(); ri != skin_root_joints.end(); ri++) {
514 if (a->uses_joint_or_descendant(*ri)) {
515 shared = b->get_armature();
525 ob_arm = skin.set_armature(shared);
527 ob_arm = skin.create_armature(scene); //once for every armature
529 // enter armature edit mode
530 ED_armature_to_edit(ob_arm);
534 // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
535 leaf_bone_length = FLT_MAX;
536 // min_angle = 360.0f; // minimum angle between bone head-tail and a row of bone matrix
541 check if bones have already been created for a given joint
544 std::vector<COLLADAFW::Node*>::iterator ri;
545 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
546 // for shared armature check if bone tree is already created
547 if (shared && std::find(skin_root_joints.begin(), skin_root_joints.end(), *ri) != skin_root_joints.end())
550 // since root_joints may contain joints for multiple controllers, we need to filter
551 if (skin.uses_joint_or_descendant(*ri)) {
552 create_bone(skin, *ri, NULL, (*ri)->getChildNodes().getCount(), NULL, (bArmature*)ob_arm->data);
554 if (joint_parent_map.find((*ri)->getUniqueId()) != joint_parent_map.end() && !skin.get_parent())
555 skin.set_parent(joint_parent_map[(*ri)->getUniqueId()]);
561 // exit armature edit mode
562 ED_armature_from_edit(ob_arm);
563 ED_armature_edit_free(ob_arm);
564 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
566 // set_leaf_bone_shapes(ob_arm);
567 // set_euler_rotmode();
571 // root - if this joint is the top joint in hierarchy, if a joint
572 // is a child of a node (not joint), root should be true since
573 // this is where we build armature bones from
575 void ArmatureImporter::set_pose ( Object * ob_arm , COLLADAFW::Node * root_node , char *parentname, float parent_mat[][4])
577 char * bone_name = (char *) bc_get_joint_name ( root_node);
581 bArmature * arm = (bArmature * ) ob_arm-> data ;
586 get_node_mat(obmat, root_node, NULL, NULL);
589 bPoseChannel * pchan = get_pose_channel(ob_arm -> pose , bone_name);
594 mul_m4_m4m4(mat, obmat, parent_mat);
595 bPoseChannel *parchan = get_pose_channel(ob_arm->pose, parentname);
597 mul_m4_m4m4(pchan->pose_mat, mat , parchan->pose_mat);
601 copy_m4_m4(mat, obmat);
602 float invObmat[4][4];
603 invert_m4_m4(invObmat, ob_arm->obmat);
604 mul_m4_m4m4(pchan->pose_mat, mat, invObmat);
608 mat4_to_axis_angle(ax,&angle,mat);
609 pchan->bone->roll = angle;
612 COLLADAFW::NodePointerArray& children = root_node->getChildNodes();
613 for (unsigned int i = 0; i < children.getCount(); i++) {
614 set_pose(ob_arm, children[i], bone_name, mat);
619 void ArmatureImporter::add_joint(COLLADAFW::Node *node, bool root, Object *parent, Scene *sce)
621 joint_by_uid[node->getUniqueId()] = node;
623 root_joints.push_back(node);
627 joint_parent_map[node->getUniqueId()] = parent;
633 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node)
635 // root_joints.push_back(node);
636 Object *ob_arm = find_armature(node);
638 get_armature_joints(ob_arm).root_joints.push_back(node);
642 fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
648 // here we add bones to armatures, having armatures previously created in write_controller
649 void ArmatureImporter::make_armatures(bContext *C)
651 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
652 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
654 SkinInfo& skin = it->second;
656 create_armature_bones(skin);
658 // link armature with a mesh object
659 Object *ob = mesh_importer->get_object_by_geom_uid(*get_geometry_uid(skin.get_controller_uid()));
661 skin.link_armature(C, ob, joint_by_uid, this);
663 fprintf(stderr, "Cannot find object to link armature with.\n");
665 // set armature parent if any
666 Object *par = skin.get_parent();
668 bc_set_parent(skin.get_armature(), par, C, false);
670 // free memory stolen from SkinControllerData
674 //for bones without skins
675 create_armature_bones();
679 // link with meshes, create vertex groups, assign weights
680 void ArmatureImporter::link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
682 Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
685 fprintf(stderr, "Cannot find object by geometry UID.\n");
689 if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
690 fprintf(stderr, "Cannot find skin info by controller data UID.\n");
694 SkinInfo& skin = skin_by_data_uid[conroller_data_id];
696 // create vertex groups
700 bool ArmatureImporter::write_skin_controller_data(const COLLADAFW::SkinControllerData* data)
702 // at this stage we get vertex influence info that should go into me->verts and ob->defbase
703 // there's no info to which object this should be long so we associate it with skin controller data UID
705 // don't forget to call defgroup_unique_name before we copy
707 // controller data uid -> [armature] -> joint data,
711 SkinInfo skin(unit_converter);
712 skin.borrow_skin_controller_data(data);
714 // store join inv bind matrix to use it later in armature construction
715 const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
716 for (unsigned int i = 0; i < data->getJointsCount(); i++) {
717 skin.add_joint(inv_bind_mats[i]);
720 skin_by_data_uid[data->getUniqueId()] = skin;
725 bool ArmatureImporter::write_controller(const COLLADAFW::Controller* controller)
727 // - create and store armature object
729 const COLLADAFW::UniqueId& skin_id = controller->getUniqueId();
731 if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
732 COLLADAFW::SkinController *co = (COLLADAFW::SkinController*)controller;
733 // to be able to find geom id by controller id
734 geom_uid_by_controller_uid[skin_id] = co->getSource();
736 const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
737 if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
738 fprintf(stderr, "Cannot find skin by controller data UID.\n");
742 skin_by_data_uid[data_uid].set_controller(co);
747 fprintf(stderr, "Morph controller is not supported yet.\n");
754 COLLADAFW::UniqueId *ArmatureImporter::get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
756 if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
759 return &geom_uid_by_controller_uid[controller_uid];
762 Object *ArmatureImporter::get_armature_for_joint(COLLADAFW::Node *node)
764 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
765 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
766 SkinInfo& skin = it->second;
768 if (skin.uses_joint_or_descendant(node))
769 return skin.get_armature();
772 std::map<COLLADAFW::UniqueId, Object*>::iterator arm;
773 for (arm = unskinned_armature_map.begin(); arm != unskinned_armature_map.end(); arm++) {
774 if(arm->first == node->getUniqueId() )
780 void ArmatureImporter::set_tags_map(TagsMap & tagsMap)
782 this->uid_tags_map = tagsMap;
785 void ArmatureImporter::get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
787 BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", bc_get_joint_name(node));
790 // gives a world-space mat
791 bool ArmatureImporter::get_joint_bind_mat(float m[][4], COLLADAFW::Node *joint)
793 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
795 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
796 SkinInfo& skin = it->second;
797 if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {