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