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