fix:T50079 collada matrix and blender matrix are transposed. This was not regarded...
[blender.git] / source / blender / collada / AnimationImporter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory, Sukhitha Jayathilake.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/collada/AnimationImporter.cpp
24  *  \ingroup collada
25  */
26
27 #include <stddef.h>
28
29 /* COLLADABU_ASSERT, may be able to remove later */
30 #include "COLLADABUPlatform.h"
31
32 #include "DNA_armature_types.h"
33
34 #include "ED_keyframing.h"
35
36 #include "BLI_listbase.h"
37 #include "BLI_math.h"
38 #include "BLI_string.h"
39 #include "BLI_string_utils.h"
40
41 #include "BLT_translation.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         fcu->flag = (FCURVE_VISIBLE | FCURVE_AUTO_HANDLES | FCURVE_SELECTED);
69         fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
70         fcu->array_index = array_index;
71         return fcu;
72 }
73         
74 void AnimationImporter::create_bezt(FCurve *fcu, float frame, float output)
75 {
76         BezTriple bez;
77         memset(&bez, 0, sizeof(BezTriple));
78         bez.vec[1][0] = frame;
79         bez.vec[1][1] = output;
80         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
81         bez.f1 = bez.f2 = bez.f3 = SELECT;
82         bez.h1 = bez.h2 = HD_AUTO;
83         insert_bezt_fcurve(fcu, &bez, 0);
84         calchandles_fcurve(fcu);
85 }
86
87 // create one or several fcurves depending on the number of parameters being animated
88 void AnimationImporter::animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
89 {
90         COLLADAFW::FloatOrDoubleArray& input = curve->getInputValues();
91         COLLADAFW::FloatOrDoubleArray& output = curve->getOutputValues();
92
93         float fps = (float)FPS;
94         size_t dim = curve->getOutDimension();
95         unsigned int i;
96
97         std::vector<FCurve *>& fcurves = curve_map[curve->getUniqueId()];
98
99         switch (dim) {
100                 case 1: // X, Y, Z or angle
101                 case 3: // XYZ
102                 case 4:
103                 case 16: // matrix
104                 {
105                         for (i = 0; i < dim; i++) {
106                                 FCurve *fcu = (FCurve *)MEM_callocN(sizeof(FCurve), "FCurve");
107
108                                 fcu->flag = (FCURVE_VISIBLE | FCURVE_AUTO_HANDLES | FCURVE_SELECTED);
109                                 // fcu->rna_path = BLI_strdupn(path, strlen(path));
110                                 fcu->array_index = 0;
111                                 fcu->totvert = curve->getKeyCount();
112
113                                 // create beztriple for each key
114                                 for (unsigned int j = 0; j < curve->getKeyCount(); j++) {
115                                         BezTriple bez;
116                                         memset(&bez, 0, sizeof(BezTriple));
117
118
119                                         // input, output
120                                         bez.vec[1][0] = bc_get_float_value(input, j) * fps; 
121                                         bez.vec[1][1] = bc_get_float_value(output, j * dim + i);
122
123
124                                         if (curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER ||
125                                             curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_STEP)
126                                         {
127                                                 COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
128                                                 COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
129
130                                                 // intangent
131                                                 bez.vec[0][0] = bc_get_float_value(intan, (j * 2 * dim) + (2 * i)) * fps;
132                                                 bez.vec[0][1] = bc_get_float_value(intan, (j * 2 * dim) + (2 * i) + 1);
133
134                                                 // outtangent
135                                                 bez.vec[2][0] = bc_get_float_value(outtan, (j * 2 * dim) + (2 * i)) * fps;
136                                                 bez.vec[2][1] = bc_get_float_value(outtan, (j * 2 * dim) + (2 * i) + 1);
137                                                 if (curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER) 
138                                                         bez.ipo = BEZT_IPO_BEZ;
139                                                 else 
140                                                         bez.ipo = BEZT_IPO_CONST;
141                                                 //bez.h1 = bez.h2 = HD_AUTO;
142                                         }
143                                         else {
144                                                 bez.h1 = bez.h2 = HD_AUTO; 
145                                                 bez.ipo = BEZT_IPO_LIN;
146                                         }
147                                         // bez.ipo = U.ipo_new; /* use default interpolation mode here... */
148                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
149
150                                         insert_bezt_fcurve(fcu, &bez, 0);
151                                 }
152
153                                 calchandles_fcurve(fcu);
154
155                                 fcurves.push_back(fcu);
156                                 unused_curves.push_back(fcu);
157                         }
158                 }
159                 break;
160                 default:
161                         fprintf(stderr, "Output dimension of %d is not yet supported (animation id = %s)\n", (int)dim, curve->getOriginalId().c_str());
162         }
163 }
164
165
166 void AnimationImporter::fcurve_deg_to_rad(FCurve *cu)
167 {
168         for (unsigned int i = 0; i < cu->totvert; i++) {
169                 // TODO convert handles too
170                 cu->bezt[i].vec[1][1] *= DEG2RADF(1.0f);
171                 cu->bezt[i].vec[0][1] *= DEG2RADF(1.0f);
172                 cu->bezt[i].vec[2][1] *= DEG2RADF(1.0f);
173         }
174 }
175
176 void AnimationImporter::fcurve_is_used(FCurve *fcu)
177 {
178         unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
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 = BKE_action_group_find_name(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, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "Group"), '.',
226                                                        offsetof(bActionGroup, name), 64);
227                                 }
228                                 
229                                 /* add F-Curve to group */
230                                 action_groups_add_channel(act, grp, fcu);
231                                 fcurve_is_used(fcu);
232                                 
233                         }
234 #if 0
235                         if (is_rotation) {
236                                 fcurves_actionGroup_map[grp].push_back(fcu);
237                         }
238 #endif
239                 }
240                 else {
241                         BLI_addtail(&act->curves, fcu);
242                         fcurve_is_used(fcu);
243                 }
244         }
245 }
246
247 AnimationImporter::AnimationImporter(UnitConverter *conv, ArmatureImporter *arm, Scene *scene) :
248         TransformReader(conv), armature_importer(arm), scene(scene) {
249 }
250
251 AnimationImporter::~AnimationImporter()
252 {
253         // free unused FCurves
254         for (std::vector<FCurve *>::iterator it = unused_curves.begin(); it != unused_curves.end(); it++)
255                 free_fcurve(*it);
256
257         if (unused_curves.size())
258                 fprintf(stderr, "removed %d unused curves\n", (int)unused_curves.size());
259 }
260
261 bool AnimationImporter::write_animation(const COLLADAFW::Animation *anim)
262 {
263         if (anim->getAnimationType() == COLLADAFW::Animation::ANIMATION_CURVE) {
264                 COLLADAFW::AnimationCurve *curve = (COLLADAFW::AnimationCurve *)anim;
265                 
266                 // XXX Don't know if it's necessary
267                 // Should we check outPhysicalDimension?
268                 if (curve->getInPhysicalDimension() != COLLADAFW::PHYSICAL_DIMENSION_TIME) {
269                         fprintf(stderr, "Inputs physical dimension is not time.\n");
270                         return true;
271                 }
272
273                 // a curve can have mixed interpolation type,
274                 // in this case curve->getInterpolationTypes returns a list of interpolation types per key
275                 COLLADAFW::AnimationCurve::InterpolationType interp = curve->getInterpolationType();
276
277                 if (interp != COLLADAFW::AnimationCurve::INTERPOLATION_MIXED) {
278                         switch (interp) {
279                                 case COLLADAFW::AnimationCurve::INTERPOLATION_LINEAR:
280                                 case COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER:
281                                 case COLLADAFW::AnimationCurve::INTERPOLATION_STEP:
282                                         animation_to_fcurves(curve);
283                                         break;
284                                 default:
285                                         // TODO there're also CARDINAL, HERMITE, BSPLINE and STEP types
286                                         fprintf(stderr, "CARDINAL, HERMITE and BSPLINE anim interpolation types not supported yet.\n");
287                                         break;
288                         }
289                 }
290                 else {
291                         // not supported yet
292                         fprintf(stderr, "MIXED anim interpolation type is not supported yet.\n");
293                 }
294         }
295         else {
296                 fprintf(stderr, "FORMULA animation type is not supported yet.\n");
297         }
298         
299         return true;
300 }
301         
302 // called on post-process stage after writeVisualScenes
303 bool AnimationImporter::write_animation_list(const COLLADAFW::AnimationList *animlist)
304 {
305         const COLLADAFW::UniqueId& animlist_id = animlist->getUniqueId();
306
307         animlist_map[animlist_id] = animlist;
308
309 #if 0
310
311         // should not happen
312         if (uid_animated_map.find(animlist_id) == uid_animated_map.end()) {
313                 return true;
314         }
315
316         // for bones rna_path is like: pose.bones["bone-name"].rotation
317
318
319 #endif
320
321         return true;
322 }
323
324 // \todo refactor read_node_transform to not automatically apply anything,
325 // but rather return the transform matrix, so caller can do with it what is
326 // necessary. Same for \ref get_node_mat
327 void AnimationImporter::read_node_transform(COLLADAFW::Node *node, Object *ob)
328 {
329         float mat[4][4];
330         TransformReader::get_node_mat(mat, node, &uid_animated_map, ob);
331         if (ob) {
332                 copy_m4_m4(ob->obmat, mat);
333                 BKE_object_apply_mat4(ob, ob->obmat, 0, 0);
334         }
335 }
336
337 #if 0
338 virtual void AnimationImporter::change_eul_to_quat(Object *ob, bAction *act)
339 {
340         bActionGroup *grp;
341         int i;
342         
343         for (grp = (bActionGroup *)act->groups.first; grp; grp = grp->next) {
344
345                 FCurve *eulcu[3] = {NULL, NULL, NULL};
346                 
347                 if (fcurves_actionGroup_map.find(grp) == fcurves_actionGroup_map.end())
348                         continue;
349
350                 std::vector<FCurve *> &rot_fcurves = fcurves_actionGroup_map[grp];
351                 
352                 if (rot_fcurves.size() > 3) continue;
353
354                 for (i = 0; i < rot_fcurves.size(); i++)
355                         eulcu[rot_fcurves[i]->array_index] = rot_fcurves[i];
356
357                 char joint_path[100];
358                 char rna_path[100];
359
360                 BLI_snprintf(joint_path, sizeof(joint_path), "pose.bones[\"%s\"]", grp->name);
361                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_quaternion", joint_path);
362
363                 FCurve *quatcu[4] = {
364                         create_fcurve(0, rna_path),
365                         create_fcurve(1, rna_path),
366                         create_fcurve(2, rna_path),
367                         create_fcurve(3, rna_path)
368                 };
369
370                 bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, grp->name);
371
372                 float m4[4][4], irest[3][3];
373                 invert_m4_m4(m4, chan->bone->arm_mat);
374                 copy_m3_m4(irest, m4);
375
376                 for (i = 0; i < 3; i++) {
377
378                         FCurve *cu = eulcu[i];
379
380                         if (!cu) continue;
381
382                         for (int j = 0; j < cu->totvert; j++) {
383                                 float frame = cu->bezt[j].vec[1][0];
384
385                                 float eul[3] = {
386                                         eulcu[0] ? evaluate_fcurve(eulcu[0], frame) : 0.0f,
387                                         eulcu[1] ? evaluate_fcurve(eulcu[1], frame) : 0.0f,
388                                         eulcu[2] ? evaluate_fcurve(eulcu[2], frame) : 0.0f
389                                 };
390
391                                 // make eul relative to bone rest pose
392                                 float rot[3][3], rel[3][3], quat[4];
393
394                                 /*eul_to_mat3(rot, eul);
395
396                                    mul_m3_m3m3(rel, irest, rot);
397
398                                    mat3_to_quat(quat, rel);
399                                  */
400
401                                 eul_to_quat(quat, eul);
402
403                                 for (int k = 0; k < 4; k++)
404                                         create_bezt(quatcu[k], frame, quat[k]);
405                         }
406                 }
407
408                 // now replace old Euler curves
409
410                 for (i = 0; i < 3; i++) {
411                         if (!eulcu[i]) continue;
412
413                         action_groups_remove_channel(act, eulcu[i]);
414                         free_fcurve(eulcu[i]);
415                 }
416
417                 chan->rotmode = ROT_MODE_QUAT;
418
419                 for (i = 0; i < 4; i++)
420                         action_groups_add_channel(act, grp, quatcu[i]);
421         }
422
423         bPoseChannel *pchan;
424         for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = pchan->next) {
425                 pchan->rotmode = ROT_MODE_QUAT;
426         }
427 }
428 #endif
429
430
431 //sets the rna_path and array index to curve
432 void AnimationImporter::modify_fcurve(std::vector<FCurve *> *curves, const char *rna_path, int array_index)
433 {
434         std::vector<FCurve *>::iterator it;
435         int i;
436         for (it = curves->begin(), i = 0; it != curves->end(); it++, i++) {
437                 FCurve *fcu = *it;
438                 fcu->rna_path = BLI_strdup(rna_path);
439                 
440                 if (array_index == -1) fcu->array_index = i;
441                 else fcu->array_index = array_index;
442
443                 fcurve_is_used(fcu);
444         }
445 }
446
447 void AnimationImporter::unused_fcurve(std::vector<FCurve *> *curves)
448 {
449         // when an error happens and we can't actually use curve remove it from unused_curves
450         std::vector<FCurve *>::iterator it;
451         for (it = curves->begin(); it != curves->end(); it++) {
452                 FCurve *fcu = *it;
453                 fcurve_is_used(fcu);
454         }
455 }
456
457 void AnimationImporter::find_frames(std::vector<float> *frames, std::vector<FCurve *> *curves)
458 {
459         std::vector<FCurve *>::iterator iter;
460         for (iter = curves->begin(); iter != curves->end(); iter++) {
461                 FCurve *fcu = *iter;
462
463                 for (unsigned int k = 0; k < fcu->totvert; k++) {
464                         //get frame value from bezTriple
465                         float fra = fcu->bezt[k].vec[1][0];
466                         //if frame already not added add frame to frames
467                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
468                                 frames->push_back(fra);
469
470                 }
471         }
472 }
473
474 //creates the rna_paths and array indices of fcurves from animations using transformation and bound animation class of each animation.
475 void AnimationImporter:: Assign_transform_animations(COLLADAFW::Transformation *transform,
476                                                      const COLLADAFW::AnimationList::AnimationBinding *binding,
477                                                      std::vector<FCurve *> *curves, bool is_joint, char *joint_path)
478 {
479         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
480         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
481         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
482
483         //to check if the no of curves are valid
484         bool xyz = ((tm_type == COLLADAFW::Transformation::TRANSLATE || tm_type == COLLADAFW::Transformation::SCALE) && binding->animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
485
486
487         if (!((!xyz && curves->size() == 1) || (xyz && curves->size() == 3) || is_matrix)) {
488                 fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves->size());
489                 return;
490         }
491
492         char rna_path[100];
493
494         switch (tm_type) {
495                 case COLLADAFW::Transformation::TRANSLATE:
496                 case COLLADAFW::Transformation::SCALE:
497                 {
498                         bool loc = tm_type == COLLADAFW::Transformation::TRANSLATE;
499                         if (is_joint)
500                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
501                         else
502                                 BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
503
504                         switch (binding->animationClass) {
505                                 case COLLADAFW::AnimationList::POSITION_X:
506                                         modify_fcurve(curves, rna_path, 0);
507                                         break;
508                                 case COLLADAFW::AnimationList::POSITION_Y:
509                                         modify_fcurve(curves, rna_path, 1);
510                                         break;
511                                 case COLLADAFW::AnimationList::POSITION_Z:
512                                         modify_fcurve(curves, rna_path, 2);
513                                         break;
514                                 case COLLADAFW::AnimationList::POSITION_XYZ:
515                                         modify_fcurve(curves, rna_path, -1);
516                                         break;
517                                 default:
518                                         unused_fcurve(curves);
519                                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
520                                                 binding->animationClass, loc ? "TRANSLATE" : "SCALE");
521                         }
522                         break;
523                 }
524
525
526                 case COLLADAFW::Transformation::ROTATE:
527                 {
528                         if (is_joint)
529                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
530                         else
531                                 BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
532                         std::vector<FCurve *>::iterator iter;
533                         for (iter = curves->begin(); iter != curves->end(); iter++) {
534                                 FCurve *fcu = *iter;
535
536                                 //if transform is rotation the fcurves values must be turned in to radian.
537                                 if (is_rotation)
538                                         fcurve_deg_to_rad(fcu);
539                         }
540                         COLLADAFW::Rotate *rot = (COLLADAFW::Rotate *)transform;
541                         COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
542
543                         switch (binding->animationClass) {
544                                 case COLLADAFW::AnimationList::ANGLE:
545                                         if (COLLADABU::Math::Vector3::UNIT_X == axis) {
546                                                 modify_fcurve(curves, rna_path, 0);
547                                         }
548                                         else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
549                                                 modify_fcurve(curves, rna_path, 1);
550                                         }
551                                         else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
552                                                 modify_fcurve(curves, rna_path, 2);
553                                         }
554                                         else
555                                                 unused_fcurve(curves);
556                                         break;
557                                 case COLLADAFW::AnimationList::AXISANGLE:
558                                 // TODO convert axis-angle to quat? or XYZ?
559                                 default:
560                                         unused_fcurve(curves);
561                                         fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
562                                                 binding->animationClass);
563                         }
564                         break;
565                 }
566
567                 case COLLADAFW::Transformation::MATRIX:
568                         /*{
569                            COLLADAFW::Matrix *mat = (COLLADAFW::Matrix*)transform;
570                            COLLADABU::Math::Matrix4 mat4 = mat->getMatrix();
571                            switch (binding->animationClass) {
572                            case COLLADAFW::AnimationList::TRANSFORM:
573
574                            }
575                            }*/
576                         unused_fcurve(curves);
577                         break;
578                 case COLLADAFW::Transformation::SKEW:
579                 case COLLADAFW::Transformation::LOOKAT:
580                         unused_fcurve(curves);
581                         fprintf(stderr, "Animation of SKEW and LOOKAT transformations is not supported yet.\n");
582                         break;
583         }
584
585 }
586
587 //creates the rna_paths and array indices of fcurves from animations using color and bound animation class of each animation.
588 void AnimationImporter:: Assign_color_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, const char *anim_type)
589 {
590         char rna_path[100];
591         BLI_strncpy(rna_path, anim_type, sizeof(rna_path));
592
593         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
594         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
595         //all the curves belonging to the current binding
596         std::vector<FCurve *> animcurves;
597         for (unsigned int j = 0; j < bindings.getCount(); j++) {
598                 animcurves = curve_map[bindings[j].animation];
599
600                 switch (bindings[j].animationClass) {
601                         case COLLADAFW::AnimationList::COLOR_R:
602                                 modify_fcurve(&animcurves, rna_path, 0);
603                                 break;
604                         case COLLADAFW::AnimationList::COLOR_G:
605                                 modify_fcurve(&animcurves, rna_path, 1);
606                                 break;
607                         case COLLADAFW::AnimationList::COLOR_B:
608                                 modify_fcurve(&animcurves, rna_path, 2);
609                                 break;
610                         case COLLADAFW::AnimationList::COLOR_RGB:
611                         case COLLADAFW::AnimationList::COLOR_RGBA: // to do-> set intensity
612                                 modify_fcurve(&animcurves, rna_path, -1);
613                                 break;
614
615                         default:
616                                 unused_fcurve(&animcurves);
617                                 fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
618                                         bindings[j].animationClass, "COLOR");
619                 }
620
621                 std::vector<FCurve *>::iterator iter;
622                 //Add the curves of the current animation to the object
623                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
624                         FCurve *fcu = *iter;
625                         BLI_addtail(AnimCurves, fcu);
626                         fcurve_is_used(fcu);
627                 }
628         }
629 }
630
631 void AnimationImporter:: Assign_float_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, const char *anim_type)
632 {
633         char rna_path[100];
634         if (animlist_map.find(listid) == animlist_map.end()) {
635                 return;
636         }
637         else {
638                 //anim_type has animations
639                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
640                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
641                 //all the curves belonging to the current binding
642                 std::vector<FCurve *> animcurves;
643                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
644                         animcurves = curve_map[bindings[j].animation];
645
646                         BLI_strncpy(rna_path, anim_type, sizeof(rna_path));
647                         modify_fcurve(&animcurves, rna_path, 0);
648                         std::vector<FCurve *>::iterator iter;
649                         //Add the curves of the current animation to the object
650                         for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
651                                 FCurve *fcu = *iter;
652                                 /* All anim_types whose values are to be converted from Degree to Radians can be ORed here */
653                                 if (STREQ("spot_size", anim_type)) {
654                                         /* NOTE: Do NOT convert if imported file was made by blender <= 2.69.10
655                                          * Reason: old blender versions stored spot_size in radians (was a bug)
656                                          */
657                                         if (this->import_from_version == "" || BLI_natstrcmp(this->import_from_version.c_str(), "2.69.10") != -1) {
658                                                 fcurve_deg_to_rad(fcu);
659                                         }
660                                 }
661                                 /** XXX What About animtype "rotation" ? */
662
663                                 BLI_addtail(AnimCurves, fcu);
664                                 fcurve_is_used(fcu);
665                         }
666                 }
667         }
668         
669 }
670
671 /*
672  * Lens animations must be stored in COLLADA by using FOV,
673  * while blender internally uses focal length.
674  * The imported animation curves must be converted appropriately.
675  */
676 void AnimationImporter::Assign_lens_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, const double aspect, Camera *cam, const char *anim_type, int fov_type)
677 {
678         char rna_path[100];
679         if (animlist_map.find(listid) == animlist_map.end()) {
680                 return;
681         }
682         else {
683                 //anim_type has animations
684                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
685                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
686                 //all the curves belonging to the current binding
687                 std::vector<FCurve *> animcurves;
688                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
689                         animcurves = curve_map[bindings[j].animation];
690
691                         BLI_strncpy(rna_path, anim_type, sizeof(rna_path));
692
693                         modify_fcurve(&animcurves, rna_path, 0);
694                         std::vector<FCurve *>::iterator iter;
695                         //Add the curves of the current animation to the object
696                         for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
697                                 FCurve *fcu = *iter;
698                                 
699                                 for (unsigned int i = 0; i < fcu->totvert; i++) {
700
701                                         double input_fov = fcu->bezt[i].vec[1][1];
702
703                                         // NOTE: Needs more testing (As we curretnly have no official test data for this)
704                                         double xfov = (fov_type == CAMERA_YFOV) ? (2.0f * atanf(aspect * tanf(DEG2RADF(input_fov) * 0.5f))) : DEG2RADF(input_fov);
705
706                                         fcu->bezt[i].vec[1][1] = fov_to_focallength(xfov, cam->sensor_x);
707                                 }
708
709                                 BLI_addtail(AnimCurves, fcu);
710                                 fcurve_is_used(fcu);
711                         }
712                 }
713         }
714 }
715
716 void AnimationImporter::apply_matrix_curves(Object *ob, std::vector<FCurve *>& animcurves, COLLADAFW::Node *root, COLLADAFW::Node *node,
717                                             COLLADAFW::Transformation *tm)
718 {
719         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
720         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
721         char joint_path[200];
722         if (is_joint)
723                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
724
725         std::vector<float> frames;
726         find_frames(&frames, &animcurves);
727
728         float irest_dae[4][4];
729         float rest[4][4], irest[4][4];
730
731         if (is_joint) {
732                 get_joint_rest_mat(irest_dae, root, node);
733                 invert_m4(irest_dae);
734
735                 Bone *bone = BKE_armature_find_bone_name((bArmature *)ob->data, bone_name);
736                 if (!bone) {
737                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
738                         return;
739                 }
740
741                 unit_m4(rest);
742                 copy_m4_m4(rest, bone->arm_mat);
743                 invert_m4_m4(irest, rest);
744         }
745         // new curves to assign matrix transform animation
746         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
747         unsigned int totcu = 10;
748         const char *tm_str = NULL;
749         char rna_path[200];
750         for (int i = 0; i < totcu; i++) {
751
752                 int axis = i;
753
754                 if (i < 4) {
755                         tm_str = "rotation_quaternion";
756                         axis = i;
757                 }
758                 else if (i < 7) {
759                         tm_str = "location";
760                         axis = i - 4;
761                 }
762                 else {
763                         tm_str = "scale";
764                         axis = i - 7;
765                 }
766
767
768                 if (is_joint)
769                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
770                 else
771                         BLI_strncpy(rna_path, tm_str, sizeof(rna_path));
772                 newcu[i] = create_fcurve(axis, rna_path);
773                 newcu[i]->totvert = frames.size();
774         }
775
776         if (frames.size() == 0)
777                 return;
778
779         std::sort(frames.begin(), frames.end());
780
781         std::vector<float>::iterator it;
782
783         float qref[4];
784         unit_qt(qref);
785
786         // sample values at each frame
787         for (it = frames.begin(); it != frames.end(); it++) {
788                 float fra = *it;
789
790                 float mat[4][4];
791                 float matfra[4][4];
792
793                 unit_m4(matfra);
794
795                 // calc object-space mat
796                 evaluate_transform_at_frame(matfra, node, fra);
797
798
799                 // for joints, we need a special matrix
800                 if (is_joint) {
801                         // special matrix: iR * M * iR_dae * R
802                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
803                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
804                         float temp[4][4], par[4][4];
805
806                         // calc M
807                         calc_joint_parent_mat_rest(par, NULL, root, node);
808                         mul_m4_m4m4(temp, par, matfra);
809
810                         // evaluate_joint_world_transform_at_frame(temp, NULL, node, fra);
811
812                         // calc special matrix
813                         mul_m4_series(mat, irest, temp, irest_dae, rest);
814                 }
815                 else {
816                         copy_m4_m4(mat, matfra);
817                 }
818
819                 float rot[4], loc[3], scale[3];
820                 transpose_m4(mat);
821
822                 bc_rotate_from_reference_quat(rot, qref, mat);
823                 copy_qt_qt(qref, rot);
824
825 #if 0
826                 for (int i = 0 ; i < 4;  i++) {
827                         rot[i] = RAD2DEGF(rot[i]);
828                 }
829 #endif
830                 copy_v3_v3(loc, mat[3]);
831                 mat4_to_size(scale, mat);
832
833                 // add keys
834                 for (int i = 0; i < totcu; i++) {
835                         if (i < 4)
836                                 add_bezt(newcu[i], fra, rot[i]);
837                         else if (i < 7)
838                                 add_bezt(newcu[i], fra, loc[i - 4]);
839                         else
840                                 add_bezt(newcu[i], fra, scale[i - 7]);
841                 }
842         }
843         verify_adt_action((ID *)&ob->id, 1);
844
845         ListBase *curves = &ob->adt->action->curves;
846
847         // add curves
848         for (int i = 0; i < totcu; i++) {
849                 if (is_joint)
850                         add_bone_fcurve(ob, node, newcu[i]);
851                 else
852                         BLI_addtail(curves, newcu[i]);
853                 // fcurve_is_used(newcu[i]);  // never added to unused
854         }
855
856
857         if (is_joint) {
858                 bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, bone_name);
859                 chan->rotmode = ROT_MODE_QUAT;
860         }
861         else {
862                 ob->rotmode = ROT_MODE_QUAT;
863         }
864
865         return;
866
867 }
868
869 /*
870  * This function returns the aspet ration from the Collada camera.
871  *
872  * Note:COLLADA allows to specify either XFov, or YFov alone. 
873  * In that case the aspect ratio can be determined from
874  * the viewport aspect ratio (which is 1:1 ?)
875  * XXX: check this: its probably wrong!
876  * If both values are specified, then the aspect ration is simply xfov/yfov
877  * and if aspect ratio is efined, then .. well then its that one.
878  */
879 static const double get_aspect_ratio(const COLLADAFW::Camera *camera)
880 {
881         double aspect =  camera->getAspectRatio().getValue();
882
883         if (aspect == 0) {
884                 const double yfov   =  camera->getYFov().getValue();
885
886                 if (yfov == 0) {
887                         aspect = 1; // assume yfov and xfov are equal
888                 }
889                 else {
890                         const double xfov   =  camera->getXFov().getValue();
891                         if (xfov==0)
892                                 aspect = 1;
893                         else
894                                 aspect = xfov / yfov;
895                 }
896         }
897         return aspect;
898 }
899
900
901 void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
902                                              std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>& root_map,
903                                              std::multimap<COLLADAFW::UniqueId, Object *>& object_map,
904                                              std::map<COLLADAFW::UniqueId, const COLLADAFW::Object *> FW_object_map)
905 {
906         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
907         COLLADAFW::UniqueId uid = node->getUniqueId();
908         COLLADAFW::Node *root = root_map.find(uid) == root_map.end() ? node : root_map[uid];
909
910         Object *ob;
911         if (is_joint)
912                 ob = armature_importer->get_armature_for_joint(root);
913         else
914                 ob = object_map.find(uid) == object_map.end() ? NULL : object_map.find(uid)->second;
915
916         if (!ob) {
917                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
918                 return;
919         }
920
921
922         AnimationImporter::AnimMix *animType = get_animation_type(node, FW_object_map);
923         bAction *act;
924
925         if ( (animType->transform) != 0) {
926                 /* const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL; */ /* UNUSED */
927                 char joint_path[200];
928
929                 if (is_joint)
930                         armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
931
932
933                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID *)&ob->id, 1);
934                 else act = ob->adt->action;
935
936                 //Get the list of animation curves of the object
937                 ListBase *AnimCurves = &(act->curves);
938
939                 const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
940
941                 //for each transformation in node 
942                 for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
943                         COLLADAFW::Transformation *transform = nodeTransforms[i];
944                         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
945
946                         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
947                         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
948
949                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
950
951                         //check if transformation has animations
952                         if (animlist_map.find(listid) == animlist_map.end()) {
953                                 continue;
954                         }
955                         else {
956                                 //transformation has animations
957                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
958                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
959                                 //all the curves belonging to the current binding
960                                 std::vector<FCurve *> animcurves;
961                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
962                                         animcurves = curve_map[bindings[j].animation];
963                                         if (is_matrix) {
964                                                 apply_matrix_curves(ob, animcurves, root, node,  transform);
965                                         }
966                                         else {                          
967
968                                                 if (is_joint) {
969                                                         add_bone_animation_sampled(ob, animcurves, root, node, transform);
970                                                 }
971                                                 else {
972                                                         //calculate rnapaths and array index of fcurves according to transformation and animation class
973                                                         Assign_transform_animations(transform, &bindings[j], &animcurves, is_joint, joint_path);
974
975                                                         std::vector<FCurve *>::iterator iter;
976                                                         //Add the curves of the current animation to the object
977                                                         for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
978                                                                 FCurve *fcu = *iter;
979                                                         
980                                                                 BLI_addtail(AnimCurves, fcu);
981                                                                 fcurve_is_used(fcu);
982                                                         }
983                                                 }
984                                                 
985                                         }
986                                 }
987                         }
988                         if (is_rotation && !is_joint) {
989                                 ob->rotmode = ROT_MODE_EUL;
990                         }
991                 }
992         }
993
994         if ((animType->light) != 0) {
995                 Lamp *lamp  = (Lamp *) ob->data;
996
997                 if (!lamp->adt || !lamp->adt->action) act = verify_adt_action((ID *)&lamp->id, 1);
998                 else act = lamp->adt->action;
999
1000                 ListBase *AnimCurves = &(act->curves);
1001                 const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
1002
1003                 for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
1004                         const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
1005
1006                         if ((animType->light & LIGHT_COLOR) != 0) {
1007                                 const COLLADAFW::Color *col =  &(light->getColor());
1008                                 const COLLADAFW::UniqueId& listid = col->getAnimationList();
1009
1010                                 Assign_color_animations(listid, AnimCurves, "color"); 
1011                         }
1012                         if ((animType->light & LIGHT_FOA) != 0) {
1013                                 const COLLADAFW::AnimatableFloat *foa =  &(light->getFallOffAngle());
1014                                 const COLLADAFW::UniqueId& listid = foa->getAnimationList();
1015
1016                                 Assign_float_animations(listid, AnimCurves, "spot_size");
1017                         }
1018                         if ( (animType->light & LIGHT_FOE) != 0) {
1019                                 const COLLADAFW::AnimatableFloat *foe =  &(light->getFallOffExponent());
1020                                 const COLLADAFW::UniqueId& listid = foe->getAnimationList();
1021
1022                                 Assign_float_animations(listid, AnimCurves, "spot_blend");
1023
1024                         }
1025                 }
1026         }
1027
1028         if (animType->camera != 0) {
1029                 Camera *cam  = (Camera *) ob->data;
1030                 if (!cam->adt || !cam->adt->action)
1031                         act = verify_adt_action((ID *)&cam->id, 1);
1032                 else
1033                         act = cam->adt->action;
1034
1035                 ListBase *AnimCurves = &(act->curves);
1036                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
1037
1038                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
1039                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
1040
1041                         if ((animType->camera & CAMERA_XFOV) != 0) {
1042                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
1043                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
1044                                 double aspect = get_aspect_ratio(camera); 
1045                                 Assign_lens_animations(listid, AnimCurves, aspect, cam, "lens", CAMERA_XFOV);
1046                         }
1047
1048                         else if ((animType->camera & CAMERA_YFOV) != 0) {
1049                                 const COLLADAFW::AnimatableFloat *yfov =  &(camera->getYFov());
1050                                 const COLLADAFW::UniqueId& listid = yfov->getAnimationList();
1051                                 double aspect = get_aspect_ratio(camera); 
1052                                 Assign_lens_animations(listid, AnimCurves, aspect, cam, "lens", CAMERA_YFOV);
1053                         }
1054
1055                         else if ((animType->camera & CAMERA_XMAG) != 0) {
1056                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
1057                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
1058                                 Assign_float_animations(listid, AnimCurves, "ortho_scale");
1059                         }
1060
1061                         else if ((animType->camera & CAMERA_YMAG) != 0) {
1062                                 const COLLADAFW::AnimatableFloat *ymag =  &(camera->getYMag());
1063                                 const COLLADAFW::UniqueId& listid = ymag->getAnimationList();
1064                                 Assign_float_animations(listid, AnimCurves, "ortho_scale");
1065                         }
1066
1067                         if ((animType->camera & CAMERA_ZFAR) != 0) {
1068                                 const COLLADAFW::AnimatableFloat *zfar =  &(camera->getFarClippingPlane());
1069                                 const COLLADAFW::UniqueId& listid = zfar->getAnimationList();
1070                                 Assign_float_animations(listid, AnimCurves, "clip_end");
1071                         }
1072
1073                         if ((animType->camera & CAMERA_ZNEAR) != 0) {
1074                                 const COLLADAFW::AnimatableFloat *znear =  &(camera->getNearClippingPlane());
1075                                 const COLLADAFW::UniqueId& listid = znear->getAnimationList();
1076                                 Assign_float_animations(listid, AnimCurves, "clip_start");
1077                         }
1078
1079                 }
1080         }
1081         if (animType->material != 0) {
1082                 Material *ma = give_current_material(ob, 1);
1083                 if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID *)&ma->id, 1);
1084                 else act = ma->adt->action;
1085
1086                 ListBase *AnimCurves = &(act->curves);
1087
1088                 const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1089                 for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1090                         const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1091                         for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1092                                 const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1093                                 const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1094                                 if (ef != NULL) { /* can be NULL [#28909] */
1095                                         const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
1096                                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1097                                         if ((animType->material & MATERIAL_SHININESS) != 0) {
1098                                                 const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
1099                                                 const COLLADAFW::UniqueId& listid =  shin->getAnimationList();
1100                                                 Assign_float_animations(listid, AnimCurves, "specular_hardness");
1101                                         }
1102
1103                                         if ((animType->material & MATERIAL_IOR) != 0) {
1104                                                 const COLLADAFW::FloatOrParam *ior = &(efc->getIndexOfRefraction());
1105                                                 const COLLADAFW::UniqueId& listid =  ior->getAnimationList();
1106                                                 Assign_float_animations(listid, AnimCurves, "raytrace_transparency.ior");
1107                                         }
1108
1109                                         if ((animType->material & MATERIAL_SPEC_COLOR) != 0) {
1110                                                 const COLLADAFW::ColorOrTexture *cot = &(efc->getSpecular());
1111                                                 const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
1112                                                 Assign_color_animations(listid, AnimCurves, "specular_color");
1113                                         }
1114
1115                                         if ((animType->material & MATERIAL_DIFF_COLOR) != 0) {
1116                                                 const COLLADAFW::ColorOrTexture *cot = &(efc->getDiffuse());
1117                                                 const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
1118                                                 Assign_color_animations(listid, AnimCurves, "diffuse_color");
1119                                         }
1120                                 }
1121                         }
1122                 }
1123         }
1124
1125         delete animType;
1126 }
1127
1128 void AnimationImporter::add_bone_animation_sampled(Object *ob, std::vector<FCurve *>& animcurves, COLLADAFW::Node *root, COLLADAFW::Node *node, COLLADAFW::Transformation *tm)
1129 {
1130         const char *bone_name = bc_get_joint_name(node);
1131         char joint_path[200];
1132         armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1133
1134         std::vector<float> frames;
1135         find_frames(&frames, &animcurves);
1136
1137         // convert degrees to radians
1138         if (tm->getTransformationType() == COLLADAFW::Transformation::ROTATE) {
1139
1140                 std::vector<FCurve *>::iterator iter;
1141                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
1142                         FCurve *fcu = *iter;
1143
1144                         fcurve_deg_to_rad(fcu);
1145                 }
1146         }
1147
1148
1149         float irest_dae[4][4];
1150         float rest[4][4], irest[4][4];
1151
1152         get_joint_rest_mat(irest_dae, root, node);
1153         invert_m4(irest_dae);
1154
1155         Bone *bone = BKE_armature_find_bone_name((bArmature *)ob->data, bone_name);
1156         if (!bone) {
1157                 fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1158                 return;
1159         }
1160
1161         unit_m4(rest);
1162         copy_m4_m4(rest, bone->arm_mat);
1163         invert_m4_m4(irest, rest);
1164
1165         // new curves to assign matrix transform animation
1166         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1167         unsigned int totcu = 10;
1168         const char *tm_str = NULL;
1169         char rna_path[200];
1170         for (int i = 0; i < totcu; i++) {
1171
1172                 int axis = i;
1173
1174                 if (i < 4) {
1175                         tm_str = "rotation_quaternion";
1176                         axis = i;
1177                 }
1178                 else if (i < 7) {
1179                         tm_str = "location";
1180                         axis = i - 4;
1181                 }
1182                 else {
1183                         tm_str = "scale";
1184                         axis = i - 7;
1185                 }
1186
1187
1188                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1189
1190                 newcu[i] = create_fcurve(axis, rna_path);
1191                 newcu[i]->totvert = frames.size();
1192         }
1193
1194         if (frames.size() == 0)
1195                 return;
1196
1197         std::sort(frames.begin(), frames.end());
1198
1199         float qref[4];
1200         unit_qt(qref);
1201
1202         std::vector<float>::iterator it;
1203
1204         // sample values at each frame
1205         for (it = frames.begin(); it != frames.end(); it++) {
1206                 float fra = *it;
1207
1208                 float mat[4][4];
1209                 float matfra[4][4];
1210
1211                 unit_m4(matfra);
1212
1213                 // calc object-space mat
1214                 evaluate_transform_at_frame(matfra, node, fra);
1215
1216
1217                 // for joints, we need a special matrix
1218                 // special matrix: iR * M * iR_dae * R
1219                 // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1220                 // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1221                 float temp[4][4], par[4][4];
1222
1223
1224                 // calc M
1225                 calc_joint_parent_mat_rest(par, NULL, root, node);
1226                 mul_m4_m4m4(temp, par, matfra);
1227
1228                 // evaluate_joint_world_transform_at_frame(temp, NULL, node, fra);
1229
1230                 // calc special matrix
1231                 mul_m4_series(mat, irest, temp, irest_dae, rest);
1232
1233                 float rot[4], loc[3], scale[3];
1234
1235                 bc_rotate_from_reference_quat(rot, qref, mat);
1236                 copy_qt_qt(qref, rot);
1237
1238                 copy_v3_v3(loc, mat[3]);
1239                 mat4_to_size(scale, mat);
1240
1241                 // add keys
1242                 for (int i = 0; i < totcu; i++) {
1243                         if (i < 4)
1244                                 add_bezt(newcu[i], fra, rot[i]);
1245                         else if (i < 7)
1246                                 add_bezt(newcu[i], fra, loc[i - 4]);
1247                         else
1248                                 add_bezt(newcu[i], fra, scale[i - 7]);
1249                 }
1250         }
1251         verify_adt_action((ID *)&ob->id, 1);
1252
1253         // add curves
1254         for (int i = 0; i < totcu; i++) {
1255                 add_bone_fcurve(ob, node, newcu[i]);
1256                 // fcurve_is_used(newcu[i]);  // never added to unused
1257         }
1258
1259         bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, bone_name);
1260         chan->rotmode = ROT_MODE_QUAT;
1261
1262 }
1263
1264
1265 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
1266 AnimationImporter::AnimMix *AnimationImporter::get_animation_type(const COLLADAFW::Node *node,
1267                                                                   std::map<COLLADAFW::UniqueId, const COLLADAFW::Object *> FW_object_map)
1268 {
1269         AnimMix *types = new AnimMix();
1270
1271         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1272
1273         //for each transformation in node 
1274         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
1275                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1276                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1277
1278                 //check if transformation has animations
1279                 if (animlist_map.find(listid) == animlist_map.end()) {
1280                         continue;
1281                 }
1282                 else {
1283                         types->transform = types->transform | NODE_TRANSFORM;
1284                         break;
1285                 }
1286         }
1287         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
1288
1289         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
1290                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
1291                 types->light = setAnimType(&(light->getColor()), (types->light), LIGHT_COLOR);
1292                 types->light = setAnimType(&(light->getFallOffAngle()), (types->light), LIGHT_FOA);
1293                 types->light = setAnimType(&(light->getFallOffExponent()), (types->light), LIGHT_FOE);
1294
1295                 if (types->light != 0) break;
1296
1297         }
1298
1299         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
1300         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
1301                 const COLLADAFW::Camera *camera  = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
1302                 if ( camera == NULL ) {
1303                         // Can happen if the node refers to an unknown camera.
1304                         continue;
1305                 }
1306
1307                 const bool is_perspective_type   = camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE;
1308
1309                 int addition;
1310                 const COLLADAFW::Animatable *mag;
1311                 const COLLADAFW::UniqueId listid = camera->getYMag().getAnimationList();
1312                 if (animlist_map.find(listid) != animlist_map.end()) {
1313                         mag = &(camera->getYMag());
1314                         addition = (is_perspective_type) ? CAMERA_YFOV: CAMERA_YMAG;
1315                 }
1316                 else {
1317                         mag = &(camera->getXMag());
1318                         addition = (is_perspective_type) ? CAMERA_XFOV: CAMERA_XMAG;
1319                 }
1320                 types->camera = setAnimType(mag, (types->camera), addition);
1321
1322                 types->camera = setAnimType(&(camera->getFarClippingPlane()), (types->camera), CAMERA_ZFAR);
1323                 types->camera = setAnimType(&(camera->getNearClippingPlane()), (types->camera), CAMERA_ZNEAR);
1324
1325                 if (types->camera != 0) break;
1326
1327         }
1328
1329         const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1330         for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1331                 const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1332                 for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1333                         const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1334                         const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1335                         if (ef != NULL) { /* can be NULL [#28909] */
1336                                 const COLLADAFW::CommonEffectPointerArray& commonEffects = ef->getCommonEffects();
1337                                 if (!commonEffects.empty()) {
1338                                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1339                                         types->material =  setAnimType(&(efc->getShininess()), (types->material), MATERIAL_SHININESS);
1340                                         types->material =  setAnimType(&(efc->getSpecular().getColor()), (types->material), MATERIAL_SPEC_COLOR);
1341                                         types->material =  setAnimType(&(efc->getDiffuse().getColor()), (types->material), MATERIAL_DIFF_COLOR);
1342                                         // types->material =  setAnimType(&(efc->get()), (types->material), MATERIAL_TRANSPARENCY);
1343                                         types->material =  setAnimType(&(efc->getIndexOfRefraction()), (types->material), MATERIAL_IOR);
1344                                 }
1345                         }
1346                 }
1347         }
1348         return types;
1349 }
1350
1351 int AnimationImporter::setAnimType(const COLLADAFW::Animatable *prop, int types, int addition)
1352 {
1353         int anim_type;
1354         const COLLADAFW::UniqueId& listid       = prop->getAnimationList();
1355         if (animlist_map.find(listid) != animlist_map.end())
1356                 anim_type =  types | addition;
1357         else
1358                 anim_type = types;
1359
1360         return anim_type;
1361 }               
1362
1363 // Is not used anymore.
1364 void AnimationImporter::find_frames_old(std::vector<float> *frames, COLLADAFW::Node *node, COLLADAFW::Transformation::TransformationType tm_type)
1365 {
1366         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1367         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1368         // for each <rotate>, <translate>, etc. there is a separate Transformation
1369         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1370
1371         unsigned int i;
1372         // find frames at which to sample plus convert all rotation keys to radians
1373         for (i = 0; i < nodeTransforms.getCount(); i++) {
1374                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1375                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
1376
1377
1378                 if (nodeTmType == tm_type) {
1379                         //get animation bindings for the current transformation
1380                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1381                         //if transform is animated its animlist must exist.
1382                         if (animlist_map.find(listid) != animlist_map.end()) {
1383                                 
1384                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1385                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1386
1387                                 if (bindings.getCount()) {
1388                                         //for each AnimationBinding get the fcurves which animate the transform
1389                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
1390                                                 std::vector<FCurve *>& curves = curve_map[bindings[j].animation];
1391                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
1392
1393                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
1394                                                         std::vector<FCurve *>::iterator iter;
1395
1396                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
1397                                                                 FCurve *fcu = *iter;
1398
1399                                                                 //if transform is rotation the fcurves values must be turned in to radian.
1400                                                                 if (is_rotation)
1401                                                                         fcurve_deg_to_rad(fcu);
1402
1403                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1404                                                                         //get frame value from bezTriple
1405                                                                         float fra = fcu->bezt[k].vec[1][0];
1406                                                                         //if frame already not added add frame to frames
1407                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1408                                                                                 frames->push_back(fra);
1409                                                                 }
1410                                                         }
1411                                                 }
1412                                                 else {
1413                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1414                                                 }
1415                                         }
1416                                 }
1417                         }
1418                 }
1419         }
1420 }
1421
1422
1423
1424 // prerequisites:
1425 // animlist_map - map animlist id -> animlist
1426 // curve_map - map anim id -> curve(s)
1427 Object *AnimationImporter::translate_animation_OLD(COLLADAFW::Node *node,
1428                                                    std::map<COLLADAFW::UniqueId, Object *>& object_map,
1429                                                    std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>& root_map,
1430                                                    COLLADAFW::Transformation::TransformationType tm_type,
1431                                                    Object *par_job)
1432 {
1433         
1434         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1435         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1436         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1437         
1438         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1439         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1440         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1441         if (!ob) {
1442                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1443                 return NULL;
1444         }
1445
1446         // frames at which to sample
1447         std::vector<float> frames;
1448         
1449         find_frames_old(&frames, node, tm_type);
1450         
1451         unsigned int i;
1452         
1453         float irest_dae[4][4];
1454         float rest[4][4], irest[4][4];
1455
1456         if (is_joint) {
1457                 get_joint_rest_mat(irest_dae, root, node);
1458                 invert_m4(irest_dae);
1459
1460                 Bone *bone = BKE_armature_find_bone_name((bArmature *)ob->data, bone_name);
1461                 if (!bone) {
1462                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1463                         return NULL;
1464                 }
1465
1466                 unit_m4(rest);
1467                 copy_m4_m4(rest, bone->arm_mat);
1468                 invert_m4_m4(irest, rest);
1469         }
1470
1471         Object *job = NULL;
1472
1473 #ifdef ARMATURE_TEST
1474         FCurve *job_curves[10];
1475         job = get_joint_object(root, node, par_job);
1476 #endif
1477
1478         if (frames.size() == 0)
1479                 return job;
1480
1481         std::sort(frames.begin(), frames.end());
1482
1483         const char *tm_str = NULL;
1484         switch (tm_type) {
1485                 case COLLADAFW::Transformation::ROTATE:
1486                         tm_str = "rotation_quaternion";
1487                         break;
1488                 case COLLADAFW::Transformation::SCALE:
1489                         tm_str = "scale";
1490                         break;
1491                 case COLLADAFW::Transformation::TRANSLATE:
1492                         tm_str = "location";
1493                         break;
1494                 case COLLADAFW::Transformation::MATRIX:
1495                         break;
1496                 default:
1497                         return job;
1498         }
1499
1500         char rna_path[200];
1501         char joint_path[200];
1502
1503         if (is_joint)
1504                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1505
1506         // new curves
1507         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1508         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1509
1510         for (i = 0; i < totcu; i++) {
1511
1512                 int axis = i;
1513
1514                 if (is_matrix) {
1515                         if (i < 4) {
1516                                 tm_str = "rotation_quaternion";
1517                                 axis = i;
1518                         }
1519                         else if (i < 7) {
1520                                 tm_str = "location";
1521                                 axis = i - 4;
1522                         }
1523                         else {
1524                                 tm_str = "scale";
1525                                 axis = i - 7;
1526                         }
1527                 }
1528
1529                 if (is_joint)
1530                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1531                 else
1532                         BLI_strncpy(rna_path, tm_str, sizeof(rna_path));
1533                 newcu[i] = create_fcurve(axis, rna_path);
1534
1535 #ifdef ARMATURE_TEST
1536                 if (is_joint)
1537                         job_curves[i] = create_fcurve(axis, tm_str);
1538 #endif
1539         }
1540
1541         std::vector<float>::iterator it;
1542
1543         // sample values at each frame
1544         for (it = frames.begin(); it != frames.end(); it++) {
1545                 float fra = *it;
1546
1547                 float mat[4][4];
1548                 float matfra[4][4];
1549
1550                 unit_m4(matfra);
1551
1552                 // calc object-space mat
1553                 evaluate_transform_at_frame(matfra, node, fra);
1554
1555                 // for joints, we need a special matrix
1556                 if (is_joint) {
1557                         // special matrix: iR * M * iR_dae * R
1558                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1559                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1560                         float temp[4][4], par[4][4];
1561
1562                         // calc M
1563                         calc_joint_parent_mat_rest(par, NULL, root, node);
1564                         mul_m4_m4m4(temp, par, matfra);
1565
1566                         // evaluate_joint_world_transform_at_frame(temp, NULL, node, fra);
1567
1568                         // calc special matrix
1569                         mul_m4_series(mat, irest, temp, irest_dae, rest);
1570                 }
1571                 else {
1572                         copy_m4_m4(mat, matfra);
1573                 }
1574
1575                 float val[4], rot[4], loc[3], scale[3];
1576
1577                 switch (tm_type) {
1578                         case COLLADAFW::Transformation::ROTATE:
1579                                 mat4_to_quat(val, mat);
1580                                 break;
1581                         case COLLADAFW::Transformation::SCALE:
1582                                 mat4_to_size(val, mat);
1583                                 break;
1584                         case COLLADAFW::Transformation::TRANSLATE:
1585                                 copy_v3_v3(val, mat[3]);
1586                                 break;
1587                         case COLLADAFW::Transformation::MATRIX:
1588                                 mat4_to_quat(rot, mat);
1589                                 copy_v3_v3(loc, mat[3]);
1590                                 mat4_to_size(scale, mat);
1591                                 break;
1592                         default:
1593                                 break;
1594                 }
1595
1596                 // add keys
1597                 for (i = 0; i < totcu; i++) {
1598                         if (is_matrix) {
1599                                 if (i < 4)
1600                                         add_bezt(newcu[i], fra, rot[i]);
1601                                 else if (i < 7)
1602                                         add_bezt(newcu[i], fra, loc[i - 4]);
1603                                 else
1604                                         add_bezt(newcu[i], fra, scale[i - 7]);
1605                         }
1606                         else {
1607                                 add_bezt(newcu[i], fra, val[i]);
1608                         }
1609                 }
1610
1611 #ifdef ARMATURE_TEST
1612                 if (is_joint) {
1613                         switch (tm_type) {
1614                                 case COLLADAFW::Transformation::ROTATE:
1615                                         mat4_to_quat(val, matfra);
1616                                         break;
1617                                 case COLLADAFW::Transformation::SCALE:
1618                                         mat4_to_size(val, matfra);
1619                                         break;
1620                                 case COLLADAFW::Transformation::TRANSLATE:
1621                                         copy_v3_v3(val, matfra[3]);
1622                                         break;
1623                                 case MATRIX:
1624                                         mat4_to_quat(rot, matfra);
1625                                         copy_v3_v3(loc, matfra[3]);
1626                                         mat4_to_size(scale, matfra);
1627                                         break;
1628                                 default:
1629                                         break;
1630                         }
1631
1632                         for (i = 0; i < totcu; i++) {
1633                                 if (is_matrix) {
1634                                         if (i < 4)
1635                                                 add_bezt(job_curves[i], fra, rot[i]);
1636                                         else if (i < 7)
1637                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1638                                         else
1639                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1640                                 }
1641                                 else {
1642                                         add_bezt(job_curves[i], fra, val[i]);
1643                                 }
1644                         }
1645                 }
1646 #endif
1647         }
1648
1649         verify_adt_action((ID *)&ob->id, 1);
1650
1651         ListBase *curves = &ob->adt->action->curves;
1652
1653         // add curves
1654         for (i = 0; i < totcu; i++) {
1655                 if (is_joint)
1656                         add_bone_fcurve(ob, node, newcu[i]);
1657                 else
1658                         BLI_addtail(curves, newcu[i]);
1659
1660 #ifdef ARMATURE_TEST
1661                 if (is_joint)
1662                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1663 #endif
1664         }
1665
1666         if (is_rotation || is_matrix) {
1667                 if (is_joint) {
1668                         bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, bone_name);
1669                         chan->rotmode = ROT_MODE_QUAT;
1670                 }
1671                 else {
1672                         ob->rotmode = ROT_MODE_QUAT;
1673                 }
1674         }
1675
1676         return job;
1677 }
1678
1679 // internal, better make it private
1680 // warning: evaluates only rotation and only assigns matrix transforms now
1681 // prerequisites: animlist_map, curve_map
1682 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1683 {
1684         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1685
1686         unit_m4(mat);
1687
1688         for (unsigned int i = 0; i < tms.getCount(); i++) {
1689                 COLLADAFW::Transformation *tm = tms[i];
1690                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1691                 float m[4][4];
1692
1693                 unit_m4(m);
1694
1695                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1696                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1697                         switch (type) {
1698                                 case COLLADAFW::Transformation::ROTATE:
1699                                         dae_rotate_to_mat4(tm, m);
1700                                         break;
1701                                 case COLLADAFW::Transformation::TRANSLATE:
1702                                         dae_translate_to_mat4(tm, m);
1703                                         break;
1704                                 case COLLADAFW::Transformation::SCALE:
1705                                         dae_scale_to_mat4(tm, m);
1706                                         break;
1707                                 case COLLADAFW::Transformation::MATRIX:
1708                                         dae_matrix_to_mat4(tm, m);
1709                                         break;
1710                                 default:
1711                                         fprintf(stderr, "unsupported transformation type %d\n", type);
1712                         }
1713                 }
1714
1715                 float temp[4][4];
1716                 copy_m4_m4(temp, mat);
1717
1718                 mul_m4_m4m4(mat, temp, m);
1719         }
1720 }
1721
1722 static void report_class_type_unsupported(const char *path, 
1723                                          const COLLADAFW::AnimationList::AnimationClass animclass,
1724                                          const COLLADAFW::Transformation::TransformationType type) 
1725 {
1726         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1727                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1728         }
1729         else {
1730                 fprintf(stderr, "%s: animation class %d is not supported yet for transformation type %d\n", path, animclass, type);
1731         }
1732 }
1733
1734 // return true to indicate that mat contains a sane value
1735 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1736 {
1737         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1738         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1739
1740         if (type != COLLADAFW::Transformation::ROTATE &&
1741             type != COLLADAFW::Transformation::SCALE &&
1742             type != COLLADAFW::Transformation::TRANSLATE &&
1743             type != COLLADAFW::Transformation::MATRIX) {
1744                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1745                 return false;
1746         }
1747
1748         if (animlist_map.find(listid) == animlist_map.end())
1749                 return false;
1750
1751         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1752         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1753
1754         if (bindings.getCount()) {
1755                 float vec[3];
1756
1757                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1758                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1759
1760                 if (is_scale)
1761                         dae_scale_to_v3(tm, vec);
1762                 else if (is_translate)
1763                         dae_translate_to_v3(tm, vec);
1764
1765                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1766                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1767                         std::vector<FCurve *>& curves = curve_map[binding.animation];
1768                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1769                         char path[100];
1770
1771                         switch (type) {
1772                                 case COLLADAFW::Transformation::ROTATE:
1773                                         BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1774                                         break;
1775                                 case COLLADAFW::Transformation::SCALE:
1776                                         BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1777                                         break;
1778                                 case COLLADAFW::Transformation::TRANSLATE:
1779                                         BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1780                                         break;
1781                                 case COLLADAFW::Transformation::MATRIX:
1782                                         BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1783                                         break;
1784                                 default:
1785                                         break;
1786                         }
1787
1788                         if (type == COLLADAFW::Transformation::ROTATE) {
1789                                 if (curves.size() != 1) {
1790                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1791                                         return false;
1792                                 }
1793
1794                                 // TODO support other animclasses
1795                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1796                                         report_class_type_unsupported(path, animclass, type);
1797                                         return false;
1798                                 }
1799
1800                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate *)tm)->getRotationAxis();
1801
1802                                 float ax[3] = {(float)axis[0], (float)axis[1], (float)axis[2]};
1803                                 float angle = evaluate_fcurve(curves[0], fra);
1804                                 axis_angle_to_mat4(mat, ax, angle);
1805
1806                                 return true;
1807                         }
1808                         else if (is_scale || is_translate) {
1809                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1810
1811                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1812                                         if (is_xyz)
1813                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1814                                         else
1815                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1816                                         return false;
1817                                 }
1818                                 
1819                                 switch (animclass) {
1820                                         case COLLADAFW::AnimationList::POSITION_X:
1821                                                 vec[0] = evaluate_fcurve(curves[0], fra);
1822                                                 break;
1823                                         case COLLADAFW::AnimationList::POSITION_Y:
1824                                                 vec[1] = evaluate_fcurve(curves[0], fra);
1825                                                 break;
1826                                         case COLLADAFW::AnimationList::POSITION_Z:
1827                                                 vec[2] = evaluate_fcurve(curves[0], fra);
1828                                                 break;
1829                                         case COLLADAFW::AnimationList::POSITION_XYZ:
1830                                                 vec[0] = evaluate_fcurve(curves[0], fra);
1831                                                 vec[1] = evaluate_fcurve(curves[1], fra);
1832                                                 vec[2] = evaluate_fcurve(curves[2], fra);
1833                                                 break;
1834                                         default:
1835                                                 report_class_type_unsupported(path, animclass, type);
1836                                                 break;
1837                                 }
1838                         }
1839                         else if (type == COLLADAFW::Transformation::MATRIX) {
1840                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1841                                 if (curves.size() != 16) {
1842                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1843                                         return false;
1844                                 }
1845
1846                                 COLLADABU::Math::Matrix4 matrix;
1847                                 int i = 0, j = 0;
1848
1849                                 for (std::vector<FCurve *>::iterator it = curves.begin(); it != curves.end(); it++) {
1850                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1851                                         j++;
1852                                         if (j == 4) {
1853                                                 i++;
1854                                                 j = 0;
1855                                         }
1856                                         fcurve_is_used(*it);
1857                                 }
1858
1859                                 COLLADAFW::Matrix tm(matrix);
1860                                 dae_matrix_to_mat4(&tm, mat);
1861
1862                                 std::vector<FCurve *>::iterator it;
1863
1864                                 return true;
1865                         }
1866                 }
1867
1868                 if (is_scale)
1869                         size_to_mat4(mat, vec);
1870                 else
1871                         copy_v3_v3(mat[3], vec);
1872
1873                 return is_scale || is_translate;
1874         }
1875
1876         return false;
1877 }
1878
1879 // gives a world-space mat of joint at rest position
1880 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1881 {
1882         // if bind mat is not available,
1883         // use "current" node transform, i.e. all those tms listed inside <node>
1884         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1885                 float par[4][4], m[4][4];
1886
1887                 calc_joint_parent_mat_rest(par, NULL, root, node);
1888                 get_node_mat(m, node, NULL, NULL);
1889                 mul_m4_m4m4(mat, par, m);
1890         }
1891 }
1892
1893 // gives a world-space mat, end's mat not included
1894 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1895 {
1896         float m[4][4];
1897
1898         if (node == end) {
1899                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1900                 return true;
1901         }
1902
1903         // use bind matrix if available or calc "current" world mat
1904         if (!armature_importer->get_joint_bind_mat(m, node)) {
1905                 if (par) {
1906                         float temp[4][4];
1907                         get_node_mat(temp, node, NULL, NULL);
1908                         mul_m4_m4m4(m, par, temp);
1909                 }
1910                 else {
1911                         get_node_mat(m, node, NULL, NULL);
1912                 }
1913         }
1914
1915         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1916         for (unsigned int i = 0; i < children.getCount(); i++) {
1917                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1918                         return true;
1919         }
1920
1921         return false;
1922 }
1923
1924 #ifdef ARMATURE_TEST
1925 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1926 {
1927         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1928                 Object *job = bc_add_object(scene, OB_EMPTY, (char *)get_joint_name(node));
1929
1930                 job->lay = BKE_scene_base_find(scene, job)->lay = 2;
1931
1932                 mul_v3_fl(job->size, 0.5f);
1933                 DAG_id_tag_update(&job->id, OB_RECALC_OB);
1934
1935                 verify_adt_action((ID *)&job->id, 1);
1936
1937                 job->rotmode = ROT_MODE_QUAT;
1938
1939                 float mat[4][4];
1940                 get_joint_rest_mat(mat, root, node);
1941
1942                 if (par_job) {
1943                         float temp[4][4], ipar[4][4];
1944                         invert_m4_m4(ipar, par_job->obmat);
1945                         copy_m4_m4(temp, mat);
1946                         mul_m4_m4m4(mat, ipar, temp);
1947                 }
1948
1949                 bc_decompose(mat, job->loc, NULL, job->quat, job->size);
1950
1951                 if (par_job) {
1952                         job->parent = par_job;
1953
1954                         DAG_id_tag_update(&par_job->id, OB_RECALC_OB);
1955                         job->parsubstr[0] = 0;
1956                 }
1957
1958                 BKE_object_where_is_calc(scene, job);
1959
1960                 // after parenting and layer change
1961                 DAG_relations_tag_update(CTX_data_main(C));
1962
1963                 joint_objects[node->getUniqueId()] = job;
1964         }
1965
1966         return joint_objects[node->getUniqueId()];
1967 }
1968 #endif
1969
1970 #if 0
1971 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1972 // mat must be identity on enter, node must be root
1973 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1974 {
1975         float m[4][4];
1976         if (par) {
1977                 float temp[4][4];
1978                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1979                 mul_m4_m4m4(m, par, temp);
1980         }
1981         else {
1982                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1983         }
1984
1985         if (node == end) {
1986                 copy_m4_m4(mat, m);
1987                 return true;
1988         }
1989         else {
1990                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1991                 for (int i = 0; i < children.getCount(); i++) {
1992                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1993                                 return true;
1994                 }
1995         }
1996
1997         return false;
1998 }
1999 #endif
2000
2001 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
2002 {
2003         const char *bone_name = bc_get_joint_name(node);
2004         bAction *act = ob->adt->action;
2005                         
2006         /* try to find group */
2007         bActionGroup *grp = BKE_action_group_find_name(act, bone_name);
2008
2009         /* no matching groups, so add one */
2010         if (grp == NULL) {
2011                 /* Add a new group, and make it active */
2012                 grp = (bActionGroup *)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
2013
2014                 grp->flag = AGRP_SELECTED;
2015                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
2016
2017                 BLI_addtail(&act->groups, grp);
2018                 BLI_uniquename(&act->groups, grp, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "Group"), '.',
2019                                offsetof(bActionGroup, name), 64);
2020         }
2021
2022         /* add F-Curve to group */
2023         action_groups_add_channel(act, grp, fcu);
2024 }
2025
2026 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
2027 {
2028         //float fps = (float)FPS;
2029         BezTriple bez;
2030         memset(&bez, 0, sizeof(BezTriple));
2031         bez.vec[1][0] = fra;
2032         bez.vec[1][1] = value;
2033         bez.ipo = BEZT_IPO_LIN; /* use default interpolation mode here... */
2034         bez.f1 = bez.f2 = bez.f3 = SELECT;
2035         bez.h1 = bez.h2 = HD_AUTO;
2036         insert_bezt_fcurve(fcu, &bez, 0);
2037         calchandles_fcurve(fcu);
2038 }
2039
2040 void AnimationImporter::set_import_from_version(std::string import_from_version)
2041 {
2042         this->import_from_version = import_from_version;
2043 }