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