svn merge -r40197:40311 ^/trunk/blender
[blender.git] / source / blender / blenkernel / intern / armature.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/armature.c
27  *  \ingroup bke
28  */
29
30
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42 #include "BLI_utildefines.h"
43
44 #include "DNA_anim_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_mesh_types.h"
48 #include "DNA_lattice_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_nla_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_object_types.h"
53
54 #include "BKE_animsys.h"
55 #include "BKE_armature.h"
56 #include "BKE_action.h"
57 #include "BKE_anim.h"
58 #include "BKE_constraint.h"
59 #include "BKE_curve.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_DerivedMesh.h"
62 #include "BKE_deform.h"
63 #include "BKE_displist.h"
64 #include "BKE_global.h"
65 #include "BKE_idprop.h"
66 #include "BKE_library.h"
67 #include "BKE_lattice.h"
68 #include "BKE_main.h"
69 #include "BKE_object.h"
70
71 #include "BIK_api.h"
72 #include "BKE_sketch.h"
73
74 /*      **************** Generic Functions, data level *************** */
75
76 bArmature *add_armature(const char *name)
77 {
78         bArmature *arm;
79         
80         arm= alloc_libblock (&G.main->armature, ID_AR, name);
81         arm->deformflag = ARM_DEF_VGROUP|ARM_DEF_ENVELOPE;
82         arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
83         arm->layer= 1;
84         return arm;
85 }
86
87 bArmature *get_armature(Object *ob)
88 {
89         if(ob->type==OB_ARMATURE)
90                 return (bArmature *)ob->data;
91         return NULL;
92 }
93
94 void free_bonelist (ListBase *lb)
95 {
96         Bone *bone;
97
98         for(bone=lb->first; bone; bone=bone->next) {
99                 if(bone->prop) {
100                         IDP_FreeProperty(bone->prop);
101                         MEM_freeN(bone->prop);
102                 }
103                 free_bonelist(&bone->childbase);
104         }
105         
106         BLI_freelistN(lb);
107 }
108
109 void free_armature(bArmature *arm)
110 {
111         if (arm) {
112                 free_bonelist(&arm->bonebase);
113                 
114                 /* free editmode data */
115                 if (arm->edbo) {
116                         BLI_freelistN(arm->edbo);
117                         
118                         MEM_freeN(arm->edbo);
119                         arm->edbo= NULL;
120                 }
121
122                 /* free sketch */
123                 if (arm->sketch) {
124                         freeSketch(arm->sketch);
125                         arm->sketch = NULL;
126                 }
127                 
128                 /* free animation data */
129                 if (arm->adt) {
130                         BKE_free_animdata(&arm->id);
131                         arm->adt= NULL;
132                 }
133         }
134 }
135
136 void make_local_armature(bArmature *arm)
137 {
138         Main *bmain= G.main;
139         int local=0, lib=0;
140         Object *ob;
141
142         if (arm->id.lib==NULL) return;
143         if (arm->id.us==1) {
144                 arm->id.lib= NULL;
145                 arm->id.flag= LIB_LOCAL;
146                 new_id(&bmain->armature, (ID*)arm, NULL);
147                 return;
148         }
149
150         for(ob= bmain->object.first; ob && ELEM(0, lib, local); ob= ob->id.next) {
151                 if(ob->data == arm) {
152                         if(ob->id.lib) lib= 1;
153                         else local= 1;
154                 }
155         }
156
157         if(local && lib==0) {
158                 arm->id.lib= NULL;
159                 arm->id.flag= LIB_LOCAL;
160                 new_id(&bmain->armature, (ID *)arm, NULL);
161         }
162         else if(local && lib) {
163                 bArmature *armn= copy_armature(arm);
164                 armn->id.us= 0;
165                 
166                 for(ob= bmain->object.first; ob; ob= ob->id.next) {
167                         if(ob->data == arm) {
168                                 if(ob->id.lib==NULL) {
169                                         ob->data= armn;
170                                         armn->id.us++;
171                                         arm->id.us--;
172                                 }
173                         }
174                 }
175         }
176 }
177
178 static void     copy_bonechildren (Bone* newBone, Bone* oldBone, Bone* actBone, Bone **newActBone)
179 {
180         Bone    *curBone, *newChildBone;
181         
182         if(oldBone == actBone)
183                 *newActBone= newBone;
184
185         if(oldBone->prop)
186                 newBone->prop= IDP_CopyProperty(oldBone->prop);
187
188         /*      Copy this bone's list*/
189         BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
190         
191         /*      For each child in the list, update it's children*/
192         newChildBone=newBone->childbase.first;
193         for (curBone=oldBone->childbase.first;curBone;curBone=curBone->next){
194                 newChildBone->parent=newBone;
195                 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
196                 newChildBone=newChildBone->next;
197         }
198 }
199
200 bArmature *copy_armature(bArmature *arm)
201 {
202         bArmature *newArm;
203         Bone            *oldBone, *newBone;
204         Bone            *newActBone= NULL;
205         
206         newArm= copy_libblock (arm);
207         BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
208         
209         /*      Duplicate the childrens' lists*/
210         newBone=newArm->bonebase.first;
211         for (oldBone=arm->bonebase.first;oldBone;oldBone=oldBone->next){
212                 newBone->parent=NULL;
213                 copy_bonechildren (newBone, oldBone, arm->act_bone, &newActBone);
214                 newBone=newBone->next;
215         };
216         
217         newArm->act_bone= newActBone;
218
219         newArm->edbo= NULL;
220         newArm->act_edbone= NULL;
221         newArm->sketch= NULL;
222
223         return newArm;
224 }
225
226 static Bone *get_named_bone_bonechildren (Bone *bone, const char *name)
227 {
228         Bone *curBone, *rbone;
229         
230         if (!strcmp (bone->name, name))
231                 return bone;
232         
233         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
234                 rbone=get_named_bone_bonechildren (curBone, name);
235                 if (rbone)
236                         return rbone;
237         }
238         
239         return NULL;
240 }
241
242
243 Bone *get_named_bone (bArmature *arm, const char *name)
244 /*
245         Walk the list until the bone is found
246  */
247 {
248         Bone *bone=NULL, *curBone;
249         
250         if (!arm) return NULL;
251         
252         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
253                 bone = get_named_bone_bonechildren (curBone, name);
254                 if (bone)
255                         return bone;
256         }
257         
258         return bone;
259 }
260
261 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for unique names afterwards)
262  *      strip_number: removes number extensions  (TODO: not used)
263  *      axis: the axis to name on
264  *      head/tail: the head/tail co-ordinate of the bone on the specified axis
265  */
266 int bone_autoside_name (char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
267 {
268         unsigned int len;
269         char    basename[MAXBONENAME]= "";
270         char    extension[5]= "";
271
272         len= strlen(name);
273         if (len == 0) return 0;
274         BLI_strncpy(basename, name, sizeof(basename));
275         
276         /* Figure out extension to append: 
277          *      - The extension to append is based upon the axis that we are working on.
278          *      - If head happens to be on 0, then we must consider the tail position as well to decide
279          *        which side the bone is on
280          *              -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
281          *              -> Otherwise, extension is added from perspective of object based on which side tail goes to
282          *      - If head is non-zero, extension is added from perspective of object based on side head is on
283          */
284         if (axis == 2) {
285                 /* z-axis - vertical (top/bottom) */
286                 if (IS_EQ(head, 0)) {
287                         if (tail < 0)
288                                 strcpy(extension, "Bot");
289                         else if (tail > 0)
290                                 strcpy(extension, "Top");
291                 }
292                 else {
293                         if (head < 0)
294                                 strcpy(extension, "Bot");
295                         else
296                                 strcpy(extension, "Top");
297                 }
298         }
299         else if (axis == 1) {
300                 /* y-axis - depth (front/back) */
301                 if (IS_EQ(head, 0)) {
302                         if (tail < 0)
303                                 strcpy(extension, "Fr");
304                         else if (tail > 0)
305                                 strcpy(extension, "Bk");
306                 }
307                 else {
308                         if (head < 0)
309                                 strcpy(extension, "Fr");
310                         else
311                                 strcpy(extension, "Bk");
312                 }
313         }
314         else {
315                 /* x-axis - horizontal (left/right) */
316                 if (IS_EQ(head, 0)) {
317                         if (tail < 0)
318                                 strcpy(extension, "R");
319                         else if (tail > 0)
320                                 strcpy(extension, "L");
321                 }
322                 else {
323                         if (head < 0)
324                                 strcpy(extension, "R");
325                         else if (head > 0)
326                                 strcpy(extension, "L");
327                 }
328         }
329
330         /* Simple name truncation 
331          *      - truncate if there is an extension and it wouldn't be able to fit
332          *      - otherwise, just append to end
333          */
334         if (extension[0]) {
335                 int change = 1;
336                 
337                 while (change) { /* remove extensions */
338                         change = 0;
339                         if (len > 2 && basename[len-2]=='.') {
340                                 if (basename[len-1]=='L' || basename[len-1] == 'R' ) { /* L R */
341                                         basename[len-2] = '\0';
342                                         len-=2;
343                                         change= 1;
344                                 }
345                         } else if (len > 3 && basename[len-3]=='.') {
346                                 if (    (basename[len-2]=='F' && basename[len-1] == 'r') ||     /* Fr */
347                                                 (basename[len-2]=='B' && basename[len-1] == 'k')        /* Bk */
348                                 ) {
349                                         basename[len-3] = '\0';
350                                         len-=3;
351                                         change= 1;
352                                 }
353                         } else if (len > 4 && basename[len-4]=='.') {
354                                 if (    (basename[len-3]=='T' && basename[len-2]=='o' && basename[len-1] == 'p') ||     /* Top */
355                                                 (basename[len-3]=='B' && basename[len-2]=='o' && basename[len-1] == 't')        /* Bot */
356                                 ) {
357                                         basename[len-4] = '\0';
358                                         len-=4;
359                                         change= 1;
360                                 }
361                         }
362                 }
363
364                 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
365                         strncpy(name, basename, len-strlen(extension));
366                 }
367
368                 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
369
370                 return 1;
371         }
372
373         else {
374                 return 0;
375         }
376 }
377
378 /* ************* B-Bone support ******************* */
379
380 #define MAX_BBONE_SUBDIV        32
381
382 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
383 static void equalize_bezier(float *data, int desired)
384 {
385         float *fp, totdist, ddist, dist, fac1, fac2;
386         float pdist[MAX_BBONE_SUBDIV+1];
387         float temp[MAX_BBONE_SUBDIV+1][4];
388         int a, nr;
389         
390         pdist[0]= 0.0f;
391         for(a=0, fp= data; a<MAX_BBONE_SUBDIV; a++, fp+=4) {
392                 QUATCOPY(temp[a], fp);
393                 pdist[a+1]= pdist[a]+len_v3v3(fp, fp+4);
394         }
395         /* do last point */
396         QUATCOPY(temp[a], fp);
397         totdist= pdist[a];
398         
399         /* go over distances and calculate new points */
400         ddist= totdist/((float)desired);
401         nr= 1;
402         for(a=1, fp= data+4; a<desired; a++, fp+=4) {
403                 
404                 dist= ((float)a)*ddist;
405                 
406                 /* we're looking for location (distance) 'dist' in the array */
407                 while((dist>= pdist[nr]) && nr<MAX_BBONE_SUBDIV) {
408                         nr++;
409                 }
410                 
411                 fac1= pdist[nr]- pdist[nr-1];
412                 fac2= pdist[nr]-dist;
413                 fac1= fac2/fac1;
414                 fac2= 1.0f-fac1;
415                 
416                 fp[0]= fac1*temp[nr-1][0]+ fac2*temp[nr][0];
417                 fp[1]= fac1*temp[nr-1][1]+ fac2*temp[nr][1];
418                 fp[2]= fac1*temp[nr-1][2]+ fac2*temp[nr][2];
419                 fp[3]= fac1*temp[nr-1][3]+ fac2*temp[nr][3];
420         }
421         /* set last point, needed for orientation calculus */
422         QUATCOPY(fp, temp[MAX_BBONE_SUBDIV]);
423 }
424
425 /* returns pointer to static array, filled with desired amount of bone->segments elements */
426 /* this calculation is done  within unit bone space */
427 Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
428 {
429         static Mat4 bbone_array[MAX_BBONE_SUBDIV];
430         static Mat4 bbone_rest_array[MAX_BBONE_SUBDIV];
431         Mat4 *result_array= (rest)? bbone_rest_array: bbone_array;
432         bPoseChannel *next, *prev;
433         Bone *bone= pchan->bone;
434         float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1=0.0f, roll2;
435         float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
436         float data[MAX_BBONE_SUBDIV+1][4], *fp;
437         int a, doscale= 0;
438
439         length= bone->length;
440
441         if(!rest) {
442                 /* check if we need to take non-uniform bone scaling into account */
443                 scale[0]= len_v3(pchan->pose_mat[0]);
444                 scale[1]= len_v3(pchan->pose_mat[1]);
445                 scale[2]= len_v3(pchan->pose_mat[2]);
446
447                 if(fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
448                         unit_m4(scalemat);
449                         scalemat[0][0]= scale[0];
450                         scalemat[1][1]= scale[1];
451                         scalemat[2][2]= scale[2];
452                         invert_m4_m4(iscalemat, scalemat);
453
454                         length *= scale[1];
455                         doscale = 1;
456                 }
457         }
458         
459         hlength1= bone->ease1*length*0.390464f;         // 0.5*sqrt(2)*kappa, the handle length for near-perfect circles
460         hlength2= bone->ease2*length*0.390464f;
461         
462         /* evaluate next and prev bones */
463         if(bone->flag & BONE_CONNECTED)
464                 prev= pchan->parent;
465         else
466                 prev= NULL;
467         
468         next= pchan->child;
469         
470         /* find the handle points, since this is inside bone space, the 
471                 first point = (0,0,0)
472                 last point =  (0, length, 0) */
473         
474         if(rest) {
475                 invert_m4_m4(imat, pchan->bone->arm_mat);
476         }
477         else if(doscale) {
478                 copy_m4_m4(posemat, pchan->pose_mat);
479                 normalize_m4(posemat);
480                 invert_m4_m4(imat, posemat);
481         }
482         else
483                 invert_m4_m4(imat, pchan->pose_mat);
484         
485         if(prev) {
486                 float difmat[4][4], result[3][3], imat3[3][3];
487
488                 /* transform previous point inside this bone space */
489                 if(rest)
490                         VECCOPY(h1, prev->bone->arm_head)
491                 else
492                         VECCOPY(h1, prev->pose_head)
493                 mul_m4_v3(imat, h1);
494
495                 if(prev->bone->segments>1) {
496                         /* if previous bone is B-bone too, use average handle direction */
497                         h1[1]-= length;
498                         roll1= 0.0f;
499                 }
500
501                 normalize_v3(h1);
502                 mul_v3_fl(h1, -hlength1);
503
504                 if(prev->bone->segments==1) {
505                         /* find the previous roll to interpolate */
506                         if(rest)
507                                 mul_m4_m4m4(difmat, prev->bone->arm_mat, imat);
508                         else
509                                 mul_m4_m4m4(difmat, prev->pose_mat, imat);
510                         copy_m3_m4(result, difmat);                             // the desired rotation at beginning of next bone
511                         
512                         vec_roll_to_mat3(h1, 0.0f, mat3);                       // the result of vec_roll without roll
513                         
514                         invert_m3_m3(imat3, mat3);
515                         mul_m3_m3m3(mat3, result, imat3);                       // the matrix transforming vec_roll to desired roll
516                         
517                         roll1= (float)atan2(mat3[2][0], mat3[2][2]);
518                 }
519         }
520         else {
521                 h1[0]= 0.0f; h1[1]= hlength1; h1[2]= 0.0f;
522                 roll1= 0.0f;
523         }
524         if(next) {
525                 float difmat[4][4], result[3][3], imat3[3][3];
526                 
527                 /* transform next point inside this bone space */
528                 if(rest)
529                         VECCOPY(h2, next->bone->arm_tail)
530                 else
531                         VECCOPY(h2, next->pose_tail)
532                 mul_m4_v3(imat, h2);
533                 /* if next bone is B-bone too, use average handle direction */
534                 if(next->bone->segments>1);
535                 else h2[1]-= length;
536                 normalize_v3(h2);
537                 
538                 /* find the next roll to interpolate as well */
539                 if(rest)
540                         mul_m4_m4m4(difmat, next->bone->arm_mat, imat);
541                 else
542                         mul_m4_m4m4(difmat, next->pose_mat, imat);
543                 copy_m3_m4(result, difmat);                             // the desired rotation at beginning of next bone
544                 
545                 vec_roll_to_mat3(h2, 0.0f, mat3);                       // the result of vec_roll without roll
546                 
547                 invert_m3_m3(imat3, mat3);
548                 mul_m3_m3m3(mat3, imat3, result);                       // the matrix transforming vec_roll to desired roll
549                 
550                 roll2= (float)atan2(mat3[2][0], mat3[2][2]);
551                 
552                 /* and only now negate handle */
553                 mul_v3_fl(h2, -hlength2);
554         }
555         else {
556                 h2[0]= 0.0f; h2[1]= -hlength2; h2[2]= 0.0f;
557                 roll2= 0.0;
558         }
559
560         /* make curve */
561         if(bone->segments > MAX_BBONE_SUBDIV)
562                 bone->segments= MAX_BBONE_SUBDIV;
563         
564         forward_diff_bezier(0.0, h1[0],         h2[0],                  0.0,            data[0],        MAX_BBONE_SUBDIV, 4*sizeof(float));
565         forward_diff_bezier(0.0, h1[1],         length + h2[1], length,         data[0]+1,      MAX_BBONE_SUBDIV, 4*sizeof(float));
566         forward_diff_bezier(0.0, h1[2],         h2[2],                  0.0,            data[0]+2,      MAX_BBONE_SUBDIV, 4*sizeof(float));
567         forward_diff_bezier(roll1, roll1 + 0.390464f*(roll2-roll1), roll2 - 0.390464f*(roll2-roll1),    roll2,  data[0]+3,      MAX_BBONE_SUBDIV, 4*sizeof(float));
568         
569         equalize_bezier(data[0], bone->segments);       // note: does stride 4!
570         
571         /* make transformation matrices for the segments for drawing */
572         for(a=0, fp= data[0]; a<bone->segments; a++, fp+=4) {
573                 sub_v3_v3v3(h1, fp+4, fp);
574                 vec_roll_to_mat3(h1, fp[3], mat3);              // fp[3] is roll
575
576                 copy_m4_m3(result_array[a].mat, mat3);
577                 VECCOPY(result_array[a].mat[3], fp);
578
579                 if(doscale) {
580                         /* correct for scaling when this matrix is used in scaled space */
581                         mul_serie_m4(result_array[a].mat, iscalemat, result_array[a].mat,
582                                 scalemat, NULL, NULL, NULL, NULL, NULL);
583                 }
584         }
585         
586         return result_array;
587 }
588
589 /* ************ Armature Deform ******************* */
590
591 typedef struct bPoseChanDeform {
592         Mat4            *b_bone_mats;   
593         DualQuat        *dual_quat;
594         DualQuat        *b_bone_dual_quats;
595 } bPoseChanDeform;
596
597 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, int use_quaternion)
598 {
599         Bone *bone= pchan->bone;
600         Mat4 *b_bone= b_bone_spline_setup(pchan, 0);
601         Mat4 *b_bone_rest= b_bone_spline_setup(pchan, 1);
602         Mat4 *b_bone_mats;
603         DualQuat *b_bone_dual_quats= NULL;
604         float tmat[4][4]= MAT4_UNITY;
605         int a;
606         
607         /* allocate b_bone matrices and dual quats */
608         b_bone_mats= MEM_mallocN((1+bone->segments)*sizeof(Mat4), "BBone defmats");
609         pdef_info->b_bone_mats= b_bone_mats;
610
611         if(use_quaternion) {
612                 b_bone_dual_quats= MEM_mallocN((bone->segments)*sizeof(DualQuat), "BBone dqs");
613                 pdef_info->b_bone_dual_quats= b_bone_dual_quats;
614         }
615         
616         /* first matrix is the inverse arm_mat, to bring points in local bone space
617            for finding out which segment it belongs to */
618         invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
619
620         /* then we make the b_bone_mats:
621                 - first transform to local bone space
622                 - translate over the curve to the bbone mat space
623                 - transform with b_bone matrix
624                 - transform back into global space */
625
626         for(a=0; a<bone->segments; a++) {
627                 invert_m4_m4(tmat, b_bone_rest[a].mat);
628
629                 mul_serie_m4(b_bone_mats[a+1].mat, pchan->chan_mat, bone->arm_mat,
630                         b_bone[a].mat, tmat, b_bone_mats[0].mat, NULL, NULL, NULL);
631
632                 if(use_quaternion)
633                         mat4_to_dquat( &b_bone_dual_quats[a],bone->arm_mat, b_bone_mats[a+1].mat);
634         }
635 }
636
637 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float *co, DualQuat *dq, float defmat[][3])
638 {
639         Mat4 *b_bone= pdef_info->b_bone_mats;
640         float (*mat)[4]= b_bone[0].mat;
641         float segment, y;
642         int a;
643         
644         /* need to transform co back to bonespace, only need y */
645         y= mat[0][1]*co[0] + mat[1][1]*co[1] + mat[2][1]*co[2] + mat[3][1];
646         
647         /* now calculate which of the b_bones are deforming this */
648         segment= bone->length/((float)bone->segments);
649         a= (int)(y/segment);
650         
651         /* note; by clamping it extends deform at endpoints, goes best with
652            straight joints in restpos. */
653         CLAMP(a, 0, bone->segments-1);
654
655         if(dq) {
656                 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
657         }
658         else {
659                 mul_m4_v3(b_bone[a+1].mat, co);
660
661                 if(defmat)
662                         copy_m3_m4(defmat, b_bone[a+1].mat);
663         }
664 }
665
666 /* using vec with dist to bone b1 - b2 */
667 float distfactor_to_bone (float vec[3], float b1[3], float b2[3], float rad1, float rad2, float rdist)
668 {
669         float dist=0.0f; 
670         float bdelta[3];
671         float pdelta[3];
672         float hsqr, a, l, rad;
673         
674         sub_v3_v3v3(bdelta, b2, b1);
675         l = normalize_v3(bdelta);
676         
677         sub_v3_v3v3(pdelta, vec, b1);
678         
679         a = bdelta[0]*pdelta[0] + bdelta[1]*pdelta[1] + bdelta[2]*pdelta[2];
680         hsqr = ((pdelta[0]*pdelta[0]) + (pdelta[1]*pdelta[1]) + (pdelta[2]*pdelta[2]));
681         
682         if (a < 0.0F){
683                 /* If we're past the end of the bone, do a spherical field attenuation thing */
684                 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])) ;
685                 rad= rad1;
686         }
687         else if (a > l){
688                 /* If we're past the end of the bone, do a spherical field attenuation thing */
689                 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])) ;
690                 rad= rad2;
691         }
692         else {
693                 dist= (hsqr - (a*a));
694                 
695                 if(l!=0.0f) {
696                         rad= a/l;
697                         rad= rad*rad2 + (1.0f-rad)*rad1;
698                 }
699                 else rad= rad1;
700         }
701         
702         a= rad*rad;
703         if(dist < a) 
704                 return 1.0f;
705         else {
706                 l= rad+rdist;
707                 l*= l;
708                 if(rdist==0.0f || dist >= l) 
709                         return 0.0f;
710                 else {
711                         a= (float)sqrt(dist)-rad;
712                         return 1.0f-( a*a )/( rdist*rdist );
713                 }
714         }
715 }
716
717 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[][3], float mat[][3])
718 {
719         float wmat[3][3];
720
721         if(pchan->bone->segments>1)
722                 copy_m3_m3(wmat, bbonemat);
723         else
724                 copy_m3_m4(wmat, pchan->chan_mat);
725
726         mul_m3_fl(wmat, weight);
727         add_m3_m3m3(mat, mat, wmat);
728 }
729
730 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float *vec, DualQuat *dq, float mat[][3], float *co)
731 {
732         Bone *bone= pchan->bone;
733         float fac, contrib=0.0;
734         float cop[3], bbonemat[3][3];
735         DualQuat bbonedq;
736
737         if(bone==NULL) return 0.0f;
738         
739         VECCOPY (cop, co);
740
741         fac= distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
742         
743         if (fac > 0.0f) {
744                 
745                 fac*=bone->weight;
746                 contrib= fac;
747                 if(contrib > 0.0f) {
748                         if(vec) {
749                                 if(bone->segments>1)
750                                         // applies on cop and bbonemat
751                                         b_bone_deform(pdef_info, bone, cop, NULL, (mat)?bbonemat:NULL);
752                                 else
753                                         mul_m4_v3(pchan->chan_mat, cop);
754
755                                 //      Make this a delta from the base position
756                                 sub_v3_v3(cop, co);
757                                 madd_v3_v3fl(vec, cop, fac);
758
759                                 if(mat)
760                                         pchan_deform_mat_add(pchan, fac, bbonemat, mat);
761                         }
762                         else {
763                                 if(bone->segments>1) {
764                                         b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
765                                         add_weighted_dq_dq(dq, &bbonedq, fac);
766                                 }
767                                 else
768                                         add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
769                         }
770                 }
771         }
772         
773         return contrib;
774 }
775
776 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float *vec, DualQuat *dq, float mat[][3], float *co, float *contrib)
777 {
778         float cop[3], bbonemat[3][3];
779         DualQuat bbonedq;
780
781         if (!weight)
782                 return;
783
784         VECCOPY(cop, co);
785
786         if(vec) {
787                 if(pchan->bone->segments>1)
788                         // applies on cop and bbonemat
789                         b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat)?bbonemat:NULL);
790                 else
791                         mul_m4_v3(pchan->chan_mat, cop);
792                 
793                 vec[0]+=(cop[0]-co[0])*weight;
794                 vec[1]+=(cop[1]-co[1])*weight;
795                 vec[2]+=(cop[2]-co[2])*weight;
796
797                 if(mat)
798                         pchan_deform_mat_add(pchan, weight, bbonemat, mat);
799         }
800         else {
801                 if(pchan->bone->segments>1) {
802                         b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
803                         add_weighted_dq_dq(dq, &bbonedq, weight);
804                 }
805                 else
806                         add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
807         }
808
809         (*contrib)+=weight;
810 }
811
812 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm,
813                                                    float (*vertexCos)[3], float (*defMats)[3][3],
814                                                    int numVerts, int deformflag, 
815                                                    float (*prevCos)[3], const char *defgrp_name)
816 {
817         bPoseChanDeform *pdef_info_array;
818         bPoseChanDeform *pdef_info= NULL;
819         bArmature *arm= armOb->data;
820         bPoseChannel *pchan, **defnrToPC = NULL;
821         int *defnrToPCIndex= NULL;
822         MDeformVert *dverts = NULL;
823         bDeformGroup *dg;
824         DualQuat *dualquats= NULL;
825         float obinv[4][4], premat[4][4], postmat[4][4];
826         const short use_envelope = deformflag & ARM_DEF_ENVELOPE;
827         const short use_quaternion = deformflag & ARM_DEF_QUATERNION;
828         const short invert_vgroup= deformflag & ARM_DEF_INVERT_VGROUP;
829         int numGroups = 0;              /* safety for vertexgroup index overflow */
830         int i, target_totvert = 0;      /* safety for vertexgroup overflow */
831         int use_dverts = 0;
832         int armature_def_nr;
833         int totchan;
834
835         if(arm->edbo) return;
836         
837         invert_m4_m4(obinv, target->obmat);
838         copy_m4_m4(premat, target->obmat);
839         mul_m4_m4m4(postmat, armOb->obmat, obinv);
840         invert_m4_m4(premat, postmat);
841
842         /* bone defmats are already in the channels, chan_mat */
843         
844         /* initialize B_bone matrices and dual quaternions */
845         totchan= BLI_countlist(&armOb->pose->chanbase);
846
847         if(use_quaternion) {
848                 dualquats= MEM_callocN(sizeof(DualQuat)*totchan, "dualquats");
849         }
850         
851         pdef_info_array= MEM_callocN(sizeof(bPoseChanDeform)*totchan, "bPoseChanDeform");
852
853         totchan= 0;
854         pdef_info= pdef_info_array;
855         for(pchan= armOb->pose->chanbase.first; pchan; pchan= pchan->next, pdef_info++) {
856                 if(!(pchan->bone->flag & BONE_NO_DEFORM)) {
857                         if(pchan->bone->segments > 1)
858                                 pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
859
860                         if(use_quaternion) {
861                                 pdef_info->dual_quat= &dualquats[totchan++];
862                                 mat4_to_dquat( pdef_info->dual_quat,pchan->bone->arm_mat, pchan->chan_mat);
863                         }
864                 }
865         }
866
867         /* get the def_nr for the overall armature vertex group if present */
868         armature_def_nr= defgroup_name_index(target, defgrp_name);
869         
870         if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
871                 numGroups = BLI_countlist(&target->defbase);
872                 
873                 if(target->type==OB_MESH) {
874                         Mesh *me= target->data;
875                         dverts = me->dvert;
876                         if(dverts)
877                                 target_totvert = me->totvert;
878                 }
879                 else {
880                         Lattice *lt= target->data;
881                         dverts = lt->dvert;
882                         if(dverts)
883                                 target_totvert = lt->pntsu*lt->pntsv*lt->pntsw;
884                 }
885         }
886         
887         /* get a vertex-deform-index to posechannel array */
888         if(deformflag & ARM_DEF_VGROUP) {
889                 if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
890                         /* if we have a DerivedMesh, only use dverts if it has them */
891                         if(dm)
892                                 if(dm->getVertData(dm, 0, CD_MDEFORMVERT))
893                                         use_dverts = 1;
894                                 else use_dverts = 0;
895                         else if(dverts) use_dverts = 1;
896
897                         if(use_dverts) {
898                                 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * numGroups, "defnrToBone");
899                                 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * numGroups, "defnrToIndex");
900                                 for(i = 0, dg = target->defbase.first; dg;
901                                         i++, dg = dg->next) {
902                                         defnrToPC[i] = get_pose_channel(armOb->pose, dg->name);
903                                         /* exclude non-deforming bones */
904                                         if(defnrToPC[i]) {
905                                                 if(defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
906                                                         defnrToPC[i]= NULL;
907                                                 }
908                                                 else {
909                                                         defnrToPCIndex[i]= BLI_findindex(&armOb->pose->chanbase, defnrToPC[i]);
910                                                 }
911                                         }
912                                 }
913                         }
914                 }
915         }
916
917         for(i = 0; i < numVerts; i++) {
918                 MDeformVert *dvert;
919                 DualQuat sumdq, *dq = NULL;
920                 float *co, dco[3];
921                 float sumvec[3], summat[3][3];
922                 float *vec = NULL, (*smat)[3] = NULL;
923                 float contrib = 0.0f;
924                 float armature_weight = 1.0f;   /* default to 1 if no overall def group */
925                 float prevco_weight = 1.0f;             /* weight for optional cached vertexcos */
926                 int       j;
927
928                 if(use_quaternion) {
929                         memset(&sumdq, 0, sizeof(DualQuat));
930                         dq= &sumdq;
931                 }
932                 else {
933                         sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
934                         vec= sumvec;
935
936                         if(defMats) {
937                                 zero_m3(summat);
938                                 smat = summat;
939                         }
940                 }
941
942                 if(use_dverts || armature_def_nr >= 0) {
943                         if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
944                         else if(dverts && i < target_totvert) dvert = dverts + i;
945                         else dvert = NULL;
946                 } else
947                         dvert = NULL;
948
949                 if(armature_def_nr >= 0 && dvert) {
950                         armature_weight= defvert_find_weight(dvert, armature_def_nr);
951
952                         if(invert_vgroup) {
953                                 armature_weight= 1.0f-armature_weight;
954                         }
955
956                         /* hackish: the blending factor can be used for blending with prevCos too */
957                         if(prevCos) {
958                                 prevco_weight= armature_weight;
959                                 armature_weight= 1.0f;
960                         }
961                 }
962
963                 /* check if there's any  point in calculating for this vert */
964                 if(armature_weight == 0.0f) continue;
965                 
966                 /* get the coord we work on */
967                 co= prevCos?prevCos[i]:vertexCos[i];
968                 
969                 /* Apply the object's matrix */
970                 mul_m4_v3(premat, co);
971                 
972                 if(use_dverts && dvert && dvert->totweight) { // use weight groups ?
973                         int deformed = 0;
974                         
975                         for(j = 0; j < dvert->totweight; j++){
976                                 int index = dvert->dw[j].def_nr;
977                                 if(index < numGroups && (pchan= defnrToPC[index])) {
978                                         float weight = dvert->dw[j].weight;
979                                         Bone *bone= pchan->bone;
980                                         pdef_info= pdef_info_array + defnrToPCIndex[index];
981
982                                         deformed = 1;
983                                         
984                                         if(bone && bone->flag & BONE_MULT_VG_ENV) {
985                                                 weight *= distfactor_to_bone(co, bone->arm_head,
986                                                                                                          bone->arm_tail,
987                                                                                                          bone->rad_head,
988                                                                                                          bone->rad_tail,
989                                                                                                          bone->dist);
990                                         }
991                                         pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
992                                 }
993                         }
994                         /* if there are vertexgroups but not groups with bones
995                          * (like for softbody groups)
996                          */
997                         if(deformed == 0 && use_envelope) {
998                                 pdef_info= pdef_info_array;
999                                 for(pchan= armOb->pose->chanbase.first; pchan;
1000                                         pchan= pchan->next, pdef_info++) {
1001                                         if(!(pchan->bone->flag & BONE_NO_DEFORM))
1002                                                 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1003                                 }
1004                         }
1005                 }
1006                 else if(use_envelope) {
1007                         pdef_info= pdef_info_array;
1008                         for(pchan = armOb->pose->chanbase.first; pchan;
1009                                 pchan = pchan->next, pdef_info++) {
1010                                 if(!(pchan->bone->flag & BONE_NO_DEFORM))
1011                                         contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1012                         }
1013                 }
1014
1015                 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1016                 if(contrib > 0.0001f) {
1017                         if(use_quaternion) {
1018                                 normalize_dq(dq, contrib);
1019
1020                                 if(armature_weight != 1.0f) {
1021                                         VECCOPY(dco, co);
1022                                         mul_v3m3_dq( dco, (defMats)? summat: NULL,dq);
1023                                         sub_v3_v3(dco, co);
1024                                         mul_v3_fl(dco, armature_weight);
1025                                         add_v3_v3(co, dco);
1026                                 }
1027                                 else
1028                                         mul_v3m3_dq( co, (defMats)? summat: NULL,dq);
1029
1030                                 smat = summat;
1031                         }
1032                         else {
1033                                 mul_v3_fl(vec, armature_weight/contrib);
1034                                 add_v3_v3v3(co, vec, co);
1035                         }
1036
1037                         if(defMats) {
1038                                 float pre[3][3], post[3][3], tmpmat[3][3];
1039
1040                                 copy_m3_m4(pre, premat);
1041                                 copy_m3_m4(post, postmat);
1042                                 copy_m3_m3(tmpmat, defMats[i]);
1043
1044                                 if(!use_quaternion) /* quaternion already is scale corrected */
1045                                         mul_m3_fl(smat, armature_weight/contrib);
1046
1047                                 mul_serie_m3(defMats[i], tmpmat, pre, smat, post,
1048                                         NULL, NULL, NULL, NULL);
1049                         }
1050                 }
1051                 
1052                 /* always, check above code */
1053                 mul_m4_v3(postmat, co);
1054                 
1055                 
1056                 /* interpolate with previous modifier position using weight group */
1057                 if(prevCos) {
1058                         float mw= 1.0f - prevco_weight;
1059                         vertexCos[i][0]= prevco_weight*vertexCos[i][0] + mw*co[0];
1060                         vertexCos[i][1]= prevco_weight*vertexCos[i][1] + mw*co[1];
1061                         vertexCos[i][2]= prevco_weight*vertexCos[i][2] + mw*co[2];
1062                 }
1063         }
1064
1065         if(dualquats) MEM_freeN(dualquats);
1066         if(defnrToPC) MEM_freeN(defnrToPC);
1067         if(defnrToPCIndex) MEM_freeN(defnrToPCIndex);
1068
1069         /* free B_bone matrices */
1070         pdef_info= pdef_info_array;
1071         for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1072                 if(pdef_info->b_bone_mats) {
1073                         MEM_freeN(pdef_info->b_bone_mats);
1074                 }
1075                 if(pdef_info->b_bone_dual_quats) {
1076                         MEM_freeN(pdef_info->b_bone_dual_quats);
1077                 }
1078         }
1079
1080         MEM_freeN(pdef_info_array);
1081 }
1082
1083 /* ************ END Armature Deform ******************* */
1084
1085 void get_objectspace_bone_matrix (struct Bone* bone, float M_accumulatedMatrix[][4], int UNUSED(root), int UNUSED(posed))
1086 {
1087         copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1088 }
1089
1090 /* **************** Space to Space API ****************** */
1091
1092 /* Convert World-Space Matrix to Pose-Space Matrix */
1093 void armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4]) 
1094 {
1095         float obmat[4][4];
1096         
1097         /* prevent crashes */
1098         if (ob==NULL) return;
1099         
1100         /* get inverse of (armature) object's matrix  */
1101         invert_m4_m4(obmat, ob->obmat);
1102         
1103         /* multiply given matrix by object's-inverse to find pose-space matrix */
1104         mul_m4_m4m4(outmat, obmat, inmat);
1105 }
1106
1107 /* Convert Wolrd-Space Location to Pose-Space Location
1108  * NOTE: this cannot be used to convert to pose-space location of the supplied
1109  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1110  */
1111 void armature_loc_world_to_pose(Object *ob, float *inloc, float *outloc) 
1112 {
1113         float xLocMat[4][4]= MAT4_UNITY;
1114         float nLocMat[4][4];
1115         
1116         /* build matrix for location */
1117         VECCOPY(xLocMat[3], inloc);
1118
1119         /* get bone-space cursor matrix and extract location */
1120         armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1121         VECCOPY(outloc, nLocMat[3]);
1122 }
1123
1124 /* Convert Pose-Space Matrix to Bone-Space Matrix 
1125  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1126  *              pose-channel into its local space (i.e. 'visual'-keyframing)
1127  */
1128 void armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1129 {
1130         float pc_trans[4][4], inv_trans[4][4];
1131         float pc_posemat[4][4], inv_posemat[4][4];
1132         float pose_mat[4][4];
1133
1134         /* paranoia: prevent crashes with no pose-channel supplied */
1135         if (pchan==NULL) return;
1136
1137         /* default flag */
1138         if((pchan->bone->flag & BONE_NO_LOCAL_LOCATION)==0) {
1139                 /* get the inverse matrix of the pchan's transforms */
1140                 switch(pchan->rotmode) {
1141                 case ROT_MODE_QUAT:
1142                         loc_quat_size_to_mat4(pc_trans, pchan->loc, pchan->quat, pchan->size);
1143                         break;
1144                 case ROT_MODE_AXISANGLE:
1145                         loc_axisangle_size_to_mat4(pc_trans, pchan->loc, pchan->rotAxis, pchan->rotAngle, pchan->size);
1146                         break;
1147                 default: /* euler */
1148                         loc_eul_size_to_mat4(pc_trans, pchan->loc, pchan->eul, pchan->size);
1149                 }
1150
1151                 copy_m4_m4(pose_mat, pchan->pose_mat);
1152         }
1153         else {
1154                 /* local location, this is not default, different calculation
1155                  * note: only tested for location with pose bone snapping.
1156                  * If this is not useful in other cases the BONE_NO_LOCAL_LOCATION
1157                  * case may have to be split into its own function. */
1158                 unit_m4(pc_trans);
1159                 copy_v3_v3(pc_trans[3], pchan->loc);
1160
1161                 /* use parents rotation/scale space + own absolute position */
1162                 if(pchan->parent)       copy_m4_m4(pose_mat, pchan->parent->pose_mat);
1163                 else                            unit_m4(pose_mat);
1164
1165                 copy_v3_v3(pose_mat[3], pchan->pose_mat[3]);
1166         }
1167
1168
1169         invert_m4_m4(inv_trans, pc_trans);
1170         
1171         /* Remove the pchan's transforms from it's pose_mat.
1172          * This should leave behind the effects of restpose + 
1173          * parenting + constraints
1174          */
1175         mul_m4_m4m4(pc_posemat, inv_trans, pose_mat);
1176         
1177         /* get the inverse of the leftovers so that we can remove 
1178          * that component from the supplied matrix
1179          */
1180         invert_m4_m4(inv_posemat, pc_posemat);
1181         
1182         /* get the new matrix */
1183         mul_m4_m4m4(outmat, inmat, inv_posemat);
1184 }
1185
1186 /* Convert Pose-Space Location to Bone-Space Location
1187  * NOTE: this cannot be used to convert to pose-space location of the supplied
1188  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1189  */
1190 void armature_loc_pose_to_bone(bPoseChannel *pchan, float *inloc, float *outloc) 
1191 {
1192         float xLocMat[4][4]= MAT4_UNITY;
1193         float nLocMat[4][4];
1194         
1195         /* build matrix for location */
1196         VECCOPY(xLocMat[3], inloc);
1197
1198         /* get bone-space cursor matrix and extract location */
1199         armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1200         VECCOPY(outloc, nLocMat[3]);
1201 }
1202
1203 /* same as object_mat3_to_rot() */
1204 void pchan_mat3_to_rot(bPoseChannel *pchan, float mat[][3], short use_compat)
1205 {
1206         switch(pchan->rotmode) {
1207         case ROT_MODE_QUAT:
1208                 mat3_to_quat(pchan->quat, mat);
1209                 break;
1210         case ROT_MODE_AXISANGLE:
1211                 mat3_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1212                 break;
1213         default: /* euler */
1214                 if(use_compat)  mat3_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1215                 else                    mat3_to_eulO(pchan->eul, pchan->rotmode, mat);
1216         }
1217 }
1218
1219 /* Apply a 4x4 matrix to the pose bone,
1220  * similar to object_apply_mat4()
1221  */
1222 void pchan_apply_mat4(bPoseChannel *pchan, float mat[][4], short use_compat)
1223 {
1224         float rot[3][3];
1225         mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1226         pchan_mat3_to_rot(pchan, rot, use_compat);
1227 }
1228
1229 /* Remove rest-position effects from pose-transform for obtaining
1230  * 'visual' transformation of pose-channel.
1231  * (used by the Visual-Keyframing stuff)
1232  */
1233 void armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
1234 {
1235         float imat[4][4];
1236         
1237         invert_m4_m4(imat, arm_mat);
1238         mul_m4_m4m4(delta_mat, pose_mat, imat);
1239 }
1240
1241 /* **************** Rotation Mode Conversions ****************************** */
1242 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1243
1244 /* Called from RNA when rotation mode changes 
1245  *      - the result should be that the rotations given in the provided pointers have had conversions 
1246  *        applied (as appropriate), such that the rotation of the element hasn't 'visually' changed 
1247  */
1248 void BKE_rotMode_change_values (float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1249 {
1250         /* check if any change - if so, need to convert data */
1251         if (newMode > 0) { /* to euler */
1252                 if (oldMode == ROT_MODE_AXISANGLE) {
1253                         /* axis-angle to euler */
1254                         axis_angle_to_eulO( eul, newMode,axis, *angle);
1255                 }
1256                 else if (oldMode == ROT_MODE_QUAT) {
1257                         /* quat to euler */
1258                         normalize_qt(quat);
1259                         quat_to_eulO( eul, newMode,quat);
1260                 }
1261                 /* else { no conversion needed } */
1262         }
1263         else if (newMode == ROT_MODE_QUAT) { /* to quat */
1264                 if (oldMode == ROT_MODE_AXISANGLE) {
1265                         /* axis angle to quat */
1266                         axis_angle_to_quat(quat, axis, *angle);
1267                 }
1268                 else if (oldMode > 0) {
1269                         /* euler to quat */
1270                         eulO_to_quat( quat,eul, oldMode);
1271                 }
1272                 /* else { no conversion needed } */
1273         }
1274         else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1275                 if (oldMode > 0) {
1276                         /* euler to axis angle */
1277                         eulO_to_axis_angle( axis, angle,eul, oldMode);
1278                 }
1279                 else if (oldMode == ROT_MODE_QUAT) {
1280                         /* quat to axis angle */
1281                         normalize_qt(quat);
1282                         quat_to_axis_angle( axis, angle,quat);
1283                 }
1284                 
1285                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1286                 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1287                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1288                         axis[1]= 1.0f;
1289                 }
1290         }
1291 }
1292
1293 /* **************** The new & simple (but OK!) armature evaluation ********* */ 
1294
1295 /*  ****************** And how it works! ****************************************
1296
1297   This is the bone transformation trick; they're hierarchical so each bone(b)
1298   is in the coord system of bone(b-1):
1299
1300   arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) 
1301   
1302   -> yoffs is just the y axis translation in parent's coord system
1303   -> d_root is the translation of the bone root, also in parent's coord system
1304
1305   pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1306
1307   we then - in init deform - store the deform in chan_mat, such that:
1308
1309   pose_mat(b)= arm_mat(b) * chan_mat(b)
1310   
1311   *************************************************************************** */
1312 /*  Computes vector and roll based on a rotation. "mat" must
1313          contain only a rotation, and no scaling. */ 
1314 void mat3_to_vec_roll(float mat[][3], float *vec, float *roll) 
1315 {
1316         if (vec)
1317                 copy_v3_v3(vec, mat[1]);
1318
1319         if (roll) {
1320                 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1321
1322                 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1323                 invert_m3_m3(vecmatinv, vecmat);
1324                 mul_m3_m3m3(rollmat, vecmatinv, mat);
1325
1326                 *roll= (float)atan2(rollmat[2][0], rollmat[2][2]);
1327         }
1328 }
1329
1330 /*      Calculates the rest matrix of a bone based
1331         On its vector and a roll around that vector */
1332 void vec_roll_to_mat3(float *vec, float roll, float mat[][3])
1333 {
1334         float   nor[3], axis[3], target[3]={0,1,0};
1335         float   theta;
1336         float   rMatrix[3][3], bMatrix[3][3];
1337
1338         normalize_v3_v3(nor, vec);
1339         
1340         /*      Find Axis & Amount for bone matrix*/
1341         cross_v3_v3v3(axis,target,nor);
1342
1343         /* was 0.0000000000001, caused bug [#23954], smaller values give unstable
1344          * roll when toggling editmode.
1345          *
1346          * was 0.00001, causes bug [#27675], with 0.00000495,
1347          * so a value inbetween these is needed.
1348          */
1349         if (dot_v3v3(axis,axis) > 0.000001f) {
1350                 /* if nor is *not* a multiple of target ... */
1351                 normalize_v3(axis);
1352                 
1353                 theta= angle_normalized_v3v3(target, nor);
1354                 
1355                 /*      Make Bone matrix*/
1356                 vec_rot_to_mat3( bMatrix,axis, theta);
1357         }
1358         else {
1359                 /* if nor is a multiple of target ... */
1360                 float updown;
1361                 
1362                 /* point same direction, or opposite? */
1363                 updown = ( dot_v3v3(target,nor) > 0 ) ? 1.0f : -1.0f;
1364                 
1365                 /* I think this should work ... */
1366                 bMatrix[0][0]=updown; bMatrix[0][1]=0.0;    bMatrix[0][2]=0.0;
1367                 bMatrix[1][0]=0.0;    bMatrix[1][1]=updown; bMatrix[1][2]=0.0;
1368                 bMatrix[2][0]=0.0;    bMatrix[2][1]=0.0;    bMatrix[2][2]=1.0;
1369         }
1370         
1371         /*      Make Roll matrix*/
1372         vec_rot_to_mat3( rMatrix,nor, roll);
1373         
1374         /*      Combine and output result*/
1375         mul_m3_m3m3(mat, rMatrix, bMatrix);
1376 }
1377
1378
1379 /* recursive part, calculates restposition of entire tree of children */
1380 /* used by exiting editmode too */
1381 void where_is_armature_bone(Bone *bone, Bone *prevbone)
1382 {
1383         float vec[3];
1384         
1385         /* Bone Space */
1386         sub_v3_v3v3(vec, bone->tail, bone->head);
1387         vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1388
1389         bone->length= len_v3v3(bone->head, bone->tail);
1390         
1391         /* this is called on old file reading too... */
1392         if(bone->xwidth==0.0f) {
1393                 bone->xwidth= 0.1f;
1394                 bone->zwidth= 0.1f;
1395                 bone->segments= 1;
1396         }
1397         
1398         if(prevbone) {
1399                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
1400                 
1401                 /* bone transform itself */
1402                 copy_m4_m3(offs_bone, bone->bone_mat);
1403                                 
1404                 /* The bone's root offset (is in the parent's coordinate system) */
1405                 VECCOPY(offs_bone[3], bone->head);
1406
1407                 /* Get the length translation of parent (length along y axis) */
1408                 offs_bone[3][1]+= prevbone->length;
1409                 
1410                 /* Compose the matrix for this bone  */
1411                 mul_m4_m4m4(bone->arm_mat, offs_bone, prevbone->arm_mat);
1412         }
1413         else {
1414                 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1415                 VECCOPY(bone->arm_mat[3], bone->head);
1416         }
1417         
1418         /* and the kiddies */
1419         prevbone= bone;
1420         for(bone= bone->childbase.first; bone; bone= bone->next) {
1421                 where_is_armature_bone(bone, prevbone);
1422         }
1423 }
1424
1425 /* updates vectors and matrices on rest-position level, only needed 
1426    after editing armature itself, now only on reading file */
1427 void where_is_armature (bArmature *arm)
1428 {
1429         Bone *bone;
1430         
1431         /* hierarchical from root to children */
1432         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1433                 where_is_armature_bone(bone, NULL);
1434         }
1435 }
1436
1437 /* if bone layer is protected, copy the data from from->pose
1438  * when used with linked libraries this copies from the linked pose into the local pose */
1439 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1440 {
1441         bPose *pose= ob->pose, *frompose= from->pose;
1442         bPoseChannel *pchan, *pchanp, pchanw;
1443         bConstraint *con;
1444         int error = 0;
1445         
1446         if (frompose==NULL) return;
1447
1448         /* in some cases when rigs change, we cant synchronize
1449          * to avoid crashing check for possible errors here */
1450         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1451                 if (pchan->bone->layer & layer_protected) {
1452                         if(get_pose_channel(frompose, pchan->name) == NULL) {
1453                                 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n", from->id.name, pchan->name);
1454                                 error = 1;
1455                         }
1456                 }
1457         }
1458
1459         if(error)
1460                 return;
1461         
1462         /* clear all transformation values from library */
1463         rest_pose(frompose);
1464         
1465         /* copy over all of the proxy's bone groups */
1466                 /* TODO for later - implement 'local' bone groups as for constraints
1467                  *      Note: this isn't trivial, as bones reference groups by index not by pointer, 
1468                  *               so syncing things correctly needs careful attention
1469                  */
1470         BLI_freelistN(&pose->agroups);
1471         BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1472         pose->active_group= frompose->active_group;
1473         
1474         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1475                 pchanp= get_pose_channel(frompose, pchan->name);
1476
1477                 if (pchan->bone->layer & layer_protected) {
1478                         ListBase proxylocal_constraints = {NULL, NULL};
1479                         
1480                         /* copy posechannel to temp, but restore important pointers */
1481                         pchanw= *pchanp;
1482                         pchanw.prev= pchan->prev;
1483                         pchanw.next= pchan->next;
1484                         pchanw.parent= pchan->parent;
1485                         pchanw.child= pchan->child;
1486                         
1487                         /* this is freed so copy a copy, else undo crashes */
1488                         if(pchanw.prop) {
1489                                 pchanw.prop= IDP_CopyProperty(pchanw.prop);
1490
1491                                 /* use the values from the the existing props */
1492                                 if(pchan->prop) {
1493                                         IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1494                                 }
1495                         }
1496
1497                         /* constraints - proxy constraints are flushed... local ones are added after 
1498                          *      1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1499                          *      2. copy proxy-pchan's constraints on-to new
1500                          *      3. add extracted local constraints back on top 
1501                          *
1502                          *  note for copy_constraints: when copying constraints, disable 'do_extern' otherwise we get the libs direct linked in this blend.
1503                          */
1504                         extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
1505                         copy_constraints(&pchanw.constraints, &pchanp->constraints, FALSE);
1506                         BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1507                         
1508                         /* constraints - set target ob pointer to own object */
1509                         for (con= pchanw.constraints.first; con; con= con->next) {
1510                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1511                                 ListBase targets = {NULL, NULL};
1512                                 bConstraintTarget *ct;
1513                                 
1514                                 if (cti && cti->get_constraint_targets) {
1515                                         cti->get_constraint_targets(con, &targets);
1516                                         
1517                                         for (ct= targets.first; ct; ct= ct->next) {
1518                                                 if (ct->tar == from)
1519                                                         ct->tar = ob;
1520                                         }
1521                                         
1522                                         if (cti->flush_constraint_targets)
1523                                                 cti->flush_constraint_targets(con, &targets, 0);
1524                                 }
1525                         }
1526                         
1527                         /* free stuff from current channel */
1528                         free_pose_channel(pchan);
1529                         
1530                         /* the final copy */
1531                         *pchan= pchanw;
1532                 }
1533                 else {
1534                         /* always copy custom shape */
1535                         pchan->custom= pchanp->custom;
1536                         pchan->custom_tx= pchanp->custom_tx;
1537
1538                         /* ID-Property Syncing */
1539                         {
1540                                 IDProperty *prop_orig= pchan->prop;
1541                                 if(pchanp->prop) {
1542                                         pchan->prop= IDP_CopyProperty(pchanp->prop);
1543                                         if(prop_orig) {
1544                                                 /* copy existing values across when types match */
1545                                                 IDP_SyncGroupValues(pchan->prop, prop_orig);
1546                                         }
1547                                 }
1548                                 else {
1549                                         pchan->prop= NULL;
1550                                 }
1551                                 if (prop_orig) {
1552                                         IDP_FreeProperty(prop_orig);
1553                                         MEM_freeN(prop_orig);
1554                                 }
1555                         }
1556                 }
1557         }
1558 }
1559
1560 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1561 {
1562         bPoseChannel *pchan = verify_pose_channel (pose, bone->name);   // verify checks and/or adds
1563
1564         pchan->bone= bone;
1565         pchan->parent= parchan;
1566         
1567         counter++;
1568         
1569         for(bone= bone->childbase.first; bone; bone= bone->next) {
1570                 counter= rebuild_pose_bone(pose, bone, pchan, counter);
1571                 /* for quick detecting of next bone in chain, only b-bone uses it now */
1572                 if(bone->flag & BONE_CONNECTED)
1573                         pchan->child= get_pose_channel(pose, bone->name);
1574         }
1575         
1576         return counter;
1577 }
1578
1579 /* only after leave editmode, duplicating, validating older files, library syncing */
1580 /* NOTE: pose->flag is set for it */
1581 void armature_rebuild_pose(Object *ob, bArmature *arm)
1582 {
1583         Bone *bone;
1584         bPose *pose;
1585         bPoseChannel *pchan, *next;
1586         int counter=0;
1587                 
1588         /* only done here */
1589         if(ob->pose==NULL) {
1590                 /* create new pose */
1591                 ob->pose= MEM_callocN(sizeof(bPose), "new pose");
1592                 
1593                 /* set default settings for animviz */
1594                 animviz_settings_init(&ob->pose->avs);
1595         }
1596         pose= ob->pose;
1597         
1598         /* clear */
1599         for(pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1600                 pchan->bone= NULL;
1601                 pchan->child= NULL;
1602         }
1603         
1604         /* first step, check if all channels are there */
1605         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1606                 counter= rebuild_pose_bone(pose, bone, NULL, counter);
1607         }
1608
1609         /* and a check for garbage */
1610         for(pchan= pose->chanbase.first; pchan; pchan= next) {
1611                 next= pchan->next;
1612                 if(pchan->bone==NULL) {
1613                         free_pose_channel(pchan);
1614                         free_pose_channels_hash(pose);
1615                         BLI_freelinkN(&pose->chanbase, pchan);
1616                 }
1617         }
1618         // printf("rebuild pose %s, %d bones\n", ob->id.name, counter);
1619         
1620         /* synchronize protected layers with proxy */
1621         if(ob->proxy) {
1622                 object_copy_proxy_drivers(ob, ob->proxy);
1623                 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1624         }
1625         
1626         update_pose_constraint_flags(ob->pose); // for IK detection for example
1627         
1628         /* the sorting */
1629         if(counter>1)
1630                 DAG_pose_sort(ob);
1631         
1632         ob->pose->flag &= ~POSE_RECALC;
1633         ob->pose->flag |= POSE_WAS_REBUILT;
1634
1635         make_pose_channels_hash(ob->pose);
1636 }
1637
1638
1639 /* ********************** SPLINE IK SOLVER ******************* */
1640
1641 /* Temporary evaluation tree data used for Spline IK */
1642 typedef struct tSplineIK_Tree {
1643         struct tSplineIK_Tree *next, *prev;
1644         
1645         int     type;                                   /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
1646         
1647         short free_points;                              /* free the point positions array */
1648         short chainlen;                                 /* number of bones in the chain */
1649         
1650         float *points;                                  /* parametric positions for the joints along the curve */
1651         bPoseChannel **chain;                   /* chain of bones to affect using Spline IK (ordered from the tip) */
1652         
1653         bPoseChannel *root;                             /* bone that is the root node of the chain */
1654         
1655         bConstraint *con;                               /* constraint for this chain */
1656         bSplineIKConstraint *ikData;    /* constraint settings for this chain */
1657 } tSplineIK_Tree;
1658
1659 /* ----------- */
1660
1661 /* Tag the bones in the chain formed by the given bone for IK */
1662 static void splineik_init_tree_from_pchan(Scene *scene, Object *UNUSED(ob), bPoseChannel *pchan_tip)
1663 {
1664         bPoseChannel *pchan, *pchanRoot=NULL;
1665         bPoseChannel *pchanChain[255];
1666         bConstraint *con = NULL;
1667         bSplineIKConstraint *ikData = NULL;
1668         float boneLengths[255], *jointPoints;
1669         float totLength = 0.0f;
1670         short free_joints = 0;
1671         int segcount = 0;
1672         
1673         /* find the SplineIK constraint */
1674         for (con= pchan_tip->constraints.first; con; con= con->next) {
1675                 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
1676                         ikData= con->data;
1677                         
1678                         /* target can only be curve */
1679                         if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))  
1680                                 continue;
1681                         /* skip if disabled */
1682                         if ( (con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE|CONSTRAINT_OFF)) )
1683                                 continue;
1684                         
1685                         /* otherwise, constraint is ok... */
1686                         break;
1687                 }
1688         }
1689         if (con == NULL)
1690                 return;
1691                 
1692         /* make sure that the constraint targets are ok 
1693          *      - this is a workaround for a depsgraph bug...
1694          */
1695         if (ikData->tar) {
1696                 Curve *cu= ikData->tar->data;
1697                 
1698                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1699                  *              currently for paths to work it needs to go through the bevlist/displist system (ton) 
1700                  */
1701                 
1702                 /* only happens on reload file, but violates depsgraph still... fix! */
1703                 if ((cu->path==NULL) || (cu->path->data==NULL))
1704                         makeDispListCurveTypes(scene, ikData->tar, 0);
1705         }
1706         
1707         /* find the root bone and the chain of bones from the root to the tip 
1708          * NOTE: this assumes that the bones are connected, but that may not be true...
1709          */
1710         for (pchan= pchan_tip; pchan && (segcount < ikData->chainlen); pchan= pchan->parent, segcount++) {
1711                 /* store this segment in the chain */
1712                 pchanChain[segcount]= pchan;
1713                 
1714                 /* if performing rebinding, calculate the length of the bone */
1715                 boneLengths[segcount]= pchan->bone->length;
1716                 totLength += boneLengths[segcount];
1717         }
1718         
1719         if (segcount == 0)
1720                 return;
1721         else
1722                 pchanRoot= pchanChain[segcount-1];
1723         
1724         /* perform binding step if required */
1725         if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
1726                 float segmentLen= (1.0f / (float)segcount);
1727                 int i;
1728                 
1729                 /* setup new empty array for the points list */
1730                 if (ikData->points) 
1731                         MEM_freeN(ikData->points);
1732                 ikData->numpoints= ikData->chainlen+1; 
1733                 ikData->points= MEM_callocN(sizeof(float)*ikData->numpoints, "Spline IK Binding");
1734                 
1735                 /* bind 'tip' of chain (i.e. first joint = tip of bone with the Spline IK Constraint) */
1736                 ikData->points[0] = 1.0f;
1737                 
1738                 /* perform binding of the joints to parametric positions along the curve based 
1739                  * proportion of the total length that each bone occupies
1740                  */
1741                 for (i = 0; i < segcount; i++) {
1742                         /* 'head' joints, travelling towards the root of the chain
1743                          *      - 2 methods; the one chosen depends on whether we've got usable lengths
1744                          */
1745                         if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
1746                                 /* 1) equi-spaced joints */
1747                                 ikData->points[i+1]= ikData->points[i] - segmentLen;
1748                         }
1749                         else {
1750                                 /*      2) to find this point on the curve, we take a step from the previous joint
1751                                  *        a distance given by the proportion that this bone takes
1752                                  */
1753                                 ikData->points[i+1]= ikData->points[i] - (boneLengths[i] / totLength);
1754                         }
1755                 }
1756                 
1757                 /* spline has now been bound */
1758                 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
1759         }
1760         
1761         /* apply corrections for sensitivity to scaling on a copy of the bind points,
1762          * since it's easier to determine the positions of all the joints beforehand this way
1763          */
1764         if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
1765                 Curve *cu= (Curve *)ikData->tar->data;
1766                 float splineLen, maxScale;
1767                 int i;
1768                 
1769                 /* make a copy of the points array, that we'll store in the tree 
1770                  *      - although we could just multiply the points on the fly, this approach means that
1771                  *        we can introduce per-segment stretchiness later if it is necessary
1772                  */
1773                 jointPoints= MEM_dupallocN(ikData->points);
1774                 free_joints= 1;
1775                 
1776                 /* get the current length of the curve */
1777                 // NOTE: this is assumed to be correct even after the curve was resized
1778                 splineLen= cu->path->totdist;
1779                 
1780                 /* calculate the scale factor to multiply all the path values by so that the 
1781                  * bone chain retains its current length, such that
1782                  *      maxScale * splineLen = totLength
1783                  */
1784                 maxScale = totLength / splineLen;
1785                 
1786                 /* apply scaling correction to all of the temporary points */
1787                 // TODO: this is really not adequate enough on really short chains
1788                 for (i = 0; i < segcount; i++)
1789                         jointPoints[i] *= maxScale;
1790         }
1791         else {
1792                 /* just use the existing points array */
1793                 jointPoints= ikData->points;
1794                 free_joints= 0;
1795         }
1796         
1797         /* make a new Spline-IK chain, and store it in the IK chains */
1798         // TODO: we should check if there is already an IK chain on this, since that would take presidence...
1799         {
1800                 /* make new tree */
1801                 tSplineIK_Tree *tree= MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
1802                 tree->type= CONSTRAINT_TYPE_SPLINEIK;
1803                 
1804                 tree->chainlen= segcount;
1805                 
1806                 /* copy over the array of links to bones in the chain (from tip to root) */
1807                 tree->chain= MEM_callocN(sizeof(bPoseChannel*)*segcount, "SplineIK Chain");
1808                 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel*)*segcount);
1809                 
1810                 /* store reference to joint position array */
1811                 tree->points= jointPoints;
1812                 tree->free_points= free_joints;
1813                 
1814                 /* store references to different parts of the chain */
1815                 tree->root= pchanRoot;
1816                 tree->con= con;
1817                 tree->ikData= ikData;
1818                 
1819                 /* AND! link the tree to the root */
1820                 BLI_addtail(&pchanRoot->iktree, tree);
1821         }
1822         
1823         /* mark root channel having an IK tree */
1824         pchanRoot->flag |= POSE_IKSPLINE;
1825 }
1826
1827 /* Tag which bones are members of Spline IK chains */
1828 static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime))
1829 {
1830         bPoseChannel *pchan;
1831         
1832         /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
1833         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1834                 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
1835                         splineik_init_tree_from_pchan(scene, ob, pchan);
1836         }
1837 }
1838
1839 /* ----------- */
1840
1841 /* Evaluate spline IK for a given bone */
1842 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan, int index, float ctime)
1843 {
1844         bSplineIKConstraint *ikData= tree->ikData;
1845         float poseHead[3], poseTail[3], poseMat[4][4]; 
1846         float splineVec[3], scaleFac, radius=1.0f;
1847         
1848         /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
1849         where_is_pose_bone(scene, ob, pchan, ctime, 1);
1850         
1851         VECCOPY(poseHead, pchan->pose_head);
1852         VECCOPY(poseTail, pchan->pose_tail);
1853         
1854         /* step 1: determine the positions for the endpoints of the bone */
1855         {
1856                 float vec[4], dir[3], rad;
1857                 float tailBlendFac= 1.0f;
1858                 
1859                 /* determine if the bone should still be affected by SplineIK */
1860                 if (tree->points[index+1] >= 1.0f) {
1861                         /* spline doesn't affect the bone anymore, so done... */
1862                         pchan->flag |= POSE_DONE;
1863                         return;
1864                 }
1865                 else if ((tree->points[index] >= 1.0f) && (tree->points[index+1] < 1.0f)) {
1866                         /* blending factor depends on the amount of the bone still left on the chain */
1867                         tailBlendFac= (1.0f - tree->points[index+1]) / (tree->points[index] - tree->points[index+1]);
1868                 }
1869                 
1870                 /* tail endpoint */
1871                 if ( where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL) ) {
1872                         /* apply curve's object-mode transforms to the position 
1873                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1874                          */
1875                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1876                                 mul_m4_v3(ikData->tar->obmat, vec);
1877                         
1878                         /* convert the position to pose-space, then store it */
1879                         mul_m4_v3(ob->imat, vec);
1880                         interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
1881                         
1882                         /* set the new radius */
1883                         radius= rad;
1884                 }
1885                 
1886                 /* head endpoint */
1887                 if ( where_on_path(ikData->tar, tree->points[index+1], vec, dir, NULL, &rad, NULL) ) {
1888                         /* apply curve's object-mode transforms to the position 
1889                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1890                          */
1891                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1892                                 mul_m4_v3(ikData->tar->obmat, vec);
1893                         
1894                         /* store the position, and convert it to pose space */
1895                         mul_m4_v3(ob->imat, vec);
1896                         VECCOPY(poseHead, vec);
1897                         
1898                         /* set the new radius (it should be the average value) */
1899                         radius = (radius+rad) / 2;
1900                 }
1901         }
1902         
1903         /* step 2: determine the implied transform from these endpoints 
1904          *      - splineVec: the vector direction that the spline applies on the bone
1905          *      - scaleFac: the factor that the bone length is scaled by to get the desired amount
1906          */
1907         sub_v3_v3v3(splineVec, poseTail, poseHead);
1908         scaleFac= len_v3(splineVec) / pchan->bone->length;
1909         
1910         /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis 
1911          *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
1912          */
1913         {
1914                 float dmat[3][3], rmat[3][3], tmat[3][3];
1915                 float raxis[3], rangle;
1916                 
1917                 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
1918                  * orientation-relevant axes, and normalising them
1919                  */
1920                 VECCOPY(rmat[0], pchan->pose_mat[0]);
1921                 VECCOPY(rmat[1], pchan->pose_mat[1]);
1922                 VECCOPY(rmat[2], pchan->pose_mat[2]);
1923                 normalize_m3(rmat);
1924                 
1925                 /* also, normalise the orientation imposed by the bone, now that we've extracted the scale factor */
1926                 normalize_v3(splineVec);
1927                 
1928                 /* calculate smallest axis-angle rotation necessary for getting from the
1929                  * current orientation of the bone, to the spline-imposed direction
1930                  */
1931                 cross_v3_v3v3(raxis, rmat[1], splineVec);
1932                 
1933                 rangle= dot_v3v3(rmat[1], splineVec);
1934                 rangle= acos( MAX2(-1.0f, MIN2(1.0f, rangle)) );
1935                 
1936                 /* multiply the magnitude of the angle by the influence of the constraint to 
1937                  * control the influence of the SplineIK effect 
1938                  */
1939                 rangle *= tree->con->enforce;
1940                 
1941                 /* construct rotation matrix from the axis-angle rotation found above 
1942                  *      - this call takes care to make sure that the axis provided is a unit vector first
1943                  */
1944                 axis_angle_to_mat3(dmat, raxis, rangle);
1945                 
1946                 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
1947                  * while still maintaining roll control from the existing bone animation
1948                  */
1949                 mul_m3_m3m3(tmat, dmat, rmat); // m1, m3, m2
1950                 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
1951                 copy_m4_m3(poseMat, tmat);
1952         }
1953         
1954         /* step 4: set the scaling factors for the axes */
1955         {
1956                 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
1957                 mul_v3_fl(poseMat[1], scaleFac);
1958                 
1959                 /* set the scaling factors of the x and z axes from... */
1960                 switch (ikData->xzScaleMode) {
1961                         case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
1962                         {
1963                                 /* original scales get used */
1964                                 float scale;
1965                                 
1966                                 /* x-axis scale */
1967                                 scale= len_v3(pchan->pose_mat[0]);
1968                                 mul_v3_fl(poseMat[0], scale);
1969                                 /* z-axis scale */
1970                                 scale= len_v3(pchan->pose_mat[2]);
1971                                 mul_v3_fl(poseMat[2], scale);
1972                         }
1973                                 break;
1974                         case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
1975                         {
1976                                 /* 'volume preservation' */
1977                                 float scale;
1978                                 
1979                                 /* calculate volume preservation factor which is 
1980                                  * basically the inverse of the y-scaling factor 
1981                                  */
1982                                 if (fabsf(scaleFac) != 0.0f) {
1983                                         scale= 1.0f / fabsf(scaleFac);
1984                                         
1985                                         /* we need to clamp this within sensible values */
1986                                         // NOTE: these should be fine for now, but should get sanitised in future
1987                                         CLAMP(scale, 0.0001f, 100000.0f);
1988                                 }
1989                                 else
1990                                         scale= 1.0f;
1991                                 
1992                                 /* apply the scaling */
1993                                 mul_v3_fl(poseMat[0], scale);
1994                                 mul_v3_fl(poseMat[2], scale);
1995                         }
1996                                 break;
1997                 }
1998                 
1999                 /* finally, multiply the x and z scaling by the radius of the curve too, 
2000                  * to allow automatic scales to get tweaked still
2001                  */
2002                 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
2003                         mul_v3_fl(poseMat[0], radius);
2004                         mul_v3_fl(poseMat[2], radius);
2005                 }
2006         }
2007         
2008         /* step 5: set the location of the bone in the matrix */
2009         if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
2010                 /* when the 'no-root' option is affected, the chain can retain
2011                  * the shape but be moved elsewhere
2012                  */
2013                 VECCOPY(poseHead, pchan->pose_head);
2014         }
2015         else if (tree->con->enforce < 1.0f) {
2016                 /* when the influence is too low
2017                  *      - blend the positions for the 'root' bone
2018                  *      - stick to the parent for any other
2019                  */
2020                 if (pchan->parent) {
2021                         VECCOPY(poseHead, pchan->pose_head);
2022                 }
2023                 else {
2024                         // FIXME: this introduces popping artifacts when we reach 0.0
2025                         interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
2026                 }
2027         }
2028         VECCOPY(poseMat[3], poseHead);
2029         
2030         /* finally, store the new transform */
2031         copy_m4_m4(pchan->pose_mat, poseMat);
2032         VECCOPY(pchan->pose_head, poseHead);
2033         
2034         /* recalculate tail, as it's now outdated after the head gets adjusted above! */
2035         where_is_pose_bone_tail(pchan);
2036         
2037         /* done! */
2038         pchan->flag |= POSE_DONE;
2039 }
2040
2041 /* Evaluate the chain starting from the nominated bone */
2042 static void splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
2043 {
2044         tSplineIK_Tree *tree;
2045         
2046         /* for each pose-tree, execute it if it is spline, otherwise just free it */
2047         for (tree= pchan_root->iktree.first; tree; tree= pchan_root->iktree.first) {
2048                 /* only evaluate if tagged for Spline IK */
2049                 if (tree->type == CONSTRAINT_TYPE_SPLINEIK) {
2050                         int i;
2051                         
2052                         /* walk over each bone in the chain, calculating the effects of spline IK
2053                          *      - the chain is traversed in the opposite order to storage order (i.e. parent to children)
2054                          *        so that dependencies are correct
2055                          */
2056                         for (i= tree->chainlen-1; i >= 0; i--) {
2057                                 bPoseChannel *pchan= tree->chain[i];
2058                                 splineik_evaluate_bone(tree, scene, ob, pchan, i, ctime);
2059                         }
2060                         
2061                         /* free the tree info specific to SplineIK trees now */
2062                         if (tree->chain) MEM_freeN(tree->chain);
2063                         if (tree->free_points) MEM_freeN(tree->points);
2064                 }
2065                 
2066                 /* free this tree */
2067                 BLI_freelinkN(&pchan_root->iktree, tree);
2068         }
2069 }
2070
2071 /* ********************** THE POSE SOLVER ******************* */
2072
2073 /* loc/rot/size to given mat4 */
2074 void pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2075 {
2076         float smat[3][3];
2077         float rmat[3][3];
2078         float tmat[3][3];
2079         
2080         /* get scaling matrix */
2081         size_to_mat3(smat, pchan->size);
2082         
2083         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2084         if (pchan->rotmode > 0) {
2085                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2086                 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2087         }
2088         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2089                 /* axis-angle - not really that great for 3D-changing orientations */
2090                 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2091         }
2092         else {
2093                 /* quats are normalised before use to eliminate scaling issues */
2094                 float quat[4];
2095                 
2096                 /* NOTE: we now don't normalise the stored values anymore, since this was kindof evil in some cases
2097                  * but if this proves to be too problematic, switch back to the old system of operating directly on 
2098                  * the stored copy
2099                  */
2100                 normalize_qt_qt(quat, pchan->quat);
2101                 quat_to_mat3(rmat, quat);
2102         }
2103         
2104         /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2105         mul_m3_m3m3(tmat, rmat, smat);
2106         copy_m4_m3(chan_mat, tmat);
2107         
2108         /* prevent action channels breaking chains */
2109         /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2110         if ((pchan->bone==NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2111                 VECCOPY(chan_mat[3], pchan->loc);
2112         }
2113 }
2114
2115 /* loc/rot/size to mat4 */
2116 /* used in constraint.c too */
2117 void pchan_calc_mat(bPoseChannel *pchan)
2118 {
2119         /* this is just a wrapper around the copy of this function which calculates the matrix 
2120          * and stores the result in any given channel
2121          */
2122         pchan_to_mat4(pchan, pchan->chan_mat);
2123 }
2124
2125 /* NLA strip modifiers */
2126 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2127 {
2128         bActionModifier *amod;
2129         bActionStrip *strip, *strip2;
2130         float scene_cfra= (float)scene->r.cfra;
2131         int do_modif;
2132
2133         for (strip=armob->nlastrips.first; strip; strip=strip->next) {
2134                 do_modif=0;
2135                 
2136                 if (scene_cfra>=strip->start && scene_cfra<=strip->end)
2137                         do_modif=1;
2138                 
2139                 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2140                         do_modif=1;
2141                         
2142                         /* if there are any other strips active, ignore modifiers for this strip - 
2143                          * 'hold' option should only hold action modifiers if there are 
2144                          * no other active strips */
2145                         for (strip2=strip->next; strip2; strip2=strip2->next) {
2146                                 if (strip2 == strip) continue;
2147                                 
2148                                 if (scene_cfra>=strip2->start && scene_cfra<=strip2->end) {
2149                                         if (!(strip2->flag & ACTSTRIP_MUTE))
2150                                                 do_modif=0;
2151                                 }
2152                         }
2153                         
2154                         /* if there are any later, activated, strips with 'hold' set, they take precedence, 
2155                          * so ignore modifiers for this strip */
2156                         for (strip2=strip->next; strip2; strip2=strip2->next) {
2157                                 if (scene_cfra < strip2->start) continue;
2158                                 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2159                                         do_modif=0;
2160                                 }
2161                         }
2162                 }
2163                 
2164                 if (do_modif) {
2165                         /* temporal solution to prevent 2 strips accumulating */
2166                         if(scene_cfra==strip->end && strip->next && strip->next->start==scene_cfra)
2167                                 continue;
2168                         
2169                         for(amod= strip->modifiers.first; amod; amod= amod->next) {
2170                                 switch (amod->type) {
2171                                 case ACTSTRIP_MOD_DEFORM:
2172                                 {
2173                                         /* validate first */
2174                                         if(amod->ob && amod->ob->type==OB_CURVE && amod->channel[0]) {
2175                                                 
2176                                                 if( strcmp(pchan->name, amod->channel)==0 ) {
2177                                                         float mat4[4][4], mat3[3][3];
2178                                                         
2179                                                         curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2180                                                         copy_m4_m4(mat4, pchan->pose_mat);
2181                                                         mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2182                                                         
2183                                                 }
2184                                         }
2185                                 }
2186                                         break;
2187                                 case ACTSTRIP_MOD_NOISE:        
2188                                 {
2189                                         if( strcmp(pchan->name, amod->channel)==0 ) {
2190                                                 float nor[3], loc[3], ofs;
2191                                                 float eul[3], size[3], eulo[3], sizeo[3];
2192                                                 
2193                                                 /* calculate turbulance */
2194                                                 ofs = amod->turbul / 200.0f;
2195                                                 
2196                                                 /* make a copy of starting conditions */
2197                                                 VECCOPY(loc, pchan->pose_mat[3]);
2198                                                 mat4_to_eul( eul,pchan->pose_mat);
2199                                                 mat4_to_size( size,pchan->pose_mat);
2200                                                 VECCOPY(eulo, eul);
2201                                                 VECCOPY(sizeo, size);
2202                                                 
2203                                                 /* apply noise to each set of channels */
2204                                                 if (amod->channels & 4) {
2205                                                         /* for scaling */
2206                                                         nor[0] = BLI_gNoise(amod->noisesize, size[0]+ofs, size[1], size[2], 0, 0) - ofs;
2207                                                         nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1]+ofs, size[2], 0, 0) - ofs;        
2208                                                         nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2]+ofs, 0, 0) - ofs;
2209                                                         add_v3_v3(size, nor);
2210                                                         
2211                                                         if (sizeo[0] != 0)
2212                                                                 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2213                                                         if (sizeo[1] != 0)
2214                                                                 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2215                                                         if (sizeo[2] != 0)
2216                                                                 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2217                                                 }
2218                                                 if (amod->channels & 2) {
2219                                                         /* for rotation */
2220                                                         nor[0] = BLI_gNoise(amod->noisesize, eul[0]+ofs, eul[1], eul[2], 0, 0) - ofs;
2221                                                         nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1]+ofs, eul[2], 0, 0) - ofs;   
2222                                                         nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2]+ofs, 0, 0) - ofs;
2223                                                         
2224                                                         compatible_eul(nor, eulo);
2225                                                         add_v3_v3(eul, nor);
2226                                                         compatible_eul(eul, eulo);
2227                                                         
2228                                                         loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2229                                                 }
2230                                                 if (amod->channels & 1) {
2231                                                         /* for location */
2232                                                         nor[0] = BLI_gNoise(amod->noisesize, loc[0]+ofs, loc[1], loc[2], 0, 0) - ofs;
2233                                                         nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1]+ofs, loc[2], 0, 0) - ofs;   
2234                                                         nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2]+ofs, 0, 0) - ofs;
2235                                                         
2236                                                         add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2237                                                 }
2238                                         }
2239                                 }
2240                                         break;
2241                                 }
2242                         }
2243                 }
2244         }
2245 }
2246
2247 /* calculate tail of posechannel */
2248 void where_is_pose_bone_tail(bPoseChannel *pchan)
2249 {
2250         float vec[3];
2251         
2252         VECCOPY(vec, pchan->pose_mat[1]);
2253         mul_v3_fl(vec, pchan->bone->length);
2254         add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2255 }
2256
2257 /* The main armature solver, does all constraints excluding IK */
2258 /* pchan is validated, as having bone and parent pointer
2259  * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2260  */
2261 void where_is_pose_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, int do_extra)
2262 {
2263         Bone *bone, *parbone;
2264         bPoseChannel *parchan;
2265         float vec[3];
2266         
2267         /* set up variables for quicker access below */
2268         bone= pchan->bone;
2269         parbone= bone->parent;
2270         parchan= pchan->parent;
2271         
2272         /* this gives a chan_mat with actions (ipos) results */
2273         if(do_extra)    pchan_calc_mat(pchan);
2274         else                    unit_m4(pchan->chan_mat);
2275
2276         /* construct the posemat based on PoseChannels, that we do before applying constraints */
2277         /* pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2278         
2279         if(parchan) {
2280                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
2281                 
2282                 /* bone transform itself */
2283                 copy_m4_m3(offs_bone, bone->bone_mat);
2284                 
2285                 /* The bone's root offset (is in the parent's coordinate system) */
2286                 VECCOPY(offs_bone[3], bone->head);
2287                 
2288                 /* Get the length translation of parent (length along y axis) */
2289                 offs_bone[3][1]+= parbone->length;
2290                 
2291                 /* Compose the matrix for this bone  */
2292                 if((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) { // uses restposition rotation, but actual position
2293                         float tmat[4][4];
2294                         /* the rotation of the parent restposition */
2295                         copy_m4_m4(tmat, parbone->arm_mat);
2296                         mul_serie_m4(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2297                 }
2298                 else if(bone->flag & BONE_HINGE) {      // same as above but apply parent scale
2299                         float tmat[4][4];
2300
2301                         /* apply the parent matrix scale */
2302                         float tsmat[4][4], tscale[3];
2303
2304                         /* the rotation of the parent restposition */
2305                         copy_m4_m4(tmat, parbone->arm_mat);
2306
2307                         /* extract the scale of the parent matrix */
2308                         mat4_to_size(tscale, parchan->pose_mat);
2309                         size_to_mat4(tsmat, tscale);
2310                         mul_m4_m4m4(tmat, tmat, tsmat);
2311
2312                         mul_serie_m4(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2313                 }
2314                 else if(bone->flag & BONE_NO_SCALE) {
2315                         float orthmat[4][4];
2316                         
2317                         /* do transform, with an ortho-parent matrix */
2318                         copy_m4_m4(orthmat, parchan->pose_mat);
2319                         normalize_m4(orthmat);
2320                         mul_serie_m4(pchan->pose_mat, orthmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2321                 }
2322                 else
2323                         mul_serie_m4(pchan->pose_mat, parchan->pose_mat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2324                 
2325                 /* in these cases we need to compute location separately */
2326                 if(bone->flag & (BONE_HINGE|BONE_NO_SCALE|BONE_NO_LOCAL_LOCATION)) {
2327                         float bone_loc[3], chan_loc[3];
2328
2329                         mul_v3_m4v3(bone_loc, parchan->pose_mat, offs_bone[3]);
2330                         copy_v3_v3(chan_loc, pchan->chan_mat[3]);
2331
2332                         /* no local location is not transformed by bone matrix */
2333                         if(!(bone->flag & BONE_NO_LOCAL_LOCATION))
2334                                 mul_mat3_m4_v3(offs_bone, chan_loc);
2335
2336                         /* for hinge we use armature instead of pose mat */
2337                         if(bone->flag & BONE_HINGE) mul_mat3_m4_v3(parbone->arm_mat, chan_loc);
2338                         else mul_mat3_m4_v3(parchan->pose_mat, chan_loc);
2339
2340                         add_v3_v3v3(pchan->pose_mat[3], bone_loc, chan_loc);
2341                 }
2342         }
2343         else {
2344                 mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
2345
2346                 /* optional location without arm_mat rotation */
2347                 if(bone->flag & BONE_NO_LOCAL_LOCATION)
2348                         add_v3_v3v3(pchan->pose_mat[3], bone->arm_mat[3], pchan->chan_mat[3]);
2349                 
2350                 /* only rootbones get the cyclic offset (unless user doesn't want that) */
2351                 if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2352                         add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2353         }
2354         
2355         if(do_extra) {
2356                 /* do NLA strip modifiers - i.e. curve follow */
2357                 do_strip_modifiers(scene, ob, bone, pchan);
2358                 
2359                 /* Do constraints */
2360                 if (pchan->constraints.first) {
2361                         bConstraintOb *cob;
2362
2363                         /* make a copy of location of PoseChannel for later */
2364                         VECCOPY(vec, pchan->pose_mat[3]);
2365
2366                         /* prepare PoseChannel for Constraint solving
2367                          * - makes a copy of matrix, and creates temporary struct to use
2368                          */
2369                         cob= constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2370
2371                         /* Solve PoseChannel's Constraints */
2372                         solve_constraints(&pchan->constraints, cob, ctime);     // ctime doesnt alter objects
2373
2374                         /* cleanup after Constraint Solving
2375                          * - applies matrix back to pchan, and frees temporary struct used
2376                          */
2377                         constraints_clear_evalob(cob);
2378
2379                         /* prevent constraints breaking a chain */
2380                         if(pchan->bone->flag & BONE_CONNECTED) {
2381                                 VECCOPY(pchan->pose_mat[3], vec);
2382                         }
2383                 }
2384         }
2385         
2386         /* calculate head */
2387         VECCOPY(pchan->pose_head, pchan->pose_mat[3]);
2388         /* calculate tail */
2389         where_is_pose_bone_tail(pchan);
2390 }
2391
2392 /* This only reads anim data from channels, and writes to channels */
2393 /* This is the only function adding poses */
2394 void where_is_pose (Scene *scene, Object *ob)
2395 {
2396         bArmature *arm;
2397         Bone *bone;
2398         bPoseChannel *pchan;
2399         float imat[4][4];
2400         float ctime;
2401         
2402         if(ob->type!=OB_ARMATURE) return;
2403         arm = ob->data;
2404         
2405         if(ELEM(NULL, arm, scene)) return;
2406         if((ob->pose==NULL) || (ob->pose->flag & POSE_RECALC)) 
2407                 armature_rebuild_pose(ob, arm);
2408            
2409         ctime= bsystem_time(scene, ob, (float)scene->r.cfra, 0.0);      /* not accurate... */
2410         
2411         /* In editmode or restposition we read the data from the bones */
2412         if(arm->edbo || (arm->flag & ARM_RESTPOS)) {
2413                 
2414                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2415                         bone= pchan->bone;
2416                         if(bone) {
2417                                 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2418                                 VECCOPY(pchan->pose_head, bone->arm_head);
2419                                 VECCOPY(pchan->pose_tail, bone->arm_tail);
2420                         }
2421                 }
2422         }
2423         else {
2424                 invert_m4_m4(ob->imat, ob->obmat);      // imat is needed 
2425                 
2426                 /* 1. clear flags */
2427                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2428                         pchan->flag &= ~(POSE_DONE|POSE_CHAIN|POSE_IKTREE|POSE_IKSPLINE);
2429                 }
2430                 
2431                 /* 2a. construct the IK tree (standard IK) */
2432                 BIK_initialize_tree(scene, ob, ctime);
2433                 
2434                 /* 2b. construct the Spline IK trees 
2435                  *  - this is not integrated as an IK plugin, since it should be able
2436                  *        to function in conjunction with standard IK
2437                  */
2438                 splineik_init_tree(scene, ob, ctime);
2439                 
2440                 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2441                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2442                         /* 4a. if we find an IK root, we handle it separated */
2443                         if(pchan->flag & POSE_IKTREE) {
2444                                 BIK_execute_tree(scene, ob, pchan, ctime);
2445                         }
2446                         /* 4b. if we find a Spline IK root, we handle it separated too */
2447                         else if(pchan->flag & POSE_IKSPLINE) {
2448                                 splineik_execute_tree(scene, ob, pchan, ctime);
2449                         }
2450                         /* 5. otherwise just call the normal solver */
2451                         else if(!(pchan->flag & POSE_DONE)) {
2452                                 where_is_pose_bone(scene, ob, pchan, ctime, 1);
2453                         }
2454                 }
2455                 /* 6. release the IK tree */
2456                 BIK_release_tree(scene, ob, ctime);
2457         }
2458                 
2459         /* calculating deform matrices */
2460         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2461                 if(pchan->bone) {
2462                         invert_m4_m4(imat, pchan->bone->arm_mat);
2463                         mul_m4_m4m4(pchan->chan_mat, imat, pchan->pose_mat);
2464                 }
2465         }
2466 }
2467
2468 /* Jason was here */
2469 /* Returns total selected vgroups */
2470 int get_selected_defgroups(Object *ob, char *dg_selection, int defbase_len)
2471 {
2472         bDeformGroup *defgroup;
2473         unsigned int i;
2474         Object *armob= object_pose_armature_get(ob);
2475         int dg_flags_sel_tot= 0;
2476
2477         if(armob) {
2478                 bPose *pose= armob->pose;
2479                 for (i= 0, defgroup= ob->defbase.first; i < defbase_len && defgroup; defgroup = defgroup->next, i++) {
2480                         bPoseChannel *pchan= get_pose_channel(pose, defgroup->name);
2481                         if(pchan && (pchan->bone->flag & BONE_SELECTED)) {
2482                                 dg_selection[i]= TRUE;
2483                                 dg_flags_sel_tot++;
2484                         }
2485                         else {
2486                                 dg_selection[i]= FALSE;
2487                         }
2488                 }
2489         }
2490         else {
2491                 memset(dg_selection, FALSE, sizeof(char) * defbase_len);
2492         }
2493
2494         return dg_flags_sel_tot;
2495 }