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