afc5a972a65bae05760dde4729c6b0407dae3241
[blender-staging.git] / source / blender / blenkernel / intern / armature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <math.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <float.h>
34
35 #include "MEM_guardedalloc.h"
36
37 //XXX #include "nla.h"
38
39 #include "BLI_arithb.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_cellalloc.h"
42
43 #include "DNA_armature_types.h"
44 #include "DNA_action_types.h"
45 #include "DNA_constraint_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_lattice_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_nla_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_view3d_types.h"
53
54 #include "BKE_armature.h"
55 #include "BKE_action.h"
56 #include "BKE_blender.h"
57 #include "BKE_constraint.h"
58 #include "BKE_curve.h"
59 #include "BKE_deform.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_DerivedMesh.h"
62 #include "BKE_displist.h"
63 #include "BKE_global.h"
64 #include "BKE_library.h"
65 #include "BKE_lattice.h"
66 #include "BKE_main.h"
67 #include "BKE_object.h"
68 #include "BKE_object.h"
69 #include "BKE_utildefines.h"
70 #include "BIK_api.h"
71 #include "BKE_sketch.h"
72
73 #ifdef HAVE_CONFIG_H
74 #include <config.h>
75 #endif
76
77 /*      **************** Generic Functions, data level *************** */
78
79 bArmature *add_armature(char *name)
80 {
81         bArmature *arm;
82         
83         arm= alloc_libblock (&G.main->armature, ID_AR, name);
84         arm->deformflag = ARM_DEF_VGROUP|ARM_DEF_ENVELOPE;
85         arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
86         arm->layer= 1;
87         return arm;
88 }
89
90 bArmature *get_armature(Object *ob)
91 {
92         if(ob->type==OB_ARMATURE)
93                 return (bArmature *)ob->data;
94         return NULL;
95 }
96
97 void free_boneChildren(Bone *bone)
98
99         Bone *child;
100         
101         if (bone) {
102                 
103                 child=bone->childbase.first;
104                 if (child){
105                         while (child){
106                                 free_boneChildren (child);
107                                 child=child->next;
108                         }
109                         BLI_freelistN (&bone->childbase);
110                 }
111         }
112 }
113
114 void free_bones (bArmature *arm)
115 {
116         Bone *bone;
117         /*      Free children (if any)  */
118         bone= arm->bonebase.first;
119         if (bone) {
120                 while (bone){
121                         free_boneChildren (bone);
122                         bone=bone->next;
123                 }
124         }
125         
126         
127         BLI_freelistN(&arm->bonebase);
128 }
129
130 void free_armature(bArmature *arm)
131 {
132         if (arm) {
133                 free_bones(arm);
134                 
135                 /* free editmode data */
136                 if (arm->edbo) {
137                         BLI_freelistN(arm->edbo);
138                         
139                         MEM_freeN(arm->edbo);
140                         arm->edbo= NULL;
141                 }
142
143                 /* free sketch */
144                 if (arm->sketch) {
145                         freeSketch(arm->sketch);
146                         arm->sketch = NULL;
147                 }
148         }
149 }
150
151 void make_local_armature(bArmature *arm)
152 {
153         int local=0, lib=0;
154         Object *ob;
155         bArmature *newArm;
156         
157         if (arm->id.lib==0)
158                 return;
159         if (arm->id.us==1) {
160                 arm->id.lib= 0;
161                 arm->id.flag= LIB_LOCAL;
162                 new_id(0, (ID*)arm, 0);
163                 return;
164         }
165         
166         if(local && lib==0) {
167                 arm->id.lib= 0;
168                 arm->id.flag= LIB_LOCAL;
169                 new_id(0, (ID *)arm, 0);
170         }
171         else if(local && lib) {
172                 newArm= copy_armature(arm);
173                 newArm->id.us= 0;
174                 
175                 ob= G.main->object.first;
176                 while(ob) {
177                         if(ob->data==arm) {
178                                 
179                                 if(ob->id.lib==0) {
180                                         ob->data= newArm;
181                                         newArm->id.us++;
182                                         arm->id.us--;
183                                 }
184                         }
185                         ob= ob->id.next;
186                 }
187         }
188 }
189
190 static void     copy_bonechildren (Bone* newBone, Bone* oldBone)
191 {
192         Bone    *curBone, *newChildBone;
193         
194         /*      Copy this bone's list*/
195         BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
196         
197         /*      For each child in the list, update it's children*/
198         newChildBone=newBone->childbase.first;
199         for (curBone=oldBone->childbase.first;curBone;curBone=curBone->next){
200                 newChildBone->parent=newBone;
201                 copy_bonechildren(newChildBone,curBone);
202                 newChildBone=newChildBone->next;
203         }
204 }
205
206 bArmature *copy_armature(bArmature *arm)
207 {
208         bArmature *newArm;
209         Bone            *oldBone, *newBone;
210         
211         newArm= copy_libblock (arm);
212         BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
213         
214         /*      Duplicate the childrens' lists*/
215         newBone=newArm->bonebase.first;
216         for (oldBone=arm->bonebase.first;oldBone;oldBone=oldBone->next){
217                 newBone->parent=NULL;
218                 copy_bonechildren (newBone, oldBone);
219                 newBone=newBone->next;
220         };
221         
222         return newArm;
223 }
224
225 static Bone *get_named_bone_bonechildren (Bone *bone, const char *name)
226 {
227         Bone *curBone, *rbone;
228         
229         if (!strcmp (bone->name, name))
230                 return bone;
231         
232         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
233                 rbone=get_named_bone_bonechildren (curBone, name);
234                 if (rbone)
235                         return rbone;
236         }
237         
238         return NULL;
239 }
240
241
242 Bone *get_named_bone (bArmature *arm, const char *name)
243 /*
244         Walk the list until the bone is found
245  */
246 {
247         Bone *bone=NULL, *curBone;
248         
249         if (!arm) return NULL;
250         
251         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
252                 bone = get_named_bone_bonechildren (curBone, name);
253                 if (bone)
254                         return bone;
255         }
256         
257         return bone;
258 }
259
260
261 #define IS_SEPARATOR(a) (a=='.' || a==' ' || a=='-' || a=='_')
262
263 /* finds the best possible flipped name. For renaming; check for unique names afterwards */
264 /* if strip_number: removes number extensions */
265 void bone_flip_name (char *name, int strip_number)
266 {
267         int             len;
268         char    prefix[128]={""};       /* The part before the facing */
269         char    suffix[128]={""};       /* The part after the facing */
270         char    replace[128]={""};      /* The replacement string */
271         char    number[128]={""};       /* The number extension string */
272         char    *index=NULL;
273
274         len= strlen(name);
275         if(len<3) return;       // we don't do names like .R or .L
276
277         /* We first check the case with a .### extension, let's find the last period */
278         if(isdigit(name[len-1])) {
279                 index= strrchr(name, '.');      // last occurrance
280                 if (index && isdigit(index[1]) ) {              // doesnt handle case bone.1abc2 correct..., whatever!
281                         if(strip_number==0) 
282                                 strcpy(number, index);
283                         *index= 0;
284                         len= strlen(name);
285                 }
286         }
287
288         strcpy (prefix, name);
289
290         /* first case; separator . - _ with extensions r R l L  */
291         if( IS_SEPARATOR(name[len-2]) ) {
292                 switch(name[len-1]) {
293                         case 'l':
294                                 prefix[len-1]= 0;
295                                 strcpy(replace, "r");
296                                 break;
297                         case 'r':
298                                 prefix[len-1]= 0;
299                                 strcpy(replace, "l");
300                                 break;
301                         case 'L':
302                                 prefix[len-1]= 0;
303                                 strcpy(replace, "R");
304                                 break;
305                         case 'R':
306                                 prefix[len-1]= 0;
307                                 strcpy(replace, "L");
308                                 break;
309                 }
310         }
311         /* case; beginning with r R l L , with separator after it */
312         else if( IS_SEPARATOR(name[1]) ) {
313                 switch(name[0]) {
314                         case 'l':
315                                 strcpy(replace, "r");
316                                 strcpy(suffix, name+1);
317                                 prefix[0]= 0;
318                                 break;
319                         case 'r':
320                                 strcpy(replace, "l");
321                                 strcpy(suffix, name+1);
322                                 prefix[0]= 0;
323                                 break;
324                         case 'L':
325                                 strcpy(replace, "R");
326                                 strcpy(suffix, name+1);
327                                 prefix[0]= 0;
328                                 break;
329                         case 'R':
330                                 strcpy(replace, "L");
331                                 strcpy(suffix, name+1);
332                                 prefix[0]= 0;
333                                 break;
334                 }
335         }
336         else if(len > 5) {
337                 /* hrms, why test for a separator? lets do the rule 'ultimate left or right' */
338                 index = BLI_strcasestr(prefix, "right");
339                 if (index==prefix || index==prefix+len-5) {
340                         if(index[0]=='r') 
341                                 strcpy (replace, "left");
342                         else {
343                                 if(index[1]=='I') 
344                                         strcpy (replace, "LEFT");
345                                 else
346                                         strcpy (replace, "Left");
347                         }
348                         *index= 0;
349                         strcpy (suffix, index+5);
350                 }
351                 else {
352                         index = BLI_strcasestr(prefix, "left");
353                         if (index==prefix || index==prefix+len-4) {
354                                 if(index[0]=='l') 
355                                         strcpy (replace, "right");
356                                 else {
357                                         if(index[1]=='E') 
358                                                 strcpy (replace, "RIGHT");
359                                         else
360                                                 strcpy (replace, "Right");
361                                 }
362                                 *index= 0;
363                                 strcpy (suffix, index+4);
364                         }
365                 }               
366         }
367
368         sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
369 }
370
371 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for unique names afterwards)
372  * This assumes that bone names are at most 32 chars long!
373  *      strip_number: removes number extensions  (TODO: not used)
374  *      axis: the axis to name on
375  *      head/tail: the head/tail co-ordinate of the bone on the specified axis
376  */
377 void bone_autoside_name (char *name, int strip_number, short axis, float head, float tail)
378 {
379         unsigned int len;
380         char    basename[32]={""};
381         char    extension[5]={""};
382
383         len= strlen(name);
384         if (len == 0) return;
385         strcpy(basename, name);
386         
387         /* Figure out extension to append: 
388          *      - The extension to append is based upon the axis that we are working on.
389          *      - If head happens to be on 0, then we must consider the tail position as well to decide
390          *        which side the bone is on
391          *              -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
392          *              -> Otherwise, extension is added from perspective of object based on which side tail goes to
393          *      - If head is non-zero, extension is added from perspective of object based on side head is on
394          */
395         if (axis == 2) {
396                 /* z-axis - vertical (top/bottom) */
397                 if (IS_EQ(head, 0)) {
398                         if (tail < 0)
399                                 strcpy(extension, "Bot");
400                         else if (tail > 0)
401                                 strcpy(extension, "Top");
402                 }
403                 else {
404                         if (head < 0)
405                                 strcpy(extension, "Bot");
406                         else
407                                 strcpy(extension, "Top");
408                 }
409         }
410         else if (axis == 1) {
411                 /* y-axis - depth (front/back) */
412                 if (IS_EQ(head, 0)) {
413                         if (tail < 0)
414                                 strcpy(extension, "Fr");
415                         else if (tail > 0)
416                                 strcpy(extension, "Bk");
417                 }
418                 else {
419                         if (head < 0)
420                                 strcpy(extension, "Fr");
421                         else
422                                 strcpy(extension, "Bk");
423                 }
424         }
425         else {
426                 /* x-axis - horizontal (left/right) */
427                 if (IS_EQ(head, 0)) {
428                         if (tail < 0)
429                                 strcpy(extension, "R");
430                         else if (tail > 0)
431                                 strcpy(extension, "L");
432                 }
433                 else {
434                         if (head < 0)
435                                 strcpy(extension, "R");
436                         else if (head > 0)
437                                 strcpy(extension, "L");
438                 }
439         }
440
441         /* Simple name truncation 
442          *      - truncate if there is an extension and it wouldn't be able to fit
443          *      - otherwise, just append to end
444          */
445         if (extension[0]) {
446                 int change = 1;
447                 
448                 while (change) { /* remove extensions */
449                         change = 0;
450                         if (len > 2 && basename[len-2]=='.') {
451                                 if (basename[len-1]=='L' || basename[len-1] == 'R' ) { /* L R */
452                                         basename[len-2] = '\0';
453                                         len-=2;
454                                         change= 1;
455                                 }
456                         } else if (len > 3 && basename[len-3]=='.') {
457                                 if (    (basename[len-2]=='F' && basename[len-1] == 'r') ||     /* Fr */
458                                                 (basename[len-2]=='B' && basename[len-1] == 'k')        /* Bk */
459                                 ) {
460                                         basename[len-3] = '\0';
461                                         len-=3;
462                                         change= 1;
463                                 }
464                         } else if (len > 4 && basename[len-4]=='.') {
465                                 if (    (basename[len-3]=='T' && basename[len-2]=='o' && basename[len-1] == 'p') ||     /* Top */
466                                                 (basename[len-3]=='B' && basename[len-2]=='o' && basename[len-1] == 't')        /* Bot */
467                                 ) {
468                                         basename[len-4] = '\0';
469                                         len-=4;
470                                         change= 1;
471                                 }
472                         }
473                 }
474                 
475                 if ((32 - len) < strlen(extension) + 1) { /* add 1 for the '.' */
476                         strncpy(name, basename, len-strlen(extension));
477                 }
478         }
479
480         sprintf(name, "%s.%s", basename, extension);
481 }
482
483 /* ************* B-Bone support ******************* */
484
485 #define MAX_BBONE_SUBDIV        32
486
487 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
488 static void equalize_bezier(float *data, int desired)
489 {
490         float *fp, totdist, ddist, dist, fac1, fac2;
491         float pdist[MAX_BBONE_SUBDIV+1];
492         float temp[MAX_BBONE_SUBDIV+1][4];
493         int a, nr;
494         
495         pdist[0]= 0.0f;
496         for(a=0, fp= data; a<MAX_BBONE_SUBDIV; a++, fp+=4) {
497                 QUATCOPY(temp[a], fp);
498                 pdist[a+1]= pdist[a]+VecLenf(fp, fp+4);
499         }
500         /* do last point */
501         QUATCOPY(temp[a], fp);
502         totdist= pdist[a];
503         
504         /* go over distances and calculate new points */
505         ddist= totdist/((float)desired);
506         nr= 1;
507         for(a=1, fp= data+4; a<desired; a++, fp+=4) {
508                 
509                 dist= ((float)a)*ddist;
510                 
511                 /* we're looking for location (distance) 'dist' in the array */
512                 while((dist>= pdist[nr]) && nr<MAX_BBONE_SUBDIV) {
513                         nr++;
514                 }
515                 
516                 fac1= pdist[nr]- pdist[nr-1];
517                 fac2= pdist[nr]-dist;
518                 fac1= fac2/fac1;
519                 fac2= 1.0f-fac1;
520                 
521                 fp[0]= fac1*temp[nr-1][0]+ fac2*temp[nr][0];
522                 fp[1]= fac1*temp[nr-1][1]+ fac2*temp[nr][1];
523                 fp[2]= fac1*temp[nr-1][2]+ fac2*temp[nr][2];
524                 fp[3]= fac1*temp[nr-1][3]+ fac2*temp[nr][3];
525         }
526         /* set last point, needed for orientation calculus */
527         QUATCOPY(fp, temp[MAX_BBONE_SUBDIV]);
528 }
529
530 /* returns pointer to static array, filled with desired amount of bone->segments elements */
531 /* this calculation is done  within unit bone space */
532 Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
533 {
534         static Mat4 bbone_array[MAX_BBONE_SUBDIV];
535         static Mat4 bbone_rest_array[MAX_BBONE_SUBDIV];
536         Mat4 *result_array= (rest)? bbone_rest_array: bbone_array;
537         bPoseChannel *next, *prev;
538         Bone *bone= pchan->bone;
539         float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1=0.0f, roll2;
540         float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
541         float data[MAX_BBONE_SUBDIV+1][4], *fp;
542         int a, doscale= 0;
543
544         length= bone->length;
545
546         if(!rest) {
547                 /* check if we need to take non-uniform bone scaling into account */
548                 scale[0]= VecLength(pchan->pose_mat[0]);
549                 scale[1]= VecLength(pchan->pose_mat[1]);
550                 scale[2]= VecLength(pchan->pose_mat[2]);
551
552                 if(fabs(scale[0] - scale[1]) > 1e-6f || fabs(scale[1] - scale[2]) > 1e-6f) {
553                         Mat4One(scalemat);
554                         scalemat[0][0]= scale[0];
555                         scalemat[1][1]= scale[1];
556                         scalemat[2][2]= scale[2];
557                         Mat4Invert(iscalemat, scalemat);
558
559                         length *= scale[1];
560                         doscale = 1;
561                 }
562         }
563         
564         hlength1= bone->ease1*length*0.390464f;         // 0.5*sqrt(2)*kappa, the handle length for near-perfect circles
565         hlength2= bone->ease2*length*0.390464f;
566         
567         /* evaluate next and prev bones */
568         if(bone->flag & BONE_CONNECTED)
569                 prev= pchan->parent;
570         else
571                 prev= NULL;
572         
573         next= pchan->child;
574         
575         /* find the handle points, since this is inside bone space, the 
576                 first point = (0,0,0)
577                 last point =  (0, length, 0) */
578         
579         if(rest) {
580                 Mat4Invert(imat, pchan->bone->arm_mat);
581         }
582         else if(doscale) {
583                 Mat4CpyMat4(posemat, pchan->pose_mat);
584                 Mat4Ortho(posemat);
585                 Mat4Invert(imat, posemat);
586         }
587         else
588                 Mat4Invert(imat, pchan->pose_mat);
589         
590         if(prev) {
591                 float difmat[4][4], result[3][3], imat3[3][3];
592
593                 /* transform previous point inside this bone space */
594                 if(rest)
595                         VECCOPY(h1, prev->bone->arm_head)
596                 else
597                         VECCOPY(h1, prev->pose_head)
598                 Mat4MulVecfl(imat, h1);
599
600                 if(prev->bone->segments>1) {
601                         /* if previous bone is B-bone too, use average handle direction */
602                         h1[1]-= length;
603                         roll1= 0.0f;
604                 }
605
606                 Normalize(h1);
607                 VecMulf(h1, -hlength1);
608
609                 if(prev->bone->segments==1) {
610                         /* find the previous roll to interpolate */
611                         if(rest)
612                                 Mat4MulMat4(difmat, prev->bone->arm_mat, imat);
613                         else
614                                 Mat4MulMat4(difmat, prev->pose_mat, imat);
615                         Mat3CpyMat4(result, difmat);                            // the desired rotation at beginning of next bone
616                         
617                         vec_roll_to_mat3(h1, 0.0f, mat3);                       // the result of vec_roll without roll
618                         
619                         Mat3Inv(imat3, mat3);
620                         Mat3MulMat3(mat3, result, imat3);                       // the matrix transforming vec_roll to desired roll
621                         
622                         roll1= (float)atan2(mat3[2][0], mat3[2][2]);
623                 }
624         }
625         else {
626                 h1[0]= 0.0f; h1[1]= hlength1; h1[2]= 0.0f;
627                 roll1= 0.0f;
628         }
629         if(next) {
630                 float difmat[4][4], result[3][3], imat3[3][3];
631                 
632                 /* transform next point inside this bone space */
633                 if(rest)
634                         VECCOPY(h2, next->bone->arm_tail)
635                 else
636                         VECCOPY(h2, next->pose_tail)
637                 Mat4MulVecfl(imat, h2);
638                 /* if next bone is B-bone too, use average handle direction */
639                 if(next->bone->segments>1);
640                 else h2[1]-= length;
641                 Normalize(h2);
642                 
643                 /* find the next roll to interpolate as well */
644                 if(rest)
645                         Mat4MulMat4(difmat, next->bone->arm_mat, imat);
646                 else
647                         Mat4MulMat4(difmat, next->pose_mat, imat);
648                 Mat3CpyMat4(result, difmat);                            // the desired rotation at beginning of next bone
649                 
650                 vec_roll_to_mat3(h2, 0.0f, mat3);                       // the result of vec_roll without roll
651                 
652                 Mat3Inv(imat3, mat3);
653                 Mat3MulMat3(mat3, imat3, result);                       // the matrix transforming vec_roll to desired roll
654                 
655                 roll2= (float)atan2(mat3[2][0], mat3[2][2]);
656                 
657                 /* and only now negate handle */
658                 VecMulf(h2, -hlength2);
659         }
660         else {
661                 h2[0]= 0.0f; h2[1]= -hlength2; h2[2]= 0.0f;
662                 roll2= 0.0;
663         }
664
665         /* make curve */
666         if(bone->segments > MAX_BBONE_SUBDIV)
667                 bone->segments= MAX_BBONE_SUBDIV;
668         
669         forward_diff_bezier(0.0, h1[0],         h2[0],                  0.0,            data[0],        MAX_BBONE_SUBDIV, 4*sizeof(float));
670         forward_diff_bezier(0.0, h1[1],         length + h2[1], length,         data[0]+1,      MAX_BBONE_SUBDIV, 4*sizeof(float));
671         forward_diff_bezier(0.0, h1[2],         h2[2],                  0.0,            data[0]+2,      MAX_BBONE_SUBDIV, 4*sizeof(float));
672         forward_diff_bezier(roll1, roll1 + 0.390464f*(roll2-roll1), roll2 - 0.390464f*(roll2-roll1),    roll2,  data[0]+3,      MAX_BBONE_SUBDIV, 4*sizeof(float));
673         
674         equalize_bezier(data[0], bone->segments);       // note: does stride 4!
675         
676         /* make transformation matrices for the segments for drawing */
677         for(a=0, fp= data[0]; a<bone->segments; a++, fp+=4) {
678                 VecSubf(h1, fp+4, fp);
679                 vec_roll_to_mat3(h1, fp[3], mat3);              // fp[3] is roll
680
681                 Mat4CpyMat3(result_array[a].mat, mat3);
682                 VECCOPY(result_array[a].mat[3], fp);
683
684                 if(doscale) {
685                         /* correct for scaling when this matrix is used in scaled space */
686                         Mat4MulSerie(result_array[a].mat, iscalemat, result_array[a].mat,
687                                 scalemat, NULL, NULL, NULL, NULL, NULL);
688                 }
689         }
690         
691         return result_array;
692 }
693
694 /* ************ Armature Deform ******************* */
695
696 static void pchan_b_bone_defmats(bPoseChannel *pchan, int use_quaternion, int rest_def)
697 {
698         Bone *bone= pchan->bone;
699         Mat4 *b_bone= b_bone_spline_setup(pchan, 0);
700         Mat4 *b_bone_rest= (rest_def)? NULL: b_bone_spline_setup(pchan, 1);
701         Mat4 *b_bone_mats;
702         DualQuat *b_bone_dual_quats= NULL;
703         float tmat[4][4];
704         int a;
705         
706         /* allocate b_bone matrices and dual quats */
707         b_bone_mats= MEM_mallocN((1+bone->segments)*sizeof(Mat4), "BBone defmats");
708         pchan->b_bone_mats= b_bone_mats;
709
710         if(use_quaternion) {
711                 b_bone_dual_quats= MEM_mallocN((bone->segments)*sizeof(DualQuat), "BBone dqs");
712                 pchan->b_bone_dual_quats= b_bone_dual_quats;
713         }
714         
715         /* first matrix is the inverse arm_mat, to bring points in local bone space
716            for finding out which segment it belongs to */
717         Mat4Invert(b_bone_mats[0].mat, bone->arm_mat);
718
719         /* then we make the b_bone_mats:
720             - first transform to local bone space
721                 - translate over the curve to the bbone mat space
722                 - transform with b_bone matrix
723                 - transform back into global space */
724         Mat4One(tmat);
725
726         for(a=0; a<bone->segments; a++) {
727                 if(b_bone_rest)
728                         Mat4Invert(tmat, b_bone_rest[a].mat);
729                 else
730                         tmat[3][1] = -a*(bone->length/(float)bone->segments);
731
732                 Mat4MulSerie(b_bone_mats[a+1].mat, pchan->chan_mat, bone->arm_mat,
733                         b_bone[a].mat, tmat, b_bone_mats[0].mat, NULL, NULL, NULL);
734
735                 if(use_quaternion)
736                         Mat4ToDQuat(bone->arm_mat, b_bone_mats[a+1].mat, &b_bone_dual_quats[a]);
737         }
738 }
739
740 static void b_bone_deform(bPoseChannel *pchan, Bone *bone, float *co, DualQuat *dq, float defmat[][3])
741 {
742         Mat4 *b_bone= pchan->b_bone_mats;
743         float (*mat)[4]= b_bone[0].mat;
744         float segment, y;
745         int a;
746         
747         /* need to transform co back to bonespace, only need y */
748         y= mat[0][1]*co[0] + mat[1][1]*co[1] + mat[2][1]*co[2] + mat[3][1];
749         
750         /* now calculate which of the b_bones are deforming this */
751         segment= bone->length/((float)bone->segments);
752         a= (int)(y/segment);
753         
754         /* note; by clamping it extends deform at endpoints, goes best with
755            straight joints in restpos. */
756         CLAMP(a, 0, bone->segments-1);
757
758         if(dq) {
759                 DQuatCpyDQuat(dq, &((DualQuat*)pchan->b_bone_dual_quats)[a]);
760         }
761         else {
762                 Mat4MulVecfl(b_bone[a+1].mat, co);
763
764                 if(defmat)
765                         Mat3CpyMat4(defmat, b_bone[a+1].mat);
766         }
767 }
768
769 /* using vec with dist to bone b1 - b2 */
770 float distfactor_to_bone (float vec[3], float b1[3], float b2[3], float rad1, float rad2, float rdist)
771 {
772         float dist=0.0f; 
773         float bdelta[3];
774         float pdelta[3];
775         float hsqr, a, l, rad;
776         
777         VecSubf (bdelta, b2, b1);
778         l = Normalize (bdelta);
779         
780         VecSubf (pdelta, vec, b1);
781         
782         a = bdelta[0]*pdelta[0] + bdelta[1]*pdelta[1] + bdelta[2]*pdelta[2];
783         hsqr = ((pdelta[0]*pdelta[0]) + (pdelta[1]*pdelta[1]) + (pdelta[2]*pdelta[2]));
784         
785         if (a < 0.0F){
786                 /* If we're past the end of the bone, do a spherical field attenuation thing */
787                 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])) ;
788                 rad= rad1;
789         }
790         else if (a > l){
791                 /* If we're past the end of the bone, do a spherical field attenuation thing */
792                 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])) ;
793                 rad= rad2;
794         }
795         else {
796                 dist= (hsqr - (a*a));
797                 
798                 if(l!=0.0f) {
799                         rad= a/l;
800                         rad= rad*rad2 + (1.0f-rad)*rad1;
801                 }
802                 else rad= rad1;
803         }
804         
805         a= rad*rad;
806         if(dist < a) 
807                 return 1.0f;
808         else {
809                 l= rad+rdist;
810                 l*= l;
811                 if(rdist==0.0f || dist >= l) 
812                         return 0.0f;
813                 else {
814                         a= (float)sqrt(dist)-rad;
815                         return 1.0f-( a*a )/( rdist*rdist );
816                 }
817         }
818 }
819
820 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[][3], float mat[][3])
821 {
822         float wmat[3][3];
823
824         if(pchan->bone->segments>1)
825                 Mat3CpyMat3(wmat, bbonemat);
826         else
827                 Mat3CpyMat4(wmat, pchan->chan_mat);
828
829         Mat3MulFloat((float*)wmat, weight);
830         Mat3AddMat3(mat, mat, wmat);
831 }
832
833 static float dist_bone_deform(bPoseChannel *pchan, float *vec, DualQuat *dq, float mat[][3], float *co)
834 {
835         Bone *bone= pchan->bone;
836         float fac, contrib=0.0;
837         float cop[3], bbonemat[3][3];
838         DualQuat bbonedq;
839
840         if(bone==NULL) return 0.0f;
841         
842         VECCOPY (cop, co);
843
844         fac= distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
845         
846         if (fac>0.0) {
847                 
848                 fac*=bone->weight;
849                 contrib= fac;
850                 if(contrib>0.0) {
851                         if(vec) {
852                                 if(bone->segments>1)
853                                         // applies on cop and bbonemat
854                                         b_bone_deform(pchan, bone, cop, NULL, (mat)?bbonemat:NULL);
855                                 else
856                                         Mat4MulVecfl(pchan->chan_mat, cop);
857
858                                 //      Make this a delta from the base position
859                                 VecSubf (cop, cop, co);
860                                 cop[0]*=fac; cop[1]*=fac; cop[2]*=fac;
861                                 VecAddf (vec, vec, cop);
862
863                                 if(mat)
864                                         pchan_deform_mat_add(pchan, fac, bbonemat, mat);
865                         }
866                         else {
867                                 if(bone->segments>1) {
868                                         b_bone_deform(pchan, bone, cop, &bbonedq, NULL);
869                                         DQuatAddWeighted(dq, &bbonedq, fac);
870                                 }
871                                 else
872                                         DQuatAddWeighted(dq, pchan->dual_quat, fac);
873                         }
874                 }
875         }
876         
877         return contrib;
878 }
879
880 static void pchan_bone_deform(bPoseChannel *pchan, float weight, float *vec, DualQuat *dq, float mat[][3], float *co, float *contrib)
881 {
882         float cop[3], bbonemat[3][3];
883         DualQuat bbonedq;
884
885         if (!weight)
886                 return;
887
888         VECCOPY(cop, co);
889
890         if(vec) {
891                 if(pchan->bone->segments>1)
892                         // applies on cop and bbonemat
893                         b_bone_deform(pchan, pchan->bone, cop, NULL, (mat)?bbonemat:NULL);
894                 else
895                         Mat4MulVecfl(pchan->chan_mat, cop);
896                 
897                 vec[0]+=(cop[0]-co[0])*weight;
898                 vec[1]+=(cop[1]-co[1])*weight;
899                 vec[2]+=(cop[2]-co[2])*weight;
900
901                 if(mat)
902                         pchan_deform_mat_add(pchan, weight, bbonemat, mat);
903         }
904         else {
905                 if(pchan->bone->segments>1) {
906                         b_bone_deform(pchan, pchan->bone, cop, &bbonedq, NULL);
907                         DQuatAddWeighted(dq, &bbonedq, weight);
908                 }
909                 else
910                         DQuatAddWeighted(dq, pchan->dual_quat, weight);
911         }
912
913         (*contrib)+=weight;
914 }
915
916 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm,
917                            float (*vertexCos)[3], float (*defMats)[3][3],
918                                                    int numVerts, int deformflag, 
919                                                    float (*prevCos)[3], const char *defgrp_name)
920 {
921         bArmature *arm= armOb->data;
922         bPoseChannel *pchan, **defnrToPC = NULL;
923         MDeformVert *dverts = NULL;
924         bDeformGroup *dg;
925         DualQuat *dualquats= NULL;
926         float obinv[4][4], premat[4][4], postmat[4][4];
927         int use_envelope = deformflag & ARM_DEF_ENVELOPE;
928         int use_quaternion = deformflag & ARM_DEF_QUATERNION;
929         int bbone_rest_def = deformflag & ARM_DEF_B_BONE_REST;
930         int invert_vgroup= deformflag & ARM_DEF_INVERT_VGROUP;
931         int numGroups = 0;              /* safety for vertexgroup index overflow */
932         int i, target_totvert = 0;      /* safety for vertexgroup overflow */
933         int use_dverts = 0;
934         int armature_def_nr = -1;
935         int totchan;
936
937         if(arm->edbo) return;
938         
939         Mat4Invert(obinv, target->obmat);
940         Mat4CpyMat4(premat, target->obmat);
941         Mat4MulMat4(postmat, armOb->obmat, obinv);
942         Mat4Invert(premat, postmat);
943
944         /* bone defmats are already in the channels, chan_mat */
945         
946         /* initialize B_bone matrices and dual quaternions */
947         if(use_quaternion) {
948                 totchan= BLI_countlist(&armOb->pose->chanbase);
949                 dualquats= MEM_callocN(sizeof(DualQuat)*totchan, "dualquats");
950         }
951
952         totchan= 0;
953         for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next) {
954                 if(!(pchan->bone->flag & BONE_NO_DEFORM)) {
955                         if(pchan->bone->segments > 1)
956                                 pchan_b_bone_defmats(pchan, use_quaternion, bbone_rest_def);
957
958                         if(use_quaternion) {
959                                 pchan->dual_quat= &dualquats[totchan++];
960                                 Mat4ToDQuat(pchan->bone->arm_mat, pchan->chan_mat, pchan->dual_quat);
961                         }
962                 }
963         }
964
965         /* get the def_nr for the overall armature vertex group if present */
966         for(i = 0, dg = target->defbase.first; dg; i++, dg = dg->next)
967                 if(defgrp_name && strcmp(defgrp_name, dg->name) == 0)
968                         armature_def_nr = i;
969
970         /* get a vertex-deform-index to posechannel array */
971         if(deformflag & ARM_DEF_VGROUP) {
972                 if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
973                         numGroups = BLI_countlist(&target->defbase);
974                         
975                         if(target->type==OB_MESH) {
976                                 Mesh *me= target->data;
977                                 dverts = me->dvert;
978                                 target_totvert = me->totvert;
979                         }
980                         else {
981                                 Lattice *lt= target->data;
982                                 dverts = lt->dvert;
983                                 if(dverts)
984                                         target_totvert = lt->pntsu*lt->pntsv*lt->pntsw;
985                         }
986                         /* if we have a DerivedMesh, only use dverts if it has them */
987                         if(dm)
988                                 if(dm->getVertData(dm, 0, CD_MDEFORMVERT))
989                                         use_dverts = 1;
990                                 else use_dverts = 0;
991                         else if(dverts) use_dverts = 1;
992
993                         if(use_dverts) {
994                                 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * numGroups,
995                                                         "defnrToBone");
996                                 for(i = 0, dg = target->defbase.first; dg;
997                                     i++, dg = dg->next) {
998                                         defnrToPC[i] = get_pose_channel(armOb->pose, dg->name);
999                                         /* exclude non-deforming bones */
1000                                         if(defnrToPC[i]) {
1001                                                 if(defnrToPC[i]->bone->flag & BONE_NO_DEFORM)
1002                                                         defnrToPC[i]= NULL;
1003                                         }
1004                                 }
1005                         }
1006                 }
1007         }
1008
1009         for(i = 0; i < numVerts; i++) {
1010                 MDeformVert *dvert;
1011                 DualQuat sumdq, *dq = NULL;
1012                 float *co, dco[3];
1013                 float sumvec[3], summat[3][3];
1014                 float *vec = NULL, (*smat)[3] = NULL;
1015                 float contrib = 0.0f;
1016                 float armature_weight = 1.0f;   /* default to 1 if no overall def group */
1017                 float prevco_weight = 1.0f;             /* weight for optional cached vertexcos */
1018                 int       j;
1019
1020                 if(use_quaternion) {
1021                         memset(&sumdq, 0, sizeof(DualQuat));
1022                         dq= &sumdq;
1023                 }
1024                 else {
1025                         sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
1026                         vec= sumvec;
1027
1028                         if(defMats) {
1029                                 Mat3Clr((float*)summat);
1030                                 smat = summat;
1031                         }
1032                 }
1033
1034                 if(use_dverts || armature_def_nr >= 0) {
1035                         if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
1036                         else if(dverts && i < target_totvert) dvert = dverts + i;
1037                         else dvert = NULL;
1038                 } else
1039                         dvert = NULL;
1040
1041                 if(armature_def_nr >= 0 && dvert) {
1042                         armature_weight = 0.0f; /* a def group was given, so default to 0 */
1043                         for(j = 0; j < dvert->totweight; j++) {
1044                                 if(dvert->dw[j].def_nr == armature_def_nr) {
1045                                         armature_weight = dvert->dw[j].weight;
1046                                         break;
1047                                 }
1048                         }
1049                         /* hackish: the blending factor can be used for blending with prevCos too */
1050                         if(prevCos) {
1051                                 if(invert_vgroup)
1052                                         prevco_weight= 1.0f-armature_weight;
1053                                 else
1054                                         prevco_weight= armature_weight;
1055                                 armature_weight= 1.0f;
1056                         }
1057                 }
1058
1059                 /* check if there's any  point in calculating for this vert */
1060                 if(armature_weight == 0.0f) continue;
1061                 
1062                 /* get the coord we work on */
1063                 co= prevCos?prevCos[i]:vertexCos[i];
1064                 
1065                 /* Apply the object's matrix */
1066                 Mat4MulVecfl(premat, co);
1067                 
1068                 if(use_dverts && dvert && dvert->totweight) { // use weight groups ?
1069                         int deformed = 0;
1070                         
1071                         for(j = 0; j < dvert->totweight; j++){
1072                                 int index = dvert->dw[j].def_nr;
1073                                 pchan = index < numGroups?defnrToPC[index]:NULL;
1074                                 if(pchan) {
1075                                         float weight = dvert->dw[j].weight;
1076                                         Bone *bone = pchan->bone;
1077
1078                                         deformed = 1;
1079                                         
1080                                         if(bone && bone->flag & BONE_MULT_VG_ENV) {
1081                                                 weight *= distfactor_to_bone(co, bone->arm_head,
1082                                                                              bone->arm_tail,
1083                                                                              bone->rad_head,
1084                                                                              bone->rad_tail,
1085                                                                              bone->dist);
1086                                         }
1087                                         pchan_bone_deform(pchan, weight, vec, dq, smat, co, &contrib);
1088                                 }
1089                         }
1090                         /* if there are vertexgroups but not groups with bones
1091                          * (like for softbody groups)
1092                          */
1093                         if(deformed == 0 && use_envelope) {
1094                                 for(pchan = armOb->pose->chanbase.first; pchan;
1095                                     pchan = pchan->next) {
1096                                         if(!(pchan->bone->flag & BONE_NO_DEFORM))
1097                                                 contrib += dist_bone_deform(pchan, vec, dq, smat, co);
1098                                 }
1099                         }
1100                 }
1101                 else if(use_envelope) {
1102                         for(pchan = armOb->pose->chanbase.first; pchan;
1103                             pchan = pchan->next) {
1104                                 if(!(pchan->bone->flag & BONE_NO_DEFORM))
1105                                         contrib += dist_bone_deform(pchan, vec, dq, smat, co);
1106                         }
1107                 }
1108
1109                 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1110                 if(contrib > 0.0001f) {
1111                         if(use_quaternion) {
1112                                 DQuatNormalize(dq, contrib);
1113
1114                                 if(armature_weight != 1.0f) {
1115                                         VECCOPY(dco, co);
1116                                         DQuatMulVecfl(dq, dco, (defMats)? summat: NULL);
1117                                         VecSubf(dco, dco, co);
1118                                         VecMulf(dco, armature_weight);
1119                                         VecAddf(co, co, dco);
1120                                 }
1121                                 else
1122                                         DQuatMulVecfl(dq, co, (defMats)? summat: NULL);
1123
1124                                 smat = summat;
1125                         }
1126                         else {
1127                                 VecMulf(vec, armature_weight/contrib);
1128                                 VecAddf(co, vec, co);
1129                         }
1130
1131                         if(defMats) {
1132                                 float pre[3][3], post[3][3], tmpmat[3][3];
1133
1134                                 Mat3CpyMat4(pre, premat);
1135                                 Mat3CpyMat4(post, postmat);
1136                                 Mat3CpyMat3(tmpmat, defMats[i]);
1137
1138                                 if(!use_quaternion) /* quaternion already is scale corrected */
1139                                         Mat3MulFloat((float*)smat, armature_weight/contrib);
1140
1141                                 Mat3MulSerie(defMats[i], tmpmat, pre, smat, post,
1142                                         NULL, NULL, NULL, NULL);
1143                         }
1144                 }
1145                 
1146                 /* always, check above code */
1147                 Mat4MulVecfl(postmat, co);
1148                 
1149                 
1150                 /* interpolate with previous modifier position using weight group */
1151                 if(prevCos) {
1152                         float mw= 1.0f - prevco_weight;
1153                         vertexCos[i][0]= prevco_weight*vertexCos[i][0] + mw*co[0];
1154                         vertexCos[i][1]= prevco_weight*vertexCos[i][1] + mw*co[1];
1155                         vertexCos[i][2]= prevco_weight*vertexCos[i][2] + mw*co[2];
1156                 }
1157         }
1158
1159         if(dualquats) MEM_freeN(dualquats);
1160         if(defnrToPC) MEM_freeN(defnrToPC);
1161         
1162         /* free B_bone matrices */
1163         for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next) {
1164                 if(pchan->b_bone_mats) {
1165                         MEM_freeN(pchan->b_bone_mats);
1166                         pchan->b_bone_mats = NULL;
1167                 }
1168                 if(pchan->b_bone_dual_quats) {
1169                         MEM_freeN(pchan->b_bone_dual_quats);
1170                         pchan->b_bone_dual_quats = NULL;
1171                 }
1172
1173                 pchan->dual_quat = NULL;
1174         }
1175 }
1176
1177 /* ************ END Armature Deform ******************* */
1178
1179 void get_objectspace_bone_matrix (struct Bone* bone, float M_accumulatedMatrix[][4], int root, int posed)
1180 {
1181         Mat4CpyMat4(M_accumulatedMatrix, bone->arm_mat);
1182 }
1183
1184 /* **************** Space to Space API ****************** */
1185
1186 /* Convert World-Space Matrix to Pose-Space Matrix */
1187 void armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4]) 
1188 {
1189         float obmat[4][4];
1190         
1191         /* prevent crashes */
1192         if (ob==NULL) return;
1193         
1194         /* get inverse of (armature) object's matrix  */
1195         Mat4Invert(obmat, ob->obmat);
1196         
1197         /* multiply given matrix by object's-inverse to find pose-space matrix */
1198         Mat4MulMat4(outmat, obmat, inmat);
1199 }
1200
1201 /* Convert Wolrd-Space Location to Pose-Space Location
1202  * NOTE: this cannot be used to convert to pose-space location of the supplied
1203  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1204  */
1205 void armature_loc_world_to_pose(Object *ob, float *inloc, float *outloc) 
1206 {
1207         float xLocMat[4][4];
1208         float nLocMat[4][4];
1209         
1210         /* build matrix for location */
1211         Mat4One(xLocMat);
1212         VECCOPY(xLocMat[3], inloc);
1213
1214         /* get bone-space cursor matrix and extract location */
1215         armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1216         VECCOPY(outloc, nLocMat[3]);
1217 }
1218
1219 /* Convert Pose-Space Matrix to Bone-Space Matrix 
1220  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1221  *              pose-channel into its local space (i.e. 'visual'-keyframing)
1222  */
1223 void armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1224 {
1225         float pc_trans[4][4], inv_trans[4][4];
1226         float pc_posemat[4][4], inv_posemat[4][4];
1227         
1228         /* paranoia: prevent crashes with no pose-channel supplied */
1229         if (pchan==NULL) return;
1230         
1231         /* get the inverse matrix of the pchan's transforms */
1232         if (pchan->rotmode)
1233                 LocEulSizeToMat4(pc_trans, pchan->loc, pchan->eul, pchan->size);
1234         else
1235                 LocQuatSizeToMat4(pc_trans, pchan->loc, pchan->quat, pchan->size);
1236         Mat4Invert(inv_trans, pc_trans);
1237         
1238         /* Remove the pchan's transforms from it's pose_mat.
1239          * This should leave behind the effects of restpose + 
1240          * parenting + constraints
1241          */
1242         Mat4MulMat4(pc_posemat, inv_trans, pchan->pose_mat);
1243         
1244         /* get the inverse of the leftovers so that we can remove 
1245          * that component from the supplied matrix
1246          */
1247         Mat4Invert(inv_posemat, pc_posemat);
1248         
1249         /* get the new matrix */
1250         Mat4MulMat4(outmat, inmat, inv_posemat);
1251 }
1252
1253 /* Convert Pose-Space Location to Bone-Space Location
1254  * NOTE: this cannot be used to convert to pose-space location of the supplied
1255  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1256  */
1257 void armature_loc_pose_to_bone(bPoseChannel *pchan, float *inloc, float *outloc) 
1258 {
1259         float xLocMat[4][4];
1260         float nLocMat[4][4];
1261         
1262         /* build matrix for location */
1263         Mat4One(xLocMat);
1264         VECCOPY(xLocMat[3], inloc);
1265
1266         /* get bone-space cursor matrix and extract location */
1267         armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1268         VECCOPY(outloc, nLocMat[3]);
1269 }
1270
1271 /* Remove rest-position effects from pose-transform for obtaining
1272  * 'visual' transformation of pose-channel. 
1273  * (used by the Visual-Keyframing stuff)
1274  */
1275 void armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
1276 {
1277         float imat[4][4];
1278  
1279         Mat4Invert(imat, arm_mat);
1280         Mat4MulMat4(delta_mat, pose_mat, imat);
1281 }
1282
1283 /* **************** Rotation Mode Conversions ****************************** */
1284 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1285
1286 /* Called from RNA when rotation mode changes 
1287  *      - the result should be that the rotations given in the provided pointers have had conversions 
1288  *        applied (as appropriate), such that the rotation of the element hasn't 'visually' changed 
1289  */
1290 void BKE_rotMode_change_values (float quat[4], float eul[3], float *axis, float angle[3], short oldMode, short newMode)
1291 {
1292         /* check if any change - if so, need to convert data */
1293         if (newMode > 0) { /* to euler */
1294                 if (oldMode == ROT_MODE_AXISANGLE) {
1295                         /* axis-angle to euler */
1296                         AxisAngleToEulO(axis, *angle, eul, newMode);
1297                 }
1298                 else if (oldMode == ROT_MODE_QUAT) {
1299                         /* quat to euler */
1300                         QuatToEulO(quat, eul, newMode);
1301                 }
1302                 /* else { no conversion needed } */
1303         }
1304         else if (newMode == ROT_MODE_QUAT) { /* to quat */
1305                 if (oldMode == ROT_MODE_AXISANGLE) {
1306                         /* axis angle to quat */
1307                         AxisAngleToQuat(quat, axis, *angle);
1308                 }
1309                 else if (oldMode > 0) {
1310                         /* euler to quat */
1311                         EulOToQuat(eul, oldMode, quat);
1312                 }
1313                 /* else { no conversion needed } */
1314         }
1315         else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1316                 if (oldMode > 0) {
1317                         /* euler to axis angle */
1318                         EulOToAxisAngle(eul, oldMode, axis, angle);
1319                 }
1320                 else if (oldMode == ROT_MODE_QUAT) {
1321                         /* quat to axis angle */
1322                         QuatToAxisAngle(quat, axis, angle);
1323                 }
1324                 
1325                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1326                 if (IS_EQ(axis[0], axis[1]) && IS_EQ(axis[1], axis[2])) {
1327                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1328                         axis[1]= 1.0f;
1329                 }
1330         }
1331 }
1332
1333 /* **************** The new & simple (but OK!) armature evaluation ********* */ 
1334
1335 /*  ****************** And how it works! ****************************************
1336
1337   This is the bone transformation trick; they're hierarchical so each bone(b)
1338   is in the coord system of bone(b-1):
1339
1340   arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) 
1341   
1342   -> yoffs is just the y axis translation in parent's coord system
1343   -> d_root is the translation of the bone root, also in parent's coord system
1344
1345   pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1346
1347   we then - in init deform - store the deform in chan_mat, such that:
1348
1349   pose_mat(b)= arm_mat(b) * chan_mat(b)
1350   
1351   *************************************************************************** */
1352 /*  Computes vector and roll based on a rotation. "mat" must
1353      contain only a rotation, and no scaling. */ 
1354 void mat3_to_vec_roll(float mat[][3], float *vec, float *roll) 
1355 {
1356     if (vec)
1357         VecCopyf(vec, mat[1]);
1358
1359     if (roll) {
1360         float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1361
1362         vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1363         Mat3Inv(vecmatinv, vecmat);
1364         Mat3MulMat3(rollmat, vecmatinv, mat);
1365
1366         *roll= (float)atan2(rollmat[2][0], rollmat[2][2]);
1367     }
1368 }
1369
1370 /*      Calculates the rest matrix of a bone based
1371         On its vector and a roll around that vector */
1372 void vec_roll_to_mat3(float *vec, float roll, float mat[][3])
1373 {
1374         float   nor[3], axis[3], target[3]={0,1,0};
1375         float   theta;
1376         float   rMatrix[3][3], bMatrix[3][3];
1377         
1378         VECCOPY (nor, vec);
1379         Normalize (nor);
1380         
1381         /*      Find Axis & Amount for bone matrix*/
1382         Crossf (axis,target,nor);
1383
1384         if (Inpf(axis,axis) > 0.0000000000001) {
1385                 /* if nor is *not* a multiple of target ... */
1386                 Normalize (axis);
1387                 
1388                 theta= NormalizedVecAngle2(target, nor);
1389                 
1390                 /*      Make Bone matrix*/
1391                 VecRotToMat3(axis, theta, bMatrix);
1392         }
1393         else {
1394                 /* if nor is a multiple of target ... */
1395                 float updown;
1396                 
1397                 /* point same direction, or opposite? */
1398                 updown = ( Inpf (target,nor) > 0 ) ? 1.0f : -1.0f;
1399                 
1400                 /* I think this should work ... */
1401                 bMatrix[0][0]=updown; bMatrix[0][1]=0.0;    bMatrix[0][2]=0.0;
1402                 bMatrix[1][0]=0.0;    bMatrix[1][1]=updown; bMatrix[1][2]=0.0;
1403                 bMatrix[2][0]=0.0;    bMatrix[2][1]=0.0;    bMatrix[2][2]=1.0;
1404         }
1405         
1406         /*      Make Roll matrix*/
1407         VecRotToMat3(nor, roll, rMatrix);
1408         
1409         /*      Combine and output result*/
1410         Mat3MulMat3 (mat, rMatrix, bMatrix);
1411 }
1412
1413
1414 /* recursive part, calculates restposition of entire tree of children */
1415 /* used by exiting editmode too */
1416 void where_is_armature_bone(Bone *bone, Bone *prevbone)
1417 {
1418         float vec[3];
1419         
1420         /* Bone Space */
1421         VecSubf (vec, bone->tail, bone->head);
1422         vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1423
1424         bone->length= VecLenf(bone->head, bone->tail);
1425         
1426         /* this is called on old file reading too... */
1427         if(bone->xwidth==0.0) {
1428                 bone->xwidth= 0.1f;
1429                 bone->zwidth= 0.1f;
1430                 bone->segments= 1;
1431         }
1432         
1433         if(prevbone) {
1434                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
1435                 
1436                 /* bone transform itself */
1437                 Mat4CpyMat3(offs_bone, bone->bone_mat);
1438                                 
1439                 /* The bone's root offset (is in the parent's coordinate system) */
1440                 VECCOPY(offs_bone[3], bone->head);
1441
1442                 /* Get the length translation of parent (length along y axis) */
1443                 offs_bone[3][1]+= prevbone->length;
1444                 
1445                 /* Compose the matrix for this bone  */
1446                 Mat4MulMat4(bone->arm_mat, offs_bone, prevbone->arm_mat);
1447         }
1448         else {
1449                 Mat4CpyMat3(bone->arm_mat, bone->bone_mat);
1450                 VECCOPY(bone->arm_mat[3], bone->head);
1451         }
1452         
1453         /* head */
1454         VECCOPY(bone->arm_head, bone->arm_mat[3]);
1455         /* tail is in current local coord system */
1456         VECCOPY(vec, bone->arm_mat[1]);
1457         VecMulf(vec, bone->length);
1458         VecAddf(bone->arm_tail, bone->arm_head, vec);
1459         
1460         /* and the kiddies */
1461         prevbone= bone;
1462         for(bone= bone->childbase.first; bone; bone= bone->next) {
1463                 where_is_armature_bone(bone, prevbone);
1464         }
1465 }
1466
1467 /* updates vectors and matrices on rest-position level, only needed 
1468    after editing armature itself, now only on reading file */
1469 void where_is_armature (bArmature *arm)
1470 {
1471         Bone *bone;
1472         
1473         /* hierarchical from root to children */
1474         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1475                 where_is_armature_bone(bone, NULL);
1476         }
1477 }
1478
1479 /* if bone layer is protected, copy the data from from->pose */
1480 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1481 {
1482         bPose *pose= ob->pose, *frompose= from->pose;
1483         bPoseChannel *pchan, *pchanp, pchanw;
1484         bConstraint *con;
1485         
1486         if (frompose==NULL) return;
1487         
1488         /* exception, armature local layer should be proxied too */
1489         if (pose->proxy_layer)
1490                 ((bArmature *)ob->data)->layer= pose->proxy_layer;
1491         
1492         /* clear all transformation values from library */
1493         rest_pose(frompose);
1494         
1495         /* copy over all of the proxy's bone groups */
1496                 /* TODO for later - implement 'local' bone groups as for constraints
1497                  *      Note: this isn't trivial, as bones reference groups by index not by pointer, 
1498                  *               so syncing things correctly needs careful attention
1499                  */
1500         BLI_freelistN(&pose->agroups);
1501         BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1502         pose->active_group= frompose->active_group;
1503         
1504         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1505                 if (pchan->bone->layer & layer_protected) {
1506                         ListBase proxylocal_constraints = {NULL, NULL};
1507                         pchanp= get_pose_channel(frompose, pchan->name);
1508                         
1509                         /* copy posechannel to temp, but restore important pointers */
1510                         pchanw= *pchanp;
1511                         pchanw.prev= pchan->prev;
1512                         pchanw.next= pchan->next;
1513                         pchanw.parent= pchan->parent;
1514                         pchanw.child= pchan->child;
1515                         pchanw.path= NULL;
1516                         
1517                         /* constraints - proxy constraints are flushed... local ones are added after 
1518                          *      1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1519                          *      2. copy proxy-pchan's constraints on-to new
1520                          *      3. add extracted local constraints back on top 
1521                          */
1522                         extract_proxylocal_constraints(&proxylocal_constraints, &pchan->constraints);
1523                         copy_constraints(&pchanw.constraints, &pchanp->constraints);
1524                         addlisttolist(&pchanw.constraints, &proxylocal_constraints);
1525                         
1526                         /* constraints - set target ob pointer to own object */
1527                         for (con= pchanw.constraints.first; con; con= con->next) {
1528                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1529                                 ListBase targets = {NULL, NULL};
1530                                 bConstraintTarget *ct;
1531                                 
1532                                 if (cti && cti->get_constraint_targets) {
1533                                         cti->get_constraint_targets(con, &targets);
1534                                         
1535                                         for (ct= targets.first; ct; ct= ct->next) {
1536                                                 if (ct->tar == from)
1537                                                         ct->tar = ob;
1538                                         }
1539                                         
1540                                         if (cti->flush_constraint_targets)
1541                                                 cti->flush_constraint_targets(con, &targets, 0);
1542                                 }
1543                         }
1544                         
1545                         /* free stuff from current channel */
1546                         if (pchan->path) MEM_freeN(pchan->path);
1547                         free_constraints(&pchan->constraints);
1548                         
1549                         /* the final copy */
1550                         *pchan= pchanw;
1551                 }
1552         }
1553 }
1554
1555 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1556 {
1557         bPoseChannel *pchan = verify_pose_channel (pose, bone->name);   // verify checks and/or adds
1558
1559         pchan->bone= bone;
1560         pchan->parent= parchan;
1561         
1562         counter++;
1563         
1564         for(bone= bone->childbase.first; bone; bone= bone->next) {
1565                 counter= rebuild_pose_bone(pose, bone, pchan, counter);
1566                 /* for quick detecting of next bone in chain, only b-bone uses it now */
1567                 if(bone->flag & BONE_CONNECTED)
1568                         pchan->child= get_pose_channel(pose, bone->name);
1569         }
1570         
1571         return counter;
1572 }
1573
1574 /* only after leave editmode, duplicating, validating older files, library syncing */
1575 /* NOTE: pose->flag is set for it */
1576 void armature_rebuild_pose(Object *ob, bArmature *arm)
1577 {
1578         Bone *bone;
1579         bPose *pose;
1580         bPoseChannel *pchan, *next;
1581         int counter=0;
1582                 
1583         /* only done here */
1584         if(ob->pose==NULL) ob->pose= MEM_callocN(sizeof(bPose), "new pose");
1585         pose= ob->pose;
1586         
1587         /* clear */
1588         for(pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1589                 pchan->bone= NULL;
1590                 pchan->child= NULL;
1591         }
1592         
1593         /* first step, check if all channels are there */
1594         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1595                 counter= rebuild_pose_bone(pose, bone, NULL, counter);
1596         }
1597
1598         /* and a check for garbage */
1599         for(pchan= pose->chanbase.first; pchan; pchan= next) {
1600                 next= pchan->next;
1601                 if(pchan->bone==NULL) {
1602                         if(pchan->path)
1603                                 MEM_freeN(pchan->path);
1604                         free_constraints(&pchan->constraints);
1605                         BLI_freelinkN(&pose->chanbase, pchan);
1606                 }
1607         }
1608         // printf("rebuild pose %s, %d bones\n", ob->id.name, counter);
1609         
1610         /* synchronize protected layers with proxy */
1611         if(ob->proxy)
1612                 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1613         
1614         update_pose_constraint_flags(ob->pose); // for IK detection for example
1615         
1616         /* the sorting */
1617         if(counter>1)
1618                 DAG_pose_sort(ob);
1619         
1620         ob->pose->flag &= ~POSE_RECALC;
1621         ob->pose->flag |= POSE_WAS_REBUILT;
1622 }
1623
1624
1625 /* ********************** THE POSE SOLVER ******************* */
1626
1627
1628 /* loc/rot/size to mat4 */
1629 /* used in constraint.c too */
1630 void chan_calc_mat(bPoseChannel *chan)
1631 {
1632         float smat[3][3];
1633         float rmat[3][3];
1634         float tmat[3][3];
1635         
1636         /* get scaling matrix */
1637         SizeToMat3(chan->size, smat);
1638         
1639         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1640         if (chan->rotmode > 0) {
1641                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1642                 EulOToMat3(chan->eul, chan->rotmode, rmat);
1643         }
1644         else if (chan->rotmode == ROT_MODE_AXISANGLE) {
1645                 /* axis-angle - not really that great for 3D-changing orientations */
1646                 AxisAngleToMat3(chan->rotAxis, chan->rotAngle, rmat);
1647         }
1648         else {
1649                 /* quats are normalised before use to eliminate scaling issues */
1650                 NormalQuat(chan->quat);
1651                 QuatToMat3(chan->quat, rmat);
1652         }
1653         
1654         /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
1655         Mat3MulMat3(tmat, rmat, smat);
1656         Mat4CpyMat3(chan->chan_mat, tmat);
1657         
1658         /* prevent action channels breaking chains */
1659         /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
1660         if ((chan->bone==NULL) || !(chan->bone->flag & BONE_CONNECTED)) {
1661                 VECCOPY(chan->chan_mat[3], chan->loc);
1662         }
1663 }
1664
1665 /* NLA strip modifiers */
1666 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
1667 {
1668         bActionModifier *amod;
1669         bActionStrip *strip, *strip2;
1670         float scene_cfra= (float)scene->r.cfra;
1671         int do_modif;
1672
1673         for (strip=armob->nlastrips.first; strip; strip=strip->next) {
1674                 do_modif=0;
1675                 
1676                 if (scene_cfra>=strip->start && scene_cfra<=strip->end)
1677                         do_modif=1;
1678                 
1679                 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
1680                         do_modif=1;
1681                         
1682                         /* if there are any other strips active, ignore modifiers for this strip - 
1683                          * 'hold' option should only hold action modifiers if there are 
1684                          * no other active strips */
1685                         for (strip2=strip->next; strip2; strip2=strip2->next) {
1686                                 if (strip2 == strip) continue;
1687                                 
1688                                 if (scene_cfra>=strip2->start && scene_cfra<=strip2->end) {
1689                                         if (!(strip2->flag & ACTSTRIP_MUTE))
1690                                                 do_modif=0;
1691                                 }
1692                         }
1693                         
1694                         /* if there are any later, activated, strips with 'hold' set, they take precedence, 
1695                          * so ignore modifiers for this strip */
1696                         for (strip2=strip->next; strip2; strip2=strip2->next) {
1697                                 if (scene_cfra < strip2->start) continue;
1698                                 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
1699                                         do_modif=0;
1700                                 }
1701                         }
1702                 }
1703                 
1704                 if (do_modif) {
1705                         /* temporal solution to prevent 2 strips accumulating */
1706                         if(scene_cfra==strip->end && strip->next && strip->next->start==scene_cfra)
1707                                 continue;
1708                         
1709                         for(amod= strip->modifiers.first; amod; amod= amod->next) {
1710                                 switch (amod->type) {
1711                                 case ACTSTRIP_MOD_DEFORM:
1712                                 {
1713                                         /* validate first */
1714                                         if(amod->ob && amod->ob->type==OB_CURVE && amod->channel[0]) {
1715                                                 
1716                                                 if( strcmp(pchan->name, amod->channel)==0 ) {
1717                                                         float mat4[4][4], mat3[3][3];
1718                                                         
1719                                                         curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
1720                                                         Mat4CpyMat4(mat4, pchan->pose_mat);
1721                                                         Mat4MulMat34(pchan->pose_mat, mat3, mat4);
1722                                                         
1723                                                 }
1724                                         }
1725                                 }
1726                                         break;
1727                                 case ACTSTRIP_MOD_NOISE:        
1728                                 {
1729                                         if( strcmp(pchan->name, amod->channel)==0 ) {
1730                                                 float nor[3], loc[3], ofs;
1731                                                 float eul[3], size[3], eulo[3], sizeo[3];
1732                                                 
1733                                                 /* calculate turbulance */
1734                                                 ofs = amod->turbul / 200.0f;
1735                                                 
1736                                                 /* make a copy of starting conditions */
1737                                                 VECCOPY(loc, pchan->pose_mat[3]);
1738                                                 Mat4ToEul(pchan->pose_mat, eul);
1739                                                 Mat4ToSize(pchan->pose_mat, size);
1740                                                 VECCOPY(eulo, eul);
1741                                                 VECCOPY(sizeo, size);
1742                                                 
1743                                                 /* apply noise to each set of channels */
1744                                                 if (amod->channels & 4) {
1745                                                         /* for scaling */
1746                                                         nor[0] = BLI_gNoise(amod->noisesize, size[0]+ofs, size[1], size[2], 0, 0) - ofs;
1747                                                         nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1]+ofs, size[2], 0, 0) - ofs;        
1748                                                         nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2]+ofs, 0, 0) - ofs;
1749                                                         VecAddf(size, size, nor);
1750                                                         
1751                                                         if (sizeo[0] != 0)
1752                                                                 VecMulf(pchan->pose_mat[0], size[0] / sizeo[0]);
1753                                                         if (sizeo[1] != 0)
1754                                                                 VecMulf(pchan->pose_mat[1], size[1] / sizeo[1]);
1755                                                         if (sizeo[2] != 0)
1756                                                                 VecMulf(pchan->pose_mat[2], size[2] / sizeo[2]);
1757                                                 }
1758                                                 if (amod->channels & 2) {
1759                                                         /* for rotation */
1760                                                         nor[0] = BLI_gNoise(amod->noisesize, eul[0]+ofs, eul[1], eul[2], 0, 0) - ofs;
1761                                                         nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1]+ofs, eul[2], 0, 0) - ofs;   
1762                                                         nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2]+ofs, 0, 0) - ofs;
1763                                                         
1764                                                         compatible_eul(nor, eulo);
1765                                                         VecAddf(eul, eul, nor);
1766                                                         compatible_eul(eul, eulo);
1767                                                         
1768                                                         LocEulSizeToMat4(pchan->pose_mat, loc, eul, size);
1769                                                 }
1770                                                 if (amod->channels & 1) {
1771                                                         /* for location */
1772                                                         nor[0] = BLI_gNoise(amod->noisesize, loc[0]+ofs, loc[1], loc[2], 0, 0) - ofs;
1773                                                         nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1]+ofs, loc[2], 0, 0) - ofs;   
1774                                                         nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2]+ofs, 0, 0) - ofs;
1775                                                         
1776                                                         VecAddf(pchan->pose_mat[3], loc, nor);
1777                                                 }
1778                                         }
1779                                 }
1780                                         break;
1781                                 }
1782                         }
1783                 }
1784         }
1785 }
1786
1787
1788 /* The main armature solver, does all constraints excluding IK */
1789 /* pchan is validated, as having bone and parent pointer */
1790 void where_is_pose_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime)
1791 {
1792         Bone *bone, *parbone;
1793         bPoseChannel *parchan;
1794         float vec[3];
1795         
1796         /* set up variables for quicker access below */
1797         bone= pchan->bone;
1798         parbone= bone->parent;
1799         parchan= pchan->parent;
1800         
1801         /* this gives a chan_mat with actions (ipos) results */
1802         chan_calc_mat(pchan);
1803         
1804         /* construct the posemat based on PoseChannels, that we do before applying constraints */
1805         /* pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
1806         
1807         if(parchan) {
1808                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
1809                 
1810                 /* bone transform itself */
1811                 Mat4CpyMat3(offs_bone, bone->bone_mat);
1812                 
1813                 /* The bone's root offset (is in the parent's coordinate system) */
1814                 VECCOPY(offs_bone[3], bone->head);
1815                 
1816                 /* Get the length translation of parent (length along y axis) */
1817                 offs_bone[3][1]+= parbone->length;
1818                 
1819                 /* Compose the matrix for this bone  */
1820                 if(bone->flag & BONE_HINGE) {   // uses restposition rotation, but actual position
1821                         float tmat[4][4];
1822                         
1823                         /* the rotation of the parent restposition */
1824                         Mat4CpyMat4(tmat, parbone->arm_mat);
1825                         
1826                         /* the location of actual parent transform */
1827                         VECCOPY(tmat[3], offs_bone[3]);
1828                         offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
1829                         Mat4MulVecfl(parchan->pose_mat, tmat[3]);
1830                         
1831                         Mat4MulSerie(pchan->pose_mat, tmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
1832                 }
1833                 else if(bone->flag & BONE_NO_SCALE) {
1834                         float orthmat[4][4];
1835                         
1836                         /* get the official transform, but we only use the vector from it (optimize...) */
1837                         Mat4MulSerie(pchan->pose_mat, parchan->pose_mat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
1838                         VECCOPY(vec, pchan->pose_mat[3]);
1839                         
1840                         /* do this again, but with an ortho-parent matrix */
1841                         Mat4CpyMat4(orthmat, parchan->pose_mat);
1842                         Mat4Ortho(orthmat);
1843                         Mat4MulSerie(pchan->pose_mat, orthmat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
1844                         
1845                         /* copy correct transform */
1846                         VECCOPY(pchan->pose_mat[3], vec);
1847                 }
1848                 else 
1849                         Mat4MulSerie(pchan->pose_mat, parchan->pose_mat, offs_bone, pchan->chan_mat, NULL, NULL, NULL, NULL, NULL);
1850         }
1851         else {
1852                 Mat4MulMat4(pchan->pose_mat, pchan->chan_mat, bone->arm_mat);
1853                 
1854                 /* only rootbones get the cyclic offset (unless user doesn't want that) */
1855                 if ((bone->flag & BONE_NO_CYCLICOFFSET) == 0)
1856                         VecAddf(pchan->pose_mat[3], pchan->pose_mat[3], ob->pose->cyclic_offset);
1857         }
1858         
1859         /* do NLA strip modifiers - i.e. curve follow */
1860         do_strip_modifiers(scene, ob, bone, pchan);
1861         
1862         /* Do constraints */
1863         if (pchan->constraints.first) {
1864                 bConstraintOb *cob;
1865                 
1866                 /* make a copy of location of PoseChannel for later */
1867                 VECCOPY(vec, pchan->pose_mat[3]);
1868                 
1869                 /* prepare PoseChannel for Constraint solving 
1870                  * - makes a copy of matrix, and creates temporary struct to use 
1871                  */
1872                 cob= constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
1873                 
1874                 /* Solve PoseChannel's Constraints */
1875                 solve_constraints(&pchan->constraints, cob, ctime);     // ctime doesnt alter objects
1876                 
1877                 /* cleanup after Constraint Solving 
1878                  * - applies matrix back to pchan, and frees temporary struct used
1879                  */
1880                 constraints_clear_evalob(cob);
1881                 
1882                 /* prevent constraints breaking a chain */
1883                 if(pchan->bone->flag & BONE_CONNECTED) {
1884                         VECCOPY(pchan->pose_mat[3], vec);
1885                 }
1886         }
1887         
1888         /* calculate head */
1889         VECCOPY(pchan->pose_head, pchan->pose_mat[3]);
1890         /* calculate tail */
1891         VECCOPY(vec, pchan->pose_mat[1]);
1892         VecMulf(vec, bone->length);
1893         VecAddf(pchan->pose_tail, pchan->pose_head, vec);
1894 }
1895
1896 /* This only reads anim data from channels, and writes to channels */
1897 /* This is the only function adding poses */
1898 void where_is_pose (Scene *scene, Object *ob)
1899 {
1900         bArmature *arm;
1901         Bone *bone;
1902         bPoseChannel *pchan;
1903         float imat[4][4];
1904         float ctime;
1905         
1906         if(ob->type!=OB_ARMATURE) return;
1907         arm = ob->data;
1908         
1909         if(ELEM(NULL, arm, scene)) return;
1910         if((ob->pose==NULL) || (ob->pose->flag & POSE_RECALC)) 
1911            armature_rebuild_pose(ob, arm);
1912            
1913         ctime= bsystem_time(scene, ob, (float)scene->r.cfra, 0.0);      /* not accurate... */
1914         
1915         /* In editmode or restposition we read the data from the bones */
1916         if(arm->edbo || (arm->flag & ARM_RESTPOS)) {
1917                 
1918                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1919                         bone= pchan->bone;
1920                         if(bone) {
1921                                 Mat4CpyMat4(pchan->pose_mat, bone->arm_mat);
1922                                 VECCOPY(pchan->pose_head, bone->arm_head);
1923                                 VECCOPY(pchan->pose_tail, bone->arm_tail);
1924                         }
1925                 }
1926         }
1927         else {
1928                 Mat4Invert(ob->imat, ob->obmat);        // imat is needed 
1929
1930                 /* 1. clear flags */
1931                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1932                         pchan->flag &= ~(POSE_DONE|POSE_CHAIN|POSE_IKTREE);
1933                 }
1934                 /* 2. construct the IK tree */
1935                 BIK_initialize_tree(scene, ob, ctime);
1936
1937                 /* 3. the main loop, channels are already hierarchical sorted from root to children */
1938                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1939                         
1940                         /* 4. if we find an IK root, we handle it separated */
1941                         if(pchan->flag & POSE_IKTREE) {
1942                                 BIK_execute_tree(scene, ob, pchan, ctime);
1943                         }
1944                         /* 5. otherwise just call the normal solver */
1945                         else if(!(pchan->flag & POSE_DONE)) {
1946                                 where_is_pose_bone(scene, ob, pchan, ctime);
1947                         }
1948                 }
1949                 /* 6. release the IK tree */
1950                 BIK_release_tree(scene, ob, ctime);
1951         }
1952                 
1953         /* calculating deform matrices */
1954         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1955                 if(pchan->bone) {
1956                         Mat4Invert(imat, pchan->bone->arm_mat);
1957                         Mat4MulMat4(pchan->chan_mat, imat, pchan->pose_mat);
1958                 }
1959         }
1960 }