0fc01e510206d3eb24d23fd901112a583a0e1f96
[blender.git] / source / blender / collada / AnimationImporter.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
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.
10  *
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.
15  *
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.
19  *
20  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory.
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/collada/AnimationImporter.cpp
26  *  \ingroup collada
27  */
28
29 #include <stddef.h>
30
31 /* COLLADABU_ASSERT, may be able to remove later */
32 #include "COLLADABUPlatform.h"
33
34 #include "DNA_armature_types.h"
35
36 #include "ED_keyframing.h"
37
38 #include "BLI_listbase.h"
39 #include "BLI_math.h"
40 #include "BLI_path_util.h"
41 #include "BLI_string.h"
42
43 #include "BKE_action.h"
44 #include "BKE_armature.h"
45 #include "BKE_fcurve.h"
46 #include "BKE_object.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "collada_utils.h"
51 #include "AnimationImporter.h"
52 #include "ArmatureImporter.h"
53 #include "MaterialExporter.h"
54
55 #include <algorithm>
56
57 // first try node name, if not available (since is optional), fall back to original id
58 template<class T>
59 static const char *bc_get_joint_name(T *node)
60 {
61         const std::string& id = node->getName();
62         return id.size() ? id.c_str() : node->getOriginalId().c_str();
63 }
64
65 FCurve *AnimationImporter::create_fcurve(int array_index, const char *rna_path)
66 {
67         FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
68         
69         fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
70         fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
71         fcu->array_index = array_index;
72         return fcu;
73 }
74         
75 void AnimationImporter::create_bezt(FCurve *fcu, float frame, float output)
76 {
77         BezTriple bez;
78         memset(&bez, 0, sizeof(BezTriple));
79         bez.vec[1][0] = frame;
80         bez.vec[1][1] = output;
81         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
82         bez.f1 = bez.f2 = bez.f3 = SELECT;
83         bez.h1 = bez.h2 = HD_AUTO;
84         insert_bezt_fcurve(fcu, &bez, 0);
85         calchandles_fcurve(fcu);
86 }
87
88 // create one or several fcurves depending on the number of parameters being animated
89 void AnimationImporter::animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
90 {
91         COLLADAFW::FloatOrDoubleArray& input = curve->getInputValues();
92         COLLADAFW::FloatOrDoubleArray& output = curve->getOutputValues();
93    
94         if( curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER ) {
95         COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
96     COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
97         }
98         float fps = (float)FPS;
99         size_t dim = curve->getOutDimension();
100         unsigned int i;
101         
102         std::vector<FCurve*>& fcurves = curve_map[curve->getUniqueId()];
103
104         switch (dim) {
105         case 1: // X, Y, Z or angle
106         case 3: // XYZ
107         case 4:
108         case 16: // matrix
109                 {
110                         for (i = 0; i < dim; i++ ) {
111                                 FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
112                         
113                                 fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
114                                 // fcu->rna_path = BLI_strdupn(path, strlen(path));
115                                 fcu->array_index = 0;
116                                 fcu->totvert = curve->getKeyCount();
117                         
118                                 // create beztriple for each key
119                                 for (unsigned int j = 0; j < curve->getKeyCount(); j++) {
120                                         BezTriple bez;
121                                         memset(&bez, 0, sizeof(BezTriple));
122
123                                         
124                                         // input, output
125                                         bez.vec[1][0] = bc_get_float_value(input, j) * fps; 
126                                         bez.vec[1][1] = bc_get_float_value(output, j * dim + i);
127
128
129                                         if( curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER ) 
130                                         {
131                                                 COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
132                         COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
133
134                                                 // intangent
135                                                  bez.vec[0][0] = bc_get_float_value(intan, (j * 2 * dim ) + (2 * i)) * fps;
136                                                  bez.vec[0][1] = bc_get_float_value(intan, (j * 2 * dim )+ (2 * i) + 1);
137
138                                                  // outtangent
139                                                  bez.vec[2][0] = bc_get_float_value(outtan, (j * 2 * dim ) + (2 * i)) * fps;
140                                                  bez.vec[2][1] = bc_get_float_value(outtan, (j * 2 * dim )+ (2 * i) + 1);
141                                              bez.ipo = BEZT_IPO_BEZ;
142                                                  //bez.h1 = bez.h2 = HD_AUTO;   
143                                         }
144                                         else 
145                                         {
146                                                 bez.h1 = bez.h2 = HD_AUTO; 
147                                                 bez.ipo = BEZT_IPO_LIN;
148                                         }
149                                         // bez.ipo = U.ipo_new; /* use default interpolation mode here... */
150                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
151                                         
152                                         insert_bezt_fcurve(fcu, &bez, 0);
153                                 }
154
155                                 calchandles_fcurve(fcu);
156
157                                 fcurves.push_back(fcu);
158                         }
159                 }
160                 break;
161         default:
162                 fprintf(stderr, "Output dimension of %d is not yet supported (animation id = %s)\n", (int)dim, curve->getOriginalId().c_str());
163         }
164
165         for (std::vector<FCurve*>::iterator it = fcurves.begin(); it != fcurves.end(); it++)
166                 unused_curves.push_back(*it);
167 }
168
169
170 void AnimationImporter::fcurve_deg_to_rad(FCurve *cu)
171 {
172         for (unsigned int i = 0; i < cu->totvert; i++) {
173                 // TODO convert handles too
174                 cu->bezt[i].vec[1][1] *= M_PI / 180.0f;
175                 cu->bezt[i].vec[0][1] *= M_PI / 180.0f;
176                 cu->bezt[i].vec[2][1] *= M_PI / 180.0f;
177                 cu->bezt[i].vec[1][0];
178         }
179 }
180
181 void AnimationImporter::add_fcurves_to_object(Object *ob, std::vector<FCurve*>& curves, char *rna_path, int array_index, Animation *animated)
182 {
183         bAction *act;
184         
185         if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
186         else act = ob->adt->action;
187         
188         std::vector<FCurve*>::iterator it;
189         int i;
190
191 #if 0
192         char *p = strstr(rna_path, "rotation_euler");
193         bool is_rotation = p && *(p + strlen("rotation_euler")) == '\0';
194
195         // convert degrees to radians for rotation
196         if (is_rotation)
197                 fcurve_deg_to_rad(fcu);
198 #endif
199         
200         for (it = curves.begin(), i = 0; it != curves.end(); it++, i++) {
201                 FCurve *fcu = *it;
202                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
203                 
204                 if (array_index == -1) fcu->array_index = i;
205                 else fcu->array_index = array_index;
206         
207                 if (ob->type == OB_ARMATURE) {
208                         bActionGroup *grp = NULL;
209                         const char *bone_name = bc_get_joint_name(animated->node);
210                         
211                         if (bone_name) {
212                                 /* try to find group */
213                                 grp = action_groups_find_named(act, bone_name);
214                                 
215                                 /* no matching groups, so add one */
216                                 if (grp == NULL) {
217                                         /* Add a new group, and make it active */
218                                         grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
219                                         
220                                         grp->flag = AGRP_SELECTED;
221                                         BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
222                                         
223                                         BLI_addtail(&act->groups, grp);
224                                         BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
225                                 }
226                                 
227                                 /* add F-Curve to group */
228                                 action_groups_add_channel(act, grp, fcu);
229                                 
230                         }
231 #if 0
232                         if (is_rotation) {
233                                 fcurves_actionGroup_map[grp].push_back(fcu);
234                         }
235 #endif
236                 }
237                 else {
238                         BLI_addtail(&act->curves, fcu);
239                 }
240
241                 // curve is used, so remove it from unused_curves
242                 unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
243         }
244 }
245
246 AnimationImporter::AnimationImporter(UnitConverter *conv, ArmatureImporter *arm, Scene *scene) :
247                 TransformReader(conv), armature_importer(arm), scene(scene) { }
248
249 AnimationImporter::~AnimationImporter()
250 {
251         // free unused FCurves
252         for (std::vector<FCurve*>::iterator it = unused_curves.begin(); it != unused_curves.end(); it++)
253                 free_fcurve(*it);
254
255         if (unused_curves.size())
256                 fprintf(stderr, "removed %d unused curves\n", (int)unused_curves.size());
257 }
258
259 bool AnimationImporter::write_animation(const COLLADAFW::Animation* anim) 
260 {
261         if (anim->getAnimationType() == COLLADAFW::Animation::ANIMATION_CURVE) {
262                 COLLADAFW::AnimationCurve *curve = (COLLADAFW::AnimationCurve*)anim;
263                 
264                 // XXX Don't know if it's necessary
265                 // Should we check outPhysicalDimension?
266                 if (curve->getInPhysicalDimension() != COLLADAFW::PHYSICAL_DIMENSION_TIME) {
267                         fprintf(stderr, "Inputs physical dimension is not time. \n");
268                         return true;
269                 }
270
271                 // a curve can have mixed interpolation type,
272                 // in this case curve->getInterpolationTypes returns a list of interpolation types per key
273                 COLLADAFW::AnimationCurve::InterpolationType interp = curve->getInterpolationType();
274
275                 if (interp != COLLADAFW::AnimationCurve::INTERPOLATION_MIXED) {
276                         switch (interp) {
277                         case COLLADAFW::AnimationCurve::INTERPOLATION_LINEAR:
278                         case COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER:
279                                 animation_to_fcurves(curve);
280                                 break;
281                         default:
282                                 // TODO there're also CARDINAL, HERMITE, BSPLINE and STEP types
283                                 fprintf(stderr, "CARDINAL, HERMITE, BSPLINE and STEP anim interpolation types not supported yet.\n");
284                                 break;
285                         }
286                 }
287                 else {
288                         // not supported yet
289                         fprintf(stderr, "MIXED anim interpolation type is not supported yet.\n");
290                 }
291         }
292         else {
293                 fprintf(stderr, "FORMULA animation type is not supported yet.\n");
294         }
295         
296         return true;
297 }
298         
299 // called on post-process stage after writeVisualScenes
300 bool AnimationImporter::write_animation_list(const COLLADAFW::AnimationList* animlist) 
301 {
302         const COLLADAFW::UniqueId& animlist_id = animlist->getUniqueId();
303     
304         animlist_map[animlist_id] = animlist;
305     
306 #if 0
307
308         // should not happen
309         if (uid_animated_map.find(animlist_id) == uid_animated_map.end()) {
310                 return true;
311         }
312
313         // for bones rna_path is like: pose.bones["bone-name"].rotation
314         
315         // what does this AnimationList animate?
316         Animation& animated = uid_animated_map[animlist_id];
317         Object *ob = animated.ob;
318     
319         char rna_path[100];
320         char joint_path[100];
321         bool is_joint = false;
322
323         // if ob is NULL, it should be a JOINT
324         if (!ob) {
325                 
326                 ob = armature_importer->get_armature_for_joint(animated.node);
327
328                 if (!ob) {
329 //                      fprintf(stderr, "Cannot find armature for node %s\n", get_joint_name(animated.node));
330                         return true;
331                 }
332
333                 armature_importer->get_rna_path_for_joint(animated.node, joint_path, sizeof(joint_path));
334
335                 is_joint = true;
336         }
337         printf("object for animlist: %s found\n", animlist->getUniqueId().toAscii().c_str());
338         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
339
340         switch (animated.tm->getTransformationType()) {
341         case COLLADAFW::Transformation::TRANSLATE:
342         case COLLADAFW::Transformation::SCALE:
343                 {
344                         bool loc = animated.tm->getTransformationType() == COLLADAFW::Transformation::TRANSLATE;
345                         if (is_joint)
346                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
347                         else
348                                 BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
349
350                         for (int i = 0; i < bindings.getCount(); i++) {
351                                 const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
352                                 COLLADAFW::UniqueId anim_uid = binding.animation;
353
354                                 if (curve_map.find(anim_uid) == curve_map.end()) {
355                                         fprintf(stderr, "Cannot find FCurve by animation UID.\n");
356                                         continue;
357                                 }
358
359                                 std::vector<FCurve*>& fcurves = curve_map[anim_uid];
360                                 
361                                 switch (binding.animationClass) {
362                                 case COLLADAFW::AnimationList::POSITION_X:
363                                         add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
364                                         break;
365                                 case COLLADAFW::AnimationList::POSITION_Y:
366                                         add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
367                                         break;
368                                 case COLLADAFW::AnimationList::POSITION_Z:
369                                         add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
370                                         break;
371                                 case COLLADAFW::AnimationList::POSITION_XYZ:
372                                         add_fcurves_to_object(ob, fcurves, rna_path, -1, &animated);
373                                         break;
374                                 default:
375                                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
376                                                         binding.animationClass, loc ? "TRANSLATE" : "SCALE");
377                                 }
378                         }
379                 }
380                 break;
381         case COLLADAFW::Transformation::ROTATE:
382                 {
383                         if (is_joint)
384                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
385                         else
386                                 BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
387
388                         COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)animated.tm;
389                         COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
390                         
391                         for (int i = 0; i < bindings.getCount(); i++) {
392                                 const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
393                                 COLLADAFW::UniqueId anim_uid = binding.animation;
394
395                                 if (curve_map.find(anim_uid) == curve_map.end()) {
396                                         fprintf(stderr, "Cannot find FCurve by animation UID.\n");
397                                         continue;
398                                 }
399
400                                 std::vector<FCurve*>& fcurves = curve_map[anim_uid];
401
402                                 switch (binding.animationClass) {
403                                 case COLLADAFW::AnimationList::ANGLE:
404                                         if (COLLADABU::Math::Vector3::UNIT_X == axis) {
405                                                 add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
406                                         }
407                                         else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
408                                                 add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
409                                         }
410                                         else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
411                                                 add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
412                                         }
413                                         break;
414                                 case COLLADAFW::AnimationList::AXISANGLE:
415                                         // TODO convert axis-angle to quat? or XYZ?
416                                 default:
417                                         fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
418                                                         binding.animationClass);
419                                 }
420                         }
421                 }
422                 break;
423         case COLLADAFW::Transformation::MATRIX:
424         case COLLADAFW::Transformation::SKEW:
425         case COLLADAFW::Transformation::LOOKAT:
426                 fprintf(stderr, "Animation of MATRIX, SKEW and LOOKAT transformations is not supported yet.\n");
427                 break;
428         }
429 #endif
430         
431         return true;
432 }
433
434 // \todo refactor read_node_transform to not automatically apply anything,
435 // but rather return the transform matrix, so caller can do with it what is
436 // necessary. Same for \ref get_node_mat
437 void AnimationImporter::read_node_transform(COLLADAFW::Node *node, Object *ob)
438 {
439         float mat[4][4];
440         TransformReader::get_node_mat(mat, node, &uid_animated_map, ob);
441         if (ob) {
442                 copy_m4_m4(ob->obmat, mat);
443                 object_apply_mat4(ob, ob->obmat, 0, 0);
444         }
445 }
446
447 #if 0
448 virtual void AnimationImporter::change_eul_to_quat(Object *ob, bAction *act)
449 {
450         bActionGroup *grp;
451         int i;
452         
453         for (grp = (bActionGroup*)act->groups.first; grp; grp = grp->next) {
454
455                 FCurve *eulcu[3] = {NULL, NULL, NULL};
456                 
457                 if (fcurves_actionGroup_map.find(grp) == fcurves_actionGroup_map.end())
458                         continue;
459
460                 std::vector<FCurve*> &rot_fcurves = fcurves_actionGroup_map[grp];
461                 
462                 if (rot_fcurves.size() > 3) continue;
463
464                 for (i = 0; i < rot_fcurves.size(); i++)
465                         eulcu[rot_fcurves[i]->array_index] = rot_fcurves[i];
466
467                 char joint_path[100];
468                 char rna_path[100];
469
470                 BLI_snprintf(joint_path, sizeof(joint_path), "pose.bones[\"%s\"]", grp->name);
471                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_quaternion", joint_path);
472
473                 FCurve *quatcu[4] = {
474                         create_fcurve(0, rna_path),
475                         create_fcurve(1, rna_path),
476                         create_fcurve(2, rna_path),
477                         create_fcurve(3, rna_path)
478                 };
479
480                 bPoseChannel *chan = get_pose_channel(ob->pose, grp->name);
481
482                 float m4[4][4], irest[3][3];
483                 invert_m4_m4(m4, chan->bone->arm_mat);
484                 copy_m3_m4(irest, m4);
485
486                 for (i = 0; i < 3; i++) {
487
488                         FCurve *cu = eulcu[i];
489
490                         if (!cu) continue;
491
492                         for (int j = 0; j < cu->totvert; j++) {
493                                 float frame = cu->bezt[j].vec[1][0];
494
495                                 float eul[3] = {
496                                         eulcu[0] ? evaluate_fcurve(eulcu[0], frame) : 0.0f,
497                                         eulcu[1] ? evaluate_fcurve(eulcu[1], frame) : 0.0f,
498                                         eulcu[2] ? evaluate_fcurve(eulcu[2], frame) : 0.0f
499                                 };
500
501                                 // make eul relative to bone rest pose
502                                 float rot[3][3], rel[3][3], quat[4];
503
504                                 /*eul_to_mat3(rot, eul);
505
506                                 mul_m3_m3m3(rel, irest, rot);
507
508                                 mat3_to_quat(quat, rel);
509                                 */
510
511                                 eul_to_quat(quat, eul);
512
513                                 for (int k = 0; k < 4; k++)
514                                         create_bezt(quatcu[k], frame, quat[k]);
515                         }
516                 }
517
518                 // now replace old Euler curves
519
520                 for (i = 0; i < 3; i++) {
521                         if (!eulcu[i]) continue;
522
523                         action_groups_remove_channel(act, eulcu[i]);
524                         free_fcurve(eulcu[i]);
525                 }
526
527                 chan->rotmode = ROT_MODE_QUAT;
528
529                 for (i = 0; i < 4; i++)
530                         action_groups_add_channel(act, grp, quatcu[i]);
531         }
532
533         bPoseChannel *pchan;
534         for (pchan = (bPoseChannel*)ob->pose->chanbase.first; pchan; pchan = pchan->next) {
535                 pchan->rotmode = ROT_MODE_QUAT;
536         }
537 }
538 #endif
539
540
541 //sets the rna_path and array index to curve
542 void AnimationImporter::modify_fcurve(std::vector<FCurve*>* curves , char* rna_path , int array_index )
543 {   
544         std::vector<FCurve*>::iterator it;
545         int i;
546         for (it = curves->begin(), i = 0; it != curves->end(); it++, i++) {
547                 FCurve *fcu = *it;
548                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
549                 
550                 if (array_index == -1) fcu->array_index = i;
551                 else fcu->array_index = array_index;
552
553                 unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
554         }
555 }
556
557 void AnimationImporter::find_frames( std::vector<float>* frames , std::vector<FCurve*>* curves)
558 {
559         std::vector<FCurve*>::iterator iter;
560                 for (iter = curves->begin(); iter != curves->end(); iter++) {
561                         FCurve *fcu = *iter;
562         
563                 for (unsigned int k = 0; k < fcu->totvert; k++) {
564                         //get frame value from bezTriple
565                         float fra = fcu->bezt[k].vec[1][0];
566                         //if frame already not added add frame to frames
567                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
568                                 frames->push_back(fra);
569                                                         
570                 }
571                 }
572 }
573
574 //creates the rna_paths and array indices of fcurves from animations using transformation and bound animation class of each animation.
575 void AnimationImporter:: Assign_transform_animations(COLLADAFW::Transformation * transform , 
576                                                                                                          const COLLADAFW::AnimationList::AnimationBinding * binding,
577                                                                                                          std::vector<FCurve*>* curves, bool is_joint, char * joint_path)
578 {
579         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
580         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
581         bool is_rotation = tm_type  == COLLADAFW::Transformation::ROTATE;
582         
583         //to check if the no of curves are valid
584         bool xyz = ((tm_type == COLLADAFW::Transformation::TRANSLATE ||tm_type  == COLLADAFW::Transformation::SCALE) && binding->animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
585                         
586         
587         if (!((!xyz && curves->size() == 1) || (xyz && curves->size() == 3) || is_matrix)) {
588                 fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves->size());
589                 return;
590         }
591         
592         char rna_path[100];
593                                                         
594         switch (tm_type) {
595                 case COLLADAFW::Transformation::TRANSLATE:
596                 case COLLADAFW::Transformation::SCALE:
597                         {
598                                 bool loc = tm_type == COLLADAFW::Transformation::TRANSLATE;
599                                 if (is_joint)
600                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
601                                 else
602                                         BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
603
604                                 switch (binding->animationClass) {
605                                         case COLLADAFW::AnimationList::POSITION_X:
606                                                 modify_fcurve(curves, rna_path, 0 );
607                                                 break;
608                                         case COLLADAFW::AnimationList::POSITION_Y:
609                                                 modify_fcurve(curves, rna_path, 1 );
610                                                 break;
611                                         case COLLADAFW::AnimationList::POSITION_Z:
612                                                 modify_fcurve(curves, rna_path, 2 );
613                                                 break;
614                                         case COLLADAFW::AnimationList::POSITION_XYZ:
615                                                 modify_fcurve(curves, rna_path, -1 );
616                                                 break;
617                                         default:
618                                                 fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
619                                                                 binding->animationClass, loc ? "TRANSLATE" : "SCALE");
620                                         }
621                 break;
622                         }
623                 
624                 
625                 case COLLADAFW::Transformation::ROTATE:
626                         {
627                                 if (is_joint)
628                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
629                                 else
630                                         BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
631                 std::vector<FCurve*>::iterator iter;
632                                 for (iter = curves->begin(); iter != curves->end(); iter++) {
633                                         FCurve* fcu = *iter;
634                                         
635                                         //if transform is rotation the fcurves values must be turned in to radian.
636                                         if (is_rotation)
637                                                 fcurve_deg_to_rad(fcu);          
638                                 }                                       
639                                 COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)transform;
640                                 COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
641                         
642                                 switch (binding->animationClass) {
643                                         case COLLADAFW::AnimationList::ANGLE:
644                                                 if (COLLADABU::Math::Vector3::UNIT_X == axis) {
645                                                         modify_fcurve(curves, rna_path, 0 );
646                                                 }
647                                                 else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
648                                                         modify_fcurve(curves, rna_path, 1 );
649                                                 }
650                                                 else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
651                                                         modify_fcurve(curves, rna_path, 2 );
652                                                 }
653                                                 break;
654                                         case COLLADAFW::AnimationList::AXISANGLE:
655                                                 // TODO convert axis-angle to quat? or XYZ?
656                                         default:
657                                                 fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
658                                                                 binding->animationClass);
659                                         }
660                         break;
661                         }
662                         
663                 case COLLADAFW::Transformation::MATRIX:
664                 case COLLADAFW::Transformation::SKEW:
665                 case COLLADAFW::Transformation::LOOKAT:
666                         fprintf(stderr, "Animation of MATRIX, SKEW and LOOKAT transformations is not supported yet.\n");
667                         break;
668                 }
669         
670 }
671
672 void AnimationImporter:: Assign_color_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves ,char * anim_type)
673 {
674         char rna_path[100];
675         BLI_strncpy(rna_path,anim_type, sizeof(rna_path));
676     
677         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
678         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
679                                 //all the curves belonging to the current binding
680         std::vector<FCurve*> animcurves;    
681         for (unsigned int j = 0; j < bindings.getCount(); j++) {
682                  animcurves = curve_map[bindings[j].animation];
683                 //calculate rnapaths and array index of fcurves according to transformation and animation class
684                  //Assign_color_animations( &bindings[j], &animcurves); 
685                 
686             switch (bindings[j].animationClass) {
687                 case COLLADAFW::AnimationList::COLOR_R:
688                         modify_fcurve(&animcurves, rna_path, 0 );
689                         break;
690                 case COLLADAFW::AnimationList::COLOR_G:
691                         modify_fcurve(&animcurves, rna_path, 1 );
692                         break;
693                 case COLLADAFW::AnimationList::COLOR_B:
694                         modify_fcurve(&animcurves, rna_path, 2 );
695                         break;
696                 case COLLADAFW::AnimationList::COLOR_RGB:
697                 case COLLADAFW::AnimationList::COLOR_RGBA:
698                         modify_fcurve(&animcurves, rna_path, -1 );
699                         break;
700                         
701                 default:
702                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
703                                         bindings[j].animationClass, "COLOR" );
704                 }
705
706                  std::vector<FCurve*>::iterator iter;
707                 //Add the curves of the current animation to the object
708                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
709                         FCurve * fcu = *iter;
710                         BLI_addtail(AnimCurves, fcu);   
711                 }                               
712         }
713
714         
715 }
716
717 void AnimationImporter:: Assign_float_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, char * anim_type)
718 {
719         char rna_path[100];
720         if (animlist_map.find(listid) == animlist_map.end()) return ;
721         else 
722         {
723                 //transformation has animations
724                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
725                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
726                 //all the curves belonging to the current binding
727                 std::vector<FCurve*> animcurves;    
728                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
729                          animcurves = curve_map[bindings[j].animation];
730                         //calculate rnapaths and array index of fcurves according to transformation and animation class
731                          BLI_strncpy(rna_path, anim_type , sizeof(rna_path));
732                          modify_fcurve(&animcurves, rna_path, 0 );
733                          std::vector<FCurve*>::iterator iter;
734                                 //Add the curves of the current animation to the object
735                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
736                                         FCurve * fcu = *iter;
737                                         BLI_addtail(AnimCurves, fcu);   
738                                 }                               
739                 }
740         }
741         
742 }
743
744 void AnimationImporter::translate_Animations_NEW ( COLLADAFW::Node * node , 
745                                                                                                    std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
746                                                                                                    std::map<COLLADAFW::UniqueId, Object*>& object_map,
747                                                                                                    std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map)
748 {
749         AnimationImporter::AnimMix* animType = get_animation_type(node, FW_object_map );
750
751         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
752         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
753         Object *ob = is_joint ? armature_importer->get_armature_for_joint(root) : object_map[node->getUniqueId()];
754         if (!ob)
755         {
756                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
757                 return;
758         }
759
760         bAction * act;
761         bActionGroup *grp = NULL;
762     
763         //if ( (animType & NODE_TRANSFORM) != 0 )
764         if ( (animType->transform) != 0 )
765         {
766         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
767         char joint_path[200];
768
769                 if ( is_joint ) 
770                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
771                 
772         
773                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
774                                         else act = ob->adt->action;
775                                         //Get the list of animation curves of the object
776             
777                 ListBase *AnimCurves = &(act->curves);
778
779                 const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
780         
781                 //for each transformation in node 
782                 for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
783                         COLLADAFW::Transformation *transform = nodeTransforms[i];
784                         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
785
786                         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
787                         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
788                                 
789                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
790                 
791                         //check if transformation has animations    
792                         if (animlist_map.find(listid) == animlist_map.end()) continue ; 
793                         else 
794                         {
795                                 //transformation has animations
796                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
797                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
798                                 //all the curves belonging to the current binding
799                                 std::vector<FCurve*> animcurves;    
800                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
801                                          animcurves = curve_map[bindings[j].animation];
802                                         //calculate rnapaths and array index of fcurves according to transformation and animation class
803                                          Assign_transform_animations(transform, &bindings[j], &animcurves, is_joint, joint_path ); 
804                                         
805                                          std::vector<FCurve*>::iterator iter;
806                                                 //Add the curves of the current animation to the object
807                                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
808                                                         FCurve * fcu = *iter;
809                                                          if (ob->type == OB_ARMATURE) 
810                                                                 add_bone_fcurve( ob, node , fcu );
811                                                          else 
812                                                          BLI_addtail(AnimCurves, fcu);  
813                                                 }                               
814                                 }
815                         }
816                         if (is_rotation || is_matrix) {
817                                 if (is_joint) 
818                                 {
819                                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
820                                         chan->rotmode = ROT_MODE_EUL;
821                                 }
822                                 else 
823                                 {
824                                         ob->rotmode = ROT_MODE_EUL;
825                                 }
826                         }
827                 }
828         }
829
830         if ((animType->light) != 0)
831         {
832                 Lamp * lamp  = (Lamp*) ob->data;
833
834                 if (!lamp->adt || !lamp->adt->action) act = verify_adt_action((ID*)&lamp->id, 1);
835                                         else act = lamp->adt->action;
836
837                 ListBase *AnimCurves = &(act->curves);
838                 const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
839
840                 for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
841                         const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
842
843                         if ((animType->light & LIGHT_COLOR) != 0)
844                         {
845                                 const COLLADAFW::Color *col =  &(light->getColor());
846                                 const COLLADAFW::UniqueId& listid = col->getAnimationList();
847                                 
848                                 Assign_color_animations(listid, AnimCurves, "color"); 
849                         }
850                         if ((animType->light & LIGHT_FOA) != 0 )
851                         {
852                                 const COLLADAFW::AnimatableFloat *foa =  &(light->getFallOffAngle());
853                                 const COLLADAFW::UniqueId& listid = foa->getAnimationList();
854                                 
855                                 Assign_float_animations( listid ,AnimCurves, "spot_size"); 
856                         }
857                         if ( (animType->light & LIGHT_FOE) != 0 )
858                         {
859                                 const COLLADAFW::AnimatableFloat *foe =  &(light->getFallOffExponent());
860                                 const COLLADAFW::UniqueId& listid = foe->getAnimationList();
861                                 
862                                 Assign_float_animations( listid ,AnimCurves, "spot_blend"); 
863                         
864                         }
865                 }
866         }
867
868         if ( (animType->camera) != 0) 
869         {
870                 Camera * camera  = (Camera*) ob->data;
871
872                 if (!camera->adt || !camera->adt->action) act = verify_adt_action((ID*)&camera->id, 1);
873                                         else act = camera->adt->action;
874
875                 ListBase *AnimCurves = &(act->curves);
876                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras= node->getInstanceCameras();
877
878                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
879                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
880
881                         if ((animType->camera & CAMERA_XFOV) != 0 )
882                         {
883                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
884                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
885                                 Assign_float_animations( listid ,AnimCurves, "lens"); 
886                         }
887
888                         else if ((animType->camera & CAMERA_XMAG) != 0 )
889                         {
890                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
891                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
892                                 Assign_float_animations( listid ,AnimCurves, "ortho_scale"); 
893                         }
894
895                         if ((animType->camera & CAMERA_ZFAR) != 0 )
896                         {
897                                 const COLLADAFW::AnimatableFloat *zfar =  &(camera->getFarClippingPlane());
898                                 const COLLADAFW::UniqueId& listid = zfar->getAnimationList();
899                                 Assign_float_animations( listid ,AnimCurves, "clip_end"); 
900                         }
901
902                         if ((animType->camera & CAMERA_ZNEAR) != 0 )
903                         {
904                                 const COLLADAFW::AnimatableFloat *znear =  &(camera->getNearClippingPlane());
905                                 const COLLADAFW::UniqueId& listid = znear->getAnimationList();
906                                 Assign_float_animations( listid ,AnimCurves, "clip_start"); 
907                         }
908
909                 }
910         }
911         if ( animType->material != 0){
912                  Material *ma = give_current_material(ob, 1);
913                  if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID*)&ma->id, 1);
914                                 else act = ma->adt->action;
915
916                 ListBase *AnimCurves = &(act->curves);
917                 
918                 const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
919                 for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
920                         const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
921                         for (unsigned int j = 0; j < matBinds.getCount(); j++) {
922                                 const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
923                                 const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
924                                 const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
925                                 COLLADAFW::EffectCommon *efc = commonEffects[0];
926                                 if((animType->material & MATERIAL_SHININESS) != 0){
927                                         const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
928                                         const COLLADAFW::UniqueId& listid =  shin->getAnimationList();
929                                         Assign_float_animations( listid, AnimCurves , "specular_hardness" );
930                                 }
931
932                                 if((animType->material & MATERIAL_IOR) != 0){
933                                         const COLLADAFW::FloatOrParam *ior = &(efc->getIndexOfRefraction());
934                                         const COLLADAFW::UniqueId& listid =  ior->getAnimationList();
935                                         Assign_float_animations( listid, AnimCurves , "raytrace_transparency.ior" );
936                                 }
937
938                                 if((animType->material & MATERIAL_SPEC_COLOR) != 0){
939                                         const COLLADAFW::ColorOrTexture *cot = &(efc->getSpecular());
940                                         const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
941                                         Assign_color_animations( listid, AnimCurves , "specular_color" );
942                                 }
943                                 
944                                 if((animType->material & MATERIAL_DIFF_COLOR) != 0){
945                                         const COLLADAFW::ColorOrTexture *cot = &(efc->getDiffuse());
946                                         const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
947                                         Assign_color_animations( listid, AnimCurves , "diffuse_color" );
948                                 }
949                         }
950                 }       
951         }
952 }
953
954
955 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
956 AnimationImporter::AnimMix* AnimationImporter::get_animation_type ( const COLLADAFW::Node * node , 
957                                                                                         std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map) 
958 {
959         AnimMix *types = new AnimMix();
960         
961         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
962         
963         //for each transformation in node 
964         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
965                 COLLADAFW::Transformation *transform = nodeTransforms[i];
966                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
967                 
968                 //check if transformation has animations    
969                 if (animlist_map.find(listid) == animlist_map.end()) continue ;
970                 else 
971                 {
972                         types->transform = types->transform|NODE_TRANSFORM;
973                         break;
974                 }
975         }
976         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
977
978         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
979                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
980                 types->light = setAnimType(&(light->getColor()),(types->light), LIGHT_COLOR);
981                 types->light = setAnimType(&(light->getFallOffAngle()),(types->light), LIGHT_FOA);
982                 types->light = setAnimType(&(light->getFallOffExponent()),(types->light), LIGHT_FOE);
983                 
984                 if ( types->light != 0) break;
985                 
986         }
987
988         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
989         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
990                 const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
991
992                 if ( camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE )
993                 {
994                     types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XFOV);
995                 }
996                 else 
997                 {
998                         types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XMAG);
999                 }
1000                 types->camera = setAnimType(&(camera->getFarClippingPlane()),(types->camera), CAMERA_ZFAR);
1001                 types->camera = setAnimType(&(camera->getNearClippingPlane()),(types->camera), CAMERA_ZNEAR);
1002
1003                 if ( types->camera != 0) break;
1004
1005         }
1006
1007         const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1008         for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1009                 const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1010                 for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1011                         const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1012                         const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1013                         const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
1014                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1015                         types->material =  setAnimType(&(efc->getShininess()),(types->material), MATERIAL_SHININESS);
1016                         types->material =  setAnimType(&(efc->getSpecular().getColor()),(types->material), MATERIAL_SPEC_COLOR);
1017                         types->material =  setAnimType(&(efc->getDiffuse().getColor()),(types->material), MATERIAL_DIFF_COLOR);
1018                    // types->material =  setAnimType(&(efc->get()),(types->material), MATERIAL_TRANSPARENCY);
1019                         types->material =  setAnimType(&(efc->getIndexOfRefraction()),(types->material), MATERIAL_IOR);
1020                 }
1021         }
1022         return types;
1023 }
1024
1025 int AnimationImporter::setAnimType ( const COLLADAFW::Animatable * prop , int types, int addition)
1026 {
1027                 const COLLADAFW::UniqueId& listid =  prop->getAnimationList();
1028                 if (animlist_map.find(listid) != animlist_map.end()) 
1029                                 return types|addition;
1030                 else return types;
1031 }               
1032
1033 //XXX Is not used anymore.
1034 void AnimationImporter::find_frames_old(std::vector<float> * frames, COLLADAFW::Node * node , COLLADAFW::Transformation::TransformationType tm_type)
1035 {
1036         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1037         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1038         // for each <rotate>, <translate>, etc. there is a separate Transformation
1039         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1040
1041         unsigned int i;
1042         // find frames at which to sample plus convert all rotation keys to radians
1043         for (i = 0; i < nodeTransforms.getCount(); i++) {
1044                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1045                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
1046
1047
1048                 if (nodeTmType == tm_type) {
1049                         //get animation bindings for the current transformation
1050                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1051                         //if transform is animated its animlist must exist.
1052                         if (animlist_map.find(listid) != animlist_map.end()) {
1053                                 
1054                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1055                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1056                 
1057                                 if (bindings.getCount()) {
1058                                         //for each AnimationBinding get the fcurves which animate the transform
1059                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
1060                                                 std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
1061                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
1062
1063                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
1064                                                         std::vector<FCurve*>::iterator iter;
1065
1066                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
1067                                                                 FCurve *fcu = *iter;
1068                                 
1069                                                                 //if transform is rotation the fcurves values must be turned in to radian.
1070                                                                 if (is_rotation)
1071                                                                         fcurve_deg_to_rad(fcu);
1072
1073                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1074                                                                         //get frame value from bezTriple
1075                                                                         float fra = fcu->bezt[k].vec[1][0];
1076                                                                         //if frame already not added add frame to frames
1077                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1078                                                                                 frames->push_back(fra);
1079                                                                 }
1080                                                         }
1081                                                 }
1082                                                 else {
1083                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1084                                                 }
1085                                         }
1086                                 }
1087                         }
1088                 }
1089         }
1090 }
1091
1092
1093 // prerequisites:
1094 // animlist_map - map animlist id -> animlist
1095 // curve_map - map anim id -> curve(s)
1096 Object *AnimationImporter::translate_animation(COLLADAFW::Node *node,
1097                                                         std::map<COLLADAFW::UniqueId, Object*>& object_map,
1098                                                         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
1099                                                         COLLADAFW::Transformation::TransformationType tm_type,
1100                                                         Object *par_job)
1101 {
1102         
1103         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1104         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1105         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1106         
1107         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1108         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1109         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1110         if (!ob) {
1111                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1112                 return NULL;
1113         }
1114
1115         // frames at which to sample
1116         std::vector<float> frames;
1117         
1118         find_frames_old(&frames, node , tm_type);
1119         
1120         unsigned int i;
1121         
1122         float irest_dae[4][4];
1123         float rest[4][4], irest[4][4];
1124
1125         if (is_joint) {
1126                 get_joint_rest_mat(irest_dae, root, node);
1127                 invert_m4(irest_dae);
1128
1129                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
1130                 if (!bone) {
1131                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1132                         return NULL;
1133                 }
1134
1135                 unit_m4(rest);
1136                 copy_m4_m4(rest, bone->arm_mat);
1137                 invert_m4_m4(irest, rest);
1138         }
1139
1140         Object *job = NULL;
1141
1142 #ifdef ARMATURE_TEST
1143         FCurve *job_curves[10];
1144         job = get_joint_object(root, node, par_job);
1145 #endif
1146
1147         if (frames.size() == 0)
1148                 return job;
1149
1150         std::sort(frames.begin(), frames.end());
1151
1152         const char *tm_str = NULL;
1153         switch (tm_type) {
1154         case COLLADAFW::Transformation::ROTATE:
1155                 tm_str = "rotation_quaternion";
1156                 break;
1157         case COLLADAFW::Transformation::SCALE:
1158                 tm_str = "scale";
1159                 break;
1160         case COLLADAFW::Transformation::TRANSLATE:
1161                 tm_str = "location";
1162                 break;
1163         case COLLADAFW::Transformation::MATRIX:
1164                 break;
1165         default:
1166                 return job;
1167         }
1168
1169         char rna_path[200];
1170         char joint_path[200];
1171
1172         if (is_joint)
1173                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1174
1175         // new curves
1176         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1177         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1178
1179         for (i = 0; i < totcu; i++) {
1180
1181                 int axis = i;
1182
1183                 if (is_matrix) {
1184                         if (i < 4) {
1185                                 tm_str = "rotation_quaternion";
1186                                 axis = i;
1187                         }
1188                         else if (i < 7) {
1189                                 tm_str = "location";
1190                                 axis = i - 4;
1191                         }
1192                         else {
1193                                 tm_str = "scale";
1194                                 axis = i - 7;
1195                         }
1196                 }
1197
1198                 if (is_joint)
1199                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1200                 else
1201                         strcpy(rna_path, tm_str);
1202                 newcu[i] = create_fcurve(axis, rna_path);
1203
1204 #ifdef ARMATURE_TEST
1205                 if (is_joint)
1206                         job_curves[i] = create_fcurve(axis, tm_str);
1207 #endif
1208         }
1209
1210         std::vector<float>::iterator it;
1211
1212         // sample values at each frame
1213         for (it = frames.begin(); it != frames.end(); it++) {
1214                 float fra = *it;
1215
1216                 float mat[4][4];
1217                 float matfra[4][4];
1218
1219                 unit_m4(matfra);
1220
1221                 // calc object-space mat
1222                 evaluate_transform_at_frame(matfra, node, fra);
1223
1224                 // for joints, we need a special matrix
1225                 if (is_joint) {
1226                         // special matrix: iR * M * iR_dae * R
1227                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1228                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1229                         float temp[4][4], par[4][4];
1230
1231                         // calc M
1232                         calc_joint_parent_mat_rest(par, NULL, root, node);
1233                         mul_m4_m4m4(temp, matfra, par);
1234
1235                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
1236
1237                         // calc special matrix
1238                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1239                 }
1240                 else {
1241                         copy_m4_m4(mat, matfra);
1242                 }
1243
1244                 float val[4], rot[4], loc[3], scale[3];
1245
1246                 switch (tm_type) {
1247                 case COLLADAFW::Transformation::ROTATE:
1248                         mat4_to_quat(val, mat);
1249                         break;
1250                 case COLLADAFW::Transformation::SCALE:
1251                         mat4_to_size(val, mat);
1252                         break;
1253                 case COLLADAFW::Transformation::TRANSLATE:
1254                         copy_v3_v3(val, mat[3]);
1255                         break;
1256                 case COLLADAFW::Transformation::MATRIX:
1257                         mat4_to_quat(rot, mat);
1258                         copy_v3_v3(loc, mat[3]);
1259                         mat4_to_size(scale, mat);
1260                         break;
1261                 default:
1262                         break;
1263                 }
1264
1265                 // add keys
1266                 for (i = 0; i < totcu; i++) {
1267                         if (is_matrix) {
1268                                 if (i < 4)
1269                                         add_bezt(newcu[i], fra, rot[i]);
1270                                 else if (i < 7)
1271                                         add_bezt(newcu[i], fra, loc[i - 4]);
1272                                 else
1273                                         add_bezt(newcu[i], fra, scale[i - 7]);
1274                         }
1275                         else {
1276                                 add_bezt(newcu[i], fra, val[i]);
1277                         }
1278                 }
1279
1280 #ifdef ARMATURE_TEST
1281                 if (is_joint) {
1282                         switch (tm_type) {
1283                         case COLLADAFW::Transformation::ROTATE:
1284                                 mat4_to_quat(val, matfra);
1285                                 break;
1286                         case COLLADAFW::Transformation::SCALE:
1287                                 mat4_to_size(val, matfra);
1288                                 break;
1289                         case COLLADAFW::Transformation::TRANSLATE:
1290                                 copy_v3_v3(val, matfra[3]);
1291                                 break;
1292                         case MATRIX:
1293                                 mat4_to_quat(rot, matfra);
1294                                 copy_v3_v3(loc, matfra[3]);
1295                                 mat4_to_size(scale, matfra);
1296                                 break;
1297                         default:
1298                                 break;
1299                         }
1300
1301                         for (i = 0; i < totcu; i++) {
1302                                 if (is_matrix) {
1303                                         if (i < 4)
1304                                                 add_bezt(job_curves[i], fra, rot[i]);
1305                                         else if (i < 7)
1306                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1307                                         else
1308                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1309                                 }
1310                                 else {
1311                                         add_bezt(job_curves[i], fra, val[i]);
1312                                 }
1313                         }
1314                 }
1315 #endif
1316         }
1317
1318         verify_adt_action((ID*)&ob->id, 1);
1319
1320         ListBase *curves = &ob->adt->action->curves;
1321
1322         // add curves
1323         for (i = 0; i < totcu; i++) {
1324                 if (is_joint)
1325                         add_bone_fcurve(ob, node, newcu[i]);
1326                 else
1327                         BLI_addtail(curves, newcu[i]);
1328
1329 #ifdef ARMATURE_TEST
1330                 if (is_joint)
1331                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1332 #endif
1333         }
1334
1335         if (is_rotation || is_matrix) {
1336                 if (is_joint) {
1337                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
1338                         chan->rotmode = ROT_MODE_QUAT;
1339                 }
1340                 else {
1341                         ob->rotmode = ROT_MODE_QUAT;
1342                 }
1343         }
1344
1345         return job;
1346 }
1347
1348 // internal, better make it private
1349 // warning: evaluates only rotation
1350 // prerequisites: animlist_map, curve_map
1351 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1352 {
1353         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1354
1355         unit_m4(mat);
1356
1357         for (unsigned int i = 0; i < tms.getCount(); i++) {
1358                 COLLADAFW::Transformation *tm = tms[i];
1359                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1360                 float m[4][4];
1361
1362                 unit_m4(m);
1363
1364                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1365                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1366                         switch (type) {
1367                         case COLLADAFW::Transformation::ROTATE:
1368                                 dae_rotate_to_mat4(tm, m);
1369                                 break;
1370                         case COLLADAFW::Transformation::TRANSLATE:
1371                                 dae_translate_to_mat4(tm, m);
1372                                 break;
1373                         case COLLADAFW::Transformation::SCALE:
1374                                 dae_scale_to_mat4(tm, m);
1375                                 break;
1376                         case COLLADAFW::Transformation::MATRIX:
1377                                 dae_matrix_to_mat4(tm, m);
1378                                 break;
1379                         default:
1380                                 fprintf(stderr, "unsupported transformation type %d\n", type);
1381                         }
1382                 }
1383
1384                 float temp[4][4];
1385                 copy_m4_m4(temp, mat);
1386
1387                 mul_m4_m4m4(mat, m, temp);
1388         }
1389 }
1390
1391 // return true to indicate that mat contains a sane value
1392 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1393 {
1394         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1395         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1396
1397         if (type != COLLADAFW::Transformation::ROTATE &&
1398             type != COLLADAFW::Transformation::SCALE &&
1399             type != COLLADAFW::Transformation::TRANSLATE &&
1400             type != COLLADAFW::Transformation::MATRIX) {
1401                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1402                 return false;
1403         }
1404
1405         if (animlist_map.find(listid) == animlist_map.end())
1406                 return false;
1407
1408         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1409         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1410
1411         if (bindings.getCount()) {
1412                 float vec[3];
1413
1414                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1415                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1416
1417                 if (type == COLLADAFW::Transformation::SCALE)
1418                         dae_scale_to_v3(tm, vec);
1419                 else if (type == COLLADAFW::Transformation::TRANSLATE)
1420                         dae_translate_to_v3(tm, vec);
1421
1422                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1423                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1424                         std::vector<FCurve*>& curves = curve_map[binding.animation];
1425                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1426                         char path[100];
1427
1428                         switch (type) {
1429                         case COLLADAFW::Transformation::ROTATE:
1430                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1431                                 break;
1432                         case COLLADAFW::Transformation::SCALE:
1433                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1434                                 break;
1435                         case COLLADAFW::Transformation::TRANSLATE:
1436                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1437                                 break;
1438                         case COLLADAFW::Transformation::MATRIX:
1439                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1440                                 break;
1441                         default:
1442                                 break;
1443                         }
1444
1445                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1446                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1447                                 continue;
1448                         }
1449
1450                         if (type == COLLADAFW::Transformation::ROTATE) {
1451                                 if (curves.size() != 1) {
1452                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1453                                         return false;
1454                                 }
1455
1456                                 // TODO support other animclasses
1457                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1458                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1459                                         return false;
1460                                 }
1461
1462                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
1463                                 float ax[3] = {axis[0], axis[1], axis[2]};
1464                                 float angle = evaluate_fcurve(curves[0], fra);
1465                                 axis_angle_to_mat4(mat, ax, angle);
1466
1467                                 return true;
1468                         }
1469                         else if (is_scale || is_translate) {
1470                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1471
1472                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1473                                         if (is_xyz)
1474                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1475                                         else
1476                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1477                                         return false;
1478                                 }
1479                                 
1480                                 switch (animclass) {
1481                                 case COLLADAFW::AnimationList::POSITION_X:
1482                                         vec[0] = evaluate_fcurve(curves[0], fra);
1483                                         break;
1484                                 case COLLADAFW::AnimationList::POSITION_Y:
1485                                         vec[1] = evaluate_fcurve(curves[0], fra);
1486                                         break;
1487                                 case COLLADAFW::AnimationList::POSITION_Z:
1488                                         vec[2] = evaluate_fcurve(curves[0], fra);
1489                                         break;
1490                                 case COLLADAFW::AnimationList::POSITION_XYZ:
1491                                         vec[0] = evaluate_fcurve(curves[0], fra);
1492                                         vec[1] = evaluate_fcurve(curves[1], fra);
1493                                         vec[2] = evaluate_fcurve(curves[2], fra);
1494                                         break;
1495                                 default:
1496                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1497                                         break;
1498                                 }
1499                         }
1500                         else if (type == COLLADAFW::Transformation::MATRIX) {
1501                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1502                                 if (curves.size() != 16) {
1503                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1504                                         return false;
1505                                 }
1506
1507                                 COLLADABU::Math::Matrix4 matrix;
1508                                 int i = 0, j = 0;
1509
1510                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
1511                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1512                                         j++;
1513                                         if (j == 4) {
1514                                                 i++;
1515                                                 j = 0;
1516                                         }
1517                                 }
1518
1519                                 COLLADAFW::Matrix tm(matrix);
1520                                 dae_matrix_to_mat4(&tm, mat);
1521
1522                                 return true;
1523                         }
1524                 }
1525
1526                 if (is_scale)
1527                         size_to_mat4(mat, vec);
1528                 else
1529                         copy_v3_v3(mat[3], vec);
1530
1531                 return is_scale || is_translate;
1532         }
1533
1534         return false;
1535 }
1536
1537 // gives a world-space mat of joint at rest position
1538 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1539 {
1540         // if bind mat is not available,
1541         // use "current" node transform, i.e. all those tms listed inside <node>
1542         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1543                 float par[4][4], m[4][4];
1544
1545                 calc_joint_parent_mat_rest(par, NULL, root, node);
1546                 get_node_mat(m, node, NULL, NULL);
1547                 mul_m4_m4m4(mat, m, par);
1548         }
1549 }
1550
1551 // gives a world-space mat, end's mat not included
1552 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1553 {
1554         float m[4][4];
1555
1556         if (node == end) {
1557                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1558                 return true;
1559         }
1560
1561         // use bind matrix if available or calc "current" world mat
1562         if (!armature_importer->get_joint_bind_mat(m, node)) {
1563                 if (par) {
1564                         float temp[4][4];
1565                         get_node_mat(temp, node, NULL, NULL);
1566                         mul_m4_m4m4(m, temp, par);
1567                 }
1568                 else {
1569                         get_node_mat(m, node, NULL, NULL);
1570                 }
1571         }
1572
1573         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1574         for (unsigned int i = 0; i < children.getCount(); i++) {
1575                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1576                         return true;
1577         }
1578
1579         return false;
1580 }
1581
1582 #ifdef ARMATURE_TEST
1583 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1584 {
1585         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1586                 Object *job = add_object(scene, OB_EMPTY);
1587
1588                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1589
1590                 job->lay = object_in_scene(job, scene)->lay = 2;
1591
1592                 mul_v3_fl(job->size, 0.5f);
1593                 job->recalc |= OB_RECALC_OB;
1594
1595                 verify_adt_action((ID*)&job->id, 1);
1596
1597                 job->rotmode = ROT_MODE_QUAT;
1598
1599                 float mat[4][4];
1600                 get_joint_rest_mat(mat, root, node);
1601
1602                 if (par_job) {
1603                         float temp[4][4], ipar[4][4];
1604                         invert_m4_m4(ipar, par_job->obmat);
1605                         copy_m4_m4(temp, mat);
1606                         mul_m4_m4m4(mat, temp, ipar);
1607                 }
1608
1609                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1610
1611                 if (par_job) {
1612                         job->parent = par_job;
1613
1614                         par_job->recalc |= OB_RECALC_OB;
1615                         job->parsubstr[0] = 0;
1616                 }
1617
1618                 where_is_object(scene, job);
1619
1620                 // after parenting and layer change
1621                 DAG_scene_sort(CTX_data_main(C), scene);
1622
1623                 joint_objects[node->getUniqueId()] = job;
1624         }
1625
1626         return joint_objects[node->getUniqueId()];
1627 }
1628 #endif
1629
1630 #if 0
1631 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1632 // mat must be identity on enter, node must be root
1633 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1634 {
1635         float m[4][4];
1636         if (par) {
1637                 float temp[4][4];
1638                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1639                 mul_m4_m4m4(m, temp, par);
1640         }
1641         else {
1642                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1643         }
1644
1645         if (node == end) {
1646                 copy_m4_m4(mat, m);
1647                 return true;
1648         }
1649         else {
1650                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1651                 for (int i = 0; i < children.getCount(); i++) {
1652                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1653                                 return true;
1654                 }
1655         }
1656
1657         return false;
1658 }
1659 #endif
1660
1661 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1662 {
1663         const char *bone_name = bc_get_joint_name(node);
1664         bAction *act = ob->adt->action;
1665                         
1666         /* try to find group */
1667         bActionGroup *grp = action_groups_find_named(act, bone_name);
1668
1669         /* no matching groups, so add one */
1670         if (grp == NULL) {
1671                 /* Add a new group, and make it active */
1672                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1673                                         
1674                 grp->flag = AGRP_SELECTED;
1675                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1676                                         
1677                 BLI_addtail(&act->groups, grp);
1678                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1679         }
1680                                 
1681         /* add F-Curve to group */
1682         action_groups_add_channel(act, grp, fcu);
1683 }
1684
1685 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1686 {
1687         BezTriple bez;
1688         memset(&bez, 0, sizeof(BezTriple));
1689         bez.vec[1][0] = fra;
1690         bez.vec[1][1] = value;
1691         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1692         bez.f1 = bez.f2 = bez.f3 = SELECT;
1693         bez.h1 = bez.h2 = HD_AUTO;
1694         insert_bezt_fcurve(fcu, &bez, 0);
1695         calchandles_fcurve(fcu);
1696 }