Math Lib: add transpose_m3_m3, m3_m4, m4_m4
[blender.git] / source / blender / ikplugin / intern / iksolver_plugin.c
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/iksolver_plugin.c
30  *  \ingroup ikplugin
31  */
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BIK_api.h"
36 #include "BLI_blenlib.h"
37 #include "BLI_math.h"
38 #include "BLI_utildefines.h"
39
40 #include "BKE_armature.h"
41 #include "BKE_constraint.h"
42
43 #include "DNA_object_types.h"
44 #include "DNA_action_types.h"
45 #include "DNA_constraint_types.h"
46 #include "DNA_armature_types.h"
47
48 #include "IK_solver.h"
49 #include "iksolver_plugin.h"
50
51 #include <string.h> /* memcpy */
52
53 /* ********************** THE IK SOLVER ******************* */
54
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)
58 {
59         bPoseChannel *curchan, *pchan_root = NULL, *chanlist[256], **oldchan;
60         PoseTree *tree;
61         PoseTarget *target;
62         bConstraint *con;
63         bKinematicConstraint *data;
64         int a, t, segcount = 0, size, newsize, *oldparent, parent;
65
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;
74                 }
75         }
76         if (con == NULL) return;
77
78         /* exclude tip from chain? */
79         if (!(data->flag & CONSTRAINT_IK_TIP))
80                 pchan_tip = pchan_tip->parent;
81
82         /* Find the chain's root & count the segments needed */
83         for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
84                 pchan_root = curchan;
85
86                 curchan->flag |= POSE_CHAIN;    // don't forget to clear this
87                 chanlist[segcount] = curchan;
88                 segcount++;
89
90                 if (segcount == data->rootbone || segcount > 255) break;  // 255 is weak
91         }
92         if (!segcount) return;
93
94         /* setup the chain data */
95
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;
102                         else
103                                 break;
104                 }
105                 if (target) break;
106         }
107
108         /* create a target */
109         target = MEM_callocN(sizeof(PoseTarget), "posetarget");
110         target->con = con;
111         pchan_tip->flag &= ~POSE_CHAIN;
112
113         if (tree == NULL) {
114                 /* make new tree */
115                 tree = MEM_callocN(sizeof(PoseTree), "posetree");
116
117                 tree->type = CONSTRAINT_TYPE_KINEMATIC;
118
119                 tree->iterations = data->iterations;
120                 tree->totchannel = segcount;
121                 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
122
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;
128                 }
129                 target->tip = segcount - 1;
130
131                 /* AND! link the tree to the root */
132                 BLI_addtail(&pchan_root->iktree, tree);
133         }
134         else {
135                 tree->iterations = MAX2(data->iterations, tree->iterations);
136                 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
137
138                 /* skip common pose channels and add remaining*/
139                 size = MIN2(segcount, tree->totchannel);
140                 a = t = 0;
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)
145                                 break;
146                         for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1]; a++, t++) ;
147                 }
148
149                 segcount = segcount - a;
150                 target->tip = tree->totchannel + segcount - 1;
151
152                 if (segcount > 0) {
153                         for (parent = a - 1; parent < tree->totchannel; parent++)
154                                 if (tree->pchan[parent] == chanlist[segcount - 1]->parent)
155                                         break;
156
157                         /* shouldn't happen, but could with dependency cycles */
158                         if (parent == tree->totchannel)
159                                 parent = a - 1;
160
161                         /* resize array */
162                         newsize = tree->totchannel + segcount;
163                         oldchan = tree->pchan;
164                         oldparent = tree->parent;
165
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);
170                         MEM_freeN(oldchan);
171                         MEM_freeN(oldparent);
172
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;
177                         }
178                         tree->parent[tree->totchannel] = parent;
179
180                         tree->totchannel = newsize;
181                 }
182
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);
186         }
187
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;
192 }
193
194
195 /* transform from bone(b) to bone(b+1), store in chan_mat */
196 static void make_dmats(bPoseChannel *pchan)
197 {
198         if (pchan->parent) {
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
202         }
203         else {
204                 copy_m4_m4(pchan->chan_mat, pchan->pose_mat);
205         }
206 }
207
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
212 {
213         float vec[3], ikmat[4][4];
214
215         copy_m4_m3(ikmat, ik_mat);
216
217         if (pchan->parent)
218                 mul_m4_series(pchan->pose_mat, pchan->parent->pose_mat, pchan->chan_mat, ikmat);
219         else
220                 mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, ikmat);
221
222         /* calculate head */
223         copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
224         /* calculate tail */
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);
228
229         pchan->flag |= POSE_DONE;
230 }
231
232
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)
236 {
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;
248         bPoseChannel *pchan;
249         IK_Segment *seg, *parent, **iktree, *iktarget;
250         IK_Solver *solver;
251         PoseTarget *target;
252         bKinematicConstraint *data, *poleangledata = NULL;
253         Bone *bone;
254
255         if (tree->totchannel == 0)
256                 return;
257
258         iktree = MEM_mallocN(sizeof(void *) * tree->totchannel, "ik tree");
259
260         for (a = 0; a < tree->totchannel; a++) {
261                 pchan = tree->pchan[a];
262                 bone = pchan->bone;
263
264                 /* set DoF flag */
265                 flag = 0;
266                 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP))
267                         flag |= IK_XDOF;
268                 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP))
269                         flag |= IK_YDOF;
270                 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP))
271                         flag |= IK_ZDOF;
272
273                 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
274                         flag |= IK_TRANS_YDOF;
275                         hasstretch = 1;
276                 }
277
278                 seg = iktree[a] = IK_CreateSegment(flag);
279
280                 /* find parent */
281                 if (a == 0)
282                         parent = NULL;
283                 else
284                         parent = iktree[tree->parent[a]];
285
286                 IK_SetParent(seg, parent);
287
288                 /* get the matrix that transforms from prevbone into this bone */
289                 copy_m3_m4(R_bonemat, pchan->pose_mat);
290
291                 /* gather transformations for this IK segment */
292
293                 if (pchan->parent)
294                         copy_m3_m4(R_parmat, pchan->parent->pose_mat);
295                 else
296                         unit_m3(R_parmat);
297
298                 /* bone offset */
299                 if (pchan->parent && (a > 0))
300                         sub_v3_v3v3(start, pchan->pose_head, pchan->parent->pose_tail);
301                 else
302                         /* only root bone (a = 0) has no parent */
303                         start[0] = start[1] = start[2] = 0.0f;
304
305                 /* change length based on bone size */
306                 length = bone->length * len_v3(R_bonemat[1]);
307
308                 /* compute rest basis and its inverse */
309                 copy_m3_m3(rest_basis, bone->bone_mat);
310                 transpose_m3_m3(irest_basis, bone->bone_mat);
311
312                 /* compute basis with rest_basis removed */
313                 invert_m3_m3(iR_parmat, R_parmat);
314                 mul_m3_m3m3(full_basis, iR_parmat, R_bonemat);
315                 mul_m3_m3m3(basis, irest_basis, full_basis);
316
317                 /* basis must be pure rotation */
318                 normalize_m3(basis);
319
320                 /* transform offset into local bone space */
321                 normalize_m3(iR_parmat);
322                 mul_m3_v3(iR_parmat, start);
323
324                 IK_SetTransform(seg, start, rest_basis, basis, length);
325
326                 if (pchan->ikflag & BONE_IK_XLIMIT)
327                         IK_SetLimit(seg, IK_X, pchan->limitmin[0], pchan->limitmax[0]);
328                 if (pchan->ikflag & BONE_IK_YLIMIT)
329                         IK_SetLimit(seg, IK_Y, pchan->limitmin[1], pchan->limitmax[1]);
330                 if (pchan->ikflag & BONE_IK_ZLIMIT)
331                         IK_SetLimit(seg, IK_Z, pchan->limitmin[2], pchan->limitmax[2]);
332
333                 IK_SetStiffness(seg, IK_X, pchan->stiffness[0]);
334                 IK_SetStiffness(seg, IK_Y, pchan->stiffness[1]);
335                 IK_SetStiffness(seg, IK_Z, pchan->stiffness[2]);
336
337                 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
338                         const float ikstretch = pchan->ikstretch * pchan->ikstretch;
339                         /* this function does its own clamping */
340                         IK_SetStiffness(seg, IK_TRANS_Y, 1.0f - ikstretch);
341                         IK_SetLimit(seg, IK_TRANS_Y, IK_STRETCH_STIFF_MIN, IK_STRETCH_STIFF_MAX);
342                 }
343         }
344
345         solver = IK_CreateSolver(iktree[0]);
346
347         /* set solver goals */
348
349         /* first set the goal inverse transform, assuming the root of tree was done ok! */
350         pchan = tree->pchan[0];
351         if (pchan->parent) {
352                 /* transform goal by parent mat, so this rotation is not part of the
353                  * segment's basis. otherwise rotation limits do not work on the
354                  * local transform of the segment itself. */
355                 copy_m4_m4(rootmat, pchan->parent->pose_mat);
356                 /* However, we do not want to get (i.e. reverse) parent's scale, as it generates [#31008]
357                  * kind of nasty bugs... */
358                 normalize_m4(rootmat);
359         }
360         else
361                 unit_m4(rootmat);
362         copy_v3_v3(rootmat[3], pchan->pose_head);
363
364         mul_m4_m4m4(imat, ob->obmat, rootmat);
365         invert_m4_m4(goalinv, imat);
366
367         for (target = tree->targets.first; target; target = target->next) {
368                 float polepos[3];
369                 int poleconstrain = 0;
370
371                 data = (bKinematicConstraint *)target->con->data;
372
373                 /* 1.0=ctime, we pass on object for auto-ik (owner-type here is object, even though
374                  * strictly speaking, it is a posechannel)
375                  */
376                 BKE_constraint_target_matrix_get(scene, target->con, 0, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
377
378                 /* and set and transform goal */
379                 mul_m4_m4m4(goal, goalinv, rootmat);
380
381                 copy_v3_v3(goalpos, goal[3]);
382                 copy_m3_m4(goalrot, goal);
383                 normalize_m3(goalrot);
384
385                 /* same for pole vector target */
386                 if (data->poletar) {
387                         BKE_constraint_target_matrix_get(scene, target->con, 1, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
388
389                         if (data->flag & CONSTRAINT_IK_SETANGLE) {
390                                 /* don't solve IK when we are setting the pole angle */
391                                 break;
392                         }
393                         else {
394                                 mul_m4_m4m4(goal, goalinv, rootmat);
395                                 copy_v3_v3(polepos, goal[3]);
396                                 poleconstrain = 1;
397
398                                 /* for pole targets, we blend the result of the ik solver
399                                  * instead of the target position, otherwise we can't get
400                                  * a smooth transition */
401                                 resultblend = 1;
402                                 resultinf = target->con->enforce;
403
404                                 if (data->flag & CONSTRAINT_IK_GETANGLE) {
405                                         poleangledata = data;
406                                         data->flag &= ~CONSTRAINT_IK_GETANGLE;
407                                 }
408                         }
409                 }
410
411                 /* do we need blending? */
412                 if (!resultblend && target->con->enforce != 1.0f) {
413                         float q1[4], q2[4], q[4];
414                         float fac = target->con->enforce;
415                         float mfac = 1.0f - fac;
416
417                         pchan = tree->pchan[target->tip];
418
419                         /* end effector in world space */
420                         copy_m4_m4(end_pose, pchan->pose_mat);
421                         copy_v3_v3(end_pose[3], pchan->pose_tail);
422                         mul_m4_series(world_pose, goalinv, ob->obmat, end_pose);
423
424                         /* blend position */
425                         goalpos[0] = fac * goalpos[0] + mfac * world_pose[3][0];
426                         goalpos[1] = fac * goalpos[1] + mfac * world_pose[3][1];
427                         goalpos[2] = fac * goalpos[2] + mfac * world_pose[3][2];
428
429                         /* blend rotation */
430                         mat3_to_quat(q1, goalrot);
431                         mat4_to_quat(q2, world_pose);
432                         interp_qt_qtqt(q, q1, q2, mfac);
433                         quat_to_mat3(goalrot, q);
434                 }
435
436                 iktarget = iktree[target->tip];
437
438                 if ((data->flag & CONSTRAINT_IK_POS) && data->weight != 0.0f) {
439                         if (poleconstrain)
440                                 IK_SolverSetPoleVectorConstraint(solver, iktarget, goalpos,
441                                                                  polepos, data->poleangle, (poleangledata == data));
442                         IK_SolverAddGoal(solver, iktarget, goalpos, data->weight);
443                 }
444                 if ((data->flag & CONSTRAINT_IK_ROT) && (data->orientweight != 0.0f))
445                         if ((data->flag & CONSTRAINT_IK_AUTO) == 0)
446                                 IK_SolverAddGoalOrientation(solver, iktarget, goalrot,
447                                                             data->orientweight);
448         }
449
450         /* solve */
451         IK_Solve(solver, 0.0f, tree->iterations);
452
453         if (poleangledata)
454                 poleangledata->poleangle = IK_SolverGetPoleAngle(solver);
455
456         IK_FreeSolver(solver);
457
458         /* gather basis changes */
459         tree->basis_change = MEM_mallocN(sizeof(float[3][3]) * tree->totchannel, "ik basis change");
460         if (hasstretch)
461                 ikstretch = MEM_mallocN(sizeof(float) * tree->totchannel, "ik stretch");
462
463         for (a = 0; a < tree->totchannel; a++) {
464                 IK_GetBasisChange(iktree[a], tree->basis_change[a]);
465
466                 if (hasstretch) {
467                         /* have to compensate for scaling received from parent */
468                         float parentstretch, stretch;
469
470                         pchan = tree->pchan[a];
471                         parentstretch = (tree->parent[a] >= 0) ? ikstretch[tree->parent[a]] : 1.0f;
472
473                         if (tree->stretch && (pchan->ikstretch > 0.0f)) {
474                                 float trans[3], length;
475
476                                 IK_GetTranslationChange(iktree[a], trans);
477                                 length = pchan->bone->length * len_v3(pchan->pose_mat[1]);
478
479                                 ikstretch[a] = (length == 0.0f) ? 1.0f : (trans[1] + length) / length;
480                         }
481                         else
482                                 ikstretch[a] = 1.0;
483
484                         stretch = (parentstretch == 0.0f) ? 1.0f : ikstretch[a] / parentstretch;
485
486                         mul_v3_fl(tree->basis_change[a][0], stretch);
487                         mul_v3_fl(tree->basis_change[a][1], stretch);
488                         mul_v3_fl(tree->basis_change[a][2], stretch);
489                 }
490
491                 if (resultblend && resultinf != 1.0f) {
492                         unit_m3(identity);
493                         blend_m3_m3m3(tree->basis_change[a], identity,
494                                       tree->basis_change[a], resultinf);
495                 }
496
497                 IK_FreeSegment(iktree[a]);
498         }
499
500         MEM_freeN(iktree);
501         if (ikstretch) MEM_freeN(ikstretch);
502 }
503
504 static void free_posetree(PoseTree *tree)
505 {
506         BLI_freelistN(&tree->targets);
507         if (tree->pchan) MEM_freeN(tree->pchan);
508         if (tree->parent) MEM_freeN(tree->parent);
509         if (tree->basis_change) MEM_freeN(tree->basis_change);
510         MEM_freeN(tree);
511 }
512
513 ///----------------------------------------
514 /// Plugin API for legacy iksolver
515
516 void iksolver_initialize_tree(struct Scene *UNUSED(scene), struct Object *ob, float UNUSED(ctime))
517 {
518         bPoseChannel *pchan;
519
520         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
521                 if (pchan->constflag & PCHAN_HAS_IK) // flag is set on editing constraints
522                         initialize_posetree(ob, pchan);  // will attach it to root!
523         }
524         ob->pose->flag &= ~POSE_WAS_REBUILT;
525 }
526
527 void iksolver_execute_tree(struct Scene *scene, struct Object *ob,  struct bPoseChannel *pchan, float ctime)
528 {
529         while (pchan->iktree.first) {
530                 PoseTree *tree = pchan->iktree.first;
531                 int a;
532
533                 /* stop on the first tree that isn't a standard IK chain */
534                 if (tree->type != CONSTRAINT_TYPE_KINEMATIC)
535                         return;
536
537                 /* 4. walk over the tree for regular solving */
538                 for (a = 0; a < tree->totchannel; a++) {
539                         if (!(tree->pchan[a]->flag & POSE_DONE))    // successive trees can set the flag
540                                 BKE_pose_where_is_bone(scene, ob, tree->pchan[a], ctime, 1);
541                         /* tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is() */
542                         tree->pchan[a]->flag |= POSE_CHAIN;
543                 }
544                 /* 5. execute the IK solver */
545                 execute_posetree(scene, ob, tree);
546
547                 /* 6. apply the differences to the channels,
548                  *    we need to calculate the original differences first */
549                 for (a = 0; a < tree->totchannel; a++) {
550                         make_dmats(tree->pchan[a]);
551                 }
552
553                 for (a = 0; a < tree->totchannel; a++) {
554                         /* sets POSE_DONE */
555                         where_is_ik_bone(tree->pchan[a], tree->basis_change[a]);
556                 }
557
558                 /* 7. and free */
559                 BLI_remlink(&pchan->iktree, tree);
560                 free_posetree(tree);
561         }
562 }
563