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