2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
23 * ***** END GPL LICENSE BLOCK *****
26 /** \file blender/blenkernel/intern/armature.c
38 #include "MEM_guardedalloc.h"
41 #include "BLI_listbase.h"
42 #include "BLI_string.h"
43 #include "BLI_ghash.h"
45 #include "BLI_utildefines.h"
47 #include "DNA_anim_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_constraint_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_lattice_types.h"
52 #include "DNA_listBase.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_object_types.h"
57 #include "BKE_animsys.h"
58 #include "BKE_armature.h"
59 #include "BKE_action.h"
61 #include "BKE_constraint.h"
62 #include "BKE_curve.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_deform.h"
65 #include "BKE_displist.h"
66 #include "BKE_global.h"
67 #include "BKE_idprop.h"
68 #include "BKE_library.h"
69 #include "BKE_library_query.h"
70 #include "BKE_library_remap.h"
71 #include "BKE_lattice.h"
73 #include "BKE_object.h"
74 #include "BKE_scene.h"
77 #include "BKE_sketch.h"
79 /* **************** Generic Functions, data level *************** */
81 bArmature *BKE_armature_add(Main *bmain, const char *name)
85 arm = BKE_libblock_alloc(bmain, ID_AR, name);
86 arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
87 arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
93 bArmature *BKE_armature_from_object(Object *ob)
95 if (ob->type == OB_ARMATURE)
96 return (bArmature *)ob->data;
100 int BKE_armature_bonelist_count(ListBase *lb)
103 for (Bone *bone = lb->first; bone; bone = bone->next) {
104 i += 1 + BKE_armature_bonelist_count(&bone->childbase);
110 void BKE_armature_bonelist_free(ListBase *lb)
114 for (bone = lb->first; bone; bone = bone->next) {
116 IDP_FreeProperty(bone->prop);
117 MEM_freeN(bone->prop);
119 BKE_armature_bonelist_free(&bone->childbase);
125 /** Free (or release) any data used by this armature (does not free the armature itself). */
126 void BKE_armature_free(bArmature *arm)
128 BKE_animdata_free(&arm->id, false);
130 BKE_armature_bonelist_free(&arm->bonebase);
132 /* free editmode data */
134 BLI_freelistN(arm->edbo);
136 MEM_freeN(arm->edbo);
142 freeSketch(arm->sketch);
147 void BKE_armature_make_local(Main *bmain, bArmature *arm, const bool lib_local)
149 BKE_id_make_local_generic(bmain, &arm->id, true, lib_local);
152 static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone)
154 Bone *curBone, *newChildBone;
156 if (oldBone == actBone)
157 *newActBone = newBone;
160 newBone->prop = IDP_CopyProperty(oldBone->prop);
162 /* Copy this bone's list */
163 BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
165 /* For each child in the list, update it's children */
166 newChildBone = newBone->childbase.first;
167 for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) {
168 newChildBone->parent = newBone;
169 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
170 newChildBone = newChildBone->next;
174 bArmature *BKE_armature_copy(Main *bmain, bArmature *arm)
177 Bone *oldBone, *newBone;
178 Bone *newActBone = NULL;
180 newArm = BKE_libblock_copy(bmain, &arm->id);
181 BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
183 /* Duplicate the childrens' lists */
184 newBone = newArm->bonebase.first;
185 for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) {
186 newBone->parent = NULL;
187 copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone);
188 newBone = newBone->next;
191 newArm->act_bone = newActBone;
194 newArm->act_edbone = NULL;
195 newArm->sketch = NULL;
197 BKE_id_copy_ensure_local(bmain, &arm->id, &newArm->id);
202 static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name)
204 Bone *curBone, *rbone;
206 for (curBone = lb->first; curBone; curBone = curBone->next) {
207 if (STREQ(curBone->name, name))
210 rbone = get_named_bone_bonechildren(&curBone->childbase, name);
220 * Walk the list until the bone is found (slow!),
221 * use #BKE_armature_bone_from_name_map for multiple lookups.
223 Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
228 return get_named_bone_bonechildren(&arm->bonebase, name);
231 static void armature_bone_from_name_insert_recursive(GHash *bone_hash, ListBase *lb)
233 for (Bone *bone = lb->first; bone; bone = bone->next) {
234 BLI_ghash_insert(bone_hash, bone->name, bone);
235 armature_bone_from_name_insert_recursive(bone_hash, &bone->childbase);
240 * Create a (name -> bone) map.
242 * \note typically #bPose.chanhash us used via #BKE_pose_channel_find_name
243 * this is for the cases we can't use pose channels.
245 GHash *BKE_armature_bone_from_name_map(bArmature *arm)
247 const int bones_count = BKE_armature_bonelist_count(&arm->bonebase);
248 GHash *bone_hash = BLI_ghash_str_new_ex(__func__, bones_count);
249 armature_bone_from_name_insert_recursive(bone_hash, &arm->bonebase);
253 bool BKE_armature_bone_flag_test_recursive(const Bone *bone, int flag)
255 if (bone->flag & flag) {
258 else if (bone->parent) {
259 return BKE_armature_bone_flag_test_recursive(bone->parent, flag);
266 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
267 * unique names afterwards) strip_number: removes number extensions (TODO: not used)
268 * axis: the axis to name on
269 * head/tail: the head/tail co-ordinate of the bone on the specified axis */
270 int bone_autoside_name(char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
273 char basename[MAXBONENAME] = "";
274 char extension[5] = "";
279 BLI_strncpy(basename, name, sizeof(basename));
281 /* Figure out extension to append:
282 * - The extension to append is based upon the axis that we are working on.
283 * - If head happens to be on 0, then we must consider the tail position as well to decide
284 * which side the bone is on
285 * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
286 * -> Otherwise, extension is added from perspective of object based on which side tail goes to
287 * - If head is non-zero, extension is added from perspective of object based on side head is on
290 /* z-axis - vertical (top/bottom) */
291 if (IS_EQF(head, 0.0f)) {
293 strcpy(extension, "Bot");
295 strcpy(extension, "Top");
299 strcpy(extension, "Bot");
301 strcpy(extension, "Top");
304 else if (axis == 1) {
305 /* y-axis - depth (front/back) */
306 if (IS_EQF(head, 0.0f)) {
308 strcpy(extension, "Fr");
310 strcpy(extension, "Bk");
314 strcpy(extension, "Fr");
316 strcpy(extension, "Bk");
320 /* x-axis - horizontal (left/right) */
321 if (IS_EQF(head, 0.0f)) {
323 strcpy(extension, "R");
325 strcpy(extension, "L");
329 strcpy(extension, "R");
330 /* XXX Shouldn't this be simple else, as for z and y axes? */
332 strcpy(extension, "L");
336 /* Simple name truncation
337 * - truncate if there is an extension and it wouldn't be able to fit
338 * - otherwise, just append to end
343 while (changed) { /* remove extensions */
345 if (len > 2 && basename[len - 2] == '.') {
346 if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
347 basename[len - 2] = '\0';
352 else if (len > 3 && basename[len - 3] == '.') {
353 if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
354 (basename[len - 2] == 'B' && basename[len - 1] == 'k')) /* Bk */
356 basename[len - 3] = '\0';
361 else if (len > 4 && basename[len - 4] == '.') {
362 if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' && basename[len - 1] == 'p') || /* Top */
363 (basename[len - 3] == 'B' && basename[len - 2] == 'o' && basename[len - 1] == 't')) /* Bot */
365 basename[len - 4] = '\0';
372 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
373 strncpy(name, basename, len - strlen(extension));
376 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
385 /* ************* B-Bone support ******************* */
387 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
388 void equalize_bbone_bezier(float *data, int desired)
390 float *fp, totdist, ddist, dist, fac1, fac2;
391 float pdist[MAX_BBONE_SUBDIV + 1];
392 float temp[MAX_BBONE_SUBDIV + 1][4];
396 for (a = 0, fp = data; a < MAX_BBONE_SUBDIV; a++, fp += 4) {
397 copy_qt_qt(temp[a], fp);
398 pdist[a + 1] = pdist[a] + len_v3v3(fp, fp + 4);
401 copy_qt_qt(temp[a], fp);
404 /* go over distances and calculate new points */
405 ddist = totdist / ((float)desired);
407 for (a = 1, fp = data + 4; a < desired; a++, fp += 4) {
408 dist = ((float)a) * ddist;
410 /* we're looking for location (distance) 'dist' in the array */
411 while ((nr < MAX_BBONE_SUBDIV) && (dist >= pdist[nr]))
414 fac1 = pdist[nr] - pdist[nr - 1];
415 fac2 = pdist[nr] - dist;
419 fp[0] = fac1 * temp[nr - 1][0] + fac2 * temp[nr][0];
420 fp[1] = fac1 * temp[nr - 1][1] + fac2 * temp[nr][1];
421 fp[2] = fac1 * temp[nr - 1][2] + fac2 * temp[nr][2];
422 fp[3] = fac1 * temp[nr - 1][3] + fac2 * temp[nr][3];
424 /* set last point, needed for orientation calculus */
425 copy_qt_qt(fp, temp[MAX_BBONE_SUBDIV]);
428 /* returns pointer to static array, filled with desired amount of bone->segments elements */
429 /* this calculation is done within unit bone space */
430 void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BBONE_SUBDIV])
432 bPoseChannel *next, *prev;
433 Bone *bone = pchan->bone;
434 float h1[3], h2[3], scale[3], length, roll1 = 0.0f, roll2;
435 float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
436 float data[MAX_BBONE_SUBDIV + 1][4], *fp;
438 bool do_scale = false;
440 length = bone->length;
443 /* check if we need to take non-uniform bone scaling into account */
444 mat4_to_size(scale, pchan->pose_mat);
446 if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
447 size_to_mat4(scalemat, scale);
448 invert_m4_m4(iscalemat, scalemat);
455 /* get "next" and "prev" bones - these are used for handle calculations */
456 if (pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) {
457 /* use the provided bones as the next/prev - leave blank to eliminate this effect altogether */
458 prev = pchan->bbone_prev;
459 next = pchan->bbone_next;
462 /* evaluate next and prev bones */
463 if (bone->flag & BONE_CONNECTED)
464 prev = pchan->parent;
471 /* find the handle points, since this is inside bone space, the
472 * first point = (0, 0, 0)
473 * last point = (0, length, 0) */
475 invert_m4_m4(imat, pchan->bone->arm_mat);
478 copy_m4_m4(posemat, pchan->pose_mat);
479 normalize_m4(posemat);
480 invert_m4_m4(imat, posemat);
483 invert_m4_m4(imat, pchan->pose_mat);
486 float difmat[4][4], result[3][3], imat3[3][3];
488 /* transform previous point inside this bone space */
489 if ((pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) &&
490 (pchan->bboneflag & PCHAN_BBONE_CUSTOM_START_REL))
492 /* Use delta movement (from restpose), and apply this relative to the current bone's head */
494 /* in restpose, arm_head == pose_head */
495 h1[0] = h1[1] = h1[2] = 0.0f;
499 sub_v3_v3v3(delta, prev->pose_head, prev->bone->arm_head);
500 sub_v3_v3v3(h1, pchan->pose_head, delta);
504 /* Use bone head as absolute position */
506 copy_v3_v3(h1, prev->bone->arm_head);
508 copy_v3_v3(h1, prev->pose_head);
512 if (prev->bone->segments > 1) {
513 /* if previous bone is B-bone too, use average handle direction */
521 if (prev->bone->segments == 1) {
522 /* find the previous roll to interpolate */
524 mul_m4_m4m4(difmat, imat, prev->bone->arm_mat);
526 mul_m4_m4m4(difmat, imat, prev->pose_mat);
527 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
529 vec_roll_to_mat3(h1, 0.0f, mat3); /* the result of vec_roll without roll */
531 invert_m3_m3(imat3, mat3);
532 mul_m3_m3m3(mat3, result, imat3); /* the matrix transforming vec_roll to desired roll */
534 roll1 = atan2f(mat3[2][0], mat3[2][2]);
538 h1[0] = 0.0f; h1[1] = 1.0; h1[2] = 0.0f;
542 float difmat[4][4], result[3][3], imat3[3][3];
544 /* transform next point inside this bone space */
545 if ((pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) &&
546 (pchan->bboneflag & PCHAN_BBONE_CUSTOM_END_REL))
548 /* Use delta movement (from restpose), and apply this relative to the current bone's tail */
550 /* in restpose, arm_tail == pose_tail */
551 h2[0] = h2[1] = h2[2] = 0.0f;
555 sub_v3_v3v3(delta, next->pose_tail, next->bone->arm_tail);
556 add_v3_v3v3(h2, pchan->pose_tail, delta);
560 /* Use bone tail as absolute position */
562 copy_v3_v3(h2, next->bone->arm_tail);
564 copy_v3_v3(h2, next->pose_tail);
568 /* if next bone is B-bone too, use average handle direction */
569 if (next->bone->segments > 1) {
577 /* find the next roll to interpolate as well */
579 mul_m4_m4m4(difmat, imat, next->bone->arm_mat);
581 mul_m4_m4m4(difmat, imat, next->pose_mat);
582 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
584 vec_roll_to_mat3(h2, 0.0f, mat3); /* the result of vec_roll without roll */
586 invert_m3_m3(imat3, mat3);
587 mul_m3_m3m3(mat3, imat3, result); /* the matrix transforming vec_roll to desired roll */
589 roll2 = atan2f(mat3[2][0], mat3[2][2]);
593 h2[0] = 0.0f; h2[1] = 1.0f; h2[2] = 0.0f;
598 const float circle_factor = length * (cubic_tangent_factor_circle_v3(h1, h2) / 0.75f);
600 const float hlength1 = bone->ease1 * circle_factor;
601 const float hlength2 = bone->ease2 * circle_factor;
603 /* and only now negate h2 */
604 mul_v3_fl(h1, hlength1);
605 mul_v3_fl(h2, -hlength2);
608 /* Add effects from bbone properties over the top
609 * - These properties allow users to hand-animate the
610 * bone curve/shape, without having to resort to using
612 * - The "bone" level offsets are for defining the restpose
613 * shape of the bone (e.g. for curved eyebrows for example).
614 * -> In the viewport, it's needed to define what the rest pose
616 * -> For "rest == 0", we also still need to have it present
617 * so that we can "cancel out" this restpose when it comes
618 * time to deform some geometry, it won't cause double transforms.
619 * - The "pchan" level offsets are the ones that animators actually
623 /* add extra rolls */
624 roll1 += bone->roll1 + (!rest ? pchan->roll1 : 0.0f);
625 roll2 += bone->roll2 + (!rest ? pchan->roll2 : 0.0f);
627 if (bone->flag & BONE_ADD_PARENT_END_ROLL) {
630 roll1 += prev->bone->roll2;
633 roll1 += prev->roll2;
637 /* extra curve x / y */
638 /* NOTE: Scale correction factors here are to compensate for some random floating-point glitches
639 * when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results
640 * in the bone length getting scaled up too (from 1 to 8), causing the curve to flatten out.
642 const float xscale_correction = (do_scale) ? scale[0] : 1.0f;
643 const float yscale_correction = (do_scale) ? scale[2] : 1.0f;
645 h1[0] += (bone->curveInX + (!rest ? pchan->curveInX : 0.0f)) * xscale_correction;
646 h1[2] += (bone->curveInY + (!rest ? pchan->curveInY : 0.0f)) * yscale_correction;
648 h2[0] += (bone->curveOutX + (!rest ? pchan->curveOutX : 0.0f)) * xscale_correction;
649 h2[2] += (bone->curveOutY + (!rest ? pchan->curveOutY : 0.0f)) * yscale_correction;
653 if (bone->segments > MAX_BBONE_SUBDIV)
654 bone->segments = MAX_BBONE_SUBDIV;
656 BKE_curve_forward_diff_bezier(0.0f, h1[0], h2[0], 0.0f, data[0], MAX_BBONE_SUBDIV, 4 * sizeof(float));
657 BKE_curve_forward_diff_bezier(0.0f, h1[1], length + h2[1], length, data[0] + 1, MAX_BBONE_SUBDIV, 4 * sizeof(float));
658 BKE_curve_forward_diff_bezier(0.0f, h1[2], h2[2], 0.0f, data[0] + 2, MAX_BBONE_SUBDIV, 4 * sizeof(float));
659 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));
661 equalize_bbone_bezier(data[0], bone->segments); /* note: does stride 4! */
663 /* make transformation matrices for the segments for drawing */
664 for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) {
665 sub_v3_v3v3(h1, fp + 4, fp);
666 vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */
668 copy_m4_m3(result_array[a].mat, mat3);
669 copy_v3_v3(result_array[a].mat[3], fp);
672 /* correct for scaling when this matrix is used in scaled space */
673 mul_m4_series(result_array[a].mat, iscalemat, result_array[a].mat, scalemat);
678 const int num_segments = bone->segments;
680 const float scaleIn = bone->scaleIn * (!rest ? pchan->scaleIn : 1.0f);
681 const float scaleFactorIn = 1.0f + (scaleIn - 1.0f) * ((float)(num_segments - a) / (float)num_segments);
683 const float scaleOut = bone->scaleOut * (!rest ? pchan->scaleOut : 1.0f);
684 const float scaleFactorOut = 1.0f + (scaleOut - 1.0f) * ((float)(a + 1) / (float)num_segments);
686 const float scalefac = scaleFactorIn * scaleFactorOut;
687 float bscalemat[4][4], bscale[3];
689 bscale[0] = scalefac;
691 bscale[2] = scalefac;
693 size_to_mat4(bscalemat, bscale);
695 /* Note: don't multiply by inverse scale mat here, as it causes problems with scaling shearing and breaking segment chains */
696 /*mul_m4_series(result_array[a].mat, ibscalemat, result_array[a].mat, bscalemat);*/
697 mul_m4_series(result_array[a].mat, result_array[a].mat, bscalemat);
703 /* ************ Armature Deform ******************* */
705 typedef struct bPoseChanDeform {
708 DualQuat *b_bone_dual_quats;
711 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, const bool use_quaternion)
713 Bone *bone = pchan->bone;
714 Mat4 b_bone[MAX_BBONE_SUBDIV], b_bone_rest[MAX_BBONE_SUBDIV];
716 DualQuat *b_bone_dual_quats = NULL;
719 b_bone_spline_setup(pchan, 0, b_bone);
720 b_bone_spline_setup(pchan, 1, b_bone_rest);
722 /* allocate b_bone matrices and dual quats */
723 b_bone_mats = MEM_mallocN((1 + bone->segments) * sizeof(Mat4), "BBone defmats");
724 pdef_info->b_bone_mats = b_bone_mats;
726 if (use_quaternion) {
727 b_bone_dual_quats = MEM_mallocN((bone->segments) * sizeof(DualQuat), "BBone dqs");
728 pdef_info->b_bone_dual_quats = b_bone_dual_quats;
731 /* first matrix is the inverse arm_mat, to bring points in local bone space
732 * for finding out which segment it belongs to */
733 invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
735 /* then we make the b_bone_mats:
736 * - first transform to local bone space
737 * - translate over the curve to the bbone mat space
738 * - transform with b_bone matrix
739 * - transform back into global space */
741 for (a = 0; a < bone->segments; a++) {
744 invert_m4_m4(tmat, b_bone_rest[a].mat);
745 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);
748 mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
752 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], DualQuat *dq, float defmat[3][3])
754 Mat4 *b_bone = pdef_info->b_bone_mats;
755 float (*mat)[4] = b_bone[0].mat;
759 /* need to transform co back to bonespace, only need y */
760 y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1];
762 /* now calculate which of the b_bones are deforming this */
763 segment = bone->length / ((float)bone->segments);
764 a = (int)(y / segment);
766 /* note; by clamping it extends deform at endpoints, goes best with
767 * straight joints in restpos. */
768 CLAMP(a, 0, bone->segments - 1);
771 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
774 mul_m4_v3(b_bone[a + 1].mat, co);
777 copy_m3_m4(defmat, b_bone[a + 1].mat);
782 /* using vec with dist to bone b1 - b2 */
783 float distfactor_to_bone(const float vec[3], const float b1[3], const float b2[3], float rad1, float rad2, float rdist)
788 float hsqr, a, l, rad;
790 sub_v3_v3v3(bdelta, b2, b1);
791 l = normalize_v3(bdelta);
793 sub_v3_v3v3(pdelta, vec, b1);
795 a = dot_v3v3(bdelta, pdelta);
796 hsqr = len_squared_v3(pdelta);
799 /* If we're past the end of the bone, do a spherical field attenuation thing */
800 dist_sq = len_squared_v3v3(b1, vec);
804 /* If we're past the end of the bone, do a spherical field attenuation thing */
805 dist_sq = len_squared_v3v3(b2, vec);
809 dist_sq = (hsqr - (a * a));
813 rad = rad * rad2 + (1.0f - rad) * rad1;
825 if (rdist == 0.0f || dist_sq >= l)
828 a = sqrtf(dist_sq) - rad;
829 return 1.0f - (a * a) / (rdist * rdist);
834 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[3][3], float mat[3][3])
838 if (pchan->bone->segments > 1)
839 copy_m3_m3(wmat, bbonemat);
841 copy_m3_m4(wmat, pchan->chan_mat);
843 mul_m3_fl(wmat, weight);
844 add_m3_m3m3(mat, mat, wmat);
847 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float vec[3], DualQuat *dq,
848 float mat[3][3], const float co[3])
850 Bone *bone = pchan->bone;
851 float fac, contrib = 0.0;
852 float cop[3], bbonemat[3][3];
860 fac = distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
865 if (contrib > 0.0f) {
867 if (bone->segments > 1)
868 /* applies on cop and bbonemat */
869 b_bone_deform(pdef_info, bone, cop, NULL, (mat) ? bbonemat : NULL);
871 mul_m4_v3(pchan->chan_mat, cop);
873 /* Make this a delta from the base position */
875 madd_v3_v3fl(vec, cop, fac);
878 pchan_deform_mat_add(pchan, fac, bbonemat, mat);
881 if (bone->segments > 1) {
882 b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
883 add_weighted_dq_dq(dq, &bbonedq, fac);
886 add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
894 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq,
895 float mat[3][3], const float co[3], float *contrib)
897 float cop[3], bbonemat[3][3];
906 if (pchan->bone->segments > 1)
907 /* applies on cop and bbonemat */
908 b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat) ? bbonemat : NULL);
910 mul_m4_v3(pchan->chan_mat, cop);
912 vec[0] += (cop[0] - co[0]) * weight;
913 vec[1] += (cop[1] - co[1]) * weight;
914 vec[2] += (cop[2] - co[2]) * weight;
917 pchan_deform_mat_add(pchan, weight, bbonemat, mat);
920 if (pchan->bone->segments > 1) {
921 b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
922 add_weighted_dq_dq(dq, &bbonedq, weight);
925 add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
928 (*contrib) += weight;
931 typedef struct ArmatureBBoneDefmatsData {
932 bPoseChanDeform *pdef_info_array;
935 } ArmatureBBoneDefmatsData;
937 static void armature_bbone_defmats_cb(void *userdata, Link *iter, int index)
939 ArmatureBBoneDefmatsData *data = userdata;
940 bPoseChannel *pchan = (bPoseChannel *)iter;
942 if (!(pchan->bone->flag & BONE_NO_DEFORM)) {
943 bPoseChanDeform *pdef_info = &data->pdef_info_array[index];
944 const bool use_quaternion = data->use_quaternion;
946 if (pchan->bone->segments > 1) {
947 pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
950 if (use_quaternion) {
951 pdef_info->dual_quat = &data->dualquats[index];
952 mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat);
957 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3],
958 float (*defMats)[3][3], int numVerts, int deformflag,
959 float (*prevCos)[3], const char *defgrp_name)
961 bPoseChanDeform *pdef_info_array;
962 bPoseChanDeform *pdef_info = NULL;
963 bArmature *arm = armOb->data;
964 bPoseChannel *pchan, **defnrToPC = NULL;
965 int *defnrToPCIndex = NULL;
966 MDeformVert *dverts = NULL;
968 DualQuat *dualquats = NULL;
969 float obinv[4][4], premat[4][4], postmat[4][4];
970 const bool use_envelope = (deformflag & ARM_DEF_ENVELOPE) != 0;
971 const bool use_quaternion = (deformflag & ARM_DEF_QUATERNION) != 0;
972 const bool invert_vgroup = (deformflag & ARM_DEF_INVERT_VGROUP) != 0;
973 int defbase_tot = 0; /* safety for vertexgroup index overflow */
974 int i, target_totvert = 0; /* safety for vertexgroup overflow */
975 bool use_dverts = false;
979 /* in editmode, or not an armature */
980 if (arm->edbo || (armOb->pose == NULL)) {
984 invert_m4_m4(obinv, target->obmat);
985 copy_m4_m4(premat, target->obmat);
986 mul_m4_m4m4(postmat, obinv, armOb->obmat);
987 invert_m4_m4(premat, postmat);
989 /* bone defmats are already in the channels, chan_mat */
991 /* initialize B_bone matrices and dual quaternions */
992 totchan = BLI_listbase_count(&armOb->pose->chanbase);
994 if (use_quaternion) {
995 dualquats = MEM_callocN(sizeof(DualQuat) * totchan, "dualquats");
998 pdef_info_array = MEM_callocN(sizeof(bPoseChanDeform) * totchan, "bPoseChanDeform");
1000 ArmatureBBoneDefmatsData data = {
1001 .pdef_info_array = pdef_info_array, .dualquats = dualquats, .use_quaternion = use_quaternion
1003 BLI_task_parallel_listbase(&armOb->pose->chanbase, &data, armature_bbone_defmats_cb, totchan > 512);
1005 /* get the def_nr for the overall armature vertex group if present */
1006 armature_def_nr = defgroup_name_index(target, defgrp_name);
1008 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
1009 defbase_tot = BLI_listbase_count(&target->defbase);
1011 if (target->type == OB_MESH) {
1012 Mesh *me = target->data;
1015 target_totvert = me->totvert;
1018 Lattice *lt = target->data;
1021 target_totvert = lt->pntsu * lt->pntsv * lt->pntsw;
1025 /* get a vertex-deform-index to posechannel array */
1026 if (deformflag & ARM_DEF_VGROUP) {
1027 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
1028 /* if we have a DerivedMesh, only use dverts if it has them */
1030 use_dverts = (dm->getVertDataArray(dm, CD_MDEFORMVERT) != NULL);
1037 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone");
1038 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex");
1039 /* TODO(sergey): Some considerations here:
1041 * - Make it more generic function, maybe even keep together with chanhash.
1042 * - Check whether keeping this consistent across frames gives speedup.
1043 * - Don't use hash for small armatures.
1045 GHash *idx_hash = BLI_ghash_ptr_new("pose channel index by name");
1046 int pchan_index = 0;
1047 for (pchan = armOb->pose->chanbase.first; pchan != NULL; pchan = pchan->next, ++pchan_index) {
1048 BLI_ghash_insert(idx_hash, pchan, SET_INT_IN_POINTER(pchan_index));
1050 for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) {
1051 defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name);
1052 /* exclude non-deforming bones */
1054 if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
1055 defnrToPC[i] = NULL;
1058 defnrToPCIndex[i] = GET_INT_FROM_POINTER(BLI_ghash_lookup(idx_hash, defnrToPC[i]));
1062 BLI_ghash_free(idx_hash, NULL, NULL);
1067 for (i = 0; i < numVerts; i++) {
1069 DualQuat sumdq, *dq = NULL;
1071 float sumvec[3], summat[3][3];
1072 float *vec = NULL, (*smat)[3] = NULL;
1073 float contrib = 0.0f;
1074 float armature_weight = 1.0f; /* default to 1 if no overall def group */
1075 float prevco_weight = 1.0f; /* weight for optional cached vertexcos */
1077 if (use_quaternion) {
1078 memset(&sumdq, 0, sizeof(DualQuat));
1082 sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
1091 if (use_dverts || armature_def_nr != -1) {
1093 dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
1094 else if (dverts && i < target_totvert)
1102 if (armature_def_nr != -1 && dvert) {
1103 armature_weight = defvert_find_weight(dvert, armature_def_nr);
1106 armature_weight = 1.0f - armature_weight;
1108 /* hackish: the blending factor can be used for blending with prevCos too */
1110 prevco_weight = armature_weight;
1111 armature_weight = 1.0f;
1115 /* check if there's any point in calculating for this vert */
1116 if (armature_weight == 0.0f)
1119 /* get the coord we work on */
1120 co = prevCos ? prevCos[i] : vertexCos[i];
1122 /* Apply the object's matrix */
1123 mul_m4_v3(premat, co);
1125 if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */
1126 MDeformWeight *dw = dvert->dw;
1130 for (j = dvert->totweight; j != 0; j--, dw++) {
1131 const int index = dw->def_nr;
1132 if (index >= 0 && index < defbase_tot && (pchan = defnrToPC[index])) {
1133 float weight = dw->weight;
1134 Bone *bone = pchan->bone;
1135 pdef_info = pdef_info_array + defnrToPCIndex[index];
1139 if (bone && bone->flag & BONE_MULT_VG_ENV) {
1140 weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
1141 bone->rad_head, bone->rad_tail, bone->dist);
1143 pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
1146 /* if there are vertexgroups but not groups with bones
1147 * (like for softbody groups) */
1148 if (deformed == 0 && use_envelope) {
1149 pdef_info = pdef_info_array;
1150 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1151 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1152 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1156 else if (use_envelope) {
1157 pdef_info = pdef_info_array;
1158 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1159 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1160 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1164 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1165 if (contrib > 0.0001f) {
1166 if (use_quaternion) {
1167 normalize_dq(dq, contrib);
1169 if (armature_weight != 1.0f) {
1170 copy_v3_v3(dco, co);
1171 mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq);
1173 mul_v3_fl(dco, armature_weight);
1177 mul_v3m3_dq(co, (defMats) ? summat : NULL, dq);
1182 mul_v3_fl(vec, armature_weight / contrib);
1183 add_v3_v3v3(co, vec, co);
1187 float pre[3][3], post[3][3], tmpmat[3][3];
1189 copy_m3_m4(pre, premat);
1190 copy_m3_m4(post, postmat);
1191 copy_m3_m3(tmpmat, defMats[i]);
1193 if (!use_quaternion) /* quaternion already is scale corrected */
1194 mul_m3_fl(smat, armature_weight / contrib);
1196 mul_m3_series(defMats[i], post, smat, pre, tmpmat);
1200 /* always, check above code */
1201 mul_m4_v3(postmat, co);
1203 /* interpolate with previous modifier position using weight group */
1205 float mw = 1.0f - prevco_weight;
1206 vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0];
1207 vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1];
1208 vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2];
1213 MEM_freeN(dualquats);
1215 MEM_freeN(defnrToPC);
1217 MEM_freeN(defnrToPCIndex);
1219 /* free B_bone matrices */
1220 pdef_info = pdef_info_array;
1221 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1222 if (pdef_info->b_bone_mats)
1223 MEM_freeN(pdef_info->b_bone_mats);
1224 if (pdef_info->b_bone_dual_quats)
1225 MEM_freeN(pdef_info->b_bone_dual_quats);
1228 MEM_freeN(pdef_info_array);
1231 /* ************ END Armature Deform ******************* */
1233 void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[4][4], int UNUSED(root),
1236 copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1239 /* **************** Space to Space API ****************** */
1241 /* Convert World-Space Matrix to Pose-Space Matrix */
1242 void BKE_armature_mat_world_to_pose(Object *ob, float inmat[4][4], float outmat[4][4])
1246 /* prevent crashes */
1250 /* get inverse of (armature) object's matrix */
1251 invert_m4_m4(obmat, ob->obmat);
1253 /* multiply given matrix by object's-inverse to find pose-space matrix */
1254 mul_m4_m4m4(outmat, inmat, obmat);
1257 /* Convert World-Space Location to Pose-Space Location
1258 * NOTE: this cannot be used to convert to pose-space location of the supplied
1259 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1260 void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
1262 float xLocMat[4][4];
1263 float nLocMat[4][4];
1265 /* build matrix for location */
1267 copy_v3_v3(xLocMat[3], inloc);
1269 /* get bone-space cursor matrix and extract location */
1270 BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1271 copy_v3_v3(outloc, nLocMat[3]);
1274 /* Simple helper, computes the offset bone matrix.
1275 * offs_bone = yoffs(b-1) + root(b) + bonemat(b).
1276 * Not exported, as it is only used in this file currently... */
1277 static void get_offset_bone_mat(Bone *bone, float offs_bone[4][4])
1279 BLI_assert(bone->parent != NULL);
1281 /* Bone transform itself. */
1282 copy_m4_m3(offs_bone, bone->bone_mat);
1284 /* The bone's root offset (is in the parent's coordinate system). */
1285 copy_v3_v3(offs_bone[3], bone->head);
1287 /* Get the length translation of parent (length along y axis). */
1288 offs_bone[3][1] += bone->parent->length;
1291 /* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space.
1292 * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
1293 * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1296 * This allows to get the transformations of a bone in its object space, *before* constraints (and IK)
1297 * get applied (used by pose evaluation code).
1298 * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
1299 * in object space (used by interactive transform, and snapping code).
1301 * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
1302 * will differ from the rotation/scale matrix...
1304 * NOTE: This cannot be used to convert to pose-space transforms of the supplied
1305 * pose-channel into its local space (i.e. 'visual'-keyframing).
1306 * (note: I don't understand that, so I keep it :p --mont29).
1308 void BKE_pchan_to_pose_mat(bPoseChannel *pchan, float rotscale_mat[4][4], float loc_mat[4][4])
1310 Bone *bone, *parbone;
1311 bPoseChannel *parchan;
1313 /* set up variables for quicker access below */
1315 parbone = bone->parent;
1316 parchan = pchan->parent;
1319 float offs_bone[4][4];
1320 /* yoffs(b-1) + root(b) + bonemat(b). */
1321 get_offset_bone_mat(bone, offs_bone);
1323 /* Compose the rotscale matrix for this bone. */
1324 if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) {
1325 /* Parent rest rotation and scale. */
1326 mul_m4_m4m4(rotscale_mat, parbone->arm_mat, offs_bone);
1328 else if (bone->flag & BONE_HINGE) {
1329 /* Parent rest rotation and pose scale. */
1330 float tmat[4][4], tscale[3];
1332 /* Extract the scale of the parent pose matrix. */
1333 mat4_to_size(tscale, parchan->pose_mat);
1334 size_to_mat4(tmat, tscale);
1336 /* Applies the parent pose scale to the rest matrix. */
1337 mul_m4_m4m4(tmat, tmat, parbone->arm_mat);
1339 mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1341 else if (bone->flag & BONE_NO_SCALE) {
1342 /* Parent pose rotation and rest scale (i.e. no scaling). */
1344 copy_m4_m4(tmat, parchan->pose_mat);
1346 mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1349 mul_m4_m4m4(rotscale_mat, parchan->pose_mat, offs_bone);
1351 /* Compose the loc matrix for this bone. */
1352 /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
1354 /* In this case, use the object's space *orientation*. */
1355 if (bone->flag & BONE_NO_LOCAL_LOCATION) {
1356 /* XXX I'm sure that code can be simplified! */
1357 float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
1362 mul_v3_m4v3(bone_loc[3], parchan->pose_mat, offs_bone[3]);
1364 unit_m3(bone_rotscale);
1365 copy_m3_m4(tmat3, parchan->pose_mat);
1366 mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
1368 copy_m4_m3(tmat4, bone_rotscale);
1369 mul_m4_m4m4(loc_mat, bone_loc, tmat4);
1371 /* Those flags do not affect position, use plain parent transform space! */
1372 else if (bone->flag & (BONE_HINGE | BONE_NO_SCALE)) {
1373 mul_m4_m4m4(loc_mat, parchan->pose_mat, offs_bone);
1375 /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */
1377 copy_m4_m4(loc_mat, rotscale_mat);
1381 /* Rotation/scaling. */
1382 copy_m4_m4(rotscale_mat, pchan->bone->arm_mat);
1384 if (pchan->bone->flag & BONE_NO_LOCAL_LOCATION) {
1385 /* Translation of arm_mat, without the rotation. */
1387 copy_v3_v3(loc_mat[3], pchan->bone->arm_mat[3]);
1390 copy_m4_m4(loc_mat, rotscale_mat);
1394 /* Convert Pose-Space Matrix to Bone-Space Matrix.
1395 * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1396 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1397 void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1399 float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1401 /* Security, this allows to call with inmat == outmat! */
1402 copy_m4_m4(inmat_, inmat);
1404 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1405 invert_m4(rotscale_mat);
1408 mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1409 mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1412 /* Convert Bone-Space Matrix to Pose-Space Matrix. */
1413 void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1415 float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1417 /* Security, this allows to call with inmat == outmat! */
1418 copy_m4_m4(inmat_, inmat);
1420 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1422 mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1423 mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1426 /* Convert Pose-Space Location to Bone-Space Location
1427 * NOTE: this cannot be used to convert to pose-space location of the supplied
1428 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1429 void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
1431 float xLocMat[4][4];
1432 float nLocMat[4][4];
1434 /* build matrix for location */
1436 copy_v3_v3(xLocMat[3], inloc);
1438 /* get bone-space cursor matrix and extract location */
1439 BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1440 copy_v3_v3(outloc, nLocMat[3]);
1443 void BKE_armature_mat_pose_to_bone_ex(Object *ob, bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1445 bPoseChannel work_pchan = *pchan;
1447 /* recalculate pose matrix with only parent transformations,
1448 * bone loc/sca/rot is ignored, scene and frame are not used. */
1449 BKE_pose_where_is_bone(NULL, ob, &work_pchan, 0.0f, false);
1451 /* find the matrix, need to remove the bone transforms first so this is
1452 * calculated as a matrix to set rather then a difference ontop of whats
1455 BKE_pchan_apply_mat4(&work_pchan, outmat, false);
1457 BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
1460 /* same as BKE_object_mat3_to_rot() */
1461 void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[3][3], bool use_compat)
1463 BLI_ASSERT_UNIT_M3(mat);
1465 switch (pchan->rotmode) {
1467 mat3_normalized_to_quat(pchan->quat, mat);
1469 case ROT_MODE_AXISANGLE:
1470 mat3_normalized_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1472 default: /* euler */
1474 mat3_normalized_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1476 mat3_normalized_to_eulO(pchan->eul, pchan->rotmode, mat);
1481 /* Apply a 4x4 matrix to the pose bone,
1482 * similar to BKE_object_apply_mat4() */
1483 void BKE_pchan_apply_mat4(bPoseChannel *pchan, float mat[4][4], bool use_compat)
1486 mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1487 BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
1490 /* Remove rest-position effects from pose-transform for obtaining
1491 * 'visual' transformation of pose-channel.
1492 * (used by the Visual-Keyframing stuff) */
1493 void BKE_armature_mat_pose_to_delta(float delta_mat[4][4], float pose_mat[4][4], float arm_mat[4][4])
1497 invert_m4_m4(imat, arm_mat);
1498 mul_m4_m4m4(delta_mat, imat, pose_mat);
1501 /* **************** Rotation Mode Conversions ****************************** */
1502 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1504 /* Called from RNA when rotation mode changes
1505 * - the result should be that the rotations given in the provided pointers have had conversions
1506 * applied (as appropriate), such that the rotation of the element hasn't 'visually' changed */
1507 void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1509 /* check if any change - if so, need to convert data */
1510 if (newMode > 0) { /* to euler */
1511 if (oldMode == ROT_MODE_AXISANGLE) {
1512 /* axis-angle to euler */
1513 axis_angle_to_eulO(eul, newMode, axis, *angle);
1515 else if (oldMode == ROT_MODE_QUAT) {
1518 quat_to_eulO(eul, newMode, quat);
1520 /* else { no conversion needed } */
1522 else if (newMode == ROT_MODE_QUAT) { /* to quat */
1523 if (oldMode == ROT_MODE_AXISANGLE) {
1524 /* axis angle to quat */
1525 axis_angle_to_quat(quat, axis, *angle);
1527 else if (oldMode > 0) {
1529 eulO_to_quat(quat, eul, oldMode);
1531 /* else { no conversion needed } */
1533 else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1535 /* euler to axis angle */
1536 eulO_to_axis_angle(axis, angle, eul, oldMode);
1538 else if (oldMode == ROT_MODE_QUAT) {
1539 /* quat to axis angle */
1541 quat_to_axis_angle(axis, angle, quat);
1544 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1545 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1546 /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1552 /* **************** The new & simple (but OK!) armature evaluation ********* */
1554 /* ****************** And how it works! ****************************************
1556 * This is the bone transformation trick; they're hierarchical so each bone(b)
1557 * is in the coord system of bone(b-1):
1559 * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
1561 * -> yoffs is just the y axis translation in parent's coord system
1562 * -> d_root is the translation of the bone root, also in parent's coord system
1564 * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1566 * we then - in init deform - store the deform in chan_mat, such that:
1568 * pose_mat(b)= arm_mat(b) * chan_mat(b)
1570 * *************************************************************************** */
1572 /* Computes vector and roll based on a rotation.
1573 * "mat" must contain only a rotation, and no scaling. */
1574 void mat3_to_vec_roll(float mat[3][3], float r_vec[3], float *r_roll)
1577 copy_v3_v3(r_vec, mat[1]);
1581 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1583 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1584 invert_m3_m3(vecmatinv, vecmat);
1585 mul_m3_m3m3(rollmat, vecmatinv, mat);
1587 *r_roll = atan2f(rollmat[2][0], rollmat[2][2]);
1591 /* Calculates the rest matrix of a bone based on its vector and a roll around that vector. */
1592 /* Given v = (v.x, v.y, v.z) our (normalized) bone vector, we want the rotation matrix M
1593 * from the Y axis (so that M * (0, 1, 0) = v).
1594 * -> The rotation axis a lays on XZ plane, and it is orthonormal to v, hence to the projection of v onto XZ plane.
1595 * -> a = (v.z, 0, -v.x)
1596 * We know a is eigenvector of M (so M * a = a).
1597 * Finally, we have w, such that M * w = (0, 1, 0) (i.e. the vector that will be aligned with Y axis once transformed).
1598 * We know w is symmetric to v by the Y axis.
1599 * -> w = (-v.x, v.y, -v.z)
1601 * Solving this, we get (x, y and z being the components of v):
1602 * ┌ (x^2 * y + z^2) / (x^2 + z^2), x, x * z * (y - 1) / (x^2 + z^2) ┐
1603 * M = │ x * (y^2 - 1) / (x^2 + z^2), y, z * (y^2 - 1) / (x^2 + z^2) │
1604 * └ x * z * (y - 1) / (x^2 + z^2), z, (x^2 + z^2 * y) / (x^2 + z^2) ┘
1606 * This is stable as long as v (the bone) is not too much aligned with +/-Y (i.e. x and z components
1607 * are not too close to 0).
1609 * 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).
1610 * This allows to simplifies M like this:
1611 * ┌ 1 - x^2 / (1 + y), x, -x * z / (1 + y) ┐
1613 * └ -x * z / (1 + y), z, 1 - z^2 / (1 + y) ┘
1615 * Written this way, we see the case v = +Y is no more a singularity. The only one remaining is the bone being
1618 * Let's handle the asymptotic behavior when bone vector is reaching the limit of y = -1. Each of the four corner
1619 * elements can vary from -1 to 1, depending on the axis a chosen for doing the rotation. And the "rotation" here
1620 * is in fact established by mirroring XZ plane by that given axis, then inversing the Y-axis.
1621 * For sufficiently small x and z, and with y approaching -1, all elements but the four corner ones of M
1622 * will degenerate. So let's now focus on these corner elements.
1624 * We rewrite M so that it only contains its four corner elements, and combine the 1 / (1 + y) factor:
1625 * ┌ 1 + y - x^2, -x * z ┐
1626 * M* = 1 / (1 + y) * │ │
1627 * └ -x * z, 1 + y - z^2 ┘
1629 * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability, so we ignore it and
1630 * normalize M instead. We know y^2 = 1 - (x^2 + z^2), and y < 0, hence y = -sqrt(1 - (x^2 + z^2)).
1631 * Since x and z are both close to 0, we apply the binomial expansion to the first order:
1632 * y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2. Which gives:
1633 * ┌ z^2 - x^2, -2 * x * z ┐
1634 * M* = 1 / (x^2 + z^2) * │ │
1635 * └ -2 * x * z, x^2 - z^2 ┘
1637 void vec_roll_to_mat3_normalized(const float nor[3], const float roll, float mat[3][3])
1639 #define THETA_THRESHOLD_NEGY 1.0e-9f
1640 #define THETA_THRESHOLD_NEGY_CLOSE 1.0e-5f
1643 float rMatrix[3][3], bMatrix[3][3];
1645 BLI_ASSERT_UNIT_V3(nor);
1647 theta = 1.0f + nor[1];
1649 /* With old algo, 1.0e-13f caused T23954 and T31333, 1.0e-6f caused T27675 and T30438,
1650 * so using 1.0e-9f as best compromise.
1652 * New algo is supposed much more precise, since less complex computations are performed,
1653 * but it uses two different threshold values...
1655 * Note: When theta is close to zero, we have to check we do have non-null X/Z components as well
1656 * (due to float precision errors, we can have nor = (0.0, 0.99999994, 0.0)...).
1658 if (theta > THETA_THRESHOLD_NEGY_CLOSE || ((nor[0] || nor[2]) && theta > THETA_THRESHOLD_NEGY)) {
1660 * We got these values for free... so be happy with it... ;)
1662 bMatrix[0][1] = -nor[0];
1663 bMatrix[1][0] = nor[0];
1664 bMatrix[1][1] = nor[1];
1665 bMatrix[1][2] = nor[2];
1666 bMatrix[2][1] = -nor[2];
1667 if (theta > THETA_THRESHOLD_NEGY_CLOSE) {
1668 /* If nor is far enough from -Y, apply the general case. */
1669 bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
1670 bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
1671 bMatrix[2][0] = bMatrix[0][2] = -nor[0] * nor[2] / theta;
1674 /* If nor is too close to -Y, apply the special case. */
1675 theta = nor[0] * nor[0] + nor[2] * nor[2];
1676 bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
1677 bMatrix[2][2] = -bMatrix[0][0];
1678 bMatrix[2][0] = bMatrix[0][2] = 2.0f * nor[0] * nor[2] / theta;
1682 /* If nor is -Y, simple symmetry by Z axis. */
1684 bMatrix[0][0] = bMatrix[1][1] = -1.0;
1687 /* Make Roll matrix */
1688 axis_angle_normalized_to_mat3(rMatrix, nor, roll);
1690 /* Combine and output result */
1691 mul_m3_m3m3(mat, rMatrix, bMatrix);
1693 #undef THETA_THRESHOLD_NEGY
1694 #undef THETA_THRESHOLD_NEGY_CLOSE
1697 void vec_roll_to_mat3(const float vec[3], const float roll, float mat[3][3])
1701 normalize_v3_v3(nor, vec);
1702 vec_roll_to_mat3_normalized(nor, roll, mat);
1705 /* recursive part, calculates restposition of entire tree of children */
1706 /* used by exiting editmode too */
1707 void BKE_armature_where_is_bone(Bone *bone, Bone *prevbone, const bool use_recursion)
1712 sub_v3_v3v3(vec, bone->tail, bone->head);
1713 bone->length = len_v3(vec);
1714 vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1716 /* this is called on old file reading too... */
1717 if (bone->xwidth == 0.0f) {
1718 bone->xwidth = 0.1f;
1719 bone->zwidth = 0.1f;
1724 float offs_bone[4][4];
1725 /* yoffs(b-1) + root(b) + bonemat(b) */
1726 get_offset_bone_mat(bone, offs_bone);
1728 /* Compose the matrix for this bone */
1729 mul_m4_m4m4(bone->arm_mat, prevbone->arm_mat, offs_bone);
1732 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1733 copy_v3_v3(bone->arm_mat[3], bone->head);
1736 /* and the kiddies */
1737 if (use_recursion) {
1739 for (bone = bone->childbase.first; bone; bone = bone->next) {
1740 BKE_armature_where_is_bone(bone, prevbone, use_recursion);
1745 /* updates vectors and matrices on rest-position level, only needed
1746 * after editing armature itself, now only on reading file */
1747 void BKE_armature_where_is(bArmature *arm)
1751 /* hierarchical from root to children */
1752 for (bone = arm->bonebase.first; bone; bone = bone->next) {
1753 BKE_armature_where_is_bone(bone, NULL, true);
1757 /* if bone layer is protected, copy the data from from->pose
1758 * when used with linked libraries this copies from the linked pose into the local pose */
1759 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1761 bPose *pose = ob->pose, *frompose = from->pose;
1762 bPoseChannel *pchan, *pchanp;
1766 if (frompose == NULL)
1769 /* in some cases when rigs change, we cant synchronize
1770 * to avoid crashing check for possible errors here */
1771 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1772 if (pchan->bone->layer & layer_protected) {
1773 if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
1774 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n",
1775 from->id.name, pchan->name);
1784 /* clear all transformation values from library */
1785 BKE_pose_rest(frompose);
1787 /* copy over all of the proxy's bone groups */
1789 * - implement 'local' bone groups as for constraints
1790 * Note: this isn't trivial, as bones reference groups by index not by pointer,
1791 * so syncing things correctly needs careful attention */
1792 BLI_freelistN(&pose->agroups);
1793 BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1794 pose->active_group = frompose->active_group;
1796 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1797 pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
1799 if (UNLIKELY(pchanp == NULL)) {
1800 /* happens for proxies that become invalid because of a missing link
1801 * for regular cases it shouldn't happen at all */
1803 else if (pchan->bone->layer & layer_protected) {
1804 ListBase proxylocal_constraints = {NULL, NULL};
1805 bPoseChannel pchanw;
1807 /* copy posechannel to temp, but restore important pointers */
1809 pchanw.bone = pchan->bone;
1810 pchanw.prev = pchan->prev;
1811 pchanw.next = pchan->next;
1812 pchanw.parent = pchan->parent;
1813 pchanw.child = pchan->child;
1814 pchanw.custom_tx = pchan->custom_tx;
1816 pchanw.mpath = pchan->mpath;
1817 pchan->mpath = NULL;
1819 /* this is freed so copy a copy, else undo crashes */
1821 pchanw.prop = IDP_CopyProperty(pchanw.prop);
1823 /* use the values from the existing props */
1825 IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1829 /* constraints - proxy constraints are flushed... local ones are added after
1830 * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1831 * 2. copy proxy-pchan's constraints on-to new
1832 * 3. add extracted local constraints back on top
1834 * Note for BKE_constraints_copy: when copying constraints, disable 'do_extern' otherwise
1835 * we get the libs direct linked in this blend.
1837 BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints);
1838 BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false);
1839 BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1841 /* constraints - set target ob pointer to own object */
1842 for (con = pchanw.constraints.first; con; con = con->next) {
1843 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1844 ListBase targets = {NULL, NULL};
1845 bConstraintTarget *ct;
1847 if (cti && cti->get_constraint_targets) {
1848 cti->get_constraint_targets(con, &targets);
1850 for (ct = targets.first; ct; ct = ct->next) {
1851 if (ct->tar == from)
1855 if (cti->flush_constraint_targets)
1856 cti->flush_constraint_targets(con, &targets, 0);
1860 /* free stuff from current channel */
1861 BKE_pose_channel_free(pchan);
1863 /* copy data in temp back over to the cleaned-out (but still allocated) original channel */
1865 if (pchan->custom) {
1866 id_us_plus(&pchan->custom->id);
1870 /* always copy custom shape */
1871 pchan->custom = pchanp->custom;
1872 if (pchan->custom) {
1873 id_us_plus(&pchan->custom->id);
1875 if (pchanp->custom_tx)
1876 pchan->custom_tx = BKE_pose_channel_find_name(pose, pchanp->custom_tx->name);
1878 /* ID-Property Syncing */
1880 IDProperty *prop_orig = pchan->prop;
1882 pchan->prop = IDP_CopyProperty(pchanp->prop);
1884 /* copy existing values across when types match */
1885 IDP_SyncGroupValues(pchan->prop, prop_orig);
1892 IDP_FreeProperty(prop_orig);
1893 MEM_freeN(prop_orig);
1900 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1902 bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
1905 pchan->parent = parchan;
1909 for (bone = bone->childbase.first; bone; bone = bone->next) {
1910 counter = rebuild_pose_bone(pose, bone, pchan, counter);
1911 /* for quick detecting of next bone in chain, only b-bone uses it now */
1912 if (bone->flag & BONE_CONNECTED)
1913 pchan->child = BKE_pose_channel_find_name(pose, bone->name);
1920 * Clear pointers of object's pose (needed in remap case, since we cannot always wait for a complete pose rebuild).
1922 void BKE_pose_clear_pointers(bPose *pose)
1924 for (bPoseChannel *pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1926 pchan->child = NULL;
1930 /* only after leave editmode, duplicating, validating older files, library syncing */
1931 /* NOTE: pose->flag is set for it */
1932 void BKE_pose_rebuild(Object *ob, bArmature *arm)
1936 bPoseChannel *pchan, *next;
1939 /* only done here */
1940 if (ob->pose == NULL) {
1941 /* create new pose */
1942 ob->pose = MEM_callocN(sizeof(bPose), "new pose");
1944 /* set default settings for animviz */
1945 animviz_settings_init(&ob->pose->avs);
1950 BKE_pose_clear_pointers(pose);
1952 /* first step, check if all channels are there */
1953 for (bone = arm->bonebase.first; bone; bone = bone->next) {
1954 counter = rebuild_pose_bone(pose, bone, NULL, counter);
1957 /* and a check for garbage */
1958 for (pchan = pose->chanbase.first; pchan; pchan = next) {
1960 if (pchan->bone == NULL) {
1961 BKE_pose_channel_free(pchan);
1962 BKE_pose_channels_hash_free(pose);
1963 BLI_freelinkN(&pose->chanbase, pchan);
1966 /* printf("rebuild pose %s, %d bones\n", ob->id.name, counter); */
1968 /* synchronize protected layers with proxy */
1970 BKE_object_copy_proxy_drivers(ob, ob->proxy);
1971 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1974 BKE_pose_update_constraint_flags(ob->pose); /* for IK detection for example */
1976 ob->pose->flag &= ~POSE_RECALC;
1977 ob->pose->flag |= POSE_WAS_REBUILT;
1979 BKE_pose_channels_hash_make(ob->pose);
1982 /* ********************** THE POSE SOLVER ******************* */
1984 /* loc/rot/size to given mat4 */
1985 void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
1991 /* get scaling matrix */
1992 size_to_mat3(smat, pchan->size);
1994 /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1995 if (pchan->rotmode > 0) {
1996 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1997 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
1999 else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2000 /* axis-angle - not really that great for 3D-changing orientations */
2001 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2004 /* quats are normalized before use to eliminate scaling issues */
2007 /* NOTE: we now don't normalize the stored values anymore, since this was kindof evil in some cases
2008 * but if this proves to be too problematic, switch back to the old system of operating directly on
2011 normalize_qt_qt(quat, pchan->quat);
2012 quat_to_mat3(rmat, quat);
2015 /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2016 mul_m3_m3m3(tmat, rmat, smat);
2017 copy_m4_m3(chan_mat, tmat);
2019 /* prevent action channels breaking chains */
2020 /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2021 if ((pchan->bone == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2022 copy_v3_v3(chan_mat[3], pchan->loc);
2026 /* loc/rot/size to mat4 */
2027 /* used in constraint.c too */
2028 void BKE_pchan_calc_mat(bPoseChannel *pchan)
2030 /* this is just a wrapper around the copy of this function which calculates the matrix
2031 * and stores the result in any given channel
2033 BKE_pchan_to_mat4(pchan, pchan->chan_mat);
2036 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2038 /* NLA strip modifiers */
2039 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2041 bActionModifier *amod;
2042 bActionStrip *strip, *strip2;
2043 float scene_cfra = BKE_scene_frame_get(scene);
2046 for (strip = armob->nlastrips.first; strip; strip = strip->next) {
2049 if (scene_cfra >= strip->start && scene_cfra <= strip->end)
2052 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2055 /* if there are any other strips active, ignore modifiers for this strip -
2056 * 'hold' option should only hold action modifiers if there are
2057 * no other active strips */
2058 for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2059 if (strip2 == strip) continue;
2061 if (scene_cfra >= strip2->start && scene_cfra <= strip2->end) {
2062 if (!(strip2->flag & ACTSTRIP_MUTE))
2067 /* if there are any later, activated, strips with 'hold' set, they take precedence,
2068 * so ignore modifiers for this strip */
2069 for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2070 if (scene_cfra < strip2->start) continue;
2071 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2078 /* temporal solution to prevent 2 strips accumulating */
2079 if (scene_cfra == strip->end && strip->next && strip->next->start == scene_cfra)
2082 for (amod = strip->modifiers.first; amod; amod = amod->next) {
2083 switch (amod->type) {
2084 case ACTSTRIP_MOD_DEFORM:
2086 /* validate first */
2087 if (amod->ob && amod->ob->type == OB_CURVE && amod->channel[0]) {
2089 if (STREQ(pchan->name, amod->channel)) {
2090 float mat4[4][4], mat3[3][3];
2092 curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2093 copy_m4_m4(mat4, pchan->pose_mat);
2094 mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2100 case ACTSTRIP_MOD_NOISE:
2102 if (STREQ(pchan->name, amod->channel)) {
2103 float nor[3], loc[3], ofs;
2104 float eul[3], size[3], eulo[3], sizeo[3];
2106 /* calculate turbulance */
2107 ofs = amod->turbul / 200.0f;
2109 /* make a copy of starting conditions */
2110 copy_v3_v3(loc, pchan->pose_mat[3]);
2111 mat4_to_eul(eul, pchan->pose_mat);
2112 mat4_to_size(size, pchan->pose_mat);
2113 copy_v3_v3(eulo, eul);
2114 copy_v3_v3(sizeo, size);
2116 /* apply noise to each set of channels */
2117 if (amod->channels & 4) {
2119 nor[0] = BLI_gNoise(amod->noisesize, size[0] + ofs, size[1], size[2], 0, 0) - ofs;
2120 nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1] + ofs, size[2], 0, 0) - ofs;
2121 nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2] + ofs, 0, 0) - ofs;
2122 add_v3_v3(size, nor);
2125 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2127 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2129 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2131 if (amod->channels & 2) {
2133 nor[0] = BLI_gNoise(amod->noisesize, eul[0] + ofs, eul[1], eul[2], 0, 0) - ofs;
2134 nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1] + ofs, eul[2], 0, 0) - ofs;
2135 nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2] + ofs, 0, 0) - ofs;
2137 compatible_eul(nor, eulo);
2138 add_v3_v3(eul, nor);
2139 compatible_eul(eul, eulo);
2141 loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2143 if (amod->channels & 1) {
2145 nor[0] = BLI_gNoise(amod->noisesize, loc[0] + ofs, loc[1], loc[2], 0, 0) - ofs;
2146 nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1] + ofs, loc[2], 0, 0) - ofs;
2147 nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2] + ofs, 0, 0) - ofs;
2149 add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2162 /* calculate tail of posechannel */
2163 void BKE_pose_where_is_bone_tail(bPoseChannel *pchan)
2167 copy_v3_v3(vec, pchan->pose_mat[1]);
2168 mul_v3_fl(vec, pchan->bone->length);
2169 add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2172 /* The main armature solver, does all constraints excluding IK */
2173 /* pchan is validated, as having bone and parent pointer
2174 * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2176 void BKE_pose_where_is_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, bool do_extra)
2178 /* This gives a chan_mat with actions (ipos) results. */
2180 BKE_pchan_calc_mat(pchan);
2182 unit_m4(pchan->chan_mat);
2184 /* Construct the posemat based on PoseChannels, that we do before applying constraints. */
2185 /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2186 BKE_armature_mat_bone_to_pose(pchan, pchan->chan_mat, pchan->pose_mat);
2188 /* Only rootbones get the cyclic offset (unless user doesn't want that). */
2189 /* XXX That could be a problem for snapping and other "reverse transform" features... */
2190 if (!pchan->parent) {
2191 if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2192 add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2196 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2197 /* do NLA strip modifiers - i.e. curve follow */
2198 do_strip_modifiers(scene, ob, bone, pchan);
2201 /* Do constraints */
2202 if (pchan->constraints.first) {
2206 /* make a copy of location of PoseChannel for later */
2207 copy_v3_v3(vec, pchan->pose_mat[3]);
2209 /* prepare PoseChannel for Constraint solving
2210 * - makes a copy of matrix, and creates temporary struct to use
2212 cob = BKE_constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2214 /* Solve PoseChannel's Constraints */
2215 BKE_constraints_solve(&pchan->constraints, cob, ctime); /* ctime doesnt alter objects */
2217 /* cleanup after Constraint Solving
2218 * - applies matrix back to pchan, and frees temporary struct used
2220 BKE_constraints_clear_evalob(cob);
2222 /* prevent constraints breaking a chain */
2223 if (pchan->bone->flag & BONE_CONNECTED) {
2224 copy_v3_v3(pchan->pose_mat[3], vec);
2229 /* calculate head */
2230 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
2231 /* calculate tail */
2232 BKE_pose_where_is_bone_tail(pchan);
2235 /* This only reads anim data from channels, and writes to channels */
2236 /* This is the only function adding poses */
2237 void BKE_pose_where_is(Scene *scene, Object *ob)
2241 bPoseChannel *pchan;
2245 if (ob->type != OB_ARMATURE)
2249 if (ELEM(NULL, arm, scene))
2251 if ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC))
2252 BKE_pose_rebuild(ob, arm);
2254 ctime = BKE_scene_frame_get(scene); /* not accurate... */
2256 /* In editmode or restposition we read the data from the bones */
2257 if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
2258 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2261 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2262 copy_v3_v3(pchan->pose_head, bone->arm_head);
2263 copy_v3_v3(pchan->pose_tail, bone->arm_tail);
2268 invert_m4_m4(ob->imat, ob->obmat); /* imat is needed */
2270 /* 1. clear flags */
2271 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2272 pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
2275 /* 2a. construct the IK tree (standard IK) */
2276 BIK_initialize_tree(scene, ob, ctime);
2278 /* 2b. construct the Spline IK trees
2279 * - this is not integrated as an IK plugin, since it should be able
2280 * to function in conjunction with standard IK
2282 BKE_pose_splineik_init_tree(scene, ob, ctime);
2284 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2285 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2286 /* 4a. if we find an IK root, we handle it separated */
2287 if (pchan->flag & POSE_IKTREE) {
2288 BIK_execute_tree(scene, ob, pchan, ctime);
2290 /* 4b. if we find a Spline IK root, we handle it separated too */
2291 else if (pchan->flag & POSE_IKSPLINE) {
2292 BKE_splineik_execute_tree(scene, ob, pchan, ctime);
2294 /* 5. otherwise just call the normal solver */
2295 else if (!(pchan->flag & POSE_DONE)) {
2296 BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);
2299 /* 6. release the IK tree */
2300 BIK_release_tree(scene, ob, ctime);
2303 /* calculating deform matrices */
2304 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2306 invert_m4_m4(imat, pchan->bone->arm_mat);
2307 mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
2312 /************** Bounding box ********************/
2313 static int minmax_armature(Object *ob, float r_min[3], float r_max[3])
2315 bPoseChannel *pchan;
2317 /* For now, we assume BKE_pose_where_is has already been called (hence we have valid data in pachan). */
2318 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2319 minmax_v3v3_v3(r_min, r_max, pchan->pose_head);
2320 minmax_v3v3_v3(r_min, r_max, pchan->pose_tail);
2323 return (BLI_listbase_is_empty(&ob->pose->chanbase) == false);
2326 static void boundbox_armature(Object *ob)
2329 float min[3], max[3];
2331 if (ob->bb == NULL) {
2332 ob->bb = MEM_callocN(sizeof(BoundBox), "Armature boundbox");
2336 INIT_MINMAX(min, max);
2337 if (!minmax_armature(ob, min, max)) {
2338 min[0] = min[1] = min[2] = -1.0f;
2339 max[0] = max[1] = max[2] = 1.0f;
2342 BKE_boundbox_init_from_minmax(bb, min, max);
2344 bb->flag &= ~BOUNDBOX_DIRTY;
2347 BoundBox *BKE_armature_boundbox_get(Object *ob)
2349 boundbox_armature(ob);
2354 bool BKE_pose_minmax(Object *ob, float r_min[3], float r_max[3], bool use_hidden, bool use_select)
2356 bool changed = false;
2359 bArmature *arm = ob->data;
2360 bPoseChannel *pchan;
2362 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2363 /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2364 * (editarmature.c:2592)... Skip in this case too! */
2366 (!((use_hidden == false) && (PBONE_VISIBLE(arm, pchan->bone) == false)) &&
2367 !((use_select == true) && ((pchan->bone->flag & BONE_SELECTED) == 0))))
2369 bPoseChannel *pchan_tx = (pchan->custom && pchan->custom_tx) ? pchan->custom_tx : pchan;
2370 BoundBox *bb_custom = ((pchan->custom) && !(arm->flag & ARM_NO_CUSTOM)) ?
2371 BKE_object_boundbox_get(pchan->custom) : NULL;
2373 float mat[4][4], smat[4][4];
2374 scale_m4_fl(smat, PCHAN_CUSTOM_DRAW_SIZE(pchan));
2375 mul_m4_series(mat, ob->obmat, pchan_tx->pose_mat, smat);
2376 BKE_boundbox_minmax(bb_custom, mat, r_min, r_max);
2380 mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_head);
2381 minmax_v3v3_v3(r_min, r_max, vec);
2382 mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_tail);
2383 minmax_v3v3_v3(r_min, r_max, vec);
2394 /************** Graph evaluation ********************/
2396 bPoseChannel *BKE_armature_ik_solver_find_root(
2397 bPoseChannel *pchan,
2398 bKinematicConstraint *data)
2400 bPoseChannel *rootchan = pchan;
2401 if (!(data->flag & CONSTRAINT_IK_TIP)) {
2402 /* Exclude tip from chain. */
2403 rootchan = rootchan->parent;
2405 if (rootchan != NULL) {
2407 while (rootchan->parent) {
2408 /* Continue up chain, until we reach target number of items. */
2410 if (segcount == data->rootbone) {
2413 rootchan = rootchan->parent;
2419 bPoseChannel *BKE_armature_splineik_solver_find_root(
2420 bPoseChannel *pchan,
2421 bSplineIKConstraint *data)
2423 bPoseChannel *rootchan = pchan;
2425 BLI_assert(rootchan != NULL);
2426 while (rootchan->parent) {
2427 /* Continue up chain, until we reach target number of items. */
2429 if (segcount == data->chainlen) {
2432 rootchan = rootchan->parent;