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"
40 #include "BLI_bpath.h"
42 #include "BLI_blenlib.h"
43 #include "BLI_utildefines.h"
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_constraint_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_lattice_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_nla_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_object_types.h"
55 #include "BKE_animsys.h"
56 #include "BKE_armature.h"
57 #include "BKE_action.h"
59 #include "BKE_constraint.h"
60 #include "BKE_curve.h"
61 #include "BKE_depsgraph.h"
62 #include "BKE_DerivedMesh.h"
63 #include "BKE_deform.h"
64 #include "BKE_displist.h"
65 #include "BKE_global.h"
66 #include "BKE_idprop.h"
67 #include "BKE_library.h"
68 #include "BKE_lattice.h"
70 #include "BKE_object.h"
71 #include "BKE_scene.h"
74 #include "BKE_sketch.h"
76 /* **************** Generic Functions, data level *************** */
78 bArmature *BKE_armature_add(const char *name)
82 arm = BKE_libblock_alloc(&G.main->armature, ID_AR, name);
83 arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
84 arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
89 bArmature *BKE_armature_from_object(Object *ob)
91 if (ob->type == OB_ARMATURE)
92 return (bArmature *)ob->data;
96 void BKE_armature_bonelist_free(ListBase *lb)
100 for (bone = lb->first; bone; bone = bone->next) {
102 IDP_FreeProperty(bone->prop);
103 MEM_freeN(bone->prop);
105 BKE_armature_bonelist_free(&bone->childbase);
111 void BKE_armature_free(bArmature *arm)
114 BKE_armature_bonelist_free(&arm->bonebase);
116 /* free editmode data */
118 BLI_freelistN(arm->edbo);
120 MEM_freeN(arm->edbo);
126 freeSketch(arm->sketch);
130 /* free animation data */
132 BKE_free_animdata(&arm->id);
138 void BKE_armature_make_local(bArmature *arm)
140 Main *bmain = G.main;
141 int is_local = FALSE, is_lib = FALSE;
144 if (arm->id.lib == NULL)
146 if (arm->id.us == 1) {
147 id_clear_lib_data(bmain, &arm->id);
151 for (ob = bmain->object.first; ob && ELEM(0, is_lib, is_local); ob = ob->id.next) {
152 if (ob->data == arm) {
160 if (is_local && is_lib == FALSE) {
161 id_clear_lib_data(bmain, &arm->id);
163 else if (is_local && is_lib) {
164 bArmature *arm_new = BKE_armature_copy(arm);
167 /* Remap paths of new ID using old library as base. */
168 BKE_id_lib_local_paths(bmain, arm->id.lib, &arm_new->id);
170 for (ob = bmain->object.first; ob; ob = ob->id.next) {
171 if (ob->data == arm) {
172 if (ob->id.lib == NULL) {
182 static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone)
184 Bone *curBone, *newChildBone;
186 if (oldBone == actBone)
187 *newActBone = newBone;
190 newBone->prop = IDP_CopyProperty(oldBone->prop);
192 /* Copy this bone's list */
193 BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
195 /* For each child in the list, update it's children */
196 newChildBone = newBone->childbase.first;
197 for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) {
198 newChildBone->parent = newBone;
199 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
200 newChildBone = newChildBone->next;
204 bArmature *BKE_armature_copy(bArmature *arm)
207 Bone *oldBone, *newBone;
208 Bone *newActBone = NULL;
210 newArm = BKE_libblock_copy(&arm->id);
211 BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
213 /* Duplicate the childrens' lists*/
214 newBone = newArm->bonebase.first;
215 for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) {
216 newBone->parent = NULL;
217 copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone);
218 newBone = newBone->next;
221 newArm->act_bone = newActBone;
224 newArm->act_edbone = NULL;
225 newArm->sketch = NULL;
230 static Bone *get_named_bone_bonechildren(Bone *bone, const char *name)
232 Bone *curBone, *rbone;
234 if (!strcmp(bone->name, name))
237 for (curBone = bone->childbase.first; curBone; curBone = curBone->next) {
238 rbone = get_named_bone_bonechildren(curBone, name);
247 /* Walk the list until the bone is found */
248 Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
250 Bone *bone = NULL, *curBone;
255 for (curBone = arm->bonebase.first; curBone; curBone = curBone->next) {
256 bone = get_named_bone_bonechildren(curBone, name);
264 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
265 * unique names afterwards) strip_number: removes number extensions (TODO: not used)
266 * axis: the axis to name on
267 * head/tail: the head/tail co-ordinate of the bone on the specified axis */
268 int bone_autoside_name(char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
271 char basename[MAXBONENAME] = "";
272 char extension[5] = "";
277 BLI_strncpy(basename, name, sizeof(basename));
279 /* Figure out extension to append:
280 * - The extension to append is based upon the axis that we are working on.
281 * - If head happens to be on 0, then we must consider the tail position as well to decide
282 * which side the bone is on
283 * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
284 * -> Otherwise, extension is added from perspective of object based on which side tail goes to
285 * - If head is non-zero, extension is added from perspective of object based on side head is on
288 /* z-axis - vertical (top/bottom) */
289 if (IS_EQ(head, 0)) {
291 strcpy(extension, "Bot");
293 strcpy(extension, "Top");
297 strcpy(extension, "Bot");
299 strcpy(extension, "Top");
302 else if (axis == 1) {
303 /* y-axis - depth (front/back) */
304 if (IS_EQ(head, 0)) {
306 strcpy(extension, "Fr");
308 strcpy(extension, "Bk");
312 strcpy(extension, "Fr");
314 strcpy(extension, "Bk");
318 /* x-axis - horizontal (left/right) */
319 if (IS_EQ(head, 0)) {
321 strcpy(extension, "R");
323 strcpy(extension, "L");
327 strcpy(extension, "R");
328 /* XXX Shouldn't this be simple else, as for z and y axes? */
330 strcpy(extension, "L");
334 /* Simple name truncation
335 * - truncate if there is an extension and it wouldn't be able to fit
336 * - otherwise, just append to end
341 while (change) { /* remove extensions */
343 if (len > 2 && basename[len - 2] == '.') {
344 if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
345 basename[len - 2] = '\0';
350 else if (len > 3 && basename[len - 3] == '.') {
351 if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
352 (basename[len - 2] == 'B' && basename[len - 1] == 'k')) /* Bk */
354 basename[len - 3] = '\0';
359 else if (len > 4 && basename[len - 4] == '.') {
360 if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' && basename[len - 1] == 'p') || /* Top */
361 (basename[len - 3] == 'B' && basename[len - 2] == 'o' && basename[len - 1] == 't')) /* Bot */
363 basename[len - 4] = '\0';
370 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
371 strncpy(name, basename, len - strlen(extension));
374 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
383 /* ************* B-Bone support ******************* */
385 #define MAX_BBONE_SUBDIV 32
387 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
388 static void equalize_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 ((dist >= pdist[nr]) && nr < MAX_BBONE_SUBDIV)
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 Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
432 static Mat4 bbone_array[MAX_BBONE_SUBDIV];
433 static Mat4 bbone_rest_array[MAX_BBONE_SUBDIV];
434 Mat4 *result_array = (rest) ? bbone_rest_array : bbone_array;
435 bPoseChannel *next, *prev;
436 Bone *bone = pchan->bone;
437 float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1 = 0.0f, roll2;
438 float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
439 float data[MAX_BBONE_SUBDIV + 1][4], *fp;
442 length = bone->length;
445 /* check if we need to take non-uniform bone scaling into account */
446 scale[0] = len_v3(pchan->pose_mat[0]);
447 scale[1] = len_v3(pchan->pose_mat[1]);
448 scale[2] = len_v3(pchan->pose_mat[2]);
450 if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
452 scalemat[0][0] = scale[0];
453 scalemat[1][1] = scale[1];
454 scalemat[2][2] = scale[2];
455 invert_m4_m4(iscalemat, scalemat);
462 hlength1 = bone->ease1 * length * 0.390464f; /* 0.5f * sqrt(2) * kappa, the handle length for near-perfect circles */
463 hlength2 = bone->ease2 * length * 0.390464f;
465 /* evaluate next and prev bones */
466 if (bone->flag & BONE_CONNECTED)
467 prev = pchan->parent;
473 /* find the handle points, since this is inside bone space, the
474 * first point = (0, 0, 0)
475 * last point = (0, length, 0) */
477 invert_m4_m4(imat, pchan->bone->arm_mat);
480 copy_m4_m4(posemat, pchan->pose_mat);
481 normalize_m4(posemat);
482 invert_m4_m4(imat, posemat);
485 invert_m4_m4(imat, pchan->pose_mat);
488 float difmat[4][4], result[3][3], imat3[3][3];
490 /* transform previous point inside this bone space */
492 copy_v3_v3(h1, prev->bone->arm_head);
494 copy_v3_v3(h1, prev->pose_head);
497 if (prev->bone->segments > 1) {
498 /* if previous bone is B-bone too, use average handle direction */
504 mul_v3_fl(h1, -hlength1);
506 if (prev->bone->segments == 1) {
507 /* find the previous roll to interpolate */
509 mult_m4_m4m4(difmat, imat, prev->bone->arm_mat);
511 mult_m4_m4m4(difmat, imat, prev->pose_mat);
512 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
514 vec_roll_to_mat3(h1, 0.0f, mat3); /* the result of vec_roll without roll */
516 invert_m3_m3(imat3, mat3);
517 mul_m3_m3m3(mat3, result, imat3); /* the matrix transforming vec_roll to desired roll */
519 roll1 = (float)atan2(mat3[2][0], mat3[2][2]);
523 h1[0] = 0.0f; h1[1] = hlength1; h1[2] = 0.0f;
527 float difmat[4][4], result[3][3], imat3[3][3];
529 /* transform next point inside this bone space */
531 copy_v3_v3(h2, next->bone->arm_tail);
533 copy_v3_v3(h2, next->pose_tail);
536 /* if next bone is B-bone too, use average handle direction */
537 if (next->bone->segments > 1)
543 /* find the next roll to interpolate as well */
545 mult_m4_m4m4(difmat, imat, next->bone->arm_mat);
547 mult_m4_m4m4(difmat, imat, next->pose_mat);
548 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
550 vec_roll_to_mat3(h2, 0.0f, mat3); /* the result of vec_roll without roll */
552 invert_m3_m3(imat3, mat3);
553 mul_m3_m3m3(mat3, imat3, result); /* the matrix transforming vec_roll to desired roll */
555 roll2 = (float)atan2(mat3[2][0], mat3[2][2]);
557 /* and only now negate handle */
558 mul_v3_fl(h2, -hlength2);
561 h2[0] = 0.0f; h2[1] = -hlength2; h2[2] = 0.0f;
566 if (bone->segments > MAX_BBONE_SUBDIV)
567 bone->segments = MAX_BBONE_SUBDIV;
569 BKE_curve_forward_diff_bezier(0.0f, h1[0], h2[0], 0.0f, data[0], MAX_BBONE_SUBDIV, 4 * sizeof(float));
570 BKE_curve_forward_diff_bezier(0.0f, h1[1], length + h2[1], length, data[0] + 1, MAX_BBONE_SUBDIV, 4 * sizeof(float));
571 BKE_curve_forward_diff_bezier(0.0f, h1[2], h2[2], 0.0f, data[0] + 2, MAX_BBONE_SUBDIV, 4 * sizeof(float));
572 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));
574 equalize_bezier(data[0], bone->segments); /* note: does stride 4! */
576 /* make transformation matrices for the segments for drawing */
577 for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) {
578 sub_v3_v3v3(h1, fp + 4, fp);
579 vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */
581 copy_m4_m3(result_array[a].mat, mat3);
582 copy_v3_v3(result_array[a].mat[3], fp);
585 /* correct for scaling when this matrix is used in scaled space */
586 mul_serie_m4(result_array[a].mat, iscalemat, result_array[a].mat, scalemat, NULL, NULL, NULL, NULL, NULL);
593 /* ************ Armature Deform ******************* */
595 typedef struct bPoseChanDeform {
598 DualQuat *b_bone_dual_quats;
601 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, int use_quaternion)
603 Bone *bone = pchan->bone;
604 Mat4 *b_bone = b_bone_spline_setup(pchan, 0);
605 Mat4 *b_bone_rest = b_bone_spline_setup(pchan, 1);
607 DualQuat *b_bone_dual_quats = NULL;
608 float tmat[4][4] = MAT4_UNITY;
611 /* allocate b_bone matrices and dual quats */
612 b_bone_mats = MEM_mallocN((1 + bone->segments) * sizeof(Mat4), "BBone defmats");
613 pdef_info->b_bone_mats = b_bone_mats;
615 if (use_quaternion) {
616 b_bone_dual_quats = MEM_mallocN((bone->segments) * sizeof(DualQuat), "BBone dqs");
617 pdef_info->b_bone_dual_quats = b_bone_dual_quats;
620 /* first matrix is the inverse arm_mat, to bring points in local bone space
621 * for finding out which segment it belongs to */
622 invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
624 /* then we make the b_bone_mats:
625 * - first transform to local bone space
626 * - translate over the curve to the bbone mat space
627 * - transform with b_bone matrix
628 * - transform back into global space */
630 for (a = 0; a < bone->segments; a++) {
631 invert_m4_m4(tmat, b_bone_rest[a].mat);
633 mul_serie_m4(b_bone_mats[a + 1].mat, pchan->chan_mat, bone->arm_mat, b_bone[a].mat, tmat, b_bone_mats[0].mat,
637 mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
641 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], DualQuat *dq, float defmat[][3])
643 Mat4 *b_bone = pdef_info->b_bone_mats;
644 float (*mat)[4] = b_bone[0].mat;
648 /* need to transform co back to bonespace, only need y */
649 y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1];
651 /* now calculate which of the b_bones are deforming this */
652 segment = bone->length / ((float)bone->segments);
653 a = (int)(y / segment);
655 /* note; by clamping it extends deform at endpoints, goes best with
656 * straight joints in restpos. */
657 CLAMP(a, 0, bone->segments - 1);
660 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
663 mul_m4_v3(b_bone[a + 1].mat, co);
666 copy_m3_m4(defmat, b_bone[a + 1].mat);
671 /* using vec with dist to bone b1 - b2 */
672 float distfactor_to_bone(const float vec[3], const float b1[3], const float b2[3], float rad1, float rad2, float rdist)
677 float hsqr, a, l, rad;
679 sub_v3_v3v3(bdelta, b2, b1);
680 l = normalize_v3(bdelta);
682 sub_v3_v3v3(pdelta, vec, b1);
684 a = dot_v3v3(bdelta, pdelta);
685 hsqr = dot_v3v3(pdelta, pdelta);
688 /* If we're past the end of the bone, do a spherical field attenuation thing */
689 dist = len_squared_v3v3(b1, vec);
693 /* If we're past the end of the bone, do a spherical field attenuation thing */
694 dist = len_squared_v3v3(b2, vec);
698 dist = (hsqr - (a * a));
702 rad = rad * rad2 + (1.0f - rad) * rad1;
714 if (rdist == 0.0f || dist >= l)
717 a = sqrtf(dist) - rad;
718 return 1.0f - (a * a) / (rdist * rdist);
723 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[][3], float mat[][3])
727 if (pchan->bone->segments > 1)
728 copy_m3_m3(wmat, bbonemat);
730 copy_m3_m4(wmat, pchan->chan_mat);
732 mul_m3_fl(wmat, weight);
733 add_m3_m3m3(mat, mat, wmat);
736 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float vec[3], DualQuat *dq,
737 float mat[][3], float *co)
739 Bone *bone = pchan->bone;
740 float fac, contrib = 0.0;
741 float cop[3], bbonemat[3][3];
749 fac = distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
754 if (contrib > 0.0f) {
756 if (bone->segments > 1)
757 /* applies on cop and bbonemat */
758 b_bone_deform(pdef_info, bone, cop, NULL, (mat) ? bbonemat : NULL);
760 mul_m4_v3(pchan->chan_mat, cop);
762 /* Make this a delta from the base position */
764 madd_v3_v3fl(vec, cop, fac);
767 pchan_deform_mat_add(pchan, fac, bbonemat, mat);
770 if (bone->segments > 1) {
771 b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
772 add_weighted_dq_dq(dq, &bbonedq, fac);
775 add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
783 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq,
784 float mat[][3], float *co, float *contrib)
786 float cop[3], bbonemat[3][3];
795 if (pchan->bone->segments > 1)
796 /* applies on cop and bbonemat */
797 b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat) ? bbonemat : NULL);
799 mul_m4_v3(pchan->chan_mat, cop);
801 vec[0] += (cop[0] - co[0]) * weight;
802 vec[1] += (cop[1] - co[1]) * weight;
803 vec[2] += (cop[2] - co[2]) * weight;
806 pchan_deform_mat_add(pchan, weight, bbonemat, mat);
809 if (pchan->bone->segments > 1) {
810 b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
811 add_weighted_dq_dq(dq, &bbonedq, weight);
814 add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
817 (*contrib) += weight;
820 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3],
821 float (*defMats)[3][3], int numVerts, int deformflag,
822 float (*prevCos)[3], const char *defgrp_name)
824 bPoseChanDeform *pdef_info_array;
825 bPoseChanDeform *pdef_info = NULL;
826 bArmature *arm = armOb->data;
827 bPoseChannel *pchan, **defnrToPC = NULL;
828 int *defnrToPCIndex = NULL;
829 MDeformVert *dverts = NULL;
831 DualQuat *dualquats = NULL;
832 float obinv[4][4], premat[4][4], postmat[4][4];
833 const short use_envelope = deformflag & ARM_DEF_ENVELOPE;
834 const short use_quaternion = deformflag & ARM_DEF_QUATERNION;
835 const short invert_vgroup = deformflag & ARM_DEF_INVERT_VGROUP;
836 int defbase_tot = 0; /* safety for vertexgroup index overflow */
837 int i, target_totvert = 0; /* safety for vertexgroup overflow */
838 int use_dverts = FALSE;
842 if (arm->edbo) return;
844 invert_m4_m4(obinv, target->obmat);
845 copy_m4_m4(premat, target->obmat);
846 mult_m4_m4m4(postmat, obinv, armOb->obmat);
847 invert_m4_m4(premat, postmat);
849 /* bone defmats are already in the channels, chan_mat */
851 /* initialize B_bone matrices and dual quaternions */
852 totchan = BLI_countlist(&armOb->pose->chanbase);
854 if (use_quaternion) {
855 dualquats = MEM_callocN(sizeof(DualQuat) * totchan, "dualquats");
858 pdef_info_array = MEM_callocN(sizeof(bPoseChanDeform) * totchan, "bPoseChanDeform");
861 pdef_info = pdef_info_array;
862 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
863 if (!(pchan->bone->flag & BONE_NO_DEFORM)) {
864 if (pchan->bone->segments > 1)
865 pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
867 if (use_quaternion) {
868 pdef_info->dual_quat = &dualquats[totchan++];
869 mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat);
874 /* get the def_nr for the overall armature vertex group if present */
875 armature_def_nr = defgroup_name_index(target, defgrp_name);
877 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
878 defbase_tot = BLI_countlist(&target->defbase);
880 if (target->type == OB_MESH) {
881 Mesh *me = target->data;
884 target_totvert = me->totvert;
887 Lattice *lt = target->data;
890 target_totvert = lt->pntsu * lt->pntsv * lt->pntsw;
894 /* get a vertex-deform-index to posechannel array */
895 if (deformflag & ARM_DEF_VGROUP) {
896 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
897 /* if we have a DerivedMesh, only use dverts if it has them */
899 use_dverts = (dm->getVertData(dm, 0, CD_MDEFORMVERT) != NULL);
906 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone");
907 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex");
908 for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) {
909 defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name);
910 /* exclude non-deforming bones */
912 if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
916 defnrToPCIndex[i] = BLI_findindex(&armOb->pose->chanbase, defnrToPC[i]);
924 for (i = 0; i < numVerts; i++) {
926 DualQuat sumdq, *dq = NULL;
928 float sumvec[3], summat[3][3];
929 float *vec = NULL, (*smat)[3] = NULL;
930 float contrib = 0.0f;
931 float armature_weight = 1.0f; /* default to 1 if no overall def group */
932 float prevco_weight = 1.0f; /* weight for optional cached vertexcos */
934 if (use_quaternion) {
935 memset(&sumdq, 0, sizeof(DualQuat));
939 sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
948 if (use_dverts || armature_def_nr >= 0) {
950 dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
951 else if (dverts && i < target_totvert)
959 if (armature_def_nr >= 0 && dvert) {
960 armature_weight = defvert_find_weight(dvert, armature_def_nr);
963 armature_weight = 1.0f - armature_weight;
965 /* hackish: the blending factor can be used for blending with prevCos too */
967 prevco_weight = armature_weight;
968 armature_weight = 1.0f;
972 /* check if there's any point in calculating for this vert */
973 if (armature_weight == 0.0f)
976 /* get the coord we work on */
977 co = prevCos ? prevCos[i] : vertexCos[i];
979 /* Apply the object's matrix */
980 mul_m4_v3(premat, co);
982 if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */
983 MDeformWeight *dw = dvert->dw;
987 for (j = dvert->totweight; j != 0; j--, dw++) {
988 const int index = dw->def_nr;
989 if (index < defbase_tot && (pchan = defnrToPC[index])) {
990 float weight = dw->weight;
991 Bone *bone = pchan->bone;
992 pdef_info = pdef_info_array + defnrToPCIndex[index];
996 if (bone && bone->flag & BONE_MULT_VG_ENV) {
997 weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
998 bone->rad_head, bone->rad_tail, bone->dist);
1000 pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
1003 /* if there are vertexgroups but not groups with bones
1004 * (like for softbody groups) */
1005 if (deformed == 0 && use_envelope) {
1006 pdef_info = pdef_info_array;
1007 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1008 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1009 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1013 else if (use_envelope) {
1014 pdef_info = pdef_info_array;
1015 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1016 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1017 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1021 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1022 if (contrib > 0.0001f) {
1023 if (use_quaternion) {
1024 normalize_dq(dq, contrib);
1026 if (armature_weight != 1.0f) {
1027 copy_v3_v3(dco, co);
1028 mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq);
1030 mul_v3_fl(dco, armature_weight);
1034 mul_v3m3_dq(co, (defMats) ? summat : NULL, dq);
1039 mul_v3_fl(vec, armature_weight / contrib);
1040 add_v3_v3v3(co, vec, co);
1044 float pre[3][3], post[3][3], tmpmat[3][3];
1046 copy_m3_m4(pre, premat);
1047 copy_m3_m4(post, postmat);
1048 copy_m3_m3(tmpmat, defMats[i]);
1050 if (!use_quaternion) /* quaternion already is scale corrected */
1051 mul_m3_fl(smat, armature_weight / contrib);
1053 mul_serie_m3(defMats[i], tmpmat, pre, smat, post, NULL, NULL, NULL, NULL);
1057 /* always, check above code */
1058 mul_m4_v3(postmat, co);
1060 /* interpolate with previous modifier position using weight group */
1062 float mw = 1.0f - prevco_weight;
1063 vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0];
1064 vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1];
1065 vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2];
1070 MEM_freeN(dualquats);
1072 MEM_freeN(defnrToPC);
1074 MEM_freeN(defnrToPCIndex);
1076 /* free B_bone matrices */
1077 pdef_info = pdef_info_array;
1078 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1079 if (pdef_info->b_bone_mats)
1080 MEM_freeN(pdef_info->b_bone_mats);
1081 if (pdef_info->b_bone_dual_quats)
1082 MEM_freeN(pdef_info->b_bone_dual_quats);
1085 MEM_freeN(pdef_info_array);
1088 /* ************ END Armature Deform ******************* */
1090 void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[][4], int UNUSED(root),
1093 copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1096 /* **************** Space to Space API ****************** */
1098 /* Convert World-Space Matrix to Pose-Space Matrix */
1099 void BKE_armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4])
1103 /* prevent crashes */
1107 /* get inverse of (armature) object's matrix */
1108 invert_m4_m4(obmat, ob->obmat);
1110 /* multiply given matrix by object's-inverse to find pose-space matrix */
1111 mult_m4_m4m4(outmat, inmat, obmat);
1114 /* Convert World-Space Location to Pose-Space Location
1115 * NOTE: this cannot be used to convert to pose-space location of the supplied
1116 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1117 void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
1119 float xLocMat[4][4] = MAT4_UNITY;
1120 float nLocMat[4][4];
1122 /* build matrix for location */
1123 copy_v3_v3(xLocMat[3], inloc);
1125 /* get bone-space cursor matrix and extract location */
1126 BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1127 copy_v3_v3(outloc, nLocMat[3]);
1130 /* Simple helper, computes the offset bone matrix.
1131 * offs_bone = yoffs(b-1) + root(b) + bonemat(b).
1132 * Not exported, as it is only used in this file currently... */
1133 static void get_offset_bone_mat(Bone *bone, float offs_bone[][4])
1138 /* Bone transform itself. */
1139 copy_m4_m3(offs_bone, bone->bone_mat);
1141 /* The bone's root offset (is in the parent's coordinate system). */
1142 copy_v3_v3(offs_bone[3], bone->head);
1144 /* Get the length translation of parent (length along y axis). */
1145 offs_bone[3][1] += bone->parent->length;
1148 /* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space.
1149 * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
1150 * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1153 * This allows to get the transformations of a bone in its object space, *before* constraints (and IK)
1154 * get applied (used by pose evaluation code).
1155 * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
1156 * in object space (used by interactive transform, and snapping code).
1158 * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
1159 * will differ from the rotation/scale matrix...
1161 * NOTE: This cannot be used to convert to pose-space transforms of the supplied
1162 * pose-channel into its local space (i.e. 'visual'-keyframing).
1163 * (note: I don't understand that, so I keep it :p --mont29).
1165 void BKE_pchan_to_pose_mat(bPoseChannel *pchan, float rotscale_mat[][4], float loc_mat[][4])
1167 Bone *bone, *parbone;
1168 bPoseChannel *parchan;
1170 /* set up variables for quicker access below */
1172 parbone = bone->parent;
1173 parchan = pchan->parent;
1176 float offs_bone[4][4];
1177 /* yoffs(b-1) + root(b) + bonemat(b). */
1178 get_offset_bone_mat(bone, offs_bone);
1180 /* Compose the rotscale matrix for this bone. */
1181 if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) {
1182 /* Parent rest rotation and scale. */
1183 mult_m4_m4m4(rotscale_mat, parbone->arm_mat, offs_bone);
1185 else if (bone->flag & BONE_HINGE) {
1186 /* Parent rest rotation and pose scale. */
1187 float tmat[4][4], tscale[3];
1189 /* Extract the scale of the parent pose matrix. */
1190 mat4_to_size(tscale, parchan->pose_mat);
1191 size_to_mat4(tmat, tscale);
1193 /* Applies the parent pose scale to the rest matrix. */
1194 mult_m4_m4m4(tmat, tmat, parbone->arm_mat);
1196 mult_m4_m4m4(rotscale_mat, tmat, offs_bone);
1198 else if (bone->flag & BONE_NO_SCALE) {
1199 /* Parent pose rotation and rest scale (i.e. no scaling). */
1201 copy_m4_m4(tmat, parchan->pose_mat);
1203 mult_m4_m4m4(rotscale_mat, tmat, offs_bone);
1206 mult_m4_m4m4(rotscale_mat, parchan->pose_mat, offs_bone);
1208 /* Compose the loc matrix for this bone. */
1209 /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
1211 /* In this case, use the object's space *orientation*. */
1212 if (bone->flag & BONE_NO_LOCAL_LOCATION) {
1213 /* XXX I'm sure that code can be simplified! */
1214 float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
1219 mul_v3_m4v3(bone_loc[3], parchan->pose_mat, offs_bone[3]);
1221 unit_m3(bone_rotscale);
1222 copy_m3_m4(tmat3, parchan->pose_mat);
1223 mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
1225 copy_m4_m3(tmat4, bone_rotscale);
1226 mult_m4_m4m4(loc_mat, bone_loc, tmat4);
1228 /* Those flags do not affect position, use plain parent transform space! */
1229 else if (bone->flag & (BONE_HINGE | BONE_NO_SCALE)) {
1230 mult_m4_m4m4(loc_mat, parchan->pose_mat, offs_bone);
1232 /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */
1234 copy_m4_m4(loc_mat, rotscale_mat);
1238 /* Rotation/scaling. */
1239 copy_m4_m4(rotscale_mat, pchan->bone->arm_mat);
1241 if (pchan->bone->flag & BONE_NO_LOCAL_LOCATION) {
1242 /* Translation of arm_mat, without the rotation. */
1244 copy_v3_v3(loc_mat[3], pchan->bone->arm_mat[3]);
1247 copy_m4_m4(loc_mat, rotscale_mat);
1251 /* Convert Pose-Space Matrix to Bone-Space Matrix.
1252 * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1253 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1254 void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1256 float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1258 /* Security, this allows to call with inmat == outmat! */
1259 copy_m4_m4(inmat_, inmat);
1261 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1262 invert_m4(rotscale_mat);
1265 mult_m4_m4m4(outmat, rotscale_mat, inmat_);
1266 mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1269 /* Convert Bone-Space Matrix to Pose-Space Matrix. */
1270 void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1272 float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1274 /* Security, this allows to call with inmat == outmat! */
1275 copy_m4_m4(inmat_, inmat);
1277 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1279 mult_m4_m4m4(outmat, rotscale_mat, inmat_);
1280 mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1283 /* Convert Pose-Space Location to Bone-Space Location
1284 * NOTE: this cannot be used to convert to pose-space location of the supplied
1285 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1286 void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
1288 float xLocMat[4][4] = MAT4_UNITY;
1289 float nLocMat[4][4];
1291 /* build matrix for location */
1292 copy_v3_v3(xLocMat[3], inloc);
1294 /* get bone-space cursor matrix and extract location */
1295 BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1296 copy_v3_v3(outloc, nLocMat[3]);
1299 void BKE_armature_mat_pose_to_bone_ex(Object *ob, bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1301 bPoseChannel work_pchan = *pchan;
1303 /* recalculate pose matrix with only parent transformations,
1304 * bone loc/sca/rot is ignored, scene and frame are not used. */
1305 BKE_pose_where_is_bone(NULL, ob, &work_pchan, 0.0f, FALSE);
1307 /* find the matrix, need to remove the bone transforms first so this is
1308 * calculated as a matrix to set rather then a difference ontop of whats
1311 BKE_pchan_apply_mat4(&work_pchan, outmat, FALSE);
1313 BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
1316 /* same as BKE_object_mat3_to_rot() */
1317 void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[][3], short use_compat)
1319 switch (pchan->rotmode) {
1321 mat3_to_quat(pchan->quat, mat);
1323 case ROT_MODE_AXISANGLE:
1324 mat3_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1326 default: /* euler */
1328 mat3_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1330 mat3_to_eulO(pchan->eul, pchan->rotmode, mat);
1334 /* Apply a 4x4 matrix to the pose bone,
1335 * similar to BKE_object_apply_mat4() */
1336 void BKE_pchan_apply_mat4(bPoseChannel *pchan, float mat[][4], short use_compat)
1339 mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1340 BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
1343 /* Remove rest-position effects from pose-transform for obtaining
1344 * 'visual' transformation of pose-channel.
1345 * (used by the Visual-Keyframing stuff) */
1346 void BKE_armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
1350 invert_m4_m4(imat, arm_mat);
1351 mult_m4_m4m4(delta_mat, imat, pose_mat);
1354 /* **************** Rotation Mode Conversions ****************************** */
1355 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1357 /* Called from RNA when rotation mode changes
1358 * - the result should be that the rotations given in the provided pointers have had conversions
1359 * applied (as appropriate), such that the rotation of the element hasn't 'visually' changed */
1360 void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1362 /* check if any change - if so, need to convert data */
1363 if (newMode > 0) { /* to euler */
1364 if (oldMode == ROT_MODE_AXISANGLE) {
1365 /* axis-angle to euler */
1366 axis_angle_to_eulO(eul, newMode, axis, *angle);
1368 else if (oldMode == ROT_MODE_QUAT) {
1371 quat_to_eulO(eul, newMode, quat);
1373 /* else { no conversion needed } */
1375 else if (newMode == ROT_MODE_QUAT) { /* to quat */
1376 if (oldMode == ROT_MODE_AXISANGLE) {
1377 /* axis angle to quat */
1378 axis_angle_to_quat(quat, axis, *angle);
1380 else if (oldMode > 0) {
1382 eulO_to_quat(quat, eul, oldMode);
1384 /* else { no conversion needed } */
1386 else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1388 /* euler to axis angle */
1389 eulO_to_axis_angle(axis, angle, eul, oldMode);
1391 else if (oldMode == ROT_MODE_QUAT) {
1392 /* quat to axis angle */
1394 quat_to_axis_angle(axis, angle, quat);
1397 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1398 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1399 /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1405 /* **************** The new & simple (but OK!) armature evaluation ********* */
1407 /* ****************** And how it works! ****************************************
1409 * This is the bone transformation trick; they're hierarchical so each bone(b)
1410 * is in the coord system of bone(b-1):
1412 * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
1414 * -> yoffs is just the y axis translation in parent's coord system
1415 * -> d_root is the translation of the bone root, also in parent's coord system
1417 * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1419 * we then - in init deform - store the deform in chan_mat, such that:
1421 * pose_mat(b)= arm_mat(b) * chan_mat(b)
1423 * *************************************************************************** */
1424 /* Computes vector and roll based on a rotation.
1425 * "mat" must contain only a rotation, and no scaling. */
1426 void mat3_to_vec_roll(float mat[][3], float vec[3], float *roll)
1429 copy_v3_v3(vec, mat[1]);
1432 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1434 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1435 invert_m3_m3(vecmatinv, vecmat);
1436 mul_m3_m3m3(rollmat, vecmatinv, mat);
1438 *roll = (float)atan2(rollmat[2][0], rollmat[2][2]);
1442 /* Calculates the rest matrix of a bone based
1443 * On its vector and a roll around that vector */
1444 void vec_roll_to_mat3(const float vec[3], const float roll, float mat[][3])
1446 float nor[3], axis[3], target[3] = {0, 1, 0};
1448 float rMatrix[3][3], bMatrix[3][3];
1450 normalize_v3_v3(nor, vec);
1452 /* Find Axis & Amount for bone matrix */
1453 cross_v3_v3v3(axis, target, nor);
1455 /* was 0.0000000000001, caused bug [#23954], smaller values give unstable
1456 * roll when toggling editmode.
1458 * was 0.00001, causes bug [#27675], with 0.00000495,
1459 * so a value inbetween these is needed.
1461 * was 0.000001, causes bug [#30438] (which is same as [#27675, imho).
1462 * Reseting it to org value seems to cause no more [#23954]...
1464 * was 0.0000000000001, caused bug [#31333], smaller values give unstable
1465 * roll when toggling editmode again...
1466 * No good value here, trying 0.000000001 as best compromize. :/
1468 if (dot_v3v3(axis, axis) > 1.0e-9f) {
1469 /* if nor is *not* a multiple of target ... */
1472 theta = angle_normalized_v3v3(target, nor);
1474 /* Make Bone matrix*/
1475 vec_rot_to_mat3(bMatrix, axis, theta);
1478 /* if nor is a multiple of target ... */
1481 /* point same direction, or opposite? */
1482 updown = (dot_v3v3(target, nor) > 0) ? 1.0f : -1.0f;
1484 /* I think this should work... */
1485 bMatrix[0][0] = updown; bMatrix[0][1] = 0.0; bMatrix[0][2] = 0.0;
1486 bMatrix[1][0] = 0.0; bMatrix[1][1] = updown; bMatrix[1][2] = 0.0;
1487 bMatrix[2][0] = 0.0; bMatrix[2][1] = 0.0; bMatrix[2][2] = 1.0;
1490 /* Make Roll matrix */
1491 vec_rot_to_mat3(rMatrix, nor, roll);
1493 /* Combine and output result */
1494 mul_m3_m3m3(mat, rMatrix, bMatrix);
1498 /* recursive part, calculates restposition of entire tree of children */
1499 /* used by exiting editmode too */
1500 void BKE_armature_where_is_bone(Bone *bone, Bone *prevbone)
1505 sub_v3_v3v3(vec, bone->tail, bone->head);
1506 vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1508 bone->length = len_v3v3(bone->head, bone->tail);
1510 /* this is called on old file reading too... */
1511 if (bone->xwidth == 0.0f) {
1512 bone->xwidth = 0.1f;
1513 bone->zwidth = 0.1f;
1518 float offs_bone[4][4];
1519 /* yoffs(b-1) + root(b) + bonemat(b) */
1520 get_offset_bone_mat(bone, offs_bone);
1522 /* Compose the matrix for this bone */
1523 mult_m4_m4m4(bone->arm_mat, prevbone->arm_mat, offs_bone);
1526 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1527 copy_v3_v3(bone->arm_mat[3], bone->head);
1530 /* and the kiddies */
1532 for (bone = bone->childbase.first; bone; bone = bone->next) {
1533 BKE_armature_where_is_bone(bone, prevbone);
1537 /* updates vectors and matrices on rest-position level, only needed
1538 * after editing armature itself, now only on reading file */
1539 void BKE_armature_where_is(bArmature *arm)
1543 /* hierarchical from root to children */
1544 for (bone = arm->bonebase.first; bone; bone = bone->next) {
1545 BKE_armature_where_is_bone(bone, NULL);
1549 /* if bone layer is protected, copy the data from from->pose
1550 * when used with linked libraries this copies from the linked pose into the local pose */
1551 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1553 bPose *pose = ob->pose, *frompose = from->pose;
1554 bPoseChannel *pchan, *pchanp, pchanw;
1558 if (frompose == NULL)
1561 /* in some cases when rigs change, we cant synchronize
1562 * to avoid crashing check for possible errors here */
1563 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1564 if (pchan->bone->layer & layer_protected) {
1565 if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
1566 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n",
1567 from->id.name, pchan->name);
1576 /* clear all transformation values from library */
1577 BKE_pose_rest(frompose);
1579 /* copy over all of the proxy's bone groups */
1581 * - implement 'local' bone groups as for constraints
1582 * Note: this isn't trivial, as bones reference groups by index not by pointer,
1583 * so syncing things correctly needs careful attention */
1584 BLI_freelistN(&pose->agroups);
1585 BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1586 pose->active_group = frompose->active_group;
1588 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1589 pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
1591 if (pchan->bone->layer & layer_protected) {
1592 ListBase proxylocal_constraints = {NULL, NULL};
1594 /* copy posechannel to temp, but restore important pointers */
1596 pchanw.prev = pchan->prev;
1597 pchanw.next = pchan->next;
1598 pchanw.parent = pchan->parent;
1599 pchanw.child = pchan->child;
1601 /* this is freed so copy a copy, else undo crashes */
1603 pchanw.prop = IDP_CopyProperty(pchanw.prop);
1605 /* use the values from the the existing props */
1607 IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1611 /* constraints - proxy constraints are flushed... local ones are added after
1612 * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1613 * 2. copy proxy-pchan's constraints on-to new
1614 * 3. add extracted local constraints back on top
1616 * Note for copy_constraints: when copying constraints, disable 'do_extern' otherwise
1617 * we get the libs direct linked in this blend. */
1618 extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
1619 copy_constraints(&pchanw.constraints, &pchanp->constraints, FALSE);
1620 BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1622 /* constraints - set target ob pointer to own object */
1623 for (con = pchanw.constraints.first; con; con = con->next) {
1624 bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
1625 ListBase targets = {NULL, NULL};
1626 bConstraintTarget *ct;
1628 if (cti && cti->get_constraint_targets) {
1629 cti->get_constraint_targets(con, &targets);
1631 for (ct = targets.first; ct; ct = ct->next) {
1632 if (ct->tar == from)
1636 if (cti->flush_constraint_targets)
1637 cti->flush_constraint_targets(con, &targets, 0);
1641 /* free stuff from current channel */
1642 BKE_pose_channel_free(pchan);
1644 /* the final copy */
1648 /* always copy custom shape */
1649 pchan->custom = pchanp->custom;
1650 pchan->custom_tx = pchanp->custom_tx;
1652 /* ID-Property Syncing */
1654 IDProperty *prop_orig = pchan->prop;
1656 pchan->prop = IDP_CopyProperty(pchanp->prop);
1658 /* copy existing values across when types match */
1659 IDP_SyncGroupValues(pchan->prop, prop_orig);
1666 IDP_FreeProperty(prop_orig);
1667 MEM_freeN(prop_orig);
1674 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1676 bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
1679 pchan->parent = parchan;
1683 for (bone = bone->childbase.first; bone; bone = bone->next) {
1684 counter = rebuild_pose_bone(pose, bone, pchan, counter);
1685 /* for quick detecting of next bone in chain, only b-bone uses it now */
1686 if (bone->flag & BONE_CONNECTED)
1687 pchan->child = BKE_pose_channel_find_name(pose, bone->name);
1693 /* only after leave editmode, duplicating, validating older files, library syncing */
1694 /* NOTE: pose->flag is set for it */
1695 void BKE_pose_rebuild(Object *ob, bArmature *arm)
1699 bPoseChannel *pchan, *next;
1702 /* only done here */
1703 if (ob->pose == NULL) {
1704 /* create new pose */
1705 ob->pose = MEM_callocN(sizeof(bPose), "new pose");
1707 /* set default settings for animviz */
1708 animviz_settings_init(&ob->pose->avs);
1713 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1715 pchan->child = NULL;
1718 /* first step, check if all channels are there */
1719 for (bone = arm->bonebase.first; bone; bone = bone->next) {
1720 counter = rebuild_pose_bone(pose, bone, NULL, counter);
1723 /* and a check for garbage */
1724 for (pchan = pose->chanbase.first; pchan; pchan = next) {
1726 if (pchan->bone == NULL) {
1727 BKE_pose_channel_free(pchan);
1728 BKE_pose_channels_hash_free(pose);
1729 BLI_freelinkN(&pose->chanbase, pchan);
1732 /* printf("rebuild pose %s, %d bones\n", ob->id.name, counter); */
1734 /* synchronize protected layers with proxy */
1736 BKE_object_copy_proxy_drivers(ob, ob->proxy);
1737 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1740 BKE_pose_update_constraint_flags(ob->pose); /* for IK detection for example */
1746 ob->pose->flag &= ~POSE_RECALC;
1747 ob->pose->flag |= POSE_WAS_REBUILT;
1749 BKE_pose_channels_hash_make(ob->pose);
1753 /* ********************** SPLINE IK SOLVER ******************* */
1755 /* Temporary evaluation tree data used for Spline IK */
1756 typedef struct tSplineIK_Tree {
1757 struct tSplineIK_Tree *next, *prev;
1759 int type; /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
1761 short free_points; /* free the point positions array */
1762 short chainlen; /* number of bones in the chain */
1764 float *points; /* parametric positions for the joints along the curve */
1765 bPoseChannel **chain; /* chain of bones to affect using Spline IK (ordered from the tip) */
1767 bPoseChannel *root; /* bone that is the root node of the chain */
1769 bConstraint *con; /* constraint for this chain */
1770 bSplineIKConstraint *ikData; /* constraint settings for this chain */
1775 /* Tag the bones in the chain formed by the given bone for IK */
1776 static void splineik_init_tree_from_pchan(Scene *scene, Object *UNUSED(ob), bPoseChannel *pchan_tip)
1778 bPoseChannel *pchan, *pchanRoot = NULL;
1779 bPoseChannel *pchanChain[255];
1780 bConstraint *con = NULL;
1781 bSplineIKConstraint *ikData = NULL;
1782 float boneLengths[255], *jointPoints;
1783 float totLength = 0.0f;
1784 short free_joints = 0;
1787 /* find the SplineIK constraint */
1788 for (con = pchan_tip->constraints.first; con; con = con->next) {
1789 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
1792 /* target can only be curve */
1793 if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))
1795 /* skip if disabled */
1796 if ((con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)))
1799 /* otherwise, constraint is ok... */
1806 /* make sure that the constraint targets are ok
1807 * - this is a workaround for a depsgraph bug...
1810 Curve *cu = ikData->tar->data;
1812 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1813 * currently for paths to work it needs to go through the bevlist/displist system (ton)
1816 /* only happens on reload file, but violates depsgraph still... fix! */
1817 if ((cu->path == NULL) || (cu->path->data == NULL))
1818 BKE_displist_make_curveTypes(scene, ikData->tar, 0);
1821 /* find the root bone and the chain of bones from the root to the tip
1822 * NOTE: this assumes that the bones are connected, but that may not be true... */
1823 for (pchan = pchan_tip; pchan && (segcount < ikData->chainlen); pchan = pchan->parent, segcount++) {
1824 /* store this segment in the chain */
1825 pchanChain[segcount] = pchan;
1827 /* if performing rebinding, calculate the length of the bone */
1828 boneLengths[segcount] = pchan->bone->length;
1829 totLength += boneLengths[segcount];
1835 pchanRoot = pchanChain[segcount - 1];
1837 /* perform binding step if required */
1838 if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
1839 float segmentLen = (1.0f / (float)segcount);
1842 /* setup new empty array for the points list */
1844 MEM_freeN(ikData->points);
1845 ikData->numpoints = ikData->chainlen + 1;
1846 ikData->points = MEM_callocN(sizeof(float) * ikData->numpoints, "Spline IK Binding");
1848 /* bind 'tip' of chain (i.e. first joint = tip of bone with the Spline IK Constraint) */
1849 ikData->points[0] = 1.0f;
1851 /* perform binding of the joints to parametric positions along the curve based
1852 * proportion of the total length that each bone occupies
1854 for (i = 0; i < segcount; i++) {
1855 /* 'head' joints, traveling towards the root of the chain
1856 * - 2 methods; the one chosen depends on whether we've got usable lengths
1858 if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
1859 /* 1) equi-spaced joints */
1860 ikData->points[i + 1] = ikData->points[i] - segmentLen;
1863 /* 2) to find this point on the curve, we take a step from the previous joint
1864 * a distance given by the proportion that this bone takes
1866 ikData->points[i + 1] = ikData->points[i] - (boneLengths[i] / totLength);
1870 /* spline has now been bound */
1871 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
1874 /* apply corrections for sensitivity to scaling on a copy of the bind points,
1875 * since it's easier to determine the positions of all the joints beforehand this way
1877 if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
1878 Curve *cu = (Curve *)ikData->tar->data;
1879 float splineLen, maxScale;
1882 /* make a copy of the points array, that we'll store in the tree
1883 * - although we could just multiply the points on the fly, this approach means that
1884 * we can introduce per-segment stretchiness later if it is necessary
1886 jointPoints = MEM_dupallocN(ikData->points);
1889 /* get the current length of the curve */
1890 /* NOTE: this is assumed to be correct even after the curve was resized */
1891 splineLen = cu->path->totdist;
1893 /* calculate the scale factor to multiply all the path values by so that the
1894 * bone chain retains its current length, such that
1895 * maxScale * splineLen = totLength
1897 maxScale = totLength / splineLen;
1899 /* apply scaling correction to all of the temporary points */
1900 /* TODO: this is really not adequate enough on really short chains */
1901 for (i = 0; i < segcount; i++)
1902 jointPoints[i] *= maxScale;
1905 /* just use the existing points array */
1906 jointPoints = ikData->points;
1910 /* make a new Spline-IK chain, and store it in the IK chains */
1911 /* TODO: we should check if there is already an IK chain on this, since that would take presidence... */
1914 tSplineIK_Tree *tree = MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
1915 tree->type = CONSTRAINT_TYPE_SPLINEIK;
1917 tree->chainlen = segcount;
1919 /* copy over the array of links to bones in the chain (from tip to root) */
1920 tree->chain = MEM_callocN(sizeof(bPoseChannel *) * segcount, "SplineIK Chain");
1921 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel *) * segcount);
1923 /* store reference to joint position array */
1924 tree->points = jointPoints;
1925 tree->free_points = free_joints;
1927 /* store references to different parts of the chain */
1928 tree->root = pchanRoot;
1930 tree->ikData = ikData;
1932 /* AND! link the tree to the root */
1933 BLI_addtail(&pchanRoot->siktree, tree);
1936 /* mark root channel having an IK tree */
1937 pchanRoot->flag |= POSE_IKSPLINE;
1940 /* Tag which bones are members of Spline IK chains */
1941 static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime))
1943 bPoseChannel *pchan;
1945 /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
1946 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1947 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
1948 splineik_init_tree_from_pchan(scene, ob, pchan);
1954 /* Evaluate spline IK for a given bone */
1955 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan,
1956 int index, float ctime)
1958 bSplineIKConstraint *ikData = tree->ikData;
1959 float poseHead[3], poseTail[3], poseMat[4][4];
1960 float splineVec[3], scaleFac, radius = 1.0f;
1962 /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
1963 BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);
1965 copy_v3_v3(poseHead, pchan->pose_head);
1966 copy_v3_v3(poseTail, pchan->pose_tail);
1968 /* step 1: determine the positions for the endpoints of the bone */
1970 float vec[4], dir[3], rad;
1971 float tailBlendFac = 1.0f;
1973 /* determine if the bone should still be affected by SplineIK */
1974 if (tree->points[index + 1] >= 1.0f) {
1975 /* spline doesn't affect the bone anymore, so done... */
1976 pchan->flag |= POSE_DONE;
1979 else if ((tree->points[index] >= 1.0f) && (tree->points[index + 1] < 1.0f)) {
1980 /* blending factor depends on the amount of the bone still left on the chain */
1981 tailBlendFac = (1.0f - tree->points[index + 1]) / (tree->points[index] - tree->points[index + 1]);
1985 if (where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL)) {
1986 /* apply curve's object-mode transforms to the position
1987 * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1989 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1990 mul_m4_v3(ikData->tar->obmat, vec);
1992 /* convert the position to pose-space, then store it */
1993 mul_m4_v3(ob->imat, vec);
1994 interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
1996 /* set the new radius */
2001 if (where_on_path(ikData->tar, tree->points[index + 1], vec, dir, NULL, &rad, NULL)) {
2002 /* apply curve's object-mode transforms to the position
2003 * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
2005 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
2006 mul_m4_v3(ikData->tar->obmat, vec);
2008 /* store the position, and convert it to pose space */
2009 mul_m4_v3(ob->imat, vec);
2010 copy_v3_v3(poseHead, vec);
2012 /* set the new radius (it should be the average value) */
2013 radius = (radius + rad) / 2;
2017 /* step 2: determine the implied transform from these endpoints
2018 * - splineVec: the vector direction that the spline applies on the bone
2019 * - scaleFac: the factor that the bone length is scaled by to get the desired amount
2021 sub_v3_v3v3(splineVec, poseTail, poseHead);
2022 scaleFac = len_v3(splineVec) / pchan->bone->length;
2024 /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis
2025 * - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
2028 float dmat[3][3], rmat[3][3], tmat[3][3];
2029 float raxis[3], rangle;
2031 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
2032 * orientation-relevant axes, and normalizing them
2034 copy_v3_v3(rmat[0], pchan->pose_mat[0]);
2035 copy_v3_v3(rmat[1], pchan->pose_mat[1]);
2036 copy_v3_v3(rmat[2], pchan->pose_mat[2]);
2039 /* also, normalize the orientation imposed by the bone, now that we've extracted the scale factor */
2040 normalize_v3(splineVec);
2042 /* calculate smallest axis-angle rotation necessary for getting from the
2043 * current orientation of the bone, to the spline-imposed direction
2045 cross_v3_v3v3(raxis, rmat[1], splineVec);
2047 rangle = dot_v3v3(rmat[1], splineVec);
2048 rangle = acos(MAX2(-1.0f, MIN2(1.0f, rangle)));
2050 /* multiply the magnitude of the angle by the influence of the constraint to
2051 * control the influence of the SplineIK effect
2053 rangle *= tree->con->enforce;
2055 /* construct rotation matrix from the axis-angle rotation found above
2056 * - this call takes care to make sure that the axis provided is a unit vector first
2058 axis_angle_to_mat3(dmat, raxis, rangle);
2060 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
2061 * while still maintaining roll control from the existing bone animation
2063 mul_m3_m3m3(tmat, dmat, rmat); /* m1, m3, m2 */
2064 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
2065 copy_m4_m3(poseMat, tmat);
2068 /* step 4: set the scaling factors for the axes */
2070 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
2071 mul_v3_fl(poseMat[1], scaleFac);
2073 /* set the scaling factors of the x and z axes from... */
2074 switch (ikData->xzScaleMode) {
2075 case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
2077 /* original scales get used */
2081 scale = len_v3(pchan->pose_mat[0]);
2082 mul_v3_fl(poseMat[0], scale);
2084 scale = len_v3(pchan->pose_mat[2]);
2085 mul_v3_fl(poseMat[2], scale);
2088 case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
2090 /* 'volume preservation' */
2093 /* calculate volume preservation factor which is
2094 * basically the inverse of the y-scaling factor
2096 if (fabsf(scaleFac) != 0.0f) {
2097 scale = 1.0f / fabsf(scaleFac);
2099 /* we need to clamp this within sensible values */
2100 /* NOTE: these should be fine for now, but should get sanitised in future */
2101 CLAMP(scale, 0.0001f, 100000.0f);
2106 /* apply the scaling */
2107 mul_v3_fl(poseMat[0], scale);
2108 mul_v3_fl(poseMat[2], scale);
2113 /* finally, multiply the x and z scaling by the radius of the curve too,
2114 * to allow automatic scales to get tweaked still
2116 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
2117 mul_v3_fl(poseMat[0], radius);
2118 mul_v3_fl(poseMat[2], radius);
2122 /* step 5: set the location of the bone in the matrix */
2123 if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
2124 /* when the 'no-root' option is affected, the chain can retain
2125 * the shape but be moved elsewhere
2127 copy_v3_v3(poseHead, pchan->pose_head);
2129 else if (tree->con->enforce < 1.0f) {
2130 /* when the influence is too low
2131 * - blend the positions for the 'root' bone
2132 * - stick to the parent for any other
2134 if (pchan->parent) {
2135 copy_v3_v3(poseHead, pchan->pose_head);
2138 /* FIXME: this introduces popping artifacts when we reach 0.0 */
2139 interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
2142 copy_v3_v3(poseMat[3], poseHead);
2144 /* finally, store the new transform */
2145 copy_m4_m4(pchan->pose_mat, poseMat);
2146 copy_v3_v3(pchan->pose_head, poseHead);
2148 /* recalculate tail, as it's now outdated after the head gets adjusted above! */
2149 BKE_pose_where_is_bone_tail(pchan);
2152 pchan->flag |= POSE_DONE;
2155 /* Evaluate the chain starting from the nominated bone */
2156 static void splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
2158 tSplineIK_Tree *tree;
2160 /* for each pose-tree, execute it if it is spline, otherwise just free it */
2161 while ((tree = pchan_root->siktree.first) != NULL) {
2164 /* walk over each bone in the chain, calculating the effects of spline IK
2165 * - the chain is traversed in the opposite order to storage order (i.e. parent to children)
2166 * so that dependencies are correct
2168 for (i = tree->chainlen - 1; i >= 0; i--) {
2169 bPoseChannel *pchan = tree->chain[i];
2170 splineik_evaluate_bone(tree, scene, ob, pchan, i, ctime);
2173 /* free the tree info specific to SplineIK trees now */
2175 MEM_freeN(tree->chain);
2176 if (tree->free_points)
2177 MEM_freeN(tree->points);
2179 /* free this tree */
2180 BLI_freelinkN(&pchan_root->siktree, tree);
2184 /* ********************** THE POSE SOLVER ******************* */
2186 /* loc/rot/size to given mat4 */
2187 void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2193 /* get scaling matrix */
2194 size_to_mat3(smat, pchan->size);
2196 /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2197 if (pchan->rotmode > 0) {
2198 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2199 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2201 else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2202 /* axis-angle - not really that great for 3D-changing orientations */
2203 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2206 /* quats are normalised before use to eliminate scaling issues */
2209 /* NOTE: we now don't normalize the stored values anymore, since this was kindof evil in some cases
2210 * but if this proves to be too problematic, switch back to the old system of operating directly on
2213 normalize_qt_qt(quat, pchan->quat);
2214 quat_to_mat3(rmat, quat);
2217 /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2218 mul_m3_m3m3(tmat, rmat, smat);
2219 copy_m4_m3(chan_mat, tmat);
2221 /* prevent action channels breaking chains */
2222 /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2223 if ((pchan->bone == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2224 copy_v3_v3(chan_mat[3], pchan->loc);
2228 /* loc/rot/size to mat4 */
2229 /* used in constraint.c too */
2230 void BKE_pchan_calc_mat(bPoseChannel *pchan)
2232 /* this is just a wrapper around the copy of this function which calculates the matrix
2233 * and stores the result in any given channel
2235 BKE_pchan_to_mat4(pchan, pchan->chan_mat);
2238 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2240 /* NLA strip modifiers */
2241 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2243 bActionModifier *amod;
2244 bActionStrip *strip, *strip2;
2245 float scene_cfra = (float)scene->r.cfra;
2248 for (strip = armob->nlastrips.first; strip; strip = strip->next) {
2251 if (scene_cfra >= strip->start && scene_cfra <= strip->end)
2254 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2257 /* if there are any other strips active, ignore modifiers for this strip -
2258 * 'hold' option should only hold action modifiers if there are
2259 * no other active strips */
2260 for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2261 if (strip2 == strip) continue;
2263 if (scene_cfra >= strip2->start && scene_cfra <= strip2->end) {
2264 if (!(strip2->flag & ACTSTRIP_MUTE))
2269 /* if there are any later, activated, strips with 'hold' set, they take precedence,
2270 * so ignore modifiers for this strip */
2271 for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2272 if (scene_cfra < strip2->start) continue;
2273 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2280 /* temporal solution to prevent 2 strips accumulating */
2281 if (scene_cfra == strip->end && strip->next && strip->next->start == scene_cfra)
2284 for (amod = strip->modifiers.first; amod; amod = amod->next) {
2285 switch (amod->type) {
2286 case ACTSTRIP_MOD_DEFORM:
2288 /* validate first */
2289 if (amod->ob && amod->ob->type == OB_CURVE && amod->channel[0]) {
2291 if (strcmp(pchan->name, amod->channel) == 0) {
2292 float mat4[4][4], mat3[3][3];
2294 curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2295 copy_m4_m4(mat4, pchan->pose_mat);
2296 mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2302 case ACTSTRIP_MOD_NOISE:
2304 if (strcmp(pchan->name, amod->channel) == 0) {
2305 float nor[3], loc[3], ofs;
2306 float eul[3], size[3], eulo[3], sizeo[3];
2308 /* calculate turbulance */
2309 ofs = amod->turbul / 200.0f;
2311 /* make a copy of starting conditions */
2312 copy_v3_v3(loc, pchan->pose_mat[3]);
2313 mat4_to_eul(eul, pchan->pose_mat);
2314 mat4_to_size(size, pchan->pose_mat);
2315 copy_v3_v3(eulo, eul);
2316 copy_v3_v3(sizeo, size);
2318 /* apply noise to each set of channels */
2319 if (amod->channels & 4) {
2321 nor[0] = BLI_gNoise(amod->noisesize, size[0] + ofs, size[1], size[2], 0, 0) - ofs;
2322 nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1] + ofs, size[2], 0, 0) - ofs;
2323 nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2] + ofs, 0, 0) - ofs;
2324 add_v3_v3(size, nor);
2327 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2329 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2331 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2333 if (amod->channels & 2) {
2335 nor[0] = BLI_gNoise(amod->noisesize, eul[0] + ofs, eul[1], eul[2], 0, 0) - ofs;
2336 nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1] + ofs, eul[2], 0, 0) - ofs;
2337 nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2] + ofs, 0, 0) - ofs;
2339 compatible_eul(nor, eulo);
2340 add_v3_v3(eul, nor);
2341 compatible_eul(eul, eulo);
2343 loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2345 if (amod->channels & 1) {
2347 nor[0] = BLI_gNoise(amod->noisesize, loc[0] + ofs, loc[1], loc[2], 0, 0) - ofs;
2348 nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1] + ofs, loc[2], 0, 0) - ofs;
2349 nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2] + ofs, 0, 0) - ofs;
2351 add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2364 /* calculate tail of posechannel */
2365 void BKE_pose_where_is_bone_tail(bPoseChannel *pchan)
2369 copy_v3_v3(vec, pchan->pose_mat[1]);
2370 mul_v3_fl(vec, pchan->bone->length);
2371 add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2374 /* The main armature solver, does all constraints excluding IK */
2375 /* pchan is validated, as having bone and parent pointer
2376 * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2378 void BKE_pose_where_is_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, int do_extra)
2380 /* This gives a chan_mat with actions (ipos) results. */
2382 BKE_pchan_calc_mat(pchan);
2384 unit_m4(pchan->chan_mat);
2386 /* Construct the posemat based on PoseChannels, that we do before applying constraints. */
2387 /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2388 BKE_armature_mat_bone_to_pose(pchan, pchan->chan_mat, pchan->pose_mat);
2390 /* Only rootbones get the cyclic offset (unless user doesn't want that). */
2391 /* XXX That could be a problem for snapping and other "reverse transform" features... */
2392 if (!pchan->parent) {
2393 if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2394 add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2398 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2399 /* do NLA strip modifiers - i.e. curve follow */
2400 do_strip_modifiers(scene, ob, bone, pchan);
2403 /* Do constraints */
2404 if (pchan->constraints.first) {
2408 /* make a copy of location of PoseChannel for later */
2409 copy_v3_v3(vec, pchan->pose_mat[3]);
2411 /* prepare PoseChannel for Constraint solving
2412 * - makes a copy of matrix, and creates temporary struct to use
2414 cob = constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2416 /* Solve PoseChannel's Constraints */
2417 solve_constraints(&pchan->constraints, cob, ctime); /* ctime doesnt alter objects */
2419 /* cleanup after Constraint Solving
2420 * - applies matrix back to pchan, and frees temporary struct used
2422 constraints_clear_evalob(cob);
2424 /* prevent constraints breaking a chain */
2425 if (pchan->bone->flag & BONE_CONNECTED) {
2426 copy_v3_v3(pchan->pose_mat[3], vec);
2431 /* calculate head */
2432 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
2433 /* calculate tail */
2434 BKE_pose_where_is_bone_tail(pchan);
2437 /* This only reads anim data from channels, and writes to channels */
2438 /* This is the only function adding poses */
2439 void BKE_pose_where_is(Scene *scene, Object *ob)
2443 bPoseChannel *pchan;
2447 if (ob->type != OB_ARMATURE)
2451 if (ELEM(NULL, arm, scene))
2453 if ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC))
2454 BKE_pose_rebuild(ob, arm);
2456 ctime = BKE_scene_frame_get(scene); /* not accurate... */
2458 /* In editmode or restposition we read the data from the bones */
2459 if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
2460 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2463 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2464 copy_v3_v3(pchan->pose_head, bone->arm_head);
2465 copy_v3_v3(pchan->pose_tail, bone->arm_tail);
2470 invert_m4_m4(ob->imat, ob->obmat); /* imat is needed */
2472 /* 1. clear flags */
2473 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2474 pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
2477 /* 2a. construct the IK tree (standard IK) */
2478 BIK_initialize_tree(scene, ob, ctime);
2480 /* 2b. construct the Spline IK trees
2481 * - this is not integrated as an IK plugin, since it should be able
2482 * to function in conjunction with standard IK
2484 splineik_init_tree(scene, ob, ctime);
2486 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2487 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2488 /* 4a. if we find an IK root, we handle it separated */
2489 if (pchan->flag & POSE_IKTREE) {
2490 BIK_execute_tree(scene, ob, pchan, ctime);
2492 /* 4b. if we find a Spline IK root, we handle it separated too */
2493 else if (pchan->flag & POSE_IKSPLINE) {
2494 splineik_execute_tree(scene, ob, pchan, ctime);
2496 /* 5. otherwise just call the normal solver */
2497 else if (!(pchan->flag & POSE_DONE)) {
2498 BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);
2501 /* 6. release the IK tree */
2502 BIK_release_tree(scene, ob, ctime);
2505 /* calculating deform matrices */
2506 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2508 invert_m4_m4(imat, pchan->bone->arm_mat);
2509 mult_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
2515 /* Returns total selected vgroups,
2516 * wpi.defbase_sel is assumed malloc'd, all values are set */
2517 int get_selected_defgroups(Object *ob, char *dg_selection, int defbase_tot)
2519 bDeformGroup *defgroup;
2521 Object *armob = BKE_object_pose_armature_get(ob);
2522 int dg_flags_sel_tot = 0;
2525 bPose *pose = armob->pose;
2526 for (i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) {
2527 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, defgroup->name);
2528 if (pchan && (pchan->bone->flag & BONE_SELECTED)) {
2529 dg_selection[i] = TRUE;
2533 dg_selection[i] = FALSE;
2538 memset(dg_selection, FALSE, sizeof(char) * defbase_tot);
2541 return dg_flags_sel_tot;
2544 /************** Bounding box ********************/
2545 static int minmax_armature(Object *ob, float r_min[3], float r_max[3])
2547 bPoseChannel *pchan;
2549 /* For now, we assume BKE_pose_where_is has already been called (hence we have valid data in pachan). */
2550 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2551 minmax_v3v3_v3(r_min, r_max, pchan->pose_head);
2552 minmax_v3v3_v3(r_min, r_max, pchan->pose_tail);
2555 return (ob->pose->chanbase.first != NULL);
2558 static void boundbox_armature(Object *ob, float loc[3], float size[3])
2561 float min[3], max[3];
2562 float mloc[3], msize[3];
2565 ob->bb = MEM_callocN(sizeof(BoundBox), "Armature boundbox");
2573 INIT_MINMAX(min, max);
2574 if (!minmax_armature(ob, min, max)) {
2575 min[0] = min[1] = min[2] = -1.0f;
2576 max[0] = max[1] = max[2] = 1.0f;
2579 mid_v3_v3v3(loc, min, max);
2581 size[0] = (max[0] - min[0]) / 2.0f;
2582 size[1] = (max[1] - min[1]) / 2.0f;
2583 size[2] = (max[2] - min[2]) / 2.0f;
2585 BKE_boundbox_init_from_minmax(bb, min, max);
2588 BoundBox *BKE_armature_boundbox_get(Object *ob)
2590 boundbox_armature(ob, NULL, NULL);