85602d58178c932f1a81e27f0acce0229779ddb5
[blender.git] / source / blender / src / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * editarmature.c: Interface for creating and posing armature objects
32  */
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <math.h>
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #ifdef WIN32
43 #include "BLI_winstuff.h"
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "BMF_Api.h"
49
50 #include "DNA_action_types.h"
51 #include "DNA_armature_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_screen_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58
59 #include "BLI_blenlib.h"
60 #include "BLI_arithb.h"
61 #include "BLI_editVert.h"
62
63 #include "BKE_utildefines.h"
64 #include "BKE_action.h"
65 #include "BKE_armature.h"
66 #include "BKE_constraint.h"
67 #include "BKE_global.h"
68 #include "BKE_object.h"
69 #include "BKE_subsurf.h"
70
71 #include "BIF_gl.h"
72 #include "BIF_graphics.h"
73 #include "BIF_interface.h"
74 #include "BIF_resources.h"
75 #include "BIF_screen.h"
76 #include "BIF_space.h"
77 #include "BIF_toolbox.h"
78 #include "BIF_editarmature.h"
79 #include "BIF_poseobject.h"
80 #include "BIF_mywindow.h"
81 #include "BIF_editdeform.h"
82
83 #include "BDR_editobject.h"
84 #include "BDR_drawobject.h"
85
86 #include "BSE_edit.h"
87 #include "BSE_view.h"
88 #include "BSE_trans_types.h"
89 #include "BSE_editaction.h"
90
91 #include "mydevice.h"
92 #include "blendef.h"
93 #include "nla.h"
94
95 /*  >>>>> FIXME: ARG!  Colours should be defined in a header somewhere! */
96 /*      Note, these came from drawobject.c  They really should be in a nice header file somewhere */
97 #define B_YELLOW        0x77FFFF
98 #define B_PURPLE        0xFF70FF
99
100 #define B_CYAN          0xFFFF00
101 #define B_AQUA          0xFFBB55 /* 0xFF8833*/
102
103 extern  int tottrans;                                   /* Originally defined in editobject.c */
104 extern  struct TransOb *transmain;                              /* Originally defined in editobject.c */
105 extern  float centre[3], centroid[3];   /* Originally defined in editobject.c */
106
107 /*      Macros  */
108 #define TEST_EDITARMATURE {if(G.obedit==0) return; if( (G.vd->lay & G.obedit->lay)==0 ) return;}
109
110 /* Local Function Prototypes */
111 static void editbones_to_armature (ListBase *bones, Object *ob);
112
113 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist);
114 static int      select_bonechildren_by_name (struct Bone *bone, char *name, int select);
115
116 static void draw_boneverti (float x, float y, float z, float size, int flag);
117 static void draw_bone (int armflag, int boneflag, unsigned int id, char *name, float length);
118 static void draw_bonechildren (struct Bone *bone, int flag, unsigned int *index);
119 static void add_bone_input (struct Object *ob);
120 static void make_boneList(struct ListBase* list, struct ListBase *bones, struct EditBone *parent);
121 static void make_bone_menu_children (struct Bone *bone, char *str, int *index);
122 static void delete_bone(struct EditBone* exBone);
123 static void clear_armature_children (struct Bone *bone, struct bPose *pose, char mode);
124
125 static int      count_bones (struct bArmature *arm, int flagmask, int allbones);
126
127 static int      count_bonechildren (struct Bone *bone, int incount, int flagmask, int allbones);
128 static int      add_trans_bonechildren (struct Object* ob, struct Bone* bone, struct TransOb* buffer, int index, char mode);
129 static void deselect_bonechildren (struct Bone *bone, int mode);
130 static void selectconnected_posebonechildren (struct Bone *bone);
131
132 static int      editbone_name_exists (char* name);
133
134 static void *get_nearest_bone (int findunsel);
135 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask);
136
137 static Bone *get_first_selected_bonechildren (Bone *bone);
138
139
140 /* Functions */
141
142
143
144 void apply_rot_armature (Object *ob, float mat[3][3]){
145         ListBase        list;
146         EditBone *ebone;
147         bArmature *arm;
148
149         arm = get_armature(ob);
150
151         if (!arm)
152                 return;
153
154         /* Put the armature into editmode */
155         list.first= list.last = NULL;
156         make_boneList(&list, &arm->bonebase, NULL);
157
158         /* Do the rotations */
159         for (ebone = list.first; ebone; ebone=ebone->next){
160         
161                 {
162
163                         /* Fixme: This is essentially duplicated from join_armature */
164
165                         float premat[4][4];
166                         float postmat[4][4];
167                         float difmat[4][4];
168                         float imat[4][4];
169                         float temp[4][4];
170                         float delta[3];
171                         float rmat[4][4];
172                         
173                         Mat4CpyMat3 (rmat, mat);
174                         /* Get the premat */
175                         VecSubf (delta, ebone->tail, ebone->head);
176                         make_boneMatrixvr(temp, delta, ebone->roll);
177                         Mat4MulMat4 (premat, temp, rmat);
178                         
179                         Mat4MulVecfl(rmat, ebone->head);
180                         Mat4MulVecfl(rmat, ebone->tail);
181                         
182                         /* Get the postmat */
183                         VecSubf (delta, ebone->tail, ebone->head);
184                         make_boneMatrixvr(postmat, delta, ebone->roll);
185                         
186                         /* Find the roll */
187                         Mat4Invert (imat, premat);
188                         Mat4MulMat4 (difmat, postmat, imat);
189                         
190 #if 0
191                         printmatrix4 ("Difmat", difmat);
192 #endif
193                         ebone->roll -=atan(difmat[2][0]/difmat[2][2]);
194                         
195                         if (difmat[0][0]<0)
196                                 ebone->roll +=M_PI;
197                         
198                 }
199
200                 
201         }
202         
203         /* Turn the list into an armature */
204         editbones_to_armature(&list, ob);
205         
206         /* Free the editbones */
207         if (list.first){
208                 BLI_freelistN (&list);
209         }
210
211 }
212
213
214
215 static Bone *get_first_selected_bonechildren (Bone *bone)
216 {
217         Bone *curbone, *result;
218
219         if (bone->flag & BONE_SELECTED)
220                 return bone;
221
222         for (curbone = bone->childbase.first; curbone; curbone=curbone->next){
223                 result = get_first_selected_bonechildren(curbone);
224                 if (result)
225                         return result;
226         };
227
228         return NULL;
229 }
230
231 Bone *get_first_selected_bone (void)
232 {
233         Bone *curbone, *result;
234         bArmature *arm;
235
236         arm = get_armature(OBACT);
237         if (!arm)
238                 return NULL;
239
240         for (curbone = arm->bonebase.first; curbone; curbone=curbone->next){
241                 result = get_first_selected_bonechildren(curbone);
242                 if (result)
243                         return result;
244         }
245
246         return NULL;
247 }
248
249 void clever_numbuts_posearmature (void)
250 {
251         /* heh -- 'clever numbuts'! */
252         bArmature *arm;
253         Bone *bone;
254         bPoseChannel *chan;
255
256         arm = get_armature(OBACT);
257         if (!arm)
258                 return;
259
260         bone = get_first_selected_bone();
261
262         if (!bone)
263                 return;
264
265         add_numbut(0, NUM|FLO, "Loc X:", -G.vd->far, G.vd->far, bone->loc, 0);
266         add_numbut(1, NUM|FLO, "Loc Y:", -G.vd->far, G.vd->far, bone->loc+1, 0);
267         add_numbut(2, NUM|FLO, "Loc Z:", -G.vd->far, G.vd->far, bone->loc+2, 0);
268
269         add_numbut(3, NUM|FLO, "Quat X:", -G.vd->far, G.vd->far, bone->quat, 0);
270         add_numbut(4, NUM|FLO, "Quat Y:", -G.vd->far, G.vd->far, bone->quat+1, 0);
271         add_numbut(5, NUM|FLO, "Quat Z:", -G.vd->far, G.vd->far, bone->quat+2, 0);
272         add_numbut(6, NUM|FLO, "Quat W:", -G.vd->far, G.vd->far, bone->quat+3, 0);
273
274         add_numbut(7, NUM|FLO, "Size X:", -G.vd->far, G.vd->far, bone->size, 0);
275         add_numbut(8, NUM|FLO, "Size Y:", -G.vd->far, G.vd->far, bone->size+1, 0);
276         add_numbut(9, NUM|FLO, "Size Z:", -G.vd->far, G.vd->far, bone->size+2, 0);
277
278         do_clever_numbuts("Active Bone", 10, REDRAW);
279
280         /* This is similar to code in special_trans_update */
281         
282         if (!G.obpose->pose) G.obpose->pose= MEM_callocN(sizeof(bPose), "pose");
283         chan = MEM_callocN (sizeof (bPoseChannel), "transPoseChannel");
284
285         chan->flag |= POSE_LOC|POSE_ROT|POSE_SIZE;
286         memcpy (chan->loc, bone->loc, sizeof (chan->loc));
287         memcpy (chan->quat, bone->quat, sizeof (chan->quat));
288         memcpy (chan->size, bone->size, sizeof (chan->size));
289         strcpy (chan->name, bone->name);
290         
291         set_pose_channel (G.obpose->pose, chan);
292         
293 }
294
295 void clever_numbuts_armature (void)
296 {
297         EditBone *ebone, *child;
298         
299         ebone= G.edbo.first;
300
301         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
302                 if (ebone->flag & BONE_SELECTED)
303                         break;
304         }
305
306         if (!ebone)
307                 return;
308
309         add_numbut(0, NUM|FLO, "Root X:", -G.vd->far, G.vd->far, ebone->head, 0);
310         add_numbut(1, NUM|FLO, "Root Y:", -G.vd->far, G.vd->far, ebone->head+1, 0);
311         add_numbut(2, NUM|FLO, "Root Z:", -G.vd->far, G.vd->far, ebone->head+2, 0);
312
313         add_numbut(3, NUM|FLO, "Tip X:", -G.vd->far, G.vd->far, ebone->tail, 0);
314         add_numbut(4, NUM|FLO, "Tip Y:", -G.vd->far, G.vd->far, ebone->tail+1, 0);
315         add_numbut(5, NUM|FLO, "Tip Z:", -G.vd->far, G.vd->far, ebone->tail+2, 0);
316
317         /* Convert roll to degrees */
318         ebone->roll *= (180.0F/M_PI);
319         add_numbut(6, NUM|FLO, "Roll:", -G.vd->far, G.vd->far, &ebone->roll, 0);
320
321         do_clever_numbuts("Active Bone", 7, REDRAW);
322
323         /* Convert roll to radians */
324         ebone->roll /= (180.0F/M_PI);
325
326         //      Update our parent
327         if (ebone->parent && ebone->flag & BONE_IK_TOPARENT){
328                 VECCOPY (ebone->parent->tail, ebone->head);
329         }
330
331         //      Update our children if necessary
332         for (child = G.edbo.first; child; child=child->next){
333                 if (child->parent == ebone && child->flag & BONE_IK_TOPARENT){
334                         VECCOPY (child->head, ebone->tail);
335                 }
336         }
337 }
338
339 void select_bone_by_name (bArmature *arm, char *name, int select)
340 {
341         Bone *bone;
342
343         if (!arm)
344                 return;
345
346         for (bone=arm->bonebase.first; bone; bone=bone->next)
347                 if (select_bonechildren_by_name (bone, name, select))
348                         break;
349 }
350
351 static int select_bonechildren_by_name (Bone *bone, char *name, int select)
352 {
353         Bone *curBone;
354
355         if (!strcmp (bone->name, name)){
356                 if (select)
357                         bone->flag |= BONE_SELECTED;
358                 else
359                         bone->flag &= ~BONE_SELECTED;
360                 return 1;
361         }
362
363         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
364                 if (select_bonechildren_by_name (curBone, name, select))
365                         return 1;
366         }
367
368         return 0;
369 }
370 void selectconnected_armature(void)
371 {
372         EditBone *bone, *curBone, *next;
373
374         if (G.qual & LR_SHIFTKEY)
375                 bone= get_nearest_bone(0);
376         else
377                 bone= get_nearest_bone(1);
378
379         if (!bone)
380                 return;
381
382         /* Select parents */
383         for (curBone=bone; curBone; curBone=next){
384                 if (G.qual & LR_SHIFTKEY){
385                         curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
386                 }
387                 else{
388                         curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
389                 }
390
391                 if (curBone->flag & BONE_IK_TOPARENT)
392                         next=curBone->parent;
393                 else
394                         next=NULL;
395         }
396
397         /* Select children */
398         while (bone){
399                 for (curBone=G.edbo.first; curBone; curBone=next){
400                         next = curBone->next;
401                         if (curBone->parent == bone){
402                                 if (curBone->flag & BONE_IK_TOPARENT){
403                                         if (G.qual & LR_SHIFTKEY)
404                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
405                                         else
406                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
407                                         bone=curBone;
408                                         break;
409                                 }
410                                 else{ 
411                                         bone=NULL;
412                                         break;
413                                 }
414                         }
415                 }
416                 if (!curBone)
417                         bone=NULL;
418
419         }
420
421         countall();
422         allqueue (REDRAWVIEW3D, 0);
423
424 }
425
426 void selectconnected_posearmature(void)
427 {
428         Bone *bone, *curBone, *next;
429
430         if (G.qual & LR_SHIFTKEY)
431                 bone= get_nearest_bone(0);
432         else
433                 bone = get_nearest_bone(1);
434
435         if (!bone)
436                 return;
437
438         /* Select parents */
439         for (curBone=bone; curBone; curBone=next){
440                 select_actionchannel_by_name (G.obpose->action, curBone->name, !(G.qual & LR_SHIFTKEY));
441                 if (G.qual & LR_SHIFTKEY)
442                         curBone->flag &= ~BONE_SELECTED;
443                 else
444                         curBone->flag |= BONE_SELECTED;
445
446                 if (curBone->flag & BONE_IK_TOPARENT)
447                         next=curBone->parent;
448                 else
449                         next=NULL;
450         }
451
452         /* Select children */
453         for (curBone=bone->childbase.first; curBone; curBone=next){
454                 selectconnected_posebonechildren (curBone);
455         }
456         
457         countall();
458         allqueue (REDRAWVIEW3D, 0);
459         allqueue (REDRAWACTION, 0);
460 }
461
462 static void selectconnected_posebonechildren (Bone *bone)
463 {
464         Bone *curBone;
465
466         if (!(bone->flag & BONE_IK_TOPARENT))
467                 return;
468
469         select_actionchannel_by_name (G.obpose->action, bone->name, !(G.qual & LR_SHIFTKEY));
470
471         if (G.qual & LR_SHIFTKEY)
472                 bone->flag &= ~BONE_SELECTED;
473         else
474                 bone->flag |= BONE_SELECTED;
475
476         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
477                 selectconnected_posebonechildren (curBone);
478         }
479 }
480
481
482 char *make_bone_menu (bArmature *arm)
483 {
484         char *menustr=NULL;
485         Bone *curBone;
486         int             size;
487         int             index=0;
488         
489
490         //      Count the bones
491         size = (count_bones (arm, 0xFFFFFFFF, 1)*48) + 256;
492         menustr = MEM_callocN(size, "bonemenu");
493
494         sprintf (menustr, "Select Bone%%t");
495
496         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
497                 make_bone_menu_children (curBone, menustr, &index);
498         }
499
500         return menustr;
501 }
502
503 static void make_bone_menu_children (Bone *bone, char *str, int *index)
504 {
505         Bone *curBone;
506
507         sprintf (str, "%s|%s%%x%d", str, bone->name, *index);
508         (*index) ++;
509
510         for (curBone=bone->childbase.first; curBone; curBone=curBone->next)
511                 make_bone_menu_children (curBone, str, index);
512 }
513
514 void free_editArmature(void)
515 {
516
517         /*      Clear the editbones list */
518         if (G.edbo.first){
519                 BLI_freelistN (&G.edbo);
520         }
521 }
522
523 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask){
524         EditBone        *ebone;
525         unsigned int buffer[MAXPICKBUF];
526         short           hits;
527         int              i, takeNext=0;
528         int             sel;
529         unsigned int    hitresult, hitbone, firstunSel=-1;
530
531         persp(PERSP_VIEW);
532
533         glInitNames();
534         hits= selectprojektie(buffer, 0, 0, 0, 0);
535
536         /* See if there are any selected bones in this group */
537         if (hits){
538                 for (i=0; i< hits; i++){
539                         hitresult = buffer[3+(i*4)];
540                         if (!(hitresult&BONESEL_NOSEL)){
541
542                                 /* Determine which points are selected */
543                                 hitbone = hitresult & ~(BONESEL_ROOT|BONESEL_TIP);
544
545                                 /* Determine what the current bone is */
546                                 ebone = BLI_findlink(&G.edbo, hitbone);
547
548                                 /* See if it is selected */
549                                 sel = 0;
550                                 if ((hitresult & (BONESEL_TIP|BONESEL_ROOT)) == (BONESEL_TIP|BONESEL_ROOT))
551                                         sel = (ebone->flag & (BONE_TIPSEL| BONE_ROOTSEL)) == (BONE_TIPSEL|BONE_ROOTSEL) ? 1 : 0;
552                                 else if (hitresult & BONESEL_TIP)
553                                         sel |= ebone->flag & BONE_TIPSEL;
554                                 else if (hitresult & BONESEL_ROOT)
555                                         sel |= ebone->flag & BONE_ROOTSEL;
556                                 if (!findunsel)
557                                         sel = !sel;
558                         
559                                 if (sel)
560                                         takeNext=1;
561                                 else{
562                                         if (firstunSel == -1)
563                                                 firstunSel = hitresult;
564                                         if (takeNext){
565                                                 *selmask =0;
566                                                 if (hitresult & BONESEL_ROOT)
567                                                         *selmask |= BONE_ROOTSEL;
568                                                 if (hitresult & BONESEL_TIP)
569                                                         *selmask |= BONE_TIPSEL;
570                                                 return ebone;
571                                         }
572                                 }
573                         }
574                 }
575
576                 if (firstunSel != -1){
577                         *selmask = 0;
578                         if (firstunSel & BONESEL_ROOT)
579                                 *selmask |= BONE_ROOTSEL;
580                         if (firstunSel & BONESEL_TIP)
581                                 *selmask |= BONE_TIPSEL;
582                         return BLI_findlink(&G.edbo, firstunSel & ~(BONESEL_ROOT|BONESEL_TIP));
583                 }
584 #if 1
585                 else{
586                         *selmask = 0;
587                         if (buffer[3] & BONESEL_ROOT)
588                                 *selmask |= BONE_ROOTSEL;
589                         if (buffer[3] & BONESEL_TIP)
590                                 *selmask |= BONE_TIPSEL;
591 #if 1
592                         return BLI_findlink(&G.edbo, buffer[3] & ~(BONESEL_ROOT|BONESEL_TIP));
593 #else
594                         return NULL;
595 #endif
596                 }
597 #endif
598         }
599
600         *selmask = 0;
601         return NULL;
602 }
603
604 static void * get_nearest_bone (int findunsel){
605         void            *firstunSel=NULL, *data;
606         unsigned int buffer[MAXPICKBUF];
607         short           hits;
608         int              i, takeNext=0;
609         int             sel;
610         unsigned int    hitresult;
611         Bone *bone;
612         EditBone *ebone;
613
614         persp(PERSP_VIEW);
615
616         glInitNames();
617         hits= selectprojektie(buffer, 0, 0, 0, 0);
618
619
620         /* See if there are any selected bones in this group */
621         if (hits){
622                 for (i=0; i< hits; i++){
623                         hitresult = buffer[3+(i*4)];
624                         if (!(hitresult&BONESEL_NOSEL)){
625
626                                 /* Determine which points are selected */
627                                 hitresult &= ~(BONESEL_ROOT|BONESEL_TIP);
628
629                                 /* Determine what the current bone is */
630                                 if (!G.obedit){
631                                         bone = get_indexed_bone(OBACT->data, hitresult);
632                                         if (findunsel)
633                                                 sel = (bone->flag & BONE_SELECTED);
634                                         else
635                                                 sel = !(bone->flag & BONE_SELECTED);                                    
636                                         data = bone;
637                                 }
638                                 else{
639                                         ebone = BLI_findlink(&G.edbo, hitresult);
640                                         if (findunsel)
641                                                 sel = (ebone->flag & BONE_SELECTED);
642                                         else
643                                                 sel = !(ebone->flag & BONE_SELECTED);
644                                         
645                                         data = ebone;
646                                 }
647                                 
648                                 if (sel)
649                                         takeNext=1;
650                                 else{
651                                         if (!firstunSel)
652                                                 firstunSel=data;
653                                         if (takeNext)
654                                                 return data;
655                                 }
656                         }
657                 }
658
659                 if (firstunSel)
660                         return firstunSel;
661 #if 1
662                 else{
663 #if 1
664                         if (G.obedit)
665                                 return BLI_findlink(&G.edbo, buffer[3] & ~(BONESEL_ROOT|BONESEL_TIP));
666                         else
667                                 return get_indexed_bone(OBACT->data, buffer[3] & ~(BONESEL_ROOT|BONESEL_TIP));
668 #else
669                         return NULL;
670 #endif
671                 }
672 #endif
673         }
674
675         return NULL;
676 }
677
678 void delete_armature(void)
679 {
680         EditBone        *curBone, *next;
681         
682         TEST_EDITARMATURE;
683         if(okee("Erase selected")==0) return;
684         
685         for (curBone=G.edbo.first;curBone;curBone=next){
686                 next=curBone->next;
687                 if (curBone->flag&BONE_SELECTED)
688                         delete_bone(curBone);
689         }
690         
691         
692         allqueue(REDRAWVIEW3D, 0);
693         allqueue(REDRAWBUTSEDIT, 0);
694         allqueue(REDRAWBUTSOBJECT, 0);
695         countall();
696 }
697
698
699 static void delete_bone(EditBone* exBone)
700 {
701         EditBone        *curBone;
702         bPoseChannel *chan;
703         
704         /*      Find any bones that refer to this bone  */
705         for (curBone=G.edbo.first;curBone;curBone=curBone->next){
706                 if (curBone->parent==exBone){
707                         curBone->parent=exBone->parent;
708                         curBone->flag &= ~BONE_IK_TOPARENT;
709                 }
710         }
711         
712         /*  Erase any associated pose channel */
713         if (G.obedit->pose){
714                 for (chan=G.obedit->pose->chanbase.first; chan; chan=chan->next){
715                         if (!strcmp (chan->name, exBone->name)){
716                                 free_constraints(&chan->constraints);
717                                 BLI_freelinkN (&G.obedit->pose->chanbase, chan);
718                                 break;
719                         }
720                 }
721         }
722
723
724         allqueue(REDRAWBUTSOBJECT, 0);
725         allqueue(REDRAWBUTSEDIT, 0);
726
727         BLI_freelinkN (&G.edbo,exBone);
728 }
729
730 void remake_editArmature(void)
731 {
732         if(okee("Reload Original data")==0) return;
733         
734         make_editArmature();
735         allqueue(REDRAWVIEW3D, 0);
736         allqueue(REDRAWBUTSHEAD, 0);
737         allqueue(REDRAWBUTSOBJECT, 0);
738         allqueue(REDRAWBUTSEDIT, 0);
739 }
740
741 void mouse_armature(void)
742 {
743         EditBone*       nearBone = NULL;
744         int     selmask;
745
746         nearBone=get_nearest_editbonepoint(1, &selmask);
747
748         if (nearBone){
749                 if ((G.qual & LR_SHIFTKEY) && (nearBone->flag & selmask))
750                         nearBone->flag &= ~selmask;
751                 else
752                         nearBone->flag |= selmask;
753
754                 if (!(G.qual & LR_SHIFTKEY)){
755                         deselectall_armature();
756                         nearBone->flag |= selmask;
757                 }
758                 allqueue(REDRAWVIEW3D, 0);
759                 allqueue(REDRAWBUTSEDIT, 0);
760                 allqueue(REDRAWBUTSOBJECT, 0);
761         };
762         countall();
763         rightmouse_transform();
764 }
765
766 void make_editArmature(void)
767 {
768         bArmature       *arm;
769         
770         if (G.obedit==0)
771                 return;
772         
773         free_editArmature();
774         
775         arm= get_armature(G.obedit);
776         if (!arm)
777                 return;
778         
779         make_boneList (&G.edbo, &arm->bonebase,NULL);
780 }
781
782 static void editbones_to_armature (ListBase *list, Object *ob)
783 {
784         bArmature *arm;
785         EditBone *eBone;
786         Bone    *newBone;
787
788         arm = get_armature(ob);
789         if (!list)
790                 return;
791         if (!arm)
792                 return;
793
794         free_bones(arm);
795         
796
797         /*      Copy the bones from the editData into the armature*/
798         for (eBone=list->first;eBone;eBone=eBone->next){
799                 newBone=MEM_callocN (sizeof(Bone), "bone");
800                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
801                 
802                 strcpy (newBone->name, eBone->name);
803                 memcpy (newBone->head, eBone->head, sizeof(float)*3);
804                 memcpy (newBone->tail, eBone->tail, sizeof(float)*3);
805                 newBone->flag=eBone->flag &~(BONE_SELECTED|BONE_HILIGHTED);
806 //              newBone->roll=eBone->roll;
807                 newBone->roll = 0.0F;
808
809                 /*      >>>>> FIXME: This isn't a very good system: a lot of
810                                         pointless copying involved.  To be investigated
811                                         once things are working better.
812                 */
813
814                 newBone->weight = eBone->weight;
815                 newBone->dist = eBone->dist;
816                 newBone->boneclass = eBone->boneclass;
817
818                 memcpy (newBone->loc, eBone->loc, sizeof(eBone->loc));
819                 memcpy (newBone->dloc, eBone->dloc, sizeof(eBone->dloc));
820 /*              memcpy (newBone->orig, eBone->orig, sizeof(eBone->orig));*/
821                 memcpy (newBone->size, eBone->size, sizeof(eBone->size));
822                 memcpy (newBone->dsize, eBone->dsize, sizeof(eBone->dsize));
823                 memcpy (newBone->quat, eBone->quat, sizeof(eBone->quat));
824                 memcpy (newBone->dquat, eBone->dquat, sizeof(eBone->dquat));
825                 memcpy (newBone->obmat, eBone->obmat, sizeof(eBone->obmat));
826         }
827
828         /*      Fix parenting in a separate pass to ensure ebone->bone connections
829                 are valid at this point */
830         for (eBone=list->first;eBone;eBone=eBone->next){
831                 newBone= (Bone*) eBone->temp;
832                 if (eBone->parent){
833                         newBone->parent=(Bone*) eBone->parent->temp;
834                         BLI_addtail (&newBone->parent->childbase,newBone);
835
836                         {
837                                 float M_boneRest[4][4];
838                                 float M_parentRest[4][4];
839                                 float iM_parentRest[4][4];
840                                 float   delta[3];
841                         
842                                 /* Get the parent's global matrix (rotation only)*/
843                                 VecSubf (delta, eBone->parent->tail, eBone->parent->head);
844                                 make_boneMatrixvr(M_parentRest, delta, eBone->parent->roll);
845
846                                 /* Get this bone's global matrix (rotation only)*/
847                                 VecSubf (delta, eBone->tail, eBone->head);
848                                 make_boneMatrixvr(M_boneRest, delta, eBone->roll);
849
850                                 /* Invert the parent matrix */
851                                 Mat4Invert (iM_parentRest, M_parentRest);
852
853                                 /* Get the new head and tail */
854                                 VecSubf (newBone->head, eBone->head, eBone->parent->tail);
855                                 VecSubf (newBone->tail, eBone->tail, eBone->parent->tail);
856
857                                 Mat4MulVecfl(iM_parentRest, newBone->head);
858                                 Mat4MulVecfl(iM_parentRest, newBone->tail);
859         
860
861                         }
862
863                 }
864                 /*      ...otherwise add this bone to the armature's bonebase */
865                 else
866                         BLI_addtail (&arm->bonebase,newBone);
867         }
868
869         /* Make a pass through the new armature to fix rolling */
870         fix_bonelist_roll (&arm->bonebase, list);
871         /* Get rid of pose channels that may have belonged to deleted bones */
872         collect_pose_garbage(ob);
873         /* Ensure all bones have channels */
874         apply_pose_armature(arm, ob->pose, 0);
875
876         /* Calculate and cache the inverse restposition matrices (needed for deformation)*/
877         precalc_bonelist_irestmats(&arm->bonebase);
878 }
879
880
881 void load_editArmature(void)
882 {
883         bArmature               *arm;
884
885         arm=get_armature(G.obedit);
886         if (!arm)
887                 return;
888         
889 #if 1
890         editbones_to_armature(&G.edbo, G.obedit);
891 #else
892         free_bones(arm);
893         
894
895         /*      Copy the bones from the editData into the armature*/
896         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
897                 newBone=MEM_callocN (sizeof(Bone), "bone");
898                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
899                 
900                 strcpy (newBone->name, eBone->name);
901                 memcpy (newBone->head, eBone->head, sizeof(float)*3);
902                 memcpy (newBone->tail, eBone->tail, sizeof(float)*3);
903                 newBone->flag=eBone->flag &~(BONE_SELECTED|BONE_HILIGHTED);
904         //      newBone->roll=eBone->roll;
905                 newBone->roll = 0.0F;
906
907                 /*      >>>>> FIXME: This isn't a very good system: a lot of
908                                         pointless copying involved.  To be investigated
909                                         once things are working better.
910                 */
911
912                 newBone->weight = eBone->weight;
913                 newBone->dist = eBone->dist;
914                 newBone->boneclass = eBone->boneclass;
915
916                 memcpy (newBone->loc, eBone->loc, sizeof(eBone->loc));
917                 memcpy (newBone->dloc, eBone->dloc, sizeof(eBone->dloc));
918 /*              memcpy (newBone->orig, eBone->orig, sizeof(eBone->orig));*/
919                 memcpy (newBone->size, eBone->size, sizeof(eBone->size));
920                 memcpy (newBone->dsize, eBone->dsize, sizeof(eBone->dsize));
921                 memcpy (newBone->quat, eBone->quat, sizeof(eBone->quat));
922                 memcpy (newBone->dquat, eBone->dquat, sizeof(eBone->dquat));
923                 memcpy (newBone->obmat, eBone->obmat, sizeof(eBone->obmat));
924         }
925
926         /*      Fix parenting in a separate pass to ensure ebone->bone connections
927                 are valid at this point */
928         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
929                 newBone= (Bone*) eBone->temp;
930                 if (eBone->parent){
931                         newBone->parent=(Bone*) eBone->parent->temp;
932                         BLI_addtail (&newBone->parent->childbase,newBone);
933
934                         {
935                                 float M_boneRest[4][4];
936                                 float M_parentRest[4][4];
937                                 float M_relativeBone[4][4];
938                                 float iM_parentRest[4][4];
939                                 float   delta[3];
940                         
941                                 /* Get the parent's global matrix (rotation only)*/
942                                 VecSubf (delta, eBone->parent->tail, eBone->parent->head);
943                                 make_boneMatrixvr(M_parentRest, delta, eBone->parent->roll);
944
945                                 /* Get this bone's global matrix (rotation only)*/
946                                 VecSubf (delta, eBone->tail, eBone->head);
947                                 make_boneMatrixvr(M_boneRest, delta, eBone->roll);
948
949                                 /* Invert the parent matrix */
950                                 Mat4Invert (iM_parentRest, M_parentRest);
951
952                                 /* Get the new head and tail */
953                                 VecSubf (newBone->head, eBone->head, eBone->parent->tail);
954                                 VecSubf (newBone->tail, eBone->tail, eBone->parent->tail);
955
956                                 Mat4MulVecfl(iM_parentRest, newBone->head);
957                                 Mat4MulVecfl(iM_parentRest, newBone->tail);
958         
959
960                         }
961
962                 }
963                 /*      ...otherwise add this bone to the armature's bonebase */
964                 else
965                         BLI_addtail (&arm->bonebase,newBone);
966         }
967
968         /* Make a pass through the new armature to fix rolling */
969         fix_bonelist_roll (&arm->bonebase, &G.edbo);
970
971         /* Get rid of pose channels that may have belonged to deleted bones */
972         collect_pose_garbage(G.obedit);
973 #endif
974 }
975
976 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
977 {
978         Bone *curBone;
979         EditBone *ebone;
980
981         for (curBone=bonelist->first; curBone; curBone=curBone->next){
982                 
983                 /* Fix this bone's roll */
984 #if 1
985                 {
986                         float premat[4][4];
987                         float postmat[4][4];
988                         float difmat[4][4];
989                         float imat[4][4];
990                         float delta[3];
991
992                         /* Find the associated editbone */
993                         for (ebone = editbonelist->first; ebone; ebone=ebone->next)
994                                 if ((Bone*)ebone->temp == curBone)
995                                         break;
996                         
997                                 if (ebone){
998                                         /* Get the premat */
999                                         VecSubf (delta, ebone->tail, ebone->head);
1000                                         make_boneMatrixvr(premat, delta, ebone->roll);
1001                                         
1002                                         /* Get the postmat */
1003                                         get_objectspace_bone_matrix(curBone, postmat, 1, 0);
1004                                         postmat[3][0]=postmat[3][1]=postmat[3][2]=0.0F;
1005 #if 1
1006                                         Mat4Invert (imat, premat);
1007                                         Mat4MulMat4 (difmat, postmat, imat);
1008 #else
1009                                         Mat4Invert (imat, postmat);
1010                                         Mat4MulMat4 (difmat, premat, imat);
1011 #endif
1012 #if 0
1013                                         printf ("Bone %s\n", curBone->name);
1014                                         printmatrix4 ("premat", premat);
1015                                         printmatrix4 ("postmat", postmat);
1016                                         printmatrix4 ("difmat", difmat);
1017                                         printf ("Roll = %f\n",  (-atan(difmat[2][0]/difmat[2][2]) * (180.0/M_PI)));
1018 #endif
1019                                         curBone->roll = -atan(difmat[2][0]/difmat[2][2]);
1020                                         
1021                                         if (difmat[0][0]<0)
1022                                                 curBone->roll +=M_PI;
1023                                         
1024                                 }
1025                 }
1026 #endif
1027                 
1028                 fix_bonelist_roll (&curBone->childbase, editbonelist);
1029         }
1030 }
1031
1032 void make_bone_parent(void)
1033 {
1034 /*      error ("Bone Parenting not yet implemented");   */
1035         return;
1036 }
1037
1038 static void make_boneList(ListBase* list, ListBase *bones, EditBone *parent)
1039 {
1040         EditBone        *eBone;
1041         Bone            *curBone;
1042         
1043         for (curBone=bones->first; curBone; curBone=curBone->next){
1044                 eBone=MEM_callocN(sizeof(EditBone),"make_editbone");
1045                 
1046                 /*      Copy relevant data from bone to eBone */
1047                 eBone->parent=parent;
1048                 strcpy (eBone->name, curBone->name);
1049                 eBone->flag = curBone->flag & ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1050
1051                 /* Print bone matrix before and after */
1052
1053                 get_bone_root_pos(curBone, eBone->head, 0);
1054                 get_bone_tip_pos(curBone, eBone->tail, 0);
1055 //              eBone->roll=curBone->roll;
1056                 eBone->roll=0;
1057
1058 #if 1
1059                 {
1060                         float delta[3];
1061                         float premat[4][4];
1062                         float postmat[4][4];
1063                         float imat[4][4];
1064                         float difmat[4][4];
1065
1066                         VecSubf (delta, eBone->tail, eBone->head);
1067                         make_boneMatrixvr(postmat, delta, eBone->roll);
1068
1069                         get_objectspace_bone_matrix(curBone, premat, 1, 0);
1070
1071 #if 0
1072                         Mat4Invert (imat, premat);
1073                         Mat4MulMat4 (difmat, postmat, imat);
1074 #else
1075                         Mat4Invert (imat, postmat);
1076                         Mat4MulMat4 (difmat, premat, imat);
1077 #endif
1078 #if 0
1079                         printf ("Bone %s\n", curBone->name);
1080                         printmatrix4 ("diffmat", difmat);
1081                         printf ("Roll : atan of %f / %f = %f\n", difmat[2][0], difmat[2][2], (float)atan(difmat[2][0]/difmat[2][2])*(180.0F/M_PI));
1082 #endif
1083                         eBone->roll = atan(difmat[2][0]/difmat[2][2]);
1084
1085                          if (difmat[0][0]<0)
1086                                 eBone->roll +=M_PI;
1087                 }
1088 #endif          
1089                 eBone->dist= curBone->dist;
1090                 eBone->weight= curBone->weight;
1091                 eBone->boneclass = curBone->boneclass;
1092                 memcpy (eBone->loc, curBone->loc, sizeof(curBone->loc));
1093                 memcpy (eBone->dloc, curBone->dloc, sizeof(curBone->dloc));
1094                 /*              memcpy (eBone->orig, curBone->orig, sizeof(curBone->orig));*/
1095                 memcpy (eBone->size, curBone->size, sizeof(curBone->size));
1096                 memcpy (eBone->dsize, curBone->dsize, sizeof(curBone->dsize));
1097                 memcpy (eBone->quat, curBone->quat, sizeof(curBone->quat));
1098                 memcpy (eBone->dquat, curBone->dquat, sizeof(curBone->dquat));
1099                 memcpy (eBone->obmat, curBone->obmat, sizeof(curBone->obmat));
1100                 
1101
1102                 BLI_addtail (list, eBone);
1103                 
1104                 /*      Add children if necessary */
1105                 if (curBone->childbase.first) 
1106                         make_boneList (list, &curBone->childbase, eBone);
1107         }
1108         
1109
1110 }
1111
1112 #if 0
1113 static EditVert*         add_armatureVert (float *loc)
1114 {
1115         EditVert*       vert=NULL;
1116
1117         vert = MEM_callocN (sizeof (EditVert), "armaturevert");
1118         if (vert){
1119                 VECCOPY (vert->co, loc);
1120                 BLI_addtail (&G.edve,vert);
1121         }
1122
1123         return vert;
1124
1125 }
1126
1127 static EditVert* get_armatureVert (float *loc)
1128 {
1129         EditVert*       vert;
1130
1131         for (vert=G.edve.first;vert;vert=vert->next){
1132                 if ((vert->co[0]==loc[0])&&(vert->co[1]==loc[1])&&(vert->co[2]==loc[2])){
1133                         return (vert);
1134                 }
1135         }
1136
1137         return add_armatureVert (loc);
1138 }
1139 #endif
1140
1141 void draw_armature(Object *ob)
1142 {
1143         bArmature       *arm;
1144         Bone            *bone;
1145         EditBone        *eBone;
1146         unsigned int    index;
1147         float           delta[3],offset[3];
1148         float           bmat[4][4];
1149         float   length;
1150         
1151         if (ob==NULL) return;
1152         
1153         arm= ob->data; 
1154         if (arm==NULL) return;
1155
1156         if (!(ob->lay & G.vd->lay))
1157                 return;
1158
1159         if (arm->flag & ARM_DRAWXRAY) {
1160                 if(G.zbuf) glDisable(GL_DEPTH_TEST);
1161         }
1162
1163         /* If we're in editmode, draw the Global edit data */
1164         if(ob==G.obedit || (G.obedit && ob->data==G.obedit->data)) {
1165                 cpack (0x000000);
1166                 
1167                 arm->flag |= ARM_EDITMODE;
1168                 for (eBone=G.edbo.first, index=0; eBone; eBone=eBone->next, index++){
1169                         if (ob==G.obedit){
1170         //                      if ((eBone->flag&(BONE_TIPSEL | BONE_ROOTSEL))==(BONE_TIPSEL|BONE_ROOTSEL))
1171         //                              cpack (B_YELLOW);
1172         //                      else
1173                                         cpack (B_PURPLE);
1174                         }
1175                         else cpack (0x000000);
1176                         
1177                         glPushMatrix();
1178                         
1179                         /*      Compose the parent transforms (i.e. their translations) */
1180                         VECCOPY (offset,eBone->head);
1181
1182                         glTranslatef (offset[0],offset[1],offset[2]);
1183                         
1184                         delta[0]=eBone->tail[0]-eBone->head[0]; 
1185                         delta[1]=eBone->tail[1]-eBone->head[1]; 
1186                         delta[2]=eBone->tail[2]-eBone->head[2];
1187                         
1188                         length = sqrt (delta[0]*delta[0] + delta[1]*delta[1] +delta[2]*delta[2]);
1189
1190                         make_boneMatrixvr(bmat, delta, eBone->roll);
1191                         glMultMatrixf (bmat);
1192                         draw_bone (arm->flag, eBone->flag, index, eBone->name, length);
1193
1194                         glPopMatrix();
1195                         if (eBone->parent){
1196                                 glLoadName (-1);
1197                                 setlinestyle(3);
1198                                 
1199                                 glBegin(GL_LINES);
1200                                 glVertex3fv(eBone->parent->tail);
1201                                 glVertex3fv(eBone->head);
1202                                 glEnd();
1203
1204                                 setlinestyle(0);
1205                         }
1206                 };
1207                 arm->flag &= ~ARM_EDITMODE;
1208                 cpack (B_YELLOW);
1209                 
1210         }
1211         else{
1212                 /*      Draw hierarchical bone list (non-edit data) */
1213
1214                 /* Ensure we're using the mose recent pose */
1215                 if (!ob->pose)
1216                         ob->pose=MEM_callocN (sizeof(bPose), "pose");
1217
1218 #if 1   /* Activate if there are problems with action lag */
1219                 apply_pose_armature(arm, ob->pose, 0);
1220                 where_is_armature (ob);
1221 #endif
1222
1223                 if (G.obpose == ob){
1224                         arm->flag |= ARM_POSEMODE;
1225 #if 0   /* Depreciated interactive ik goal drawing */
1226                         if (arm->chainbase.first){
1227                                 glPushMatrix();
1228                                 glTranslatef(((PoseChain*)arm->chainbase.first)->goal[0],
1229                                         ((PoseChain*)arm->chainbase.first)->goal[1],
1230                                         ((PoseChain*)arm->chainbase.first)->goal[2]);
1231                                 drawaxes(1.0);
1232                                 glPopMatrix();
1233                         }
1234 #endif
1235                 }
1236                 index = 0;
1237                 for (bone=arm->bonebase.first; bone; bone=bone->next) {
1238                         glPushMatrix();
1239                         draw_bonechildren(bone, arm->flag, &index);
1240                         glPopMatrix();
1241                         if (arm->flag & ARM_POSEMODE)
1242                                 cpack (B_CYAN);
1243                 }
1244
1245                 arm->flag &= ~ARM_POSEMODE; 
1246         }
1247
1248         if (arm->flag & ARM_DRAWXRAY) {
1249                 if(G.zbuf) glEnable(GL_DEPTH_TEST);
1250         }
1251 }
1252
1253 static void draw_boneverti (float x, float y, float z, float size, int flag)
1254 {
1255         GLUquadricObj   *qobj;
1256
1257         size*=0.05;
1258
1259 /*
1260                 Ultimately dots should be drawn in screenspace
1261                 For now we'll just draw them any old way.
1262 */
1263         glPushMatrix();
1264
1265         glTranslatef(x, y, z);
1266
1267         qobj    = gluNewQuadric(); 
1268         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
1269         gluPartialDisk( qobj, 0,  1.0F*size, 32, 1, 360.0, 360.0);
1270
1271         glRotatef (90, 0, 1, 0);
1272         gluPartialDisk( qobj, 0,  1.0F*size, 32, 1, 360.0, 360.0);
1273
1274         glRotatef (90, 1, 0, 0);
1275         gluPartialDisk( qobj, 0,  1.0F*size, 32, 1, 360.0, 360.0);
1276
1277         gluDeleteQuadric(qobj);  
1278
1279         glPopMatrix();
1280 }
1281
1282 static void draw_bonechildren (Bone *bone, int flag, unsigned int *index)
1283 {
1284         Bone *cbone;
1285         float   delta[3];
1286         float   length;
1287         float M_objectspacemat[4][4];
1288
1289         if (bone==NULL) return;
1290         
1291         if (flag & ARM_POSEMODE){
1292                 if (bone->flag & BONE_SELECTED)
1293                         cpack (B_CYAN);
1294                 else
1295                         cpack (B_AQUA);
1296         }
1297         
1298         //      Draw a line from our root to the parent's tip
1299         if (bone->parent && !(bone->flag & (BONE_IK_TOPARENT|BONE_HIDDEN)) ){
1300                 float childMat[4][4];
1301                 float boneMat[4][4];
1302                 float tip[3], root[3];
1303                 get_objectspace_bone_matrix(bone->parent, boneMat, 0, 1);
1304                 get_objectspace_bone_matrix(bone, childMat, 1, 1);
1305                 
1306                 VECCOPY (tip, boneMat[3]);
1307                 VECCOPY (root, childMat[3]);
1308                 
1309                 if (flag & ARM_POSEMODE)
1310                         glLoadName (-1);
1311                 setlinestyle(3);
1312                 glBegin(GL_LINES);
1313                 glVertex3fv(tip);
1314                 glVertex3fv(root);
1315                 glEnd();
1316                 setlinestyle(0);
1317         }
1318         
1319         
1320         /* Draw this bone in objectspace */
1321         delta[0]=bone->tail[0]-bone->head[0];
1322         delta[1]=bone->tail[1]-bone->head[1];
1323         delta[2]=bone->tail[2]-bone->head[2];
1324         length = sqrt (delta[0]*delta[0] + delta[1]*delta[1] + delta[2]*delta[2] );
1325         
1326         /* Incorporates offset, rest rotation, user rotation and parent coordinates*/
1327         get_objectspace_bone_matrix(bone, M_objectspacemat, 1, 1);
1328         
1329         if (!(bone->flag & BONE_HIDDEN)){
1330                 glPushMatrix();
1331                 glMultMatrixf(M_objectspacemat);
1332                 
1333                 
1334                 if (flag & ARM_POSEMODE)
1335                         draw_bone(flag, (bone->parent && bone->parent->flag & BONE_HIDDEN) ? (bone->flag & ~BONE_IK_TOPARENT) : (bone->flag), *index, bone->name, length);
1336                 else
1337                         draw_bone(flag, (bone->parent && bone->parent->flag & BONE_HIDDEN) ? (bone->flag & ~BONE_IK_TOPARENT) : (bone->flag), -1, bone->name, length);
1338                 glPopMatrix();
1339         }
1340         (*index)++;
1341
1342         /* Draw the children */
1343         for (cbone= bone->childbase.first; cbone; cbone=cbone->next){
1344                 draw_bonechildren (cbone, flag, index);
1345         }
1346 }
1347
1348 static void draw_bone (int armflag, int boneflag, unsigned int id, char *name, float length)
1349 {
1350         float vec[2];
1351         float   bulge;
1352         float   pointsize;
1353         /* 
1354         FIXME: This routine should probably draw the bones in screenspace using
1355         the projected start & end points of the transformed bone 
1356         */
1357         
1358         pointsize = length;
1359         if (pointsize<0.1)
1360                 pointsize=0.1;
1361
1362         /*      Draw a 3d octahedral bone       */
1363         
1364         bulge=length*0.1;
1365
1366         if (id!=-1)
1367                 glLoadName((GLuint) id );
1368
1369         glPushMatrix();
1370
1371         /*      Draw root point if we have no IK parent */
1372         if (!(boneflag & BONE_IK_TOPARENT)){
1373                 if (id != -1)
1374                         glLoadName (id | BONESEL_ROOT);
1375                 if (armflag & ARM_EDITMODE){
1376                         if (boneflag & BONE_ROOTSEL)
1377                                 cpack (B_YELLOW);
1378                         else
1379                                 cpack (B_PURPLE);
1380                 }
1381                 draw_boneverti (0, 0, 0, pointsize, 0);
1382         }
1383
1384         /*      Draw tip point (for selection only )*/
1385
1386         if (id != -1)
1387                 glLoadName (id | BONESEL_TIP);
1388         
1389         if (armflag & ARM_EDITMODE){
1390                 if (boneflag & BONE_TIPSEL)
1391                         cpack (B_YELLOW);
1392                 else
1393                         cpack (B_PURPLE);
1394         }
1395         
1396         draw_boneverti (0, length, 0, pointsize, 0);
1397
1398         if (id != -1){
1399                 if (armflag & ARM_POSEMODE)
1400                         glLoadName((GLuint) id);
1401                 else{
1402 #if 1   /* Bones not selectable in editmode */  
1403                         glLoadName((GLuint) -1);
1404 #else
1405                         glLoadName ((GLuint) id|BONESEL_TIP|BONESEL_ROOT);
1406 #endif
1407                 }
1408         }
1409         
1410         
1411         if (armflag & ARM_EDITMODE){
1412                 if (boneflag & BONE_SELECTED)
1413                         cpack (B_YELLOW);
1414                 else
1415                         cpack (B_PURPLE);
1416         }
1417         
1418         /*      Draw additional axes */
1419         if (armflag & ARM_DRAWAXES){
1420                 drawaxes(length*0.25F);
1421         }
1422         
1423         /*      Section 1*/
1424         glBegin(GL_LINE_STRIP);
1425         vec[0]= vec[1]= 0;
1426         glVertex2fv(vec);
1427         
1428         vec[0]= -bulge; vec[1]= bulge;
1429         glVertex2fv(vec);
1430         
1431         vec[0]= 0; vec[1]= length;
1432         glVertex2fv(vec);
1433         
1434         vec[0]= bulge; vec[1]= bulge;
1435         glVertex2fv(vec);
1436         
1437         vec[0]= 0; vec[1]= 0;
1438         glVertex2fv(vec);
1439         glEnd();
1440         
1441         /*      Section 2*/
1442         glRotatef(90,0,1,0);
1443         glBegin(GL_LINE_STRIP);
1444         vec[0]= vec[1]= 0;
1445         glVertex2fv(vec);
1446         
1447         vec[0]= -bulge; vec[1]= bulge;
1448         glVertex2fv(vec);
1449         
1450         vec[0]= 0; vec[1]= length;
1451         glVertex2fv(vec);
1452         
1453         vec[0]= bulge; vec[1]= bulge;
1454         glVertex2fv(vec);
1455         
1456         vec[0]= 0; vec[1]= 0;
1457         glVertex2fv(vec);
1458         glEnd();
1459         
1460         /*      Square*/
1461         glTranslatef (0,bulge,0);
1462         glRotatef(45,0,1,0);
1463         glRotatef(90,1,0,0);
1464         glBegin(GL_LINE_STRIP);
1465         
1466         vec[0]= -bulge*.707;vec[1]=-bulge*.707;
1467         glVertex2fv(vec);
1468         
1469         vec[0]= bulge*.707;vec[1]= -bulge*.707;
1470         glVertex2fv(vec);
1471         
1472         vec[0]= bulge*.707;vec[1]= bulge*.707;
1473         glVertex2fv(vec);
1474         
1475         vec[0]= -bulge*.707;vec[1]= bulge*.707;
1476         glVertex2fv(vec);
1477         
1478         vec[0]= vec[1]= -bulge*.707;
1479         glVertex2fv(vec);
1480         glEnd();
1481         
1482
1483         glPopMatrix();
1484
1485         /*      Draw the bone name */
1486         if (armflag & ARM_DRAWNAMES){
1487                 glRasterPos3f(0,  length/2.0,  0);
1488                 BMF_DrawString(G.font, " ");
1489                 BMF_DrawString(G.font, name);
1490         }
1491 }
1492
1493
1494
1495 void add_primitiveArmature(int type)
1496 {
1497         if(G.scene->id.lib) return;
1498         
1499         /* this function also comes from an info window */
1500         if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
1501         if(G.vd==NULL) return;
1502         
1503         G.f &= ~(G_VERTEXPAINT+G_FACESELECT+G_TEXTUREPAINT+G_WEIGHTPAINT);
1504         setcursor_space(SPACE_VIEW3D, CURSOR_STD);
1505
1506         check_editmode(OB_ARMATURE);
1507         
1508         /* If we're not the "obedit", make a new object and enter editmode */
1509         if(G.obedit==NULL) {
1510                 add_object(OB_ARMATURE);
1511                 base_init_from_view3d(BASACT, G.vd);
1512                 G.obedit= BASACT->object;
1513                 
1514                 where_is_object(G.obedit);
1515                 
1516                 make_editArmature();
1517                 setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
1518         }
1519         
1520         switch (type){
1521         default:
1522                 add_bone_input (G.obedit);      
1523                 break;
1524         };
1525         
1526         countall();
1527
1528         allqueue(REDRAWALL, 0);
1529 }
1530
1531 static void add_bone_input (Object *ob)
1532 /*
1533         FUNCTION: 
1534         Creates a bone chain under user input.
1535         As the user clicks to accept each bone,
1536         a new bone is started as the child and IK
1537         child of the previous bone.  Pressing ESC
1538         cancels the current bone and leaves bone
1539         adding mode.
1540
1541 */
1542 {
1543         float           *cursLoc, cent[3], dx, dy;
1544         float           mat[3][3], curs[3],     cmat[3][3], imat[3][3], rmat[4][4], itmat[4][4];
1545         short           xo, yo, mval[2], afbreek=0;
1546         short           val;
1547         float           restmat[4][4], tempVec[4];
1548         EditBone        *bone;
1549         EditBone        *parent;
1550         unsigned short          event;
1551         float           angle, scale;
1552         float           length, lengths;
1553         float   newEnd[4];
1554         int                     addbones=1;
1555         float           dvec[3], dvecp[3];
1556         
1557         cursLoc= give_cursor();
1558         
1559         VECCOPY (curs,cursLoc);
1560         
1561         while (addbones>0){
1562                 afbreek=0;
1563                 /*      Create an inverse matrix */
1564                 Mat3CpyMat4(mat, G.obedit->obmat);
1565                 VECCOPY(cent, curs);
1566                 cent[0]-= G.obedit->obmat[3][0];
1567                 cent[1]-= G.obedit->obmat[3][1];
1568                 cent[2]-= G.obedit->obmat[3][2];
1569                 
1570                 Mat3CpyMat4(imat, G.vd->viewmat);
1571                 Mat3MulVecfl(imat, cent);
1572                 
1573                 Mat3MulMat3(cmat, imat, mat);
1574                 Mat3Inv(imat,cmat);
1575                 
1576                 /*      Create a temporary bone */
1577                 bone= MEM_callocN(sizeof(EditBone), "eBone");
1578                 
1579                 /*      If we're the child of something, set that up now */
1580                 if (addbones>1){
1581                         parent=G.edbo.last;
1582                         bone->parent=parent;
1583                         bone->flag|=BONE_IK_TOPARENT;
1584                 }
1585                 
1586                 strcpy (bone->name,"Bone");
1587                 unique_editbone_name (bone->name);
1588         
1589                 BLI_addtail(&G.edbo, bone);
1590         
1591                 bone->flag |= BONE_QUATROT;
1592                 bone->flag |= (BONE_SELECTED);
1593                 deselectall_armature();
1594                 bone->flag |= BONE_SELECTED|BONE_HILIGHTED|BONE_TIPSEL|BONE_ROOTSEL;
1595                 
1596                 bone->weight= 1.0F;
1597                 bone->dist= 1.0F;
1598                 bone->boneclass = BONE_SKINNABLE;
1599
1600                 /*      Project cursor center to screenspace. */
1601                 getmouseco_areawin(mval);
1602                 xo= mval[0];
1603                 yo= mval[1];
1604                 window_to_3d(dvecp, xo, yo);
1605
1606                 while (1) {
1607
1608                         getmouseco_areawin(mval);
1609                         window_to_3d(dvec, mval[0], mval[1]);
1610
1611                         scale=1000;
1612
1613                         dx=     ((float)mval[0]-(float)xo)*scale;
1614                         dy= ((float)mval[1]-(float)yo)*scale;
1615         
1616                         /*              Calc bone length*/
1617                         lengths= sqrt((dx*dx)+(dy*dy));
1618                         length = sqrt(((dvec[0]-dvecp[0])*(dvec[0]-dvecp[0]))+((dvec[1]-dvecp[1])*(dvec[1]-dvecp[1]))+((dvec[2]-dvecp[2])*(dvec[2]-dvecp[2])));
1619
1620                         /*              Find rotation around screen normal */
1621                         if (lengths>0.0F) {
1622                                 angle= acos(dy/lengths);
1623                                 if (dx<0.0F)
1624                                         angle*= -1.0F;
1625                         }
1626                         else angle= 0.0F;
1627                         
1628                         /*              FIXME:  Is there a blender-defined way of making rot and trans matrices? */
1629                         rmat[0][0]= cos (angle);
1630                         rmat[0][1]= -sin (angle);
1631                         rmat[0][2]= 0.0F;
1632                         rmat[0][3]= 0.0F;
1633                         rmat[1][0]= sin (angle);
1634                         rmat[1][1]= cos (angle);
1635                         rmat[1][2]= 0.0F;
1636                         rmat[1][3]= 0.0F;
1637                         rmat[2][0]= 0.0F;
1638                         rmat[2][1]= 0.0F;
1639                         rmat[2][2]= 1.0F;
1640                         rmat[2][3]= 0.0F;
1641                         rmat[3][0]= cent[0];
1642                         rmat[3][1]= cent[1];
1643                         rmat[3][2]= cent[2];
1644                         rmat[3][3]= 1.0F;
1645                         
1646                         /*              Rotate object's inversemat by the bone's rotation
1647                         to get the coordinate space of the bone */
1648                         Mat4CpyMat3     (itmat, imat);
1649                         Mat4MulMat4 (restmat, rmat, itmat);
1650                         
1651                         /*      Find the bone head */
1652                         tempVec[0]=0; tempVec[1]=0.0F; tempVec[2]=0.0F; tempVec[3]=1.0F;
1653                         Mat4MulVec4fl (restmat, tempVec);
1654                         VECCOPY (bone->head, tempVec);
1655                         
1656                         /*      Find the bone tail */
1657                         tempVec[0]=0; tempVec[1]=length; tempVec[2]=0.0F; tempVec[3]=1.0F;
1658                         Mat4MulVec4fl (restmat, tempVec);
1659                         VECCOPY (bone->tail, tempVec);
1660                         
1661                         /*      IF we're a child of something, add the parents' translates      */
1662                         
1663                         /*      Offset of child is new cursor*/
1664
1665                         VECCOPY (newEnd,bone->tail); newEnd[3]=1;
1666
1667                         /*      Set the bone's transformations  */
1668                         Mat4One (bone->obmat);
1669                         bone->size[0]=bone->size[1]=bone->size[2]=1.0F;
1670
1671                         force_draw();
1672                         while(qtest()) {
1673                                 event= extern_qread(&val);
1674                                 if(val) {
1675                                         switch(event) {
1676                                         case ESCKEY:
1677                                         case RIGHTMOUSE:
1678                                                 BLI_freelinkN (&G.edbo,bone);
1679                                                 afbreek=1;
1680                                                 addbones=0;
1681                                                 break;
1682                                         case LEFTMOUSE:
1683                                         case MIDDLEMOUSE:
1684                                         case SPACEKEY:
1685                                         case RETKEY:
1686                                                 afbreek= 1;
1687                                                                                         
1688                                                 Mat4MulVec4fl (G.obedit->obmat,newEnd);
1689                                                 
1690                                                 curs[0]=newEnd[0];
1691                                                 curs[1]=newEnd[1];
1692                                                 curs[2]=newEnd[2];
1693                                                 addbones++;
1694                                                 break;
1695                                         }       /*      End of case*/
1696                                 }       /*      End of if (val)*/
1697                                 if(afbreek) break;
1698                         }       /*      Endd of Qtest loop      */
1699
1700                 if(afbreek) break;
1701                 }/*     End of positioning loop (while)*/
1702         }       /*      End of bone adding loop*/
1703         
1704         countall();
1705
1706 }
1707
1708
1709 void deselectall_armature(void)
1710 /*      Actually, it toggles selection, deselecting
1711         everything if anything is selected */
1712 {
1713         EditBone        *eBone;
1714         int                     sel=1;
1715         
1716         
1717         /*      Determine if there are any selected bones
1718                 And therefore whether we are selecting or deselecting */
1719         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1720                 if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1721                         sel=0;
1722                         break;
1723                 };
1724         };
1725         
1726         /*      Set the flags */
1727         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1728                 if (sel)
1729                         eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1730                 else
1731                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1732         };
1733         allqueue(REDRAWVIEW3D, 0);
1734         allqueue(REDRAWBUTSEDIT, 0);
1735         allqueue(REDRAWBUTSHEAD, 0);
1736         allqueue(REDRAWBUTSOBJECT, 0);
1737         countall();
1738 }
1739
1740 void join_armature(void)
1741 {
1742         
1743         Object  *ob;
1744         Base    *base, *nextbase;
1745         ListBase eblist;
1746         EditBone *curbone, *next;
1747         float   mat[4][4], imat[4][4];
1748         
1749         /*      Ensure we're not in editmode and that the active object is an armature*/
1750         if(G.obedit) return;
1751         
1752         ob= OBACT;
1753         if(ob->type!=OB_ARMATURE) return;
1754         
1755         /*      Make sure the user wants to continue*/
1756         if(okee("Join selected Armatures")==0) return;
1757         
1758         /*      Put the active armature into editmode and join the bones from the other one*/
1759 #if 1
1760         enter_editmode();
1761 #else
1762         baselist.first=baselist.last=0;
1763         make_boneList(&baselist, &((bArmature*)ob->data)->bonebase, NULL);
1764 #endif
1765         
1766         for (base=FIRSTBASE; base; base=nextbase) {
1767                 nextbase = base->next;
1768                 if (TESTBASE(base)){
1769                         if ((base->object->type==OB_ARMATURE) && (base->object!=ob)){
1770                                 /* Make a list of editbones */
1771                                 eblist.first=eblist.last=0;
1772                                 make_boneList (&eblist, &((bArmature*)base->object->data)->bonebase,NULL);
1773                                 /* Find the difference matrix */
1774                                 Mat4Invert(imat, ob->obmat);
1775                                 Mat4MulMat4(mat, base->object->obmat, imat);
1776                                 
1777                                 /* Copy bones from the object to the edit armature */
1778                                 for (curbone=eblist.first; curbone; curbone=next){
1779                                         next = curbone->next;
1780                                         
1781                                         /* Blank out tranformation data */
1782                                         curbone->loc[0]=curbone->loc[1]=curbone->loc[2]=0.0F;
1783                                         curbone->size[0]=curbone->size[1]=curbone->size[2]=1.0F;
1784                                         curbone->quat[0]=curbone->quat[1]=curbone->quat[2]=curbone->quat[3]=0.0F;
1785                                         
1786                                         unique_editbone_name (curbone->name);
1787                                         
1788                                         /* Transform the bone */
1789                                         {
1790                                                 float premat[4][4];
1791                                                 float postmat[4][4];
1792                                                 float difmat[4][4];
1793                                                 float imat[4][4];
1794                                                 float temp[4][4];
1795                                                 float delta[3];
1796
1797                                                 /* Get the premat */
1798                                                 VecSubf (delta, curbone->tail, curbone->head);
1799                                                 make_boneMatrixvr(temp, delta, curbone->roll);
1800                                                 Mat4MulMat4 (premat, temp, mat);
1801
1802                                                 Mat4MulVecfl(mat, curbone->head);
1803                                                 Mat4MulVecfl(mat, curbone->tail);
1804
1805                                                 /* Get the postmat */
1806                                                 VecSubf (delta, curbone->tail, curbone->head);
1807                                                 make_boneMatrixvr(postmat, delta, curbone->roll);
1808                                                 
1809                                                 /* Find the roll */
1810                                                 Mat4Invert (imat, premat);
1811                                                 Mat4MulMat4 (difmat, postmat, imat);
1812                                                 
1813                                                 curbone->roll -=atan(difmat[2][0]/difmat[2][2]);
1814                                                 
1815                                                 if (difmat[0][0]<0)
1816                                                         curbone->roll +=M_PI;
1817
1818                                         }
1819 #if 1
1820                                         BLI_remlink(&eblist, curbone);
1821                                         BLI_addtail(&G.edbo, curbone);
1822 #else
1823                                         BLI_remlink(&eblist, curbone);
1824                                         BLI_addtail(&baselist, curbone);
1825 #endif
1826                                 }
1827                                 
1828                                 free_and_unlink_base(base);
1829                         }
1830                 }
1831         }
1832         
1833 #if 1
1834         exit_editmode(1);
1835 #else
1836         editbones_to_armature(&baselist, ob);
1837         if (baselist.first){
1838                 BLI_freelistN (&baselist);
1839         }
1840 #endif
1841         allqueue(REDRAWVIEW3D, 0);
1842
1843 }
1844
1845
1846 static int      editbone_name_exists (char *name){
1847         EditBone        *eBone;
1848         
1849         for (eBone=G.edbo.first; eBone; eBone=eBone->next){
1850                 if (!strcmp (name, eBone->name))
1851                         return 1;
1852         }
1853         
1854         return 0;
1855                 
1856 }
1857
1858 void unique_editbone_name (char *name){
1859         char            tempname[64];
1860         int                     number;
1861         char            *dot;
1862         
1863         
1864         if (editbone_name_exists(name)){
1865                 /*      Strip off the suffix */
1866                 dot=strchr(name, '.');
1867                 if (dot)
1868                         *dot=0;
1869                 
1870                 for (number = 1; number <=999; number++){
1871                         sprintf (tempname, "%s.%03d", name, number);
1872                         if (!editbone_name_exists(tempname)){
1873                                 strcpy (name, tempname);
1874                                 return;
1875                         }
1876                 }
1877         }
1878 }
1879
1880 void extrude_armature(void)
1881 {
1882         EditBone *newbone, *curbone, *first=NULL, *partest;
1883         
1884         TEST_EDITARMATURE;
1885         
1886         
1887         if(okee("Extrude Bone Segments")==0) return;
1888         
1889         /* Duplicate the necessary bones */
1890         for (curbone = G.edbo.first; ((curbone) && (curbone!=first)); curbone=curbone->next){
1891                 if (curbone->flag & (BONE_TIPSEL|BONE_SELECTED)){
1892                         newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
1893                         
1894                         
1895                         VECCOPY (newbone->head, curbone->tail);
1896                         VECCOPY (newbone->tail, newbone->head);
1897                         newbone->parent = curbone;
1898                         newbone->flag = BONE_TIPSEL;
1899                         newbone->flag |= BONE_QUATROT;
1900                         newbone->weight= curbone->weight;
1901                         newbone->dist= curbone->dist;
1902                         newbone->boneclass= curbone->boneclass;
1903
1904                         Mat4One(newbone->obmat);
1905                         
1906                         /* See if there are any ik children of the parent */
1907                         for (partest = G.edbo.first; partest; partest=partest->next){
1908                                 if ((partest->parent == curbone) && (partest->flag & BONE_IK_TOPARENT))
1909                                         break;
1910                         }
1911                         
1912                         if (!partest)
1913                                 newbone->flag |= BONE_IK_TOPARENT;
1914                         
1915                         strcpy (newbone->name, curbone->name);
1916                         unique_editbone_name(newbone->name);
1917                         
1918                         /* Add the new bone to the list */
1919                         BLI_addtail(&G.edbo, newbone);
1920                         if (!first)
1921                                 first = newbone;
1922                 }
1923                 
1924                 /* Deselect the old bone */
1925                 curbone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
1926                 
1927         }
1928         
1929         /* Transform the endpoints */
1930         countall();
1931         transform('g');         
1932         allqueue(REDRAWBUTSEDIT, 0);
1933         allqueue(REDRAWBUTSOBJECT, 0);
1934 }
1935
1936 void addvert_armature(void)
1937 {
1938 /*      
1939         I haven't decided if it will be possible to add bones in this way.
1940         For the moment, we'll use Extrude, or explicit parenting.
1941         */
1942 }
1943
1944
1945
1946
1947
1948 void adduplicate_armature(void)
1949 {
1950         EditBone        *eBone = NULL;
1951         EditBone        *curBone;
1952         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
1953
1954         countall();
1955
1956         /*      Find the selected bones and duplicate them as needed */
1957         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1958                 if (curBone->flag & BONE_SELECTED){
1959
1960                         eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
1961                         eBone->flag |= BONE_SELECTED;
1962
1963                         /*      Copy data from old bone to new bone */
1964                         memcpy (eBone, curBone, sizeof(EditBone));
1965
1966                         /* Blank out tranformation data */
1967                         eBone->loc[0]=eBone->loc[1]=eBone->loc[2]=0.0F;
1968                         eBone->size[0]=eBone->size[1]=eBone->size[2]=1.0F;
1969                         eBone->quat[0]=eBone->quat[1]=eBone->quat[2]=eBone->quat[3]=0.0F;
1970
1971                         curBone->temp = eBone;
1972                         eBone->temp = curBone;
1973
1974                         unique_editbone_name (eBone->name);
1975                         BLI_addtail (&G.edbo, eBone);
1976                         if (!firstDup)
1977                                 firstDup=eBone;
1978                 }
1979         }
1980
1981         if (eBone){
1982                 /*      Fix the head and tail */        
1983                 if (eBone->parent && !eBone->parent->flag & BONE_SELECTED){
1984                         VecSubf (eBone->tail, eBone->tail, eBone->head);
1985                         VecSubf (eBone->head, eBone->head, eBone->head);
1986                 }
1987         }
1988
1989         /*      Run though the list and fix the pointers */
1990         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1991
1992                 if (curBone->flag & BONE_SELECTED){
1993                         eBone=(EditBone*) curBone->temp;
1994
1995                         /*      If this bone has no parent,
1996                                         Set the duplicate->parent to NULL
1997                         */
1998                         if (!curBone->parent){
1999                                 eBone->parent = NULL;
2000                         }
2001                         /*      If this bone has a parent that IS selected,
2002                                         Set the duplicate->parent to the curBone->parent->duplicate
2003                         */
2004                          else if (curBone->parent->flag & BONE_SELECTED){
2005                                 eBone->parent=(EditBone*) curBone->parent->temp;
2006                         }
2007                         /*      If this bone has a parent that IS not selected,
2008                                         Set the duplicate->parent to the curBone->parent
2009                         */
2010                          else {
2011                                 eBone->parent=(EditBone*) curBone->parent; 
2012                                 eBone->flag &= ~BONE_IK_TOPARENT;
2013                         }
2014                          
2015                 }
2016         } 
2017         
2018         /*      Deselect the old bones and select the new ones */
2019
2020         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
2021                 curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2022         }
2023
2024
2025         transform('g');
2026         allqueue(REDRAWBUTSEDIT, 0);
2027         allqueue(REDRAWBUTSOBJECT, 0);
2028 }
2029
2030 /*
2031  *
2032  *      POSING FUNCTIONS: Maybe move these to a separate file at some point
2033  *
2034  *
2035  */
2036
2037
2038 void clear_armature(Object *ob, char mode){
2039         Bone    *curBone;
2040         bArmature       *arm;
2041
2042         arm=get_armature(ob);
2043         
2044         if (!arm)
2045                 return;
2046
2047         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
2048                 clear_armature_children (curBone, ob->pose, mode);
2049         }
2050
2051         where_is_armature (ob);
2052
2053 }
2054
2055 static void clear_armature_children (Bone *bone, bPose *pose, char mode){
2056         Bone                    *curBone;
2057         bPoseChannel    *chan;
2058         if (!bone)
2059                 return;
2060         
2061         chan = verify_pose_channel (pose, bone->name);
2062
2063         if (!chan)
2064                 return;
2065
2066         if (bone->flag & BONE_SELECTED){
2067                 switch (mode){
2068                 case 'r':
2069                         chan->quat[1]=chan->quat[2]=chan->quat[3]=0.0F; chan->quat[0]=1.0F;
2070                         break;
2071                 case 'g':
2072                         chan->loc[0]=chan->loc[1]=chan->loc[2]=0.0F;
2073                         break;
2074                 case 's':
2075                         chan->size[0]=chan->size[1]=chan->size[2]=1.0F;
2076                         break;
2077                         
2078                 }
2079         }
2080
2081         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
2082                 clear_armature_children (curBone, pose, mode);
2083         }
2084
2085 }
2086
2087 void mousepose_armature(void)
2088 /*
2089         Handles right-clicking for selection
2090         of bones in armature pose modes.
2091 */
2092 {
2093         Bone            *nearBone;
2094
2095         if (!G.obpose)
2096                 return;
2097
2098         nearBone = get_nearest_bone(1);
2099
2100         if (nearBone){
2101                 if (!(G.qual & LR_SHIFTKEY)){
2102                         deselectall_posearmature(0);
2103                         nearBone->flag|=BONE_SELECTED;
2104                         select_actionchannel_by_name(G.obpose->action, nearBone->name, 1);
2105                 }
2106                 else {
2107                         if (nearBone->flag & BONE_SELECTED){
2108                                 nearBone->flag &= ~BONE_SELECTED;
2109                                 select_actionchannel_by_name(G.obpose->action, nearBone->name, 0);
2110                         }
2111                         else{
2112                                 nearBone->flag |= BONE_SELECTED;
2113                                 select_actionchannel_by_name(G.obpose->action, nearBone->name, 1);
2114                         }
2115                 };
2116         }
2117
2118         allqueue(REDRAWVIEW3D, 0);
2119         allqueue(REDRAWACTION, 0);
2120         allqueue(REDRAWIPO, 0);         /* To force action ipo update */
2121         allqueue(REDRAWBUTSOBJECT, 0);
2122
2123 //      countall();
2124         rightmouse_transform();
2125         
2126 }
2127
2128 void make_trans_bones (char mode)
2129 /*      Used in pose mode       */
2130 {
2131         bArmature               *arm;
2132         Bone                    *curBone;
2133         int                             count=0;
2134
2135         transmain=NULL;
2136
2137         arm=get_armature (G.obpose);
2138         if (!arm)
2139                 return;
2140
2141         if (arm->flag & ARM_RESTPOS){
2142                 notice ("Transformation not possible while Rest Position is enabled");
2143                 return;
2144         }
2145
2146
2147         if (!(G.obpose->lay & G.vd->lay))
2148                 return;
2149
2150
2151         centroid[0]=centroid[1]=centroid[2]=0;
2152
2153         apply_pose_armature(arm, G.obpose->pose, 0);
2154         where_is_armature (G.obpose);
2155
2156         /*      Allocate memory for the transformation record */
2157         tottrans= count_bones (arm, BONE_SELECTED, 0);
2158
2159         if (!tottrans)
2160                 return;
2161
2162         transmain= MEM_callocN(tottrans*sizeof(TransOb), "bonetransmain");
2163
2164         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
2165                 count = add_trans_bonechildren (G.obpose, curBone, transmain, count, mode);
2166         }
2167         
2168         tottrans=count;
2169         
2170         if (tottrans){
2171                 centroid[0]/=tottrans;
2172                 centroid[1]/=tottrans;
2173                 centroid[2]/=tottrans;
2174                 Mat4MulVecfl (G.obpose->obmat, centroid);
2175         }
2176         else{
2177                 MEM_freeN (transmain);
2178         }
2179         return;
2180
2181 }
2182
2183 static int      count_bones (bArmature *arm, int flagmask, int allbones)
2184 {
2185         int     count=0;
2186         Bone    *curBone;
2187
2188         if (!arm)
2189                 return 0;
2190
2191         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
2192                 count = count_bonechildren (curBone, count, flagmask, allbones);
2193         }
2194
2195         return count;
2196
2197 }
2198
2199 static int count_bonechildren (Bone *bone, int incount, int flagmask, int allbones){
2200
2201         Bone    *curBone;
2202
2203         if (!bone)
2204                 return incount;
2205
2206         if (bone->flag & flagmask || flagmask == 0xFFFFFFFF){
2207                 incount++;
2208                 if (!allbones)
2209                         return incount;
2210         }
2211
2212         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
2213                 incount=count_bonechildren (curBone, incount, flagmask, allbones);
2214         }
2215
2216         return incount;
2217 }
2218
2219
2220 static int add_trans_bonechildren (Object* ob, Bone* bone, TransOb* buffer, int index, char mode)
2221 {
2222         Bone    *curBone;
2223         TransOb *curOb;
2224         float   parmat[4][4], tempmat[4][4];
2225         float tempobmat[4][4];
2226         float vec[3];
2227         if (!bone)
2228                 return index;
2229
2230         
2231         
2232         /* We don't let IK children get "grabbed" */
2233         if (bone->flag & BONE_SELECTED){
2234                 if (!((mode=='g' || mode=='G') && (bone->flag & BONE_IK_TOPARENT))){
2235                         
2236                         get_bone_root_pos (bone, vec, 1);
2237                 
2238                         VecAddf (centroid, centroid, vec);
2239                         
2240                         curOb=&buffer[index];
2241                         
2242                         curOb->ob = ob;
2243                         curOb->rot=NULL;
2244
2245                         curOb->quat= bone->quat;
2246                         curOb->size= bone->size;
2247                         curOb->loc = bone->loc;
2248
2249                         curOb->data = bone; //  FIXME: Dangerous
2250                         
2251                         memcpy (curOb->oldquat, bone->quat, sizeof (bone->quat));
2252                         memcpy (curOb->oldsize, bone->size, sizeof (bone->size));
2253                         memcpy (curOb->oldloc, bone->loc, sizeof (bone->loc));
2254
2255 #if 0
2256                         if (bone->parent)
2257                                 get_objectspace_bone_matrix(bone->parent, tempmat, 1, 1);
2258                         else
2259                                 Mat4One (tempmat);
2260 #else
2261                         /* Get the matrix of this bone minus the usertransform */
2262                         Mat4CpyMat4 (tempobmat, bone->obmat);
2263                         Mat4One (bone->obmat);
2264                         get_objectspace_bone_matrix(bone, tempmat, 1, 1);
2265                         Mat4CpyMat4 (bone->obmat, tempobmat);
2266
2267                         
2268 #endif
2269
2270 #if 1
2271                         Mat4MulMat4 (parmat, tempmat, ob->obmat);       /* Original */
2272
2273                         /* Get world transform */
2274                         get_objectspace_bone_matrix(bone, tempmat, 1, 1);
2275                         if (ob->parent){
2276                                 where_is_object(ob->parent);
2277                                 Mat4MulSerie (tempobmat, ob->parent->obmat, ob->obmat, tempmat, NULL, NULL, NULL, NULL, NULL);
2278                         }
2279                         else
2280                                 Mat4MulSerie (tempobmat, ob->obmat, tempmat, NULL, NULL, NULL, NULL, NULL, NULL);
2281                         Mat3CpyMat4 (curOb->axismat, tempobmat);
2282                         Mat3Ortho(curOb->axismat);
2283
2284 #else
2285                         Mat4MulMat4 (parmat, ob->obmat, tempmat);
2286 #endif
2287                         Mat3CpyMat4 (curOb->parmat, parmat);
2288                         Mat3Inv (curOb->parinv, curOb->parmat);
2289
2290                         Mat3CpyMat4 (curOb->obmat, bone->obmat);
2291                         Mat3Inv (curOb->obinv, curOb->obmat);
2292                         
2293                         index++;
2294                         return index;
2295                 }
2296
2297         }
2298         
2299         /*      Recursively search  */
2300         for (curBone = bone->childbase.first; curBone; curBone=curBone->next){
2301                 index=add_trans_bonechildren (ob, curBone, buffer, index, mode);
2302         }
2303
2304         return index;
2305 }
2306
2307 static void deselect_bonechildren (Bone *bone, int mode)
2308 {
2309         Bone    *curBone;
2310
2311         if (!bone)
2312                 return;
2313
2314         if (mode==0)
2315                 bone->flag &= ~BONE_SELECTED;
2316         else if (!(bone->flag & BONE_HIDDEN))
2317                 bone->flag |= BONE_SELECTED;
2318
2319         select_actionchannel_by_name(G.obpose->action, bone->name, mode);
2320
2321         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
2322                 deselect_bonechildren(curBone, mode);
2323         }
2324 }
2325
2326
2327 void deselectall_posearmature (int test){
2328         int     selectmode      =       0;
2329         Bone*   curBone;
2330         
2331         /*      Determine if we're selecting or deselecting     */
2332         if (test){
2333                 if (!count_bones (get_armature(G.obpose), BONE_SELECTED, 0))
2334                         selectmode = 1;
2335         }
2336         
2337         /*      Set the flags accordingly       */
2338         for (curBone=get_armature(G.obpose)->bonebase.first; curBone; curBone=curBone->next)
2339                 deselect_bonechildren (curBone, selectmode);
2340         
2341         allqueue(REDRAWVIEW3D, 0);
2342         allqueue(REDRAWACTION, 0);
2343
2344 }
2345
2346 void auto_align_armature(void)
2347 /* Sets the roll value of selected bones so that their zaxes point upwards */
2348 {
2349         EditBone *ebone;
2350         float   xaxis[3]={1.0, 0.0, 0.0}, yaxis[3], zaxis[3]={0.0, 0.0, 1.0};
2351         float   targetmat[4][4], imat[4][4];
2352         float   curmat[4][4], diffmat[4][4];
2353         float   delta[3];
2354
2355         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
2356                 if (ebone->flag & BONE_SELECTED){
2357                         /* Find the current bone matrix */
2358                         VecSubf(delta, ebone->tail, ebone->head);
2359                         make_boneMatrixvr (curmat, delta, 0.0);
2360                         
2361                         /* Make new matrix based on y axis & z-up */
2362                         VECCOPY (yaxis, curmat[1]);
2363
2364                         Mat4One(targetmat);
2365                         VECCOPY (targetmat[0], xaxis);
2366                         VECCOPY (targetmat[1], yaxis);
2367                         VECCOPY (targetmat[2], zaxis);
2368                         Mat4Ortho(targetmat);
2369
2370                         /* Find the difference between the two matrices */
2371
2372                         Mat4Invert (imat, targetmat);
2373                         Mat4MulMat4(diffmat, curmat, imat);
2374
2375                         ebone->roll = atan(diffmat[2][0]/diffmat[2][2]);
2376                         
2377                 }
2378         }
2379
2380
2381 int bone_looper(Object *ob, Bone *bone, void *data,
2382                         int (*bone_func)(Object *, Bone *, void *)) {
2383
2384     /* We want to apply the function bone_func to every bone 
2385      * in an armature -- feed bone_looper the first bone and 
2386      * a pointer to the bone_func and watch it go!. The int count 
2387      * can be useful for counting bones with a certain property
2388      * (e.g. skinnable)
2389      */
2390     int count = 0;
2391
2392     if (bone) {
2393
2394         /* only do bone_func if the bone is non null
2395          */
2396         count += bone_func(ob, bone, data);
2397
2398         /* try to execute bone_func for the first child
2399          */
2400         count += bone_looper(ob, bone->childbase.first, data,
2401                                     bone_func);
2402
2403         /* try to execute bone_func for the next bone at this
2404          * depth of the recursion.
2405          */
2406         count += bone_looper(ob, bone->next, data, bone_func);
2407     }
2408
2409     return count;
2410 }
2411
2412 int bone_skinnable(Object *ob, Bone *bone, void *data)
2413 {
2414     /* Bones that are not of boneclass BONE_UNSKINNABLE
2415      * are regarded to be "skinnable" and are eligible for
2416      * auto-skinning.
2417      *
2418      * This function performs 2 functions:
2419      *
2420      *   a) It returns 1 if the bone is skinnable.
2421      *      If we loop over all bones with this 
2422      *      function, we can count the number of
2423      *      skinnable bones.
2424      *   b) If the pointer data is non null,
2425      *      it is treated like a handle to a
2426      *      bone pointer -- the bone pointer
2427      *      is set to point at this bone, and
2428      *      the pointer the handle points to
2429      *      is incremented to point to the
2430      *      next member of an array of pointers
2431      *      to bones. This way we can loop using
2432      *      this function to construct an array of
2433      *      pointers to bones that point to all
2434      *      skinnable bones.
2435      */
2436     Bone ***hbone;
2437
2438     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2439                 if (data != NULL) {
2440                         hbone = (Bone ***) data;
2441             **hbone = bone;
2442             ++*hbone;
2443         }
2444         return 1;
2445     }
2446     return 0;
2447 }
2448
2449 int add_defgroup_unique_bone(Object *ob, Bone *bone, void *data) {
2450     /* This group creates a vertex group to ob that has the
2451      * same name as bone (provided the bone is skinnable). 
2452          * If such a vertex group aleady exist the routine exits.
2453      */
2454         if ( bone_skinnable(ob, bone, NULL) ) {
2455                 if (!get_named_vertexgroup(ob,bone->name)) {
2456                         add_defgroup_name(ob, bone->name);
2457                         return 1;
2458                 }
2459     }
2460     return 0;
2461 }
2462
2463 int dgroup_skinnable(Object *ob, Bone *bone, void *data) {
2464     /* Bones that are not of boneclass BONE_UNSKINNABLE
2465      * are regarded to be "skinnable" and are eligible for
2466      * auto-skinning.
2467      *
2468      * This function performs 2 functions:
2469      *
2470      *   a) If the bone is skinnable, it creates 
2471      *      a vertex group for ob that has
2472      *      the name of the skinnable bone
2473      *      (if one doesn't exist already).
2474      *   b) If the pointer data is non null,
2475      *      it is treated like a handle to a
2476      *      bDeformGroup pointer -- the 
2477      *      bDeformGroup pointer is set to point
2478      *      to the deform group with the bone's
2479      *      name, and the pointer the handle 
2480      *      points to is incremented to point to the
2481      *      next member of an array of pointers
2482      *      to bDeformGroups. This way we can loop using
2483      *      this function to construct an array of
2484      *      pointers to bDeformGroups, all with names
2485      *      of skinnable bones.
2486      */
2487     bDeformGroup ***hgroup, *defgroup;
2488
2489     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2490         if ( !(defgroup = get_named_vertexgroup(ob, bone->name)) ) {
2491             defgroup = add_defgroup_name(ob, bone->name);
2492         }
2493
2494         if (data != NULL) {
2495             hgroup = (bDeformGroup ***) data;
2496             **hgroup = defgroup;
2497             ++*hgroup;
2498         }
2499         return 1;
2500     }
2501     return 0;
2502 }
2503
2504 void add_verts_to_closest_dgroup(Object *ob, Object *par)
2505 {
2506     /* This function implements a crude form of 
2507      * auto-skinning: vertices are assigned to the
2508      * deformation groups associated with bones based
2509      * on thier proximity to a bone. Every vert is
2510      * given a weight of 1.0 to the weight group
2511      * cooresponding to the bone that it is
2512      * closest to. The vertex may also be assigned to
2513      * a deformation group associated to a bone
2514      * that is within 10% of the mninimum distance
2515      * between the bone and the nearest vert -- the
2516      * cooresponding weight will fall-off to zero
2517      * as the distance approaches the 10% tolerance mark.
2518          * If the mesh has subsurf enabled then the verts
2519          * on the subsurf limit surface is used to generate 
2520          * the weights rather than the verts on the cage
2521          * mesh.
2522      */
2523
2524     bArmature *arm;
2525     Bone **bonelist, **bonehandle, *bone;
2526     bDeformGroup **dgrouplist, **dgrouphandle, *defgroup;
2527     float *distance, mindist = 0.0, weight = 0.0;
2528     float   root[3];
2529     float   tip[3];
2530     float real_co[3];
2531         float *subverts = NULL;
2532     float *subvert;
2533     Mesh  *mesh;
2534     MVert *vert;
2535
2536     int numbones, i, j;
2537
2538     /* If the parent object is not an armature exit */
2539     arm = get_armature(par);
2540     if (!arm)
2541         return;
2542
2543     /* count the number of skinnable bones */
2544     numbones = bone_looper(ob, arm->bonebase.first, NULL,
2545                                   bone_skinnable);
2546
2547     /* create an array of pointer to bones that are skinnable
2548      * and fill it with all of the skinnable bones
2549      */
2550     bonelist = MEM_mallocN(numbones*sizeof(Bone *), "bonelist");
2551     bonehandle = bonelist;
2552     bone_looper(ob, arm->bonebase.first, &bonehandle,
2553                        bone_skinnable);
2554
2555     /* create an array of pointers to the deform groups that
2556      * coorespond to the skinnable bones (creating them
2557      * as necessary.
2558      */
2559     dgrouplist = MEM_mallocN(numbones*sizeof(bDeformGroup *), "dgrouplist");
2560     dgrouphandle = dgrouplist;
2561     bone_looper(ob, arm->bonebase.first, &dgrouphandle,
2562                        dgroup_skinnable);
2563
2564     /* create an array of floats that will be used for each vert
2565      * to hold the distance to each bone.
2566      */
2567     distance = MEM_mallocN(numbones*sizeof(float), "distance");
2568
2569     mesh = (Mesh*)ob->data;
2570
2571         /* Is subsurf on? Lets use the verts on the limit surface then */
2572         if ( (mesh->flag&ME_SUBSURF) && (mesh->subdiv > 0) ) {
2573                 subverts = MEM_mallocN(3*mesh->totvert*sizeof(float), "subverts");
2574                 subsurf_calculate_limit_positions(mesh, (void *)subverts);      /* (ton) made void*, dunno how to cast */
2575         }
2576
2577     /* for each vertex in the mesh ...
2578      */
2579     for ( i=0 ; i < mesh->totvert ; ++i ) {
2580         /* get the vert in global coords
2581          */
2582                 
2583                 if (subverts) {
2584                         subvert = subverts + i*3;
2585                         VECCOPY (real_co, subvert);
2586                 }
2587                 else {
2588                         vert = mesh->mvert + i;
2589                         VECCOPY (real_co, vert->co);
2590                 }
2591         Mat4MulVecfl(ob->obmat, real_co);
2592
2593
2594         /* for each skinnable bone ...
2595          */
2596         for (j=0; j < numbones; ++j) {
2597             bone = bonelist[j];
2598
2599             /* get the root of the bone in global coords
2600              */
2601             get_bone_root_pos (bone, root, 0);
2602             Mat4MulVecfl(par->obmat, root);
2603
2604             /* get the tip of the bone in global coords
2605              */
2606             get_bone_tip_pos (bone, tip, 0);
2607             Mat4MulVecfl(par->obmat, tip);
2608
2609             /* store the distance from the bone to
2610              * the vert
2611              */
2612             distance[j] = dist_to_bone(real_co, root, tip);
2613
2614             /* if this is the first bone, or if this
2615              * bone is less than mindist, then set this
2616              * distance to mindist
2617              */
2618             if (j == 0) {
2619                 mindist = distance[j];
2620             }
2621             else if (distance[j] < mindist) {
2622                 mindist = distance[j];
2623             }
2624         }
2625
2626         /* for each deform group ...
2627          */
2628         for (j=0; j < numbones; ++j) {
2629             defgroup = dgrouplist[j];
2630
2631             /* if the cooresponding bone is the closest one
2632              * add the vert to the deform group with weight 1
2633              */
2634             if (distance[j] <= mindist) {
2635                 add_vert_to_defgroup (ob, defgroup, i, 1.0, WEIGHT_REPLACE);
2636             }
2637
2638             /* if the cooresponding bone is within 10% of the
2639              * nearest distance, add the vert to the
2640              * deform group with a weight that declines with
2641              * distance
2642              */
2643             else if (distance[j] <= mindist*1.10) {
2644                 if (mindist > 0)
2645                     weight = 1.0 - (distance[j] - mindist) / (mindist * 0.10);
2646                 add_vert_to_defgroup (ob, defgroup, i, weight, WEIGHT_REPLACE);
2647             }
2648             
2649             /* if the cooresponding bone is outside of the 10% tolerance
2650              * then remove the vert from the weight group (if it is
2651              * in that group)
2652              */
2653             else {
2654                 remove_vert_defgroup (ob, defgroup, i);
2655             }
2656         }
2657     }
2658
2659     /* free the memory allocated
2660      */
2661     MEM_freeN(bonelist);
2662     MEM_freeN(dgrouplist);
2663     MEM_freeN(distance);
2664         if (subverts) MEM_freeN(subverts);
2665 }
2666
2667 void create_vgroups_from_armature(Object *ob, Object *par)
2668 {
2669         /* Lets try to create some vertex groups 
2670          * based on the bones of the parent armature.
2671          */
2672
2673         bArmature *arm;
2674         short mode;
2675
2676         /* If the parent object is not an armature exit */
2677         arm = get_armature(par);
2678         if (!arm)
2679                 return;
2680
2681         /* Prompt the user on whether/how they want the vertex groups
2682          * added to the child mesh */
2683     mode= pupmenu("Create Vertex Groups? %t|"
2684                                   "Don't Create Groups %x1|"
2685                                   "Name Groups %x2|"
2686                   "Create From Closest Bones %x3");
2687         switch (mode){
2688         case 2:
2689                 /* Traverse the bone list, trying to create empty vertex 
2690                  * groups cooresponding to the bone.
2691                  */
2692                 bone_looper(ob, arm->bonebase.first, NULL,
2693                                         add_defgroup_unique_bone);
2694                 if (ob->type == OB_MESH)
2695                         create_dverts((Mesh*)ob->data);
2696
2697                 break;
2698
2699         case 3:
2700                 /* Traverse the bone list, trying to create vertex groups 
2701                  * that are populated with the vertices for which the
2702                  * bone is closest.
2703                  */
2704                 add_verts_to_closest_dgroup(ob, par);
2705                 break;
2706
2707         }
2708
2709
2710 int hide_selected_pose_bone(Object *ob, Bone *bone, void *ptr) {
2711         if (bone->flag & BONE_SELECTED) {
2712                 bone->flag |= BONE_HIDDEN;
2713                 bone->flag &= ~BONE_SELECTED;
2714         }
2715         return 0;
2716 }
2717
2718 void hide_selected_pose_bones(void) {
2719         bArmature               *arm;
2720
2721         arm=get_armature (G.obpose);
2722
2723         if (!arm)
2724                 return;
2725
2726         bone_looper(G.obpose, arm->bonebase.first, NULL, 
2727                                 hide_selected_pose_bone);
2728
2729         force_draw();
2730 }
2731
2732 int hide_unselected_pose_bone(Object *ob, Bone *bone, void *ptr) {
2733         if (~bone->flag & BONE_SELECTED) {
2734                 bone->flag |= BONE_HIDDEN;
2735         }
2736         return 0;
2737 }
2738
2739 void hide_unselected_pose_bones(void) {
2740         bArmature               *arm;
2741
2742         arm=get_armature (G.obpose);
2743
2744         if (!arm)
2745                 return;
2746
2747         bone_looper(G.obpose, arm->bonebase.first, NULL, 
2748                                 hide_unselected_pose_bone);
2749
2750         force_draw();
2751 }
2752
2753 int show_pose_bone(Object *ob, Bone *bone, void *ptr) {
2754         if (bone->flag & BONE_HIDDEN) {
2755                 bone->flag &= ~BONE_HIDDEN;
2756                 bone->flag |= BONE_SELECTED;
2757         }
2758
2759         return 0;
2760 }
2761
2762 void show_all_pose_bones(void) {
2763         bArmature               *arm;
2764
2765         arm=get_armature (G.obpose);
2766
2767         if (!arm)
2768                 return;
2769
2770         bone_looper(G.obpose, arm->bonebase.first, NULL, 
2771                                 show_pose_bone);
2772
2773         force_draw();
2774 }
2775
2776 int is_delay_deform(void)
2777 {
2778         bArmature               *arm;
2779
2780         arm=get_armature (G.obpose);
2781
2782         if (!arm)
2783                 return 0;
2784
2785         return (arm->flag & ARM_DELAYDEFORM);
2786 }