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) {
56 ArmatureImporter::~ArmatureImporter()
58 // free skin controller data if we forget to do this earlier
59 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
60 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
66 JointData *ArmatureImporter::get_joint_data(COLLADAFW::Node *node);
68 const COLLADAFW::UniqueId& joint_id = node->getUniqueId();
70 if (joint_id_to_joint_index_map.find(joint_id) == joint_id_to_joint_index_map.end()) {
71 fprintf(stderr, "Cannot find a joint index by joint id for %s.\n",
72 node->getOriginalId().c_str());
76 int joint_index = joint_id_to_joint_index_map[joint_id];
78 return &joint_index_to_joint_info_map[joint_index];
82 void ArmatureImporter::create_bone(SkinInfo* skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
83 float parent_mat[4][4], bArmature *arm)
85 //Checking if bone is already made.
86 std::vector<COLLADAFW::Node *>::iterator it;
87 it = std::find(finished_joints.begin(), finished_joints.end(), node);
88 if (it != finished_joints.end()) return;
90 float joint_inv_bind_mat[4][4];
92 // JointData* jd = get_joint_data(node);
97 // TODO rename from Node "name" attrs later
98 EditBone *bone = ED_armature_edit_bone_add(arm, (char *)bc_get_joint_name(node));
101 if (skin && skin->get_joint_inv_bind_matrix(joint_inv_bind_mat, node)) {
102 // get original world-space matrix
103 invert_m4_m4(mat, joint_inv_bind_mat);
105 // create a bone even if there's no joint data for it (i.e. it has no influence)
108 get_node_mat(obmat, node, NULL, NULL);
112 mult_m4_m4m4(mat, parent_mat, obmat);
115 copy_m4_m4(mat, obmat);
118 if (parent) bone->parent = parent;
120 float loc[3], size[3], rot[3][3];
122 float vec[3] = {0.0f, 0.5f, 0.0f};
123 mat4_to_loc_rot_size(loc, rot, size, mat);
124 //copy_m3_m4(bonemat,mat);
125 mat3_to_vec_roll(rot, vec, &angle);
129 copy_v3_v3(bone->head, mat[3]);
131 // set tail, don't set it to head because 0-length bones are not allowed
132 add_v3_v3v3(bone->tail, bone->head, vec);
135 if (parent && totchild == 1) {
136 copy_v3_v3(parent->tail, bone->head);
138 // not setting BONE_CONNECTED because this would lock child bone location with respect to parent
139 bone->flag |= BONE_CONNECTED;
141 // XXX increase this to prevent "very" small bones?
142 const float epsilon = 0.000001f;
144 // derive leaf bone length
145 float length = len_v3v3(parent->head, parent->tail);
146 if ((length < leaf_bone_length || totbone == 0) && length > epsilon) {
147 leaf_bone_length = length;
150 // treat zero-sized bone like a leaf bone
151 if (length <= epsilon) {
152 add_leaf_bone(parent_mat, parent, node);
157 COLLADAFW::NodePointerArray& children = node->getChildNodes();
158 for (unsigned int i = 0; i < children.getCount(); i++) {
159 create_bone(skin, children[i], bone, children.getCount(), mat, arm);
162 // in second case it's not a leaf bone, but we handle it the same way
163 if (!children.getCount() || children.getCount() > 1) {
164 add_leaf_bone(mat, bone, node);
167 bone->length = len_v3v3(bone->head, bone->tail);
169 finished_joints.push_back(node);
172 void ArmatureImporter::add_leaf_bone(float mat[4][4], EditBone *bone, COLLADAFW::Node *node)
177 copy_m4_m4(leaf.mat, mat);
178 BLI_strncpy(leaf.name, bone->name, sizeof(leaf.name));
180 TagsMap::iterator etit;
182 etit = uid_tags_map.find(node->getUniqueId().toAscii());
183 if (etit != uid_tags_map.end()) {
188 et->setData("tip_x", &x);
189 et->setData("tip_y", &y);
190 et->setData("tip_z", &z);
191 float vec[3] = {x, y, z};
192 copy_v3_v3(leaf.bone->tail, leaf.bone->head);
193 add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
196 leaf_bones.push_back(leaf);
200 void ArmatureImporter::fix_leaf_bones( )
202 // just setting tail for leaf bones here
203 std::vector<LeafBone>::iterator it;
204 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
205 LeafBone& leaf = *it;
208 float vec[3] = {0.0f, 0.0f, 0.1f};
210 sub_v3_v3v3(vec, leaf.bone->tail , leaf.bone->head);
211 mul_v3_fl(vec, leaf_bone_length);
212 add_v3_v3v3(leaf.bone->tail, leaf.bone->head , vec);
218 void ArmatureImporter::set_leaf_bone_shapes(Object *ob_arm)
220 bPose *pose = ob_arm->pose;
222 std::vector<LeafBone>::iterator it;
223 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
224 LeafBone& leaf = *it;
226 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, leaf.name);
228 pchan->custom = get_empty_for_leaves();
231 fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
236 void ArmatureImporter::set_euler_rotmode()
238 // just set rotmode = ROT_MODE_EUL on pose channel for each joint
240 std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>::iterator it;
242 for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
244 COLLADAFW::Node *joint = it->second;
246 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
248 for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
249 SkinInfo& skin = sit->second;
251 if (skin.uses_joint_or_descendant(joint)) {
252 bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
255 pchan->rotmode = ROT_MODE_EUL;
258 fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
268 Object *ArmatureImporter::get_empty_for_leaves()
270 if (empty) return empty;
272 empty = bc_add_object(scene, OB_EMPTY, NULL);
273 empty->empty_drawtype = OB_EMPTY_SPHERE;
279 Object *ArmatureImporter::find_armature(COLLADAFW::Node *node)
281 JointData *jd = get_joint_data(node);
282 if (jd) return jd->ob_arm;
284 COLLADAFW::NodePointerArray& children = node->getChildNodes();
285 for (int i = 0; i < children.getCount(); i++) {
286 Object *ob_arm = find_armature(children[i]);
287 if (ob_arm) return ob_arm;
293 ArmatureJoints& ArmatureImporter::get_armature_joints(Object *ob_arm)
296 std::vector<ArmatureJoints>::iterator it;
297 for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
298 if ((*it).ob_arm == ob_arm) return *it;
301 // not found, create one
304 armature_joints.push_back(aj);
306 return armature_joints.back();
309 void ArmatureImporter::create_armature_bones( )
311 std::vector<COLLADAFW::Node *>::iterator ri;
313 leaf_bone_length = FLT_MAX;
314 //if there is an armature created for root_joint next root_joint
315 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
316 if (get_armature_for_joint(*ri) != NULL) continue;
318 Object *ob_arm = joint_parent_map[(*ri)->getUniqueId()];
323 ED_armature_to_edit(ob_arm);
327 * check if bones have already been created for a given joint
330 create_bone(NULL, *ri , NULL, (*ri)->getChildNodes().getCount(), NULL, (bArmature *)ob_arm->data);
332 //leaf bone tails are derived from the matrix, so no need of this.
335 // exit armature edit mode
336 unskinned_armature_map[(*ri)->getUniqueId()] = ob_arm;
338 ED_armature_from_edit(ob_arm);
340 //This serves no purpose, as pose is automatically reset later, in BKE_where_is_bone()
341 //set_pose(ob_arm, *ri, NULL, NULL);
343 ED_armature_edit_free(ob_arm);
344 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB | OB_RECALC_DATA);
348 void ArmatureImporter::create_armature_bones(SkinInfo& skin)
353 // - add edit bones and head/tail properties using matrices and parent-child info
355 // - set a sphere shape to leaf bones
357 Object *ob_arm = NULL;
360 * find if there's another skin sharing at least one bone with this skin
361 * if so, use that skin's armature
367 find_node_in_tree(node, root_joint)
369 skin::find_root_joints(root_joints):
370 std::vector root_joints;
371 for each root in root_joints:
372 for each joint in joints:
373 if find_node_in_tree(joint, root):
374 if (std::find(root_joints.begin(), root_joints.end(), root) == root_joints.end())
375 root_joints.push_back(root);
377 for (each skin B with armature) {
378 find all root joints for skin B
380 for each joint X in skin A:
381 for each root joint R in skin B:
382 if (find_node_in_tree(X, R)) {
392 Object *shared = NULL;
393 std::vector<COLLADAFW::Node *> skin_root_joints;
395 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
396 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
397 SkinInfo *b = &it->second;
398 if (b == a || b->BKE_armature_from_object() == NULL)
401 skin_root_joints.clear();
403 b->find_root_joints(root_joints, joint_by_uid, skin_root_joints);
405 std::vector<COLLADAFW::Node *>::iterator ri;
406 for (ri = skin_root_joints.begin(); ri != skin_root_joints.end(); ri++) {
407 if (a->uses_joint_or_descendant(*ri)) {
408 shared = b->BKE_armature_from_object();
418 ob_arm = skin.set_armature(shared);
420 ob_arm = skin.create_armature(scene); //once for every armature
422 // enter armature edit mode
423 ED_armature_to_edit(ob_arm);
427 // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
428 leaf_bone_length = FLT_MAX;
433 check if bones have already been created for a given joint
436 std::vector<COLLADAFW::Node *>::iterator ri;
437 for (ri = root_joints.begin(); ri != root_joints.end(); ri++) {
438 // for shared armature check if bone tree is already created
439 if (shared && std::find(skin_root_joints.begin(), skin_root_joints.end(), *ri) != skin_root_joints.end())
442 // since root_joints may contain joints for multiple controllers, we need to filter
443 if (skin.uses_joint_or_descendant(*ri)) {
444 create_bone(&skin, *ri, NULL, (*ri)->getChildNodes().getCount(), NULL, (bArmature *)ob_arm->data);
446 if (joint_parent_map.find((*ri)->getUniqueId()) != joint_parent_map.end() && !skin.get_parent())
447 skin.set_parent(joint_parent_map[(*ri)->getUniqueId()]);
453 // exit armature edit mode
454 ED_armature_from_edit(ob_arm);
455 ED_armature_edit_free(ob_arm);
456 DAG_id_tag_update(&ob_arm->id, OB_RECALC_OB | OB_RECALC_DATA);
460 void ArmatureImporter::set_pose(Object *ob_arm, COLLADAFW::Node *root_node, const char *parentname, float parent_mat[4][4])
462 char *bone_name = (char *) bc_get_joint_name(root_node);
467 get_node_mat(obmat, root_node, NULL, NULL);
470 bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, bone_name);
475 mult_m4_m4m4(mat, parent_mat, obmat);
476 bPoseChannel *parchan = BKE_pose_channel_find_name(ob_arm->pose, parentname);
478 mult_m4_m4m4(pchan->pose_mat, parchan->pose_mat, mat);
483 copy_m4_m4(mat, obmat);
484 float invObmat[4][4];
485 invert_m4_m4(invObmat, ob_arm->obmat);
486 mult_m4_m4m4(pchan->pose_mat, invObmat, mat);
490 //float angle = 0.0f;
491 ///*mat4_to_axis_angle(ax, &angle, mat);
492 //pchan->bone->roll = angle;*/
495 COLLADAFW::NodePointerArray& children = root_node->getChildNodes();
496 for (unsigned int i = 0; i < children.getCount(); i++) {
497 set_pose(ob_arm, children[i], bone_name, mat);
503 // root - if this joint is the top joint in hierarchy, if a joint
504 // is a child of a node (not joint), root should be true since
505 // this is where we build armature bones from
506 void ArmatureImporter::add_joint(COLLADAFW::Node *node, bool root, Object *parent, Scene *sce)
508 joint_by_uid[node->getUniqueId()] = node;
510 root_joints.push_back(node);
514 joint_parent_map[node->getUniqueId()] = parent;
520 void ArmatureImporter::add_root_joint(COLLADAFW::Node *node)
522 // root_joints.push_back(node);
523 Object *ob_arm = find_armature(node);
525 get_armature_joints(ob_arm).root_joints.push_back(node);
529 fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
535 // here we add bones to armatures, having armatures previously created in write_controller
536 void ArmatureImporter::make_armatures(bContext *C)
538 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
539 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
541 SkinInfo& skin = it->second;
543 create_armature_bones(skin);
545 // link armature with a mesh object
546 const COLLADAFW::UniqueId &uid = skin.get_controller_uid();
547 const COLLADAFW::UniqueId *guid = get_geometry_uid(uid);
549 Object *ob = mesh_importer->get_object_by_geom_uid(*guid);
551 skin.link_armature(C, ob, joint_by_uid, this);
553 fprintf(stderr, "Cannot find object to link armature with.\n");
556 fprintf(stderr, "Cannot find geometry to link armature with.\n");
558 // set armature parent if any
559 Object *par = skin.get_parent();
561 bc_set_parent(skin.BKE_armature_from_object(), par, C, false);
563 // free memory stolen from SkinControllerData
567 //for bones without skins
568 create_armature_bones();
572 // link with meshes, create vertex groups, assign weights
573 void ArmatureImporter::link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
575 Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
578 fprintf(stderr, "Cannot find object by geometry UID.\n");
582 if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
583 fprintf(stderr, "Cannot find skin info by controller data UID.\n");
587 SkinInfo& skin = skin_by_data_uid[conroller_data_id];
589 // create vertex groups
593 bool ArmatureImporter::write_skin_controller_data(const COLLADAFW::SkinControllerData *data)
595 // at this stage we get vertex influence info that should go into me->verts and ob->defbase
596 // there's no info to which object this should be long so we associate it with skin controller data UID
598 // don't forget to call defgroup_unique_name before we copy
600 // controller data uid -> [armature] -> joint data,
604 SkinInfo skin(unit_converter);
605 skin.borrow_skin_controller_data(data);
607 // store join inv bind matrix to use it later in armature construction
608 const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
609 for (unsigned int i = 0; i < data->getJointsCount(); i++) {
610 skin.add_joint(inv_bind_mats[i]);
613 skin_by_data_uid[data->getUniqueId()] = skin;
618 bool ArmatureImporter::write_controller(const COLLADAFW::Controller *controller)
620 // - create and store armature object
621 const COLLADAFW::UniqueId& con_id = controller->getUniqueId();
623 if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
624 COLLADAFW::SkinController *co = (COLLADAFW::SkinController *)controller;
625 // to be able to find geom id by controller id
626 geom_uid_by_controller_uid[con_id] = co->getSource();
628 const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
629 if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
630 fprintf(stderr, "Cannot find skin by controller data UID.\n");
634 skin_by_data_uid[data_uid].set_controller(co);
637 else if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_MORPH) {
638 COLLADAFW::MorphController *co = (COLLADAFW::MorphController *)controller;
639 // to be able to find geom id by controller id
640 geom_uid_by_controller_uid[con_id] = co->getSource();
641 //Shape keys are applied in DocumentImporter->finish()
642 morph_controllers.push_back(co);
648 void ArmatureImporter::make_shape_keys(){
649 std::vector<COLLADAFW::MorphController *>::iterator mc;
652 for (mc = morph_controllers.begin(); mc != morph_controllers.end(); mc++) {
654 COLLADAFW::UniqueIdArray& morphTargetIds = (*mc)->getMorphTargets();
655 COLLADAFW::FloatOrDoubleArray& morphWeights = (*mc)->getMorphWeights();
657 //Prereq: all the geometries must be imported and mesh objects must be made
658 Object *source_ob = this->mesh_importer->get_object_by_geom_uid((*mc)->getSource());
660 Mesh *source_me = (Mesh*) source_ob->data;
661 //insert key to source mesh
662 Key *key = source_me->key = BKE_key_add((ID *)source_me);
663 key->type = KEY_RELATIVE;
667 kb = BKE_keyblock_add_ctime(key, "Basis", FALSE);
668 BKE_key_convert_from_mesh(source_me, kb);
670 //insert other shape keys
671 for ( int i = 0 ; i < morphTargetIds.getCount() ; i++ ){
672 //better to have a seperate map of morph objects,
673 //This'll do for now since only mesh morphing is imported
674 Mesh *me = this->mesh_importer->get_mesh_by_geom_uid(morphTargetIds[i]);
678 kb = BKE_keyblock_add_ctime(key, me->id.name, FALSE);
679 BKE_key_convert_from_mesh(me, kb);
682 weight = morphWeights.getFloatValues()->getData()[i];
686 fprintf(stderr, "Morph target geometry not found.\n");
692 COLLADAFW::UniqueId *ArmatureImporter::get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
694 if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
697 return &geom_uid_by_controller_uid[controller_uid];
700 Object *ArmatureImporter::get_armature_for_joint(COLLADAFW::Node *node)
702 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
703 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
704 SkinInfo& skin = it->second;
706 if (skin.uses_joint_or_descendant(node))
707 return skin.BKE_armature_from_object();
710 std::map<COLLADAFW::UniqueId, Object *>::iterator arm;
711 for (arm = unskinned_armature_map.begin(); arm != unskinned_armature_map.end(); arm++) {
712 if (arm->first == node->getUniqueId() )
718 void ArmatureImporter::set_tags_map(TagsMap & tagsMap)
720 this->uid_tags_map = tagsMap;
723 void ArmatureImporter::get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
725 BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", bc_get_joint_name(node));
728 // gives a world-space mat
729 bool ArmatureImporter::get_joint_bind_mat(float m[4][4], COLLADAFW::Node *joint)
731 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
733 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
734 SkinInfo& skin = it->second;
735 if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {