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