2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Original author: Benoit Bolsee
26 * ***** END GPL LICENSE BLOCK *****
29 /** \file blender/ikplugin/intern/itasc_plugin.cpp
39 #include "Armature.hpp"
40 #include "MovingFrame.hpp"
41 #include "CopyPose.hpp"
42 #include "WSDLSSolver.hpp"
43 #include "WDLSSolver.hpp"
46 #include "Distance.hpp"
49 #include "MEM_guardedalloc.h"
53 #include "BLI_blenlib.h"
55 #include "BLI_utildefines.h"
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"
68 #include "itasc_plugin.h"
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
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
83 struct IK_Scene *first;
86 typedef float Vector3[3];
87 typedef float Vector4[4];
89 typedef void (*ErrorCallback)(const iTaSC::ConstraintValues *values, unsigned int nvalues, IK_Target *iktarget);
91 // one structure for each target in the scene
94 struct Scene *blscene;
95 iTaSC::MovingFrame* target;
96 iTaSC::ConstraintSet* constraint;
97 struct bConstraint* blenderConstraint;
98 struct bPoseChannel* rootChannel;
99 Object* owner; //for auto IK
100 ErrorCallback errorCallback;
101 std::string targetName;
102 std::string constraintName;
103 unsigned short controlType;
104 short channel; //index in IK channel array of channel on which this target is defined
105 short ee; //end effector number
106 bool simulation; //true when simulation mode is used (update feedback)
107 bool eeBlend; //end effector affected by enforce blending
108 float eeRest[4][4]; //end effector initial pose relative to armature
114 blenderConstraint = NULL;
122 targetName.reserve(32);
123 constraintName.reserve(32);
134 bPoseChannel* pchan; // channel where we must copy matrix back
135 KDL::Frame frame; // frame of the bone relative to object base, not armature base
136 std::string tail; // segment name of the joint from which we get the bone tail
137 std::string head; // segment name of the joint from which we get the bone head
138 int parent; // index in this array of the parent channel
139 short jointType; // type of joint, combination of IK_SegmentFlag
140 char ndof; // number of joint angles for this channel
141 char jointValid; // set to 1 when jointValue has been computed
142 // for joint constraint
143 Object* owner; // for pose and IK param
144 double jointValue[4]; // computed joint value
161 struct Scene *blscene;
163 int numchan; // number of channel in pchan
164 int numjoint; // number of joint in jointArray
165 // array of bone information, one per channel in the tree
166 IK_Channel* channels;
167 iTaSC::Armature* armature;
170 iTaSC::MovingFrame* base; // armature base object
171 KDL::Frame baseFrame; // frame of armature base relative to blArmature
172 KDL::JntArray jointArray; // buffer for storing temporary joint array
173 iTaSC::Solver* solver;
175 float blScale; // scale of the Armature object (assume uniform scaling)
176 float blInvScale; // inverse of Armature object scale
177 struct bConstraint* polarConstraint;
178 std::vector<IK_Target*> targets;
189 blScale = blInvScale = 1.0f;
193 polarConstraint = NULL;
197 // delete scene first
200 for (std::vector<IK_Target *>::iterator it = targets.begin(); it != targets.end(); ++it)
217 // type of IK joint, can be combined to list the joints corresponding to a bone
218 enum IK_SegmentFlag {
227 enum IK_SegmentAxis {
236 static int initialize_chain(Object *ob, bPoseChannel *pchan_tip, bConstraint *con)
238 bPoseChannel *curchan, *pchan_root = NULL, *chanlist[256], **oldchan;
241 bKinematicConstraint *data;
242 int a, t, segcount = 0, size, newsize, *oldparent, parent, rootbone, treecount;
244 data = (bKinematicConstraint *)con->data;
246 /* exclude tip from chain? */
247 if (!(data->flag & CONSTRAINT_IK_TIP))
248 pchan_tip = pchan_tip->parent;
250 rootbone = data->rootbone;
251 /* Find the chain's root & count the segments needed */
252 for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
253 pchan_root = curchan;
255 if (++segcount > 255) // 255 is weak
258 if (segcount == rootbone) {
259 // reached this end of the chain but if the chain is overlapping with a
260 // previous one, we must go back up to the root of the other chain
261 if ((curchan->flag & POSE_CHAIN) && BLI_listbase_is_empty(&curchan->iktree)) {
268 if (BLI_listbase_is_empty(&curchan->iktree) == false)
269 // Oh oh, there is already a chain starting from this channel and our chain is longer...
270 // Should handle this by moving the previous chain up to the beginning of our chain
271 // For now we just stop here
274 if (!segcount) return 0;
275 // we reached a limit and still not the end of a previous chain, quit
276 if ((pchan_root->flag & POSE_CHAIN) && BLI_listbase_is_empty(&pchan_root->iktree)) return 0;
278 // now that we know how many segment we have, set the flag
279 for (rootbone = segcount, segcount = 0, curchan = pchan_tip; segcount < rootbone; segcount++, curchan = curchan->parent) {
280 chanlist[segcount] = curchan;
281 curchan->flag |= POSE_CHAIN;
284 /* setup the chain data */
285 /* create a target */
286 target = (PoseTarget *)MEM_callocN(sizeof(PoseTarget), "posetarget");
288 // by contruction there can be only one tree per channel and each channel can be part of at most one tree.
289 tree = (PoseTree *)pchan_root->iktree.first;
293 tree = (PoseTree *)MEM_callocN(sizeof(PoseTree), "posetree");
295 tree->iterations = data->iterations;
296 tree->totchannel = segcount;
297 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
299 tree->pchan = (bPoseChannel **)MEM_callocN(segcount * sizeof(void *), "ik tree pchan");
300 tree->parent = (int *)MEM_callocN(segcount * sizeof(int), "ik tree parent");
301 for (a = 0; a < segcount; a++) {
302 tree->pchan[a] = chanlist[segcount - a - 1];
303 tree->parent[a] = a - 1;
305 target->tip = segcount - 1;
307 /* AND! link the tree to the root */
308 BLI_addtail(&pchan_root->iktree, tree);
313 tree->iterations = MAX2(data->iterations, tree->iterations);
314 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
316 /* skip common pose channels and add remaining*/
317 size = MIN2(segcount, tree->totchannel);
319 while (a < size && t < tree->totchannel) {
320 // locate first matching channel
321 for (; t < tree->totchannel && tree->pchan[t] != chanlist[segcount - a - 1]; t++) ;
322 if (t >= tree->totchannel)
324 for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1]; a++, t++) ;
327 segcount = segcount - a;
328 target->tip = tree->totchannel + segcount - 1;
331 for (parent = a - 1; parent < tree->totchannel; parent++)
332 if (tree->pchan[parent] == chanlist[segcount - 1]->parent)
335 /* shouldn't happen, but could with dependency cycles */
336 if (parent == tree->totchannel)
340 newsize = tree->totchannel + segcount;
341 oldchan = tree->pchan;
342 oldparent = tree->parent;
344 tree->pchan = (bPoseChannel **)MEM_callocN(newsize * sizeof(void *), "ik tree pchan");
345 tree->parent = (int *)MEM_callocN(newsize * sizeof(int), "ik tree parent");
346 memcpy(tree->pchan, oldchan, sizeof(void *) * tree->totchannel);
347 memcpy(tree->parent, oldparent, sizeof(int) * tree->totchannel);
349 MEM_freeN(oldparent);
351 /* add new pose channels at the end, in reverse order */
352 for (a = 0; a < segcount; a++) {
353 tree->pchan[tree->totchannel + a] = chanlist[segcount - a - 1];
354 tree->parent[tree->totchannel + a] = tree->totchannel + a - 1;
356 tree->parent[tree->totchannel] = parent;
358 tree->totchannel = newsize;
364 /* add target to the tree */
365 BLI_addtail(&tree->targets, target);
366 /* mark root channel having an IK tree */
367 pchan_root->flag |= POSE_IKTREE;
371 static bool is_cartesian_constraint(bConstraint *con)
373 //bKinematicConstraint* data=(bKinematicConstraint *)con->data;
378 static bool constraint_valid(bConstraint *con)
380 bKinematicConstraint *data = (bKinematicConstraint *)con->data;
382 if (data->flag & CONSTRAINT_IK_AUTO)
384 if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF))
386 if (is_cartesian_constraint(con)) {
387 /* cartesian space constraint */
388 if (data->tar == NULL)
390 if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)
396 static int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
401 /* find all IK constraints and validate them */
403 for (con = (bConstraint *)pchan_tip->constraints.first; con; con = (bConstraint *)con->next) {
404 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
405 if (constraint_valid(con))
406 treecount += initialize_chain(ob, pchan_tip, con);
412 static IK_Data *get_ikdata(bPose *pose)
415 return (IK_Data *)pose->ikdata;
416 pose->ikdata = MEM_callocN(sizeof(IK_Data), "iTaSC ikdata");
417 // here init ikdata if needed
418 // now that we have scene, make sure the default param are initialized
419 if (!DefIKParam.iksolver)
420 BKE_pose_itasc_init(&DefIKParam);
422 return (IK_Data *)pose->ikdata;
424 static double EulerAngleFromMatrix(const KDL::Rotation& R, int axis)
426 double t = KDL::sqrt(R(0, 0) * R(0, 0) + R(0, 1) * R(0, 1));
428 if (t > 16.0 * KDL::epsilon) {
429 if (axis == 0) return -KDL::atan2(R(1, 2), R(2, 2));
430 else if (axis == 1) return KDL::atan2(-R(0, 2), t);
431 else return -KDL::atan2(R(0, 1), R(0, 0));
434 if (axis == 0) return -KDL::atan2(-R(2, 1), R(1, 1));
435 else if (axis == 1) return KDL::atan2(-R(0, 2), t);
440 static double ComputeTwist(const KDL::Rotation& R)
442 // qy and qw are the y and w components of the quaternion from R
443 double qy = R(0, 2) - R(2, 0);
444 double qw = R(0, 0) + R(1, 1) + R(2, 2) + 1;
446 double tau = 2 * KDL::atan2(qy, qw);
451 static void RemoveEulerAngleFromMatrix(KDL::Rotation& R, double angle, int axis)
453 // compute twist parameter
457 T = KDL::Rotation::RotX(-angle);
460 T = KDL::Rotation::RotY(-angle);
463 T = KDL::Rotation::RotZ(-angle);
473 static void GetEulerXZY(const KDL::Rotation& R, double& X, double& Z, double& Y)
475 if (fabs(R(0, 1)) > 1.0 - KDL::epsilon) {
476 X = -KDL::sign(R(0, 1)) * KDL::atan2(R(1, 2), R(1, 0));
477 Z = -KDL::sign(R(0, 1)) * KDL::PI / 2;
481 X = KDL::atan2(R(2, 1), R(1, 1));
482 Z = KDL::atan2(-R(0, 1), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 2))));
483 Y = KDL::atan2(R(0, 2), R(0, 0));
487 static void GetEulerXYZ(const KDL::Rotation& R, double& X, double& Y, double& Z)
489 if (fabs(R(0, 2)) > 1.0 - KDL::epsilon) {
490 X = KDL::sign(R(0, 2)) * KDL::atan2(-R(1, 0), R(1, 1));
491 Y = KDL::sign(R(0, 2)) * KDL::PI / 2;
495 X = KDL::atan2(-R(1, 2), R(2, 2));
496 Y = KDL::atan2(R(0, 2), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 1))));
497 Z = KDL::atan2(-R(0, 1), R(0, 0));
502 static void GetJointRotation(KDL::Rotation& boneRot, int type, double *rot)
504 switch (type & ~IK_TRANSY) {
506 // fixed bone, no joint
509 // RX only, get the X rotation
510 rot[0] = EulerAngleFromMatrix(boneRot, 0);
513 // RY only, get the Y rotation
514 rot[0] = ComputeTwist(boneRot);
517 // RZ only, get the Z rotation
518 rot[0] = EulerAngleFromMatrix(boneRot, 2);
520 case IK_XDOF | IK_YDOF:
521 rot[1] = ComputeTwist(boneRot);
522 RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
523 rot[0] = EulerAngleFromMatrix(boneRot, 0);
527 boneRot.GetXZRot().GetValue(rot);
529 case IK_YDOF | IK_ZDOF:
531 rot[1] = ComputeTwist(boneRot);
532 RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
533 rot[0] = EulerAngleFromMatrix(boneRot, 2);
535 case IK_SWING | IK_YDOF:
536 rot[2] = ComputeTwist(boneRot);
537 RemoveEulerAngleFromMatrix(boneRot, rot[2], 1);
538 boneRot.GetXZRot().GetValue(rot);
541 boneRot.GetRot().GetValue(rot);
546 static bool target_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param)
548 IK_Target *target = (IK_Target *)param;
549 // compute next target position
550 // get target matrix from constraint.
551 bConstraint *constraint = (bConstraint *)target->blenderConstraint;
554 BKE_constraint_target_matrix_get(target->blscene, constraint, 0, CONSTRAINT_OBTYPE_OBJECT, target->owner, tarmat, 1.0);
556 // rootmat contains the target pose in world coordinate
557 // if enforce is != 1.0, blend the target position with the end effector position
558 // if the armature was in rest position. This information is available in eeRest
559 if (constraint->enforce != 1.0f && target->eeBlend) {
560 // eeRest is relative to the reference frame of the IK root
561 // get this frame in world reference
563 bPoseChannel *pchan = target->rootChannel;
565 pchan = pchan->parent;
567 copy_m4_m4(chanmat, pchan->pose_mat);
568 copy_v3_v3(chanmat[3], pchan->pose_tail);
569 mul_m4_series(restmat, target->owner->obmat, chanmat, target->eeRest);
572 mul_m4_m4m4(restmat, target->owner->obmat, target->eeRest);
575 blend_m4_m4m4(tarmat, restmat, tarmat, constraint->enforce);
577 next.setValue(&tarmat[0][0]);
581 static bool base_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param)
583 IK_Scene *ikscene = (IK_Scene *)param;
584 // compute next armature base pose
586 // ikscene->pchan[0] is the root channel of the tree
587 // if it has a parent, get the pose matrix from it and replace [3] by parent pchan->tail
588 // then multiply by the armature matrix to get ikscene->armature base position
589 bPoseChannel *pchan = ikscene->channels[0].pchan;
592 pchan = pchan->parent;
594 copy_m4_m4(chanmat, pchan->pose_mat);
595 copy_v3_v3(chanmat[3], pchan->pose_tail);
596 // save the base as a frame too so that we can compute deformation after simulation
597 ikscene->baseFrame.setValue(&chanmat[0][0]);
598 // iTaSC armature is scaled to object scale, scale the base frame too
599 ikscene->baseFrame.p *= ikscene->blScale;
600 mul_m4_m4m4(rootmat, ikscene->blArmature->obmat, chanmat);
603 copy_m4_m4(rootmat, ikscene->blArmature->obmat);
604 ikscene->baseFrame = iTaSC::F_identity;
606 next.setValue(&rootmat[0][0]);
607 // if there is a polar target (only during solving otherwise we don't have end efffector)
608 if (ikscene->polarConstraint && timestamp.update) {
609 // compute additional rotation of base frame so that armature follows the polar target
610 float imat[4][4]; // IK tree base inverse matrix
611 float polemat[4][4]; // polar target in IK tree base frame
612 float goalmat[4][4]; // target in IK tree base frame
613 float mat[4][4]; // temp matrix
614 bKinematicConstraint *poledata = (bKinematicConstraint *)ikscene->polarConstraint->data;
616 invert_m4_m4(imat, rootmat);
617 // polar constraint imply only one target
618 IK_Target *iktarget = ikscene->targets[0];
619 // root channel from which we take the bone initial orientation
620 IK_Channel &rootchan = ikscene->channels[0];
622 // get polar target matrix in world space
623 BKE_constraint_target_matrix_get(ikscene->blscene, ikscene->polarConstraint, 1, CONSTRAINT_OBTYPE_OBJECT, ikscene->blArmature, mat, 1.0);
624 // convert to armature space
625 mul_m4_m4m4(polemat, imat, mat);
626 // get the target in world space (was computed before as target object are defined before base object)
627 iktarget->target->getPose().getValue(mat[0]);
628 // convert to armature space
629 mul_m4_m4m4(goalmat, imat, mat);
630 // take position of target, polar target, end effector, in armature space
631 KDL::Vector goalpos(goalmat[3]);
632 KDL::Vector polepos(polemat[3]);
633 KDL::Vector endpos = ikscene->armature->getPose(iktarget->ee).p;
634 // get root bone orientation
635 KDL::Frame rootframe;
636 ikscene->armature->getRelativeFrame(rootframe, rootchan.tail);
637 KDL::Vector rootx = rootframe.M.UnitX();
638 KDL::Vector rootz = rootframe.M.UnitZ();
639 // and compute root bone head
640 double q_rest[3], q[3], length;
641 const KDL::Joint *joint;
642 const KDL::Frame *tip;
643 ikscene->armature->getSegment(rootchan.tail, 3, joint, q_rest[0], q[0], tip);
644 length = (joint->getType() == KDL::Joint::TransY) ? q[0] : tip->p(1);
645 KDL::Vector rootpos = rootframe.p - length *rootframe.M.UnitY();
647 // compute main directions
648 KDL::Vector dir = KDL::Normalize(endpos - rootpos);
649 KDL::Vector poledir = KDL::Normalize(goalpos - rootpos);
650 // compute up directions
651 KDL::Vector poleup = KDL::Normalize(polepos - rootpos);
652 KDL::Vector up = rootx * KDL::cos(poledata->poleangle) + rootz *KDL::sin(poledata->poleangle);
653 // from which we build rotation matrix
654 KDL::Rotation endrot, polerot;
655 // for the armature, using the root bone orientation
656 KDL::Vector x = KDL::Normalize(dir * up);
658 endrot.UnitY(KDL::Normalize(x * dir));
660 // for the polar target
661 x = KDL::Normalize(poledir * poleup);
663 polerot.UnitY(KDL::Normalize(x * poledir));
664 polerot.UnitZ(-poledir);
665 // the difference between the two is the rotation we want to apply
666 KDL::Rotation result(polerot * endrot.Inverse());
667 // apply on base frame as this is an artificial additional rotation
668 next.M = next.M * result;
669 ikscene->baseFrame.M = ikscene->baseFrame.M * result;
674 static bool copypose_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
676 IK_Target *iktarget = (IK_Target *)_param;
677 bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
678 iTaSC::ConstraintValues *values = _values;
679 bItasc *ikparam = (bItasc *) iktarget->owner->pose->ikparam;
681 // we need default parameters
683 ikparam = &DefIKParam;
685 if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
686 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
688 values->action = iTaSC::ACT_ALPHA;
691 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
693 values->action = iTaSC::ACT_ALPHA;
698 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
700 values->alpha = condata->weight;
701 values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
702 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
705 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
707 values->alpha = condata->orientweight;
708 values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
709 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
716 static void copypose_error(const iTaSC::ConstraintValues *values, unsigned int nvalues, IK_Target *iktarget)
718 iTaSC::ConstraintSingleValue *value;
722 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
724 for (i = 0, error = 0.0, value = values->values; i < values->number; ++i, ++value)
725 error += KDL::sqr(value->y - value->yd);
726 iktarget->blenderConstraint->lin_error = (float)KDL::sqrt(error);
729 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
731 for (i = 0, error = 0.0, value = values->values; i < values->number; ++i, ++value)
732 error += KDL::sqr(value->y - value->yd);
733 iktarget->blenderConstraint->rot_error = (float)KDL::sqrt(error);
738 static bool distance_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
740 IK_Target *iktarget = (IK_Target *)_param;
741 bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
742 iTaSC::ConstraintValues *values = _values;
743 bItasc *ikparam = (bItasc *) iktarget->owner->pose->ikparam;
744 // we need default parameters
746 ikparam = &DefIKParam;
748 // update weight according to mode
749 if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
753 switch (condata->mode) {
754 case LIMITDIST_INSIDE:
755 values->alpha = (values->values[0].y > condata->dist) ? condata->weight : 0.0;
757 case LIMITDIST_OUTSIDE:
758 values->alpha = (values->values[0].y < condata->dist) ? condata->weight : 0.0;
761 values->alpha = condata->weight;
764 if (!timestamp.substep) {
765 // only update value on first timestep
766 switch (condata->mode) {
767 case LIMITDIST_INSIDE:
768 values->values[0].yd = condata->dist * 0.95;
770 case LIMITDIST_OUTSIDE:
771 values->values[0].yd = condata->dist * 1.05;
774 values->values[0].yd = condata->dist;
777 values->values[0].action = iTaSC::ACT_VALUE | iTaSC::ACT_FEEDBACK;
778 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
781 values->action |= iTaSC::ACT_ALPHA;
785 static void distance_error(const iTaSC::ConstraintValues *values, unsigned int _nvalues, IK_Target *iktarget)
787 iktarget->blenderConstraint->lin_error = (float)(values->values[0].y - values->values[0].yd);
790 static bool joint_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
792 IK_Channel *ikchan = (IK_Channel *)_param;
793 bItasc *ikparam = (bItasc *)ikchan->owner->pose->ikparam;
794 bPoseChannel *chan = ikchan->pchan;
797 // a channel can be splitted into multiple joints, so we get called multiple
798 // times for one channel (this callback is only for 1 joint in the armature)
799 // the IK_JointTarget structure is shared between multiple joint constraint
800 // and the target joint values is computed only once, remember this in jointValid
801 // Don't forget to reset it before each frame
802 if (!ikchan->jointValid) {
805 if (chan->rotmode > 0) {
806 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
807 eulO_to_mat3(rmat, chan->eul, chan->rotmode);
809 else if (chan->rotmode == ROT_MODE_AXISANGLE) {
810 /* axis-angle - stored in quaternion data, but not really that great for 3D-changing orientations */
811 axis_angle_to_mat3(rmat, &chan->quat[1], chan->quat[0]);
814 /* quats are normalized before use to eliminate scaling issues */
815 normalize_qt(chan->quat);
816 quat_to_mat3(rmat, chan->quat);
818 KDL::Rotation jointRot(
819 rmat[0][0], rmat[1][0], rmat[2][0],
820 rmat[0][1], rmat[1][1], rmat[2][1],
821 rmat[0][2], rmat[1][2], rmat[2][2]);
822 GetJointRotation(jointRot, ikchan->jointType, ikchan->jointValue);
823 ikchan->jointValid = 1;
825 // determine which part of jointValue is used for this joint
826 // closely related to the way the joints are defined
827 switch (ikchan->jointType & ~IK_TRANSY) {
833 case IK_XDOF | IK_YDOF:
835 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RX) ? 0 : 1;
841 case IK_YDOF | IK_ZDOF:
843 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RZ) ? 0 : 1;
845 case IK_SWING | IK_YDOF:
847 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RY) ? 2 : 0;
857 for (unsigned int i = 0; i < _nvalues; i++, dof++) {
858 _values[i].values[0].yd = ikchan->jointValue[dof];
859 _values[i].alpha = chan->ikrotweight;
860 _values[i].feedback = ikparam->feedback;
866 // build array of joint corresponding to IK chain
867 static int convert_channels(IK_Scene *ikscene, PoseTree *tree, float ctime)
874 for (a = 0, ikchan = ikscene->channels; a < ikscene->numchan; ++a, ++ikchan) {
875 pchan = tree->pchan[a];
876 ikchan->pchan = pchan;
877 ikchan->parent = (a > 0) ? tree->parent[a] : -1;
878 ikchan->owner = ikscene->blArmature;
880 // the constraint and channels must be applied before we build the iTaSC scene,
881 // this is because some of the pose data (e.g. pose head) don't have corresponding
882 // joint angles and can't be applied to the iTaSC armature dynamically
883 if (!(pchan->flag & POSE_DONE))
884 BKE_pose_where_is_bone(ikscene->blscene, ikscene->blArmature, pchan, ctime, 1);
885 // tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is()
886 pchan->flag |= (POSE_DONE | POSE_CHAIN);
890 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP) &&
891 (!(pchan->ikflag & BONE_IK_XLIMIT) || pchan->limitmin[0] < 0.f || pchan->limitmax[0] > 0.f))
895 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP) &&
896 (!(pchan->ikflag & BONE_IK_YLIMIT) || pchan->limitmin[1] < 0.f || pchan->limitmax[1] > 0.f))
900 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP) &&
901 (!(pchan->ikflag & BONE_IK_ZLIMIT) || pchan->limitmin[2] < 0.f || pchan->limitmax[2] > 0.f))
906 if (tree->stretch && (pchan->ikstretch > 0.0)) {
910 * Logic to create the segments:
911 * RX,RY,RZ = rotational joints with no length
912 * RY(tip) = rotational joints with a fixed length arm = (0,length,0)
913 * TY = translational joint on Y axis
914 * F(pos) = fixed joint with an arm at position pos
915 * Conversion rule of the above flags:
923 * XYZ ==> full spherical unless there are limits, in which case RX+RZ+RY(tip)
924 * In case of stretch, tip=(0,0,0) and there is an additional TY joint
925 * The frame at last of these joints represents the tail of the bone.
926 * The head is computed by a reverse translation on Y axis of the bone length
927 * or in case of TY joint, by the frame at previous joint.
928 * In case of separation of bones, there is an additional F(head) joint
930 * Computing rest pose and length is complicated: the solver works in world space
932 * rest position is computed only from bone->bone_mat.
933 * bone length is computed from bone->length multiplied by the scaling factor of
934 * the armature. Non-uniform scaling will give bad result!
936 switch (flag & (IK_XDOF | IK_YDOF | IK_ZDOF)) {
938 ikchan->jointType = 0;
942 // RX only, get the X rotation
943 ikchan->jointType = IK_XDOF;
947 // RY only, get the Y rotation
948 ikchan->jointType = IK_YDOF;
952 // RZ only, get the Zz rotation
953 ikchan->jointType = IK_ZDOF;
956 case IK_XDOF | IK_YDOF:
957 ikchan->jointType = IK_XDOF | IK_YDOF;
960 case IK_XDOF | IK_ZDOF:
962 ikchan->jointType = IK_SWING;
965 case IK_YDOF | IK_ZDOF:
967 ikchan->jointType = IK_ZDOF | IK_YDOF;
970 case IK_XDOF | IK_YDOF | IK_ZDOF:
972 if (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_YLIMIT | BONE_IK_ZLIMIT))
973 // decompose in a Swing+RotY joint
974 ikchan->jointType = IK_SWING | IK_YDOF;
976 ikchan->jointType = IK_REVOLUTE;
980 if (flag & IK_TRANSY) {
981 ikchan->jointType |= IK_TRANSY;
984 njoint += ikchan->ndof;
986 // njoint is the joint coordinate, create the Joint Array
987 ikscene->jointArray.resize(njoint);
988 ikscene->numjoint = njoint;
992 // compute array of joint value corresponding to current pose
993 static void convert_pose(IK_Scene *ikscene)
995 KDL::Rotation boneRot;
999 float rmat[4][4]; // rest pose of bone with parent taken into account
1000 float bmat[4][4]; // difference
1005 // assume uniform scaling and take Y scale as general scale for the armature
1006 scale = len_v3(ikscene->blArmature->obmat[1]);
1007 rot = ikscene->jointArray(0);
1008 for (joint = a = 0, ikchan = ikscene->channels; a < ikscene->numchan && joint < ikscene->numjoint; ++a, ++ikchan) {
1009 pchan = ikchan->pchan;
1012 if (pchan->parent) {
1014 mul_m4_m4m3(bmat, pchan->parent->pose_mat, bone->bone_mat);
1017 copy_m4_m4(bmat, bone->arm_mat);
1019 invert_m4_m4(rmat, bmat);
1020 mul_m4_m4m4(bmat, rmat, pchan->pose_mat);
1022 boneRot.setValue(bmat[0]);
1023 GetJointRotation(boneRot, ikchan->jointType, rot);
1024 if (ikchan->jointType & IK_TRANSY) {
1025 // compute actual length
1026 rot[ikchan->ndof - 1] = len_v3v3(pchan->pose_tail, pchan->pose_head) * scale;
1028 rot += ikchan->ndof;
1029 joint += ikchan->ndof;
1033 // compute array of joint value corresponding to current pose
1034 static void BKE_pose_rest(IK_Scene *ikscene)
1036 bPoseChannel *pchan;
1043 // assume uniform scaling and take Y scale as general scale for the armature
1044 scale = len_v3(ikscene->blArmature->obmat[1]);
1046 SetToZero(ikscene->jointArray);
1047 // except for transY joints
1048 rot = ikscene->jointArray(0);
1049 for (joint = a = 0, ikchan = ikscene->channels; a < ikscene->numchan && joint < ikscene->numjoint; ++a, ++ikchan) {
1050 pchan = ikchan->pchan;
1053 if (ikchan->jointType & IK_TRANSY)
1054 rot[ikchan->ndof - 1] = bone->length * scale;
1055 rot += ikchan->ndof;
1056 joint += ikchan->ndof;
1060 static IK_Scene *convert_tree(Scene *blscene, Object *ob, bPoseChannel *pchan, float ctime)
1062 PoseTree *tree = (PoseTree *)pchan->iktree.first;
1064 bKinematicConstraint *condata;
1065 bConstraint *polarcon;
1067 iTaSC::Armature *arm;
1068 iTaSC::Scene *scene;
1071 KDL::Frame initPose;
1072 KDL::Rotation boneRot;
1077 bool ret = true, ingame;
1081 if (tree->totchannel == 0)
1084 ikscene = new IK_Scene;
1085 ikscene->blscene = blscene;
1086 arm = new iTaSC::Armature();
1087 scene = new iTaSC::Scene();
1088 ikscene->channels = new IK_Channel[tree->totchannel];
1089 ikscene->numchan = tree->totchannel;
1090 ikscene->armature = arm;
1091 ikscene->scene = scene;
1092 ikparam = (bItasc *)ob->pose->ikparam;
1093 ingame = (ob->pose->flag & POSE_GAME_ENGINE);
1095 // you must have our own copy
1096 ikparam = &DefIKParam;
1099 // tweak the param when in game to have efficient stepping
1100 // using fixed substep is not effecient since frames in the GE are often
1101 // shorter than in animation => move to auto step automatically and set
1102 // the target substep duration via min/max
1103 if (!(ikparam->flag & ITASC_AUTO_STEP)) {
1104 float timestep = blscene->r.frs_sec_base / blscene->r.frs_sec;
1105 if (ikparam->numstep > 0)
1106 timestep /= ikparam->numstep;
1107 // with equal min and max, the algorythm will take this step and the indicative substep most of the time
1108 ikparam->minstep = ikparam->maxstep = timestep;
1109 ikparam->flag |= ITASC_AUTO_STEP;
1112 if ((ikparam->flag & ITASC_SIMULATION) && !ingame)
1113 // no cache in animation mode
1114 ikscene->cache = new iTaSC::Cache();
1116 switch (ikparam->solver) {
1117 case ITASC_SOLVER_SDLS:
1118 ikscene->solver = new iTaSC::WSDLSSolver();
1120 case ITASC_SOLVER_DLS:
1121 ikscene->solver = new iTaSC::WDLSSolver();
1127 ikscene->blArmature = ob;
1128 // assume uniform scaling and take Y scale as general scale for the armature
1129 ikscene->blScale = len_v3(ob->obmat[1]);
1130 ikscene->blInvScale = (ikscene->blScale < KDL::epsilon) ? 0.0f : 1.0f / ikscene->blScale;
1133 std::string root("root");
1135 std::vector<double> weights;
1137 // build the array of joints corresponding to the IK chain
1138 convert_channels(ikscene, tree, ctime);
1140 // in the GE, set the initial joint angle to match the current pose
1141 // this will update the jointArray in ikscene
1142 convert_pose(ikscene);
1145 // in Blender, the rest pose is always 0 for joints
1146 BKE_pose_rest(ikscene);
1148 rot = ikscene->jointArray(0);
1150 for (a = 0, ikchan = ikscene->channels; a < tree->totchannel; ++a, ++ikchan) {
1151 pchan = ikchan->pchan;
1154 KDL::Frame tip(iTaSC::F_identity);
1155 // compute the position and rotation of the head from previous segment
1156 Vector3 *fl = bone->bone_mat;
1158 fl[0][0], fl[1][0], fl[2][0],
1159 fl[0][1], fl[1][1], fl[2][1],
1160 fl[0][2], fl[1][2], fl[2][2]);
1161 // if the bone is disconnected, the head is movable in pose mode
1162 // take that into account by using pose matrix instead of bone
1163 // Note that pose is expressed in armature space, convert to previous bone space
1165 float R_parmat[3][3];
1166 float iR_parmat[3][3];
1168 copy_m3_m4(R_parmat, pchan->parent->pose_mat);
1172 sub_v3_v3v3(start, pchan->pose_head, pchan->parent->pose_tail);
1174 start[0] = start[1] = start[2] = 0.0f;
1175 invert_m3_m3(iR_parmat, R_parmat);
1176 normalize_m3(iR_parmat);
1177 mul_m3_v3(iR_parmat, start);
1179 KDL::Vector bpos(start[0], start[1], start[2]);
1180 bpos *= ikscene->blScale;
1181 KDL::Frame head(brot, bpos);
1183 // rest pose length of the bone taking scaling into account
1184 length = bone->length * ikscene->blScale;
1185 parent = (a > 0) ? ikscene->channels[tree->parent[a]].tail : root;
1186 // first the fixed segment to the bone head
1187 if (!(ikchan->pchan->bone->flag & BONE_CONNECTED) || head.M.GetRot().Norm() > KDL::epsilon) {
1190 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, head);
1193 if (!(ikchan->jointType & IK_TRANSY)) {
1194 // fixed length, put it in tip
1198 weight[0] = (1.0 - pchan->stiffness[0]);
1199 weight[1] = (1.0 - pchan->stiffness[1]);
1200 weight[2] = (1.0 - pchan->stiffness[2]);
1201 switch (ikchan->jointType & ~IK_TRANSY) {
1205 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip);
1208 // RX only, get the X rotation
1210 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0], tip);
1211 weights.push_back(weight[0]);
1214 // RY only, get the Y rotation
1216 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[0], tip);
1217 weights.push_back(weight[1]);
1220 // RZ only, get the Zz rotation
1222 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0], tip);
1223 weights.push_back(weight[2]);
1225 case IK_XDOF | IK_YDOF:
1227 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0]);
1228 weights.push_back(weight[0]);
1233 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1234 weights.push_back(weight[1]);
1239 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0], tip);
1240 weights.push_back(weight[0]);
1241 weights.push_back(weight[2]);
1243 case IK_YDOF | IK_ZDOF:
1246 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0]);
1247 weights.push_back(weight[2]);
1252 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1253 weights.push_back(weight[1]);
1256 case IK_SWING | IK_YDOF:
1257 // decompose in a Swing+RotY joint
1259 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0]);
1260 weights.push_back(weight[0]);
1261 weights.push_back(weight[2]);
1266 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[2], tip);
1267 weights.push_back(weight[1]);
1272 ret = arm->addSegment(joint, parent, KDL::Joint::Sphere, rot[0], tip);
1273 weights.push_back(weight[0]);
1274 weights.push_back(weight[1]);
1275 weights.push_back(weight[2]);
1278 if (ret && (ikchan->jointType & IK_TRANSY)) {
1282 ret = arm->addSegment(joint, parent, KDL::Joint::TransY, rot[ikchan->ndof - 1]);
1283 const float ikstretch = pchan->ikstretch * pchan->ikstretch;
1284 /* why invert twice here? */
1285 weight[1] = (1.0 - min_ff(1.0 - ikstretch, 1.0f - 0.001f));
1286 weights.push_back(weight[1]);
1289 // error making the armature??
1291 // joint points to the segment that correspond to the bone per say
1292 ikchan->tail = joint;
1293 ikchan->head = parent;
1296 if ((ikchan->jointType & IK_XDOF) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ROTCTL))) {
1299 if (pchan->ikflag & BONE_IK_XLIMIT) {
1300 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0)
1303 if (pchan->ikflag & BONE_IK_ROTCTL) {
1304 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1308 if ((ikchan->jointType & IK_YDOF) && (pchan->ikflag & (BONE_IK_YLIMIT | BONE_IK_ROTCTL))) {
1311 if (pchan->ikflag & BONE_IK_YLIMIT) {
1312 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[1], pchan->limitmax[1]) < 0)
1315 if (pchan->ikflag & BONE_IK_ROTCTL) {
1316 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1320 if ((ikchan->jointType & IK_ZDOF) && (pchan->ikflag & (BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1323 if (pchan->ikflag & BONE_IK_ZLIMIT) {
1324 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[2], pchan->limitmax[2]) < 0)
1327 if (pchan->ikflag & BONE_IK_ROTCTL) {
1328 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1332 if ((ikchan->jointType & IK_SWING) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1335 if (pchan->ikflag & BONE_IK_XLIMIT) {
1336 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0)
1339 if (pchan->ikflag & BONE_IK_ZLIMIT) {
1340 if (arm->addLimitConstraint(joint, 1, pchan->limitmin[2], pchan->limitmax[2]) < 0)
1343 if (pchan->ikflag & BONE_IK_ROTCTL) {
1344 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1348 if ((ikchan->jointType & IK_REVOLUTE) && (pchan->ikflag & BONE_IK_ROTCTL)) {
1351 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1354 // no error, so restore
1356 rot += ikchan->ndof;
1362 // for each target, we need to add an end effector in the armature
1363 for (numtarget = 0, polarcon = NULL, ret = true, target = (PoseTarget *)tree->targets.first; target; target = (PoseTarget *)target->next) {
1364 condata = (bKinematicConstraint *)target->con->data;
1365 pchan = tree->pchan[target->tip];
1367 if (is_cartesian_constraint(target->con)) {
1368 // add the end effector
1369 IK_Target *iktarget = new IK_Target();
1370 ikscene->targets.push_back(iktarget);
1371 iktarget->ee = arm->addEndEffector(ikscene->channels[target->tip].tail);
1372 if (iktarget->ee == -1) {
1376 // initialize all the fields that we can set at this time
1377 iktarget->blenderConstraint = target->con;
1378 iktarget->channel = target->tip;
1379 iktarget->simulation = (ikparam->flag & ITASC_SIMULATION);
1380 iktarget->rootChannel = ikscene->channels[0].pchan;
1381 iktarget->owner = ob;
1382 iktarget->targetName = pchan->bone->name;
1383 iktarget->targetName += ":T:";
1384 iktarget->targetName += target->con->name;
1385 iktarget->constraintName = pchan->bone->name;
1386 iktarget->constraintName += ":C:";
1387 iktarget->constraintName += target->con->name;
1389 if (condata->poletar)
1390 // this constraint has a polar target
1391 polarcon = target->con;
1394 // deal with polar target if any
1395 if (numtarget == 1 && polarcon) {
1396 ikscene->polarConstraint = polarcon;
1398 // we can now add the armature
1399 // the armature is based on a moving frame.
1400 // initialize with the correct position in case there is no cache
1401 base_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, ikscene);
1402 ikscene->base = new iTaSC::MovingFrame(initPose);
1403 ikscene->base->setCallback(base_callback, ikscene);
1404 std::string armname;
1405 armname = ob->id.name;
1407 ret = scene->addObject(armname, ikscene->base);
1408 armname = ob->id.name;
1411 ret = scene->addObject(armname, ikscene->armature, ikscene->base);
1417 e_matrix& Wq = arm->getWq();
1418 assert(Wq.cols() == (int)weights.size());
1419 for (int q = 0; q < Wq.cols(); q++)
1420 Wq(q, q) = weights[q];
1421 // get the inverse rest pose frame of the base to compute relative rest pose of end effectors
1422 // this is needed to handle the enforce parameter
1423 // ikscene->pchan[0] is the root channel of the tree
1424 // if it has no parent, then it's just the identify Frame
1425 float invBaseFrame[4][4];
1426 pchan = ikscene->channels[0].pchan;
1427 if (pchan->parent) {
1428 // it has a parent, get the pose matrix from it
1429 float baseFrame[4][4];
1430 pchan = pchan->parent;
1431 copy_m4_m4(baseFrame, pchan->bone->arm_mat);
1432 // move to the tail and scale to get rest pose of armature base
1433 copy_v3_v3(baseFrame[3], pchan->bone->arm_tail);
1434 invert_m4_m4(invBaseFrame, baseFrame);
1437 unit_m4(invBaseFrame);
1439 // finally add the constraint
1440 for (t = 0; t < ikscene->targets.size(); t++) {
1441 IK_Target *iktarget = ikscene->targets[t];
1442 iktarget->blscene = blscene;
1443 condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
1444 pchan = tree->pchan[iktarget->channel];
1445 unsigned int controltype, bonecnt;
1449 // add the end effector
1450 // estimate the average bone length, used to clamp feedback error
1451 for (bonecnt = 0, bonelen = 0.f, a = iktarget->channel; a >= 0; a = tree->parent[a], bonecnt++)
1452 bonelen += ikscene->blScale * tree->pchan[a]->bone->length;
1455 // store the rest pose of the end effector to compute enforce target
1456 copy_m4_m4(mat, pchan->bone->arm_mat);
1457 copy_v3_v3(mat[3], pchan->bone->arm_tail);
1458 // get the rest pose relative to the armature base
1459 mul_m4_m4m4(iktarget->eeRest, invBaseFrame, mat);
1460 iktarget->eeBlend = (!ikscene->polarConstraint && condata->type == CONSTRAINT_IK_COPYPOSE) ? true : false;
1461 // use target_callback to make sure the initPose includes enforce coefficient
1462 target_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, iktarget);
1463 iktarget->target = new iTaSC::MovingFrame(initPose);
1464 iktarget->target->setCallback(target_callback, iktarget);
1465 ret = scene->addObject(iktarget->targetName, iktarget->target);
1469 switch (condata->type) {
1470 case CONSTRAINT_IK_COPYPOSE:
1472 if (condata->flag & CONSTRAINT_IK_ROT) {
1473 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_X))
1474 controltype |= iTaSC::CopyPose::CTL_ROTATIONX;
1475 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Y))
1476 controltype |= iTaSC::CopyPose::CTL_ROTATIONY;
1477 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Z))
1478 controltype |= iTaSC::CopyPose::CTL_ROTATIONZ;
1480 if (condata->flag & CONSTRAINT_IK_POS) {
1481 if (!(condata->flag & CONSTRAINT_IK_NO_POS_X))
1482 controltype |= iTaSC::CopyPose::CTL_POSITIONX;
1483 if (!(condata->flag & CONSTRAINT_IK_NO_POS_Y))
1484 controltype |= iTaSC::CopyPose::CTL_POSITIONY;
1485 if (!(condata->flag & CONSTRAINT_IK_NO_POS_Z))
1486 controltype |= iTaSC::CopyPose::CTL_POSITIONZ;
1489 iktarget->constraint = new iTaSC::CopyPose(controltype, controltype, bonelen);
1491 if (controltype & iTaSC::CopyPose::CTL_POSITION)
1492 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_POSITION, iTaSC::ACT_ALPHA, condata->weight);
1493 if (controltype & iTaSC::CopyPose::CTL_ROTATION)
1494 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_ROTATION, iTaSC::ACT_ALPHA, condata->orientweight);
1495 iktarget->constraint->registerCallback(copypose_callback, iktarget);
1496 iktarget->errorCallback = copypose_error;
1497 iktarget->controlType = controltype;
1498 // add the constraint
1499 if (condata->flag & CONSTRAINT_IK_TARGETAXIS)
1500 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, iktarget->targetName, armname, "", ikscene->channels[iktarget->channel].tail);
1502 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail);
1505 case CONSTRAINT_IK_DISTANCE:
1506 iktarget->constraint = new iTaSC::Distance(bonelen);
1507 iktarget->constraint->setControlParameter(iTaSC::Distance::ID_DISTANCE, iTaSC::ACT_VALUE, condata->dist);
1508 iktarget->constraint->registerCallback(distance_callback, iktarget);
1509 iktarget->errorCallback = distance_error;
1510 // we can update the weight on each substep
1511 iktarget->constraint->substep(true);
1512 // add the constraint
1513 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail);
1520 !scene->addCache(ikscene->cache) ||
1521 !scene->addSolver(ikscene->solver) ||
1522 !scene->initialize())
1530 static void create_scene(Scene *scene, Object *ob, float ctime)
1532 bPoseChannel *pchan;
1534 // create the IK scene
1535 for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = (bPoseChannel *)pchan->next) {
1536 // by construction there is only one tree
1537 PoseTree *tree = (PoseTree *)pchan->iktree.first;
1539 IK_Data *ikdata = get_ikdata(ob->pose);
1540 // convert tree in iTaSC::Scene
1541 IK_Scene *ikscene = convert_tree(scene, ob, pchan, ctime);
1543 ikscene->next = ikdata->first;
1544 ikdata->first = ikscene;
1546 // delete the trees once we are done
1548 BLI_remlink(&pchan->iktree, tree);
1549 BLI_freelistN(&tree->targets);
1550 if (tree->pchan) MEM_freeN(tree->pchan);
1551 if (tree->parent) MEM_freeN(tree->parent);
1552 if (tree->basis_change) MEM_freeN(tree->basis_change);
1554 tree = (PoseTree *)pchan->iktree.first;
1560 /* returns 1 if scaling has changed and tree must be reinitialized */
1561 static int init_scene(Object *ob)
1563 // check also if scaling has changed
1564 float scale = len_v3(ob->obmat[1]);
1567 if (ob->pose->ikdata) {
1568 for (scene = ((IK_Data *)ob->pose->ikdata)->first;
1570 scene = scene->next)
1572 if (fabs(scene->blScale - scale) > KDL::epsilon)
1574 scene->channels[0].pchan->flag |= POSE_IKTREE;
1580 static void execute_scene(Scene *blscene, IK_Scene *ikscene, bItasc *ikparam, float ctime, float frtime)
1584 if (ikparam->flag & ITASC_SIMULATION) {
1585 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ++ikchan) {
1586 // In simulation mode we don't allow external contraint to change our bones, mark the channel done
1587 // also tell Blender that this channel is part of IK tree (cleared on each BKE_pose_where_is()
1588 ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1589 ikchan->jointValid = 0;
1593 // in animation mode, we must get the bone position from action and constraints
1594 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ++ikchan) {
1595 if (!(ikchan->pchan->flag & POSE_DONE))
1596 BKE_pose_where_is_bone(blscene, ikscene->blArmature, ikchan->pchan, ctime, 1);
1597 // tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is()
1598 ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1599 ikchan->jointValid = 0;
1602 // only run execute the scene if at least one of our target is enabled
1603 for (i = ikscene->targets.size(); i > 0; --i) {
1604 IK_Target *iktarget = ikscene->targets[i - 1];
1605 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF))
1608 if (i == 0 && ikscene->armature->getNrOfConstraints() == 0)
1609 // all constraint disabled
1613 double timestamp = ctime * frtime + 2147483.648;
1614 double timestep = frtime;
1615 bool reiterate = (ikparam->flag & ITASC_REITERATION) ? true : false;
1616 int numstep = (ikparam->flag & ITASC_AUTO_STEP) ? 0 : ikparam->numstep;
1617 bool simulation = true;
1619 if (ikparam->flag & ITASC_SIMULATION) {
1620 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1623 // in animation mode we start from the pose after action and constraint
1624 convert_pose(ikscene);
1625 ikscene->armature->setJointArray(ikscene->jointArray);
1626 // and we don't handle velocity
1629 // time is virtual, so take fixed value for velocity parameters (see itasc_update_param)
1630 // and choose 1s timestep to allow having velocity parameters in radiant
1632 // use auto setup to let the solver test the variation of the joints
1636 if (ikscene->cache && !reiterate && simulation) {
1637 iTaSC::CacheTS sts, cts;
1638 sts = cts = (iTaSC::CacheTS)(timestamp * 1000.0 + 0.5);
1639 if (ikscene->cache->getPreviousCacheItem(ikscene->armature, 0, &cts) == NULL || cts == 0) {
1640 // the cache is empty before this time, reiterate
1641 if (ikparam->flag & ITASC_INITIAL_REITERATION)
1645 // can take the cache as a start point.
1647 timestep = sts / 1000.0;
1650 // don't cache if we are reiterating because we don't want to destroy the cache unnecessarily
1651 ikscene->scene->update(timestamp, timestep, numstep, false, !reiterate, simulation);
1653 // how many times do we reiterate?
1654 for (i = 0; i < ikparam->numiter; i++) {
1655 if (ikscene->armature->getMaxJointChange() < ikparam->precision ||
1656 ikscene->armature->getMaxEndEffectorChange() < ikparam->precision)
1660 ikscene->scene->update(timestamp, timestep, numstep, true, false, simulation);
1663 // one more fake iteration to cache
1664 ikscene->scene->update(timestamp, 0.0, 1, true, true, true);
1667 // compute constraint error
1668 for (i = ikscene->targets.size(); i > 0; --i) {
1669 IK_Target *iktarget = ikscene->targets[i - 1];
1670 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF) && iktarget->constraint) {
1671 unsigned int nvalues;
1672 const iTaSC::ConstraintValues *values;
1673 values = iktarget->constraint->getControlParameters(&nvalues);
1674 iktarget->errorCallback(values, nvalues, iktarget);
1677 // Apply result to bone:
1678 // walk the ikscene->channels
1679 // for each, get the Frame of the joint corresponding to the bone relative to its parent
1680 // combine the parent and the joint frame to get the frame relative to armature
1681 // a backward translation of the bone length gives the head
1682 // if TY, compute the scale as the ratio of the joint length with rest pose length
1683 iTaSC::Armature *arm = ikscene->armature;
1685 double q_rest[3], q[3];
1686 const KDL::Joint *joint;
1687 const KDL::Frame *tip;
1688 bPoseChannel *pchan;
1692 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; ++i, ++ikchan) {
1694 if (!arm->getRelativeFrame(frame, ikchan->tail))
1696 // this frame is relative to base, make it relative to object
1697 ikchan->frame = ikscene->baseFrame * frame;
1700 if (!arm->getRelativeFrame(frame, ikchan->tail, ikscene->channels[ikchan->parent].tail))
1702 // combine with parent frame to get frame relative to object
1703 ikchan->frame = ikscene->channels[ikchan->parent].frame * frame;
1705 // ikchan->frame is the tail frame relative to object
1707 if (!arm->getSegment(ikchan->tail, 3, joint, q_rest[0], q[0], tip))
1709 if (joint->getType() == KDL::Joint::TransY) {
1710 // stretch bones have a TY joint, compute the scale
1711 scale = (float)(q[0] / q_rest[0]);
1712 // the length is the joint itself
1713 length = (float)q[0];
1717 // for fixed bone, the length is in the tip (always along Y axis)
1720 // ready to compute the pose mat
1721 pchan = ikchan->pchan;
1723 ikchan->frame.getValue(&pchan->pose_mat[0][0]);
1724 // the scale of the object was included in the ik scene, take it out now
1725 // because the pose channels are relative to the object
1726 mul_v3_fl(pchan->pose_mat[3], ikscene->blInvScale);
1727 length *= ikscene->blInvScale;
1728 copy_v3_v3(pchan->pose_tail, pchan->pose_mat[3]);
1730 copy_v3_v3(yaxis, pchan->pose_mat[1]);
1731 mul_v3_fl(yaxis, length);
1732 sub_v3_v3v3(pchan->pose_mat[3], pchan->pose_mat[3], yaxis);
1733 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
1735 mul_v3_fl(pchan->pose_mat[0], scale);
1736 mul_v3_fl(pchan->pose_mat[1], scale);
1737 mul_v3_fl(pchan->pose_mat[2], scale);
1739 if (i < ikscene->numchan) {
1745 //---------------------------------------------------
1748 void itasc_initialize_tree(struct Scene *scene, Object *ob, float ctime)
1750 bPoseChannel *pchan;
1753 if (ob->pose->ikdata != NULL && !(ob->pose->flag & POSE_WAS_REBUILT)) {
1754 if (!init_scene(ob))
1757 // first remove old scene
1758 itasc_clear_data(ob->pose);
1759 // we should handle all the constraint and mark them all disabled
1760 // for blender but we'll start with the IK constraint alone
1761 for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = (bPoseChannel *)pchan->next) {
1762 if (pchan->constflag & PCHAN_HAS_IK)
1763 count += initialize_scene(ob, pchan);
1765 // if at least one tree, create the scenes from the PoseTree stored in the channels
1766 // postpone until execute_tree: this way the pose constraint are included
1768 // create_scene(scene, ob, ctime);
1769 //itasc_update_param(ob->pose);
1770 // make sure we don't rebuilt until the user changes something important
1771 ob->pose->flag &= ~POSE_WAS_REBUILT;
1774 void itasc_execute_tree(struct Scene *scene, struct Object *ob, struct bPoseChannel *pchan, float ctime)
1776 if (!ob->pose->ikdata) {
1777 // IK tree not yet created, no it now
1778 create_scene(scene, ob, ctime);
1779 itasc_update_param(ob->pose);
1781 if (ob->pose->ikdata) {
1782 IK_Data *ikdata = (IK_Data *)ob->pose->ikdata;
1783 bItasc *ikparam = (bItasc *) ob->pose->ikparam;
1784 // we need default parameters
1785 if (!ikparam) ikparam = &DefIKParam;
1787 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1788 if (ikscene->channels[0].pchan == pchan) {
1789 float timestep = scene->r.frs_sec_base / scene->r.frs_sec;
1790 if (ob->pose->flag & POSE_GAME_ENGINE) {
1791 timestep = ob->pose->ctime;
1792 // limit the timestep to avoid excessive number of iteration
1793 if (timestep > 0.2f)
1796 execute_scene(scene, ikscene, ikparam, ctime, timestep);
1803 void itasc_release_tree(struct Scene *scene, struct Object *ob, float ctime)
1805 // not used for iTaSC
1808 void itasc_clear_data(struct bPose *pose)
1811 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1812 for (IK_Scene *scene = ikdata->first; scene; scene = ikdata->first) {
1813 ikdata->first = scene->next;
1817 pose->ikdata = NULL;
1821 void itasc_clear_cache(struct bPose *pose)
1824 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1825 for (IK_Scene *scene = ikdata->first; scene; scene = scene->next) {
1827 // clear all cache but leaving the timestamp 0 (=rest pose)
1828 scene->cache->clearCacheFrom(NULL, 1);
1833 void itasc_update_param(struct bPose *pose)
1835 if (pose->ikdata && pose->ikparam) {
1836 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1837 bItasc *ikparam = (bItasc *)pose->ikparam;
1838 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1839 double armlength = ikscene->armature->getArmLength();
1840 ikscene->solver->setParam(iTaSC::Solver::DLS_LAMBDA_MAX, ikparam->dampmax * armlength);
1841 ikscene->solver->setParam(iTaSC::Solver::DLS_EPSILON, ikparam->dampeps * armlength);
1842 if (ikparam->flag & ITASC_SIMULATION) {
1843 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, ikparam->minstep);
1844 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, ikparam->maxstep);
1845 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1846 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, ikparam->feedback);
1849 // in animation mode timestep is 1s by convention =>
1850 // qmax becomes radiant and feedback becomes fraction of error gap corrected in one iteration
1851 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, 1.0);
1852 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, 1.0);
1853 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, 0.52);
1854 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, 0.8);
1860 void itasc_test_constraint(struct Object *ob, struct bConstraint *cons)
1862 struct bKinematicConstraint *data = (struct bKinematicConstraint *)cons->data;
1864 /* only for IK constraint */
1865 if (cons->type != CONSTRAINT_TYPE_KINEMATIC || data == NULL)
1868 switch (data->type) {
1869 case CONSTRAINT_IK_COPYPOSE:
1870 case CONSTRAINT_IK_DISTANCE:
1871 /* cartesian space constraint */