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