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