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/iksolver_plugin.c
33 #include "MEM_guardedalloc.h"
36 #include "BLI_blenlib.h"
38 #include "BLI_utildefines.h"
40 #include "BKE_armature.h"
41 #include "BKE_constraint.h"
43 #include "DNA_object_types.h"
44 #include "DNA_action_types.h"
45 #include "DNA_constraint_types.h"
46 #include "DNA_armature_types.h"
48 #include "IK_solver.h"
49 #include "iksolver_plugin.h"
51 #include <string.h> /* memcpy */
53 /* ********************** THE IK SOLVER ******************* */
55 /* allocates PoseTree, and links that to root bone/channel */
56 /* Note: detecting the IK chain is duplicate code... in drawarmature.c and in transform_conversions.c */
57 static void initialize_posetree(struct Object *UNUSED(ob), bPoseChannel *pchan_tip)
59 bPoseChannel *curchan, *pchan_root = NULL, *chanlist[256], **oldchan;
63 bKinematicConstraint *data;
64 int a, t, segcount = 0, size, newsize, *oldparent, parent;
66 /* find IK constraint, and validate it */
67 for (con = pchan_tip->constraints.first; con; con = con->next) {
68 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
69 data = (bKinematicConstraint *)con->data;
70 if (data->flag & CONSTRAINT_IK_AUTO) break;
71 if (data->tar == NULL) continue;
72 if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0) continue;
73 if ((con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) == 0 && (con->enforce != 0.0f)) break;
76 if (con == NULL) return;
78 /* exclude tip from chain? */
79 if (!(data->flag & CONSTRAINT_IK_TIP))
80 pchan_tip = pchan_tip->parent;
82 /* Find the chain's root & count the segments needed */
83 for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
86 curchan->flag |= POSE_CHAIN; // don't forget to clear this
87 chanlist[segcount] = curchan;
90 if (segcount == data->rootbone || segcount > 255) break; // 255 is weak
92 if (!segcount) return;
94 /* setup the chain data */
96 /* we make tree-IK, unless all existing targets are in this chain */
97 for (tree = pchan_root->iktree.first; tree; tree = tree->next) {
98 for (target = tree->targets.first; target; target = target->next) {
99 curchan = tree->pchan[target->tip];
100 if (curchan->flag & POSE_CHAIN)
101 curchan->flag &= ~POSE_CHAIN;
108 /* create a target */
109 target = MEM_callocN(sizeof(PoseTarget), "posetarget");
111 pchan_tip->flag &= ~POSE_CHAIN;
115 tree = MEM_callocN(sizeof(PoseTree), "posetree");
117 tree->type = CONSTRAINT_TYPE_KINEMATIC;
119 tree->iterations = data->iterations;
120 tree->totchannel = segcount;
121 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
123 tree->pchan = MEM_callocN(segcount * sizeof(void *), "ik tree pchan");
124 tree->parent = MEM_callocN(segcount * sizeof(int), "ik tree parent");
125 for (a = 0; a < segcount; a++) {
126 tree->pchan[a] = chanlist[segcount - a - 1];
127 tree->parent[a] = a - 1;
129 target->tip = segcount - 1;
131 /* AND! link the tree to the root */
132 BLI_addtail(&pchan_root->iktree, tree);
135 tree->iterations = MAX2(data->iterations, tree->iterations);
136 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
138 /* skip common pose channels and add remaining*/
139 size = MIN2(segcount, tree->totchannel);
141 while (a < size && t < tree->totchannel) {
142 /* locate first matching channel */
143 for (; t < tree->totchannel && tree->pchan[t] != chanlist[segcount - a - 1]; t++) ;
144 if (t >= tree->totchannel)
146 for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1]; a++, t++) ;
149 segcount = segcount - a;
150 target->tip = tree->totchannel + segcount - 1;
153 for (parent = a - 1; parent < tree->totchannel; parent++)
154 if (tree->pchan[parent] == chanlist[segcount - 1]->parent)
157 /* shouldn't happen, but could with dependency cycles */
158 if (parent == tree->totchannel)
162 newsize = tree->totchannel + segcount;
163 oldchan = tree->pchan;
164 oldparent = tree->parent;
166 tree->pchan = MEM_callocN(newsize * sizeof(void *), "ik tree pchan");
167 tree->parent = MEM_callocN(newsize * sizeof(int), "ik tree parent");
168 memcpy(tree->pchan, oldchan, sizeof(void *) * tree->totchannel);
169 memcpy(tree->parent, oldparent, sizeof(int) * tree->totchannel);
171 MEM_freeN(oldparent);
173 /* add new pose channels at the end, in reverse order */
174 for (a = 0; a < segcount; a++) {
175 tree->pchan[tree->totchannel + a] = chanlist[segcount - a - 1];
176 tree->parent[tree->totchannel + a] = tree->totchannel + a - 1;
178 tree->parent[tree->totchannel] = parent;
180 tree->totchannel = newsize;
183 /* move tree to end of list, for correct evaluation order */
184 BLI_remlink(&pchan_root->iktree, tree);
185 BLI_addtail(&pchan_root->iktree, tree);
188 /* add target to the tree */
189 BLI_addtail(&tree->targets, target);
190 /* mark root channel having an IK tree */
191 pchan_root->flag |= POSE_IKTREE;
195 /* transform from bone(b) to bone(b+1), store in chan_mat */
196 static void make_dmats(bPoseChannel *pchan)
199 float iR_parmat[4][4];
200 invert_m4_m4(iR_parmat, pchan->parent->pose_mat);
201 mul_m4_m4m4(pchan->chan_mat, iR_parmat, pchan->pose_mat); // delta mat
204 copy_m4_m4(pchan->chan_mat, pchan->pose_mat);
208 /* applies IK matrix to pchan, IK is done separated */
209 /* formula: pose_mat(b) = pose_mat(b-1) * diffmat(b-1, b) * ik_mat(b) */
210 /* to make this work, the diffmats have to be precalculated! Stored in chan_mat */
211 static void where_is_ik_bone(bPoseChannel *pchan, float ik_mat[3][3]) // nr = to detect if this is first bone
213 float vec[3], ikmat[4][4];
215 copy_m4_m3(ikmat, ik_mat);
218 mul_m4_series(pchan->pose_mat, pchan->parent->pose_mat, pchan->chan_mat, ikmat);
220 mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, ikmat);
223 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
225 copy_v3_v3(vec, pchan->pose_mat[1]);
226 mul_v3_fl(vec, pchan->bone->length);
227 add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
229 pchan->flag |= POSE_DONE;
233 /* called from within the core BKE_pose_where_is loop, all animsystems and constraints
234 * were executed & assigned. Now as last we do an IK pass */
235 static void execute_posetree(struct Scene *scene, Object *ob, PoseTree *tree)
237 float R_parmat[3][3], identity[3][3];
238 float iR_parmat[3][3];
239 float R_bonemat[3][3];
240 float goalrot[3][3], goalpos[3];
241 float rootmat[4][4], imat[4][4];
242 float goal[4][4], goalinv[4][4];
243 float irest_basis[3][3], full_basis[3][3];
244 float end_pose[4][4], world_pose[4][4];
245 float length, basis[3][3], rest_basis[3][3], start[3], *ikstretch = NULL;
246 float resultinf = 0.0f;
247 int a, flag, hasstretch = 0, resultblend = 0;
249 IK_Segment *seg, *parent, **iktree, *iktarget;
252 bKinematicConstraint *data, *poleangledata = NULL;
255 if (tree->totchannel == 0)
258 iktree = MEM_mallocN(sizeof(void *) * tree->totchannel, "ik tree");
260 for (a = 0; a < tree->totchannel; a++) {
261 pchan = tree->pchan[a];
266 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP))
268 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP))
270 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP))
273 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
274 flag |= IK_TRANS_YDOF;
278 seg = iktree[a] = IK_CreateSegment(flag);
284 parent = iktree[tree->parent[a]];
286 IK_SetParent(seg, parent);
288 /* get the matrix that transforms from prevbone into this bone */
289 copy_m3_m4(R_bonemat, pchan->pose_mat);
291 /* gather transformations for this IK segment */
294 copy_m3_m4(R_parmat, pchan->parent->pose_mat);
299 if (pchan->parent && (a > 0))
300 sub_v3_v3v3(start, pchan->pose_head, pchan->parent->pose_tail);
302 /* only root bone (a = 0) has no parent */
303 start[0] = start[1] = start[2] = 0.0f;
305 /* change length based on bone size */
306 length = bone->length * len_v3(R_bonemat[1]);
308 /* compute rest basis and its inverse */
309 copy_m3_m3(rest_basis, bone->bone_mat);
310 copy_m3_m3(irest_basis, bone->bone_mat);
311 transpose_m3(irest_basis);
313 /* compute basis with rest_basis removed */
314 invert_m3_m3(iR_parmat, R_parmat);
315 mul_m3_m3m3(full_basis, iR_parmat, R_bonemat);
316 mul_m3_m3m3(basis, irest_basis, full_basis);
318 /* basis must be pure rotation */
321 /* transform offset into local bone space */
322 normalize_m3(iR_parmat);
323 mul_m3_v3(iR_parmat, start);
325 IK_SetTransform(seg, start, rest_basis, basis, length);
327 if (pchan->ikflag & BONE_IK_XLIMIT)
328 IK_SetLimit(seg, IK_X, pchan->limitmin[0], pchan->limitmax[0]);
329 if (pchan->ikflag & BONE_IK_YLIMIT)
330 IK_SetLimit(seg, IK_Y, pchan->limitmin[1], pchan->limitmax[1]);
331 if (pchan->ikflag & BONE_IK_ZLIMIT)
332 IK_SetLimit(seg, IK_Z, pchan->limitmin[2], pchan->limitmax[2]);
334 IK_SetStiffness(seg, IK_X, pchan->stiffness[0]);
335 IK_SetStiffness(seg, IK_Y, pchan->stiffness[1]);
336 IK_SetStiffness(seg, IK_Z, pchan->stiffness[2]);
338 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
339 const float ikstretch = pchan->ikstretch * pchan->ikstretch;
340 /* this function does its own clamping */
341 IK_SetStiffness(seg, IK_TRANS_Y, 1.0f - ikstretch);
342 IK_SetLimit(seg, IK_TRANS_Y, IK_STRETCH_STIFF_MIN, IK_STRETCH_STIFF_MAX);
346 solver = IK_CreateSolver(iktree[0]);
348 /* set solver goals */
350 /* first set the goal inverse transform, assuming the root of tree was done ok! */
351 pchan = tree->pchan[0];
353 /* transform goal by parent mat, so this rotation is not part of the
354 * segment's basis. otherwise rotation limits do not work on the
355 * local transform of the segment itself. */
356 copy_m4_m4(rootmat, pchan->parent->pose_mat);
357 /* However, we do not want to get (i.e. reverse) parent's scale, as it generates [#31008]
358 * kind of nasty bugs... */
359 normalize_m4(rootmat);
363 copy_v3_v3(rootmat[3], pchan->pose_head);
365 mul_m4_m4m4(imat, ob->obmat, rootmat);
366 invert_m4_m4(goalinv, imat);
368 for (target = tree->targets.first; target; target = target->next) {
370 int poleconstrain = 0;
372 data = (bKinematicConstraint *)target->con->data;
374 /* 1.0=ctime, we pass on object for auto-ik (owner-type here is object, even though
375 * strictly speaking, it is a posechannel)
377 BKE_constraint_target_matrix_get(scene, target->con, 0, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
379 /* and set and transform goal */
380 mul_m4_m4m4(goal, goalinv, rootmat);
382 copy_v3_v3(goalpos, goal[3]);
383 copy_m3_m4(goalrot, goal);
384 normalize_m3(goalrot);
386 /* same for pole vector target */
388 BKE_constraint_target_matrix_get(scene, target->con, 1, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
390 if (data->flag & CONSTRAINT_IK_SETANGLE) {
391 /* don't solve IK when we are setting the pole angle */
395 mul_m4_m4m4(goal, goalinv, rootmat);
396 copy_v3_v3(polepos, goal[3]);
399 /* for pole targets, we blend the result of the ik solver
400 * instead of the target position, otherwise we can't get
401 * a smooth transition */
403 resultinf = target->con->enforce;
405 if (data->flag & CONSTRAINT_IK_GETANGLE) {
406 poleangledata = data;
407 data->flag &= ~CONSTRAINT_IK_GETANGLE;
412 /* do we need blending? */
413 if (!resultblend && target->con->enforce != 1.0f) {
414 float q1[4], q2[4], q[4];
415 float fac = target->con->enforce;
416 float mfac = 1.0f - fac;
418 pchan = tree->pchan[target->tip];
420 /* end effector in world space */
421 copy_m4_m4(end_pose, pchan->pose_mat);
422 copy_v3_v3(end_pose[3], pchan->pose_tail);
423 mul_m4_series(world_pose, goalinv, ob->obmat, end_pose);
426 goalpos[0] = fac * goalpos[0] + mfac * world_pose[3][0];
427 goalpos[1] = fac * goalpos[1] + mfac * world_pose[3][1];
428 goalpos[2] = fac * goalpos[2] + mfac * world_pose[3][2];
431 mat3_to_quat(q1, goalrot);
432 mat4_to_quat(q2, world_pose);
433 interp_qt_qtqt(q, q1, q2, mfac);
434 quat_to_mat3(goalrot, q);
437 iktarget = iktree[target->tip];
439 if ((data->flag & CONSTRAINT_IK_POS) && data->weight != 0.0f) {
441 IK_SolverSetPoleVectorConstraint(solver, iktarget, goalpos,
442 polepos, data->poleangle, (poleangledata == data));
443 IK_SolverAddGoal(solver, iktarget, goalpos, data->weight);
445 if ((data->flag & CONSTRAINT_IK_ROT) && (data->orientweight != 0.0f))
446 if ((data->flag & CONSTRAINT_IK_AUTO) == 0)
447 IK_SolverAddGoalOrientation(solver, iktarget, goalrot,
452 IK_Solve(solver, 0.0f, tree->iterations);
455 poleangledata->poleangle = IK_SolverGetPoleAngle(solver);
457 IK_FreeSolver(solver);
459 /* gather basis changes */
460 tree->basis_change = MEM_mallocN(sizeof(float[3][3]) * tree->totchannel, "ik basis change");
462 ikstretch = MEM_mallocN(sizeof(float) * tree->totchannel, "ik stretch");
464 for (a = 0; a < tree->totchannel; a++) {
465 IK_GetBasisChange(iktree[a], tree->basis_change[a]);
468 /* have to compensate for scaling received from parent */
469 float parentstretch, stretch;
471 pchan = tree->pchan[a];
472 parentstretch = (tree->parent[a] >= 0) ? ikstretch[tree->parent[a]] : 1.0f;
474 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
475 float trans[3], length;
477 IK_GetTranslationChange(iktree[a], trans);
478 length = pchan->bone->length * len_v3(pchan->pose_mat[1]);
480 ikstretch[a] = (length == 0.0f) ? 1.0f : (trans[1] + length) / length;
485 stretch = (parentstretch == 0.0f) ? 1.0f : ikstretch[a] / parentstretch;
487 mul_v3_fl(tree->basis_change[a][0], stretch);
488 mul_v3_fl(tree->basis_change[a][1], stretch);
489 mul_v3_fl(tree->basis_change[a][2], stretch);
492 if (resultblend && resultinf != 1.0f) {
494 blend_m3_m3m3(tree->basis_change[a], identity,
495 tree->basis_change[a], resultinf);
498 IK_FreeSegment(iktree[a]);
502 if (ikstretch) MEM_freeN(ikstretch);
505 static void free_posetree(PoseTree *tree)
507 BLI_freelistN(&tree->targets);
508 if (tree->pchan) MEM_freeN(tree->pchan);
509 if (tree->parent) MEM_freeN(tree->parent);
510 if (tree->basis_change) MEM_freeN(tree->basis_change);
514 ///----------------------------------------
515 /// Plugin API for legacy iksolver
517 void iksolver_initialize_tree(struct Scene *UNUSED(scene), struct Object *ob, float UNUSED(ctime))
521 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
522 if (pchan->constflag & PCHAN_HAS_IK) // flag is set on editing constraints
523 initialize_posetree(ob, pchan); // will attach it to root!
525 ob->pose->flag &= ~POSE_WAS_REBUILT;
528 void iksolver_execute_tree(struct Scene *scene, struct Object *ob, struct bPoseChannel *pchan, float ctime)
530 while (pchan->iktree.first) {
531 PoseTree *tree = pchan->iktree.first;
534 /* stop on the first tree that isn't a standard IK chain */
535 if (tree->type != CONSTRAINT_TYPE_KINEMATIC)
538 /* 4. walk over the tree for regular solving */
539 for (a = 0; a < tree->totchannel; a++) {
540 if (!(tree->pchan[a]->flag & POSE_DONE)) // successive trees can set the flag
541 BKE_pose_where_is_bone(scene, ob, tree->pchan[a], ctime, 1);
542 /* tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is() */
543 tree->pchan[a]->flag |= POSE_CHAIN;
545 /* 5. execute the IK solver */
546 execute_posetree(scene, ob, tree);
548 /* 6. apply the differences to the channels,
549 * we need to calculate the original differences first */
550 for (a = 0; a < tree->totchannel; a++) {
551 make_dmats(tree->pchan[a]);
554 for (a = 0; a < tree->totchannel; a++) {
556 where_is_ik_bone(tree->pchan[a], tree->basis_change[a]);
560 BLI_remlink(&pchan->iktree, tree);