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