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