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