Merge with trunk, revision 28446 - 28528.
[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_v3(cop, co);
854                                 madd_v3_v3fl(vec, cop, fac);
855
856                                 if(mat)
857                                         pchan_deform_mat_add(pchan, fac, bbonemat, mat);
858                         }
859                         else {
860                                 if(bone->segments>1) {
861                                         b_bone_deform(pchan, bone, cop, &bbonedq, NULL);
862                                         add_weighted_dq_dq(dq, &bbonedq, fac);
863                                 }
864                                 else
865                                         add_weighted_dq_dq(dq, pchan->dual_quat, fac);
866                         }
867                 }
868         }
869         
870         return contrib;
871 }
872
873 static void pchan_bone_deform(bPoseChannel *pchan, float weight, float *vec, DualQuat *dq, float mat[][3], float *co, float *contrib)
874 {
875         float cop[3], bbonemat[3][3];
876         DualQuat bbonedq;
877
878         if (!weight)
879                 return;
880
881         VECCOPY(cop, co);
882
883         if(vec) {
884                 if(pchan->bone->segments>1)
885                         // applies on cop and bbonemat
886                         b_bone_deform(pchan, pchan->bone, cop, NULL, (mat)?bbonemat:NULL);
887                 else
888                         mul_m4_v3(pchan->chan_mat, cop);
889                 
890                 vec[0]+=(cop[0]-co[0])*weight;
891                 vec[1]+=(cop[1]-co[1])*weight;
892                 vec[2]+=(cop[2]-co[2])*weight;
893
894                 if(mat)
895                         pchan_deform_mat_add(pchan, weight, bbonemat, mat);
896         }
897         else {
898                 if(pchan->bone->segments>1) {
899                         b_bone_deform(pchan, pchan->bone, cop, &bbonedq, NULL);
900                         add_weighted_dq_dq(dq, &bbonedq, weight);
901                 }
902                 else
903                         add_weighted_dq_dq(dq, pchan->dual_quat, weight);
904         }
905
906         (*contrib)+=weight;
907 }
908
909 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm,
910                                                    float (*vertexCos)[3], float (*defMats)[3][3],
911                                                    int numVerts, int deformflag, 
912                                                    float (*prevCos)[3], const char *defgrp_name)
913 {
914         bArmature *arm= armOb->data;
915         bPoseChannel *pchan, **defnrToPC = NULL;
916         MDeformVert *dverts = NULL;
917         bDeformGroup *dg;
918         DualQuat *dualquats= NULL;
919         float obinv[4][4], premat[4][4], postmat[4][4];
920         int use_envelope = deformflag & ARM_DEF_ENVELOPE;
921         int use_quaternion = deformflag & ARM_DEF_QUATERNION;
922         int bbone_rest_def = deformflag & ARM_DEF_B_BONE_REST;
923         int invert_vgroup= deformflag & ARM_DEF_INVERT_VGROUP;
924         int numGroups = 0;              /* safety for vertexgroup index overflow */
925         int i, target_totvert = 0;      /* safety for vertexgroup overflow */
926         int use_dverts = 0;
927         int armature_def_nr;
928         int totchan;
929
930         if(arm->edbo) return;
931         
932         invert_m4_m4(obinv, target->obmat);
933         copy_m4_m4(premat, target->obmat);
934         mul_m4_m4m4(postmat, armOb->obmat, obinv);
935         invert_m4_m4(premat, postmat);
936
937         /* bone defmats are already in the channels, chan_mat */
938         
939         /* initialize B_bone matrices and dual quaternions */
940         if(use_quaternion) {
941                 totchan= BLI_countlist(&armOb->pose->chanbase);
942                 dualquats= MEM_callocN(sizeof(DualQuat)*totchan, "dualquats");
943         }
944
945         totchan= 0;
946         for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next) {
947                 if(!(pchan->bone->flag & BONE_NO_DEFORM)) {
948                         if(pchan->bone->segments > 1)
949                                 pchan_b_bone_defmats(pchan, use_quaternion, bbone_rest_def);
950
951                         if(use_quaternion) {
952                                 pchan->dual_quat= &dualquats[totchan++];
953                                 mat4_to_dquat( pchan->dual_quat,pchan->bone->arm_mat, pchan->chan_mat);
954                         }
955                 }
956         }
957
958         /* get the def_nr for the overall armature vertex group if present */
959         armature_def_nr= defgroup_name_index(target, defgrp_name);
960         
961         if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
962                 numGroups = BLI_countlist(&target->defbase);
963                 
964                 if(target->type==OB_MESH) {
965                         Mesh *me= target->data;
966                         dverts = me->dvert;
967                         if(dverts)
968                                 target_totvert = me->totvert;
969                 }
970                 else {
971                         Lattice *lt= target->data;
972                         dverts = lt->dvert;
973                         if(dverts)
974                                 target_totvert = lt->pntsu*lt->pntsv*lt->pntsw;
975                 }
976         }
977         
978         /* get a vertex-deform-index to posechannel array */
979         if(deformflag & ARM_DEF_VGROUP) {
980                 if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
981                         /* if we have a DerivedMesh, only use dverts if it has them */
982                         if(dm)
983                                 if(dm->getVertData(dm, 0, CD_MDEFORMVERT))
984                                         use_dverts = 1;
985                                 else use_dverts = 0;
986                         else if(dverts) use_dverts = 1;
987
988                         if(use_dverts) {
989                                 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * numGroups,
990                                                                                 "defnrToBone");
991                                 for(i = 0, dg = target->defbase.first; dg;
992                                         i++, dg = dg->next) {
993                                         defnrToPC[i] = get_pose_channel(armOb->pose, dg->name);
994                                         /* exclude non-deforming bones */
995                                         if(defnrToPC[i]) {
996                                                 if(defnrToPC[i]->bone->flag & BONE_NO_DEFORM)
997                                                         defnrToPC[i]= NULL;
998                                         }
999                                 }
1000                         }
1001                 }
1002         }
1003
1004         for(i = 0; i < numVerts; i++) {
1005                 MDeformVert *dvert;
1006                 DualQuat sumdq, *dq = NULL;
1007                 float *co, dco[3];
1008                 float sumvec[3], summat[3][3];
1009                 float *vec = NULL, (*smat)[3] = NULL;
1010                 float contrib = 0.0f;
1011                 float armature_weight = 1.0f;   /* default to 1 if no overall def group */
1012                 float prevco_weight = 1.0f;             /* weight for optional cached vertexcos */
1013                 int       j;
1014
1015                 if(use_quaternion) {
1016                         memset(&sumdq, 0, sizeof(DualQuat));
1017                         dq= &sumdq;
1018                 }
1019                 else {
1020                         sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
1021                         vec= sumvec;
1022
1023                         if(defMats) {
1024                                 zero_m3(summat);
1025                                 smat = summat;
1026                         }
1027                 }
1028
1029                 if(use_dverts || armature_def_nr >= 0) {
1030                         if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
1031                         else if(dverts && i < target_totvert) dvert = dverts + i;
1032                         else dvert = NULL;
1033                 } else
1034                         dvert = NULL;
1035
1036                 if(armature_def_nr >= 0 && dvert) {
1037                         armature_weight = 0.0f; /* a def group was given, so default to 0 */
1038                         for(j = 0; j < dvert->totweight; j++) {
1039                                 if(dvert->dw[j].def_nr == armature_def_nr) {
1040                                         armature_weight = dvert->dw[j].weight;
1041                                         break;
1042                                 }
1043                         }
1044                         /* hackish: the blending factor can be used for blending with prevCos too */
1045                         if(prevCos) {
1046                                 if(invert_vgroup)
1047                                         prevco_weight= 1.0f-armature_weight;
1048                                 else
1049                                         prevco_weight= armature_weight;
1050                                 armature_weight= 1.0f;
1051                         }
1052                 }
1053
1054                 /* check if there's any  point in calculating for this vert */
1055                 if(armature_weight == 0.0f) continue;
1056                 
1057                 /* get the coord we work on */
1058                 co= prevCos?prevCos[i]:vertexCos[i];
1059                 
1060                 /* Apply the object's matrix */
1061                 mul_m4_v3(premat, co);
1062                 
1063                 if(use_dverts && dvert && dvert->totweight) { // use weight groups ?
1064                         int deformed = 0;
1065                         
1066                         for(j = 0; j < dvert->totweight; j++){
1067                                 int index = dvert->dw[j].def_nr;
1068                                 pchan = index < numGroups?defnrToPC[index]:NULL;
1069                                 if(pchan) {
1070                                         float weight = dvert->dw[j].weight;
1071                                         Bone *bone = pchan->bone;
1072
1073                                         deformed = 1;
1074                                         
1075                                         if(bone && bone->flag & BONE_MULT_VG_ENV) {
1076                                                 weight *= distfactor_to_bone(co, bone->arm_head,
1077                                                                                                          bone->arm_tail,
1078                                                                                                          bone->rad_head,
1079                                                                                                          bone->rad_tail,
1080                                                                                                          bone->dist);
1081                                         }
1082                                         pchan_bone_deform(pchan, weight, vec, dq, smat, co, &contrib);
1083                                 }
1084                         }
1085                         /* if there are vertexgroups but not groups with bones
1086                          * (like for softbody groups)
1087                          */
1088                         if(deformed == 0 && use_envelope) {
1089                                 for(pchan = armOb->pose->chanbase.first; pchan;
1090                                         pchan = pchan->next) {
1091                                         if(!(pchan->bone->flag & BONE_NO_DEFORM))
1092                                                 contrib += dist_bone_deform(pchan, vec, dq, smat, co);
1093                                 }
1094                         }
1095                 }
1096                 else if(use_envelope) {
1097                         for(pchan = armOb->pose->chanbase.first; pchan;
1098                                 pchan = pchan->next) {
1099                                 if(!(pchan->bone->flag & BONE_NO_DEFORM))
1100                                         contrib += dist_bone_deform(pchan, vec, dq, smat, co);
1101                         }
1102                 }
1103
1104                 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1105                 if(contrib > 0.0001f) {
1106                         if(use_quaternion) {
1107                                 normalize_dq(dq, contrib);
1108
1109                                 if(armature_weight != 1.0f) {
1110                                         VECCOPY(dco, co);
1111                                         mul_v3m3_dq( dco, (defMats)? summat: NULL,dq);
1112                                         sub_v3_v3(dco, co);
1113                                         mul_v3_fl(dco, armature_weight);
1114                                         add_v3_v3(co, dco);
1115                                 }
1116                                 else
1117                                         mul_v3m3_dq( co, (defMats)? summat: NULL,dq);
1118
1119                                 smat = summat;
1120                         }
1121                         else {
1122                                 mul_v3_fl(vec, armature_weight/contrib);
1123                                 add_v3_v3v3(co, vec, co);
1124                         }
1125
1126                         if(defMats) {
1127                                 float pre[3][3], post[3][3], tmpmat[3][3];
1128
1129                                 copy_m3_m4(pre, premat);
1130                                 copy_m3_m4(post, postmat);
1131                                 copy_m3_m3(tmpmat, defMats[i]);
1132
1133                                 if(!use_quaternion) /* quaternion already is scale corrected */
1134                                         mul_m3_fl(smat, armature_weight/contrib);
1135
1136                                 mul_serie_m3(defMats[i], tmpmat, pre, smat, post,
1137                                         NULL, NULL, NULL, NULL);
1138                         }
1139                 }
1140                 
1141                 /* always, check above code */
1142                 mul_m4_v3(postmat, co);
1143                 
1144                 
1145                 /* interpolate with previous modifier position using weight group */
1146                 if(prevCos) {
1147                         float mw= 1.0f - prevco_weight;
1148                         vertexCos[i][0]= prevco_weight*vertexCos[i][0] + mw*co[0];
1149                         vertexCos[i][1]= prevco_weight*vertexCos[i][1] + mw*co[1];
1150                         vertexCos[i][2]= prevco_weight*vertexCos[i][2] + mw*co[2];
1151                 }
1152         }
1153
1154         if(dualquats) MEM_freeN(dualquats);
1155         if(defnrToPC) MEM_freeN(defnrToPC);
1156         
1157         /* free B_bone matrices */
1158         for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next) {
1159                 if(pchan->b_bone_mats) {
1160                         MEM_freeN(pchan->b_bone_mats);
1161                         pchan->b_bone_mats = NULL;
1162                 }
1163                 if(pchan->b_bone_dual_quats) {
1164                         MEM_freeN(pchan->b_bone_dual_quats);
1165                         pchan->b_bone_dual_quats = NULL;
1166                 }
1167
1168                 pchan->dual_quat = NULL;
1169         }
1170 }
1171
1172 /* ************ END Armature Deform ******************* */
1173
1174 void get_objectspace_bone_matrix (struct Bone* bone, float M_accumulatedMatrix[][4], int root, int posed)
1175 {
1176         copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1177 }
1178
1179 /* **************** Space to Space API ****************** */
1180
1181 /* Convert World-Space Matrix to Pose-Space Matrix */
1182 void armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4]) 
1183 {
1184         float obmat[4][4];
1185         
1186         /* prevent crashes */
1187         if (ob==NULL) return;
1188         
1189         /* get inverse of (armature) object's matrix  */
1190         invert_m4_m4(obmat, ob->obmat);
1191         
1192         /* multiply given matrix by object's-inverse to find pose-space matrix */
1193         mul_m4_m4m4(outmat, obmat, inmat);
1194 }
1195
1196 /* Convert Wolrd-Space Location to Pose-Space Location
1197  * NOTE: this cannot be used to convert to pose-space location of the supplied
1198  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1199  */
1200 void armature_loc_world_to_pose(Object *ob, float *inloc, float *outloc) 
1201 {
1202         float xLocMat[4][4];
1203         float nLocMat[4][4];
1204         
1205         /* build matrix for location */
1206         unit_m4(xLocMat);
1207         VECCOPY(xLocMat[3], inloc);
1208
1209         /* get bone-space cursor matrix and extract location */
1210         armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1211         VECCOPY(outloc, nLocMat[3]);
1212 }
1213
1214 /* Convert Pose-Space Matrix to Bone-Space Matrix 
1215  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1216  *              pose-channel into its local space (i.e. 'visual'-keyframing)
1217  */
1218 void armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1219 {
1220         float pc_trans[4][4], inv_trans[4][4];
1221         float pc_posemat[4][4], inv_posemat[4][4];
1222         
1223         /* paranoia: prevent crashes with no pose-channel supplied */
1224         if (pchan==NULL) return;
1225         
1226         /* get the inverse matrix of the pchan's transforms */
1227         if (pchan->rotmode)
1228                 loc_eul_size_to_mat4(pc_trans, pchan->loc, pchan->eul, pchan->size);
1229         else
1230                 loc_quat_size_to_mat4(pc_trans, pchan->loc, pchan->quat, pchan->size);
1231         invert_m4_m4(inv_trans, pc_trans);
1232         
1233         /* Remove the pchan's transforms from it's pose_mat.
1234          * This should leave behind the effects of restpose + 
1235          * parenting + constraints
1236          */
1237         mul_m4_m4m4(pc_posemat, inv_trans, pchan->pose_mat);
1238         
1239         /* get the inverse of the leftovers so that we can remove 
1240          * that component from the supplied matrix
1241          */
1242         invert_m4_m4(inv_posemat, pc_posemat);
1243         
1244         /* get the new matrix */
1245         mul_m4_m4m4(outmat, inmat, inv_posemat);
1246 }
1247
1248 /* Convert Pose-Space Location to Bone-Space Location
1249  * NOTE: this cannot be used to convert to pose-space location of the supplied
1250  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1251  */
1252 void armature_loc_pose_to_bone(bPoseChannel *pchan, float *inloc, float *outloc) 
1253 {
1254         float xLocMat[4][4];
1255         float nLocMat[4][4];
1256         
1257         /* build matrix for location */
1258         unit_m4(xLocMat);
1259         VECCOPY(xLocMat[3], inloc);
1260
1261         /* get bone-space cursor matrix and extract location */
1262         armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1263         VECCOPY(outloc, nLocMat[3]);
1264 }
1265
1266
1267 /* Apply a 4x4 matrix to the pose bone,
1268  * similar to object_apply_mat4()
1269  */
1270 void pchan_apply_mat4(bPoseChannel *pchan, float mat[][4])
1271 {
1272         /* location */
1273         copy_v3_v3(pchan->loc, mat[3]);
1274
1275         /* scale */
1276         mat4_to_size(pchan->size, mat);
1277
1278         /* rotation */
1279         if (pchan->rotmode == ROT_MODE_AXISANGLE) {
1280                 float tmp_quat[4];
1281
1282                 /* need to convert to quat first (in temp var)... */
1283                 mat4_to_quat(tmp_quat, mat);
1284                 quat_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, tmp_quat);
1285         }
1286         else if (pchan->rotmode == ROT_MODE_QUAT) {
1287                 mat4_to_quat(pchan->quat, mat);
1288         }
1289         else {
1290                 mat4_to_eulO(pchan->eul, pchan->rotmode, mat);
1291         }
1292 }
1293
1294 /* Remove rest-position effects from pose-transform for obtaining
1295  * 'visual' transformation of pose-channel.
1296  * (used by the Visual-Keyframing stuff)
1297  */
1298 void armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
1299 {
1300          float imat[4][4];
1301  
1302          invert_m4_m4(imat, arm_mat);
1303          mul_m4_m4m4(delta_mat, pose_mat, imat);
1304 }
1305
1306 /* **************** Rotation Mode Conversions ****************************** */
1307 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1308
1309 /* Called from RNA when rotation mode changes 
1310  *      - the result should be that the rotations given in the provided pointers have had conversions 
1311  *        applied (as appropriate), such that the rotation of the element hasn't 'visually' changed 
1312  */
1313 void BKE_rotMode_change_values (float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1314 {
1315         /* check if any change - if so, need to convert data */
1316         if (newMode > 0) { /* to euler */
1317                 if (oldMode == ROT_MODE_AXISANGLE) {
1318                         /* axis-angle to euler */
1319                         axis_angle_to_eulO( eul, newMode,axis, *angle);
1320                 }
1321                 else if (oldMode == ROT_MODE_QUAT) {
1322                         /* quat to euler */
1323                         quat_to_eulO( eul, newMode,quat);
1324                 }
1325                 /* else { no conversion needed } */
1326         }
1327         else if (newMode == ROT_MODE_QUAT) { /* to quat */
1328                 if (oldMode == ROT_MODE_AXISANGLE) {
1329                         /* axis angle to quat */
1330                         axis_angle_to_quat(quat, axis, *angle);
1331                 }
1332                 else if (oldMode > 0) {
1333                         /* euler to quat */
1334                         eulO_to_quat( quat,eul, oldMode);
1335                 }
1336                 /* else { no conversion needed } */
1337         }
1338         else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1339                 if (oldMode > 0) {
1340                         /* euler to axis angle */
1341                         eulO_to_axis_angle( axis, angle,eul, oldMode);
1342                 }
1343                 else if (oldMode == ROT_MODE_QUAT) {
1344                         /* quat to axis angle */
1345                         quat_to_axis_angle( axis, angle,quat);
1346                 }
1347                 
1348                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1349                 if (IS_EQ(axis[0], axis[1]) && IS_EQ(axis[1], axis[2])) {
1350                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1351                         axis[1]= 1.0f;
1352                 }
1353         }
1354 }
1355
1356 /* **************** The new & simple (but OK!) armature evaluation ********* */ 
1357
1358 /*  ****************** And how it works! ****************************************
1359
1360   This is the bone transformation trick; they're hierarchical so each bone(b)
1361   is in the coord system of bone(b-1):
1362
1363   arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) 
1364   
1365   -> yoffs is just the y axis translation in parent's coord system
1366   -> d_root is the translation of the bone root, also in parent's coord system
1367
1368   pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1369
1370   we then - in init deform - store the deform in chan_mat, such that:
1371
1372   pose_mat(b)= arm_mat(b) * chan_mat(b)
1373   
1374   *************************************************************************** */
1375 /*  Computes vector and roll based on a rotation. "mat" must
1376          contain only a rotation, and no scaling. */ 
1377 void mat3_to_vec_roll(float mat[][3], float *vec, float *roll) 
1378 {
1379         if (vec)
1380                 copy_v3_v3(vec, mat[1]);
1381
1382         if (roll) {
1383                 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1384
1385                 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1386                 invert_m3_m3(vecmatinv, vecmat);
1387                 mul_m3_m3m3(rollmat, vecmatinv, mat);
1388
1389                 *roll= (float)atan2(rollmat[2][0], rollmat[2][2]);
1390         }
1391 }
1392
1393 /*      Calculates the rest matrix of a bone based
1394         On its vector and a roll around that vector */
1395 void vec_roll_to_mat3(float *vec, float roll, float mat[][3])
1396 {
1397         float   nor[3], axis[3], target[3]={0,1,0};
1398         float   theta;
1399         float   rMatrix[3][3], bMatrix[3][3];
1400         
1401         VECCOPY (nor, vec);
1402         normalize_v3(nor);
1403         
1404         /*      Find Axis & Amount for bone matrix*/
1405         cross_v3_v3v3(axis,target,nor);
1406
1407         if (dot_v3v3(axis,axis) > 0.0000000000001) {
1408                 /* if nor is *not* a multiple of target ... */
1409                 normalize_v3(axis);
1410                 
1411                 theta= angle_normalized_v3v3(target, nor);
1412                 
1413                 /*      Make Bone matrix*/
1414                 vec_rot_to_mat3( bMatrix,axis, theta);
1415         }
1416         else {
1417                 /* if nor is a multiple of target ... */
1418                 float updown;
1419                 
1420                 /* point same direction, or opposite? */
1421                 updown = ( dot_v3v3(target,nor) > 0 ) ? 1.0f : -1.0f;
1422                 
1423                 /* I think this should work ... */
1424                 bMatrix[0][0]=updown; bMatrix[0][1]=0.0;    bMatrix[0][2]=0.0;
1425                 bMatrix[1][0]=0.0;    bMatrix[1][1]=updown; bMatrix[1][2]=0.0;
1426                 bMatrix[2][0]=0.0;    bMatrix[2][1]=0.0;    bMatrix[2][2]=1.0;
1427         }
1428         
1429         /*      Make Roll matrix*/
1430         vec_rot_to_mat3( rMatrix,nor, roll);
1431         
1432         /*      Combine and output result*/
1433         mul_m3_m3m3(mat, rMatrix, bMatrix);
1434 }
1435
1436
1437 /* recursive part, calculates restposition of entire tree of children */
1438 /* used by exiting editmode too */
1439 void where_is_armature_bone(Bone *bone, Bone *prevbone)
1440 {
1441         float vec[3];
1442         
1443         /* Bone Space */
1444         sub_v3_v3v3(vec, bone->tail, bone->head);
1445         vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1446
1447         bone->length= len_v3v3(bone->head, bone->tail);
1448         
1449         /* this is called on old file reading too... */
1450         if(bone->xwidth==0.0) {
1451                 bone->xwidth= 0.1f;
1452                 bone->zwidth= 0.1f;
1453                 bone->segments= 1;
1454         }
1455         
1456         if(prevbone) {
1457                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
1458                 
1459                 /* bone transform itself */
1460                 copy_m4_m3(offs_bone, bone->bone_mat);
1461                                 
1462                 /* The bone's root offset (is in the parent's coordinate system) */
1463                 VECCOPY(offs_bone[3], bone->head);
1464
1465                 /* Get the length translation of parent (length along y axis) */
1466                 offs_bone[3][1]+= prevbone->length;
1467                 
1468                 /* Compose the matrix for this bone  */
1469                 mul_m4_m4m4(bone->arm_mat, offs_bone, prevbone->arm_mat);
1470         }
1471         else {
1472                 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1473                 VECCOPY(bone->arm_mat[3], bone->head);
1474         }
1475         
1476         /* head */
1477         VECCOPY(bone->arm_head, bone->arm_mat[3]);
1478         /* tail is in current local coord system */
1479         VECCOPY(vec, bone->arm_mat[1]);
1480         mul_v3_fl(vec, bone->length);
1481         add_v3_v3v3(bone->arm_tail, bone->arm_head, vec);
1482         
1483         /* and the kiddies */
1484         prevbone= bone;
1485         for(bone= bone->childbase.first; bone; bone= bone->next) {
1486                 where_is_armature_bone(bone, prevbone);
1487         }
1488 }
1489
1490 /* updates vectors and matrices on rest-position level, only needed 
1491    after editing armature itself, now only on reading file */
1492 void where_is_armature (bArmature *arm)
1493 {
1494         Bone *bone;
1495         
1496         /* hierarchical from root to children */
1497         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1498                 where_is_armature_bone(bone, NULL);
1499         }
1500 }
1501
1502 /* if bone layer is protected, copy the data from from->pose
1503  * when used with linked libraries this copies from the linked pose into the local pose */
1504 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1505 {
1506         bPose *pose= ob->pose, *frompose= from->pose;
1507         bPoseChannel *pchan, *pchanp, pchanw;
1508         bConstraint *con;
1509         int error = 0;
1510         
1511         if (frompose==NULL) return;
1512
1513         /* in some cases when rigs change, we cant synchronize
1514          * to avoid crashing check for possible errors here */
1515         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1516                 if (pchan->bone->layer & layer_protected) {
1517                         if(get_pose_channel(frompose, pchan->name) == NULL) {
1518                                 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n", from->id.name, pchan->name);
1519                                 error = 1;
1520                         }
1521                 }
1522         }
1523
1524         if(error)
1525                 return;
1526         
1527         /* exception, armature local layer should be proxied too */
1528         if (pose->proxy_layer)
1529                 ((bArmature *)ob->data)->layer= pose->proxy_layer;
1530         
1531         /* clear all transformation values from library */
1532         rest_pose(frompose);
1533         
1534         /* copy over all of the proxy's bone groups */
1535                 /* TODO for later - implement 'local' bone groups as for constraints
1536                  *      Note: this isn't trivial, as bones reference groups by index not by pointer, 
1537                  *               so syncing things correctly needs careful attention
1538                  */
1539         BLI_freelistN(&pose->agroups);
1540         BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1541         pose->active_group= frompose->active_group;
1542         
1543         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1544                 pchanp= get_pose_channel(frompose, pchan->name);
1545
1546                 if (pchan->bone->layer & layer_protected) {
1547                         ListBase proxylocal_constraints = {NULL, NULL};
1548                         
1549                         /* copy posechannel to temp, but restore important pointers */
1550                         pchanw= *pchanp;
1551                         pchanw.prev= pchan->prev;
1552                         pchanw.next= pchan->next;
1553                         pchanw.parent= pchan->parent;
1554                         pchanw.child= pchan->child;
1555                         pchanw.path= NULL;
1556                         
1557                         /* this is freed so copy a copy, else undo crashes */
1558                         if(pchanw.prop) {
1559                                 pchanw.prop= IDP_CopyProperty(pchanw.prop);
1560
1561                                 /* use the values from the the existing props */
1562                                 if(pchan->prop) {
1563                                         IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1564                                 }
1565                         }
1566
1567                         /* constraints - proxy constraints are flushed... local ones are added after 
1568                          *      1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1569                          *      2. copy proxy-pchan's constraints on-to new
1570                          *      3. add extracted local constraints back on top 
1571                          *
1572                          *  note for copy_constraints: when copying constraints, disable 'do_extern' otherwise we get the libs direct linked in this blend.
1573                          */
1574                         extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
1575                         copy_constraints(&pchanw.constraints, &pchanp->constraints, FALSE);
1576                         addlisttolist(&pchanw.constraints, &proxylocal_constraints);
1577                         
1578                         /* constraints - set target ob pointer to own object */
1579                         for (con= pchanw.constraints.first; con; con= con->next) {
1580                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1581                                 ListBase targets = {NULL, NULL};
1582                                 bConstraintTarget *ct;
1583                                 
1584                                 if (cti && cti->get_constraint_targets) {
1585                                         cti->get_constraint_targets(con, &targets);
1586                                         
1587                                         for (ct= targets.first; ct; ct= ct->next) {
1588                                                 if (ct->tar == from)
1589                                                         ct->tar = ob;
1590                                         }
1591                                         
1592                                         if (cti->flush_constraint_targets)
1593                                                 cti->flush_constraint_targets(con, &targets, 0);
1594                                 }
1595                         }
1596                         
1597                         /* free stuff from current channel */
1598                         free_pose_channel(pchan);
1599                         
1600                         /* the final copy */
1601                         *pchan= pchanw;
1602                 }
1603                 else {
1604                         /* always copy custom shape */
1605                         pchan->custom= pchanp->custom;
1606                         pchan->custom_tx= pchanp->custom_tx;
1607
1608                         /* ID-Property Syncing */
1609                         {
1610                                 IDProperty *prop_orig= pchan->prop;
1611                                 if(pchanp->prop) {
1612                                         pchan->prop= IDP_CopyProperty(pchanp->prop);
1613                                         if(prop_orig) {
1614                                                 /* copy existing values across when types match */
1615                                                 IDP_SyncGroupValues(pchan->prop, prop_orig);
1616                                         }
1617                                 }
1618                                 else {
1619                                         pchan->prop= NULL;
1620                                 }
1621                                 if (prop_orig) {
1622                                         IDP_FreeProperty(prop_orig);
1623                                         MEM_freeN(prop_orig);
1624                                 }
1625                         }
1626                 }
1627         }
1628 }
1629
1630 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1631 {
1632         bPoseChannel *pchan = verify_pose_channel (pose, bone->name);   // verify checks and/or adds
1633
1634         pchan->bone= bone;
1635         pchan->parent= parchan;
1636         
1637         counter++;
1638         
1639         for(bone= bone->childbase.first; bone; bone= bone->next) {
1640                 counter= rebuild_pose_bone(pose, bone, pchan, counter);
1641                 /* for quick detecting of next bone in chain, only b-bone uses it now */
1642                 if(bone->flag & BONE_CONNECTED)
1643                         pchan->child= get_pose_channel(pose, bone->name);
1644         }
1645         
1646         return counter;
1647 }
1648
1649 /* only after leave editmode, duplicating, validating older files, library syncing */
1650 /* NOTE: pose->flag is set for it */
1651 void armature_rebuild_pose(Object *ob, bArmature *arm)
1652 {
1653         Bone *bone;
1654         bPose *pose;
1655         bPoseChannel *pchan, *next;
1656         int counter=0;
1657                 
1658         /* only done here */
1659         if(ob->pose==NULL) {
1660                 /* create new pose */
1661                 ob->pose= MEM_callocN(sizeof(bPose), "new pose");
1662                 
1663                 /* set default settings for animviz */
1664                 animviz_settings_init(&ob->pose->avs);
1665         }
1666         pose= ob->pose;
1667         
1668         /* clear */
1669         for(pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1670                 pchan->bone= NULL;
1671                 pchan->child= NULL;
1672         }
1673         
1674         /* first step, check if all channels are there */
1675         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1676                 counter= rebuild_pose_bone(pose, bone, NULL, counter);
1677         }
1678
1679         /* and a check for garbage */
1680         for(pchan= pose->chanbase.first; pchan; pchan= next) {
1681                 next= pchan->next;
1682                 if(pchan->bone==NULL) {
1683                         free_pose_channel(pchan);
1684                         free_pose_channels_hash(pose);
1685                         BLI_freelinkN(&pose->chanbase, pchan);
1686                 }
1687         }
1688         // printf("rebuild pose %s, %d bones\n", ob->id.name, counter);
1689         
1690         /* synchronize protected layers with proxy */
1691         if(ob->proxy) {
1692                 object_copy_proxy_drivers(ob, ob->proxy);
1693                 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1694         }
1695         
1696         update_pose_constraint_flags(ob->pose); // for IK detection for example
1697         
1698         /* the sorting */
1699         if(counter>1)
1700                 DAG_pose_sort(ob);
1701         
1702         ob->pose->flag &= ~POSE_RECALC;
1703         ob->pose->flag |= POSE_WAS_REBUILT;
1704 }
1705
1706
1707 /* ********************** SPLINE IK SOLVER ******************* */
1708
1709 /* Temporary evaluation tree data used for Spline IK */
1710 typedef struct tSplineIK_Tree {
1711         struct tSplineIK_Tree *next, *prev;
1712         
1713         int     type;                                   /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
1714         
1715         short free_points;                              /* free the point positions array */
1716         short chainlen;                                 /* number of bones in the chain */
1717         
1718         float *points;                                  /* parametric positions for the joints along the curve */
1719         bPoseChannel **chain;                   /* chain of bones to affect using Spline IK (ordered from the tip) */
1720         
1721         bPoseChannel *root;                             /* bone that is the root node of the chain */
1722         
1723         bConstraint *con;                               /* constraint for this chain */
1724         bSplineIKConstraint *ikData;    /* constraint settings for this chain */
1725 } tSplineIK_Tree;
1726
1727 /* ----------- */
1728
1729 /* Tag the bones in the chain formed by the given bone for IK */
1730 static void splineik_init_tree_from_pchan(Scene *scene, Object *ob, bPoseChannel *pchan_tip)
1731 {
1732         bPoseChannel *pchan, *pchanRoot=NULL;
1733         bPoseChannel *pchanChain[255];
1734         bConstraint *con = NULL;
1735         bSplineIKConstraint *ikData = NULL;
1736         float boneLengths[255], *jointPoints;
1737         float totLength = 0.0f;
1738         short free_joints = 0;
1739         int segcount = 0;
1740         
1741         /* find the SplineIK constraint */
1742         for (con= pchan_tip->constraints.first; con; con= con->next) {
1743                 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
1744                         ikData= con->data;
1745                         
1746                         /* target can only be curve */
1747                         if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))  
1748                                 continue;
1749                         /* skip if disabled */
1750                         if ( (con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE|CONSTRAINT_OFF)) )
1751                                 continue;
1752                         
1753                         /* otherwise, constraint is ok... */
1754                         break;
1755                 }
1756         }
1757         if (con == NULL)
1758                 return;
1759                 
1760         /* make sure that the constraint targets are ok 
1761          *      - this is a workaround for a depsgraph bug...
1762          */
1763         if (ikData->tar) {
1764                 Curve *cu= ikData->tar->data;
1765                 
1766                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1767                  *              currently for paths to work it needs to go through the bevlist/displist system (ton) 
1768                  */
1769                 
1770                 /* only happens on reload file, but violates depsgraph still... fix! */
1771                 if ((cu->path==NULL) || (cu->path->data==NULL))
1772                         makeDispListCurveTypes(scene, ikData->tar, 0);
1773         }
1774         
1775         /* find the root bone and the chain of bones from the root to the tip 
1776          * NOTE: this assumes that the bones are connected, but that may not be true...
1777          */
1778         for (pchan= pchan_tip; pchan && (segcount < ikData->chainlen); pchan= pchan->parent, segcount++) {
1779                 /* store this segment in the chain */
1780                 pchanChain[segcount]= pchan;
1781                 
1782                 /* if performing rebinding, calculate the length of the bone */
1783                 boneLengths[segcount]= pchan->bone->length;
1784                 totLength += boneLengths[segcount];
1785         }
1786         
1787         if (segcount == 0)
1788                 return;
1789         else
1790                 pchanRoot= pchanChain[segcount-1];
1791         
1792         /* perform binding step if required */
1793         if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
1794                 float segmentLen= (1.0f / (float)segcount);
1795                 int i;
1796                 
1797                 /* setup new empty array for the points list */
1798                 if (ikData->points) 
1799                         MEM_freeN(ikData->points);
1800                 ikData->numpoints= ikData->chainlen+1; 
1801                 ikData->points= MEM_callocN(sizeof(float)*ikData->numpoints, "Spline IK Binding");
1802                 
1803                 /* perform binding of the joints to parametric positions along the curve based 
1804                  * proportion of the total length that each bone occupies
1805                  */
1806                 for (i = 0; i < segcount; i++) {
1807                         if (i != 0) {
1808                                 /* 'head' joints 
1809                                  *      - 2 methods; the one chosen depends on whether we've got usable lengths
1810                                  */
1811                                 if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
1812                                         /* 1) equi-spaced joints */
1813                                         ikData->points[i]= ikData->points[i-1] - segmentLen;
1814                                 }
1815                                 else {
1816                                          /*     2) to find this point on the curve, we take a step from the previous joint
1817                                           *       a distance given by the proportion that this bone takes
1818                                           */
1819                                         ikData->points[i]= ikData->points[i-1] - (boneLengths[i] / totLength);
1820                                 }
1821                         }
1822                         else {
1823                                 /* 'tip' of chain, special exception for the first joint */
1824                                 ikData->points[0]= 1.0f;
1825                         }
1826                 }
1827                 
1828                 /* spline has now been bound */
1829                 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
1830         }
1831         
1832         /* apply corrections for sensitivity to scaling on a copy of the bind points,
1833          * since it's easier to determine the positions of all the joints beforehand this way
1834          */
1835         if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
1836                 Curve *cu= (Curve *)ikData->tar->data;
1837                 float splineLen, maxScale;
1838                 int i;
1839                 
1840                 /* make a copy of the points array, that we'll store in the tree 
1841                  *      - although we could just multiply the points on the fly, this approach means that
1842                  *        we can introduce per-segment stretchiness later if it is necessary
1843                  */
1844                 jointPoints= MEM_dupallocN(ikData->points);
1845                 free_joints= 1;
1846                 
1847                 /* get the current length of the curve */
1848                 // NOTE: this is assumed to be correct even after the curve was resized
1849                 splineLen= cu->path->totdist;
1850                 
1851                 /* calculate the scale factor to multiply all the path values by so that the 
1852                  * bone chain retains its current length, such that
1853                  *      maxScale * splineLen = totLength
1854                  */
1855                 maxScale = totLength / splineLen;
1856                 
1857                 /* apply scaling correction to all of the temporary points */
1858                 // TODO: this is really not adequate enough on really short chains
1859                 for (i = 0; i < segcount; i++)
1860                         jointPoints[i] *= maxScale;
1861         }
1862         else {
1863                 /* just use the existing points array */
1864                 jointPoints= ikData->points;
1865                 free_joints= 0;
1866         }
1867         
1868         /* make a new Spline-IK chain, and store it in the IK chains */
1869         // TODO: we should check if there is already an IK chain on this, since that would take presidence...
1870         {
1871                 /* make new tree */
1872                 tSplineIK_Tree *tree= MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
1873                 tree->type= CONSTRAINT_TYPE_SPLINEIK;
1874                 
1875                 tree->chainlen= segcount;
1876                 
1877                 /* copy over the array of links to bones in the chain (from tip to root) */
1878                 tree->chain= MEM_callocN(sizeof(bPoseChannel*)*segcount, "SplineIK Chain");
1879                 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel*)*segcount);
1880                 
1881                 /* store reference to joint position array */
1882                 tree->points= jointPoints;
1883                 tree->free_points= free_joints;
1884                 
1885                 /* store references to different parts of the chain */
1886                 tree->root= pchanRoot;
1887                 tree->con= con;
1888                 tree->ikData= ikData;
1889                 
1890                 /* AND! link the tree to the root */
1891                 BLI_addtail(&pchanRoot->iktree, tree);
1892         }
1893         
1894         /* mark root channel having an IK tree */
1895         pchanRoot->flag |= POSE_IKSPLINE;
1896 }
1897
1898 /* Tag which bones are members of Spline IK chains */
1899 static void splineik_init_tree(Scene *scene, Object *ob, float ctime)
1900 {
1901         bPoseChannel *pchan;
1902         
1903         /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
1904         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1905                 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
1906                         splineik_init_tree_from_pchan(scene, ob, pchan);
1907         }
1908 }
1909
1910 /* ----------- */
1911
1912 /* Evaluate spline IK for a given bone */
1913 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan, int index, float ctime)
1914 {
1915         bSplineIKConstraint *ikData= tree->ikData;
1916         float poseHead[3], poseTail[3], poseMat[4][4]; 
1917         float splineVec[3], scaleFac, radius=1.0f;
1918         
1919         /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
1920         where_is_pose_bone(scene, ob, pchan, ctime, 1);
1921         
1922         VECCOPY(poseHead, pchan->pose_head);
1923         VECCOPY(poseTail, pchan->pose_tail);
1924         
1925         /* step 1: determine the positions for the endpoints of the bone */
1926         {
1927                 float vec[4], dir[3], rad;
1928                 float tailBlendFac= 1.0f;
1929                 
1930                 /* determine if the bone should still be affected by SplineIK */
1931                 if (tree->points[index+1] >= 1.0f) {
1932                         /* spline doesn't affect the bone anymore, so done... */
1933                         pchan->flag |= POSE_DONE;
1934                         return;
1935                 }
1936                 else if ((tree->points[index] >= 1.0f) && (tree->points[index+1] < 1.0f)) {
1937                         /* blending factor depends on the amount of the bone still left on the chain */
1938                         tailBlendFac= (1.0f - tree->points[index+1]) / (tree->points[index] - tree->points[index+1]);
1939                 }
1940                 
1941                 /* tail endpoint */
1942                 if ( where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL) ) {
1943                         /* apply curve's object-mode transforms to the position 
1944                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1945                          */
1946                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1947                                 mul_m4_v3(ikData->tar->obmat, vec);
1948                         
1949                         /* convert the position to pose-space, then store it */
1950                         mul_m4_v3(ob->imat, vec);
1951                         interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
1952                         
1953                         /* set the new radius */
1954                         radius= rad;
1955                 }
1956                 
1957                 /* head endpoint */
1958                 if ( where_on_path(ikData->tar, tree->points[index+1], vec, dir, NULL, &rad, NULL) ) {
1959                         /* apply curve's object-mode transforms to the position 
1960                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
1961                          */
1962                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
1963                                 mul_m4_v3(ikData->tar->obmat, vec);
1964                         
1965                         /* store the position, and convert it to pose space */
1966                         mul_m4_v3(ob->imat, vec);
1967                         VECCOPY(poseHead, vec);
1968                         
1969                         /* set the new radius (it should be the average value) */
1970                         radius = (radius+rad) / 2;
1971                 }
1972         }
1973         
1974         /* step 2: determine the implied transform from these endpoints 
1975          *      - splineVec: the vector direction that the spline applies on the bone
1976          *      - scaleFac: the factor that the bone length is scaled by to get the desired amount
1977          */
1978         sub_v3_v3v3(splineVec, poseTail, poseHead);
1979         scaleFac= len_v3(splineVec) / pchan->bone->length;
1980         
1981         /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis 
1982          *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
1983          */
1984         {
1985                 float dmat[3][3], rmat[3][3], tmat[3][3];
1986                 float raxis[3], rangle;
1987                 
1988                 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
1989                  * orientation-relevant axes, and normalising them
1990                  */
1991                 VECCOPY(rmat[0], pchan->pose_mat[0]);
1992                 VECCOPY(rmat[1], pchan->pose_mat[1]);
1993                 VECCOPY(rmat[2], pchan->pose_mat[2]);
1994                 normalize_m3(rmat);
1995                 
1996                 /* also, normalise the orientation imposed by the bone, now that we've extracted the scale factor */
1997                 normalize_v3(splineVec);
1998                 
1999                 /* calculate smallest axis-angle rotation necessary for getting from the
2000                  * current orientation of the bone, to the spline-imposed direction
2001                  */
2002                 cross_v3_v3v3(raxis, rmat[1], splineVec);
2003                 
2004                 rangle= dot_v3v3(rmat[1], splineVec);
2005                 rangle= acos( MAX2(-1.0f, MIN2(1.0f, rangle)) );
2006                 
2007                 /* multiply the magnitude of the angle by the influence of the constraint to 
2008                  * control the influence of the SplineIK effect 
2009                  */
2010                 rangle *= tree->con->enforce;
2011                 
2012                 /* construct rotation matrix from the axis-angle rotation found above 
2013                  *      - this call takes care to make sure that the axis provided is a unit vector first
2014                  */
2015                 axis_angle_to_mat3(dmat, raxis, rangle);
2016                 
2017                 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
2018                  * while still maintaining roll control from the existing bone animation
2019                  */
2020                 mul_m3_m3m3(tmat, dmat, rmat); // m1, m3, m2
2021                 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
2022                 copy_m4_m3(poseMat, tmat);
2023         }
2024         
2025         /* step 4: set the scaling factors for the axes */
2026         {
2027                 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
2028                 mul_v3_fl(poseMat[1], scaleFac);
2029                 
2030                 /* set the scaling factors of the x and z axes from... */
2031                 switch (ikData->xzScaleMode) {
2032                         case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
2033                         {
2034                                 /* original scales get used */
2035                                 float scale;
2036                                 
2037                                 /* x-axis scale */
2038                                 scale= len_v3(pchan->pose_mat[0]);
2039                                 mul_v3_fl(poseMat[0], scale);
2040                                 /* z-axis scale */
2041                                 scale= len_v3(pchan->pose_mat[2]);
2042                                 mul_v3_fl(poseMat[2], scale);
2043                         }
2044                                 break;
2045                         case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
2046                         {
2047                                 /* 'volume preservation' */
2048                                 float scale;
2049                                 
2050                                 /* calculate volume preservation factor which is 
2051                                  * basically the inverse of the y-scaling factor 
2052                                  */
2053                                 if (fabs(scaleFac) != 0.0f) {
2054                                         scale= 1.0 / fabs(scaleFac);
2055                                         
2056                                         /* we need to clamp this within sensible values */
2057                                         // NOTE: these should be fine for now, but should get sanitised in future
2058                                         scale= MIN2( MAX2(scale, 0.0001) , 100000);
2059                                 }
2060                                 else
2061                                         scale= 1.0f;
2062                                 
2063                                 /* apply the scaling */
2064                                 mul_v3_fl(poseMat[0], scale);
2065                                 mul_v3_fl(poseMat[2], scale);
2066                         }
2067                                 break;
2068                 }
2069                 
2070                 /* finally, multiply the x and z scaling by the radius of the curve too, 
2071                  * to allow automatic scales to get tweaked still
2072                  */
2073                 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
2074                         mul_v3_fl(poseMat[0], radius);
2075                         mul_v3_fl(poseMat[2], radius);
2076                 }
2077         }
2078         
2079         /* step 5: set the location of the bone in the matrix */
2080         if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
2081                 /* when the 'no-root' option is affected, the chain can retain
2082                  * the shape but be moved elsewhere
2083                  */
2084                 VECCOPY(poseHead, pchan->pose_head);
2085         }
2086         else if (tree->con->enforce < 1.0f) {
2087                 /* when the influence is too low
2088                  *      - blend the positions for the 'root' bone
2089                  *      - stick to the parent for any other
2090                  */
2091                 if (pchan->parent) {
2092                         VECCOPY(poseHead, pchan->pose_head);
2093                 }
2094                 else {
2095                         // FIXME: this introduces popping artifacts when we reach 0.0
2096                         interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
2097                 }
2098         }
2099         VECCOPY(poseMat[3], poseHead);
2100         
2101         /* finally, store the new transform */
2102         copy_m4_m4(pchan->pose_mat, poseMat);
2103         VECCOPY(pchan->pose_head, poseHead);
2104         VECCOPY(pchan->pose_tail, poseTail);
2105         
2106         /* done! */
2107         pchan->flag |= POSE_DONE;
2108 }
2109
2110 /* Evaluate the chain starting from the nominated bone */
2111 static void splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
2112 {
2113         tSplineIK_Tree *tree;
2114         
2115         /* for each pose-tree, execute it if it is spline, otherwise just free it */
2116         for (tree= pchan_root->iktree.first; tree; tree= pchan_root->iktree.first) {
2117                 /* only evaluate if tagged for Spline IK */
2118                 if (tree->type == CONSTRAINT_TYPE_SPLINEIK) {
2119                         int i;
2120                         
2121                         /* walk over each bone in the chain, calculating the effects of spline IK
2122                          *      - the chain is traversed in the opposite order to storage order (i.e. parent to children)
2123                          *        so that dependencies are correct
2124                          */
2125                         for (i= tree->chainlen-1; i >= 0; i--) {
2126                                 bPoseChannel *pchan= tree->chain[i];
2127                                 splineik_evaluate_bone(tree, scene, ob, pchan, i, ctime);
2128                         }
2129                         
2130                         // TODO: if another pass is needed to ensure the validity of the chain after blending, it should go here
2131                         
2132                         /* free the tree info specific to SplineIK trees now */
2133                         if (tree->chain) MEM_freeN(tree->chain);
2134                         if (tree->free_points) MEM_freeN(tree->points);
2135                 }
2136                 
2137                 /* free this tree */
2138                 BLI_freelinkN(&pchan_root->iktree, tree);
2139         }
2140 }
2141
2142 /* ********************** THE POSE SOLVER ******************* */
2143
2144 /* loc/rot/size to given mat4 */
2145 void pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2146 {
2147         float smat[3][3];
2148         float rmat[3][3];
2149         float tmat[3][3];
2150         
2151         /* get scaling matrix */
2152         size_to_mat3(smat, pchan->size);
2153         
2154         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2155         if (pchan->rotmode > 0) {
2156                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2157                 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2158         }
2159         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2160                 /* axis-angle - not really that great for 3D-changing orientations */
2161                 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2162         }
2163         else {
2164                 /* quats are normalised before use to eliminate scaling issues */
2165                 float quat[4];
2166                 
2167                 /* NOTE: we now don't normalise the stored values anymore, since this was kindof evil in some cases
2168                  * but if this proves to be too problematic, switch back to the old system of operating directly on 
2169                  * the stored copy
2170                  */
2171                 QUATCOPY(quat, pchan->quat);
2172                 normalize_qt(quat);
2173                 quat_to_mat3(rmat, quat);
2174         }
2175         
2176         /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2177         mul_m3_m3m3(tmat, rmat, smat);
2178         copy_m4_m3(chan_mat, tmat);
2179         
2180         /* prevent action channels breaking chains */
2181         /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2182         if ((pchan->bone==NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2183                 VECCOPY(chan_mat[3], pchan->loc);
2184         }
2185 }
2186
2187 /* loc/rot/size to mat4 */
2188 /* used in constraint.c too */
2189 void chan_calc_mat(bPoseChannel *pchan)
2190 {
2191         /* this is just a wrapper around the copy of this function which calculates the matrix 
2192          * and stores the result in any given channel
2193          */
2194         pchan_to_mat4(pchan, pchan->chan_mat);
2195 }
2196
2197 /* NLA strip modifiers */
2198 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2199 {
2200         bActionModifier *amod;
2201         bActionStrip *strip, *strip2;
2202         float scene_cfra= (float)scene->r.cfra;
2203         int do_modif;
2204
2205         for (strip=armob->nlastrips.first; strip; strip=strip->next) {
2206                 do_modif=0;
2207                 
2208                 if (scene_cfra>=strip->start && scene_cfra<=strip->end)
2209                         do_modif=1;
2210                 
2211                 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2212                         do_modif=1;
2213                         
2214                         /* if there are any other strips active, ignore modifiers for this strip - 
2215                          * 'hold' option should only hold action modifiers if there are 
2216                          * no other active strips */
2217                         for (strip2=strip->next; strip2; strip2=strip2->next) {
2218                                 if (strip2 == strip) continue;
2219                                 
2220                                 if (scene_cfra>=strip2->start && scene_cfra<=strip2->end) {
2221                                         if (!(strip2->flag & ACTSTRIP_MUTE))
2222                                                 do_modif=0;
2223                                 }
2224                         }
2225                         
2226                         /* if there are any later, activated, strips with 'hold' set, they take precedence, 
2227                          * so ignore modifiers for this strip */
2228                         for (strip2=strip->next; strip2; strip2=strip2->next) {
2229                                 if (scene_cfra < strip2->start) continue;
2230                                 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2231                                         do_modif=0;
2232                                 }
2233                         }
2234                 }
2235                 
2236                 if (do_modif) {
2237                         /* temporal solution to prevent 2 strips accumulating */
2238                         if(scene_cfra==strip->end && strip->next && strip->next->start==scene_cfra)
2239                                 continue;
2240                         
2241                         for(amod= strip->modifiers.first; amod; amod= amod->next) {
2242                                 switch (amod->type) {
2243                                 case ACTSTRIP_MOD_DEFORM:
2244                                 {
2245                                         /* validate first */
2246                                         if(amod->ob && amod->ob->type==OB_CURVE && amod->channel[0]) {
2247                                                 
2248                                                 if( strcmp(pchan->name, amod->channel)==0 ) {
2249                                                         float mat4[4][4], mat3[3][3];
2250                                                         
2251                                                         curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2252                                                         copy_m4_m4(mat4, pchan->pose_mat);
2253                                                         mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2254                                                         
2255                                                 }
2256                                         }
2257                                 }
2258                                         break;
2259                                 case ACTSTRIP_MOD_NOISE:        
2260                                 {
2261                                         if( strcmp(pchan->name, amod->channel)==0 ) {
2262                                                 float nor[3], loc[3], ofs;
2263                                                 float eul[3], size[3], eulo[3], sizeo[3];
2264                                                 
2265                                                 /* calculate turbulance */
2266                                                 ofs = amod->turbul / 200.0f;
2267                                                 
2268                                                 /* make a copy of starting conditions */
2269                                                 VECCOPY(loc, pchan->pose_mat[3]);
2270                                                 mat4_to_eul( eul,pchan->pose_mat);
2271                                                 mat4_to_size( size,pchan->pose_mat);
2272                                                 VECCOPY(eulo, eul);
2273                                                 VECCOPY(sizeo, size);
2274                                                 
2275                                                 /* apply noise to each set of channels */
2276                                                 if (amod->channels & 4) {
2277                                                         /* for scaling */
2278                                                         nor[0] = BLI_gNoise(amod->noisesize, size[0]+ofs, size[1], size[2], 0, 0) - ofs;
2279                                                         nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1]+ofs, size[2], 0, 0) - ofs;        
2280                                                         nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2]+ofs, 0, 0) - ofs;
2281                                                         add_v3_v3(size, nor);
2282                                                         
2283                                                         if (sizeo[0] != 0)
2284                                                                 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2285                                                         if (sizeo[1] != 0)
2286                                                                 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2287                                                         if (sizeo[2] != 0)
2288                                                                 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2289                                                 }
2290                                                 if (amod->channels & 2) {
2291                                                         /* for rotation */
2292                                                         nor[0] = BLI_gNoise(amod->noisesize, eul[0]+ofs, eul[1], eul[2], 0, 0) - ofs;
2293                                                         nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1]+ofs, eul[2], 0, 0) - ofs;   
2294                                                         nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2]+ofs, 0, 0) - ofs;
2295                                                         
2296                                                         compatible_eul(nor, eulo);
2297                                                         add_v3_v3(eul, nor);
2298                                                         compatible_eul(eul, eulo);
2299                                                         
2300                                                         loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2301                                                 }
2302                                                 if (amod->channels & 1) {
2303                                                         /* for location */
2304                                                         nor[0] = BLI_gNoise(amod->noisesize, loc[0]+ofs, loc[1], loc[2], 0, 0) - ofs;
2305                                                         nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1]+ofs, loc[2], 0, 0) - ofs;   
2306                                                         nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2]+ofs, 0, 0) - ofs;
2307                                                         
2308                                                         add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2309                                                 }
2310                                         }
2311                                 }
2312                                         break;
2313                                 }
2314                         }
2315                 }
2316         }
2317 }
2318
2319
2320 /* The main armature solver, does all constraints excluding IK */
2321 /* pchan is validated, as having bone and parent pointer
2322  * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2323  */
2324 void where_is_pose_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, int do_extra)
2325 {
2326         Bone *bone, *parbone;
2327         bPoseChannel *parchan;
2328         float vec[3];
2329         
2330         /* set up variables for quicker access below */
2331         bone= pchan->bone;
2332         parbone= bone->parent;
2333         parchan= pchan->parent;
2334         
2335         /* this gives a chan_mat with actions (ipos) results */
2336         if(do_extra)    chan_calc_mat(pchan);
2337         else                    unit_m4(pchan->chan_mat);
2338
2339         /* construct the posemat based on PoseChannels, that we do before applying constraints */
2340         /* pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2341         
2342         if(parchan) {
2343                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
2344                 
2345                 /* bone transform itself */
2346                 copy_m4_m3(offs_bone, bone->bone_mat);
2347                 
2348                 /* The bone's root offset (is in the parent's coordinate system) */
2349                 VECCOPY(offs_bone[3], bone->head);
2350                 
2351                 /* Get the length translation of parent (length along y axis) */
2352                 offs_bone[3][1]+= parbone->length;
2353                 
2354                 /* Compose the matrix for this bone  */
2355                 if(bone->flag & BONE_HINGE) {   // uses restposition rotation, but actual position
2356                         float tmat[4][4];
2357                         
2358                         /* the rotation of the parent restposition */
2359                         copy_m4_m4(tmat, parbone->arm_mat);
2360                         mul_serie_m4(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2361                 }
2362                 else if(bone->flag & BONE_NO_SCALE) {
2363                         float orthmat[4][4];
2364                         
2365                         /* do transform, with an ortho-parent matrix */
2366                         copy_m4_m4(orthmat, parchan->pose_mat);
2367                         normalize_m4(orthmat);
2368                         mul_serie_m4(pchan->pose_mat, orthmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2369                 }
2370                 else
2371                         mul_serie_m4(pchan->pose_mat, parchan->pose_mat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
2372                 
2373                 /* in these cases we need to compute location separately */
2374                 if(bone->flag & (BONE_HINGE|BONE_NO_SCALE|BONE_NO_LOCAL_LOCATION)) {
2375                         float bone_loc[3], chan_loc[3];
2376
2377                         mul_v3_m4v3(bone_loc, parchan->pose_mat, offs_bone[3]);
2378                         copy_v3_v3(chan_loc, pchan->chan_mat[3]);
2379
2380                         /* no local location is not transformed by bone matrix */
2381                         if(!(bone->flag & BONE_NO_LOCAL_LOCATION))
2382                                 mul_mat3_m4_v3(offs_bone, chan_loc);
2383
2384                         /* for hinge we use armature instead of pose mat */
2385                         if(bone->flag & BONE_HINGE) mul_mat3_m4_v3(parbone->arm_mat, chan_loc);
2386                         else mul_mat3_m4_v3(parchan->pose_mat, chan_loc);
2387
2388                         add_v3_v3v3(pchan->pose_mat[3], bone_loc, chan_loc);
2389                 }
2390         }
2391         else {
2392                 mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
2393
2394                 /* optional location without arm_mat rotation */
2395                 if(bone->flag & BONE_NO_LOCAL_LOCATION)
2396                         add_v3_v3v3(pchan->pose_mat[3], bone->arm_mat[3], pchan->chan_mat[3]);
2397                 
2398                 /* only rootbones get the cyclic offset (unless user doesn't want that) */
2399                 if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2400                         add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2401         }
2402         
2403         if(do_extra) {
2404                 /* do NLA strip modifiers - i.e. curve follow */
2405                 do_strip_modifiers(scene, ob, bone, pchan);
2406                 
2407                 /* Do constraints */
2408                 if (pchan->constraints.first) {
2409                         bConstraintOb *cob;
2410
2411                         /* make a copy of location of PoseChannel for later */
2412                         VECCOPY(vec, pchan->pose_mat[3]);
2413
2414                         /* prepare PoseChannel for Constraint solving
2415                          * - makes a copy of matrix, and creates temporary struct to use
2416                          */
2417                         cob= constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2418
2419                         /* Solve PoseChannel's Constraints */
2420                         solve_constraints(&pchan->constraints, cob, ctime);     // ctime doesnt alter objects
2421
2422                         /* cleanup after Constraint Solving
2423                          * - applies matrix back to pchan, and frees temporary struct used
2424                          */
2425                         constraints_clear_evalob(cob);
2426
2427                         /* prevent constraints breaking a chain */
2428                         if(pchan->bone->flag & BONE_CONNECTED) {
2429                                 VECCOPY(pchan->pose_mat[3], vec);
2430                         }
2431                 }
2432         }
2433         
2434         /* calculate head */
2435         VECCOPY(pchan->pose_head, pchan->pose_mat[3]);
2436         /* calculate tail */
2437         VECCOPY(vec, pchan->pose_mat[1]);
2438         mul_v3_fl(vec, bone->length);
2439         add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2440 }
2441
2442 /* This only reads anim data from channels, and writes to channels */
2443 /* This is the only function adding poses */
2444 void where_is_pose (Scene *scene, Object *ob)
2445 {
2446         bArmature *arm;
2447         Bone *bone;
2448         bPoseChannel *pchan;
2449         float imat[4][4];
2450         float ctime;
2451         
2452         if(ob->type!=OB_ARMATURE) return;
2453         arm = ob->data;
2454         
2455         if(ELEM(NULL, arm, scene)) return;
2456         if((ob->pose==NULL) || (ob->pose->flag & POSE_RECALC)) 
2457            armature_rebuild_pose(ob, arm);
2458            
2459         ctime= bsystem_time(scene, ob, (float)scene->r.cfra, 0.0);      /* not accurate... */
2460         
2461         /* In editmode or restposition we read the data from the bones */
2462         if(arm->edbo || (arm->flag & ARM_RESTPOS)) {
2463                 
2464                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2465                         bone= pchan->bone;
2466                         if(bone) {
2467                                 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2468                                 VECCOPY(pchan->pose_head, bone->arm_head);
2469                                 VECCOPY(pchan->pose_tail, bone->arm_tail);
2470                         }
2471                 }
2472         }
2473         else {
2474                 invert_m4_m4(ob->imat, ob->obmat);      // imat is needed 
2475                 
2476                 /* 1. clear flags */
2477                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2478                         pchan->flag &= ~(POSE_DONE|POSE_CHAIN|POSE_IKTREE|POSE_IKSPLINE);
2479                 }
2480                 
2481                 /* 2a. construct the IK tree (standard IK) */
2482                 BIK_initialize_tree(scene, ob, ctime);
2483                 
2484                 /* 2b. construct the Spline IK trees 
2485                  *  - this is not integrated as an IK plugin, since it should be able
2486                  *        to function in conjunction with standard IK
2487                  */
2488                 splineik_init_tree(scene, ob, ctime);
2489                 
2490                 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2491                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2492                         /* 4a. if we find an IK root, we handle it separated */
2493                         if(pchan->flag & POSE_IKTREE) {
2494                                 BIK_execute_tree(scene, ob, pchan, ctime);
2495                         }
2496                         /* 4b. if we find a Spline IK root, we handle it separated too */
2497                         else if(pchan->flag & POSE_IKSPLINE) {
2498                                 splineik_execute_tree(scene, ob, pchan, ctime);
2499                         }
2500                         /* 5. otherwise just call the normal solver */
2501                         else if(!(pchan->flag & POSE_DONE)) {
2502                                 where_is_pose_bone(scene, ob, pchan, ctime, 1);
2503                         }
2504                 }
2505                 /* 6. release the IK tree */
2506                 BIK_release_tree(scene, ob, ctime);
2507         }
2508                 
2509         /* calculating deform matrices */
2510         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2511                 if(pchan->bone) {
2512                         invert_m4_m4(imat, pchan->bone->arm_mat);
2513                         mul_m4_m4m4(pchan->chan_mat, imat, pchan->pose_mat);
2514                 }
2515         }
2516 }