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