4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21 * All rights reserved.
23 * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
25 * ***** END GPL LICENSE BLOCK *****
35 #include "MEM_guardedalloc.h"
38 #include "BLI_blenlib.h"
40 #include "DNA_anim_types.h"
41 #include "DNA_armature_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_lattice_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_nla_types.h"
47 #include "DNA_scene_types.h"
49 #include "BKE_animsys.h"
50 #include "BKE_armature.h"
51 #include "BKE_action.h"
53 #include "BKE_constraint.h"
54 #include "BKE_curve.h"
55 #include "BKE_depsgraph.h"
56 #include "BKE_DerivedMesh.h"
57 #include "BKE_displist.h"
58 #include "BKE_global.h"
59 #include "BKE_idprop.h"
60 #include "BKE_library.h"
61 #include "BKE_lattice.h"
63 #include "BKE_object.h"
64 #include "BKE_utildefines.h"
66 #include "BKE_sketch.h"
72 /* **************** Generic Functions, data level *************** */
74 bArmature *add_armature(char *name)
78 arm= alloc_libblock (&G.main->armature, ID_AR, name);
79 arm->deformflag = ARM_DEF_VGROUP|ARM_DEF_ENVELOPE;
80 arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
85 bArmature *get_armature(Object *ob)
87 if(ob->type==OB_ARMATURE)
88 return (bArmature *)ob->data;
92 void free_bonelist (ListBase *lb)
96 for(bone=lb->first; bone; bone=bone->next) {
98 IDP_FreeProperty(bone->prop);
99 MEM_freeN(bone->prop);
101 free_bonelist(&bone->childbase);
107 void free_armature(bArmature *arm)
110 free_bonelist(&arm->bonebase);
112 /* free editmode data */
114 BLI_freelistN(arm->edbo);
116 MEM_freeN(arm->edbo);
122 freeSketch(arm->sketch);
126 /* free animation data */
128 BKE_free_animdata(&arm->id);
134 void make_local_armature(bArmature *arm)
144 arm->id.flag= LIB_LOCAL;
145 new_id(0, (ID*)arm, 0);
149 if(local && lib==0) {
151 arm->id.flag= LIB_LOCAL;
152 new_id(0, (ID *)arm, 0);
154 else if(local && lib) {
155 newArm= copy_armature(arm);
158 ob= G.main->object.first;
173 static void copy_bonechildren (Bone* newBone, Bone* oldBone, Bone* actBone, Bone **newActBone)
175 Bone *curBone, *newChildBone;
177 if(oldBone == actBone)
178 *newActBone= newBone;
181 newBone->prop= IDP_CopyProperty(oldBone->prop);
183 /* Copy this bone's list*/
184 BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
186 /* For each child in the list, update it's children*/
187 newChildBone=newBone->childbase.first;
188 for (curBone=oldBone->childbase.first;curBone;curBone=curBone->next){
189 newChildBone->parent=newBone;
190 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
191 newChildBone=newChildBone->next;
195 bArmature *copy_armature(bArmature *arm)
198 Bone *oldBone, *newBone;
199 Bone *newActBone= NULL;
201 newArm= copy_libblock (arm);
202 BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
204 /* Duplicate the childrens' lists*/
205 newBone=newArm->bonebase.first;
206 for (oldBone=arm->bonebase.first;oldBone;oldBone=oldBone->next){
207 newBone->parent=NULL;
208 copy_bonechildren (newBone, oldBone, arm->act_bone, &newActBone);
209 newBone=newBone->next;
212 newArm->act_bone= newActBone;
216 static Bone *get_named_bone_bonechildren (Bone *bone, const char *name)
218 Bone *curBone, *rbone;
220 if (!strcmp (bone->name, name))
223 for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
224 rbone=get_named_bone_bonechildren (curBone, name);
233 Bone *get_named_bone (bArmature *arm, const char *name)
235 Walk the list until the bone is found
238 Bone *bone=NULL, *curBone;
240 if (!arm) return NULL;
242 for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
243 bone = get_named_bone_bonechildren (curBone, name);
252 #define IS_SEPARATOR(a) (a=='.' || a==' ' || a=='-' || a=='_')
254 /* finds the best possible flipped name. For renaming; check for unique names afterwards */
255 /* if strip_number: removes number extensions */
256 void bone_flip_name (char *name, int strip_number)
259 char prefix[128]={""}; /* The part before the facing */
260 char suffix[128]={""}; /* The part after the facing */
261 char replace[128]={""}; /* The replacement string */
262 char number[128]={""}; /* The number extension string */
266 if(len<3) return; // we don't do names like .R or .L
268 /* We first check the case with a .### extension, let's find the last period */
269 if(isdigit(name[len-1])) {
270 index= strrchr(name, '.'); // last occurrence
271 if (index && isdigit(index[1]) ) { // doesnt handle case bone.1abc2 correct..., whatever!
273 strcpy(number, index);
279 strcpy (prefix, name);
281 /* first case; separator . - _ with extensions r R l L */
282 if( IS_SEPARATOR(name[len-2]) ) {
283 switch(name[len-1]) {
286 strcpy(replace, "r");
290 strcpy(replace, "l");
294 strcpy(replace, "R");
298 strcpy(replace, "L");
302 /* case; beginning with r R l L , with separator after it */
303 else if( IS_SEPARATOR(name[1]) ) {
306 strcpy(replace, "r");
307 strcpy(suffix, name+1);
311 strcpy(replace, "l");
312 strcpy(suffix, name+1);
316 strcpy(replace, "R");
317 strcpy(suffix, name+1);
321 strcpy(replace, "L");
322 strcpy(suffix, name+1);
328 /* hrms, why test for a separator? lets do the rule 'ultimate left or right' */
329 index = BLI_strcasestr(prefix, "right");
330 if (index==prefix || index==prefix+len-5) {
332 strcpy (replace, "left");
335 strcpy (replace, "LEFT");
337 strcpy (replace, "Left");
340 strcpy (suffix, index+5);
343 index = BLI_strcasestr(prefix, "left");
344 if (index==prefix || index==prefix+len-4) {
346 strcpy (replace, "right");
349 strcpy (replace, "RIGHT");
351 strcpy (replace, "Right");
354 strcpy (suffix, index+4);
359 sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
362 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for unique names afterwards)
363 * This assumes that bone names are at most 32 chars long!
364 * strip_number: removes number extensions (TODO: not used)
365 * axis: the axis to name on
366 * head/tail: the head/tail co-ordinate of the bone on the specified axis
368 void bone_autoside_name (char *name, int strip_number, short axis, float head, float tail)
371 char basename[32]={""};
372 char extension[5]={""};
375 if (len == 0) return;
376 strcpy(basename, name);
378 /* Figure out extension to append:
379 * - The extension to append is based upon the axis that we are working on.
380 * - If head happens to be on 0, then we must consider the tail position as well to decide
381 * which side the bone is on
382 * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
383 * -> Otherwise, extension is added from perspective of object based on which side tail goes to
384 * - If head is non-zero, extension is added from perspective of object based on side head is on
387 /* z-axis - vertical (top/bottom) */
388 if (IS_EQ(head, 0)) {
390 strcpy(extension, "Bot");
392 strcpy(extension, "Top");
396 strcpy(extension, "Bot");
398 strcpy(extension, "Top");
401 else if (axis == 1) {
402 /* y-axis - depth (front/back) */
403 if (IS_EQ(head, 0)) {
405 strcpy(extension, "Fr");
407 strcpy(extension, "Bk");
411 strcpy(extension, "Fr");
413 strcpy(extension, "Bk");
417 /* x-axis - horizontal (left/right) */
418 if (IS_EQ(head, 0)) {
420 strcpy(extension, "R");
422 strcpy(extension, "L");
426 strcpy(extension, "R");
428 strcpy(extension, "L");
432 /* Simple name truncation
433 * - truncate if there is an extension and it wouldn't be able to fit
434 * - otherwise, just append to end
439 while (change) { /* remove extensions */
441 if (len > 2 && basename[len-2]=='.') {
442 if (basename[len-1]=='L' || basename[len-1] == 'R' ) { /* L R */
443 basename[len-2] = '\0';
447 } else if (len > 3 && basename[len-3]=='.') {
448 if ( (basename[len-2]=='F' && basename[len-1] == 'r') || /* Fr */
449 (basename[len-2]=='B' && basename[len-1] == 'k') /* Bk */
451 basename[len-3] = '\0';
455 } else if (len > 4 && basename[len-4]=='.') {
456 if ( (basename[len-3]=='T' && basename[len-2]=='o' && basename[len-1] == 'p') || /* Top */
457 (basename[len-3]=='B' && basename[len-2]=='o' && basename[len-1] == 't') /* Bot */
459 basename[len-4] = '\0';
466 if ((32 - len) < strlen(extension) + 1) { /* add 1 for the '.' */
467 strncpy(name, basename, len-strlen(extension));
471 sprintf(name, "%s.%s", basename, extension);
474 /* ************* B-Bone support ******************* */
476 #define MAX_BBONE_SUBDIV 32
478 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
479 static void equalize_bezier(float *data, int desired)
481 float *fp, totdist, ddist, dist, fac1, fac2;
482 float pdist[MAX_BBONE_SUBDIV+1];
483 float temp[MAX_BBONE_SUBDIV+1][4];
487 for(a=0, fp= data; a<MAX_BBONE_SUBDIV; a++, fp+=4) {
488 QUATCOPY(temp[a], fp);
489 pdist[a+1]= pdist[a]+len_v3v3(fp, fp+4);
492 QUATCOPY(temp[a], fp);
495 /* go over distances and calculate new points */
496 ddist= totdist/((float)desired);
498 for(a=1, fp= data+4; a<desired; a++, fp+=4) {
500 dist= ((float)a)*ddist;
502 /* we're looking for location (distance) 'dist' in the array */
503 while((dist>= pdist[nr]) && nr<MAX_BBONE_SUBDIV) {
507 fac1= pdist[nr]- pdist[nr-1];
508 fac2= pdist[nr]-dist;
512 fp[0]= fac1*temp[nr-1][0]+ fac2*temp[nr][0];
513 fp[1]= fac1*temp[nr-1][1]+ fac2*temp[nr][1];
514 fp[2]= fac1*temp[nr-1][2]+ fac2*temp[nr][2];
515 fp[3]= fac1*temp[nr-1][3]+ fac2*temp[nr][3];
517 /* set last point, needed for orientation calculus */
518 QUATCOPY(fp, temp[MAX_BBONE_SUBDIV]);
521 /* returns pointer to static array, filled with desired amount of bone->segments elements */
522 /* this calculation is done within unit bone space */
523 Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
525 static Mat4 bbone_array[MAX_BBONE_SUBDIV];
526 static Mat4 bbone_rest_array[MAX_BBONE_SUBDIV];
527 Mat4 *result_array= (rest)? bbone_rest_array: bbone_array;
528 bPoseChannel *next, *prev;
529 Bone *bone= pchan->bone;
530 float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1=0.0f, roll2;
531 float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
532 float data[MAX_BBONE_SUBDIV+1][4], *fp;
535 length= bone->length;
538 /* check if we need to take non-uniform bone scaling into account */
539 scale[0]= len_v3(pchan->pose_mat[0]);
540 scale[1]= len_v3(pchan->pose_mat[1]);
541 scale[2]= len_v3(pchan->pose_mat[2]);
543 if(fabs(scale[0] - scale[1]) > 1e-6f || fabs(scale[1] - scale[2]) > 1e-6f) {
545 scalemat[0][0]= scale[0];
546 scalemat[1][1]= scale[1];
547 scalemat[2][2]= scale[2];
548 invert_m4_m4(iscalemat, scalemat);
555 hlength1= bone->ease1*length*0.390464f; // 0.5*sqrt(2)*kappa, the handle length for near-perfect circles
556 hlength2= bone->ease2*length*0.390464f;
558 /* evaluate next and prev bones */
559 if(bone->flag & BONE_CONNECTED)
566 /* find the handle points, since this is inside bone space, the
567 first point = (0,0,0)
568 last point = (0, length, 0) */
571 invert_m4_m4(imat, pchan->bone->arm_mat);
574 copy_m4_m4(posemat, pchan->pose_mat);
575 normalize_m4(posemat);
576 invert_m4_m4(imat, posemat);
579 invert_m4_m4(imat, pchan->pose_mat);
582 float difmat[4][4], result[3][3], imat3[3][3];
584 /* transform previous point inside this bone space */
586 VECCOPY(h1, prev->bone->arm_head)
588 VECCOPY(h1, prev->pose_head)
591 if(prev->bone->segments>1) {
592 /* if previous bone is B-bone too, use average handle direction */
598 mul_v3_fl(h1, -hlength1);
600 if(prev->bone->segments==1) {
601 /* find the previous roll to interpolate */
603 mul_m4_m4m4(difmat, prev->bone->arm_mat, imat);
605 mul_m4_m4m4(difmat, prev->pose_mat, imat);
606 copy_m3_m4(result, difmat); // the desired rotation at beginning of next bone
608 vec_roll_to_mat3(h1, 0.0f, mat3); // the result of vec_roll without roll
610 invert_m3_m3(imat3, mat3);
611 mul_m3_m3m3(mat3, result, imat3); // the matrix transforming vec_roll to desired roll
613 roll1= (float)atan2(mat3[2][0], mat3[2][2]);
617 h1[0]= 0.0f; h1[1]= hlength1; h1[2]= 0.0f;
621 float difmat[4][4], result[3][3], imat3[3][3];
623 /* transform next point inside this bone space */
625 VECCOPY(h2, next->bone->arm_tail)
627 VECCOPY(h2, next->pose_tail)
629 /* if next bone is B-bone too, use average handle direction */
630 if(next->bone->segments>1);
634 /* find the next roll to interpolate as well */
636 mul_m4_m4m4(difmat, next->bone->arm_mat, imat);
638 mul_m4_m4m4(difmat, next->pose_mat, imat);
639 copy_m3_m4(result, difmat); // the desired rotation at beginning of next bone
641 vec_roll_to_mat3(h2, 0.0f, mat3); // the result of vec_roll without roll
643 invert_m3_m3(imat3, mat3);
644 mul_m3_m3m3(mat3, imat3, result); // the matrix transforming vec_roll to desired roll
646 roll2= (float)atan2(mat3[2][0], mat3[2][2]);
648 /* and only now negate handle */
649 mul_v3_fl(h2, -hlength2);
652 h2[0]= 0.0f; h2[1]= -hlength2; h2[2]= 0.0f;
657 if(bone->segments > MAX_BBONE_SUBDIV)
658 bone->segments= MAX_BBONE_SUBDIV;
660 forward_diff_bezier(0.0, h1[0], h2[0], 0.0, data[0], MAX_BBONE_SUBDIV, 4*sizeof(float));
661 forward_diff_bezier(0.0, h1[1], length + h2[1], length, data[0]+1, MAX_BBONE_SUBDIV, 4*sizeof(float));
662 forward_diff_bezier(0.0, h1[2], h2[2], 0.0, data[0]+2, MAX_BBONE_SUBDIV, 4*sizeof(float));
663 forward_diff_bezier(roll1, roll1 + 0.390464f*(roll2-roll1), roll2 - 0.390464f*(roll2-roll1), roll2, data[0]+3, MAX_BBONE_SUBDIV, 4*sizeof(float));
665 equalize_bezier(data[0], bone->segments); // note: does stride 4!
667 /* make transformation matrices for the segments for drawing */
668 for(a=0, fp= data[0]; a<bone->segments; a++, fp+=4) {
669 sub_v3_v3v3(h1, fp+4, fp);
670 vec_roll_to_mat3(h1, fp[3], mat3); // fp[3] is roll
672 copy_m4_m3(result_array[a].mat, mat3);
673 VECCOPY(result_array[a].mat[3], fp);
676 /* correct for scaling when this matrix is used in scaled space */
677 mul_serie_m4(result_array[a].mat, iscalemat, result_array[a].mat,
678 scalemat, NULL, NULL, NULL, NULL, NULL);
685 /* ************ Armature Deform ******************* */
687 static void pchan_b_bone_defmats(bPoseChannel *pchan, int use_quaternion, int rest_def)
689 Bone *bone= pchan->bone;
690 Mat4 *b_bone= b_bone_spline_setup(pchan, 0);
691 Mat4 *b_bone_rest= (rest_def)? NULL: b_bone_spline_setup(pchan, 1);
693 DualQuat *b_bone_dual_quats= NULL;
697 /* allocate b_bone matrices and dual quats */
698 b_bone_mats= MEM_mallocN((1+bone->segments)*sizeof(Mat4), "BBone defmats");
699 pchan->b_bone_mats= b_bone_mats;
702 b_bone_dual_quats= MEM_mallocN((bone->segments)*sizeof(DualQuat), "BBone dqs");
703 pchan->b_bone_dual_quats= b_bone_dual_quats;
706 /* first matrix is the inverse arm_mat, to bring points in local bone space
707 for finding out which segment it belongs to */
708 invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
710 /* then we make the b_bone_mats:
711 - first transform to local bone space
712 - translate over the curve to the bbone mat space
713 - transform with b_bone matrix
714 - transform back into global space */
717 for(a=0; a<bone->segments; a++) {
719 invert_m4_m4(tmat, b_bone_rest[a].mat);
721 tmat[3][1] = -a*(bone->length/(float)bone->segments);
723 mul_serie_m4(b_bone_mats[a+1].mat, pchan->chan_mat, bone->arm_mat,
724 b_bone[a].mat, tmat, b_bone_mats[0].mat, NULL, NULL, NULL);
727 mat4_to_dquat( &b_bone_dual_quats[a],bone->arm_mat, b_bone_mats[a+1].mat);
731 static void b_bone_deform(bPoseChannel *pchan, Bone *bone, float *co, DualQuat *dq, float defmat[][3])
733 Mat4 *b_bone= pchan->b_bone_mats;
734 float (*mat)[4]= b_bone[0].mat;
738 /* need to transform co back to bonespace, only need y */
739 y= mat[0][1]*co[0] + mat[1][1]*co[1] + mat[2][1]*co[2] + mat[3][1];
741 /* now calculate which of the b_bones are deforming this */
742 segment= bone->length/((float)bone->segments);
745 /* note; by clamping it extends deform at endpoints, goes best with
746 straight joints in restpos. */
747 CLAMP(a, 0, bone->segments-1);
750 copy_dq_dq(dq, &((DualQuat*)pchan->b_bone_dual_quats)[a]);
753 mul_m4_v3(b_bone[a+1].mat, co);
756 copy_m3_m4(defmat, b_bone[a+1].mat);
760 /* using vec with dist to bone b1 - b2 */
761 float distfactor_to_bone (float vec[3], float b1[3], float b2[3], float rad1, float rad2, float rdist)
766 float hsqr, a, l, rad;
768 sub_v3_v3v3(bdelta, b2, b1);
769 l = normalize_v3(bdelta);
771 sub_v3_v3v3(pdelta, vec, b1);
773 a = bdelta[0]*pdelta[0] + bdelta[1]*pdelta[1] + bdelta[2]*pdelta[2];
774 hsqr = ((pdelta[0]*pdelta[0]) + (pdelta[1]*pdelta[1]) + (pdelta[2]*pdelta[2]));
777 /* If we're past the end of the bone, do a spherical field attenuation thing */
778 dist= ((b1[0]-vec[0])*(b1[0]-vec[0]) +(b1[1]-vec[1])*(b1[1]-vec[1]) +(b1[2]-vec[2])*(b1[2]-vec[2])) ;
782 /* If we're past the end of the bone, do a spherical field attenuation thing */
783 dist= ((b2[0]-vec[0])*(b2[0]-vec[0]) +(b2[1]-vec[1])*(b2[1]-vec[1]) +(b2[2]-vec[2])*(b2[2]-vec[2])) ;
787 dist= (hsqr - (a*a));
791 rad= rad*rad2 + (1.0f-rad)*rad1;
802 if(rdist==0.0f || dist >= l)
805 a= (float)sqrt(dist)-rad;
806 return 1.0f-( a*a )/( rdist*rdist );
811 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[][3], float mat[][3])
815 if(pchan->bone->segments>1)
816 copy_m3_m3(wmat, bbonemat);
818 copy_m3_m4(wmat, pchan->chan_mat);
820 mul_m3_fl(wmat, weight);
821 add_m3_m3m3(mat, mat, wmat);
824 static float dist_bone_deform(bPoseChannel *pchan, float *vec, DualQuat *dq, float mat[][3], float *co)
826 Bone *bone= pchan->bone;
827 float fac, contrib=0.0;
828 float cop[3], bbonemat[3][3];
831 if(bone==NULL) return 0.0f;
835 fac= distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
844 // applies on cop and bbonemat
845 b_bone_deform(pchan, bone, cop, NULL, (mat)?bbonemat:NULL);
847 mul_m4_v3(pchan->chan_mat, cop);
849 // Make this a delta from the base position
850 sub_v3_v3v3(cop, cop, co);
851 cop[0]*=fac; cop[1]*=fac; cop[2]*=fac;
852 add_v3_v3v3(vec, vec, cop);
855 pchan_deform_mat_add(pchan, fac, bbonemat, mat);
858 if(bone->segments>1) {
859 b_bone_deform(pchan, bone, cop, &bbonedq, NULL);
860 add_weighted_dq_dq(dq, &bbonedq, fac);
863 add_weighted_dq_dq(dq, pchan->dual_quat, fac);
871 static void pchan_bone_deform(bPoseChannel *pchan, float weight, float *vec, DualQuat *dq, float mat[][3], float *co, float *contrib)
873 float cop[3], bbonemat[3][3];
882 if(pchan->bone->segments>1)
883 // applies on cop and bbonemat
884 b_bone_deform(pchan, pchan->bone, cop, NULL, (mat)?bbonemat:NULL);
886 mul_m4_v3(pchan->chan_mat, cop);
888 vec[0]+=(cop[0]-co[0])*weight;
889 vec[1]+=(cop[1]-co[1])*weight;
890 vec[2]+=(cop[2]-co[2])*weight;
893 pchan_deform_mat_add(pchan, weight, bbonemat, mat);
896 if(pchan->bone->segments>1) {
897 b_bone_deform(pchan, pchan->bone, cop, &bbonedq, NULL);
898 add_weighted_dq_dq(dq, &bbonedq, weight);
901 add_weighted_dq_dq(dq, pchan->dual_quat, weight);
907 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm,
908 float (*vertexCos)[3], float (*defMats)[3][3],
909 int numVerts, int deformflag,
910 float (*prevCos)[3], const char *defgrp_name)
912 bArmature *arm= armOb->data;
913 bPoseChannel *pchan, **defnrToPC = NULL;
914 MDeformVert *dverts = NULL;
916 DualQuat *dualquats= NULL;
917 float obinv[4][4], premat[4][4], postmat[4][4];
918 int use_envelope = deformflag & ARM_DEF_ENVELOPE;
919 int use_quaternion = deformflag & ARM_DEF_QUATERNION;
920 int bbone_rest_def = deformflag & ARM_DEF_B_BONE_REST;
921 int invert_vgroup= deformflag & ARM_DEF_INVERT_VGROUP;
922 int numGroups = 0; /* safety for vertexgroup index overflow */
923 int i, target_totvert = 0; /* safety for vertexgroup overflow */
925 int armature_def_nr = -1;
928 if(arm->edbo) return;
930 invert_m4_m4(obinv, target->obmat);
931 copy_m4_m4(premat, target->obmat);
932 mul_m4_m4m4(postmat, armOb->obmat, obinv);
933 invert_m4_m4(premat, postmat);
935 /* bone defmats are already in the channels, chan_mat */
937 /* initialize B_bone matrices and dual quaternions */
939 totchan= BLI_countlist(&armOb->pose->chanbase);
940 dualquats= MEM_callocN(sizeof(DualQuat)*totchan, "dualquats");
944 for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next) {
945 if(!(pchan->bone->flag & BONE_NO_DEFORM)) {
946 if(pchan->bone->segments > 1)
947 pchan_b_bone_defmats(pchan, use_quaternion, bbone_rest_def);
950 pchan->dual_quat= &dualquats[totchan++];
951 mat4_to_dquat( pchan->dual_quat,pchan->bone->arm_mat, pchan->chan_mat);
956 /* get the def_nr for the overall armature vertex group if present */
957 for(i = 0, dg = target->defbase.first; dg; i++, dg = dg->next)
958 if(defgrp_name && strcmp(defgrp_name, dg->name) == 0)
961 /* get a vertex-deform-index to posechannel array */
962 if(deformflag & ARM_DEF_VGROUP) {
963 if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
964 numGroups = BLI_countlist(&target->defbase);
966 if(target->type==OB_MESH) {
967 Mesh *me= target->data;
969 target_totvert = me->totvert;
972 Lattice *lt= target->data;
975 target_totvert = lt->pntsu*lt->pntsv*lt->pntsw;
977 /* if we have a DerivedMesh, only use dverts if it has them */
979 if(dm->getVertData(dm, 0, CD_MDEFORMVERT))
982 else if(dverts) use_dverts = 1;
985 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * numGroups,
987 for(i = 0, dg = target->defbase.first; dg;
988 i++, dg = dg->next) {
989 defnrToPC[i] = get_pose_channel(armOb->pose, dg->name);
990 /* exclude non-deforming bones */
992 if(defnrToPC[i]->bone->flag & BONE_NO_DEFORM)
1000 for(i = 0; i < numVerts; i++) {
1002 DualQuat sumdq, *dq = NULL;
1004 float sumvec[3], summat[3][3];
1005 float *vec = NULL, (*smat)[3] = NULL;
1006 float contrib = 0.0f;
1007 float armature_weight = 1.0f; /* default to 1 if no overall def group */
1008 float prevco_weight = 1.0f; /* weight for optional cached vertexcos */
1011 if(use_quaternion) {
1012 memset(&sumdq, 0, sizeof(DualQuat));
1016 sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
1025 if(use_dverts || armature_def_nr >= 0) {
1026 if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
1027 else if(dverts && i < target_totvert) dvert = dverts + i;
1032 if(armature_def_nr >= 0 && dvert) {
1033 armature_weight = 0.0f; /* a def group was given, so default to 0 */
1034 for(j = 0; j < dvert->totweight; j++) {
1035 if(dvert->dw[j].def_nr == armature_def_nr) {
1036 armature_weight = dvert->dw[j].weight;
1040 /* hackish: the blending factor can be used for blending with prevCos too */
1043 prevco_weight= 1.0f-armature_weight;
1045 prevco_weight= armature_weight;
1046 armature_weight= 1.0f;
1050 /* check if there's any point in calculating for this vert */
1051 if(armature_weight == 0.0f) continue;
1053 /* get the coord we work on */
1054 co= prevCos?prevCos[i]:vertexCos[i];
1056 /* Apply the object's matrix */
1057 mul_m4_v3(premat, co);
1059 if(use_dverts && dvert && dvert->totweight) { // use weight groups ?
1062 for(j = 0; j < dvert->totweight; j++){
1063 int index = dvert->dw[j].def_nr;
1064 pchan = index < numGroups?defnrToPC[index]:NULL;
1066 float weight = dvert->dw[j].weight;
1067 Bone *bone = pchan->bone;
1071 if(bone && bone->flag & BONE_MULT_VG_ENV) {
1072 weight *= distfactor_to_bone(co, bone->arm_head,
1078 pchan_bone_deform(pchan, weight, vec, dq, smat, co, &contrib);
1081 /* if there are vertexgroups but not groups with bones
1082 * (like for softbody groups)
1084 if(deformed == 0 && use_envelope) {
1085 for(pchan = armOb->pose->chanbase.first; pchan;
1086 pchan = pchan->next) {
1087 if(!(pchan->bone->flag & BONE_NO_DEFORM))
1088 contrib += dist_bone_deform(pchan, vec, dq, smat, co);
1092 else if(use_envelope) {
1093 for(pchan = armOb->pose->chanbase.first; pchan;
1094 pchan = pchan->next) {
1095 if(!(pchan->bone->flag & BONE_NO_DEFORM))
1096 contrib += dist_bone_deform(pchan, vec, dq, smat, co);
1100 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1101 if(contrib > 0.0001f) {
1102 if(use_quaternion) {
1103 normalize_dq(dq, contrib);
1105 if(armature_weight != 1.0f) {
1107 mul_v3m3_dq( dco, (defMats)? summat: NULL,dq);
1108 sub_v3_v3v3(dco, dco, co);
1109 mul_v3_fl(dco, armature_weight);
1110 add_v3_v3v3(co, co, dco);
1113 mul_v3m3_dq( co, (defMats)? summat: NULL,dq);
1118 mul_v3_fl(vec, armature_weight/contrib);
1119 add_v3_v3v3(co, vec, co);
1123 float pre[3][3], post[3][3], tmpmat[3][3];
1125 copy_m3_m4(pre, premat);
1126 copy_m3_m4(post, postmat);
1127 copy_m3_m3(tmpmat, defMats[i]);
1129 if(!use_quaternion) /* quaternion already is scale corrected */
1130 mul_m3_fl(smat, armature_weight/contrib);
1132 mul_serie_m3(defMats[i], tmpmat, pre, smat, post,
1133 NULL, NULL, NULL, NULL);
1137 /* always, check above code */
1138 mul_m4_v3(postmat, co);
1141 /* interpolate with previous modifier position using weight group */
1143 float mw= 1.0f - prevco_weight;
1144 vertexCos[i][0]= prevco_weight*vertexCos[i][0] + mw*co[0];
1145 vertexCos[i][1]= prevco_weight*vertexCos[i][1] + mw*co[1];
1146 vertexCos[i][2]= prevco_weight*vertexCos[i][2] + mw*co[2];
1150 if(dualquats) MEM_freeN(dualquats);
1151 if(defnrToPC) MEM_freeN(defnrToPC);
1153 /* free B_bone matrices */
1154 for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next) {
1155 if(pchan->b_bone_mats) {
1156 MEM_freeN(pchan->b_bone_mats);
1157 pchan->b_bone_mats = NULL;
1159 if(pchan->b_bone_dual_quats) {
1160 MEM_freeN(pchan->b_bone_dual_quats);
1161 pchan->b_bone_dual_quats = NULL;
1164 pchan->dual_quat = NULL;
1168 /* ************ END Armature Deform ******************* */
1170 void get_objectspace_bone_matrix (struct Bone* bone, float M_accumulatedMatrix[][4], int root, int posed)
1172 copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1175 /* **************** Space to Space API ****************** */
1177 /* Convert World-Space Matrix to Pose-Space Matrix */
1178 void armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4])
1182 /* prevent crashes */
1183 if (ob==NULL) return;
1185 /* get inverse of (armature) object's matrix */
1186 invert_m4_m4(obmat, ob->obmat);
1188 /* multiply given matrix by object's-inverse to find pose-space matrix */
1189 mul_m4_m4m4(outmat, obmat, inmat);
1192 /* Convert Wolrd-Space Location to Pose-Space Location
1193 * NOTE: this cannot be used to convert to pose-space location of the supplied
1194 * pose-channel into its local space (i.e. 'visual'-keyframing)
1196 void armature_loc_world_to_pose(Object *ob, float *inloc, float *outloc)
1198 float xLocMat[4][4];
1199 float nLocMat[4][4];
1201 /* build matrix for location */
1203 VECCOPY(xLocMat[3], inloc);
1205 /* get bone-space cursor matrix and extract location */
1206 armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1207 VECCOPY(outloc, nLocMat[3]);
1210 /* Convert Pose-Space Matrix to Bone-Space Matrix
1211 * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1212 * pose-channel into its local space (i.e. 'visual'-keyframing)
1214 void armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1216 float pc_trans[4][4], inv_trans[4][4];
1217 float pc_posemat[4][4], inv_posemat[4][4];
1219 /* paranoia: prevent crashes with no pose-channel supplied */
1220 if (pchan==NULL) return;
1222 /* get the inverse matrix of the pchan's transforms */
1224 loc_eul_size_to_mat4(pc_trans, pchan->loc, pchan->eul, pchan->size);
1226 loc_quat_size_to_mat4(pc_trans, pchan->loc, pchan->quat, pchan->size);
1227 invert_m4_m4(inv_trans, pc_trans);
1229 /* Remove the pchan's transforms from it's pose_mat.
1230 * This should leave behind the effects of restpose +
1231 * parenting + constraints
1233 mul_m4_m4m4(pc_posemat, inv_trans, pchan->pose_mat);
1235 /* get the inverse of the leftovers so that we can remove
1236 * that component from the supplied matrix
1238 invert_m4_m4(inv_posemat, pc_posemat);
1240 /* get the new matrix */
1241 mul_m4_m4m4(outmat, inmat, inv_posemat);
1244 /* Convert Pose-Space Location to Bone-Space Location
1245 * NOTE: this cannot be used to convert to pose-space location of the supplied
1246 * pose-channel into its local space (i.e. 'visual'-keyframing)
1248 void armature_loc_pose_to_bone(bPoseChannel *pchan, float *inloc, float *outloc)
1250 float xLocMat[4][4];
1251 float nLocMat[4][4];
1253 /* build matrix for location */
1255 VECCOPY(xLocMat[3], inloc);
1257 /* get bone-space cursor matrix and extract location */
1258 armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1259 VECCOPY(outloc, nLocMat[3]);
1263 /* Apply a 4x4 matrix to the pose bone,
1264 * similar to object_apply_mat4()
1266 void pchan_apply_mat4(bPoseChannel *pchan, float mat[][4])
1269 copy_v3_v3(pchan->loc, mat[3]);
1272 mat4_to_size(pchan->size, mat);
1275 if (pchan->rotmode == ROT_MODE_AXISANGLE) {
1278 /* need to convert to quat first (in temp var)... */
1279 mat4_to_quat(tmp_quat, mat);
1280 quat_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, tmp_quat);
1282 else if (pchan->rotmode == ROT_MODE_QUAT) {
1283 mat4_to_quat(pchan->quat, mat);
1286 mat4_to_eulO(pchan->eul, pchan->rotmode, mat);
1290 /* Remove rest-position effects from pose-transform for obtaining
1291 * 'visual' transformation of pose-channel.
1292 * (used by the Visual-Keyframing stuff)
1294 void armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
1298 invert_m4_m4(imat, arm_mat);
1299 mul_m4_m4m4(delta_mat, pose_mat, imat);
1302 /* **************** Rotation Mode Conversions ****************************** */
1303 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1305 /* Called from RNA when rotation mode changes
1306 * - the result should be that the rotations given in the provided pointers have had conversions
1307 * applied (as appropriate), such that the rotation of the element hasn't 'visually' changed
1309 void BKE_rotMode_change_values (float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1311 /* check if any change - if so, need to convert data */
1312 if (newMode > 0) { /* to euler */
1313 if (oldMode == ROT_MODE_AXISANGLE) {
1314 /* axis-angle to euler */
1315 axis_angle_to_eulO( eul, newMode,axis, *angle);
1317 else if (oldMode == ROT_MODE_QUAT) {
1319 quat_to_eulO( eul, newMode,quat);
1321 /* else { no conversion needed } */
1323 else if (newMode == ROT_MODE_QUAT) { /* to quat */
1324 if (oldMode == ROT_MODE_AXISANGLE) {
1325 /* axis angle to quat */
1326 axis_angle_to_quat(quat, axis, *angle);
1328 else if (oldMode > 0) {
1330 eulO_to_quat( quat,eul, oldMode);
1332 /* else { no conversion needed } */
1334 else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1336 /* euler to axis angle */
1337 eulO_to_axis_angle( axis, angle,eul, oldMode);
1339 else if (oldMode == ROT_MODE_QUAT) {
1340 /* quat to axis angle */
1341 quat_to_axis_angle( axis, angle,quat);
1344 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1345 if (IS_EQ(axis[0], axis[1]) && IS_EQ(axis[1], axis[2])) {
1346 /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1352 /* **************** The new & simple (but OK!) armature evaluation ********* */
1354 /* ****************** And how it works! ****************************************
1356 This is the bone transformation trick; they're hierarchical so each bone(b)
1357 is in the coord system of bone(b-1):
1359 arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
1361 -> yoffs is just the y axis translation in parent's coord system
1362 -> d_root is the translation of the bone root, also in parent's coord system
1364 pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1366 we then - in init deform - store the deform in chan_mat, such that:
1368 pose_mat(b)= arm_mat(b) * chan_mat(b)
1370 *************************************************************************** */
1371 /* Computes vector and roll based on a rotation. "mat" must
1372 contain only a rotation, and no scaling. */
1373 void mat3_to_vec_roll(float mat[][3], float *vec, float *roll)
1376 copy_v3_v3(vec, mat[1]);
1379 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1381 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1382 invert_m3_m3(vecmatinv, vecmat);
1383 mul_m3_m3m3(rollmat, vecmatinv, mat);
1385 *roll= (float)atan2(rollmat[2][0], rollmat[2][2]);
1389 /* Calculates the rest matrix of a bone based
1390 On its vector and a roll around that vector */
1391 void vec_roll_to_mat3(float *vec, float roll, float mat[][3])
1393 float nor[3], axis[3], target[3]={0,1,0};
1395 float rMatrix[3][3], bMatrix[3][3];
1400 /* Find Axis & Amount for bone matrix*/
1401 cross_v3_v3v3(axis,target,nor);
1403 if (dot_v3v3(axis,axis) > 0.0000000000001) {
1404 /* if nor is *not* a multiple of target ... */
1407 theta= angle_normalized_v3v3(target, nor);
1409 /* Make Bone matrix*/
1410 vec_rot_to_mat3( bMatrix,axis, theta);
1413 /* if nor is a multiple of target ... */
1416 /* point same direction, or opposite? */
1417 updown = ( dot_v3v3(target,nor) > 0 ) ? 1.0f : -1.0f;
1419 /* I think this should work ... */
1420 bMatrix[0][0]=updown; bMatrix[0][1]=0.0; bMatrix[0][2]=0.0;
1421 bMatrix[1][0]=0.0; bMatrix[1][1]=updown; bMatrix[1][2]=0.0;
1422 bMatrix[2][0]=0.0; bMatrix[2][1]=0.0; bMatrix[2][2]=1.0;
1425 /* Make Roll matrix*/
1426 vec_rot_to_mat3( rMatrix,nor, roll);
1428 /* Combine and output result*/
1429 mul_m3_m3m3(mat, rMatrix, bMatrix);
1433 /* recursive part, calculates restposition of entire tree of children */
1434 /* used by exiting editmode too */
1435 void where_is_armature_bone(Bone *bone, Bone *prevbone)
1440 sub_v3_v3v3(vec, bone->tail, bone->head);
1441 vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1443 bone->length= len_v3v3(bone->head, bone->tail);
1445 /* this is called on old file reading too... */
1446 if(bone->xwidth==0.0) {
1453 float offs_bone[4][4]; // yoffs(b-1) + root(b) + bonemat(b)
1455 /* bone transform itself */
1456 copy_m4_m3(offs_bone, bone->bone_mat);
1458 /* The bone's root offset (is in the parent's coordinate system) */
1459 VECCOPY(offs_bone[3], bone->head);
1461 /* Get the length translation of parent (length along y axis) */
1462 offs_bone[3][1]+= prevbone->length;
1464 /* Compose the matrix for this bone */
1465 mul_m4_m4m4(bone->arm_mat, offs_bone, prevbone->arm_mat);
1468 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1469 VECCOPY(bone->arm_mat[3], bone->head);
1473 VECCOPY(bone->arm_head, bone->arm_mat[3]);
1474 /* tail is in current local coord system */
1475 VECCOPY(vec, bone->arm_mat[1]);
1476 mul_v3_fl(vec, bone->length);
1477 add_v3_v3v3(bone->arm_tail, bone->arm_head, vec);
1479 /* and the kiddies */
1481 for(bone= bone->childbase.first; bone; bone= bone->next) {
1482 where_is_armature_bone(bone, prevbone);
1486 /* updates vectors and matrices on rest-position level, only needed
1487 after editing armature itself, now only on reading file */
1488 void where_is_armature (bArmature *arm)
1492 /* hierarchical from root to children */
1493 for(bone= arm->bonebase.first; bone; bone= bone->next) {
1494 where_is_armature_bone(bone, NULL);
1498 /* if bone layer is protected, copy the data from from->pose
1499 * when used with linked libraries this copies from the linked pose into the local pose */
1500 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1502 bPose *pose= ob->pose, *frompose= from->pose;
1503 bPoseChannel *pchan, *pchanp, pchanw;
1507 if (frompose==NULL) return;
1509 /* in some cases when rigs change, we cant synchronize
1510 * to avoid crashing check for possible errors here */
1511 for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1512 if (pchan->bone->layer & layer_protected) {
1513 if(get_pose_channel(frompose, pchan->name) == NULL) {
1514 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n", from->id.name, pchan->name);
1523 /* exception, armature local layer should be proxied too */
1524 if (pose->proxy_layer)
1525 ((bArmature *)ob->data)->layer= pose->proxy_layer;
1527 /* clear all transformation values from library */
1528 rest_pose(frompose);
1530 /* copy over all of the proxy's bone groups */
1531 /* TODO for later - implement 'local' bone groups as for constraints
1532 * Note: this isn't trivial, as bones reference groups by index not by pointer,
1533 * so syncing things correctly needs careful attention
1535 BLI_freelistN(&pose->agroups);
1536 BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1537 pose->active_group= frompose->active_group;
1539 for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1540 pchanp= get_pose_channel(frompose, pchan->name);
1542 if (pchan->bone->layer & layer_protected) {
1543 ListBase proxylocal_constraints = {NULL, NULL};
1545 /* copy posechannel to temp, but restore important pointers */
1547 pchanw.prev= pchan->prev;
1548 pchanw.next= pchan->next;
1549 pchanw.parent= pchan->parent;
1550 pchanw.child= pchan->child;
1553 /* this is freed so copy a copy, else undo crashes */
1555 pchanw.prop= IDP_CopyProperty(pchanw.prop);
1557 /* use the values from the the existing props */
1559 IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1563 /* constraints - proxy constraints are flushed... local ones are added after
1564 * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1565 * 2. copy proxy-pchan's constraints on-to new
1566 * 3. add extracted local constraints back on top
1568 extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
1569 copy_constraints(&pchanw.constraints, &pchanp->constraints);
1570 addlisttolist(&pchanw.constraints, &proxylocal_constraints);
1572 /* constraints - set target ob pointer to own object */
1573 for (con= pchanw.constraints.first; con; con= con->next) {
1574 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1575 ListBase targets = {NULL, NULL};
1576 bConstraintTarget *ct;
1578 if (cti && cti->get_constraint_targets) {
1579 cti->get_constraint_targets(con, &targets);
1581 for (ct= targets.first; ct; ct= ct->next) {
1582 if (ct->tar == from)
1586 if (cti->flush_constraint_targets)
1587 cti->flush_constraint_targets(con, &targets, 0);
1591 /* free stuff from current channel */
1592 free_pose_channel(pchan);
1594 /* the final copy */
1598 /* always copy custom shape */
1599 pchan->custom= pchanp->custom;
1600 pchan->custom_tx= pchanp->custom_tx;
1602 /* ID-Property Syncing */
1604 IDProperty *prop_orig= pchan->prop;
1606 pchan->prop= IDP_CopyProperty(pchanp->prop);
1608 /* copy existing values across when types match */
1609 IDP_SyncGroupValues(pchan->prop, prop_orig);
1616 IDP_FreeProperty(prop_orig);
1617 MEM_freeN(prop_orig);
1624 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1626 bPoseChannel *pchan = verify_pose_channel (pose, bone->name); // verify checks and/or adds
1629 pchan->parent= parchan;
1633 for(bone= bone->childbase.first; bone; bone= bone->next) {
1634 counter= rebuild_pose_bone(pose, bone, pchan, counter);
1635 /* for quick detecting of next bone in chain, only b-bone uses it now */
1636 if(bone->flag & BONE_CONNECTED)
1637 pchan->child= get_pose_channel(pose, bone->name);
1643 /* only after leave editmode, duplicating, validating older files, library syncing */
1644 /* NOTE: pose->flag is set for it */
1645 void armature_rebuild_pose(Object *ob, bArmature *arm)
1649 bPoseChannel *pchan, *next;
1652 /* only done here */
1653 if(ob->pose==NULL) {
1654 /* create new pose */
1655 ob->pose= MEM_callocN(sizeof(bPose), "new pose");
1657 /* set default settings for animviz */
1658 animviz_settings_init(&ob->pose->avs);
1663 for(pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1668 /* first step, check if all channels are there */
1669 for(bone= arm->bonebase.first; bone; bone= bone->next) {
1670 counter= rebuild_pose_bone(pose, bone, NULL, counter);
1673 /* and a check for garbage */
1674 for(pchan= pose->chanbase.first; pchan; pchan= next) {
1676 if(pchan->bone==NULL) {
1677 free_pose_channel(pchan);
1678 BLI_freelinkN(&pose->chanbase, pchan);
1681 // printf("rebuild pose %s, %d bones\n", ob->id.name, counter);
1683 /* synchronize protected layers with proxy */
1685 object_copy_proxy_drivers(ob, ob->proxy);
1686 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1689 update_pose_constraint_flags(ob->pose); // for IK detection for example
1695 ob->pose->flag &= ~POSE_RECALC;
1696 ob->pose->flag |= POSE_WAS_REBUILT;
1700 /* ********************** SPLINE IK SOLVER ******************* */
1702 /* Temporary evaluation tree data used for Spline IK */
1703 typedef struct tSplineIK_Tree {
1704 struct tSplineIK_Tree *next, *prev;
1706 int type; /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
1708 short free_points; /* free the point positions array */
1709 short chainlen; /* number of bones in the chain */
1711 float *points; /* parametric positions for the joints along the curve */
1712 bPoseChannel **chain; /* chain of bones to affect using Spline IK (ordered from the tip) */
1714 bPoseChannel *root; /* bone that is the root node of the chain */
1716 bConstraint *con; /* constraint for this chain */
1717 bSplineIKConstraint *ikData; /* constraint settings for this chain */
1722 /* Tag the bones in the chain formed by the given bone for IK */
1723 static void splineik_init_tree_from_pchan(Scene *scene, Object *ob, bPoseChannel *pchan_tip)
1725 bPoseChannel *pchan, *pchanRoot=NULL;
1726 bPoseChannel *pchanChain[255];
1727 bConstraint *con = NULL;
1728 bSplineIKConstraint *ikData = NULL;
1729 float boneLengths[255], *jointPoints;
1730 float totLength = 0.0f;
1731 short free_joints = 0;
1734 /* find the SplineIK constraint */
1735 for (con= pchan_tip->constraints.first; con; con= con->next) {
1736 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
1739 /* target can only be curve */
1740 if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))
1742 /* skip if disabled */
1743 if ( (con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE|CONSTRAINT_OFF)) )
1746 /* otherwise, constraint is ok... */
1753 /* make sure that the constraint targets are ok
1754 * - this is a workaround for a depsgraph bug...
1757 Curve *cu= ikData->tar->data;
1759 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1760 * currently for paths to work it needs to go through the bevlist/displist system (ton)
1763 /* only happens on reload file, but violates depsgraph still... fix! */
1764 if ((cu->path==NULL) || (cu->path->data==NULL))
1765 makeDispListCurveTypes(scene, ikData->tar, 0);
1768 /* find the root bone and the chain of bones from the root to the tip
1769 * NOTE: this assumes that the bones are connected, but that may not be true...
1771 for (pchan= pchan_tip; pchan; pchan= pchan->parent) {
1772 /* store this segment in the chain */
1773 pchanChain[segcount]= pchan;
1775 /* if performing rebinding, calculate the length of the bone */
1776 boneLengths[segcount]= pchan->bone->length;
1777 totLength += boneLengths[segcount];
1779 /* check if we've gotten the number of bones required yet (after incrementing the count first)
1780 * NOTE: the 255 limit here is rather ugly, but the standard IK does this too!
1783 if ((segcount == ikData->chainlen) || (segcount > 255))
1790 pchanRoot= pchanChain[segcount-1];
1792 /* perform binding step if required */
1793 if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
1794 float segmentLen= (1.0f / (float)segcount);
1797 /* setup new empty array for the points list */
1799 MEM_freeN(ikData->points);
1800 ikData->numpoints= ikData->chainlen+1;
1801 ikData->points= MEM_callocN(sizeof(float)*ikData->numpoints, "Spline IK Binding");
1803 /* perform binding of the joints to parametric positions along the curve based
1804 * proportion of the total length that each bone occupies
1806 for (i = 0; i < segcount; i++) {
1809 * - 2 methods; the one chosen depends on whether we've got usable lengths
1811 if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
1812 /* 1) equi-spaced joints */
1813 ikData->points[i]= ikData->points[i-1] - segmentLen;
1816 /* 2) to find this point on the curve, we take a step from the previous joint
1817 * a distance given by the proportion that this bone takes
1819 ikData->points[i]= ikData->points[i-1] - (boneLengths[i] / totLength);
1823 /* 'tip' of chain, special exception for the first joint */
1824 ikData->points[0]= 1.0f;
1828 /* spline has now been bound */
1829 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
1832 /* apply corrections for sensitivity to scaling on a copy of the bind points,
1833 * since it's easier to determine the positions of all the joints beforehand this way
1835 if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
1836 Curve *cu= (Curve *)ikData->tar->data;
1837 float splineLen, maxScale;
1840 /* make a copy of the points array, that we'll store in the tree
1841 * - although we could just multiply the points on the fly, this approach means that
1842 * we can introduce per-segment stretchiness later if it is necessary
1844 jointPoints= MEM_dupallocN(ikData->points);
1847 /* get the current length of the curve */
1848 // NOTE: this is assumed to be correct even after the curve was resized
1849 splineLen= cu->path->totdist;
1851 /* calculate the scale factor to multiply all the path values by so that the
1852 * bone chain retains its current length, such that
1853 * maxScale * splineLen = totLength
1855 maxScale = totLength / splineLen;
1857 /* apply scaling correction to all of the temporary points */
1858 // TODO: this is really not adequate enough on really short chains
1859 for (i = 0; i < segcount; i++)
1860 jointPoints[i] *= maxScale;
1863 /* just use the existing points array */
1864 jointPoints= ikData->points;
1868 /* make a new Spline-IK chain, and store it in the IK chains */
1869 // TODO: we should check if there is already an IK chain on this, since that would take presidence...
1872 tSplineIK_Tree *tree= MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
1873 tree->type= CONSTRAINT_TYPE_SPLINEIK;
1875 tree->chainlen= segcount;
1877 /* copy over the array of links to bones in the chain (from tip to root) */
1878 tree->chain= MEM_callocN(sizeof(bPoseChannel*)*segcount, "SplineIK Chain");
1879 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel*)*segcount);
1881 /* store reference to joint position array */
1882 tree->points= jointPoints;
1883 tree->free_points= free_joints;
1885 /* store references to different parts of the chain */
1886 tree->root= pchanRoot;
1888 tree->ikData= ikData;
1890 /* AND! link the tree to the root */
1891 BLI_addtail(&pchanRoot->iktree, tree);
1894 /* mark root channel having an IK tree */
1895 pchanRoot->flag |= POSE_IKSPLINE;
1898 /* Tag which bones are members of Spline IK chains */
1899 static void splineik_init_tree(Scene *scene, Object *ob, float ctime)
1901 bPoseChannel *pchan;
1903 /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
1904 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1905 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
1906 splineik_init_tree_from_pchan(scene, ob, pchan);
1912 /* Evaluate spline IK for a given bone */
1913 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan, int index, float ctime)
1915 bSplineIKConstraint *ikData= tree->ikData;
1916 float poseHead[3], poseTail[3], poseMat[4][4];
1917 float splineVec[3], scaleFac, radius=1.0f;
1919 /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
1920 where_is_pose_bone(scene, ob, pchan, ctime, 1);
1922 VECCOPY(poseHead, pchan->pose_head);
1923 VECCOPY(poseTail, pchan->pose_tail);
1925 /* step 1: determine the positions for the endpoints of the bone */
1927 float vec[4], dir[3], rad;
1928 float tailBlendFac= 1.0f;
1930 /* determine if the bone should still be affected by SplineIK */
1931 if (tree->points[index+1] >= 1.0f) {
1932 /* spline doesn't affect the bone anymore, so done... */
1933 pchan->flag |= POSE_DONE;
1936 else if ((tree->points[index] >= 1.0f) && (tree->points[index+1] < 1.0f)) {
1937 /* blending factor depends on the amount of the bone still left on the chain */
1938 tailBlendFac= (1.0f - tree->points[index+1]) / (tree->points[index] - tree->points[index+1]);
1942 if ( where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad) ) {
1943 /* apply curve's object-mode transforms to the position
1944 * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1946 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1947 mul_m4_v3(ikData->tar->obmat, vec);
1949 /* convert the position to pose-space, then store it */
1950 mul_m4_v3(ob->imat, vec);
1951 interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
1953 /* set the new radius */
1958 if ( where_on_path(ikData->tar, tree->points[index+1], vec, dir, NULL, &rad) ) {
1959 /* apply curve's object-mode transforms to the position
1960 * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1962 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1963 mul_m4_v3(ikData->tar->obmat, vec);
1965 /* store the position, and convert it to pose space */
1966 mul_m4_v3(ob->imat, vec);
1967 VECCOPY(poseHead, vec);
1969 /* set the new radius (it should be the average value) */
1970 radius = (radius+rad) / 2;
1974 /* step 2: determine the implied transform from these endpoints
1975 * - splineVec: the vector direction that the spline applies on the bone
1976 * - scaleFac: the factor that the bone length is scaled by to get the desired amount
1978 sub_v3_v3v3(splineVec, poseTail, poseHead);
1979 scaleFac= len_v3(splineVec) / pchan->bone->length;
1981 /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis
1982 * - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
1985 float dmat[3][3], rmat[3][3], tmat[3][3];
1986 float raxis[3], rangle;
1988 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
1989 * orientation-relevant axes, and normalising them
1991 VECCOPY(rmat[0], pchan->pose_mat[0]);
1992 VECCOPY(rmat[1], pchan->pose_mat[1]);
1993 VECCOPY(rmat[2], pchan->pose_mat[2]);
1996 /* also, normalise the orientation imposed by the bone, now that we've extracted the scale factor */
1997 normalize_v3(splineVec);
1999 /* calculate smallest axis-angle rotation necessary for getting from the
2000 * current orientation of the bone, to the spline-imposed direction
2002 cross_v3_v3v3(raxis, rmat[1], splineVec);
2004 rangle= dot_v3v3(rmat[1], splineVec);
2005 rangle= acos( MAX2(-1.0f, MIN2(1.0f, rangle)) );
2007 /* construct rotation matrix from the axis-angle rotation found above
2008 * - this call takes care to make sure that the axis provided is a unit vector first
2010 axis_angle_to_mat3(dmat, raxis, rangle);
2012 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
2013 * while still maintaining roll control from the existing bone animation
2015 mul_m3_m3m3(tmat, dmat, rmat); // m1, m3, m2
2016 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
2017 copy_m4_m3(poseMat, tmat);
2020 /* step 4: set the scaling factors for the axes */
2022 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
2023 mul_v3_fl(poseMat[1], scaleFac);
2025 /* set the scaling factors of the x and z axes from... */
2026 switch (ikData->xzScaleMode) {
2027 case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
2029 /* original scales get used */
2033 scale= len_v3(pchan->pose_mat[0]);
2034 mul_v3_fl(poseMat[0], scale);
2036 scale= len_v3(pchan->pose_mat[2]);
2037 mul_v3_fl(poseMat[2], scale);
2040 case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
2042 /* 'volume preservation' */
2045 /* calculate volume preservation factor which is
2046 * basically the inverse of the y-scaling factor
2048 if (fabs(scaleFac) != 0.0f) {
2049 scale= 1.0 / fabs(scaleFac);
2051 /* we need to clamp this within sensible values */
2052 // NOTE: these should be fine for now, but should get sanitised in future
2053 scale= MIN2( MAX2(scale, 0.0001) , 100000);
2058 /* apply the scaling */
2059 mul_v3_fl(poseMat[0], scale);
2060 mul_v3_fl(poseMat[2], scale);
2065 /* finally, multiply the x and z scaling by the radius of the curve too,
2066 * to allow automatic scales to get tweaked still
2068 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
2069 mul_v3_fl(poseMat[0], radius);
2070 mul_v3_fl(poseMat[2], radius);
2074 /* step 5: set the location of the bone in the matrix
2075 * - when the 'no-root' option is affected, the chain can retain
2076 * the shape but be moved elsewhere
2078 if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
2079 VECCOPY(poseHead, pchan->pose_head);
2081 VECCOPY(poseMat[3], poseHead);
2083 /* finally, store the new transform */
2084 copy_m4_m4(pchan->pose_mat, poseMat);
2085 VECCOPY(pchan->pose_head, poseHead);
2086 VECCOPY(pchan->pose_tail, poseTail);
2089 pchan->flag |= POSE_DONE;
2092 /* Evaluate the chain starting from the nominated bone */
2093 static void splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
2095 tSplineIK_Tree *tree;
2097 /* for each pose-tree, execute it if it is spline, otherwise just free it */
2098 for (tree= pchan_root->iktree.first; tree; tree= pchan_root->iktree.first) {
2099 /* only evaluate if tagged for Spline IK */
2100 if (tree->type == CONSTRAINT_TYPE_SPLINEIK) {
2103 /* walk over each bone in the chain, calculating the effects of spline IK
2104 * - the chain is traversed in the opposite order to storage order (i.e. parent to children)
2105 * so that dependencies are correct
2107 for (i= tree->chainlen-1; i >= 0; i--) {
2108 bPoseChannel *pchan= tree->chain[i];
2109 splineik_evaluate_bone(tree, scene, ob, pchan, i, ctime);
2112 // TODO: if another pass is needed to ensure the validity of the chain after blending, it should go here
2114 /* free the tree info specific to SplineIK trees now */
2115 if (tree->chain) MEM_freeN(tree->chain);
2116 if (tree->free_points) MEM_freeN(tree->points);
2119 /* free this tree */
2120 BLI_freelinkN(&pchan_root->iktree, tree);
2124 /* ********************** THE POSE SOLVER ******************* */
2126 /* loc/rot/size to given mat4 */
2127 void pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2133 /* get scaling matrix */
2134 size_to_mat3(smat, pchan->size);
2136 /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2137 if (pchan->rotmode > 0) {
2138 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2139 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2141 else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2142 /* axis-angle - not really that great for 3D-changing orientations */
2143 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2146 /* quats are normalised before use to eliminate scaling issues */
2149 /* NOTE: we now don't normalise the stored values anymore, since this was kindof evil in some cases
2150 * but if this proves to be too problematic, switch back to the old system of operating directly on
2153 QUATCOPY(quat, pchan->quat);
2155 quat_to_mat3(rmat, quat);
2158 /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2159 mul_m3_m3m3(tmat, rmat, smat);
2160 copy_m4_m3(chan_mat, tmat);
2162 /* prevent action channels breaking chains */
2163 /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2164 if ((pchan->bone==NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2165 VECCOPY(chan_mat[3], pchan->loc);
2169 /* loc/rot/size to mat4 */
2170 /* used in constraint.c too */
2171 void chan_calc_mat(bPoseChannel *pchan)
2173 /* this is just a wrapper around the copy of this function which calculates the matrix
2174 * and stores the result in any given channel
2176 pchan_to_mat4(pchan, pchan->chan_mat);
2179 /* NLA strip modifiers */
2180 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2182 bActionModifier *amod;
2183 bActionStrip *strip, *strip2;
2184 float scene_cfra= (float)scene->r.cfra;
2187 for (strip=armob->nlastrips.first; strip; strip=strip->next) {
2190 if (scene_cfra>=strip->start && scene_cfra<=strip->end)
2193 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2196 /* if there are any other strips active, ignore modifiers for this strip -
2197 * 'hold' option should only hold action modifiers if there are
2198 * no other active strips */
2199 for (strip2=strip->next; strip2; strip2=strip2->next) {
2200 if (strip2 == strip) continue;
2202 if (scene_cfra>=strip2->start && scene_cfra<=strip2->end) {
2203 if (!(strip2->flag & ACTSTRIP_MUTE))
2208 /* if there are any later, activated, strips with 'hold' set, they take precedence,
2209 * so ignore modifiers for this strip */
2210 for (strip2=strip->next; strip2; strip2=strip2->next) {
2211 if (scene_cfra < strip2->start) continue;
2212 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2219 /* temporal solution to prevent 2 strips accumulating */
2220 if(scene_cfra==strip->end && strip->next && strip->next->start==scene_cfra)
2223 for(amod= strip->modifiers.first; amod; amod= amod->next) {
2224 switch (amod->type) {
2225 case ACTSTRIP_MOD_DEFORM:
2227 /* validate first */
2228 if(amod->ob && amod->ob->type==OB_CURVE && amod->channel[0]) {
2230 if( strcmp(pchan->name, amod->channel)==0 ) {
2231 float mat4[4][4], mat3[3][3];
2233 curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2234 copy_m4_m4(mat4, pchan->pose_mat);
2235 mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2241 case ACTSTRIP_MOD_NOISE:
2243 if( strcmp(pchan->name, amod->channel)==0 ) {
2244 float nor[3], loc[3], ofs;
2245 float eul[3], size[3], eulo[3], sizeo[3];
2247 /* calculate turbulance */
2248 ofs = amod->turbul / 200.0f;
2250 /* make a copy of starting conditions */
2251 VECCOPY(loc, pchan->pose_mat[3]);
2252 mat4_to_eul( eul,pchan->pose_mat);
2253 mat4_to_size( size,pchan->pose_mat);
2255 VECCOPY(sizeo, size);
2257 /* apply noise to each set of channels */
2258 if (amod->channels & 4) {
2260 nor[0] = BLI_gNoise(amod->noisesize, size[0]+ofs, size[1], size[2], 0, 0) - ofs;
2261 nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1]+ofs, size[2], 0, 0) - ofs;
2262 nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2]+ofs, 0, 0) - ofs;
2263 add_v3_v3v3(size, size, nor);
2266 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2268 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2270 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2272 if (amod->channels & 2) {
2274 nor[0] = BLI_gNoise(amod->noisesize, eul[0]+ofs, eul[1], eul[2], 0, 0) - ofs;
2275 nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1]+ofs, eul[2], 0, 0) - ofs;
2276 nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2]+ofs, 0, 0) - ofs;
2278 compatible_eul(nor, eulo);
2279 add_v3_v3v3(eul, eul, nor);
2280 compatible_eul(eul, eulo);
2282 loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2284 if (amod->channels & 1) {
2286 nor[0] = BLI_gNoise(amod->noisesize, loc[0]+ofs, loc[1], loc[2], 0, 0) - ofs;
2287 nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1]+ofs, loc[2], 0, 0) - ofs;
2288 nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2]+ofs, 0, 0) - ofs;
2290 add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2302 /* The main armature solver, does all constraints excluding IK */
2303 /* pchan is validated, as having bone and parent pointer
2304 * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2306 void where_is_pose_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, int do_extra)
2308 Bone *bone, *parbone;
2309 bPoseChannel *parchan;
2312 /* set up variables for quicker access below */
2314 parbone= bone->parent;
2315 parchan= pchan->parent;
2317 /* this gives a chan_mat with actions (ipos) results */
2318 if(do_extra) chan_calc_mat(pchan);
2319 else unit_m4(pchan->chan_mat);
2321 /* construct the posemat based on PoseChannels, that we do before applying constraints */
2322 /* pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2325 float offs_bone[4][4]; // yoffs(b-1) + root(b) + bonemat(b)
2327 /* bone transform itself */
2328 copy_m4_m3(offs_bone, bone->bone_mat);
2330 /* The bone's root offset (is in the parent's coordinate system) */
2331 VECCOPY(offs_bone[3], bone->head);
2333 /* Get the length translation of parent (length along y axis) */
2334 offs_bone[3][1]+= parbone->length;
2336 /* Compose the matrix for this bone */
2337 if(bone->flag & BONE_HINGE) { // uses restposition rotation, but actual position
2340 /* the rotation of the parent restposition */
2341 copy_m4_m4(tmat, parbone->arm_mat);
2342 mul_serie_m4(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2344 else if(bone->flag & BONE_NO_SCALE) {
2345 float orthmat[4][4];
2347 /* do transform, with an ortho-parent matrix */
2348 copy_m4_m4(orthmat, parchan->pose_mat);
2349 normalize_m4(orthmat);
2350 mul_serie_m4(pchan->pose_mat, orthmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2353 mul_serie_m4(pchan->pose_mat, parchan->pose_mat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2355 /* in these cases we need to compute location separately */
2356 if(bone->flag & (BONE_HINGE|BONE_NO_SCALE|BONE_NO_LOCAL_LOCATION)) {
2357 float bone_loc[3], chan_loc[3];
2359 mul_v3_m4v3(bone_loc, parchan->pose_mat, offs_bone[3]);
2360 copy_v3_v3(chan_loc, pchan->chan_mat[3]);
2362 /* no local location is not transformed by bone matrix */
2363 if(!(bone->flag & BONE_NO_LOCAL_LOCATION))
2364 mul_mat3_m4_v3(offs_bone, chan_loc);
2366 /* for hinge we use armature instead of pose mat */
2367 if(bone->flag & BONE_HINGE) mul_mat3_m4_v3(parbone->arm_mat, chan_loc);
2368 else mul_mat3_m4_v3(parchan->pose_mat, chan_loc);
2370 add_v3_v3v3(pchan->pose_mat[3], bone_loc, chan_loc);
2374 mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
2376 /* optional location without arm_mat rotation */
2377 if(bone->flag & BONE_NO_LOCAL_LOCATION)
2378 add_v3_v3v3(pchan->pose_mat[3], bone->arm_mat[3], pchan->chan_mat[3]);
2380 /* only rootbones get the cyclic offset (unless user doesn't want that) */
2381 if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2382 add_v3_v3v3(pchan->pose_mat[3], pchan->pose_mat[3], ob->pose->cyclic_offset);
2386 /* do NLA strip modifiers - i.e. curve follow */
2387 do_strip_modifiers(scene, ob, bone, pchan);
2389 /* Do constraints */
2390 if (pchan->constraints.first) {
2393 /* make a copy of location of PoseChannel for later */
2394 VECCOPY(vec, pchan->pose_mat[3]);
2396 /* prepare PoseChannel for Constraint solving
2397 * - makes a copy of matrix, and creates temporary struct to use
2399 cob= constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2401 /* Solve PoseChannel's Constraints */
2402 solve_constraints(&pchan->constraints, cob, ctime); // ctime doesnt alter objects
2404 /* cleanup after Constraint Solving
2405 * - applies matrix back to pchan, and frees temporary struct used
2407 constraints_clear_evalob(cob);
2409 /* prevent constraints breaking a chain */
2410 if(pchan->bone->flag & BONE_CONNECTED) {
2411 VECCOPY(pchan->pose_mat[3], vec);
2416 /* calculate head */
2417 VECCOPY(pchan->pose_head, pchan->pose_mat[3]);
2418 /* calculate tail */
2419 VECCOPY(vec, pchan->pose_mat[1]);
2420 mul_v3_fl(vec, bone->length);
2421 add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2424 /* This only reads anim data from channels, and writes to channels */
2425 /* This is the only function adding poses */
2426 void where_is_pose (Scene *scene, Object *ob)
2430 bPoseChannel *pchan;
2434 if(ob->type!=OB_ARMATURE) return;
2437 if(ELEM(NULL, arm, scene)) return;
2438 if((ob->pose==NULL) || (ob->pose->flag & POSE_RECALC))
2439 armature_rebuild_pose(ob, arm);
2441 ctime= bsystem_time(scene, ob, (float)scene->r.cfra, 0.0); /* not accurate... */
2443 /* In editmode or restposition we read the data from the bones */
2444 if(arm->edbo || (arm->flag & ARM_RESTPOS)) {
2446 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2449 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2450 VECCOPY(pchan->pose_head, bone->arm_head);
2451 VECCOPY(pchan->pose_tail, bone->arm_tail);
2456 invert_m4_m4(ob->imat, ob->obmat); // imat is needed
2458 /* 1. clear flags */
2459 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2460 pchan->flag &= ~(POSE_DONE|POSE_CHAIN|POSE_IKTREE|POSE_IKSPLINE);
2463 /* 2a. construct the IK tree (standard IK) */
2464 BIK_initialize_tree(scene, ob, ctime);
2466 /* 2b. construct the Spline IK trees
2467 * - this is not integrated as an IK plugin, since it should be able
2468 * to function in conjunction with standard IK
2470 splineik_init_tree(scene, ob, ctime);
2472 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2473 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2474 /* 4a. if we find an IK root, we handle it separated */
2475 if(pchan->flag & POSE_IKTREE) {
2476 BIK_execute_tree(scene, ob, pchan, ctime);
2478 /* 4b. if we find a Spline IK root, we handle it separated too */
2479 else if(pchan->flag & POSE_IKSPLINE) {
2480 splineik_execute_tree(scene, ob, pchan, ctime);
2482 /* 5. otherwise just call the normal solver */
2483 else if(!(pchan->flag & POSE_DONE)) {
2484 where_is_pose_bone(scene, ob, pchan, ctime, 1);
2487 /* 6. release the IK tree */
2488 BIK_release_tree(scene, ob, ctime);
2491 /* calculating deform matrices */
2492 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2494 invert_m4_m4(imat, pchan->bone->arm_mat);
2495 mul_m4_m4m4(pchan->chan_mat, imat, pchan->pose_mat);