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