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