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