Cleanup: comment line length (editors)
[blender.git] / source / blender / ikplugin / intern / itasc_plugin.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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Original author: Benoit Bolsee
24  * Contributor(s):
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/ikplugin/intern/itasc_plugin.cpp
30  *  \ingroup ikplugin
31  */
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <vector>
36
37 // iTaSC headers
38 #ifdef WITH_IK_ITASC
39 #include "Armature.hpp"
40 #include "MovingFrame.hpp"
41 #include "CopyPose.hpp"
42 #include "WSDLSSolver.hpp"
43 #include "WDLSSolver.hpp"
44 #include "Scene.hpp"
45 #include "Cache.hpp"
46 #include "Distance.hpp"
47 #endif
48
49 #include "MEM_guardedalloc.h"
50
51 extern "C" {
52 #include "BIK_api.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_math.h"
55 #include "BLI_utildefines.h"
56
57 #include "BKE_global.h"
58 #include "BKE_armature.h"
59 #include "BKE_action.h"
60 #include "BKE_constraint.h"
61 #include "DNA_object_types.h"
62 #include "DNA_action_types.h"
63 #include "DNA_constraint_types.h"
64 #include "DNA_armature_types.h"
65 #include "DNA_scene_types.h"
66 };
67
68 #include "itasc_plugin.h"
69
70 // default parameters
71 static bItasc DefIKParam;
72
73 // in case of animation mode, feedback and timestep is fixed
74 // #define ANIM_TIMESTEP   1.0
75 #define ANIM_FEEDBACK   0.8
76 // #define ANIM_QMAX       0.52
77
78
79 // Structure pointed by bPose.ikdata
80 // It contains everything needed to simulate the armatures
81 // There can be several simulation islands independent to each other
82 struct IK_Data {
83         struct IK_Scene *first;
84 };
85
86 typedef float Vector3[3];
87 typedef float Vector4[4];
88 struct IK_Target;
89 typedef void (*ErrorCallback)(const iTaSC::ConstraintValues *values, unsigned int nvalues, IK_Target *iktarget);
90
91 // one structure for each target in the scene
92 struct IK_Target {
93         struct Scene                    *blscene;
94         iTaSC::MovingFrame*             target;
95         iTaSC::ConstraintSet*   constraint;
96         struct bConstraint*             blenderConstraint;
97         struct bPoseChannel*    rootChannel;
98         Object*                                 owner;                  //for auto IK
99         ErrorCallback                   errorCallback;
100         std::string                             targetName;
101         std::string                             constraintName;
102         unsigned short                  controlType;
103         short                                   channel;                //index in IK channel array of channel on which this target is defined
104         short                                   ee;                             //end effector number
105         bool                                    simulation;             //true when simulation mode is used (update feedback)
106         bool                                    eeBlend;                //end effector affected by enforce blending
107         float                                   eeRest[4][4];   //end effector initial pose relative to armature
108
109         IK_Target() {
110                 blscene = NULL;
111                 target = NULL;
112                 constraint = NULL;
113                 blenderConstraint = NULL;
114                 rootChannel = NULL;
115                 owner = NULL;
116                 controlType = 0;
117                 channel = 0;
118                 ee = 0;
119                 eeBlend = true;
120                 simulation = true;
121                 targetName.reserve(32);
122                 constraintName.reserve(32);
123         }
124         ~IK_Target() {
125                 if (constraint)
126                         delete constraint;
127                 if (target)
128                         delete target;
129         }
130 };
131
132 struct IK_Channel {
133         bPoseChannel*   pchan;          // channel where we must copy matrix back
134         KDL::Frame              frame;          // frame of the bone relative to object base, not armature base
135         std::string             tail;           // segment name of the joint from which we get the bone tail
136         std::string     head;           // segment name of the joint from which we get the bone head
137         int                             parent;         // index in this array of the parent channel
138         short                   jointType;      // type of joint, combination of IK_SegmentFlag
139         char                    ndof;           // number of joint angles for this channel
140         char                    jointValid;     // set to 1 when jointValue has been computed
141         // for joint constraint
142         Object*                 owner;                          // for pose and IK param
143         double                  jointValue[4];          // computed joint value
144
145         IK_Channel() {
146                 pchan = NULL;
147                 parent = -1;
148                 jointType = 0;
149                 ndof = 0;
150                 jointValid = 0;
151                 owner = NULL;
152                 jointValue[0] = 0.0;
153                 jointValue[1] = 0.0;
154                 jointValue[2] = 0.0;
155                 jointValue[3] = 0.0;
156         }
157 };
158
159 struct IK_Scene {
160         struct Scene            *blscene;
161         IK_Scene*                       next;
162         int                                     numchan;        // number of channel in pchan
163         int                                     numjoint;       // number of joint in jointArray
164         // array of bone information, one per channel in the tree
165         IK_Channel*                     channels;
166         iTaSC::Armature*        armature;
167         iTaSC::Cache*           cache;
168         iTaSC::Scene*           scene;
169         iTaSC::MovingFrame* base;               // armature base object
170         KDL::Frame                      baseFrame;      // frame of armature base relative to blArmature
171         KDL::JntArray           jointArray;     // buffer for storing temporary joint array
172         iTaSC::Solver*          solver;
173         Object*                         blArmature;
174         float                           blScale;        // scale of the Armature object (assume uniform scaling)
175         float                           blInvScale;     // inverse of Armature object scale
176         struct bConstraint*     polarConstraint;
177         std::vector<IK_Target*>         targets;
178
179         IK_Scene() {
180                 blscene = NULL;
181                 next = NULL;
182                 channels = NULL;
183                 armature = NULL;
184                 cache = NULL;
185                 scene = NULL;
186                 base = NULL;
187                 solver = NULL;
188                 blScale = blInvScale = 1.0f;
189                 blArmature = NULL;
190                 numchan = 0;
191                 numjoint = 0;
192                 polarConstraint = NULL;
193         }
194
195         ~IK_Scene() {
196                 // delete scene first
197                 if (scene)
198                         delete scene;
199                 for (std::vector<IK_Target *>::iterator it = targets.begin(); it != targets.end(); ++it)
200                         delete (*it);
201                 targets.clear();
202                 if (channels)
203                         delete[] channels;
204                 if (solver)
205                         delete solver;
206                 if (armature)
207                         delete armature;
208                 if (base)
209                         delete base;
210                 // delete cache last
211                 if (cache)
212                         delete cache;
213         }
214 };
215
216 // type of IK joint, can be combined to list the joints corresponding to a bone
217 enum IK_SegmentFlag {
218         IK_XDOF = 1,
219         IK_YDOF = 2,
220         IK_ZDOF = 4,
221         IK_SWING = 8,
222         IK_REVOLUTE = 16,
223         IK_TRANSY = 32,
224 };
225
226 enum IK_SegmentAxis {
227         IK_X = 0,
228         IK_Y = 1,
229         IK_Z = 2,
230         IK_TRANS_X = 3,
231         IK_TRANS_Y = 4,
232         IK_TRANS_Z = 5
233 };
234
235 static int initialize_chain(Object *ob, bPoseChannel *pchan_tip, bConstraint *con)
236 {
237         bPoseChannel *curchan, *pchan_root = NULL, *chanlist[256], **oldchan;
238         PoseTree *tree;
239         PoseTarget *target;
240         bKinematicConstraint *data;
241         int a, t, segcount = 0, size, newsize, *oldparent, parent, rootbone, treecount;
242
243         data = (bKinematicConstraint *)con->data;
244
245         /* exclude tip from chain? */
246         if (!(data->flag & CONSTRAINT_IK_TIP))
247                 pchan_tip = pchan_tip->parent;
248
249         rootbone = data->rootbone;
250         /* Find the chain's root & count the segments needed */
251         for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
252                 pchan_root = curchan;
253
254                 if (++segcount > 255)       // 255 is weak
255                         break;
256
257                 if (segcount == rootbone) {
258                         // reached this end of the chain but if the chain is overlapping with a
259                         // previous one, we must go back up to the root of the other chain
260                         if ((curchan->flag & POSE_CHAIN) && BLI_listbase_is_empty(&curchan->iktree)) {
261                                 rootbone++;
262                                 continue;
263                         }
264                         break;
265                 }
266
267                 if (BLI_listbase_is_empty(&curchan->iktree) == false)
268                         // Oh oh, there is already a chain starting from this channel and our chain is longer...
269                         // Should handle this by moving the previous chain up to the beginning of our chain
270                         // For now we just stop here
271                         break;
272         }
273         if (!segcount) return 0;
274         // we reached a limit and still not the end of a previous chain, quit
275         if ((pchan_root->flag & POSE_CHAIN) && BLI_listbase_is_empty(&pchan_root->iktree)) return 0;
276
277         // now that we know how many segment we have, set the flag
278         for (rootbone = segcount, segcount = 0, curchan = pchan_tip; segcount < rootbone; segcount++, curchan = curchan->parent) {
279                 chanlist[segcount] = curchan;
280                 curchan->flag |= POSE_CHAIN;
281         }
282
283         /* setup the chain data */
284         /* create a target */
285         target = (PoseTarget *)MEM_callocN(sizeof(PoseTarget), "posetarget");
286         target->con = con;
287         // by contruction there can be only one tree per channel and each channel can be part of at most one tree.
288         tree = (PoseTree *)pchan_root->iktree.first;
289
290         if (tree == NULL) {
291                 /* make new tree */
292                 tree = (PoseTree *)MEM_callocN(sizeof(PoseTree), "posetree");
293
294                 tree->iterations = data->iterations;
295                 tree->totchannel = segcount;
296                 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
297
298                 tree->pchan = (bPoseChannel **)MEM_callocN(segcount * sizeof(void *), "ik tree pchan");
299                 tree->parent = (int *)MEM_callocN(segcount * sizeof(int), "ik tree parent");
300                 for (a = 0; a < segcount; a++) {
301                         tree->pchan[a] = chanlist[segcount - a - 1];
302                         tree->parent[a] = a - 1;
303                 }
304                 target->tip = segcount - 1;
305
306                 /* AND! link the tree to the root */
307                 BLI_addtail(&pchan_root->iktree, tree);
308                 // new tree
309                 treecount = 1;
310         }
311         else {
312                 tree->iterations = MAX2(data->iterations, tree->iterations);
313                 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
314
315                 /* skip common pose channels and add remaining*/
316                 size = MIN2(segcount, tree->totchannel);
317                 a = t = 0;
318                 while (a < size && t < tree->totchannel) {
319                         // locate first matching channel
320                         for (; t < tree->totchannel && tree->pchan[t] != chanlist[segcount - a - 1]; t++) ;
321                         if (t >= tree->totchannel)
322                                 break;
323                         for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1]; a++, t++) ;
324                 }
325
326                 segcount = segcount - a;
327                 target->tip = tree->totchannel + segcount - 1;
328
329                 if (segcount > 0) {
330                         for (parent = a - 1; parent < tree->totchannel; parent++)
331                                 if (tree->pchan[parent] == chanlist[segcount - 1]->parent)
332                                         break;
333
334                         /* shouldn't happen, but could with dependency cycles */
335                         if (parent == tree->totchannel)
336                                 parent = a - 1;
337
338                         /* resize array */
339                         newsize = tree->totchannel + segcount;
340                         oldchan = tree->pchan;
341                         oldparent = tree->parent;
342
343                         tree->pchan = (bPoseChannel **)MEM_callocN(newsize * sizeof(void *), "ik tree pchan");
344                         tree->parent = (int *)MEM_callocN(newsize * sizeof(int), "ik tree parent");
345                         memcpy(tree->pchan, oldchan, sizeof(void *) * tree->totchannel);
346                         memcpy(tree->parent, oldparent, sizeof(int) * tree->totchannel);
347                         MEM_freeN(oldchan);
348                         MEM_freeN(oldparent);
349
350                         /* add new pose channels at the end, in reverse order */
351                         for (a = 0; a < segcount; a++) {
352                                 tree->pchan[tree->totchannel + a] = chanlist[segcount - a - 1];
353                                 tree->parent[tree->totchannel + a] = tree->totchannel + a - 1;
354                         }
355                         tree->parent[tree->totchannel] = parent;
356
357                         tree->totchannel = newsize;
358                 }
359                 // reusing tree
360                 treecount = 0;
361         }
362
363         /* add target to the tree */
364         BLI_addtail(&tree->targets, target);
365         /* mark root channel having an IK tree */
366         pchan_root->flag |= POSE_IKTREE;
367         return treecount;
368 }
369
370 static bool is_cartesian_constraint(bConstraint *con)
371 {
372         //bKinematicConstraint* data=(bKinematicConstraint *)con->data;
373
374         return true;
375 }
376
377 static bool constraint_valid(bConstraint *con)
378 {
379         bKinematicConstraint *data = (bKinematicConstraint *)con->data;
380
381         if (data->flag & CONSTRAINT_IK_AUTO)
382                 return true;
383         if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF))
384                 return false;
385         if (is_cartesian_constraint(con)) {
386                 /* cartesian space constraint */
387                 if (data->tar == NULL)
388                         return false;
389                 if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)
390                         return false;
391         }
392         return true;
393 }
394
395 static int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
396 {
397         bConstraint *con;
398         int treecount;
399
400         /* find all IK constraints and validate them */
401         treecount = 0;
402         for (con = (bConstraint *)pchan_tip->constraints.first; con; con = (bConstraint *)con->next) {
403                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
404                         if (constraint_valid(con))
405                                 treecount += initialize_chain(ob, pchan_tip, con);
406                 }
407         }
408         return treecount;
409 }
410
411 static IK_Data *get_ikdata(bPose *pose)
412 {
413         if (pose->ikdata)
414                 return (IK_Data *)pose->ikdata;
415         pose->ikdata = MEM_callocN(sizeof(IK_Data), "iTaSC ikdata");
416         // here init ikdata if needed
417         // now that we have scene, make sure the default param are initialized
418         if (!DefIKParam.iksolver)
419                 BKE_pose_itasc_init(&DefIKParam);
420
421         return (IK_Data *)pose->ikdata;
422 }
423 static double EulerAngleFromMatrix(const KDL::Rotation& R, int axis)
424 {
425         double t = KDL::sqrt(R(0, 0) * R(0, 0) + R(0, 1) * R(0, 1));
426
427         if (t > 16.0 * KDL::epsilon) {
428                 if (axis == 0) return -KDL::atan2(R(1, 2), R(2, 2));
429                 else if (axis == 1) return KDL::atan2(-R(0, 2), t);
430                 else return -KDL::atan2(R(0, 1), R(0, 0));
431         }
432         else {
433                 if (axis == 0) return -KDL::atan2(-R(2, 1), R(1, 1));
434                 else if (axis == 1) return KDL::atan2(-R(0, 2), t);
435                 else return 0.0f;
436         }
437 }
438
439 static double ComputeTwist(const KDL::Rotation& R)
440 {
441         // qy and qw are the y and w components of the quaternion from R
442         double qy = R(0, 2) - R(2, 0);
443         double qw = R(0, 0) + R(1, 1) + R(2, 2) + 1;
444
445         double tau = 2 * KDL::atan2(qy, qw);
446
447         return tau;
448 }
449
450 static void RemoveEulerAngleFromMatrix(KDL::Rotation& R, double angle, int axis)
451 {
452         // compute twist parameter
453         KDL::Rotation T;
454         switch (axis) {
455                 case 0:
456                         T = KDL::Rotation::RotX(-angle);
457                         break;
458                 case 1:
459                         T = KDL::Rotation::RotY(-angle);
460                         break;
461                 case 2:
462                         T = KDL::Rotation::RotZ(-angle);
463                         break;
464                 default:
465                         return;
466         }
467         // remove angle
468         R = R * T;
469 }
470
471 #if 0
472 static void GetEulerXZY(const KDL::Rotation& R, double& X, double& Z, double& Y)
473 {
474         if (fabs(R(0, 1)) > 1.0 - KDL::epsilon) {
475                 X = -KDL::sign(R(0, 1)) * KDL::atan2(R(1, 2), R(1, 0));
476                 Z = -KDL::sign(R(0, 1)) * KDL::PI / 2;
477                 Y = 0.0;
478         }
479         else {
480                 X = KDL::atan2(R(2, 1), R(1, 1));
481                 Z = KDL::atan2(-R(0, 1), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 2))));
482                 Y = KDL::atan2(R(0, 2), R(0, 0));
483         }
484 }
485
486 static void GetEulerXYZ(const KDL::Rotation& R, double& X, double& Y, double& Z)
487 {
488         if (fabs(R(0, 2)) > 1.0 - KDL::epsilon) {
489                 X = KDL::sign(R(0, 2)) * KDL::atan2(-R(1, 0), R(1, 1));
490                 Y = KDL::sign(R(0, 2)) * KDL::PI / 2;
491                 Z = 0.0;
492         }
493         else {
494                 X = KDL::atan2(-R(1, 2), R(2, 2));
495                 Y = KDL::atan2(R(0, 2), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 1))));
496                 Z = KDL::atan2(-R(0, 1), R(0, 0));
497         }
498 }
499 #endif
500
501 static void GetJointRotation(KDL::Rotation& boneRot, int type, double *rot)
502 {
503         switch (type & ~IK_TRANSY) {
504                 default:
505                         // fixed bone, no joint
506                         break;
507                 case IK_XDOF:
508                         // RX only, get the X rotation
509                         rot[0] = EulerAngleFromMatrix(boneRot, 0);
510                         break;
511                 case IK_YDOF:
512                         // RY only, get the Y rotation
513                         rot[0] = ComputeTwist(boneRot);
514                         break;
515                 case IK_ZDOF:
516                         // RZ only, get the Z rotation
517                         rot[0] = EulerAngleFromMatrix(boneRot, 2);
518                         break;
519                 case IK_XDOF | IK_YDOF:
520                         rot[1] = ComputeTwist(boneRot);
521                         RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
522                         rot[0] = EulerAngleFromMatrix(boneRot, 0);
523                         break;
524                 case IK_SWING:
525                         // RX+RZ
526                         boneRot.GetXZRot().GetValue(rot);
527                         break;
528                 case IK_YDOF | IK_ZDOF:
529                         // RZ+RY
530                         rot[1] = ComputeTwist(boneRot);
531                         RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
532                         rot[0] = EulerAngleFromMatrix(boneRot, 2);
533                         break;
534                 case IK_SWING | IK_YDOF:
535                         rot[2] = ComputeTwist(boneRot);
536                         RemoveEulerAngleFromMatrix(boneRot, rot[2], 1);
537                         boneRot.GetXZRot().GetValue(rot);
538                         break;
539                 case IK_REVOLUTE:
540                         boneRot.GetRot().GetValue(rot);
541                         break;
542         }
543 }
544
545 static bool target_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param)
546 {
547         IK_Target *target = (IK_Target *)param;
548         // compute next target position
549         // get target matrix from constraint.
550         bConstraint *constraint = (bConstraint *)target->blenderConstraint;
551         float tarmat[4][4];
552
553         BKE_constraint_target_matrix_get(target->blscene, constraint, 0, CONSTRAINT_OBTYPE_OBJECT, target->owner, tarmat, 1.0);
554
555         // rootmat contains the target pose in world coordinate
556         // if enforce is != 1.0, blend the target position with the end effector position
557         // if the armature was in rest position. This information is available in eeRest
558         if (constraint->enforce != 1.0f && target->eeBlend) {
559                 // eeRest is relative to the reference frame of the IK root
560                 // get this frame in world reference
561                 float restmat[4][4];
562                 bPoseChannel *pchan = target->rootChannel;
563                 if (pchan->parent) {
564                         pchan = pchan->parent;
565                         float chanmat[4][4];
566                         copy_m4_m4(chanmat, pchan->pose_mat);
567                         copy_v3_v3(chanmat[3], pchan->pose_tail);
568                         mul_m4_series(restmat, target->owner->obmat, chanmat, target->eeRest);
569                 }
570                 else {
571                         mul_m4_m4m4(restmat, target->owner->obmat, target->eeRest);
572                 }
573                 // blend the target
574                 blend_m4_m4m4(tarmat, restmat, tarmat, constraint->enforce);
575         }
576         next.setValue(&tarmat[0][0]);
577         return true;
578 }
579
580 static bool base_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param)
581 {
582         IK_Scene *ikscene = (IK_Scene *)param;
583         // compute next armature base pose
584         // algorithm:
585         // ikscene->pchan[0] is the root channel of the tree
586         // if it has a parent, get the pose matrix from it and replace [3] by parent pchan->tail
587         // then multiply by the armature matrix to get ikscene->armature base position
588         bPoseChannel *pchan = ikscene->channels[0].pchan;
589         float rootmat[4][4];
590         if (pchan->parent) {
591                 pchan = pchan->parent;
592                 float chanmat[4][4];
593                 copy_m4_m4(chanmat, pchan->pose_mat);
594                 copy_v3_v3(chanmat[3], pchan->pose_tail);
595                 // save the base as a frame too so that we can compute deformation after simulation
596                 ikscene->baseFrame.setValue(&chanmat[0][0]);
597                 // iTaSC armature is scaled to object scale, scale the base frame too
598                 ikscene->baseFrame.p *= ikscene->blScale;
599                 mul_m4_m4m4(rootmat, ikscene->blArmature->obmat, chanmat);
600         }
601         else {
602                 copy_m4_m4(rootmat, ikscene->blArmature->obmat);
603                 ikscene->baseFrame = iTaSC::F_identity;
604         }
605         next.setValue(&rootmat[0][0]);
606         // if there is a polar target (only during solving otherwise we don't have end efffector)
607         if (ikscene->polarConstraint && timestamp.update) {
608                 // compute additional rotation of base frame so that armature follows the polar target
609                 float imat[4][4];       // IK tree base inverse matrix
610                 float polemat[4][4];    // polar target in IK tree base frame
611                 float goalmat[4][4];    // target in IK tree base frame
612                 float mat[4][4];        // temp matrix
613                 bKinematicConstraint *poledata = (bKinematicConstraint *)ikscene->polarConstraint->data;
614
615                 invert_m4_m4(imat, rootmat);
616                 // polar constraint imply only one target
617                 IK_Target *iktarget = ikscene->targets[0];
618                 // root channel from which we take the bone initial orientation
619                 IK_Channel &rootchan = ikscene->channels[0];
620
621                 // get polar target matrix in world space
622                 BKE_constraint_target_matrix_get(ikscene->blscene, ikscene->polarConstraint, 1, CONSTRAINT_OBTYPE_OBJECT, ikscene->blArmature, mat, 1.0);
623                 // convert to armature space
624                 mul_m4_m4m4(polemat, imat, mat);
625                 // get the target in world space (was computed before as target object are defined before base object)
626                 iktarget->target->getPose().getValue(mat[0]);
627                 // convert to armature space
628                 mul_m4_m4m4(goalmat, imat, mat);
629                 // take position of target, polar target, end effector, in armature space
630                 KDL::Vector goalpos(goalmat[3]);
631                 KDL::Vector polepos(polemat[3]);
632                 KDL::Vector endpos = ikscene->armature->getPose(iktarget->ee).p;
633                 // get root bone orientation
634                 KDL::Frame rootframe;
635                 ikscene->armature->getRelativeFrame(rootframe, rootchan.tail);
636                 KDL::Vector rootx = rootframe.M.UnitX();
637                 KDL::Vector rootz = rootframe.M.UnitZ();
638                 // and compute root bone head
639                 double q_rest[3], q[3], length;
640                 const KDL::Joint *joint;
641                 const KDL::Frame *tip;
642                 ikscene->armature->getSegment(rootchan.tail, 3, joint, q_rest[0], q[0], tip);
643                 length = (joint->getType() == KDL::Joint::TransY) ? q[0] : tip->p(1);
644                 KDL::Vector rootpos = rootframe.p - length *rootframe.M.UnitY();
645
646                 // compute main directions
647                 KDL::Vector dir = KDL::Normalize(endpos - rootpos);
648                 KDL::Vector poledir = KDL::Normalize(goalpos - rootpos);
649                 // compute up directions
650                 KDL::Vector poleup = KDL::Normalize(polepos - rootpos);
651                 KDL::Vector up = rootx * KDL::cos(poledata->poleangle) + rootz *KDL::sin(poledata->poleangle);
652                 // from which we build rotation matrix
653                 KDL::Rotation endrot, polerot;
654                 // for the armature, using the root bone orientation
655                 KDL::Vector x = KDL::Normalize(dir * up);
656                 endrot.UnitX(x);
657                 endrot.UnitY(KDL::Normalize(x * dir));
658                 endrot.UnitZ(-dir);
659                 // for the polar target
660                 x = KDL::Normalize(poledir * poleup);
661                 polerot.UnitX(x);
662                 polerot.UnitY(KDL::Normalize(x * poledir));
663                 polerot.UnitZ(-poledir);
664                 // the difference between the two is the rotation we want to apply
665                 KDL::Rotation result(polerot * endrot.Inverse());
666                 // apply on base frame as this is an artificial additional rotation
667                 next.M = next.M * result;
668                 ikscene->baseFrame.M = ikscene->baseFrame.M * result;
669         }
670         return true;
671 }
672
673 static bool copypose_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
674 {
675         IK_Target *iktarget = (IK_Target *)_param;
676         bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
677         iTaSC::ConstraintValues *values = _values;
678         bItasc *ikparam = (bItasc *) iktarget->owner->pose->ikparam;
679
680         // we need default parameters
681         if (!ikparam)
682                 ikparam = &DefIKParam;
683
684         if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
685                 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
686                         values->alpha = 0.0;
687                         values->action = iTaSC::ACT_ALPHA;
688                         values++;
689                 }
690                 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
691                         values->alpha = 0.0;
692                         values->action = iTaSC::ACT_ALPHA;
693                         values++;
694                 }
695         }
696         else {
697                 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
698                         // update error
699                         values->alpha = condata->weight;
700                         values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
701                         values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
702                         values++;
703                 }
704                 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
705                         // update error
706                         values->alpha = condata->orientweight;
707                         values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
708                         values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
709                         values++;
710                 }
711         }
712         return true;
713 }
714
715 static void copypose_error(const iTaSC::ConstraintValues *values, unsigned int nvalues, IK_Target *iktarget)
716 {
717         iTaSC::ConstraintSingleValue *value;
718         double error;
719         int i;
720
721         if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
722                 // update error
723                 for (i = 0, error = 0.0, value = values->values; i < values->number; ++i, ++value)
724                         error += KDL::sqr(value->y - value->yd);
725                 iktarget->blenderConstraint->lin_error = (float)KDL::sqrt(error);
726                 values++;
727         }
728         if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
729                 // update error
730                 for (i = 0, error = 0.0, value = values->values; i < values->number; ++i, ++value)
731                         error += KDL::sqr(value->y - value->yd);
732                 iktarget->blenderConstraint->rot_error = (float)KDL::sqrt(error);
733                 values++;
734         }
735 }
736
737 static bool distance_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
738 {
739         IK_Target *iktarget = (IK_Target *)_param;
740         bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
741         iTaSC::ConstraintValues *values = _values;
742         bItasc *ikparam = (bItasc *) iktarget->owner->pose->ikparam;
743         // we need default parameters
744         if (!ikparam)
745                 ikparam = &DefIKParam;
746
747         // update weight according to mode
748         if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
749                 values->alpha = 0.0;
750         }
751         else {
752                 switch (condata->mode) {
753                         case LIMITDIST_INSIDE:
754                                 values->alpha = (values->values[0].y > condata->dist) ? condata->weight : 0.0;
755                                 break;
756                         case LIMITDIST_OUTSIDE:
757                                 values->alpha = (values->values[0].y < condata->dist) ? condata->weight : 0.0;
758                                 break;
759                         default:
760                                 values->alpha = condata->weight;
761                                 break;
762                 }
763                 if (!timestamp.substep) {
764                         // only update value on first timestep
765                         switch (condata->mode) {
766                                 case LIMITDIST_INSIDE:
767                                         values->values[0].yd = condata->dist * 0.95;
768                                         break;
769                                 case LIMITDIST_OUTSIDE:
770                                         values->values[0].yd = condata->dist * 1.05;
771                                         break;
772                                 default:
773                                         values->values[0].yd = condata->dist;
774                                         break;
775                         }
776                         values->values[0].action = iTaSC::ACT_VALUE | iTaSC::ACT_FEEDBACK;
777                         values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
778                 }
779         }
780         values->action |= iTaSC::ACT_ALPHA;
781         return true;
782 }
783
784 static void distance_error(const iTaSC::ConstraintValues *values, unsigned int _nvalues, IK_Target *iktarget)
785 {
786         iktarget->blenderConstraint->lin_error = (float)(values->values[0].y - values->values[0].yd);
787 }
788
789 static bool joint_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
790 {
791         IK_Channel *ikchan = (IK_Channel *)_param;
792         bItasc *ikparam = (bItasc *)ikchan->owner->pose->ikparam;
793         bPoseChannel *chan = ikchan->pchan;
794         int dof;
795
796         // a channel can be splitted into multiple joints, so we get called multiple
797         // times for one channel (this callback is only for 1 joint in the armature)
798         // the IK_JointTarget structure is shared between multiple joint constraint
799         // and the target joint values is computed only once, remember this in jointValid
800         // Don't forget to reset it before each frame
801         if (!ikchan->jointValid) {
802                 float rmat[3][3];
803
804                 if (chan->rotmode > 0) {
805                         /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
806                         eulO_to_mat3(rmat, chan->eul, chan->rotmode);
807                 }
808                 else if (chan->rotmode == ROT_MODE_AXISANGLE) {
809                         /* axis-angle - stored in quaternion data, but not really that great for 3D-changing orientations */
810                         axis_angle_to_mat3(rmat, &chan->quat[1], chan->quat[0]);
811                 }
812                 else {
813                         /* quats are normalized before use to eliminate scaling issues */
814                         normalize_qt(chan->quat);
815                         quat_to_mat3(rmat, chan->quat);
816                 }
817                 KDL::Rotation jointRot(
818                     rmat[0][0], rmat[1][0], rmat[2][0],
819                     rmat[0][1], rmat[1][1], rmat[2][1],
820                     rmat[0][2], rmat[1][2], rmat[2][2]);
821                 GetJointRotation(jointRot, ikchan->jointType, ikchan->jointValue);
822                 ikchan->jointValid = 1;
823         }
824         // determine which part of jointValue is used for this joint
825         // closely related to the way the joints are defined
826         switch (ikchan->jointType & ~IK_TRANSY) {
827                 case IK_XDOF:
828                 case IK_YDOF:
829                 case IK_ZDOF:
830                         dof = 0;
831                         break;
832                 case IK_XDOF | IK_YDOF:
833                         // X + Y
834                         dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RX) ? 0 : 1;
835                         break;
836                 case IK_SWING:
837                         // XZ
838                         dof = 0;
839                         break;
840                 case IK_YDOF | IK_ZDOF:
841                         // Z + Y
842                         dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RZ) ? 0 : 1;
843                         break;
844                 case IK_SWING | IK_YDOF:
845                         // XZ + Y
846                         dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RY) ? 2 : 0;
847                         break;
848                 case IK_REVOLUTE:
849                         dof = 0;
850                         break;
851                 default:
852                         dof = -1;
853                         break;
854         }
855         if (dof >= 0) {
856                 for (unsigned int i = 0; i < _nvalues; i++, dof++) {
857                         _values[i].values[0].yd = ikchan->jointValue[dof];
858                         _values[i].alpha = chan->ikrotweight;
859                         _values[i].feedback = ikparam->feedback;
860                 }
861         }
862         return true;
863 }
864
865 // build array of joint corresponding to IK chain
866 static int convert_channels(IK_Scene *ikscene, PoseTree *tree, float ctime)
867 {
868         IK_Channel *ikchan;
869         bPoseChannel *pchan;
870         int a, flag, njoint;
871
872         njoint = 0;
873         for (a = 0, ikchan = ikscene->channels; a < ikscene->numchan; ++a, ++ikchan) {
874                 pchan = tree->pchan[a];
875                 ikchan->pchan = pchan;
876                 ikchan->parent = (a > 0) ? tree->parent[a] : -1;
877                 ikchan->owner = ikscene->blArmature;
878
879                 // the constraint and channels must be applied before we build the iTaSC scene,
880                 // this is because some of the pose data (e.g. pose head) don't have corresponding
881                 // joint angles and can't be applied to the iTaSC armature dynamically
882                 if (!(pchan->flag & POSE_DONE))
883                         BKE_pose_where_is_bone(ikscene->blscene, ikscene->blArmature, pchan, ctime, 1);
884                 // tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is()
885                 pchan->flag |= (POSE_DONE | POSE_CHAIN);
886
887                 /* set DoF flag */
888                 flag = 0;
889                 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP) &&
890                     (!(pchan->ikflag & BONE_IK_XLIMIT) || pchan->limitmin[0] < 0.f || pchan->limitmax[0] > 0.f))
891                 {
892                         flag |= IK_XDOF;
893                 }
894                 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP) &&
895                     (!(pchan->ikflag & BONE_IK_YLIMIT) || pchan->limitmin[1] < 0.f || pchan->limitmax[1] > 0.f))
896                 {
897                         flag |= IK_YDOF;
898                 }
899                 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP) &&
900                     (!(pchan->ikflag & BONE_IK_ZLIMIT) || pchan->limitmin[2] < 0.f || pchan->limitmax[2] > 0.f))
901                 {
902                         flag |= IK_ZDOF;
903                 }
904
905                 if (tree->stretch && (pchan->ikstretch > 0.0)) {
906                         flag |= IK_TRANSY;
907                 }
908                 /*
909                  * Logic to create the segments:
910                  * RX,RY,RZ = rotational joints with no length
911                  * RY(tip) = rotational joints with a fixed length arm = (0,length,0)
912                  * TY = translational joint on Y axis
913                  * F(pos) = fixed joint with an arm at position pos
914                  * Conversion rule of the above flags:
915                  * -   ==> F(tip)
916                  * X   ==> RX(tip)
917                  * Y   ==> RY(tip)
918                  * Z   ==> RZ(tip)
919                  * XY  ==> RX+RY(tip)
920                  * XZ  ==> RX+RZ(tip)
921                  * YZ  ==> RZ+RY(tip)
922                  * XYZ ==> full spherical unless there are limits, in which case RX+RZ+RY(tip)
923                  * In case of stretch, tip=(0,0,0) and there is an additional TY joint
924                  * The frame at last of these joints represents the tail of the bone.
925                  * The head is computed by a reverse translation on Y axis of the bone length
926                  * or in case of TY joint, by the frame at previous joint.
927                  * In case of separation of bones, there is an additional F(head) joint
928                  *
929                  * Computing rest pose and length is complicated: the solver works in world space
930                  * Here is the logic:
931                  * rest position is computed only from bone->bone_mat.
932                  * bone length is computed from bone->length multiplied by the scaling factor of
933                  * the armature. Non-uniform scaling will give bad result!
934                  */
935                 switch (flag & (IK_XDOF | IK_YDOF | IK_ZDOF)) {
936                         default:
937                                 ikchan->jointType = 0;
938                                 ikchan->ndof = 0;
939                                 break;
940                         case IK_XDOF:
941                                 // RX only, get the X rotation
942                                 ikchan->jointType = IK_XDOF;
943                                 ikchan->ndof = 1;
944                                 break;
945                         case IK_YDOF:
946                                 // RY only, get the Y rotation
947                                 ikchan->jointType = IK_YDOF;
948                                 ikchan->ndof = 1;
949                                 break;
950                         case IK_ZDOF:
951                                 // RZ only, get the Zz rotation
952                                 ikchan->jointType = IK_ZDOF;
953                                 ikchan->ndof = 1;
954                                 break;
955                         case IK_XDOF | IK_YDOF:
956                                 ikchan->jointType = IK_XDOF | IK_YDOF;
957                                 ikchan->ndof = 2;
958                                 break;
959                         case IK_XDOF | IK_ZDOF:
960                                 // RX+RZ
961                                 ikchan->jointType = IK_SWING;
962                                 ikchan->ndof = 2;
963                                 break;
964                         case IK_YDOF | IK_ZDOF:
965                                 // RZ+RY
966                                 ikchan->jointType = IK_ZDOF | IK_YDOF;
967                                 ikchan->ndof = 2;
968                                 break;
969                         case IK_XDOF | IK_YDOF | IK_ZDOF:
970                                 // spherical joint
971                                 if (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_YLIMIT | BONE_IK_ZLIMIT))
972                                         // decompose in a Swing+RotY joint
973                                         ikchan->jointType = IK_SWING | IK_YDOF;
974                                 else
975                                         ikchan->jointType = IK_REVOLUTE;
976                                 ikchan->ndof = 3;
977                                 break;
978                 }
979                 if (flag & IK_TRANSY) {
980                         ikchan->jointType |= IK_TRANSY;
981                         ikchan->ndof++;
982                 }
983                 njoint += ikchan->ndof;
984         }
985         // njoint is the joint coordinate, create the Joint Array
986         ikscene->jointArray.resize(njoint);
987         ikscene->numjoint = njoint;
988         return njoint;
989 }
990
991 // compute array of joint value corresponding to current pose
992 static void convert_pose(IK_Scene *ikscene)
993 {
994         KDL::Rotation boneRot;
995         bPoseChannel *pchan;
996         IK_Channel *ikchan;
997         Bone *bone;
998         float rmat[4][4];   // rest pose of bone with parent taken into account
999         float bmat[4][4];   // difference
1000         float scale;
1001         double *rot;
1002         int a, joint;
1003
1004         // assume uniform scaling and take Y scale as general scale for the armature
1005         scale = len_v3(ikscene->blArmature->obmat[1]);
1006         rot = ikscene->jointArray(0);
1007         for (joint = a = 0, ikchan = ikscene->channels; a < ikscene->numchan && joint < ikscene->numjoint; ++a, ++ikchan) {
1008                 pchan = ikchan->pchan;
1009                 bone = pchan->bone;
1010
1011                 if (pchan->parent) {
1012                         unit_m4(bmat);
1013                         mul_m4_m4m3(bmat, pchan->parent->pose_mat, bone->bone_mat);
1014                 }
1015                 else {
1016                         copy_m4_m4(bmat, bone->arm_mat);
1017                 }
1018                 invert_m4_m4(rmat, bmat);
1019                 mul_m4_m4m4(bmat, rmat, pchan->pose_mat);
1020                 normalize_m4(bmat);
1021                 boneRot.setValue(bmat[0]);
1022                 GetJointRotation(boneRot, ikchan->jointType, rot);
1023                 if (ikchan->jointType & IK_TRANSY) {
1024                         // compute actual length
1025                         rot[ikchan->ndof - 1] = len_v3v3(pchan->pose_tail, pchan->pose_head) * scale;
1026                 }
1027                 rot += ikchan->ndof;
1028                 joint += ikchan->ndof;
1029         }
1030 }
1031
1032 // compute array of joint value corresponding to current pose
1033 static void BKE_pose_rest(IK_Scene *ikscene)
1034 {
1035         bPoseChannel *pchan;
1036         IK_Channel *ikchan;
1037         Bone *bone;
1038         float scale;
1039         double *rot;
1040         int a, joint;
1041
1042         // assume uniform scaling and take Y scale as general scale for the armature
1043         scale = len_v3(ikscene->blArmature->obmat[1]);
1044         // rest pose is 0
1045         SetToZero(ikscene->jointArray);
1046         // except for transY joints
1047         rot = ikscene->jointArray(0);
1048         for (joint = a = 0, ikchan = ikscene->channels; a < ikscene->numchan && joint < ikscene->numjoint; ++a, ++ikchan) {
1049                 pchan = ikchan->pchan;
1050                 bone = pchan->bone;
1051
1052                 if (ikchan->jointType & IK_TRANSY)
1053                         rot[ikchan->ndof - 1] = bone->length * scale;
1054                 rot += ikchan->ndof;
1055                 joint += ikchan->ndof;
1056         }
1057 }
1058
1059 static IK_Scene *convert_tree(Scene *blscene, Object *ob, bPoseChannel *pchan, float ctime)
1060 {
1061         PoseTree *tree = (PoseTree *)pchan->iktree.first;
1062         PoseTarget *target;
1063         bKinematicConstraint *condata;
1064         bConstraint *polarcon;
1065         bItasc *ikparam;
1066         iTaSC::Armature *arm;
1067         iTaSC::Scene *scene;
1068         IK_Scene *ikscene;
1069         IK_Channel *ikchan;
1070         KDL::Frame initPose;
1071         KDL::Rotation boneRot;
1072         Bone *bone;
1073         int a, numtarget;
1074         unsigned int t;
1075         float length;
1076         bool ret = true, ingame;
1077         double *rot;
1078         float start[3];
1079
1080         if (tree->totchannel == 0)
1081                 return NULL;
1082
1083         ikscene = new IK_Scene;
1084         ikscene->blscene = blscene;
1085         arm = new iTaSC::Armature();
1086         scene = new iTaSC::Scene();
1087         ikscene->channels = new IK_Channel[tree->totchannel];
1088         ikscene->numchan = tree->totchannel;
1089         ikscene->armature = arm;
1090         ikscene->scene = scene;
1091         ikparam = (bItasc *)ob->pose->ikparam;
1092         ingame = (ob->pose->flag & POSE_GAME_ENGINE);
1093         if (!ikparam) {
1094                 // you must have our own copy
1095                 ikparam = &DefIKParam;
1096         }
1097         else if (ingame) {
1098                 // tweak the param when in game to have efficient stepping
1099                 // using fixed substep is not effecient since frames in the GE are often
1100                 // shorter than in animation => move to auto step automatically and set
1101                 // the target substep duration via min/max
1102                 if (!(ikparam->flag & ITASC_AUTO_STEP)) {
1103                         float timestep = blscene->r.frs_sec_base / blscene->r.frs_sec;
1104                         if (ikparam->numstep > 0)
1105                                 timestep /= ikparam->numstep;
1106                         // with equal min and max, the algorythm will take this step and the indicative substep most of the time
1107                         ikparam->minstep = ikparam->maxstep = timestep;
1108                         ikparam->flag |= ITASC_AUTO_STEP;
1109                 }
1110         }
1111         if ((ikparam->flag & ITASC_SIMULATION) && !ingame)
1112                 // no cache in animation mode
1113                 ikscene->cache = new iTaSC::Cache();
1114
1115         switch (ikparam->solver) {
1116                 case ITASC_SOLVER_SDLS:
1117                         ikscene->solver = new iTaSC::WSDLSSolver();
1118                         break;
1119                 case ITASC_SOLVER_DLS:
1120                         ikscene->solver = new iTaSC::WDLSSolver();
1121                         break;
1122                 default:
1123                         delete ikscene;
1124                         return NULL;
1125         }
1126         ikscene->blArmature = ob;
1127         // assume uniform scaling and take Y scale as general scale for the armature
1128         ikscene->blScale = len_v3(ob->obmat[1]);
1129         ikscene->blInvScale = (ikscene->blScale < KDL::epsilon) ? 0.0f : 1.0f / ikscene->blScale;
1130
1131         std::string joint;
1132         std::string root("root");
1133         std::string parent;
1134         std::vector<double> weights;
1135         double weight[3];
1136         // build the array of joints corresponding to the IK chain
1137         convert_channels(ikscene, tree, ctime);
1138         if (ingame) {
1139                 // in the GE, set the initial joint angle to match the current pose
1140                 // this will update the jointArray in ikscene
1141                 convert_pose(ikscene);
1142         }
1143         else {
1144                 // in Blender, the rest pose is always 0 for joints
1145                 BKE_pose_rest(ikscene);
1146         }
1147         rot = ikscene->jointArray(0);
1148
1149         for (a = 0, ikchan = ikscene->channels; a < tree->totchannel; ++a, ++ikchan) {
1150                 pchan = ikchan->pchan;
1151                 bone = pchan->bone;
1152
1153                 KDL::Frame tip(iTaSC::F_identity);
1154                 // compute the position and rotation of the head from previous segment
1155                 Vector3 *fl = bone->bone_mat;
1156                 KDL::Rotation brot(
1157                     fl[0][0], fl[1][0], fl[2][0],
1158                     fl[0][1], fl[1][1], fl[2][1],
1159                     fl[0][2], fl[1][2], fl[2][2]);
1160                 // if the bone is disconnected, the head is movable in pose mode
1161                 // take that into account by using pose matrix instead of bone
1162                 // Note that pose is expressed in armature space, convert to previous bone space
1163                 {
1164                         float R_parmat[3][3];
1165                         float iR_parmat[3][3];
1166                         if (pchan->parent)
1167                                 copy_m3_m4(R_parmat, pchan->parent->pose_mat);
1168                         else
1169                                 unit_m3(R_parmat);
1170                         if (pchan->parent)
1171                                 sub_v3_v3v3(start, pchan->pose_head, pchan->parent->pose_tail);
1172                         else
1173                                 start[0] = start[1] = start[2] = 0.0f;
1174                         invert_m3_m3(iR_parmat, R_parmat);
1175                         normalize_m3(iR_parmat);
1176                         mul_m3_v3(iR_parmat, start);
1177                 }
1178                 KDL::Vector bpos(start[0], start[1], start[2]);
1179                 bpos *= ikscene->blScale;
1180                 KDL::Frame head(brot, bpos);
1181
1182                 // rest pose length of the bone taking scaling into account
1183                 length = bone->length * ikscene->blScale;
1184                 parent = (a > 0) ? ikscene->channels[tree->parent[a]].tail : root;
1185                 // first the fixed segment to the bone head
1186                 if (!(ikchan->pchan->bone->flag & BONE_CONNECTED) || head.M.GetRot().Norm() > KDL::epsilon) {
1187                         joint = bone->name;
1188                         joint += ":H";
1189                         ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, head);
1190                         parent = joint;
1191                 }
1192                 if (!(ikchan->jointType & IK_TRANSY)) {
1193                         // fixed length, put it in tip
1194                         tip.p[1] = length;
1195                 }
1196                 joint = bone->name;
1197                 weight[0] = (1.0 - pchan->stiffness[0]);
1198                 weight[1] = (1.0 - pchan->stiffness[1]);
1199                 weight[2] = (1.0 - pchan->stiffness[2]);
1200                 switch (ikchan->jointType & ~IK_TRANSY) {
1201                         case 0:
1202                                 // fixed bone
1203                                 joint += ":F";
1204                                 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip);
1205                                 break;
1206                         case IK_XDOF:
1207                                 // RX only, get the X rotation
1208                                 joint += ":RX";
1209                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0], tip);
1210                                 weights.push_back(weight[0]);
1211                                 break;
1212                         case IK_YDOF:
1213                                 // RY only, get the Y rotation
1214                                 joint += ":RY";
1215                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[0], tip);
1216                                 weights.push_back(weight[1]);
1217                                 break;
1218                         case IK_ZDOF:
1219                                 // RZ only, get the Zz rotation
1220                                 joint += ":RZ";
1221                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0], tip);
1222                                 weights.push_back(weight[2]);
1223                                 break;
1224                         case IK_XDOF | IK_YDOF:
1225                                 joint += ":RX";
1226                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0]);
1227                                 weights.push_back(weight[0]);
1228                                 if (ret) {
1229                                         parent = joint;
1230                                         joint = bone->name;
1231                                         joint += ":RY";
1232                                         ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1233                                         weights.push_back(weight[1]);
1234                                 }
1235                                 break;
1236                         case IK_SWING:
1237                                 joint += ":SW";
1238                                 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0], tip);
1239                                 weights.push_back(weight[0]);
1240                                 weights.push_back(weight[2]);
1241                                 break;
1242                         case IK_YDOF | IK_ZDOF:
1243                                 // RZ+RY
1244                                 joint += ":RZ";
1245                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0]);
1246                                 weights.push_back(weight[2]);
1247                                 if (ret) {
1248                                         parent = joint;
1249                                         joint = bone->name;
1250                                         joint += ":RY";
1251                                         ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1252                                         weights.push_back(weight[1]);
1253                                 }
1254                                 break;
1255                         case IK_SWING | IK_YDOF:
1256                                 // decompose in a Swing+RotY joint
1257                                 joint += ":SW";
1258                                 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0]);
1259                                 weights.push_back(weight[0]);
1260                                 weights.push_back(weight[2]);
1261                                 if (ret) {
1262                                         parent = joint;
1263                                         joint = bone->name;
1264                                         joint += ":RY";
1265                                         ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[2], tip);
1266                                         weights.push_back(weight[1]);
1267                                 }
1268                                 break;
1269                         case IK_REVOLUTE:
1270                                 joint += ":SJ";
1271                                 ret = arm->addSegment(joint, parent, KDL::Joint::Sphere, rot[0], tip);
1272                                 weights.push_back(weight[0]);
1273                                 weights.push_back(weight[1]);
1274                                 weights.push_back(weight[2]);
1275                                 break;
1276                 }
1277                 if (ret && (ikchan->jointType & IK_TRANSY)) {
1278                         parent = joint;
1279                         joint = bone->name;
1280                         joint += ":TY";
1281                         ret = arm->addSegment(joint, parent, KDL::Joint::TransY, rot[ikchan->ndof - 1]);
1282                         const float ikstretch = pchan->ikstretch * pchan->ikstretch;
1283                         /* why invert twice here? */
1284                         weight[1] = (1.0 - min_ff(1.0 - ikstretch, 1.0f - 0.001f));
1285                         weights.push_back(weight[1]);
1286                 }
1287                 if (!ret)
1288                         // error making the armature??
1289                         break;
1290                 // joint points to the segment that correspond to the bone per say
1291                 ikchan->tail = joint;
1292                 ikchan->head = parent;
1293                 // in case of error
1294                 ret = false;
1295                 if ((ikchan->jointType & IK_XDOF) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ROTCTL))) {
1296                         joint = bone->name;
1297                         joint += ":RX";
1298                         if (pchan->ikflag & BONE_IK_XLIMIT) {
1299                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0)
1300                                         break;
1301                         }
1302                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1303                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1304                                         break;
1305                         }
1306                 }
1307                 if ((ikchan->jointType & IK_YDOF) && (pchan->ikflag & (BONE_IK_YLIMIT | BONE_IK_ROTCTL))) {
1308                         joint = bone->name;
1309                         joint += ":RY";
1310                         if (pchan->ikflag & BONE_IK_YLIMIT) {
1311                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[1], pchan->limitmax[1]) < 0)
1312                                         break;
1313                         }
1314                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1315                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1316                                         break;
1317                         }
1318                 }
1319                 if ((ikchan->jointType & IK_ZDOF) && (pchan->ikflag & (BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1320                         joint = bone->name;
1321                         joint += ":RZ";
1322                         if (pchan->ikflag & BONE_IK_ZLIMIT) {
1323                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[2], pchan->limitmax[2]) < 0)
1324                                         break;
1325                         }
1326                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1327                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1328                                         break;
1329                         }
1330                 }
1331                 if ((ikchan->jointType & IK_SWING) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1332                         joint = bone->name;
1333                         joint += ":SW";
1334                         if (pchan->ikflag & BONE_IK_XLIMIT) {
1335                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0)
1336                                         break;
1337                         }
1338                         if (pchan->ikflag & BONE_IK_ZLIMIT) {
1339                                 if (arm->addLimitConstraint(joint, 1, pchan->limitmin[2], pchan->limitmax[2]) < 0)
1340                                         break;
1341                         }
1342                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1343                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1344                                         break;
1345                         }
1346                 }
1347                 if ((ikchan->jointType & IK_REVOLUTE) && (pchan->ikflag & BONE_IK_ROTCTL)) {
1348                         joint = bone->name;
1349                         joint += ":SJ";
1350                         if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1351                                 break;
1352                 }
1353                 //  no error, so restore
1354                 ret = true;
1355                 rot += ikchan->ndof;
1356         }
1357         if (!ret) {
1358                 delete ikscene;
1359                 return NULL;
1360         }
1361         // for each target, we need to add an end effector in the armature
1362         for (numtarget = 0, polarcon = NULL, ret = true, target = (PoseTarget *)tree->targets.first; target; target = (PoseTarget *)target->next) {
1363                 condata = (bKinematicConstraint *)target->con->data;
1364                 pchan = tree->pchan[target->tip];
1365
1366                 if (is_cartesian_constraint(target->con)) {
1367                         // add the end effector
1368                         IK_Target *iktarget = new IK_Target();
1369                         ikscene->targets.push_back(iktarget);
1370                         iktarget->ee = arm->addEndEffector(ikscene->channels[target->tip].tail);
1371                         if (iktarget->ee == -1) {
1372                                 ret = false;
1373                                 break;
1374                         }
1375                         // initialize all the fields that we can set at this time
1376                         iktarget->blenderConstraint = target->con;
1377                         iktarget->channel = target->tip;
1378                         iktarget->simulation = (ikparam->flag & ITASC_SIMULATION);
1379                         iktarget->rootChannel = ikscene->channels[0].pchan;
1380                         iktarget->owner = ob;
1381                         iktarget->targetName = pchan->bone->name;
1382                         iktarget->targetName += ":T:";
1383                         iktarget->targetName += target->con->name;
1384                         iktarget->constraintName = pchan->bone->name;
1385                         iktarget->constraintName += ":C:";
1386                         iktarget->constraintName += target->con->name;
1387                         numtarget++;
1388                         if (condata->poletar)
1389                                 // this constraint has a polar target
1390                                 polarcon = target->con;
1391                 }
1392         }
1393         // deal with polar target if any
1394         if (numtarget == 1 && polarcon) {
1395                 ikscene->polarConstraint = polarcon;
1396         }
1397         // we can now add the armature
1398         // the armature is based on a moving frame.
1399         // initialize with the correct position in case there is no cache
1400         base_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, ikscene);
1401         ikscene->base = new iTaSC::MovingFrame(initPose);
1402         ikscene->base->setCallback(base_callback, ikscene);
1403         std::string armname;
1404         armname = ob->id.name;
1405         armname += ":B";
1406         ret = scene->addObject(armname, ikscene->base);
1407         armname = ob->id.name;
1408         armname += ":AR";
1409         if (ret)
1410                 ret = scene->addObject(armname, ikscene->armature, ikscene->base);
1411         if (!ret) {
1412                 delete ikscene;
1413                 return NULL;
1414         }
1415         // set the weight
1416         e_matrix& Wq = arm->getWq();
1417         assert(Wq.cols() == (int)weights.size());
1418         for (int q = 0; q < Wq.cols(); q++)
1419                 Wq(q, q) = weights[q];
1420         // get the inverse rest pose frame of the base to compute relative rest pose of end effectors
1421         // this is needed to handle the enforce parameter
1422         // ikscene->pchan[0] is the root channel of the tree
1423         // if it has no parent, then it's just the identify Frame
1424         float invBaseFrame[4][4];
1425         pchan = ikscene->channels[0].pchan;
1426         if (pchan->parent) {
1427                 // it has a parent, get the pose matrix from it
1428                 float baseFrame[4][4];
1429                 pchan = pchan->parent;
1430                 copy_m4_m4(baseFrame, pchan->bone->arm_mat);
1431                 // move to the tail and scale to get rest pose of armature base
1432                 copy_v3_v3(baseFrame[3], pchan->bone->arm_tail);
1433                 invert_m4_m4(invBaseFrame, baseFrame);
1434         }
1435         else {
1436                 unit_m4(invBaseFrame);
1437         }
1438         // finally add the constraint
1439         for (t = 0; t < ikscene->targets.size(); t++) {
1440                 IK_Target *iktarget = ikscene->targets[t];
1441                 iktarget->blscene = blscene;
1442                 condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
1443                 pchan = tree->pchan[iktarget->channel];
1444                 unsigned int controltype, bonecnt;
1445                 double bonelen;
1446                 float mat[4][4];
1447
1448                 // add the end effector
1449                 // estimate the average bone length, used to clamp feedback error
1450                 for (bonecnt = 0, bonelen = 0.f, a = iktarget->channel; a >= 0; a = tree->parent[a], bonecnt++)
1451                         bonelen += ikscene->blScale * tree->pchan[a]->bone->length;
1452                 bonelen /= bonecnt;
1453
1454                 // store the rest pose of the end effector to compute enforce target
1455                 copy_m4_m4(mat, pchan->bone->arm_mat);
1456                 copy_v3_v3(mat[3], pchan->bone->arm_tail);
1457                 // get the rest pose relative to the armature base
1458                 mul_m4_m4m4(iktarget->eeRest, invBaseFrame, mat);
1459                 iktarget->eeBlend = (!ikscene->polarConstraint && condata->type == CONSTRAINT_IK_COPYPOSE) ? true : false;
1460                 // use target_callback to make sure the initPose includes enforce coefficient
1461                 target_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, iktarget);
1462                 iktarget->target = new iTaSC::MovingFrame(initPose);
1463                 iktarget->target->setCallback(target_callback, iktarget);
1464                 ret = scene->addObject(iktarget->targetName, iktarget->target);
1465                 if (!ret)
1466                         break;
1467
1468                 switch (condata->type) {
1469                         case CONSTRAINT_IK_COPYPOSE:
1470                                 controltype = 0;
1471                                 if (condata->flag & CONSTRAINT_IK_ROT) {
1472                                         if (!(condata->flag & CONSTRAINT_IK_NO_ROT_X))
1473                                                 controltype |= iTaSC::CopyPose::CTL_ROTATIONX;
1474                                         if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Y))
1475                                                 controltype |= iTaSC::CopyPose::CTL_ROTATIONY;
1476                                         if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Z))
1477                                                 controltype |= iTaSC::CopyPose::CTL_ROTATIONZ;
1478                                 }
1479                                 if (condata->flag & CONSTRAINT_IK_POS) {
1480                                         if (!(condata->flag & CONSTRAINT_IK_NO_POS_X))
1481                                                 controltype |= iTaSC::CopyPose::CTL_POSITIONX;
1482                                         if (!(condata->flag & CONSTRAINT_IK_NO_POS_Y))
1483                                                 controltype |= iTaSC::CopyPose::CTL_POSITIONY;
1484                                         if (!(condata->flag & CONSTRAINT_IK_NO_POS_Z))
1485                                                 controltype |= iTaSC::CopyPose::CTL_POSITIONZ;
1486                                 }
1487                                 if (controltype) {
1488                                         iktarget->constraint = new iTaSC::CopyPose(controltype, controltype, bonelen);
1489                                         // set the gain
1490                                         if (controltype & iTaSC::CopyPose::CTL_POSITION)
1491                                                 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_POSITION, iTaSC::ACT_ALPHA, condata->weight);
1492                                         if (controltype & iTaSC::CopyPose::CTL_ROTATION)
1493                                                 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_ROTATION, iTaSC::ACT_ALPHA, condata->orientweight);
1494                                         iktarget->constraint->registerCallback(copypose_callback, iktarget);
1495                                         iktarget->errorCallback = copypose_error;
1496                                         iktarget->controlType = controltype;
1497                                         // add the constraint
1498                                         if (condata->flag & CONSTRAINT_IK_TARGETAXIS)
1499                                                 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, iktarget->targetName, armname, "", ikscene->channels[iktarget->channel].tail);
1500                                         else
1501                                                 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail);
1502                                 }
1503                                 break;
1504                         case CONSTRAINT_IK_DISTANCE:
1505                                 iktarget->constraint = new iTaSC::Distance(bonelen);
1506                                 iktarget->constraint->setControlParameter(iTaSC::Distance::ID_DISTANCE, iTaSC::ACT_VALUE, condata->dist);
1507                                 iktarget->constraint->registerCallback(distance_callback, iktarget);
1508                                 iktarget->errorCallback = distance_error;
1509                                 // we can update the weight on each substep
1510                                 iktarget->constraint->substep(true);
1511                                 // add the constraint
1512                                 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail);
1513                                 break;
1514                 }
1515                 if (!ret)
1516                         break;
1517         }
1518         if (!ret ||
1519             !scene->addCache(ikscene->cache) ||
1520             !scene->addSolver(ikscene->solver) ||
1521             !scene->initialize())
1522         {
1523                 delete ikscene;
1524                 ikscene = NULL;
1525         }
1526         return ikscene;
1527 }
1528
1529 static void create_scene(Scene *scene, Object *ob, float ctime)
1530 {
1531         bPoseChannel *pchan;
1532
1533         // create the IK scene
1534         for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = (bPoseChannel *)pchan->next) {
1535                 // by construction there is only one tree
1536                 PoseTree *tree = (PoseTree *)pchan->iktree.first;
1537                 if (tree) {
1538                         IK_Data *ikdata = get_ikdata(ob->pose);
1539                         // convert tree in iTaSC::Scene
1540                         IK_Scene *ikscene = convert_tree(scene, ob, pchan, ctime);
1541                         if (ikscene) {
1542                                 ikscene->next = ikdata->first;
1543                                 ikdata->first = ikscene;
1544                         }
1545                         // delete the trees once we are done
1546                         while (tree) {
1547                                 BLI_remlink(&pchan->iktree, tree);
1548                                 BLI_freelistN(&tree->targets);
1549                                 if (tree->pchan) MEM_freeN(tree->pchan);
1550                                 if (tree->parent) MEM_freeN(tree->parent);
1551                                 if (tree->basis_change) MEM_freeN(tree->basis_change);
1552                                 MEM_freeN(tree);
1553                                 tree = (PoseTree *)pchan->iktree.first;
1554                         }
1555                 }
1556         }
1557 }
1558
1559 /* returns 1 if scaling has changed and tree must be reinitialized */
1560 static int init_scene(Object *ob)
1561 {
1562         // check also if scaling has changed
1563         float scale = len_v3(ob->obmat[1]);
1564         IK_Scene *scene;
1565
1566         if (ob->pose->ikdata) {
1567                 for (scene = ((IK_Data *)ob->pose->ikdata)->first;
1568                      scene != NULL;
1569                      scene = scene->next)
1570                 {
1571                         if (fabs(scene->blScale - scale) > KDL::epsilon)
1572                                 return 1;
1573                         scene->channels[0].pchan->flag |= POSE_IKTREE;
1574                 }
1575         }
1576         return 0;
1577 }
1578
1579 static void execute_scene(Scene *blscene, IK_Scene *ikscene, bItasc *ikparam, float ctime, float frtime)
1580 {
1581         int i;
1582         IK_Channel *ikchan;
1583         if (ikparam->flag & ITASC_SIMULATION) {
1584                 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ++ikchan) {
1585                         // In simulation mode we don't allow external contraint to change our bones, mark the channel done
1586                         // also tell Blender that this channel is part of IK tree (cleared on each BKE_pose_where_is()
1587                         ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1588                         ikchan->jointValid = 0;
1589                 }
1590         }
1591         else {
1592                 // in animation mode, we must get the bone position from action and constraints
1593                 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ++ikchan) {
1594                         if (!(ikchan->pchan->flag & POSE_DONE))
1595                                 BKE_pose_where_is_bone(blscene, ikscene->blArmature, ikchan->pchan, ctime, 1);
1596                         // tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is()
1597                         ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1598                         ikchan->jointValid = 0;
1599                 }
1600         }
1601         // only run execute the scene if at least one of our target is enabled
1602         for (i = ikscene->targets.size(); i > 0; --i) {
1603                 IK_Target *iktarget = ikscene->targets[i - 1];
1604                 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF))
1605                         break;
1606         }
1607         if (i == 0 && ikscene->armature->getNrOfConstraints() == 0)
1608                 // all constraint disabled
1609                 return;
1610
1611         // compute timestep
1612         double timestamp = ctime * frtime + 2147483.648;
1613         double timestep = frtime;
1614         bool reiterate = (ikparam->flag & ITASC_REITERATION) ? true : false;
1615         int numstep = (ikparam->flag & ITASC_AUTO_STEP) ? 0 : ikparam->numstep;
1616         bool simulation = true;
1617
1618         if (ikparam->flag & ITASC_SIMULATION) {
1619                 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1620         }
1621         else {
1622                 // in animation mode we start from the pose after action and constraint
1623                 convert_pose(ikscene);
1624                 ikscene->armature->setJointArray(ikscene->jointArray);
1625                 // and we don't handle velocity
1626                 reiterate = true;
1627                 simulation = false;
1628                 // time is virtual, so take fixed value for velocity parameters (see itasc_update_param)
1629                 // and choose 1s timestep to allow having velocity parameters in radiant
1630                 timestep = 1.0;
1631                 // use auto setup to let the solver test the variation of the joints
1632                 numstep = 0;
1633         }
1634
1635         if (ikscene->cache && !reiterate && simulation) {
1636                 iTaSC::CacheTS sts, cts;
1637                 sts = cts = (iTaSC::CacheTS)(timestamp * 1000.0 + 0.5);
1638                 if (ikscene->cache->getPreviousCacheItem(ikscene->armature, 0, &cts) == NULL || cts == 0) {
1639                         // the cache is empty before this time, reiterate
1640                         if (ikparam->flag & ITASC_INITIAL_REITERATION)
1641                                 reiterate = true;
1642                 }
1643                 else {
1644                         // can take the cache as a start point.
1645                         sts -= cts;
1646                         timestep = sts / 1000.0;
1647                 }
1648         }
1649         // don't cache if we are reiterating because we don't want to destroy the cache unnecessarily
1650         ikscene->scene->update(timestamp, timestep, numstep, false, !reiterate, simulation);
1651         if (reiterate) {
1652                 // how many times do we reiterate?
1653                 for (i = 0; i < ikparam->numiter; i++) {
1654                         if (ikscene->armature->getMaxJointChange() < ikparam->precision ||
1655                             ikscene->armature->getMaxEndEffectorChange() < ikparam->precision)
1656                         {
1657                                 break;
1658                         }
1659                         ikscene->scene->update(timestamp, timestep, numstep, true, false, simulation);
1660                 }
1661                 if (simulation) {
1662                         // one more fake iteration to cache
1663                         ikscene->scene->update(timestamp, 0.0, 1, true, true, true);
1664                 }
1665         }
1666         // compute constraint error
1667         for (i = ikscene->targets.size(); i > 0; --i) {
1668                 IK_Target *iktarget = ikscene->targets[i - 1];
1669                 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF) && iktarget->constraint) {
1670                         unsigned int nvalues;
1671                         const iTaSC::ConstraintValues *values;
1672                         values = iktarget->constraint->getControlParameters(&nvalues);
1673                         iktarget->errorCallback(values, nvalues, iktarget);
1674                 }
1675         }
1676         // Apply result to bone:
1677         // walk the ikscene->channels
1678         // for each, get the Frame of the joint corresponding to the bone relative to its parent
1679         // combine the parent and the joint frame to get the frame relative to armature
1680         // a backward translation of the bone length gives the head
1681         // if TY, compute the scale as the ratio of the joint length with rest pose length
1682         iTaSC::Armature *arm = ikscene->armature;
1683         KDL::Frame frame;
1684         double q_rest[3], q[3];
1685         const KDL::Joint *joint;
1686         const KDL::Frame *tip;
1687         bPoseChannel *pchan;
1688         float scale;
1689         float length;
1690         float yaxis[3];
1691         for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; ++i, ++ikchan) {
1692                 if (i == 0) {
1693                         if (!arm->getRelativeFrame(frame, ikchan->tail))
1694                                 break;
1695                         // this frame is relative to base, make it relative to object
1696                         ikchan->frame = ikscene->baseFrame * frame;
1697                 }
1698                 else {
1699                         if (!arm->getRelativeFrame(frame, ikchan->tail, ikscene->channels[ikchan->parent].tail))
1700                                 break;
1701                         // combine with parent frame to get frame relative to object
1702                         ikchan->frame = ikscene->channels[ikchan->parent].frame * frame;
1703                 }
1704                 // ikchan->frame is the tail frame relative to object
1705                 // get bone length
1706                 if (!arm->getSegment(ikchan->tail, 3, joint, q_rest[0], q[0], tip))
1707                         break;
1708                 if (joint->getType() == KDL::Joint::TransY) {
1709                         // stretch bones have a TY joint, compute the scale
1710                         scale = (float)(q[0] / q_rest[0]);
1711                         // the length is the joint itself
1712                         length = (float)q[0];
1713                 }
1714                 else {
1715                         scale = 1.0f;
1716                         // for fixed bone, the length is in the tip (always along Y axis)
1717                         length = tip->p(1);
1718                 }
1719                 // ready to compute the pose mat
1720                 pchan = ikchan->pchan;
1721                 // tail mat
1722                 ikchan->frame.getValue(&pchan->pose_mat[0][0]);
1723                 // the scale of the object was included in the ik scene, take it out now
1724                 // because the pose channels are relative to the object
1725                 mul_v3_fl(pchan->pose_mat[3], ikscene->blInvScale);
1726                 length *= ikscene->blInvScale;
1727                 copy_v3_v3(pchan->pose_tail, pchan->pose_mat[3]);
1728                 // shift to head
1729                 copy_v3_v3(yaxis, pchan->pose_mat[1]);
1730                 mul_v3_fl(yaxis, length);
1731                 sub_v3_v3v3(pchan->pose_mat[3], pchan->pose_mat[3], yaxis);
1732                 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
1733                 // add scale
1734                 mul_v3_fl(pchan->pose_mat[0], scale);
1735                 mul_v3_fl(pchan->pose_mat[1], scale);
1736                 mul_v3_fl(pchan->pose_mat[2], scale);
1737         }
1738         if (i < ikscene->numchan) {
1739                 // big problem
1740                 ;
1741         }
1742 }
1743
1744 //---------------------------------------------------
1745 // plugin interface
1746 //
1747 void itasc_initialize_tree(struct Scene *scene, Object *ob, float ctime)
1748 {
1749         bPoseChannel *pchan;
1750         int count = 0;
1751
1752         if (ob->pose->ikdata != NULL && !(ob->pose->flag & POSE_WAS_REBUILT)) {
1753                 if (!init_scene(ob))
1754                         return;
1755         }
1756         // first remove old scene
1757         itasc_clear_data(ob->pose);
1758         // we should handle all the constraint and mark them all disabled
1759         // for blender but we'll start with the IK constraint alone
1760         for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = (bPoseChannel *)pchan->next) {
1761                 if (pchan->constflag & PCHAN_HAS_IK)
1762                         count += initialize_scene(ob, pchan);
1763         }
1764         // if at least one tree, create the scenes from the PoseTree stored in the channels
1765         // postpone until execute_tree: this way the pose constraint are included
1766         if (count)
1767                 create_scene(scene, ob, ctime);
1768         itasc_update_param(ob->pose);
1769         // make sure we don't rebuilt until the user changes something important
1770         ob->pose->flag &= ~POSE_WAS_REBUILT;
1771 }
1772
1773 void itasc_execute_tree(struct Scene *scene, Object *ob,  bPoseChannel *pchan_root, float ctime)
1774 {
1775         if (ob->pose->ikdata) {
1776                 IK_Data *ikdata = (IK_Data *)ob->pose->ikdata;
1777                 bItasc *ikparam = (bItasc *) ob->pose->ikparam;
1778                 // we need default parameters
1779                 if (!ikparam) ikparam = &DefIKParam;
1780
1781                 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1782                         if (ikscene->channels[0].pchan == pchan_root) {
1783                                 float timestep = scene->r.frs_sec_base / scene->r.frs_sec;
1784                                 if (ob->pose->flag & POSE_GAME_ENGINE) {
1785                                         timestep = ob->pose->ctime;
1786                                         // limit the timestep to avoid excessive number of iteration
1787                                         if (timestep > 0.2f)
1788                                                 timestep = 0.2f;
1789                                 }
1790                                 execute_scene(scene, ikscene, ikparam, ctime, timestep);
1791                                 break;
1792                         }
1793                 }
1794         }
1795 }
1796
1797 void itasc_release_tree(struct Scene *scene, struct Object *ob,  float ctime)
1798 {
1799         // not used for iTaSC
1800 }
1801
1802 void itasc_clear_data(struct bPose *pose)
1803 {
1804         if (pose->ikdata) {
1805                 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1806                 for (IK_Scene *scene = ikdata->first; scene; scene = ikdata->first) {
1807                         ikdata->first = scene->next;
1808                         delete scene;
1809                 }
1810                 MEM_freeN(ikdata);
1811                 pose->ikdata = NULL;
1812         }
1813 }
1814
1815 void itasc_clear_cache(struct bPose *pose)
1816 {
1817         if (pose->ikdata) {
1818                 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1819                 for (IK_Scene *scene = ikdata->first; scene; scene = scene->next) {
1820                         if (scene->cache)
1821                                 // clear all cache but leaving the timestamp 0 (=rest pose)
1822                                 scene->cache->clearCacheFrom(NULL, 1);
1823                 }
1824         }
1825 }
1826
1827 void itasc_update_param(struct bPose *pose)
1828 {
1829         if (pose->ikdata && pose->ikparam) {
1830                 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1831                 bItasc *ikparam = (bItasc *)pose->ikparam;
1832                 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1833                         double armlength = ikscene->armature->getArmLength();
1834                         ikscene->solver->setParam(iTaSC::Solver::DLS_LAMBDA_MAX, ikparam->dampmax * armlength);
1835                         ikscene->solver->setParam(iTaSC::Solver::DLS_EPSILON, ikparam->dampeps * armlength);
1836                         if (ikparam->flag & ITASC_SIMULATION) {
1837                                 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, ikparam->minstep);
1838                                 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, ikparam->maxstep);
1839                                 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1840                                 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, ikparam->feedback);
1841                         }
1842                         else {
1843                                 // in animation mode timestep is 1s by convention =>
1844                                 // qmax becomes radiant and feedback becomes fraction of error gap corrected in one iteration
1845                                 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, 1.0);
1846                                 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, 1.0);
1847                                 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, 0.52);
1848                                 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, 0.8);
1849                         }
1850                 }
1851         }
1852 }
1853
1854 void itasc_test_constraint(struct Object *ob, struct bConstraint *cons)
1855 {
1856         struct bKinematicConstraint *data = (struct bKinematicConstraint *)cons->data;
1857
1858         /* only for IK constraint */
1859         if (cons->type != CONSTRAINT_TYPE_KINEMATIC || data == NULL)
1860                 return;
1861
1862         switch (data->type) {
1863                 case CONSTRAINT_IK_COPYPOSE:
1864                 case CONSTRAINT_IK_DISTANCE:
1865                         /* cartesian space constraint */
1866                         break;
1867         }
1868 }