initial cleanup for weight paint branch
[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                         pchanw.path= NULL;
1487                         
1488                         /* this is freed so copy a copy, else undo crashes */
1489                         if(pchanw.prop) {
1490                                 pchanw.prop= IDP_CopyProperty(pchanw.prop);
1491
1492                                 /* use the values from the the existing props */
1493                                 if(pchan->prop) {
1494                                         IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1495                                 }
1496                         }
1497
1498                         /* constraints - proxy constraints are flushed... local ones are added after 
1499                          *      1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1500                          *      2. copy proxy-pchan's constraints on-to new
1501                          *      3. add extracted local constraints back on top 
1502                          *
1503                          *  note for copy_constraints: when copying constraints, disable 'do_extern' otherwise we get the libs direct linked in this blend.
1504                          */
1505                         extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
1506                         copy_constraints(&pchanw.constraints, &pchanp->constraints, FALSE);
1507                         BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1508                         
1509                         /* constraints - set target ob pointer to own object */
1510                         for (con= pchanw.constraints.first; con; con= con->next) {
1511                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1512                                 ListBase targets = {NULL, NULL};
1513                                 bConstraintTarget *ct;
1514                                 
1515                                 if (cti && cti->get_constraint_targets) {
1516                                         cti->get_constraint_targets(con, &targets);
1517                                         
1518                                         for (ct= targets.first; ct; ct= ct->next) {
1519                                                 if (ct->tar == from)
1520                                                         ct->tar = ob;
1521                                         }
1522                                         
1523                                         if (cti->flush_constraint_targets)
1524                                                 cti->flush_constraint_targets(con, &targets, 0);
1525                                 }
1526                         }
1527                         
1528                         /* free stuff from current channel */
1529                         free_pose_channel(pchan);
1530                         
1531                         /* the final copy */
1532                         *pchan= pchanw;
1533                 }
1534                 else {
1535                         /* always copy custom shape */
1536                         pchan->custom= pchanp->custom;
1537                         pchan->custom_tx= pchanp->custom_tx;
1538
1539                         /* ID-Property Syncing */
1540                         {
1541                                 IDProperty *prop_orig= pchan->prop;
1542                                 if(pchanp->prop) {
1543                                         pchan->prop= IDP_CopyProperty(pchanp->prop);
1544                                         if(prop_orig) {
1545                                                 /* copy existing values across when types match */
1546                                                 IDP_SyncGroupValues(pchan->prop, prop_orig);
1547                                         }
1548                                 }
1549                                 else {
1550                                         pchan->prop= NULL;
1551                                 }
1552                                 if (prop_orig) {
1553                                         IDP_FreeProperty(prop_orig);
1554                                         MEM_freeN(prop_orig);
1555                                 }
1556                         }
1557                 }
1558         }
1559 }
1560
1561 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1562 {
1563         bPoseChannel *pchan = verify_pose_channel (pose, bone->name);   // verify checks and/or adds
1564
1565         pchan->bone= bone;
1566         pchan->parent= parchan;
1567         
1568         counter++;
1569         
1570         for(bone= bone->childbase.first; bone; bone= bone->next) {
1571                 counter= rebuild_pose_bone(pose, bone, pchan, counter);
1572                 /* for quick detecting of next bone in chain, only b-bone uses it now */
1573                 if(bone->flag & BONE_CONNECTED)
1574                         pchan->child= get_pose_channel(pose, bone->name);
1575         }
1576         
1577         return counter;
1578 }
1579
1580 /* only after leave editmode, duplicating, validating older files, library syncing */
1581 /* NOTE: pose->flag is set for it */
1582 void armature_rebuild_pose(Object *ob, bArmature *arm)
1583 {
1584         Bone *bone;
1585         bPose *pose;
1586         bPoseChannel *pchan, *next;
1587         int counter=0;
1588                 
1589         /* only done here */
1590         if(ob->pose==NULL) {
1591                 /* create new pose */
1592                 ob->pose= MEM_callocN(sizeof(bPose), "new pose");
1593                 
1594                 /* set default settings for animviz */
1595                 animviz_settings_init(&ob->pose->avs);
1596         }
1597         pose= ob->pose;
1598         
1599         /* clear */
1600         for(pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1601                 pchan->bone= NULL;
1602                 pchan->child= NULL;
1603         }
1604         
1605         /* first step, check if all channels are there */
1606         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1607                 counter= rebuild_pose_bone(pose, bone, NULL, counter);
1608         }
1609
1610         /* and a check for garbage */
1611         for(pchan= pose->chanbase.first; pchan; pchan= next) {
1612                 next= pchan->next;
1613                 if(pchan->bone==NULL) {
1614                         free_pose_channel(pchan);
1615                         free_pose_channels_hash(pose);
1616                         BLI_freelinkN(&pose->chanbase, pchan);
1617                 }
1618         }
1619         // printf("rebuild pose %s, %d bones\n", ob->id.name, counter);
1620         
1621         /* synchronize protected layers with proxy */
1622         if(ob->proxy) {
1623                 object_copy_proxy_drivers(ob, ob->proxy);
1624                 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1625         }
1626         
1627         update_pose_constraint_flags(ob->pose); // for IK detection for example
1628         
1629         /* the sorting */
1630         if(counter>1)
1631                 DAG_pose_sort(ob);
1632         
1633         ob->pose->flag &= ~POSE_RECALC;
1634         ob->pose->flag |= POSE_WAS_REBUILT;
1635
1636         make_pose_channels_hash(ob->pose);
1637 }
1638
1639
1640 /* ********************** SPLINE IK SOLVER ******************* */
1641
1642 /* Temporary evaluation tree data used for Spline IK */
1643 typedef struct tSplineIK_Tree {
1644         struct tSplineIK_Tree *next, *prev;
1645         
1646         int     type;                                   /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
1647         
1648         short free_points;                              /* free the point positions array */
1649         short chainlen;                                 /* number of bones in the chain */
1650         
1651         float *points;                                  /* parametric positions for the joints along the curve */
1652         bPoseChannel **chain;                   /* chain of bones to affect using Spline IK (ordered from the tip) */
1653         
1654         bPoseChannel *root;                             /* bone that is the root node of the chain */
1655         
1656         bConstraint *con;                               /* constraint for this chain */
1657         bSplineIKConstraint *ikData;    /* constraint settings for this chain */
1658 } tSplineIK_Tree;
1659
1660 /* ----------- */
1661
1662 /* Tag the bones in the chain formed by the given bone for IK */
1663 static void splineik_init_tree_from_pchan(Scene *scene, Object *UNUSED(ob), bPoseChannel *pchan_tip)
1664 {
1665         bPoseChannel *pchan, *pchanRoot=NULL;
1666         bPoseChannel *pchanChain[255];
1667         bConstraint *con = NULL;
1668         bSplineIKConstraint *ikData = NULL;
1669         float boneLengths[255], *jointPoints;
1670         float totLength = 0.0f;
1671         short free_joints = 0;
1672         int segcount = 0;
1673         
1674         /* find the SplineIK constraint */
1675         for (con= pchan_tip->constraints.first; con; con= con->next) {
1676                 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
1677                         ikData= con->data;
1678                         
1679                         /* target can only be curve */
1680                         if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))  
1681                                 continue;
1682                         /* skip if disabled */
1683                         if ( (con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE|CONSTRAINT_OFF)) )
1684                                 continue;
1685                         
1686                         /* otherwise, constraint is ok... */
1687                         break;
1688                 }
1689         }
1690         if (con == NULL)
1691                 return;
1692                 
1693         /* make sure that the constraint targets are ok 
1694          *      - this is a workaround for a depsgraph bug...
1695          */
1696         if (ikData->tar) {
1697                 Curve *cu= ikData->tar->data;
1698                 
1699                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1700                  *              currently for paths to work it needs to go through the bevlist/displist system (ton) 
1701                  */
1702                 
1703                 /* only happens on reload file, but violates depsgraph still... fix! */
1704                 if ((cu->path==NULL) || (cu->path->data==NULL))
1705                         makeDispListCurveTypes(scene, ikData->tar, 0);
1706         }
1707         
1708         /* find the root bone and the chain of bones from the root to the tip 
1709          * NOTE: this assumes that the bones are connected, but that may not be true...
1710          */
1711         for (pchan= pchan_tip; pchan && (segcount < ikData->chainlen); pchan= pchan->parent, segcount++) {
1712                 /* store this segment in the chain */
1713                 pchanChain[segcount]= pchan;
1714                 
1715                 /* if performing rebinding, calculate the length of the bone */
1716                 boneLengths[segcount]= pchan->bone->length;
1717                 totLength += boneLengths[segcount];
1718         }
1719         
1720         if (segcount == 0)
1721                 return;
1722         else
1723                 pchanRoot= pchanChain[segcount-1];
1724         
1725         /* perform binding step if required */
1726         if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
1727                 float segmentLen= (1.0f / (float)segcount);
1728                 int i;
1729                 
1730                 /* setup new empty array for the points list */
1731                 if (ikData->points) 
1732                         MEM_freeN(ikData->points);
1733                 ikData->numpoints= ikData->chainlen+1; 
1734                 ikData->points= MEM_callocN(sizeof(float)*ikData->numpoints, "Spline IK Binding");
1735                 
1736                 /* bind 'tip' of chain (i.e. first joint = tip of bone with the Spline IK Constraint) */
1737                 ikData->points[0] = 1.0f;
1738                 
1739                 /* perform binding of the joints to parametric positions along the curve based 
1740                  * proportion of the total length that each bone occupies
1741                  */
1742                 for (i = 0; i < segcount; i++) {
1743                         /* 'head' joints, travelling towards the root of the chain
1744                          *      - 2 methods; the one chosen depends on whether we've got usable lengths
1745                          */
1746                         if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
1747                                 /* 1) equi-spaced joints */
1748                                 ikData->points[i+1]= ikData->points[i] - segmentLen;
1749                         }
1750                         else {
1751                                 /*      2) to find this point on the curve, we take a step from the previous joint
1752                                  *        a distance given by the proportion that this bone takes
1753                                  */
1754                                 ikData->points[i+1]= ikData->points[i] - (boneLengths[i] / totLength);
1755                         }
1756                 }
1757                 
1758                 /* spline has now been bound */
1759                 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
1760         }
1761         
1762         /* apply corrections for sensitivity to scaling on a copy of the bind points,
1763          * since it's easier to determine the positions of all the joints beforehand this way
1764          */
1765         if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
1766                 Curve *cu= (Curve *)ikData->tar->data;
1767                 float splineLen, maxScale;
1768                 int i;
1769                 
1770                 /* make a copy of the points array, that we'll store in the tree 
1771                  *      - although we could just multiply the points on the fly, this approach means that
1772                  *        we can introduce per-segment stretchiness later if it is necessary
1773                  */
1774                 jointPoints= MEM_dupallocN(ikData->points);
1775                 free_joints= 1;
1776                 
1777                 /* get the current length of the curve */
1778                 // NOTE: this is assumed to be correct even after the curve was resized
1779                 splineLen= cu->path->totdist;
1780                 
1781                 /* calculate the scale factor to multiply all the path values by so that the 
1782                  * bone chain retains its current length, such that
1783                  *      maxScale * splineLen = totLength
1784                  */
1785                 maxScale = totLength / splineLen;
1786                 
1787                 /* apply scaling correction to all of the temporary points */
1788                 // TODO: this is really not adequate enough on really short chains
1789                 for (i = 0; i < segcount; i++)
1790                         jointPoints[i] *= maxScale;
1791         }
1792         else {
1793                 /* just use the existing points array */
1794                 jointPoints= ikData->points;
1795                 free_joints= 0;
1796         }
1797         
1798         /* make a new Spline-IK chain, and store it in the IK chains */
1799         // TODO: we should check if there is already an IK chain on this, since that would take presidence...
1800         {
1801                 /* make new tree */
1802                 tSplineIK_Tree *tree= MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
1803                 tree->type= CONSTRAINT_TYPE_SPLINEIK;
1804                 
1805                 tree->chainlen= segcount;
1806                 
1807                 /* copy over the array of links to bones in the chain (from tip to root) */
1808                 tree->chain= MEM_callocN(sizeof(bPoseChannel*)*segcount, "SplineIK Chain");
1809                 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel*)*segcount);
1810                 
1811                 /* store reference to joint position array */
1812                 tree->points= jointPoints;
1813                 tree->free_points= free_joints;
1814                 
1815                 /* store references to different parts of the chain */
1816                 tree->root= pchanRoot;
1817                 tree->con= con;
1818                 tree->ikData= ikData;
1819                 
1820                 /* AND! link the tree to the root */
1821                 BLI_addtail(&pchanRoot->iktree, tree);
1822         }
1823         
1824         /* mark root channel having an IK tree */
1825         pchanRoot->flag |= POSE_IKSPLINE;
1826 }
1827
1828 /* Tag which bones are members of Spline IK chains */
1829 static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime))
1830 {
1831         bPoseChannel *pchan;
1832         
1833         /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
1834         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1835                 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
1836                         splineik_init_tree_from_pchan(scene, ob, pchan);
1837         }
1838 }
1839
1840 /* ----------- */
1841
1842 /* Evaluate spline IK for a given bone */
1843 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan, int index, float ctime)
1844 {
1845         bSplineIKConstraint *ikData= tree->ikData;
1846         float poseHead[3], poseTail[3], poseMat[4][4]; 
1847         float splineVec[3], scaleFac, radius=1.0f;
1848         
1849         /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
1850         where_is_pose_bone(scene, ob, pchan, ctime, 1);
1851         
1852         VECCOPY(poseHead, pchan->pose_head);
1853         VECCOPY(poseTail, pchan->pose_tail);
1854         
1855         /* step 1: determine the positions for the endpoints of the bone */
1856         {
1857                 float vec[4], dir[3], rad;
1858                 float tailBlendFac= 1.0f;
1859                 
1860                 /* determine if the bone should still be affected by SplineIK */
1861                 if (tree->points[index+1] >= 1.0f) {
1862                         /* spline doesn't affect the bone anymore, so done... */
1863                         pchan->flag |= POSE_DONE;
1864                         return;
1865                 }
1866                 else if ((tree->points[index] >= 1.0f) && (tree->points[index+1] < 1.0f)) {
1867                         /* blending factor depends on the amount of the bone still left on the chain */
1868                         tailBlendFac= (1.0f - tree->points[index+1]) / (tree->points[index] - tree->points[index+1]);
1869                 }
1870                 
1871                 /* tail endpoint */
1872                 if ( where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL) ) {
1873                         /* apply curve's object-mode transforms to the position 
1874                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1875                          */
1876                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1877                                 mul_m4_v3(ikData->tar->obmat, vec);
1878                         
1879                         /* convert the position to pose-space, then store it */
1880                         mul_m4_v3(ob->imat, vec);
1881                         interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
1882                         
1883                         /* set the new radius */
1884                         radius= rad;
1885                 }
1886                 
1887                 /* head endpoint */
1888                 if ( where_on_path(ikData->tar, tree->points[index+1], vec, dir, NULL, &rad, NULL) ) {
1889                         /* apply curve's object-mode transforms to the position 
1890                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1891                          */
1892                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1893                                 mul_m4_v3(ikData->tar->obmat, vec);
1894                         
1895                         /* store the position, and convert it to pose space */
1896                         mul_m4_v3(ob->imat, vec);
1897                         VECCOPY(poseHead, vec);
1898                         
1899                         /* set the new radius (it should be the average value) */
1900                         radius = (radius+rad) / 2;
1901                 }
1902         }
1903         
1904         /* step 2: determine the implied transform from these endpoints 
1905          *      - splineVec: the vector direction that the spline applies on the bone
1906          *      - scaleFac: the factor that the bone length is scaled by to get the desired amount
1907          */
1908         sub_v3_v3v3(splineVec, poseTail, poseHead);
1909         scaleFac= len_v3(splineVec) / pchan->bone->length;
1910         
1911         /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis 
1912          *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
1913          */
1914         {
1915                 float dmat[3][3], rmat[3][3], tmat[3][3];
1916                 float raxis[3], rangle;
1917                 
1918                 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
1919                  * orientation-relevant axes, and normalising them
1920                  */
1921                 VECCOPY(rmat[0], pchan->pose_mat[0]);
1922                 VECCOPY(rmat[1], pchan->pose_mat[1]);
1923                 VECCOPY(rmat[2], pchan->pose_mat[2]);
1924                 normalize_m3(rmat);
1925                 
1926                 /* also, normalise the orientation imposed by the bone, now that we've extracted the scale factor */
1927                 normalize_v3(splineVec);
1928                 
1929                 /* calculate smallest axis-angle rotation necessary for getting from the
1930                  * current orientation of the bone, to the spline-imposed direction
1931                  */
1932                 cross_v3_v3v3(raxis, rmat[1], splineVec);
1933                 
1934                 rangle= dot_v3v3(rmat[1], splineVec);
1935                 rangle= acos( MAX2(-1.0f, MIN2(1.0f, rangle)) );
1936                 
1937                 /* multiply the magnitude of the angle by the influence of the constraint to 
1938                  * control the influence of the SplineIK effect 
1939                  */
1940                 rangle *= tree->con->enforce;
1941                 
1942                 /* construct rotation matrix from the axis-angle rotation found above 
1943                  *      - this call takes care to make sure that the axis provided is a unit vector first
1944                  */
1945                 axis_angle_to_mat3(dmat, raxis, rangle);
1946                 
1947                 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
1948                  * while still maintaining roll control from the existing bone animation
1949                  */
1950                 mul_m3_m3m3(tmat, dmat, rmat); // m1, m3, m2
1951                 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
1952                 copy_m4_m3(poseMat, tmat);
1953         }
1954         
1955         /* step 4: set the scaling factors for the axes */
1956         {
1957                 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
1958                 mul_v3_fl(poseMat[1], scaleFac);
1959                 
1960                 /* set the scaling factors of the x and z axes from... */
1961                 switch (ikData->xzScaleMode) {
1962                         case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
1963                         {
1964                                 /* original scales get used */
1965                                 float scale;
1966                                 
1967                                 /* x-axis scale */
1968                                 scale= len_v3(pchan->pose_mat[0]);
1969                                 mul_v3_fl(poseMat[0], scale);
1970                                 /* z-axis scale */
1971                                 scale= len_v3(pchan->pose_mat[2]);
1972                                 mul_v3_fl(poseMat[2], scale);
1973                         }
1974                                 break;
1975                         case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
1976                         {
1977                                 /* 'volume preservation' */
1978                                 float scale;
1979                                 
1980                                 /* calculate volume preservation factor which is 
1981                                  * basically the inverse of the y-scaling factor 
1982                                  */
1983                                 if (fabsf(scaleFac) != 0.0f) {
1984                                         scale= 1.0f / fabsf(scaleFac);
1985                                         
1986                                         /* we need to clamp this within sensible values */
1987                                         // NOTE: these should be fine for now, but should get sanitised in future
1988                                         CLAMP(scale, 0.0001f, 100000.0f);
1989                                 }
1990                                 else
1991                                         scale= 1.0f;
1992                                 
1993                                 /* apply the scaling */
1994                                 mul_v3_fl(poseMat[0], scale);
1995                                 mul_v3_fl(poseMat[2], scale);
1996                         }
1997                                 break;
1998                 }
1999                 
2000                 /* finally, multiply the x and z scaling by the radius of the curve too, 
2001                  * to allow automatic scales to get tweaked still
2002                  */
2003                 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
2004                         mul_v3_fl(poseMat[0], radius);
2005                         mul_v3_fl(poseMat[2], radius);
2006                 }
2007         }
2008         
2009         /* step 5: set the location of the bone in the matrix */
2010         if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
2011                 /* when the 'no-root' option is affected, the chain can retain
2012                  * the shape but be moved elsewhere
2013                  */
2014                 VECCOPY(poseHead, pchan->pose_head);
2015         }
2016         else if (tree->con->enforce < 1.0f) {
2017                 /* when the influence is too low
2018                  *      - blend the positions for the 'root' bone
2019                  *      - stick to the parent for any other
2020                  */
2021                 if (pchan->parent) {
2022                         VECCOPY(poseHead, pchan->pose_head);
2023                 }
2024                 else {
2025                         // FIXME: this introduces popping artifacts when we reach 0.0
2026                         interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
2027                 }
2028         }
2029         VECCOPY(poseMat[3], poseHead);
2030         
2031         /* finally, store the new transform */
2032         copy_m4_m4(pchan->pose_mat, poseMat);
2033         VECCOPY(pchan->pose_head, poseHead);
2034         
2035         /* recalculate tail, as it's now outdated after the head gets adjusted above! */
2036         where_is_pose_bone_tail(pchan);
2037         
2038         /* done! */
2039         pchan->flag |= POSE_DONE;
2040 }
2041
2042 /* Evaluate the chain starting from the nominated bone */
2043 static void splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
2044 {
2045         tSplineIK_Tree *tree;
2046         
2047         /* for each pose-tree, execute it if it is spline, otherwise just free it */
2048         for (tree= pchan_root->iktree.first; tree; tree= pchan_root->iktree.first) {
2049                 /* only evaluate if tagged for Spline IK */
2050                 if (tree->type == CONSTRAINT_TYPE_SPLINEIK) {
2051                         int i;
2052                         
2053                         /* walk over each bone in the chain, calculating the effects of spline IK
2054                          *      - the chain is traversed in the opposite order to storage order (i.e. parent to children)
2055                          *        so that dependencies are correct
2056                          */
2057                         for (i= tree->chainlen-1; i >= 0; i--) {
2058                                 bPoseChannel *pchan= tree->chain[i];
2059                                 splineik_evaluate_bone(tree, scene, ob, pchan, i, ctime);
2060                         }
2061                         
2062                         /* free the tree info specific to SplineIK trees now */
2063                         if (tree->chain) MEM_freeN(tree->chain);
2064                         if (tree->free_points) MEM_freeN(tree->points);
2065                 }
2066                 
2067                 /* free this tree */
2068                 BLI_freelinkN(&pchan_root->iktree, tree);
2069         }
2070 }
2071
2072 /* ********************** THE POSE SOLVER ******************* */
2073
2074 /* loc/rot/size to given mat4 */
2075 void pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2076 {
2077         float smat[3][3];
2078         float rmat[3][3];
2079         float tmat[3][3];
2080         
2081         /* get scaling matrix */
2082         size_to_mat3(smat, pchan->size);
2083         
2084         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2085         if (pchan->rotmode > 0) {
2086                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2087                 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2088         }
2089         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2090                 /* axis-angle - not really that great for 3D-changing orientations */
2091                 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2092         }
2093         else {
2094                 /* quats are normalised before use to eliminate scaling issues */
2095                 float quat[4];
2096                 
2097                 /* NOTE: we now don't normalise the stored values anymore, since this was kindof evil in some cases
2098                  * but if this proves to be too problematic, switch back to the old system of operating directly on 
2099                  * the stored copy
2100                  */
2101                 normalize_qt_qt(quat, pchan->quat);
2102                 quat_to_mat3(rmat, quat);
2103         }
2104         
2105         /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2106         mul_m3_m3m3(tmat, rmat, smat);
2107         copy_m4_m3(chan_mat, tmat);
2108         
2109         /* prevent action channels breaking chains */
2110         /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2111         if ((pchan->bone==NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2112                 VECCOPY(chan_mat[3], pchan->loc);
2113         }
2114 }
2115
2116 /* loc/rot/size to mat4 */
2117 /* used in constraint.c too */
2118 void pchan_calc_mat(bPoseChannel *pchan)
2119 {
2120         /* this is just a wrapper around the copy of this function which calculates the matrix 
2121          * and stores the result in any given channel
2122          */
2123         pchan_to_mat4(pchan, pchan->chan_mat);
2124 }
2125
2126 /* NLA strip modifiers */
2127 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2128 {
2129         bActionModifier *amod;
2130         bActionStrip *strip, *strip2;
2131         float scene_cfra= (float)scene->r.cfra;
2132         int do_modif;
2133
2134         for (strip=armob->nlastrips.first; strip; strip=strip->next) {
2135                 do_modif=0;
2136                 
2137                 if (scene_cfra>=strip->start && scene_cfra<=strip->end)
2138                         do_modif=1;
2139                 
2140                 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2141                         do_modif=1;
2142                         
2143                         /* if there are any other strips active, ignore modifiers for this strip - 
2144                          * 'hold' option should only hold action modifiers if there are 
2145                          * no other active strips */
2146                         for (strip2=strip->next; strip2; strip2=strip2->next) {
2147                                 if (strip2 == strip) continue;
2148                                 
2149                                 if (scene_cfra>=strip2->start && scene_cfra<=strip2->end) {
2150                                         if (!(strip2->flag & ACTSTRIP_MUTE))
2151                                                 do_modif=0;
2152                                 }
2153                         }
2154                         
2155                         /* if there are any later, activated, strips with 'hold' set, they take precedence, 
2156                          * so ignore modifiers for this strip */
2157                         for (strip2=strip->next; strip2; strip2=strip2->next) {
2158                                 if (scene_cfra < strip2->start) continue;
2159                                 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2160                                         do_modif=0;
2161                                 }
2162                         }
2163                 }
2164                 
2165                 if (do_modif) {
2166                         /* temporal solution to prevent 2 strips accumulating */
2167                         if(scene_cfra==strip->end && strip->next && strip->next->start==scene_cfra)
2168                                 continue;
2169                         
2170                         for(amod= strip->modifiers.first; amod; amod= amod->next) {
2171                                 switch (amod->type) {
2172                                 case ACTSTRIP_MOD_DEFORM:
2173                                 {
2174                                         /* validate first */
2175                                         if(amod->ob && amod->ob->type==OB_CURVE && amod->channel[0]) {
2176                                                 
2177                                                 if( strcmp(pchan->name, amod->channel)==0 ) {
2178                                                         float mat4[4][4], mat3[3][3];
2179                                                         
2180                                                         curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2181                                                         copy_m4_m4(mat4, pchan->pose_mat);
2182                                                         mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2183                                                         
2184                                                 }
2185                                         }
2186                                 }
2187                                         break;
2188                                 case ACTSTRIP_MOD_NOISE:        
2189                                 {
2190                                         if( strcmp(pchan->name, amod->channel)==0 ) {
2191                                                 float nor[3], loc[3], ofs;
2192                                                 float eul[3], size[3], eulo[3], sizeo[3];
2193                                                 
2194                                                 /* calculate turbulance */
2195                                                 ofs = amod->turbul / 200.0f;
2196                                                 
2197                                                 /* make a copy of starting conditions */
2198                                                 VECCOPY(loc, pchan->pose_mat[3]);
2199                                                 mat4_to_eul( eul,pchan->pose_mat);
2200                                                 mat4_to_size( size,pchan->pose_mat);
2201                                                 VECCOPY(eulo, eul);
2202                                                 VECCOPY(sizeo, size);
2203                                                 
2204                                                 /* apply noise to each set of channels */
2205                                                 if (amod->channels & 4) {
2206                                                         /* for scaling */
2207                                                         nor[0] = BLI_gNoise(amod->noisesize, size[0]+ofs, size[1], size[2], 0, 0) - ofs;
2208                                                         nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1]+ofs, size[2], 0, 0) - ofs;        
2209                                                         nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2]+ofs, 0, 0) - ofs;
2210                                                         add_v3_v3(size, nor);
2211                                                         
2212                                                         if (sizeo[0] != 0)
2213                                                                 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2214                                                         if (sizeo[1] != 0)
2215                                                                 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2216                                                         if (sizeo[2] != 0)
2217                                                                 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2218                                                 }
2219                                                 if (amod->channels & 2) {
2220                                                         /* for rotation */
2221                                                         nor[0] = BLI_gNoise(amod->noisesize, eul[0]+ofs, eul[1], eul[2], 0, 0) - ofs;
2222                                                         nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1]+ofs, eul[2], 0, 0) - ofs;   
2223                                                         nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2]+ofs, 0, 0) - ofs;
2224                                                         
2225                                                         compatible_eul(nor, eulo);
2226                                                         add_v3_v3(eul, nor);
2227                                                         compatible_eul(eul, eulo);
2228                                                         
2229                                                         loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2230                                                 }
2231                                                 if (amod->channels & 1) {
2232                                                         /* for location */
2233                                                         nor[0] = BLI_gNoise(amod->noisesize, loc[0]+ofs, loc[1], loc[2], 0, 0) - ofs;
2234                                                         nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1]+ofs, loc[2], 0, 0) - ofs;   
2235                                                         nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2]+ofs, 0, 0) - ofs;
2236                                                         
2237                                                         add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2238                                                 }
2239                                         }
2240                                 }
2241                                         break;
2242                                 }
2243                         }
2244                 }
2245         }
2246 }
2247
2248 /* calculate tail of posechannel */
2249 void where_is_pose_bone_tail(bPoseChannel *pchan)
2250 {
2251         float vec[3];
2252         
2253         VECCOPY(vec, pchan->pose_mat[1]);
2254         mul_v3_fl(vec, pchan->bone->length);
2255         add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2256 }
2257
2258 /* The main armature solver, does all constraints excluding IK */
2259 /* pchan is validated, as having bone and parent pointer
2260  * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2261  */
2262 void where_is_pose_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, int do_extra)
2263 {
2264         Bone *bone, *parbone;
2265         bPoseChannel *parchan;
2266         float vec[3];
2267         
2268         /* set up variables for quicker access below */
2269         bone= pchan->bone;
2270         parbone= bone->parent;
2271         parchan= pchan->parent;
2272         
2273         /* this gives a chan_mat with actions (ipos) results */
2274         if(do_extra)    pchan_calc_mat(pchan);
2275         else                    unit_m4(pchan->chan_mat);
2276
2277         /* construct the posemat based on PoseChannels, that we do before applying constraints */
2278         /* pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2279         
2280         if(parchan) {
2281                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
2282                 
2283                 /* bone transform itself */
2284                 copy_m4_m3(offs_bone, bone->bone_mat);
2285                 
2286                 /* The bone's root offset (is in the parent's coordinate system) */
2287                 VECCOPY(offs_bone[3], bone->head);
2288                 
2289                 /* Get the length translation of parent (length along y axis) */
2290                 offs_bone[3][1]+= parbone->length;
2291                 
2292                 /* Compose the matrix for this bone  */
2293                 if((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) { // uses restposition rotation, but actual position
2294                         float tmat[4][4];
2295                         /* the rotation of the parent restposition */
2296                         copy_m4_m4(tmat, parbone->arm_mat);
2297                         mul_serie_m4(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2298                 }
2299                 else if(bone->flag & BONE_HINGE) {      // same as above but apply parent scale
2300                         float tmat[4][4];
2301
2302                         /* apply the parent matrix scale */
2303                         float tsmat[4][4], tscale[3];
2304
2305                         /* the rotation of the parent restposition */
2306                         copy_m4_m4(tmat, parbone->arm_mat);
2307
2308                         /* extract the scale of the parent matrix */
2309                         mat4_to_size(tscale, parchan->pose_mat);
2310                         size_to_mat4(tsmat, tscale);
2311                         mul_m4_m4m4(tmat, tmat, tsmat);
2312
2313                         mul_serie_m4(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2314                 }
2315                 else if(bone->flag & BONE_NO_SCALE) {
2316                         float orthmat[4][4];
2317                         
2318                         /* do transform, with an ortho-parent matrix */
2319                         copy_m4_m4(orthmat, parchan->pose_mat);
2320                         normalize_m4(orthmat);
2321                         mul_serie_m4(pchan->pose_mat, orthmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2322                 }
2323                 else
2324                         mul_serie_m4(pchan->pose_mat, parchan->pose_mat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2325                 
2326                 /* in these cases we need to compute location separately */
2327                 if(bone->flag & (BONE_HINGE|BONE_NO_SCALE|BONE_NO_LOCAL_LOCATION)) {
2328                         float bone_loc[3], chan_loc[3];
2329
2330                         mul_v3_m4v3(bone_loc, parchan->pose_mat, offs_bone[3]);
2331                         copy_v3_v3(chan_loc, pchan->chan_mat[3]);
2332
2333                         /* no local location is not transformed by bone matrix */
2334                         if(!(bone->flag & BONE_NO_LOCAL_LOCATION))
2335                                 mul_mat3_m4_v3(offs_bone, chan_loc);
2336
2337                         /* for hinge we use armature instead of pose mat */
2338                         if(bone->flag & BONE_HINGE) mul_mat3_m4_v3(parbone->arm_mat, chan_loc);
2339                         else mul_mat3_m4_v3(parchan->pose_mat, chan_loc);
2340
2341                         add_v3_v3v3(pchan->pose_mat[3], bone_loc, chan_loc);
2342                 }
2343         }
2344         else {
2345                 mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
2346
2347                 /* optional location without arm_mat rotation */
2348                 if(bone->flag & BONE_NO_LOCAL_LOCATION)
2349                         add_v3_v3v3(pchan->pose_mat[3], bone->arm_mat[3], pchan->chan_mat[3]);
2350                 
2351                 /* only rootbones get the cyclic offset (unless user doesn't want that) */
2352                 if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2353                         add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2354         }
2355         
2356         if(do_extra) {
2357                 /* do NLA strip modifiers - i.e. curve follow */
2358                 do_strip_modifiers(scene, ob, bone, pchan);
2359                 
2360                 /* Do constraints */
2361                 if (pchan->constraints.first) {
2362                         bConstraintOb *cob;
2363
2364                         /* make a copy of location of PoseChannel for later */
2365                         VECCOPY(vec, pchan->pose_mat[3]);
2366
2367                         /* prepare PoseChannel for Constraint solving
2368                          * - makes a copy of matrix, and creates temporary struct to use
2369                          */
2370                         cob= constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2371
2372                         /* Solve PoseChannel's Constraints */
2373                         solve_constraints(&pchan->constraints, cob, ctime);     // ctime doesnt alter objects
2374
2375                         /* cleanup after Constraint Solving
2376                          * - applies matrix back to pchan, and frees temporary struct used
2377                          */
2378                         constraints_clear_evalob(cob);
2379
2380                         /* prevent constraints breaking a chain */
2381                         if(pchan->bone->flag & BONE_CONNECTED) {
2382                                 VECCOPY(pchan->pose_mat[3], vec);
2383                         }
2384                 }
2385         }
2386         
2387         /* calculate head */
2388         VECCOPY(pchan->pose_head, pchan->pose_mat[3]);
2389         /* calculate tail */
2390         where_is_pose_bone_tail(pchan);
2391 }
2392
2393 /* This only reads anim data from channels, and writes to channels */
2394 /* This is the only function adding poses */
2395 void where_is_pose (Scene *scene, Object *ob)
2396 {
2397         bArmature *arm;
2398         Bone *bone;
2399         bPoseChannel *pchan;
2400         float imat[4][4];
2401         float ctime;
2402         
2403         if(ob->type!=OB_ARMATURE) return;
2404         arm = ob->data;
2405         
2406         if(ELEM(NULL, arm, scene)) return;
2407         if((ob->pose==NULL) || (ob->pose->flag & POSE_RECALC)) 
2408                 armature_rebuild_pose(ob, arm);
2409            
2410         ctime= bsystem_time(scene, ob, (float)scene->r.cfra, 0.0);      /* not accurate... */
2411         
2412         /* In editmode or restposition we read the data from the bones */
2413         if(arm->edbo || (arm->flag & ARM_RESTPOS)) {
2414                 
2415                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2416                         bone= pchan->bone;
2417                         if(bone) {
2418                                 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2419                                 VECCOPY(pchan->pose_head, bone->arm_head);
2420                                 VECCOPY(pchan->pose_tail, bone->arm_tail);
2421                         }
2422                 }
2423         }
2424         else {
2425                 invert_m4_m4(ob->imat, ob->obmat);      // imat is needed 
2426                 
2427                 /* 1. clear flags */
2428                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2429                         pchan->flag &= ~(POSE_DONE|POSE_CHAIN|POSE_IKTREE|POSE_IKSPLINE);
2430                 }
2431                 
2432                 /* 2a. construct the IK tree (standard IK) */
2433                 BIK_initialize_tree(scene, ob, ctime);
2434                 
2435                 /* 2b. construct the Spline IK trees 
2436                  *  - this is not integrated as an IK plugin, since it should be able
2437                  *        to function in conjunction with standard IK
2438                  */
2439                 splineik_init_tree(scene, ob, ctime);
2440                 
2441                 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2442                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2443                         /* 4a. if we find an IK root, we handle it separated */
2444                         if(pchan->flag & POSE_IKTREE) {
2445                                 BIK_execute_tree(scene, ob, pchan, ctime);
2446                         }
2447                         /* 4b. if we find a Spline IK root, we handle it separated too */
2448                         else if(pchan->flag & POSE_IKSPLINE) {
2449                                 splineik_execute_tree(scene, ob, pchan, ctime);
2450                         }
2451                         /* 5. otherwise just call the normal solver */
2452                         else if(!(pchan->flag & POSE_DONE)) {
2453                                 where_is_pose_bone(scene, ob, pchan, ctime, 1);
2454                         }
2455                 }
2456                 /* 6. release the IK tree */
2457                 BIK_release_tree(scene, ob, ctime);
2458         }
2459                 
2460         /* calculating deform matrices */
2461         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2462                 if(pchan->bone) {
2463                         invert_m4_m4(imat, pchan->bone->arm_mat);
2464                         mul_m4_m4m4(pchan->chan_mat, imat, pchan->pose_mat);
2465                 }
2466         }
2467 }
2468
2469 /* Jason was here */
2470 char* get_selected_defgroups(Object *ob, int defcnt)
2471 {
2472         bPoseChannel *chan;
2473         bPose *pose;
2474         bDeformGroup *defgroup;
2475         //Bone *bone;
2476         char *dg_flags = MEM_callocN(defcnt*sizeof(char), "dg_selected_flags");
2477         int i;
2478         Object *armob = object_pose_armature_get(ob);
2479
2480         if(armob) {
2481                 pose = armob->pose;
2482                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
2483                         for (i = 0, defgroup = ob->defbase.first; i < defcnt && defgroup; defgroup = defgroup->next, i++) {
2484                                 if(!strcmp(defgroup->name, chan->bone->name)) {
2485                                         dg_flags[i] = (chan->bone->flag & BONE_SELECTED);
2486                                 }
2487                         }
2488                 }
2489         }
2490
2491         return dg_flags;
2492 }
2493
2494 /* TODO move duplicates to header */
2495 /* Jason was here duplicate function */
2496 int count_selected_defgroups(const char *list, int len)
2497 {
2498         int i;
2499         int cnt = 0;
2500         for(i = 0; i < len; i++) {
2501                 if (list[i]) {
2502                         cnt++;
2503                 }
2504         }
2505         return cnt;
2506 }