Pataz-Gooseberry Request: Limits on Volume Preservation for Spline IK
[blender-staging.git] / source / blender / blenkernel / intern / armature.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  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/armature.c
27  *  \ingroup bke
28  */
29
30
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42 #include "BLI_utildefines.h"
43
44 #include "DNA_anim_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_mesh_types.h"
48 #include "DNA_lattice_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_object_types.h"
52
53 #include "BKE_animsys.h"
54 #include "BKE_armature.h"
55 #include "BKE_action.h"
56 #include "BKE_anim.h"
57 #include "BKE_constraint.h"
58 #include "BKE_curve.h"
59 #include "BKE_depsgraph.h"
60 #include "BKE_DerivedMesh.h"
61 #include "BKE_deform.h"
62 #include "BKE_displist.h"
63 #include "BKE_global.h"
64 #include "BKE_idprop.h"
65 #include "BKE_library.h"
66 #include "BKE_lattice.h"
67 #include "BKE_main.h"
68 #include "BKE_object.h"
69 #include "BKE_scene.h"
70
71 #include "BIK_api.h"
72 #include "BKE_sketch.h"
73
74 /* **************** Generic Functions, data level *************** */
75
76 bArmature *BKE_armature_add(Main *bmain, const char *name)
77 {
78         bArmature *arm;
79
80         arm = BKE_libblock_alloc(bmain, ID_AR, name);
81         arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
82         arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
83         arm->layer = 1;
84         return arm;
85 }
86
87 bArmature *BKE_armature_from_object(Object *ob)
88 {
89         if (ob->type == OB_ARMATURE)
90                 return (bArmature *)ob->data;
91         return NULL;
92 }
93
94 void BKE_armature_bonelist_free(ListBase *lb)
95 {
96         Bone *bone;
97
98         for (bone = lb->first; bone; bone = bone->next) {
99                 if (bone->prop) {
100                         IDP_FreeProperty(bone->prop);
101                         MEM_freeN(bone->prop);
102                 }
103                 BKE_armature_bonelist_free(&bone->childbase);
104         }
105
106         BLI_freelistN(lb);
107 }
108
109 void BKE_armature_free(bArmature *arm)
110 {
111         if (arm) {
112                 BKE_armature_bonelist_free(&arm->bonebase);
113
114                 /* free editmode data */
115                 if (arm->edbo) {
116                         BLI_freelistN(arm->edbo);
117
118                         MEM_freeN(arm->edbo);
119                         arm->edbo = NULL;
120                 }
121
122                 /* free sketch */
123                 if (arm->sketch) {
124                         freeSketch(arm->sketch);
125                         arm->sketch = NULL;
126                 }
127
128                 /* free animation data */
129                 if (arm->adt) {
130                         BKE_free_animdata(&arm->id);
131                         arm->adt = NULL;
132                 }
133         }
134 }
135
136 void BKE_armature_make_local(bArmature *arm)
137 {
138         Main *bmain = G.main;
139         bool is_local = false, is_lib = false;
140         Object *ob;
141
142         if (arm->id.lib == NULL)
143                 return;
144         if (arm->id.us == 1) {
145                 id_clear_lib_data(bmain, &arm->id);
146                 return;
147         }
148
149         for (ob = bmain->object.first; ob && ELEM(0, is_lib, is_local); ob = ob->id.next) {
150                 if (ob->data == arm) {
151                         if (ob->id.lib)
152                                 is_lib = true;
153                         else
154                                 is_local = true;
155                 }
156         }
157
158         if (is_local && is_lib == false) {
159                 id_clear_lib_data(bmain, &arm->id);
160         }
161         else if (is_local && is_lib) {
162                 bArmature *arm_new = BKE_armature_copy(arm);
163                 arm_new->id.us = 0;
164
165                 /* Remap paths of new ID using old library as base. */
166                 BKE_id_lib_local_paths(bmain, arm->id.lib, &arm_new->id);
167
168                 for (ob = bmain->object.first; ob; ob = ob->id.next) {
169                         if (ob->data == arm) {
170                                 if (ob->id.lib == NULL) {
171                                         ob->data = arm_new;
172                                         arm_new->id.us++;
173                                         arm->id.us--;
174                                 }
175                         }
176                 }
177         }
178 }
179
180 static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone)
181 {
182         Bone *curBone, *newChildBone;
183
184         if (oldBone == actBone)
185                 *newActBone = newBone;
186
187         if (oldBone->prop)
188                 newBone->prop = IDP_CopyProperty(oldBone->prop);
189
190         /* Copy this bone's list */
191         BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
192
193         /* For each child in the list, update it's children */
194         newChildBone = newBone->childbase.first;
195         for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) {
196                 newChildBone->parent = newBone;
197                 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
198                 newChildBone = newChildBone->next;
199         }
200 }
201
202 bArmature *BKE_armature_copy(bArmature *arm)
203 {
204         bArmature *newArm;
205         Bone *oldBone, *newBone;
206         Bone *newActBone = NULL;
207
208         newArm = BKE_libblock_copy(&arm->id);
209         BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
210
211         /* Duplicate the childrens' lists */
212         newBone = newArm->bonebase.first;
213         for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) {
214                 newBone->parent = NULL;
215                 copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone);
216                 newBone = newBone->next;
217         }
218
219         newArm->act_bone = newActBone;
220
221         newArm->edbo = NULL;
222         newArm->act_edbone = NULL;
223         newArm->sketch = NULL;
224
225         if (arm->id.lib) {
226                 BKE_id_lib_local_paths(G.main, arm->id.lib, &newArm->id);
227         }
228
229         return newArm;
230 }
231
232 static Bone *get_named_bone_bonechildren(Bone *bone, const char *name)
233 {
234         Bone *curBone, *rbone;
235
236         if (!strcmp(bone->name, name))
237                 return bone;
238
239         for (curBone = bone->childbase.first; curBone; curBone = curBone->next) {
240                 rbone = get_named_bone_bonechildren(curBone, name);
241                 if (rbone)
242                         return rbone;
243         }
244
245         return NULL;
246 }
247
248
249 /* Walk the list until the bone is found */
250 Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
251 {
252         Bone *bone = NULL, *curBone;
253
254         if (!arm)
255                 return NULL;
256
257         for (curBone = arm->bonebase.first; curBone; curBone = curBone->next) {
258                 bone = get_named_bone_bonechildren(curBone, name);
259                 if (bone)
260                         return bone;
261         }
262
263         return bone;
264 }
265
266 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
267  * unique names afterwards) strip_number: removes number extensions  (TODO: not used)
268  * axis: the axis to name on
269  * head/tail: the head/tail co-ordinate of the bone on the specified axis */
270 int bone_autoside_name(char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
271 {
272         unsigned int len;
273         char basename[MAXBONENAME] = "";
274         char extension[5] = "";
275
276         len = strlen(name);
277         if (len == 0)
278                 return 0;
279         BLI_strncpy(basename, name, sizeof(basename));
280
281         /* Figure out extension to append:
282          *      - The extension to append is based upon the axis that we are working on.
283          *      - If head happens to be on 0, then we must consider the tail position as well to decide
284          *        which side the bone is on
285          *              -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
286          *              -> Otherwise, extension is added from perspective of object based on which side tail goes to
287          *      - If head is non-zero, extension is added from perspective of object based on side head is on
288          */
289         if (axis == 2) {
290                 /* z-axis - vertical (top/bottom) */
291                 if (IS_EQF(head, 0.0f)) {
292                         if (tail < 0)
293                                 strcpy(extension, "Bot");
294                         else if (tail > 0)
295                                 strcpy(extension, "Top");
296                 }
297                 else {
298                         if (head < 0)
299                                 strcpy(extension, "Bot");
300                         else
301                                 strcpy(extension, "Top");
302                 }
303         }
304         else if (axis == 1) {
305                 /* y-axis - depth (front/back) */
306                 if (IS_EQF(head, 0.0f)) {
307                         if (tail < 0)
308                                 strcpy(extension, "Fr");
309                         else if (tail > 0)
310                                 strcpy(extension, "Bk");
311                 }
312                 else {
313                         if (head < 0)
314                                 strcpy(extension, "Fr");
315                         else
316                                 strcpy(extension, "Bk");
317                 }
318         }
319         else {
320                 /* x-axis - horizontal (left/right) */
321                 if (IS_EQF(head, 0.0f)) {
322                         if (tail < 0)
323                                 strcpy(extension, "R");
324                         else if (tail > 0)
325                                 strcpy(extension, "L");
326                 }
327                 else {
328                         if (head < 0)
329                                 strcpy(extension, "R");
330                         /* XXX Shouldn't this be simple else, as for z and y axes? */
331                         else if (head > 0)
332                                 strcpy(extension, "L");
333                 }
334         }
335
336         /* Simple name truncation
337          *      - truncate if there is an extension and it wouldn't be able to fit
338          *      - otherwise, just append to end
339          */
340         if (extension[0]) {
341                 bool changed = true;
342
343                 while (changed) { /* remove extensions */
344                         changed = false;
345                         if (len > 2 && basename[len - 2] == '.') {
346                                 if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
347                                         basename[len - 2] = '\0';
348                                         len -= 2;
349                                         changed = true;
350                                 }
351                         }
352                         else if (len > 3 && basename[len - 3] == '.') {
353                                 if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
354                                     (basename[len - 2] == 'B' && basename[len - 1] == 'k')) /* Bk */
355                                 {
356                                         basename[len - 3] = '\0';
357                                         len -= 3;
358                                         changed = true;
359                                 }
360                         }
361                         else if (len > 4 && basename[len - 4] == '.') {
362                                 if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' && basename[len - 1] == 'p') || /* Top */
363                                     (basename[len - 3] == 'B' && basename[len - 2] == 'o' && basename[len - 1] == 't')) /* Bot */
364                                 {
365                                         basename[len - 4] = '\0';
366                                         len -= 4;
367                                         changed = true;
368                                 }
369                         }
370                 }
371
372                 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
373                         strncpy(name, basename, len - strlen(extension));
374                 }
375
376                 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
377
378                 return 1;
379         }
380
381         else
382                 return 0;
383 }
384
385 /* ************* B-Bone support ******************* */
386
387 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
388 static void equalize_bezier(float *data, int desired)
389 {
390         float *fp, totdist, ddist, dist, fac1, fac2;
391         float pdist[MAX_BBONE_SUBDIV + 1];
392         float temp[MAX_BBONE_SUBDIV + 1][4];
393         int a, nr;
394
395         pdist[0] = 0.0f;
396         for (a = 0, fp = data; a < MAX_BBONE_SUBDIV; a++, fp += 4) {
397                 copy_qt_qt(temp[a], fp);
398                 pdist[a + 1] = pdist[a] + len_v3v3(fp, fp + 4);
399         }
400         /* do last point */
401         copy_qt_qt(temp[a], fp);
402         totdist = pdist[a];
403
404         /* go over distances and calculate new points */
405         ddist = totdist / ((float)desired);
406         nr = 1;
407         for (a = 1, fp = data + 4; a < desired; a++, fp += 4) {
408                 dist = ((float)a) * ddist;
409
410                 /* we're looking for location (distance) 'dist' in the array */
411                 while ((nr < MAX_BBONE_SUBDIV) && (dist >= pdist[nr]))
412                         nr++;
413
414                 fac1 = pdist[nr] - pdist[nr - 1];
415                 fac2 = pdist[nr] - dist;
416                 fac1 = fac2 / fac1;
417                 fac2 = 1.0f - fac1;
418
419                 fp[0] = fac1 * temp[nr - 1][0] + fac2 * temp[nr][0];
420                 fp[1] = fac1 * temp[nr - 1][1] + fac2 * temp[nr][1];
421                 fp[2] = fac1 * temp[nr - 1][2] + fac2 * temp[nr][2];
422                 fp[3] = fac1 * temp[nr - 1][3] + fac2 * temp[nr][3];
423         }
424         /* set last point, needed for orientation calculus */
425         copy_qt_qt(fp, temp[MAX_BBONE_SUBDIV]);
426 }
427
428 /* returns pointer to static array, filled with desired amount of bone->segments elements */
429 /* this calculation is done  within unit bone space */
430 void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BBONE_SUBDIV])
431 {
432         bPoseChannel *next, *prev;
433         Bone *bone = pchan->bone;
434         float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1 = 0.0f, roll2;
435         float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
436         float data[MAX_BBONE_SUBDIV + 1][4], *fp;
437         int a;
438         bool do_scale = false;
439
440         length = bone->length;
441
442         if (!rest) {
443                 /* check if we need to take non-uniform bone scaling into account */
444                 mat4_to_size(scale, pchan->pose_mat);
445
446                 if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
447                         size_to_mat4(scalemat, scale);
448                         invert_m4_m4(iscalemat, scalemat);
449
450                         length *= scale[1];
451                         do_scale = 1;
452                 }
453         }
454
455         hlength1 = bone->ease1 * length * 0.390464f; /* 0.5f * sqrt(2) * kappa, the handle length for near-perfect circles */
456         hlength2 = bone->ease2 * length * 0.390464f;
457
458         /* evaluate next and prev bones */
459         if (bone->flag & BONE_CONNECTED)
460                 prev = pchan->parent;
461         else
462                 prev = NULL;
463
464         next = pchan->child;
465
466         /* find the handle points, since this is inside bone space, the
467          * first point = (0, 0, 0)
468          * last point =  (0, length, 0) */
469         if (rest) {
470                 invert_m4_m4(imat, pchan->bone->arm_mat);
471         }
472         else if (do_scale) {
473                 copy_m4_m4(posemat, pchan->pose_mat);
474                 normalize_m4(posemat);
475                 invert_m4_m4(imat, posemat);
476         }
477         else
478                 invert_m4_m4(imat, pchan->pose_mat);
479
480         if (prev) {
481                 float difmat[4][4], result[3][3], imat3[3][3];
482
483                 /* transform previous point inside this bone space */
484                 if (rest)
485                         copy_v3_v3(h1, prev->bone->arm_head);
486                 else
487                         copy_v3_v3(h1, prev->pose_head);
488                 mul_m4_v3(imat, h1);
489
490                 if (prev->bone->segments > 1) {
491                         /* if previous bone is B-bone too, use average handle direction */
492                         h1[1] -= length;
493                         roll1 = 0.0f;
494                 }
495
496                 normalize_v3(h1);
497                 mul_v3_fl(h1, -hlength1);
498
499                 if (prev->bone->segments == 1) {
500                         /* find the previous roll to interpolate */
501                         if (rest)
502                                 mul_m4_m4m4(difmat, imat, prev->bone->arm_mat);
503                         else
504                                 mul_m4_m4m4(difmat, imat, prev->pose_mat);
505                         copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
506
507                         vec_roll_to_mat3(h1, 0.0f, mat3); /* the result of vec_roll without roll */
508
509                         invert_m3_m3(imat3, mat3);
510                         mul_m3_m3m3(mat3, result, imat3); /* the matrix transforming vec_roll to desired roll */
511
512                         roll1 = atan2f(mat3[2][0], mat3[2][2]);
513                 }
514         }
515         else {
516                 h1[0] = 0.0f; h1[1] = hlength1; h1[2] = 0.0f;
517                 roll1 = 0.0f;
518         }
519         if (next) {
520                 float difmat[4][4], result[3][3], imat3[3][3];
521
522                 /* transform next point inside this bone space */
523                 if (rest)
524                         copy_v3_v3(h2, next->bone->arm_tail);
525                 else
526                         copy_v3_v3(h2, next->pose_tail);
527                 mul_m4_v3(imat, h2);
528
529                 /* if next bone is B-bone too, use average handle direction */
530                 if (next->bone->segments > 1) {
531                         /* pass */
532                 }
533                 else {
534                         h2[1] -= length;
535                 }
536                 normalize_v3(h2);
537
538                 /* find the next roll to interpolate as well */
539                 if (rest)
540                         mul_m4_m4m4(difmat, imat, next->bone->arm_mat);
541                 else
542                         mul_m4_m4m4(difmat, imat, next->pose_mat);
543                 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
544
545                 vec_roll_to_mat3(h2, 0.0f, mat3); /* the result of vec_roll without roll */
546
547                 invert_m3_m3(imat3, mat3);
548                 mul_m3_m3m3(mat3, imat3, result); /* the matrix transforming vec_roll to desired roll */
549
550                 roll2 = atan2f(mat3[2][0], mat3[2][2]);
551
552                 /* and only now negate handle */
553                 mul_v3_fl(h2, -hlength2);
554         }
555         else {
556                 h2[0] = 0.0f; h2[1] = -hlength2; h2[2] = 0.0f;
557                 roll2 = 0.0;
558         }
559
560         /* make curve */
561         if (bone->segments > MAX_BBONE_SUBDIV)
562                 bone->segments = MAX_BBONE_SUBDIV;
563
564         BKE_curve_forward_diff_bezier(0.0f,  h1[0],                               h2[0],                               0.0f,   data[0],     MAX_BBONE_SUBDIV, 4 * sizeof(float));
565         BKE_curve_forward_diff_bezier(0.0f,  h1[1],                               length + h2[1],                      length, data[0] + 1, MAX_BBONE_SUBDIV, 4 * sizeof(float));
566         BKE_curve_forward_diff_bezier(0.0f,  h1[2],                               h2[2],                               0.0f,   data[0] + 2, MAX_BBONE_SUBDIV, 4 * sizeof(float));
567         BKE_curve_forward_diff_bezier(roll1, roll1 + 0.390464f * (roll2 - roll1), roll2 - 0.390464f * (roll2 - roll1), roll2,  data[0] + 3, MAX_BBONE_SUBDIV, 4 * sizeof(float));
568
569         equalize_bezier(data[0], bone->segments); /* note: does stride 4! */
570
571         /* make transformation matrices for the segments for drawing */
572         for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) {
573                 sub_v3_v3v3(h1, fp + 4, fp);
574                 vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */
575
576                 copy_m4_m3(result_array[a].mat, mat3);
577                 copy_v3_v3(result_array[a].mat[3], fp);
578
579                 if (do_scale) {
580                         /* correct for scaling when this matrix is used in scaled space */
581                         mul_m4_series(result_array[a].mat, iscalemat, result_array[a].mat, scalemat);
582                 }
583         }
584 }
585
586 /* ************ Armature Deform ******************* */
587
588 typedef struct bPoseChanDeform {
589         Mat4     *b_bone_mats;
590         DualQuat *dual_quat;
591         DualQuat *b_bone_dual_quats;
592 } bPoseChanDeform;
593
594 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, int use_quaternion)
595 {
596         Bone *bone = pchan->bone;
597         Mat4 b_bone[MAX_BBONE_SUBDIV], b_bone_rest[MAX_BBONE_SUBDIV];
598         Mat4 *b_bone_mats;
599         DualQuat *b_bone_dual_quats = NULL;
600         int a;
601
602         b_bone_spline_setup(pchan, 0, b_bone);
603         b_bone_spline_setup(pchan, 1, b_bone_rest);
604
605         /* allocate b_bone matrices and dual quats */
606         b_bone_mats = MEM_mallocN((1 + bone->segments) * sizeof(Mat4), "BBone defmats");
607         pdef_info->b_bone_mats = b_bone_mats;
608
609         if (use_quaternion) {
610                 b_bone_dual_quats = MEM_mallocN((bone->segments) * sizeof(DualQuat), "BBone dqs");
611                 pdef_info->b_bone_dual_quats = b_bone_dual_quats;
612         }
613
614         /* first matrix is the inverse arm_mat, to bring points in local bone space
615          * for finding out which segment it belongs to */
616         invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
617
618         /* then we make the b_bone_mats:
619          * - first transform to local bone space
620          * - translate over the curve to the bbone mat space
621          * - transform with b_bone matrix
622          * - transform back into global space */
623
624         for (a = 0; a < bone->segments; a++) {
625                 float tmat[4][4];
626
627                 invert_m4_m4(tmat, b_bone_rest[a].mat);
628
629                 mul_m4_series(b_bone_mats[a + 1].mat, pchan->chan_mat, bone->arm_mat, b_bone[a].mat, tmat, b_bone_mats[0].mat);
630
631                 if (use_quaternion)
632                         mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
633         }
634 }
635
636 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], DualQuat *dq, float defmat[3][3])
637 {
638         Mat4 *b_bone = pdef_info->b_bone_mats;
639         float (*mat)[4] = b_bone[0].mat;
640         float segment, y;
641         int a;
642
643         /* need to transform co back to bonespace, only need y */
644         y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1];
645
646         /* now calculate which of the b_bones are deforming this */
647         segment = bone->length / ((float)bone->segments);
648         a = (int)(y / segment);
649
650         /* note; by clamping it extends deform at endpoints, goes best with
651          * straight joints in restpos. */
652         CLAMP(a, 0, bone->segments - 1);
653
654         if (dq) {
655                 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
656         }
657         else {
658                 mul_m4_v3(b_bone[a + 1].mat, co);
659
660                 if (defmat) {
661                         copy_m3_m4(defmat, b_bone[a + 1].mat);
662                 }
663         }
664 }
665
666 /* using vec with dist to bone b1 - b2 */
667 float distfactor_to_bone(const float vec[3], const float b1[3], const float b2[3], float rad1, float rad2, float rdist)
668 {
669         float dist_sq;
670         float bdelta[3];
671         float pdelta[3];
672         float hsqr, a, l, rad;
673
674         sub_v3_v3v3(bdelta, b2, b1);
675         l = normalize_v3(bdelta);
676
677         sub_v3_v3v3(pdelta, vec, b1);
678
679         a = dot_v3v3(bdelta, pdelta);
680         hsqr = len_squared_v3(pdelta);
681
682         if (a < 0.0f) {
683                 /* If we're past the end of the bone, do a spherical field attenuation thing */
684                 dist_sq = len_squared_v3v3(b1, vec);
685                 rad = rad1;
686         }
687         else if (a > l) {
688                 /* If we're past the end of the bone, do a spherical field attenuation thing */
689                 dist_sq = len_squared_v3v3(b2, vec);
690                 rad = rad2;
691         }
692         else {
693                 dist_sq = (hsqr - (a * a));
694
695                 if (l != 0.0f) {
696                         rad = a / l;
697                         rad = rad * rad2 + (1.0f - rad) * rad1;
698                 }
699                 else
700                         rad = rad1;
701         }
702
703         a = rad * rad;
704         if (dist_sq < a)
705                 return 1.0f;
706         else {
707                 l = rad + rdist;
708                 l *= l;
709                 if (rdist == 0.0f || dist_sq >= l)
710                         return 0.0f;
711                 else {
712                         a = sqrtf(dist_sq) - rad;
713                         return 1.0f - (a * a) / (rdist * rdist);
714                 }
715         }
716 }
717
718 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[3][3], float mat[3][3])
719 {
720         float wmat[3][3];
721
722         if (pchan->bone->segments > 1)
723                 copy_m3_m3(wmat, bbonemat);
724         else
725                 copy_m3_m4(wmat, pchan->chan_mat);
726
727         mul_m3_fl(wmat, weight);
728         add_m3_m3m3(mat, mat, wmat);
729 }
730
731 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float vec[3], DualQuat *dq,
732                               float mat[3][3], const float co[3])
733 {
734         Bone *bone = pchan->bone;
735         float fac, contrib = 0.0;
736         float cop[3], bbonemat[3][3];
737         DualQuat bbonedq;
738
739         if (bone == NULL)
740                 return 0.0f;
741
742         copy_v3_v3(cop, co);
743
744         fac = distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
745
746         if (fac > 0.0f) {
747                 fac *= bone->weight;
748                 contrib = fac;
749                 if (contrib > 0.0f) {
750                         if (vec) {
751                                 if (bone->segments > 1)
752                                         /* applies on cop and bbonemat */
753                                         b_bone_deform(pdef_info, bone, cop, NULL, (mat) ? bbonemat : NULL);
754                                 else
755                                         mul_m4_v3(pchan->chan_mat, cop);
756
757                                 /* Make this a delta from the base position */
758                                 sub_v3_v3(cop, co);
759                                 madd_v3_v3fl(vec, cop, fac);
760
761                                 if (mat)
762                                         pchan_deform_mat_add(pchan, fac, bbonemat, mat);
763                         }
764                         else {
765                                 if (bone->segments > 1) {
766                                         b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
767                                         add_weighted_dq_dq(dq, &bbonedq, fac);
768                                 }
769                                 else
770                                         add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
771                         }
772                 }
773         }
774
775         return contrib;
776 }
777
778 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq,
779                               float mat[3][3], const float co[3], float *contrib)
780 {
781         float cop[3], bbonemat[3][3];
782         DualQuat bbonedq;
783
784         if (!weight)
785                 return;
786
787         copy_v3_v3(cop, co);
788
789         if (vec) {
790                 if (pchan->bone->segments > 1)
791                         /* applies on cop and bbonemat */
792                         b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat) ? bbonemat : NULL);
793                 else
794                         mul_m4_v3(pchan->chan_mat, cop);
795
796                 vec[0] += (cop[0] - co[0]) * weight;
797                 vec[1] += (cop[1] - co[1]) * weight;
798                 vec[2] += (cop[2] - co[2]) * weight;
799
800                 if (mat)
801                         pchan_deform_mat_add(pchan, weight, bbonemat, mat);
802         }
803         else {
804                 if (pchan->bone->segments > 1) {
805                         b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
806                         add_weighted_dq_dq(dq, &bbonedq, weight);
807                 }
808                 else
809                         add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
810         }
811
812         (*contrib) += weight;
813 }
814
815 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3],
816                            float (*defMats)[3][3], int numVerts, int deformflag,
817                            float (*prevCos)[3], const char *defgrp_name)
818 {
819         bPoseChanDeform *pdef_info_array;
820         bPoseChanDeform *pdef_info = NULL;
821         bArmature *arm = armOb->data;
822         bPoseChannel *pchan, **defnrToPC = NULL;
823         int *defnrToPCIndex = NULL;
824         MDeformVert *dverts = NULL;
825         bDeformGroup *dg;
826         DualQuat *dualquats = NULL;
827         float obinv[4][4], premat[4][4], postmat[4][4];
828         const short use_envelope = deformflag & ARM_DEF_ENVELOPE;
829         const short use_quaternion = deformflag & ARM_DEF_QUATERNION;
830         const short invert_vgroup = deformflag & ARM_DEF_INVERT_VGROUP;
831         int defbase_tot = 0;       /* safety for vertexgroup index overflow */
832         int i, target_totvert = 0; /* safety for vertexgroup overflow */
833         bool use_dverts = false;
834         int armature_def_nr;
835         int totchan;
836
837         if (arm->edbo) return;
838
839         invert_m4_m4(obinv, target->obmat);
840         copy_m4_m4(premat, target->obmat);
841         mul_m4_m4m4(postmat, obinv, armOb->obmat);
842         invert_m4_m4(premat, postmat);
843
844         /* bone defmats are already in the channels, chan_mat */
845
846         /* initialize B_bone matrices and dual quaternions */
847         totchan = BLI_listbase_count(&armOb->pose->chanbase);
848
849         if (use_quaternion) {
850                 dualquats = MEM_callocN(sizeof(DualQuat) * totchan, "dualquats");
851         }
852
853         pdef_info_array = MEM_callocN(sizeof(bPoseChanDeform) * totchan, "bPoseChanDeform");
854
855         totchan = 0;
856         pdef_info = pdef_info_array;
857         for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
858                 if (!(pchan->bone->flag & BONE_NO_DEFORM)) {
859                         if (pchan->bone->segments > 1)
860                                 pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
861
862                         if (use_quaternion) {
863                                 pdef_info->dual_quat = &dualquats[totchan++];
864                                 mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat);
865                         }
866                 }
867         }
868
869         /* get the def_nr for the overall armature vertex group if present */
870         armature_def_nr = defgroup_name_index(target, defgrp_name);
871
872         if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
873                 defbase_tot = BLI_listbase_count(&target->defbase);
874
875                 if (target->type == OB_MESH) {
876                         Mesh *me = target->data;
877                         dverts = me->dvert;
878                         if (dverts)
879                                 target_totvert = me->totvert;
880                 }
881                 else {
882                         Lattice *lt = target->data;
883                         dverts = lt->dvert;
884                         if (dverts)
885                                 target_totvert = lt->pntsu * lt->pntsv * lt->pntsw;
886                 }
887         }
888
889         /* get a vertex-deform-index to posechannel array */
890         if (deformflag & ARM_DEF_VGROUP) {
891                 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
892                         /* if we have a DerivedMesh, only use dverts if it has them */
893                         if (dm) {
894                                 use_dverts = (dm->getVertDataArray(dm, CD_MDEFORMVERT) != NULL);
895                         }
896                         else if (dverts) {
897                                 use_dverts = true;
898                         }
899
900                         if (use_dverts) {
901                                 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone");
902                                 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex");
903                                 for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) {
904                                         defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name);
905                                         /* exclude non-deforming bones */
906                                         if (defnrToPC[i]) {
907                                                 if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
908                                                         defnrToPC[i] = NULL;
909                                                 }
910                                                 else {
911                                                         defnrToPCIndex[i] = BLI_findindex(&armOb->pose->chanbase, defnrToPC[i]);
912                                                 }
913                                         }
914                                 }
915                         }
916                 }
917         }
918
919         for (i = 0; i < numVerts; i++) {
920                 MDeformVert *dvert;
921                 DualQuat sumdq, *dq = NULL;
922                 float *co, dco[3];
923                 float sumvec[3], summat[3][3];
924                 float *vec = NULL, (*smat)[3] = NULL;
925                 float contrib = 0.0f;
926                 float armature_weight = 1.0f; /* default to 1 if no overall def group */
927                 float prevco_weight = 1.0f;   /* weight for optional cached vertexcos */
928
929                 if (use_quaternion) {
930                         memset(&sumdq, 0, sizeof(DualQuat));
931                         dq = &sumdq;
932                 }
933                 else {
934                         sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
935                         vec = sumvec;
936
937                         if (defMats) {
938                                 zero_m3(summat);
939                                 smat = summat;
940                         }
941                 }
942
943                 if (use_dverts || armature_def_nr != -1) {
944                         if (dm)
945                                 dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
946                         else if (dverts && i < target_totvert)
947                                 dvert = dverts + i;
948                         else
949                                 dvert = NULL;
950                 }
951                 else
952                         dvert = NULL;
953
954                 if (armature_def_nr != -1 && dvert) {
955                         armature_weight = defvert_find_weight(dvert, armature_def_nr);
956
957                         if (invert_vgroup)
958                                 armature_weight = 1.0f - armature_weight;
959
960                         /* hackish: the blending factor can be used for blending with prevCos too */
961                         if (prevCos) {
962                                 prevco_weight = armature_weight;
963                                 armature_weight = 1.0f;
964                         }
965                 }
966
967                 /* check if there's any  point in calculating for this vert */
968                 if (armature_weight == 0.0f)
969                         continue;
970
971                 /* get the coord we work on */
972                 co = prevCos ? prevCos[i] : vertexCos[i];
973
974                 /* Apply the object's matrix */
975                 mul_m4_v3(premat, co);
976
977                 if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */
978                         MDeformWeight *dw = dvert->dw;
979                         int deformed = 0;
980                         unsigned int j;
981
982                         for (j = dvert->totweight; j != 0; j--, dw++) {
983                                 const int index = dw->def_nr;
984                                 if (index >= 0 && index < defbase_tot && (pchan = defnrToPC[index])) {
985                                         float weight = dw->weight;
986                                         Bone *bone = pchan->bone;
987                                         pdef_info = pdef_info_array + defnrToPCIndex[index];
988
989                                         deformed = 1;
990
991                                         if (bone && bone->flag & BONE_MULT_VG_ENV) {
992                                                 weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
993                                                                              bone->rad_head, bone->rad_tail, bone->dist);
994                                         }
995                                         pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
996                                 }
997                         }
998                         /* if there are vertexgroups but not groups with bones
999                          * (like for softbody groups) */
1000                         if (deformed == 0 && use_envelope) {
1001                                 pdef_info = pdef_info_array;
1002                                 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1003                                         if (!(pchan->bone->flag & BONE_NO_DEFORM))
1004                                                 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1005                                 }
1006                         }
1007                 }
1008                 else if (use_envelope) {
1009                         pdef_info = pdef_info_array;
1010                         for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1011                                 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1012                                         contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1013                         }
1014                 }
1015
1016                 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1017                 if (contrib > 0.0001f) {
1018                         if (use_quaternion) {
1019                                 normalize_dq(dq, contrib);
1020
1021                                 if (armature_weight != 1.0f) {
1022                                         copy_v3_v3(dco, co);
1023                                         mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq);
1024                                         sub_v3_v3(dco, co);
1025                                         mul_v3_fl(dco, armature_weight);
1026                                         add_v3_v3(co, dco);
1027                                 }
1028                                 else
1029                                         mul_v3m3_dq(co, (defMats) ? summat : NULL, dq);
1030
1031                                 smat = summat;
1032                         }
1033                         else {
1034                                 mul_v3_fl(vec, armature_weight / contrib);
1035                                 add_v3_v3v3(co, vec, co);
1036                         }
1037
1038                         if (defMats) {
1039                                 float pre[3][3], post[3][3], tmpmat[3][3];
1040
1041                                 copy_m3_m4(pre, premat);
1042                                 copy_m3_m4(post, postmat);
1043                                 copy_m3_m3(tmpmat, defMats[i]);
1044
1045                                 if (!use_quaternion) /* quaternion already is scale corrected */
1046                                         mul_m3_fl(smat, armature_weight / contrib);
1047
1048                                 mul_m3_series(defMats[i], post, smat, pre, tmpmat);
1049                         }
1050                 }
1051
1052                 /* always, check above code */
1053                 mul_m4_v3(postmat, co);
1054
1055                 /* interpolate with previous modifier position using weight group */
1056                 if (prevCos) {
1057                         float mw = 1.0f - prevco_weight;
1058                         vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0];
1059                         vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1];
1060                         vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2];
1061                 }
1062         }
1063
1064         if (dualquats)
1065                 MEM_freeN(dualquats);
1066         if (defnrToPC)
1067                 MEM_freeN(defnrToPC);
1068         if (defnrToPCIndex)
1069                 MEM_freeN(defnrToPCIndex);
1070
1071         /* free B_bone matrices */
1072         pdef_info = pdef_info_array;
1073         for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1074                 if (pdef_info->b_bone_mats)
1075                         MEM_freeN(pdef_info->b_bone_mats);
1076                 if (pdef_info->b_bone_dual_quats)
1077                         MEM_freeN(pdef_info->b_bone_dual_quats);
1078         }
1079
1080         MEM_freeN(pdef_info_array);
1081 }
1082
1083 /* ************ END Armature Deform ******************* */
1084
1085 void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[4][4], int UNUSED(root),
1086                                  int UNUSED(posed))
1087 {
1088         copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1089 }
1090
1091 /* **************** Space to Space API ****************** */
1092
1093 /* Convert World-Space Matrix to Pose-Space Matrix */
1094 void BKE_armature_mat_world_to_pose(Object *ob, float inmat[4][4], float outmat[4][4])
1095 {
1096         float obmat[4][4];
1097
1098         /* prevent crashes */
1099         if (ob == NULL)
1100                 return;
1101
1102         /* get inverse of (armature) object's matrix  */
1103         invert_m4_m4(obmat, ob->obmat);
1104
1105         /* multiply given matrix by object's-inverse to find pose-space matrix */
1106         mul_m4_m4m4(outmat, inmat, obmat);
1107 }
1108
1109 /* Convert World-Space Location to Pose-Space Location
1110  * NOTE: this cannot be used to convert to pose-space location of the supplied
1111  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
1112 void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
1113 {
1114         float xLocMat[4][4];
1115         float nLocMat[4][4];
1116
1117         /* build matrix for location */
1118         unit_m4(xLocMat);
1119         copy_v3_v3(xLocMat[3], inloc);
1120
1121         /* get bone-space cursor matrix and extract location */
1122         BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1123         copy_v3_v3(outloc, nLocMat[3]);
1124 }
1125
1126 /* Simple helper, computes the offset bone matrix.
1127  *     offs_bone = yoffs(b-1) + root(b) + bonemat(b).
1128  * Not exported, as it is only used in this file currently... */
1129 static void get_offset_bone_mat(Bone *bone, float offs_bone[4][4])
1130 {
1131         if (!bone->parent)
1132                 return;
1133
1134         /* Bone transform itself. */
1135         copy_m4_m3(offs_bone, bone->bone_mat);
1136
1137         /* The bone's root offset (is in the parent's coordinate system). */
1138         copy_v3_v3(offs_bone[3], bone->head);
1139
1140         /* Get the length translation of parent (length along y axis). */
1141         offs_bone[3][1] += bone->parent->length;
1142 }
1143
1144 /* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space.
1145  * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
1146  *     pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1147  * ...function.
1148  *
1149  * This allows to get the transformations of a bone in its object space, *before* constraints (and IK)
1150  * get applied (used by pose evaluation code).
1151  * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
1152  * in object space (used by interactive transform, and snapping code).
1153  *
1154  * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
1155  * will differ from the rotation/scale matrix...
1156  *
1157  * NOTE: This cannot be used to convert to pose-space transforms of the supplied
1158  *       pose-channel into its local space (i.e. 'visual'-keyframing).
1159  *       (note: I don't understand that, so I keep it :p --mont29).
1160  */
1161 void BKE_pchan_to_pose_mat(bPoseChannel *pchan, float rotscale_mat[4][4], float loc_mat[4][4])
1162 {
1163         Bone *bone, *parbone;
1164         bPoseChannel *parchan;
1165
1166         /* set up variables for quicker access below */
1167         bone = pchan->bone;
1168         parbone = bone->parent;
1169         parchan = pchan->parent;
1170
1171         if (parchan) {
1172                 float offs_bone[4][4];
1173                 /* yoffs(b-1) + root(b) + bonemat(b). */
1174                 get_offset_bone_mat(bone, offs_bone);
1175
1176                 /* Compose the rotscale matrix for this bone. */
1177                 if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) {
1178                         /* Parent rest rotation and scale. */
1179                         mul_m4_m4m4(rotscale_mat, parbone->arm_mat, offs_bone);
1180                 }
1181                 else if (bone->flag & BONE_HINGE) {
1182                         /* Parent rest rotation and pose scale. */
1183                         float tmat[4][4], tscale[3];
1184
1185                         /* Extract the scale of the parent pose matrix. */
1186                         mat4_to_size(tscale, parchan->pose_mat);
1187                         size_to_mat4(tmat, tscale);
1188
1189                         /* Applies the parent pose scale to the rest matrix. */
1190                         mul_m4_m4m4(tmat, tmat, parbone->arm_mat);
1191
1192                         mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1193                 }
1194                 else if (bone->flag & BONE_NO_SCALE) {
1195                         /* Parent pose rotation and rest scale (i.e. no scaling). */
1196                         float tmat[4][4];
1197                         copy_m4_m4(tmat, parchan->pose_mat);
1198                         normalize_m4(tmat);
1199                         mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1200                 }
1201                 else
1202                         mul_m4_m4m4(rotscale_mat, parchan->pose_mat, offs_bone);
1203
1204                 /* Compose the loc matrix for this bone. */
1205                 /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
1206
1207                 /* In this case, use the object's space *orientation*. */
1208                 if (bone->flag & BONE_NO_LOCAL_LOCATION) {
1209                         /* XXX I'm sure that code can be simplified! */
1210                         float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
1211                         unit_m4(bone_loc);
1212                         unit_m4(loc_mat);
1213                         unit_m4(tmat4);
1214
1215                         mul_v3_m4v3(bone_loc[3], parchan->pose_mat, offs_bone[3]);
1216
1217                         unit_m3(bone_rotscale);
1218                         copy_m3_m4(tmat3, parchan->pose_mat);
1219                         mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
1220
1221                         copy_m4_m3(tmat4, bone_rotscale);
1222                         mul_m4_m4m4(loc_mat, bone_loc, tmat4);
1223                 }
1224                 /* Those flags do not affect position, use plain parent transform space! */
1225                 else if (bone->flag & (BONE_HINGE | BONE_NO_SCALE)) {
1226                         mul_m4_m4m4(loc_mat, parchan->pose_mat, offs_bone);
1227                 }
1228                 /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */
1229                 else
1230                         copy_m4_m4(loc_mat, rotscale_mat);
1231         }
1232         /* Root bones. */
1233         else {
1234                 /* Rotation/scaling. */
1235                 copy_m4_m4(rotscale_mat, pchan->bone->arm_mat);
1236                 /* Translation. */
1237                 if (pchan->bone->flag & BONE_NO_LOCAL_LOCATION) {
1238                         /* Translation of arm_mat, without the rotation. */
1239                         unit_m4(loc_mat);
1240                         copy_v3_v3(loc_mat[3], pchan->bone->arm_mat[3]);
1241                 }
1242                 else
1243                         copy_m4_m4(loc_mat, rotscale_mat);
1244         }
1245 }
1246
1247 /* Convert Pose-Space Matrix to Bone-Space Matrix.
1248  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1249  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
1250 void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1251 {
1252         float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1253
1254         /* Security, this allows to call with inmat == outmat! */
1255         copy_m4_m4(inmat_, inmat);
1256
1257         BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1258         invert_m4(rotscale_mat);
1259         invert_m4(loc_mat);
1260
1261         mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1262         mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1263 }
1264
1265 /* Convert Bone-Space Matrix to Pose-Space Matrix. */
1266 void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1267 {
1268         float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1269
1270         /* Security, this allows to call with inmat == outmat! */
1271         copy_m4_m4(inmat_, inmat);
1272
1273         BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1274
1275         mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1276         mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1277 }
1278
1279 /* Convert Pose-Space Location to Bone-Space Location
1280  * NOTE: this cannot be used to convert to pose-space location of the supplied
1281  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
1282 void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
1283 {
1284         float xLocMat[4][4];
1285         float nLocMat[4][4];
1286
1287         /* build matrix for location */
1288         unit_m4(xLocMat);
1289         copy_v3_v3(xLocMat[3], inloc);
1290
1291         /* get bone-space cursor matrix and extract location */
1292         BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1293         copy_v3_v3(outloc, nLocMat[3]);
1294 }
1295
1296 void BKE_armature_mat_pose_to_bone_ex(Object *ob, bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1297 {
1298         bPoseChannel work_pchan = *pchan;
1299
1300         /* recalculate pose matrix with only parent transformations,
1301          * bone loc/sca/rot is ignored, scene and frame are not used. */
1302         BKE_pose_where_is_bone(NULL, ob, &work_pchan, 0.0f, false);
1303
1304         /* find the matrix, need to remove the bone transforms first so this is
1305          * calculated as a matrix to set rather then a difference ontop of whats
1306          * already there. */
1307         unit_m4(outmat);
1308         BKE_pchan_apply_mat4(&work_pchan, outmat, false);
1309
1310         BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
1311 }
1312
1313 /* same as BKE_object_mat3_to_rot() */
1314 void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[3][3], bool use_compat)
1315 {
1316         switch (pchan->rotmode) {
1317                 case ROT_MODE_QUAT:
1318                         mat3_to_quat(pchan->quat, mat);
1319                         break;
1320                 case ROT_MODE_AXISANGLE:
1321                         mat3_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1322                         break;
1323                 default: /* euler */
1324                         if (use_compat)
1325                                 mat3_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1326                         else
1327                                 mat3_to_eulO(pchan->eul, pchan->rotmode, mat);
1328                         break;
1329         }
1330 }
1331
1332 /* Apply a 4x4 matrix to the pose bone,
1333  * similar to BKE_object_apply_mat4() */
1334 void BKE_pchan_apply_mat4(bPoseChannel *pchan, float mat[4][4], bool use_compat)
1335 {
1336         float rot[3][3];
1337         mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1338         BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
1339 }
1340
1341 /* Remove rest-position effects from pose-transform for obtaining
1342  * 'visual' transformation of pose-channel.
1343  * (used by the Visual-Keyframing stuff) */
1344 void BKE_armature_mat_pose_to_delta(float delta_mat[4][4], float pose_mat[4][4], float arm_mat[4][4])
1345 {
1346         float imat[4][4];
1347
1348         invert_m4_m4(imat, arm_mat);
1349         mul_m4_m4m4(delta_mat, imat, pose_mat);
1350 }
1351
1352 /* **************** Rotation Mode Conversions ****************************** */
1353 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1354
1355 /* Called from RNA when rotation mode changes
1356  * - the result should be that the rotations given in the provided pointers have had conversions
1357  *   applied (as appropriate), such that the rotation of the element hasn't 'visually' changed  */
1358 void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1359 {
1360         /* check if any change - if so, need to convert data */
1361         if (newMode > 0) { /* to euler */
1362                 if (oldMode == ROT_MODE_AXISANGLE) {
1363                         /* axis-angle to euler */
1364                         axis_angle_to_eulO(eul, newMode, axis, *angle);
1365                 }
1366                 else if (oldMode == ROT_MODE_QUAT) {
1367                         /* quat to euler */
1368                         normalize_qt(quat);
1369                         quat_to_eulO(eul, newMode, quat);
1370                 }
1371                 /* else { no conversion needed } */
1372         }
1373         else if (newMode == ROT_MODE_QUAT) { /* to quat */
1374                 if (oldMode == ROT_MODE_AXISANGLE) {
1375                         /* axis angle to quat */
1376                         axis_angle_to_quat(quat, axis, *angle);
1377                 }
1378                 else if (oldMode > 0) {
1379                         /* euler to quat */
1380                         eulO_to_quat(quat, eul, oldMode);
1381                 }
1382                 /* else { no conversion needed } */
1383         }
1384         else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1385                 if (oldMode > 0) {
1386                         /* euler to axis angle */
1387                         eulO_to_axis_angle(axis, angle, eul, oldMode);
1388                 }
1389                 else if (oldMode == ROT_MODE_QUAT) {
1390                         /* quat to axis angle */
1391                         normalize_qt(quat);
1392                         quat_to_axis_angle(axis, angle, quat);
1393                 }
1394
1395                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1396                 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1397                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1398                         axis[1] = 1.0f;
1399                 }
1400         }
1401 }
1402
1403 /* **************** The new & simple (but OK!) armature evaluation ********* */
1404
1405 /* ****************** And how it works! ****************************************
1406  *
1407  * This is the bone transformation trick; they're hierarchical so each bone(b)
1408  * is in the coord system of bone(b-1):
1409  *
1410  * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
1411  *
1412  * -> yoffs is just the y axis translation in parent's coord system
1413  * -> d_root is the translation of the bone root, also in parent's coord system
1414  *
1415  * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1416  *
1417  * we then - in init deform - store the deform in chan_mat, such that:
1418  *
1419  * pose_mat(b)= arm_mat(b) * chan_mat(b)
1420  *
1421  * *************************************************************************** */
1422
1423 /* Computes vector and roll based on a rotation.
1424  * "mat" must contain only a rotation, and no scaling. */
1425 void mat3_to_vec_roll(float mat[3][3], float r_vec[3], float *r_roll)
1426 {
1427         if (r_vec) {
1428                 copy_v3_v3(r_vec, mat[1]);
1429         }
1430
1431         if (r_roll) {
1432                 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1433
1434                 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1435                 invert_m3_m3(vecmatinv, vecmat);
1436                 mul_m3_m3m3(rollmat, vecmatinv, mat);
1437
1438                 *r_roll = atan2f(rollmat[2][0], rollmat[2][2]);
1439         }
1440 }
1441
1442 /* Calculates the rest matrix of a bone based on its vector and a roll around that vector. */
1443 /* Given v = (v.x, v.y, v.z) our (normalized) bone vector, we want the rotation matrix M
1444  * from the Y axis (so that M * (0, 1, 0) = v).
1445  *   -> The rotation axis a lays on XZ plane, and it is orthonormal to v, hence to the projection of v onto XZ plane.
1446  *   -> a = (v.z, 0, -v.x)
1447  * We know a is eigenvector of M (so M * a = a).
1448  * Finally, we have w, such that M * w = (0, 1, 0) (i.e. the vector that will be aligned with Y axis once transformed).
1449  * We know w is symmetric to v by the Y axis.
1450  *   -> w = (-v.x, v.y, -v.z)
1451  *
1452  * Solving this, we get (x, y and z being the components of v):
1453  *     ┌ (x^2 * y + z^2) / (x^2 + z^2),   x,   x * z * (y - 1) / (x^2 + z^2) ┐
1454  * M = │  x * (y^2 - 1)  / (x^2 + z^2),   y,    z * (y^2 - 1)  / (x^2 + z^2) │
1455  *     └ x * z * (y - 1) / (x^2 + z^2),   z,   (x^2 + z^2 * y) / (x^2 + z^2) ┘
1456  *
1457  * This is stable as long as v (the bone) is not too much aligned with +/-Y (i.e. x and z components
1458  * are not too close to 0).
1459  *
1460  * Since v is normalized, we have x^2 + y^2 + z^2 = 1, hence x^2 + z^2 = 1 - y^2 = (1 - y)(1 + y).
1461  * This allows to simplifies M like this:
1462  *     ┌ 1 - x^2 / (1 + y),   x,     -x * z / (1 + y) ┐
1463  * M = │                -x,   y,                   -z │
1464  *     └  -x * z / (1 + y),   z,    1 - z^2 / (1 + y) ┘
1465  *
1466  * Written this way, we see the case v = +Y is no more a singularity. The only one remaining is the bone being
1467  * aligned with -Y.
1468  *
1469  * Let's handle the asymptotic behavior when bone vector is reaching the limit of y = -1. Each of the four corner
1470  * elements can vary from -1 to 1, depending on the axis a chosen for doing the rotation. And the "rotation" here
1471  * is in fact established by mirroring XZ plane by that given axis, then inversing the Y-axis.
1472  * For sufficiently small x and z, and with y approaching -1, all elements but the four corner ones of M
1473  * will degenerate. So let's now focus on these corner elements.
1474  *
1475  * We rewrite M so that it only contains its four corner elements, and combine the 1 / (1 + y) factor:
1476  *                    ┌ 1 + y - x^2,        -x * z ┐
1477  * M* = 1 / (1 + y) * │                            │
1478  *                    └      -x * z,   1 + y - z^2 ┘
1479  *
1480  * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability, so we ignore it and
1481  * normalize M instead. We know y^2 = 1 - (x^2 + z^2), and y < 0, hence y = -sqrt(1 - (x^2 + z^2)).
1482  * Since x and z are both close to 0, we apply the binomial expansion to the first order:
1483  * y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2. Which gives:
1484  *                        ┌  z^2 - x^2,  -2 * x * z ┐
1485  * M* = 1 / (x^2 + z^2) * │                         │
1486  *                        └ -2 * x * z,   x^2 - z^2 ┘
1487  */
1488 void vec_roll_to_mat3_normalized(const float nor[3], const float roll, float mat[3][3])
1489 {
1490 #define THETA_THRESHOLD_NEGY 1.0e-9f
1491 #define THETA_THRESHOLD_NEGY_CLOSE 1.0e-5f
1492
1493         float theta;
1494         float rMatrix[3][3], bMatrix[3][3];
1495
1496         theta = 1.0f + nor[1];
1497
1498         /* With old algo, 1.0e-13f caused T23954 and T31333, 1.0e-6f caused T27675 and T30438,
1499          * so using 1.0e-9f as best compromise.
1500          *
1501          * New algo is supposed much more precise, since less complex computations are performed,
1502          * but it uses two different threshold values...
1503          *
1504          * Note: When theta is close to zero, we have to check we do have non-null X/Z components as well
1505          *       (due to float precision errors, we can have nor = (0.0, 0.99999994, 0.0)...).
1506          */
1507         if (theta > THETA_THRESHOLD_NEGY_CLOSE || ((nor[0] || nor[2]) && theta > THETA_THRESHOLD_NEGY)) {
1508                 /* nor is *not* -Y.
1509                  * We got these values for free... so be happy with it... ;)
1510                  */
1511                 bMatrix[0][1] = -nor[0];
1512                 bMatrix[1][0] = nor[0];
1513                 bMatrix[1][1] = nor[1];
1514                 bMatrix[1][2] = nor[2];
1515                 bMatrix[2][1] = -nor[2];
1516                 if (theta > THETA_THRESHOLD_NEGY_CLOSE) {
1517                         /* If nor is far enough from -Y, apply the general case. */
1518                         bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
1519                         bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
1520                         bMatrix[2][0] = bMatrix[0][2] = -nor[0] * nor[2] / theta;
1521                 }
1522                 else {
1523                         /* If nor is too close to -Y, apply the special case. */
1524                         theta = nor[0] * nor[0] + nor[2] * nor[2];
1525                         bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
1526                         bMatrix[2][2] = -bMatrix[0][0];
1527                         bMatrix[2][0] = bMatrix[0][2] = 2.0f * nor[0] * nor[2] / theta;
1528                 }
1529         }
1530         else {
1531                 /* If nor is -Y, simple symmetry by Z axis. */
1532                 unit_m3(bMatrix);
1533                 bMatrix[0][0] = bMatrix[1][1] = -1.0;
1534         }
1535
1536         /* Make Roll matrix */
1537         axis_angle_normalized_to_mat3(rMatrix, nor, roll);
1538
1539         /* Combine and output result */
1540         mul_m3_m3m3(mat, rMatrix, bMatrix);
1541
1542 #undef THETA_THRESHOLD_NEGY
1543 #undef THETA_THRESHOLD_NEGY_CLOSE
1544 }
1545
1546 void vec_roll_to_mat3(const float vec[3], const float roll, float mat[3][3])
1547 {
1548         float nor[3];
1549
1550         normalize_v3_v3(nor, vec);
1551         vec_roll_to_mat3_normalized(nor, roll, mat);
1552 }
1553
1554 /* recursive part, calculates restposition of entire tree of children */
1555 /* used by exiting editmode too */
1556 void BKE_armature_where_is_bone(Bone *bone, Bone *prevbone)
1557 {
1558         float vec[3];
1559
1560         /* Bone Space */
1561         sub_v3_v3v3(vec, bone->tail, bone->head);
1562         vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1563
1564         bone->length = len_v3v3(bone->head, bone->tail);
1565
1566         /* this is called on old file reading too... */
1567         if (bone->xwidth == 0.0f) {
1568                 bone->xwidth = 0.1f;
1569                 bone->zwidth = 0.1f;
1570                 bone->segments = 1;
1571         }
1572
1573         if (prevbone) {
1574                 float offs_bone[4][4];
1575                 /* yoffs(b-1) + root(b) + bonemat(b) */
1576                 get_offset_bone_mat(bone, offs_bone);
1577
1578                 /* Compose the matrix for this bone  */
1579                 mul_m4_m4m4(bone->arm_mat, prevbone->arm_mat, offs_bone);
1580         }
1581         else {
1582                 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1583                 copy_v3_v3(bone->arm_mat[3], bone->head);
1584         }
1585
1586         /* and the kiddies */
1587         prevbone = bone;
1588         for (bone = bone->childbase.first; bone; bone = bone->next) {
1589                 BKE_armature_where_is_bone(bone, prevbone);
1590         }
1591 }
1592
1593 /* updates vectors and matrices on rest-position level, only needed
1594  * after editing armature itself, now only on reading file */
1595 void BKE_armature_where_is(bArmature *arm)
1596 {
1597         Bone *bone;
1598
1599         /* hierarchical from root to children */
1600         for (bone = arm->bonebase.first; bone; bone = bone->next) {
1601                 BKE_armature_where_is_bone(bone, NULL);
1602         }
1603 }
1604
1605 /* if bone layer is protected, copy the data from from->pose
1606  * when used with linked libraries this copies from the linked pose into the local pose */
1607 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1608 {
1609         bPose *pose = ob->pose, *frompose = from->pose;
1610         bPoseChannel *pchan, *pchanp;
1611         bConstraint *con;
1612         int error = 0;
1613
1614         if (frompose == NULL)
1615                 return;
1616
1617         /* in some cases when rigs change, we cant synchronize
1618          * to avoid crashing check for possible errors here */
1619         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1620                 if (pchan->bone->layer & layer_protected) {
1621                         if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
1622                                 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n",
1623                                        from->id.name, pchan->name);
1624                                 error = 1;
1625                         }
1626                 }
1627         }
1628
1629         if (error)
1630                 return;
1631
1632         /* clear all transformation values from library */
1633         BKE_pose_rest(frompose);
1634
1635         /* copy over all of the proxy's bone groups */
1636         /* TODO for later
1637          * - implement 'local' bone groups as for constraints
1638          * Note: this isn't trivial, as bones reference groups by index not by pointer,
1639          *       so syncing things correctly needs careful attention */
1640         BLI_freelistN(&pose->agroups);
1641         BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1642         pose->active_group = frompose->active_group;
1643
1644         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1645                 pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
1646                 
1647                 if (UNLIKELY(pchanp == NULL)) {
1648                         /* happens for proxies that become invalid because of a missing link
1649                          * for regular cases it shouldn't happen at all */
1650                 }
1651                 else if (pchan->bone->layer & layer_protected) {
1652                         ListBase proxylocal_constraints = {NULL, NULL};
1653                         bPoseChannel pchanw;
1654                         
1655                         /* copy posechannel to temp, but restore important pointers */
1656                         pchanw = *pchanp;
1657                         pchanw.prev = pchan->prev;
1658                         pchanw.next = pchan->next;
1659                         pchanw.parent = pchan->parent;
1660                         pchanw.child = pchan->child;
1661                         pchanw.custom_tx = pchan->custom_tx;
1662
1663                         pchanw.mpath = pchan->mpath;
1664                         pchan->mpath = NULL;
1665
1666                         /* this is freed so copy a copy, else undo crashes */
1667                         if (pchanw.prop) {
1668                                 pchanw.prop = IDP_CopyProperty(pchanw.prop);
1669                                 
1670                                 /* use the values from the existing props */
1671                                 if (pchan->prop) {
1672                                         IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1673                                 }
1674                         }
1675                         
1676                         /* constraints - proxy constraints are flushed... local ones are added after
1677                          *     1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1678                          *     2. copy proxy-pchan's constraints on-to new
1679                          *     3. add extracted local constraints back on top
1680                          *
1681                          * Note for BKE_constraints_copy: when copying constraints, disable 'do_extern' otherwise
1682                          *                                we get the libs direct linked in this blend.
1683                          */
1684                         BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints);
1685                         BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false);
1686                         BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1687                         
1688                         /* constraints - set target ob pointer to own object */
1689                         for (con = pchanw.constraints.first; con; con = con->next) {
1690                                 bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1691                                 ListBase targets = {NULL, NULL};
1692                                 bConstraintTarget *ct;
1693                                 
1694                                 if (cti && cti->get_constraint_targets) {
1695                                         cti->get_constraint_targets(con, &targets);
1696                                         
1697                                         for (ct = targets.first; ct; ct = ct->next) {
1698                                                 if (ct->tar == from)
1699                                                         ct->tar = ob;
1700                                         }
1701                                         
1702                                         if (cti->flush_constraint_targets)
1703                                                 cti->flush_constraint_targets(con, &targets, 0);
1704                                 }
1705                         }
1706                         
1707                         /* free stuff from current channel */
1708                         BKE_pose_channel_free(pchan);
1709                         
1710                         /* copy data in temp back over to the cleaned-out (but still allocated) original channel */
1711                         *pchan = pchanw;
1712                         if (pchan->custom) {
1713                                 id_us_plus(&pchan->custom->id);
1714                         }
1715                 }
1716                 else {
1717                         /* always copy custom shape */
1718                         pchan->custom = pchanp->custom;
1719                         if (pchan->custom) {
1720                                 id_us_plus(&pchan->custom->id);
1721                         }
1722                         if (pchanp->custom_tx)
1723                                 pchan->custom_tx = BKE_pose_channel_find_name(pose, pchanp->custom_tx->name);
1724
1725                         /* ID-Property Syncing */
1726                         {
1727                                 IDProperty *prop_orig = pchan->prop;
1728                                 if (pchanp->prop) {
1729                                         pchan->prop = IDP_CopyProperty(pchanp->prop);
1730                                         if (prop_orig) {
1731                                                 /* copy existing values across when types match */
1732                                                 IDP_SyncGroupValues(pchan->prop, prop_orig);
1733                                         }
1734                                 }
1735                                 else {
1736                                         pchan->prop = NULL;
1737                                 }
1738                                 if (prop_orig) {
1739                                         IDP_FreeProperty(prop_orig);
1740                                         MEM_freeN(prop_orig);
1741                                 }
1742                         }
1743                 }
1744         }
1745 }
1746
1747 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1748 {
1749         bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
1750
1751         pchan->bone = bone;
1752         pchan->parent = parchan;
1753
1754         counter++;
1755
1756         for (bone = bone->childbase.first; bone; bone = bone->next) {
1757                 counter = rebuild_pose_bone(pose, bone, pchan, counter);
1758                 /* for quick detecting of next bone in chain, only b-bone uses it now */
1759                 if (bone->flag & BONE_CONNECTED)
1760                         pchan->child = BKE_pose_channel_find_name(pose, bone->name);
1761         }
1762
1763         return counter;
1764 }
1765
1766 /* only after leave editmode, duplicating, validating older files, library syncing */
1767 /* NOTE: pose->flag is set for it */
1768 void BKE_pose_rebuild(Object *ob, bArmature *arm)
1769 {
1770         Bone *bone;
1771         bPose *pose;
1772         bPoseChannel *pchan, *next;
1773         int counter = 0;
1774
1775         /* only done here */
1776         if (ob->pose == NULL) {
1777                 /* create new pose */
1778                 ob->pose = MEM_callocN(sizeof(bPose), "new pose");
1779
1780                 /* set default settings for animviz */
1781                 animviz_settings_init(&ob->pose->avs);
1782         }
1783         pose = ob->pose;
1784
1785         /* clear */
1786         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1787                 pchan->bone = NULL;
1788                 pchan->child = NULL;
1789         }
1790
1791         /* first step, check if all channels are there */
1792         for (bone = arm->bonebase.first; bone; bone = bone->next) {
1793                 counter = rebuild_pose_bone(pose, bone, NULL, counter);
1794         }
1795
1796         /* and a check for garbage */
1797         for (pchan = pose->chanbase.first; pchan; pchan = next) {
1798                 next = pchan->next;
1799                 if (pchan->bone == NULL) {
1800                         BKE_pose_channel_free(pchan);
1801                         BKE_pose_channels_hash_free(pose);
1802                         BLI_freelinkN(&pose->chanbase, pchan);
1803                 }
1804         }
1805         /* printf("rebuild pose %s, %d bones\n", ob->id.name, counter); */
1806
1807         /* synchronize protected layers with proxy */
1808         if (ob->proxy) {
1809                 BKE_object_copy_proxy_drivers(ob, ob->proxy);
1810                 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1811         }
1812
1813         BKE_pose_update_constraint_flags(ob->pose); /* for IK detection for example */
1814
1815         /* the sorting */
1816         if (counter > 1)
1817                 DAG_pose_sort(ob);
1818
1819         ob->pose->flag &= ~POSE_RECALC;
1820         ob->pose->flag |= POSE_WAS_REBUILT;
1821
1822         BKE_pose_channels_hash_make(ob->pose);
1823 }
1824
1825
1826 /* ********************** SPLINE IK SOLVER ******************* */
1827
1828 /* Temporary evaluation tree data used for Spline IK */
1829 typedef struct tSplineIK_Tree {
1830         struct tSplineIK_Tree *next, *prev;
1831
1832         int type;                    /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
1833
1834         bool free_points;            /* free the point positions array */
1835         short chainlen;              /* number of bones in the chain */
1836
1837         float *points;               /* parametric positions for the joints along the curve */
1838         bPoseChannel **chain;        /* chain of bones to affect using Spline IK (ordered from the tip) */
1839
1840         bPoseChannel *root;          /* bone that is the root node of the chain */
1841
1842         bConstraint *con;            /* constraint for this chain */
1843         bSplineIKConstraint *ikData; /* constraint settings for this chain */
1844 } tSplineIK_Tree;
1845
1846 /* ----------- */
1847
1848 /* Tag the bones in the chain formed by the given bone for IK */
1849 static void splineik_init_tree_from_pchan(Scene *scene, Object *UNUSED(ob), bPoseChannel *pchan_tip)
1850 {
1851         bPoseChannel *pchan, *pchanRoot = NULL;
1852         bPoseChannel *pchanChain[255];
1853         bConstraint *con = NULL;
1854         bSplineIKConstraint *ikData = NULL;
1855         float boneLengths[255], *jointPoints;
1856         float totLength = 0.0f;
1857         bool free_joints = 0;
1858         int segcount = 0;
1859
1860         /* find the SplineIK constraint */
1861         for (con = pchan_tip->constraints.first; con; con = con->next) {
1862                 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
1863                         ikData = con->data;
1864
1865                         /* target can only be curve */
1866                         if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))
1867                                 continue;
1868                         /* skip if disabled */
1869                         if ((con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)))
1870                                 continue;
1871
1872                         /* otherwise, constraint is ok... */
1873                         break;
1874                 }
1875         }
1876         if (con == NULL)
1877                 return;
1878
1879         /* make sure that the constraint targets are ok
1880          *     - this is a workaround for a depsgraph bug...
1881          */
1882         if (ikData->tar) {
1883                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1884                  *       currently for paths to work it needs to go through the bevlist/displist system (ton)
1885                  */
1886
1887                 /* only happens on reload file, but violates depsgraph still... fix! */
1888                 if (ELEM(NULL,  ikData->tar->curve_cache, ikData->tar->curve_cache->path, ikData->tar->curve_cache->path->data)) {
1889                         BKE_displist_make_curveTypes(scene, ikData->tar, 0);
1890                         
1891                         /* path building may fail in EditMode after removing verts [#33268]*/
1892                         if (ELEM(NULL, ikData->tar->curve_cache->path, ikData->tar->curve_cache->path->data)) {
1893                                 /* BLI_assert(cu->path != NULL); */
1894                                 return;
1895                         }
1896                 }
1897         }
1898
1899         /* find the root bone and the chain of bones from the root to the tip
1900          * NOTE: this assumes that the bones are connected, but that may not be true... */
1901         for (pchan = pchan_tip; pchan && (segcount < ikData->chainlen); pchan = pchan->parent, segcount++) {
1902                 /* store this segment in the chain */
1903                 pchanChain[segcount] = pchan;
1904
1905                 /* if performing rebinding, calculate the length of the bone */
1906                 boneLengths[segcount] = pchan->bone->length;
1907                 totLength += boneLengths[segcount];
1908         }
1909
1910         if (segcount == 0)
1911                 return;
1912         else
1913                 pchanRoot = pchanChain[segcount - 1];
1914
1915         /* perform binding step if required */
1916         if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
1917                 float segmentLen = (1.0f / (float)segcount);
1918                 int i;
1919
1920                 /* setup new empty array for the points list */
1921                 if (ikData->points)
1922                         MEM_freeN(ikData->points);
1923                 ikData->numpoints = ikData->chainlen + 1;
1924                 ikData->points = MEM_mallocN(sizeof(float) * ikData->numpoints, "Spline IK Binding");
1925
1926                 /* bind 'tip' of chain (i.e. first joint = tip of bone with the Spline IK Constraint) */
1927                 ikData->points[0] = 1.0f;
1928
1929                 /* perform binding of the joints to parametric positions along the curve based
1930                  * proportion of the total length that each bone occupies
1931                  */
1932                 for (i = 0; i < segcount; i++) {
1933                         /* 'head' joints, traveling towards the root of the chain
1934                          *  - 2 methods; the one chosen depends on whether we've got usable lengths
1935                          */
1936                         if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
1937                                 /* 1) equi-spaced joints */
1938                                 ikData->points[i + 1] = ikData->points[i] - segmentLen;
1939                         }
1940                         else {
1941                                 /* 2) to find this point on the curve, we take a step from the previous joint
1942                                  *    a distance given by the proportion that this bone takes
1943                                  */
1944                                 ikData->points[i + 1] = ikData->points[i] - (boneLengths[i] / totLength);
1945                         }
1946                 }
1947
1948                 /* spline has now been bound */
1949                 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
1950         }
1951
1952         /* disallow negative values (happens with float precision) */
1953         CLAMP_MIN(ikData->points[segcount], 0.0f);
1954
1955         /* apply corrections for sensitivity to scaling on a copy of the bind points,
1956          * since it's easier to determine the positions of all the joints beforehand this way
1957          */
1958         if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
1959                 float splineLen, maxScale;
1960                 int i;
1961
1962                 /* make a copy of the points array, that we'll store in the tree
1963                  *     - although we could just multiply the points on the fly, this approach means that
1964                  *       we can introduce per-segment stretchiness later if it is necessary
1965                  */
1966                 jointPoints = MEM_dupallocN(ikData->points);
1967                 free_joints = 1;
1968
1969                 /* get the current length of the curve */
1970                 /* NOTE: this is assumed to be correct even after the curve was resized */
1971                 splineLen = ikData->tar->curve_cache->path->totdist;
1972
1973                 /* calculate the scale factor to multiply all the path values by so that the
1974                  * bone chain retains its current length, such that
1975                  *     maxScale * splineLen = totLength
1976                  */
1977                 maxScale = totLength / splineLen;
1978
1979                 /* apply scaling correction to all of the temporary points */
1980                 /* TODO: this is really not adequate enough on really short chains */
1981                 for (i = 0; i < segcount; i++)
1982                         jointPoints[i] *= maxScale;
1983         }
1984         else {
1985                 /* just use the existing points array */
1986                 jointPoints = ikData->points;
1987                 free_joints = 0;
1988         }
1989
1990         /* make a new Spline-IK chain, and store it in the IK chains */
1991         /* TODO: we should check if there is already an IK chain on this, since that would take presidence... */
1992         {
1993                 /* make new tree */
1994                 tSplineIK_Tree *tree = MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
1995                 tree->type = CONSTRAINT_TYPE_SPLINEIK;
1996
1997                 tree->chainlen = segcount;
1998
1999                 /* copy over the array of links to bones in the chain (from tip to root) */
2000                 tree->chain = MEM_mallocN(sizeof(bPoseChannel *) * segcount, "SplineIK Chain");
2001                 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel *) * segcount);
2002
2003                 /* store reference to joint position array */
2004                 tree->points = jointPoints;
2005                 tree->free_points = free_joints;
2006
2007                 /* store references to different parts of the chain */
2008                 tree->root = pchanRoot;
2009                 tree->con = con;
2010                 tree->ikData = ikData;
2011
2012                 /* AND! link the tree to the root */
2013                 BLI_addtail(&pchanRoot->siktree, tree);
2014         }
2015
2016         /* mark root channel having an IK tree */
2017         pchanRoot->flag |= POSE_IKSPLINE;
2018 }
2019
2020 /* Tag which bones are members of Spline IK chains */
2021 static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime))
2022 {
2023         bPoseChannel *pchan;
2024
2025         /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
2026         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2027                 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
2028                         splineik_init_tree_from_pchan(scene, ob, pchan);
2029         }
2030 }
2031
2032 /* ----------- */
2033
2034 /* Evaluate spline IK for a given bone */
2035 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan,
2036                                    int index, float ctime)
2037 {
2038         bSplineIKConstraint *ikData = tree->ikData;
2039         float poseHead[3], poseTail[3], poseMat[4][4];
2040         float splineVec[3], scaleFac, radius = 1.0f;
2041
2042         /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
2043         BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);
2044
2045         copy_v3_v3(poseHead, pchan->pose_head);
2046         copy_v3_v3(poseTail, pchan->pose_tail);
2047
2048         /* step 1: determine the positions for the endpoints of the bone */
2049         {
2050                 float vec[4], dir[3], rad;
2051                 float tailBlendFac = 1.0f;
2052
2053                 /* determine if the bone should still be affected by SplineIK */
2054                 if (tree->points[index + 1] >= 1.0f) {
2055                         /* spline doesn't affect the bone anymore, so done... */
2056                         pchan->flag |= POSE_DONE;
2057                         return;
2058                 }
2059                 else if ((tree->points[index] >= 1.0f) && (tree->points[index + 1] < 1.0f)) {
2060                         /* blending factor depends on the amount of the bone still left on the chain */
2061                         tailBlendFac = (1.0f - tree->points[index + 1]) / (tree->points[index] - tree->points[index + 1]);
2062                 }
2063
2064                 /* tail endpoint */
2065                 if (where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL)) {
2066                         /* apply curve's object-mode transforms to the position
2067                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
2068                          */
2069                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
2070                                 mul_m4_v3(ikData->tar->obmat, vec);
2071
2072                         /* convert the position to pose-space, then store it */
2073                         mul_m4_v3(ob->imat, vec);
2074                         interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
2075
2076                         /* set the new radius */
2077                         radius = rad;
2078                 }
2079
2080                 /* head endpoint */
2081                 if (where_on_path(ikData->tar, tree->points[index + 1], vec, dir, NULL, &rad, NULL)) {
2082                         /* apply curve's object-mode transforms to the position
2083                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
2084                          */
2085                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
2086                                 mul_m4_v3(ikData->tar->obmat, vec);
2087
2088                         /* store the position, and convert it to pose space */
2089                         mul_m4_v3(ob->imat, vec);
2090                         copy_v3_v3(poseHead, vec);
2091
2092                         /* set the new radius (it should be the average value) */
2093                         radius = (radius + rad) / 2;
2094                 }
2095         }
2096
2097         /* step 2: determine the implied transform from these endpoints
2098          *     - splineVec: the vector direction that the spline applies on the bone
2099          *     - scaleFac: the factor that the bone length is scaled by to get the desired amount
2100          */
2101         sub_v3_v3v3(splineVec, poseTail, poseHead);
2102         scaleFac = len_v3(splineVec) / pchan->bone->length;
2103
2104         /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis
2105          *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
2106          */
2107         {
2108                 float dmat[3][3], rmat[3][3], tmat[3][3];
2109                 float raxis[3], rangle;
2110
2111                 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
2112                  * orientation-relevant axes, and normalizing them
2113                  */
2114                 copy_v3_v3(rmat[0], pchan->pose_mat[0]);
2115                 copy_v3_v3(rmat[1], pchan->pose_mat[1]);
2116                 copy_v3_v3(rmat[2], pchan->pose_mat[2]);
2117                 normalize_m3(rmat);
2118
2119                 /* also, normalize the orientation imposed by the bone, now that we've extracted the scale factor */
2120                 normalize_v3(splineVec);
2121
2122                 /* calculate smallest axis-angle rotation necessary for getting from the
2123                  * current orientation of the bone, to the spline-imposed direction
2124                  */
2125                 cross_v3_v3v3(raxis, rmat[1], splineVec);
2126
2127                 rangle = dot_v3v3(rmat[1], splineVec);
2128                 CLAMP(rangle, -1.0f, 1.0f);
2129                 rangle = acosf(rangle);
2130
2131                 /* multiply the magnitude of the angle by the influence of the constraint to
2132                  * control the influence of the SplineIK effect
2133                  */
2134                 rangle *= tree->con->enforce;
2135
2136                 /* construct rotation matrix from the axis-angle rotation found above
2137                  *      - this call takes care to make sure that the axis provided is a unit vector first
2138                  */
2139                 axis_angle_to_mat3(dmat, raxis, rangle);
2140
2141                 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
2142                  * while still maintaining roll control from the existing bone animation
2143                  */
2144                 mul_m3_m3m3(tmat, dmat, rmat); /* m1, m3, m2 */
2145                 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
2146                 copy_m4_m3(poseMat, tmat);
2147         }
2148
2149         /* step 4: set the scaling factors for the axes */
2150         {
2151                 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
2152                 mul_v3_fl(poseMat[1], scaleFac);
2153
2154                 /* set the scaling factors of the x and z axes from... */
2155                 switch (ikData->xzScaleMode) {
2156                         case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
2157                         {
2158                                 /* original scales get used */
2159                                 float scale;
2160
2161                                 /* x-axis scale */
2162                                 scale = len_v3(pchan->pose_mat[0]);
2163                                 mul_v3_fl(poseMat[0], scale);
2164                                 /* z-axis scale */
2165                                 scale = len_v3(pchan->pose_mat[2]);
2166                                 mul_v3_fl(poseMat[2], scale);
2167                                 break;
2168                         }
2169                         case CONSTRAINT_SPLINEIK_XZS_INVERSE:
2170                         {
2171                                 /* old 'volume preservation' method using the inverse scale */
2172                                 float scale;
2173
2174                                 /* calculate volume preservation factor which is
2175                                  * basically the inverse of the y-scaling factor
2176                                  */
2177                                 if (fabsf(scaleFac) != 0.0f) {
2178                                         scale = 1.0f / fabsf(scaleFac);
2179
2180                                         /* we need to clamp this within sensible values */
2181                                         /* NOTE: these should be fine for now, but should get sanitised in future */
2182                                         CLAMP(scale, 0.0001f, 100000.0f);
2183                                 }
2184                                 else
2185                                         scale = 1.0f;
2186
2187                                 /* apply the scaling */
2188                                 mul_v3_fl(poseMat[0], scale);
2189                                 mul_v3_fl(poseMat[2], scale);
2190                                 break;
2191                         }
2192                         case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
2193                         {
2194                                 /* improved volume preservation based on the Stretch To constraint */
2195                                 float scale;
2196                                 
2197                                 /* as the basis for volume preservation, we use the inverse scale factor... */
2198                                 if (fabsf(scaleFac) != 0.0f) {
2199                                         /* NOTE: The method here is taken wholesale from the Stretch To constraint */
2200                                         float bulge = powf(1.0f / fabsf(scaleFac), ikData->bulge);
2201                                         
2202                                         if (bulge > 1.0f) {
2203                                                 if (ikData->flag & STRETCHTOCON_USE_BULGE_MAX) {
2204                                                         float bulge_max = max_ff(ikData->bulge_max, 1.0f);
2205                                                         float hard = min_ff(bulge, bulge_max);
2206                                                         
2207                                                         float range = bulge_max - 1.0f;
2208                                                         float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
2209                                                         float soft = 1.0f + range * atanf((bulge - 1.0f) * scale) / (0.5f * M_PI);
2210                                                         
2211                                                         bulge = interpf(soft, hard, ikData->bulge_smooth);
2212                                                 }
2213                                         }
2214                                         if (bulge < 1.0f) {
2215                                                 if (ikData->flag & STRETCHTOCON_USE_BULGE_MIN) {
2216                                                         float bulge_min = CLAMPIS(ikData->bulge_max, 0.0f, 1.0f);
2217                                                         float hard = max_ff(bulge, bulge_min);
2218                                                         
2219                                                         float range = 1.0f - bulge_min;
2220                                                         float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
2221                                                         float soft = 1.0f - range * atanf((1.0f - bulge) * scale) / (0.5f * M_PI);
2222                                                         
2223                                                         bulge = interpf(soft, hard, ikData->bulge_smooth);
2224                                                 }
2225                                         }
2226                                         
2227                                         /* compute scale factor for xz axes from this value */
2228                                         scale = sqrt(bulge);
2229                                 }
2230                                 else {
2231                                         /* no scaling, so scale factor is simple */
2232                                         scale = 1.0f;
2233                                 }
2234                                 
2235                                 /* apply the scaling (assuming normalised scale) */
2236                                 mul_v3_fl(poseMat[0], scale);
2237                                 mul_v3_fl(poseMat[2], scale);
2238                                 break;
2239                         }
2240                 }
2241
2242                 /* finally, multiply the x and z scaling by the radius of the curve too,
2243                  * to allow automatic scales to get tweaked still
2244                  */
2245                 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
2246                         mul_v3_fl(poseMat[0], radius);
2247                         mul_v3_fl(poseMat[2], radius);
2248                 }
2249         }
2250
2251         /* step 5: set the location of the bone in the matrix */
2252         if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
2253                 /* when the 'no-root' option is affected, the chain can retain
2254                  * the shape but be moved elsewhere
2255                  */
2256                 copy_v3_v3(poseHead, pchan->pose_head);
2257         }
2258         else if (tree->con->enforce < 1.0f) {
2259                 /* when the influence is too low
2260                  *      - blend the positions for the 'root' bone
2261                  *      - stick to the parent for any other
2262                  */
2263                 if (pchan->parent) {
2264                         copy_v3_v3(poseHead, pchan->pose_head);
2265                 }
2266                 else {
2267                         /* FIXME: this introduces popping artifacts when we reach 0.0 */
2268                         interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
2269                 }
2270         }
2271         copy_v3_v3(poseMat[3], poseHead);
2272
2273         /* finally, store the new transform */
2274         copy_m4_m4(pchan->pose_mat, poseMat);
2275         copy_v3_v3(pchan->pose_head, poseHead);
2276
2277         /* recalculate tail, as it's now outdated after the head gets adjusted above! */
2278         BKE_pose_where_is_bone_tail(pchan);
2279
2280         /* done! */
2281         pchan->flag |= POSE_DONE;
2282 }
2283
2284 /* Evaluate the chain starting from the nominated bone */
2285 static void splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
2286 {
2287         tSplineIK_Tree *tree;
2288
2289         /* for each pose-tree, execute it if it is spline, otherwise just free it */
2290         while ((tree = pchan_root->siktree.first) != NULL) {
2291                 int i;
2292
2293                 /* walk over each bone in the chain, calculating the effects of spline IK
2294                  *     - the chain is traversed in the opposite order to storage order (i.e. parent to children)
2295                  *       so that dependencies are correct
2296                  */
2297                 for (i = tree->chainlen - 1; i >= 0; i--) {
2298                         bPoseChannel *pchan = tree->chain[i];
2299                         splineik_evaluate_bone(tree, scene, ob, pchan, i, ctime);
2300                 }
2301
2302                 /* free the tree info specific to SplineIK trees now */
2303                 if (tree->chain)
2304                         MEM_freeN(tree->chain);
2305                 if (tree->free_points)
2306                         MEM_freeN(tree->points);
2307
2308                 /* free this tree */
2309                 BLI_freelinkN(&pchan_root->siktree, tree);
2310         }
2311 }
2312
2313 /* ********************** THE POSE SOLVER ******************* */
2314
2315 /* loc/rot/size to given mat4 */
2316 void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2317 {
2318         float smat[3][3];
2319         float rmat[3][3];
2320         float tmat[3][3];
2321
2322         /* get scaling matrix */
2323         size_to_mat3(smat, pchan->size);
2324
2325         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2326         if (pchan->rotmode > 0) {
2327                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2328                 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2329         }
2330         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2331                 /* axis-angle - not really that great for 3D-changing orientations */
2332                 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2333         }
2334         else {
2335                 /* quats are normalized before use to eliminate scaling issues */
2336                 float quat[4];
2337
2338                 /* NOTE: we now don't normalize the stored values anymore, since this was kindof evil in some cases
2339                  * but if this proves to be too problematic, switch back to the old system of operating directly on
2340                  * the stored copy
2341                  */
2342                 normalize_qt_qt(quat, pchan->quat);
2343                 quat_to_mat3(rmat, quat);
2344         }
2345
2346         /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2347         mul_m3_m3m3(tmat, rmat, smat);
2348         copy_m4_m3(chan_mat, tmat);
2349
2350         /* prevent action channels breaking chains */
2351         /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2352         if ((pchan->bone == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2353                 copy_v3_v3(chan_mat[3], pchan->loc);
2354         }
2355 }
2356
2357 /* loc/rot/size to mat4 */
2358 /* used in constraint.c too */
2359 void BKE_pchan_calc_mat(bPoseChannel *pchan)
2360 {
2361         /* this is just a wrapper around the copy of this function which calculates the matrix
2362          * and stores the result in any given channel
2363          */
2364         BKE_pchan_to_mat4(pchan, pchan->chan_mat);
2365 }
2366
2367 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2368
2369 /* NLA strip modifiers */
2370 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2371 {
2372         bActionModifier *amod;
2373         bActionStrip *strip, *strip2;
2374         float scene_cfra = BKE_scene_frame_get(scene);
2375         int do_modif;
2376
2377         for (strip = armob->nlastrips.first; strip; strip = strip->next) {
2378                 do_modif = false;
2379
2380                 if (scene_cfra >= strip->start && scene_cfra <= strip->end)
2381                         do_modif = true;
2382
2383                 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2384                         do_modif = true;
2385
2386                         /* if there are any other strips active, ignore modifiers for this strip -
2387                          * 'hold' option should only hold action modifiers if there are
2388                          * no other active strips */
2389                         for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2390                                 if (strip2 == strip) continue;
2391
2392                                 if (scene_cfra >= strip2->start && scene_cfra <= strip2->end) {
2393                                         if (!(strip2->flag & ACTSTRIP_MUTE))
2394                                                 do_modif = false;
2395                                 }
2396                         }
2397
2398                         /* if there are any later, activated, strips with 'hold' set, they take precedence,
2399                          * so ignore modifiers for this strip */
2400                         for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2401                                 if (scene_cfra < strip2->start) continue;
2402                                 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2403                                         do_modif = false;
2404                                 }
2405                         }
2406                 }
2407
2408                 if (do_modif) {
2409                         /* temporal solution to prevent 2 strips accumulating */
2410                         if (scene_cfra == strip->end && strip->next && strip->next->start == scene_cfra)
2411                                 continue;
2412
2413                         for (amod = strip->modifiers.first; amod; amod = amod->next) {
2414                                 switch (amod->type) {
2415                                         case ACTSTRIP_MOD_DEFORM:
2416                                         {
2417                                                 /* validate first */
2418                                                 if (amod->ob && amod->ob->type == OB_CURVE && amod->channel[0]) {
2419
2420                                                         if (strcmp(pchan->name, amod->channel) == 0) {
2421                                                                 float mat4[4][4], mat3[3][3];
2422
2423                                                                 curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2424                                                                 copy_m4_m4(mat4, pchan->pose_mat);
2425                                                                 mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2426
2427                                                         }
2428                                                 }
2429                                         }
2430                                         break;
2431                                         case ACTSTRIP_MOD_NOISE:
2432                                         {
2433                                                 if (strcmp(pchan->name, amod->channel) == 0) {
2434                                                         float nor[3], loc[3], ofs;
2435                                                         float eul[3], size[3], eulo[3], sizeo[3];
2436
2437                                                         /* calculate turbulance */
2438                                                         ofs = amod->turbul / 200.0f;
2439
2440                                                         /* make a copy of starting conditions */
2441                                                         copy_v3_v3(loc, pchan->pose_mat[3]);
2442                                                         mat4_to_eul(eul, pchan->pose_mat);
2443                                                         mat4_to_size(size, pchan->pose_mat);
2444                                                         copy_v3_v3(eulo, eul);
2445                                                         copy_v3_v3(sizeo, size);
2446
2447                                                         /* apply noise to each set of channels */
2448                                                         if (amod->channels & 4) {
2449                                                                 /* for scaling */
2450                                                                 nor[0] = BLI_gNoise(amod->noisesize, size[0] + ofs, size[1], size[2], 0, 0) - ofs;
2451                                                                 nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1] + ofs, size[2], 0, 0) - ofs;
2452                                                                 nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2] + ofs, 0, 0) - ofs;
2453                                                                 add_v3_v3(size, nor);
2454
2455                                                                 if (sizeo[0] != 0)
2456                                                                         mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2457                                                                 if (sizeo[1] != 0)
2458                                                                         mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2459                                                                 if (sizeo[2] != 0)
2460                                                                         mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2461                                                         }
2462                                                         if (amod->channels & 2) {
2463                                                                 /* for rotation */
2464                                                                 nor[0] = BLI_gNoise(amod->noisesize, eul[0] + ofs, eul[1], eul[2], 0, 0) - ofs;
2465                                                                 nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1] + ofs, eul[2], 0, 0) - ofs;
2466                                                                 nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2] + ofs, 0, 0) - ofs;
2467
2468                                                                 compatible_eul(nor, eulo);
2469                                                                 add_v3_v3(eul, nor);
2470                                                                 compatible_eul(eul, eulo);
2471
2472                                                                 loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2473                                                         }
2474                                                         if (amod->channels & 1) {
2475                                                                 /* for location */
2476                                                                 nor[0] = BLI_gNoise(amod->noisesize, loc[0] + ofs, loc[1], loc[2], 0, 0) - ofs;
2477                                                                 nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1] + ofs, loc[2], 0, 0) - ofs;
2478                                                                 nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2] + ofs, 0, 0) - ofs;
2479
2480                                                                 add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2481                                                         }
2482                                                 }
2483                                         }
2484                                         break;
2485                                 }
2486                         }
2487                 }
2488         }
2489 }
2490
2491 #endif
2492
2493 /* calculate tail of posechannel */
2494 void BKE_pose_where_is_bone_tail(bPoseChannel *pchan)
2495 {
2496         float vec[3];
2497
2498         copy_v3_v3(vec, pchan->pose_mat[1]);
2499         mul_v3_fl(vec, pchan->bone->length);
2500         add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2501 }
2502
2503 /* The main armature solver, does all constraints excluding IK */
2504 /* pchan is validated, as having bone and parent pointer
2505  * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2506  */
2507 void BKE_pose_where_is_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, bool do_extra)
2508 {
2509         /* This gives a chan_mat with actions (ipos) results. */
2510         if (do_extra)
2511                 BKE_pchan_calc_mat(pchan);
2512         else
2513                 unit_m4(pchan->chan_mat);
2514
2515         /* Construct the posemat based on PoseChannels, that we do before applying constraints. */
2516         /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2517         BKE_armature_mat_bone_to_pose(pchan, pchan->chan_mat, pchan->pose_mat);
2518
2519         /* Only rootbones get the cyclic offset (unless user doesn't want that). */
2520         /* XXX That could be a problem for snapping and other "reverse transform" features... */
2521         if (!pchan->parent) {
2522                 if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2523                         add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2524         }
2525
2526         if (do_extra) {
2527 #if 0   /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2528                 /* do NLA strip modifiers - i.e. curve follow */
2529                 do_strip_modifiers(scene, ob, bone, pchan);
2530 #endif
2531
2532                 /* Do constraints */
2533                 if (pchan->constraints.first) {
2534                         bConstraintOb *cob;
2535                         float vec[3];
2536
2537                         /* make a copy of location of PoseChannel for later */
2538                         copy_v3_v3(vec, pchan->pose_mat[3]);
2539
2540                         /* prepare PoseChannel for Constraint solving
2541                          * - makes a copy of matrix, and creates temporary struct to use
2542                          */
2543                         cob = BKE_constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2544
2545                         /* Solve PoseChannel's Constraints */
2546                         BKE_constraints_solve(&pchan->constraints, cob, ctime); /* ctime doesnt alter objects */
2547
2548                         /* cleanup after Constraint Solving
2549                          * - applies matrix back to pchan, and frees temporary struct used
2550                          */
2551                         BKE_constraints_clear_evalob(cob);
2552
2553                         /* prevent constraints breaking a chain */
2554                         if (pchan->bone->flag & BONE_CONNECTED) {
2555                                 copy_v3_v3(pchan->pose_mat[3], vec);
2556                         }
2557                 }
2558         }
2559
2560         /* calculate head */
2561         copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
2562         /* calculate tail */
2563         BKE_pose_where_is_bone_tail(pchan);
2564 }
2565
2566 /* This only reads anim data from channels, and writes to channels */
2567 /* This is the only function adding poses */
2568 void BKE_pose_where_is(Scene *scene, Object *ob)
2569 {
2570         bArmature *arm;
2571         Bone *bone;
2572         bPoseChannel *pchan;
2573         float imat[4][4];
2574         float ctime;
2575
2576         if (ob->type != OB_ARMATURE)
2577                 return;
2578         arm = ob->data;
2579
2580         if (ELEM(NULL, arm, scene))
2581                 return;
2582         if ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC))
2583                 BKE_pose_rebuild(ob, arm);
2584
2585         ctime = BKE_scene_frame_get(scene); /* not accurate... */
2586
2587         /* In editmode or restposition we read the data from the bones */
2588         if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
2589                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2590                         bone = pchan->bone;
2591                         if (bone) {
2592                                 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2593                                 copy_v3_v3(pchan->pose_head, bone->arm_head);
2594                                 copy_v3_v3(pchan->pose_tail, bone->arm_tail);
2595                         }
2596                 }
2597         }
2598         else {
2599                 invert_m4_m4(ob->imat, ob->obmat); /* imat is needed */
2600
2601                 /* 1. clear flags */
2602                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2603                         pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
2604                 }
2605
2606                 /* 2a. construct the IK tree (standard IK) */
2607                 BIK_initialize_tree(scene, ob, ctime);
2608
2609                 /* 2b. construct the Spline IK trees
2610                  *  - this is not integrated as an IK plugin, since it should be able
2611                  *        to function in conjunction with standard IK
2612                  */
2613                 splineik_init_tree(scene, ob, ctime);
2614
2615                 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2616                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2617                         /* 4a. if we find an IK root, we handle it separated */
2618                         if (pchan->flag & POSE_IKTREE) {
2619                                 BIK_execute_tree(scene, ob, pchan, ctime);
2620                         }
2621                         /* 4b. if we find a Spline IK root, we handle it separated too */
2622                         else if (pchan->flag & POSE_IKSPLINE) {
2623                                 splineik_execute_tree(scene, ob, pchan, ctime);
2624                         }
2625                         /* 5. otherwise just call the normal solver */
2626                         else if (!(pchan->flag & POSE_DONE)) {
2627                                 BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);
2628                         }
2629                 }
2630                 /* 6. release the IK tree */
2631                 BIK_release_tree(scene, ob, ctime);
2632         }
2633
2634         /* calculating deform matrices */
2635         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2636                 if (pchan->bone) {
2637                         invert_m4_m4(imat, pchan->bone->arm_mat);
2638                         mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
2639                 }
2640         }
2641 }
2642
2643 /************** Bounding box ********************/
2644 static int minmax_armature(Object *ob, float r_min[3], float r_max[3])
2645 {
2646         bPoseChannel *pchan;
2647
2648         /* For now, we assume BKE_pose_where_is has already been called (hence we have valid data in pachan). */
2649         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2650                 minmax_v3v3_v3(r_min, r_max, pchan->pose_head);
2651                 minmax_v3v3_v3(r_min, r_max, pchan->pose_tail);
2652         }
2653
2654         return (BLI_listbase_is_empty(&ob->pose->chanbase) == false);
2655 }
2656
2657 static void boundbox_armature(Object *ob, float loc[3], float size[3])
2658 {
2659         BoundBox *bb;
2660         float min[3], max[3];
2661         float mloc[3], msize[3];
2662
2663         if (ob->bb == NULL)
2664                 ob->bb = MEM_callocN(sizeof(BoundBox), "Armature boundbox");
2665         bb = ob->bb;
2666
2667         if (!loc)
2668                 loc = mloc;
2669         if (!size)
2670                 size = msize;
2671
2672         INIT_MINMAX(min, max);
2673         if (!minmax_armature(ob, min, max)) {
2674                 min[0] = min[1] = min[2] = -1.0f;
2675                 max[0] = max[1] = max[2] = 1.0f;
2676         }
2677
2678         mid_v3_v3v3(loc, min, max);
2679
2680         size[0] = (max[0] - min[0]) / 2.0f;
2681         size[1] = (max[1] - min[1]) / 2.0f;
2682         size[2] = (max[2] - min[2]) / 2.0f;
2683
2684         BKE_boundbox_init_from_minmax(bb, min, max);
2685 }
2686
2687 BoundBox *BKE_armature_boundbox_get(Object *ob)
2688 {
2689         boundbox_armature(ob, NULL, NULL);
2690
2691         return ob->bb;
2692 }