Fix for weight painting errors, as reported by Bassam.
[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 <ctype.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <math.h> 
38
39 #ifdef HAVE_CONFIG_H
40 #include <config.h>
41 #endif
42
43 #include "MEM_guardedalloc.h"
44
45 #include "BMF_Api.h"
46
47 #include "DNA_action_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_constraint_types.h"
50 #include "DNA_ID.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_meshdata_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 #include "DNA_modifier_types.h"
59
60 #include "BLI_blenlib.h"
61 #include "BLI_arithb.h"
62 #include "BLI_editVert.h"
63
64 #include "BKE_action.h"
65 #include "BKE_armature.h"
66 #include "BKE_constraint.h"
67 #include "BKE_deform.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_global.h"
70 #include "BKE_main.h"
71 #include "BKE_object.h"
72 #include "BKE_subsurf.h"
73 #include "BKE_utildefines.h"
74 #include "BKE_modifier.h"
75
76 #include "BIF_editaction.h"
77 #include "BIF_editmode_undo.h"
78 #include "BIF_editdeform.h"
79 #include "BIF_editarmature.h"
80 #include "BIF_editconstraint.h"
81 #include "BIF_gl.h"
82 #include "BIF_graphics.h"
83 #include "BIF_interface.h"
84 #include "BIF_poseobject.h"
85 #include "BIF_mywindow.h"
86 #include "BIF_resources.h"
87 #include "BIF_screen.h"
88 #include "BIF_space.h"
89 #include "BIF_toolbox.h"
90 #include "BIF_transform.h"
91
92 #include "BDR_editobject.h"
93 #include "BDR_drawobject.h"
94
95 #include "BSE_edit.h"
96 #include "BSE_view.h"
97 #include "BSE_trans_types.h"
98
99 #include "PIL_time.h"
100
101 #include "mydevice.h"
102 #include "blendef.h"
103 #include "nla.h"
104
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
111 /* **************** tools on Editmode Armature **************** */
112
113 /* converts Bones to EditBone list, used for tools as well */
114 static void make_boneList(ListBase* list, ListBase *bones, EditBone *parent)
115 {
116         EditBone        *eBone;
117         Bone            *curBone;
118         float delta[3];
119         float premat[3][3];
120         float postmat[3][3];
121         float imat[3][3];
122         float difmat[3][3];
123                 
124         for (curBone=bones->first; curBone; curBone=curBone->next){
125                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
126                 
127                 /*      Copy relevant data from bone to eBone */
128                 eBone->parent=parent;
129                 strcpy (eBone->name, curBone->name);
130                 eBone->flag = curBone->flag;
131                 
132                 /* fix selection flags */
133                 if(eBone->flag & BONE_SELECTED) {
134                         eBone->flag |= BONE_TIPSEL;
135                         if(eBone->parent && (eBone->flag & BONE_CONNECTED))
136                                 eBone->parent->flag |= BONE_TIPSEL;
137                         else 
138                                 eBone->flag |= BONE_ROOTSEL;
139                 }
140                 
141                 VECCOPY(eBone->head, curBone->arm_head);
142                 VECCOPY(eBone->tail, curBone->arm_tail);                
143                 
144                 eBone->roll= 0.0;
145                 
146                 /* roll fixing */
147                 VecSubf (delta, eBone->tail, eBone->head);
148                 vec_roll_to_mat3(delta, 0.0, postmat);
149                 
150                 Mat3CpyMat4(premat, curBone->arm_mat);
151                 
152                 Mat3Inv(imat, postmat);
153                 Mat3MulMat3(difmat, imat, premat);
154                 
155                 eBone->roll = atan(difmat[2][0]/difmat[2][2]);
156                 if (difmat[0][0]<0.0) eBone->roll +=M_PI;
157                 
158                 /* rest of stuff copy */
159                 eBone->length= curBone->length;
160                 eBone->dist= curBone->dist;
161                 eBone->weight= curBone->weight;
162                 eBone->xwidth= curBone->xwidth;
163                 eBone->zwidth= curBone->zwidth;
164                 eBone->ease1= curBone->ease1;
165                 eBone->ease2= curBone->ease2;
166                 eBone->rad_head= curBone->rad_head;
167                 eBone->rad_tail= curBone->rad_tail;
168                 eBone->segments = curBone->segments;            
169                 eBone->boneclass = curBone->boneclass;
170                 
171                 BLI_addtail (list, eBone);
172                 
173                 /*      Add children if necessary */
174                 if (curBone->childbase.first) 
175                         make_boneList (list, &curBone->childbase, eBone);
176         }
177 }
178
179 /* nasty stuff for converting roll in editbones into bones */
180 /* also sets restposition in armature (arm_mat) */
181 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
182 {
183         Bone *curBone;
184         EditBone *ebone;
185         float premat[3][3];
186         float postmat[3][3];
187         float difmat[3][3];
188         float imat[3][3];
189         float delta[3];
190         
191         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
192                 /* sets local matrix and arm_mat (restpos) */
193                 where_is_armature_bone(curBone, curBone->parent);
194                 
195                 /* Find the associated editbone */
196                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
197                         if ((Bone*)ebone->temp == curBone)
198                                 break;
199                 
200                 if (ebone) {
201                         /* Get the ebone premat */
202                         VecSubf (delta, ebone->tail, ebone->head);
203                         vec_roll_to_mat3(delta, ebone->roll, premat);
204                         
205                         /* Get the bone postmat */
206                         Mat3CpyMat4(postmat, curBone->arm_mat);
207
208                         Mat3Inv(imat, premat);
209                         Mat3MulMat3(difmat, imat, postmat);
210 #if 0
211                         printf ("Bone %s\n", curBone->name);
212                         printmatrix4 ("premat", premat);
213                         printmatrix4 ("postmat", postmat);
214                         printmatrix4 ("difmat", difmat);
215                         printf ("Roll = %f\n",  (-atan(difmat[2][0]/difmat[2][2]) * (180.0/M_PI)));
216 #endif
217                         curBone->roll = -atan(difmat[2][0]/difmat[2][2]);
218                         
219                         if (difmat[0][0]<0.0) curBone->roll +=M_PI;
220                         
221                         /* and set restposition again */
222                         where_is_armature_bone(curBone, curBone->parent);
223                 }
224                 fix_bonelist_roll (&curBone->childbase, editbonelist);
225         }
226 }
227
228 /* converts the editbones back to the armature */
229 static void editbones_to_armature (ListBase *list, Object *ob)
230 {
231         bArmature *arm;
232         EditBone *eBone;
233         Bone    *newBone;
234         Object *obt;
235         
236         arm = get_armature(ob);
237         if (!list) return;
238         if (!arm) return;
239         
240         /* armature bones */
241         free_bones(arm);
242         
243         /*      Copy the bones from the editData into the armature */
244         for (eBone=list->first;eBone;eBone=eBone->next){
245                 newBone= MEM_callocN (sizeof(Bone), "bone");
246                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
247                 
248                 strcpy (newBone->name, eBone->name);
249                 memcpy (newBone->head, eBone->head, sizeof(float)*3);
250                 memcpy (newBone->tail, eBone->tail, sizeof(float)*3);
251                 newBone->flag= eBone->flag;
252                 newBone->roll = 0.0f;
253                 
254                 newBone->weight = eBone->weight;
255                 newBone->dist = eBone->dist;
256                 
257                 newBone->xwidth = eBone->xwidth;
258                 newBone->zwidth = eBone->zwidth;
259                 newBone->ease1= eBone->ease1;
260                 newBone->ease2= eBone->ease2;
261                 newBone->rad_head= eBone->rad_head;
262                 newBone->rad_tail= eBone->rad_tail;
263                 newBone->segments= eBone->segments;
264                 newBone->boneclass = eBone->boneclass;
265                 
266         }
267         
268         /*      Fix parenting in a separate pass to ensure ebone->bone connections
269                 are valid at this point */
270         for (eBone=list->first;eBone;eBone=eBone->next) {
271                 newBone= (Bone*) eBone->temp;
272                 if (eBone->parent){
273                         newBone->parent=(Bone*) eBone->parent->temp;
274                         BLI_addtail (&newBone->parent->childbase,newBone);
275                         
276                         {
277                                 float M_boneRest[3][3];
278                                 float M_parentRest[3][3];
279                                 float iM_parentRest[3][3];
280                                 float   delta[3];
281                                 
282                                 /* Get the parent's  matrix (rotation only) */
283                                 VecSubf (delta, eBone->parent->tail, eBone->parent->head);
284                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
285                                 
286                                 /* Get this bone's  matrix (rotation only) */
287                                 VecSubf (delta, eBone->tail, eBone->head);
288                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
289                                 
290                                 /* Invert the parent matrix */
291                                 Mat3Inv(iM_parentRest, M_parentRest);
292                                 
293                                 /* Get the new head and tail */
294                                 VecSubf (newBone->head, eBone->head, eBone->parent->tail);
295                                 VecSubf (newBone->tail, eBone->tail, eBone->parent->tail);
296
297                                 Mat3MulVecfl(iM_parentRest, newBone->head);
298                                 Mat3MulVecfl(iM_parentRest, newBone->tail);
299                         }
300                 }
301                 /*      ...otherwise add this bone to the armature's bonebase */
302                 else
303                         BLI_addtail (&arm->bonebase,newBone);
304         }
305         
306         /* Make a pass through the new armature to fix rolling */
307         /* also builds restposition again (like where_is_armature) */
308         fix_bonelist_roll (&arm->bonebase, list);
309         
310         /* so all users of this armature should get rebuilt */
311         for(obt= G.main->object.first; obt; obt= obt->id.next) {
312                 if(obt->data==arm)
313                         armature_rebuild_pose(obt, arm);
314         }
315         
316         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
317 }
318
319
320
321 void apply_rot_armature (Object *ob, float mat[3][3])
322 {
323         ListBase        list;
324         EditBone *ebone;
325         bArmature *arm;
326
327         arm = get_armature(ob);
328
329         if (!arm)
330                 return;
331
332         /* Put the armature into editmode */
333         list.first= list.last = NULL;
334         make_boneList(&list, &arm->bonebase, NULL);
335
336         /* Do the rotations */
337         for (ebone = list.first; ebone; ebone=ebone->next){
338                 Mat3MulVecfl(mat, ebone->head);
339                 Mat3MulVecfl(mat, ebone->tail);
340         }
341         
342         /* Turn the list into an armature */
343         editbones_to_armature(&list, ob);
344         
345         /* Free the editbones */
346         if (list.first){
347                 BLI_freelistN (&list);
348         }
349 }
350
351 void join_armature(void)
352 {
353         Object  *ob;
354         Base    *base, *nextbase;
355         ListBase eblist;
356         EditBone *curbone, *next;
357         float   mat[4][4], imat[4][4];
358         
359         /*      Ensure we're not in editmode and that the active object is an armature*/
360         if(G.obedit) return;
361         
362         ob= OBACT;
363         if(ob->type!=OB_ARMATURE) return;
364         
365         /*      Make sure the user wants to continue*/
366         if(okee("Join selected armatures")==0) return;
367         
368         /*      Put the active armature into editmode and join the bones from the other one*/
369
370         enter_editmode();
371         
372         for (base=FIRSTBASE; base; base=nextbase) {
373                 nextbase = base->next;
374                 if (TESTBASE(base)){
375                         if ((base->object->type==OB_ARMATURE) && (base->object!=ob)){
376                                 /* Make a list of editbones */
377                                 eblist.first=eblist.last= NULL;
378                                 make_boneList (&eblist, &((bArmature*)base->object->data)->bonebase,NULL);
379                                 /* Find the difference matrix */
380                                 Mat4Invert(imat, ob->obmat);
381                                 Mat4MulMat4(mat, base->object->obmat, imat);
382                                 
383                                 /* Copy bones from the object to the edit armature */
384                                 for (curbone=eblist.first; curbone; curbone=next){
385                                         next = curbone->next;
386
387                                         unique_editbone_name (curbone->name);
388                                         
389                                         /* Transform the bone */
390                                         {
391                                                 float premat[4][4];
392                                                 float postmat[4][4];
393                                                 float difmat[4][4];
394                                                 float imat[4][4];
395                                                 float temp[3][3];
396                                                 float delta[3];
397                                                 
398                                                 /* Get the premat */
399                                                 VecSubf (delta, curbone->tail, curbone->head);
400                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
401                                                 
402                                                 Mat4MulMat34 (premat, temp, mat);
403                                                 
404                                                 Mat4MulVecfl(mat, curbone->head);
405                                                 Mat4MulVecfl(mat, curbone->tail);
406                                                 
407                                                 /* Get the postmat */
408                                                 VecSubf (delta, curbone->tail, curbone->head);
409                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
410                                                 Mat4CpyMat3(postmat, temp);
411                                                 
412                                                 /* Find the roll */
413                                                 Mat4Invert (imat, premat);
414                                                 Mat4MulMat4 (difmat, postmat, imat);
415                                                 
416                                                 curbone->roll -=atan(difmat[2][0]/difmat[2][2]);
417                                                 
418                                                 if (difmat[0][0]<0)
419                                                         curbone->roll +=M_PI;
420                                                 
421                                         }
422                                         BLI_remlink(&eblist, curbone);
423                                         BLI_addtail(&G.edbo, curbone);
424                                 }
425                                 
426                                 free_and_unlink_base(base);
427                         }
428                 }
429         }
430         
431         DAG_scene_sort(G.scene);        // because we removed object(s)
432         
433         exit_editmode(1);
434         allqueue(REDRAWVIEW3D, 0);
435         allqueue(REDRAWOOPS, 0);
436
437 }
438
439 /* **************** END tools on Editmode Armature **************** */
440 /* **************** PoseMode & EditMode *************************** */
441
442 /* only for opengl selection indices */
443 Bone *get_indexed_bone (Object *ob, int index)
444 {
445         bPoseChannel *pchan;
446         int a= 0;
447         
448         if(ob->pose==NULL) return NULL;
449         index>>=16;             // bone selection codes use left 2 bytes
450         
451         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
452                 if(a==index) return pchan->bone;
453         }
454         return NULL;
455 }
456
457 /* See if there are any selected bones in this buffer */
458 static void *get_bone_from_selectbuffer(Base *base, unsigned int *buffer, short hits, short findunsel)
459 {
460         Object *ob= base->object;
461         Bone *bone;
462         EditBone *ebone;
463         void *firstunSel=NULL, *firstSel=NULL, *data;
464         unsigned int hitresult;
465         short i, takeNext=0, sel;
466         
467         for (i=0; i< hits; i++){
468                 hitresult = buffer[3+(i*4)];
469                 
470                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
471                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
472                                 
473                                 hitresult &= ~(BONESEL_ANY);
474                                 /* Determine what the current bone is */
475                                 if (G.obedit==NULL) {
476                                         /* no singular posemode, so check for correct object */
477                                         if(base->selcol == (hitresult & 0xFFFF)) {
478                                                 bone = get_indexed_bone(ob, hitresult);
479
480                                                 if (findunsel)
481                                                         sel = (bone->flag & BONE_SELECTED);
482                                                 else
483                                                         sel = !(bone->flag & BONE_SELECTED);
484                                                 
485                                                 data = bone;
486                                         }
487                                         else {
488                                                 data= NULL;
489                                                 sel= 0;
490                                         }
491                                 }
492                                 else{
493                                         ebone = BLI_findlink(&G.edbo, hitresult);
494                                         if (findunsel)
495                                                 sel = (ebone->flag & BONE_SELECTED);
496                                         else
497                                                 sel = !(ebone->flag & BONE_SELECTED);
498                                         
499                                         data = ebone;
500                                 }
501                                 
502                                 if(data) {
503                                         if (sel) {
504                                                 if(!firstSel) firstSel= data;
505                                                 takeNext=1;
506                                         }
507                                         else {
508                                                 if (!firstunSel)
509                                                         firstunSel=data;
510                                                 if (takeNext)
511                                                         return data;
512                                         }
513                                 }
514                         }
515                 }
516         }
517         
518         if (firstunSel)
519                 return firstunSel;
520         else 
521                 return firstSel;
522 }
523
524 /* used by posemode as well editmode */
525 static void *get_nearest_bone (short findunsel)
526 {
527         unsigned int buffer[MAXPICKBUF];
528         short hits;
529         
530         persp(PERSP_VIEW);
531         
532         glInitNames();
533         hits= view3d_opengl_select(buffer, MAXPICKBUF, 0, 0, 0, 0);
534
535         if (hits)
536                 return get_bone_from_selectbuffer(BASACT, buffer, hits, findunsel);
537         
538         return NULL;
539 }
540
541
542 /* **************** END PoseMode & EditMode *************************** */
543 /* **************** Posemode stuff ********************** */
544
545 static int select_bonechildren_by_name (Bone *bone, char *name, int select)
546 {
547         Bone *curBone;
548
549         if (!strcmp (bone->name, name)){
550                 if (select)
551                         bone->flag |= BONE_SELECTED;
552                 else
553                         bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
554                 return 1;
555         }
556
557         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
558                 if (select_bonechildren_by_name (curBone, name, select))
559                         return 1;
560         }
561
562         return 0;
563 }
564
565 /* called in editaction.c */
566 void select_bone_by_name (bArmature *arm, char *name, int select)
567 {
568         Bone *bone;
569         
570         if (!arm)
571                 return;
572         
573         for (bone=arm->bonebase.first; bone; bone=bone->next)
574                 if (select_bonechildren_by_name (bone, name, select))
575                         break;
576 }
577
578 static void selectconnected_posebonechildren (Object *ob, Bone *bone)
579 {
580         Bone *curBone;
581         
582         if (!(bone->flag & BONE_CONNECTED))
583                 return;
584         
585         select_actionchannel_by_name (ob->action, bone->name, !(G.qual & LR_SHIFTKEY));
586         
587         if (G.qual & LR_SHIFTKEY)
588                 bone->flag &= ~BONE_SELECTED;
589         else
590                 bone->flag |= BONE_SELECTED;
591         
592         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
593                 selectconnected_posebonechildren (ob, curBone);
594         }
595 }
596
597 /* within active object context */
598 void selectconnected_posearmature(void)
599 {
600         Bone *bone, *curBone, *next;
601         Object *ob= OBACT;
602         
603         if(!ob || !ob->pose) return;
604         
605         if (G.qual & LR_SHIFTKEY)
606                 bone= get_nearest_bone(0);
607         else
608                 bone = get_nearest_bone(1);
609         
610         if (!bone)
611                 return;
612         
613         /* Select parents */
614         for (curBone=bone; curBone; curBone=next){
615                 select_actionchannel_by_name (ob->action, curBone->name, !(G.qual & LR_SHIFTKEY));
616                 if (G.qual & LR_SHIFTKEY)
617                         curBone->flag &= ~BONE_SELECTED;
618                 else
619                         curBone->flag |= BONE_SELECTED;
620                 
621                 if (curBone->flag & BONE_CONNECTED)
622                         next=curBone->parent;
623                 else
624                         next=NULL;
625         }
626         
627         /* Select children */
628         for (curBone=bone->childbase.first; curBone; curBone=next){
629                 selectconnected_posebonechildren (ob, curBone);
630         }
631         
632         countall(); // flushes selection!
633
634         allqueue (REDRAWVIEW3D, 0);
635         allqueue(REDRAWBUTSEDIT, 0);
636         allqueue(REDRAWBUTSOBJECT, 0);
637         allqueue (REDRAWACTION, 0);
638         allqueue(REDRAWOOPS, 0);
639         BIF_undo_push("Select connected");
640
641 }
642
643 static int count_bonechildren (Bone *bone, int incount, int flagmask, int allbones){
644         
645         Bone    *curBone;
646         
647         if (!bone)
648                 return incount;
649         
650         if (bone->flag & flagmask || flagmask == 0xFFFFFFFF){
651                 incount++;
652                 if (!allbones)
653                         return incount;
654         }
655         
656         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
657                 incount=count_bonechildren (curBone, incount, flagmask, allbones);
658         }
659         
660         return incount;
661 }
662
663 static int      count_bones (bArmature *arm, int flagmask, int allbones)
664 {
665         int     count=0;
666         Bone    *curBone;
667         
668         if (!arm)
669                 return 0;
670         
671         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
672                 count = count_bonechildren (curBone, count, flagmask, allbones);
673         }
674         
675         return count;
676         
677 }
678
679 /* **************** END Posemode stuff ********************** */
680 /* **************** EditMode stuff ********************** */
681
682 /* called in space.c */
683 void selectconnected_armature(void)
684 {
685         EditBone *bone, *curBone, *next;
686
687         if (G.qual & LR_SHIFTKEY)
688                 bone= get_nearest_bone(0);
689         else
690                 bone= get_nearest_bone(1);
691
692         if (!bone)
693                 return;
694
695         /* Select parents */
696         for (curBone=bone; curBone; curBone=next){
697                 if (G.qual & LR_SHIFTKEY){
698                         curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
699                 }
700                 else{
701                         curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
702                 }
703
704                 if (curBone->flag & BONE_CONNECTED)
705                         next=curBone->parent;
706                 else
707                         next=NULL;
708         }
709
710         /* Select children */
711         while (bone){
712                 for (curBone=G.edbo.first; curBone; curBone=next){
713                         next = curBone->next;
714                         if (curBone->parent == bone){
715                                 if (curBone->flag & BONE_CONNECTED){
716                                         if (G.qual & LR_SHIFTKEY)
717                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
718                                         else
719                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
720                                         bone=curBone;
721                                         break;
722                                 }
723                                 else{ 
724                                         bone=NULL;
725                                         break;
726                                 }
727                         }
728                 }
729                 if (!curBone)
730                         bone=NULL;
731
732         }
733
734         countall(); // flushes selection!
735
736         allqueue (REDRAWVIEW3D, 0);
737         allqueue (REDRAWBUTSEDIT, 0);
738         allqueue(REDRAWBUTSOBJECT, 0);
739         allqueue(REDRAWOOPS, 0);
740         
741         BIF_undo_push("Select connected");
742
743 }
744
745 /* does bones and points */
746 /* note that BONE ROOT only gets drawn for root bones (or without IK) */
747 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask)
748 {
749         EditBone *ebone;
750         unsigned int buffer[MAXPICKBUF];
751         unsigned int hitresult, besthitresult=BONESEL_NOSEL;
752         int i, mindep= 4;
753         short hits, mval[2];
754
755         persp(PERSP_VIEW);
756
757         glInitNames();
758         
759         getmouseco_areawin(mval);
760         hits= view3d_opengl_select(buffer, MAXPICKBUF, mval[0]-5, mval[1]-5, mval[0]+5, mval[1]+5);
761         if(hits==0)
762                 hits= view3d_opengl_select(buffer, MAXPICKBUF, mval[0]-12, mval[1]-12, mval[0]+12, mval[1]+12);
763                 
764         /* See if there are any selected bones in this group */
765         if (hits) {
766                 
767                 if(hits==1) {
768                         if (!(buffer[3] & BONESEL_NOSEL)) 
769                                 besthitresult= buffer[3];
770                 }
771                 else {
772                         for (i=0; i< hits; i++) {
773                                 hitresult= buffer[3+(i*4)];
774                                 if (!(hitresult & BONESEL_NOSEL)) {
775                                         int dep;
776                                         
777                                         ebone = BLI_findlink(&G.edbo, hitresult & ~BONESEL_ANY);
778                                         
779                                         /* clicks on bone points get advantage */
780                                         if( hitresult & (BONESEL_ROOT|BONESEL_TIP)) {
781                                                 /* but also the unselected one */
782                                                 if(findunsel) {
783                                                         if( (hitresult & BONESEL_ROOT) && (ebone->flag & BONE_ROOTSEL)==0) 
784                                                                 dep= 1;
785                                                         else if( (hitresult & BONESEL_TIP) && (ebone->flag & BONE_TIPSEL)==0) 
786                                                                 dep= 1;
787                                                         else 
788                                                                 dep= 2;
789                                                 }
790                                                 else dep= 2;
791                                         }
792                                         else {
793                                                 /* bone found */
794                                                 if(findunsel) {
795                                                         if((ebone->flag & BONE_SELECTED)==0)
796                                                                 dep= 2;
797                                                         else
798                                                                 dep= 3;
799                                                 }
800                                                 else dep= 3;
801                                         }
802                                         if(dep < mindep) {
803                                                 mindep= dep;
804                                                 besthitresult= hitresult;
805                                         }
806                                 }
807                         }
808                 }
809                 
810                 if (!(besthitresult & BONESEL_NOSEL)) {
811                         
812                         ebone= BLI_findlink(&G.edbo, besthitresult & ~BONESEL_ANY);
813                         
814                         *selmask = 0;
815                         if (besthitresult & BONESEL_ROOT)
816                                 *selmask |= BONE_ROOTSEL;
817                         if (besthitresult & BONESEL_TIP)
818                                 *selmask |= BONE_TIPSEL;
819                         if (besthitresult & BONESEL_BONE)
820                                 *selmask |= BONE_SELECTED;
821                         return ebone;
822                 }
823         }
824         *selmask = 0;
825         return NULL;
826 }
827
828 static void delete_bone(EditBone* exBone)
829 {
830         EditBone        *curBone;
831         
832         /*      Find any bones that refer to this bone  */
833         for (curBone=G.edbo.first;curBone;curBone=curBone->next){
834                 if (curBone->parent==exBone){
835                         curBone->parent=exBone->parent;
836                         curBone->flag &= ~BONE_CONNECTED;
837                 }
838         }
839         
840         BLI_freelinkN (&G.edbo,exBone);
841 }
842
843 static EditBone *editbone_name_exists (char *name);     // proto for below
844
845 /* only editmode! */
846 void delete_armature(void)
847 {
848         EditBone        *curBone, *next;
849         bConstraint *con;
850         
851         TEST_EDITARMATURE;
852         if(okee("Erase selected bone(s)")==0) return;
853         
854         /*  First rase any associated pose channel */
855         if (G.obedit->pose){
856                 bPoseChannel *chan, *next;
857                 for (chan=G.obedit->pose->chanbase.first; chan; chan=next) {
858                         next= chan->next;
859                         curBone = editbone_name_exists (chan->name);
860                         
861                         if (curBone && (curBone->flag&BONE_SELECTED)) {
862                                 free_constraints(&chan->constraints);
863                                 BLI_freelinkN (&G.obedit->pose->chanbase, chan);
864                         }
865                         else {
866                                 for(con= chan->constraints.first; con; con= con->next) {
867                                         char *subtarget = get_con_subtarget_name(con, G.obedit);
868                                         if (subtarget) {
869                                                 curBone = editbone_name_exists (subtarget);
870                                                 if (curBone && (curBone->flag&BONE_SELECTED)) {
871                                                         con->flag |= CONSTRAINT_DISABLE;
872                                                         subtarget[0]= 0;
873                                                 }
874                                         }
875                                 }
876                         }
877                 }
878         }
879         
880         
881         for (curBone=G.edbo.first;curBone;curBone=next){
882                 next=curBone->next;
883                 if (curBone->flag&BONE_SELECTED)
884                         delete_bone(curBone);
885         }
886         
887         
888         allqueue(REDRAWVIEW3D, 0);
889         allqueue(REDRAWBUTSEDIT, 0);
890         allqueue(REDRAWBUTSOBJECT, 0);
891         allqueue(REDRAWOOPS, 0);
892         countall(); // flushes selection!
893         
894         BIF_undo_push("Delete bone(s)");
895 }
896
897 /* context: editmode armature */
898 void mouse_armature(void)
899 {
900         EditBone *nearBone = NULL, *ebone;
901         int     selmask;
902
903         nearBone= get_nearest_editbonepoint(1, &selmask);
904         if (nearBone) {
905                 
906                 if (!(G.qual & LR_SHIFTKEY)) {
907                         deselectall_armature(0);
908                 }
909                 
910                 /* by definition the non-root non-connected bones have no root point drawn,
911                so a root selection needs to be delivered to the parent tip,
912                countall() (bad location) flushes these flags */
913                 
914                 if(selmask & BONE_SELECTED) {
915                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
916                                 /* click in a chain */
917                                 if(G.qual & LR_SHIFTKEY) {
918                                         /* hold shift inverts this bone's selection */
919                                         if(nearBone->flag & BONE_SELECTED) {
920                                                 /* deselect this bone */
921                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
922                                                 /* only deselect parent tip if it is not selected */
923                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
924                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
925                                         }
926                                         else {
927                                                 /* select this bone */
928                                                 nearBone->flag |= BONE_TIPSEL;
929                                                 nearBone->parent->flag |= BONE_TIPSEL;
930                                         }
931                                 }
932                                 else {
933                                         /* select this bone */
934                                         nearBone->flag |= BONE_TIPSEL;
935                                         nearBone->parent->flag |= BONE_TIPSEL;
936                                 }
937                         }
938                         else {
939                                 if(G.qual & LR_SHIFTKEY) {
940                                         /* hold shift inverts this bone's selection */
941                                         if(nearBone->flag & BONE_SELECTED)
942                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
943                                         else
944                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
945                                 }
946                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
947                         }
948                 }
949                 else {
950                         if ((G.qual & LR_SHIFTKEY) && (nearBone->flag & selmask))
951                                 nearBone->flag &= ~selmask;
952                         else
953                                 nearBone->flag |= selmask;
954                 }
955
956                 countall(); // flushes selection!
957                 
958                 if(nearBone) {
959                         /* then now check for active status */
960                         for (ebone=G.edbo.first;ebone;ebone=ebone->next) ebone->flag &= ~BONE_ACTIVE;
961                         if(nearBone->flag & BONE_SELECTED) nearBone->flag |= BONE_ACTIVE;
962                 }
963                 
964                 allqueue(REDRAWVIEW3D, 0);
965                 allqueue(REDRAWBUTSEDIT, 0);
966                 allqueue(REDRAWBUTSOBJECT, 0);
967                 allqueue(REDRAWOOPS, 0);
968         }
969
970         rightmouse_transform();
971 }
972
973 void free_editArmature(void)
974 {
975         
976         /*      Clear the editbones list */
977         if (G.edbo.first){
978                 BLI_freelistN (&G.edbo);
979         }
980 }
981
982 void remake_editArmature(void)
983 {
984         if(okee("Reload original data")==0) return;
985         
986         make_editArmature();
987         allqueue(REDRAWVIEW3D, 0);
988         allqueue(REDRAWOOPS, 0);
989         allqueue(REDRAWBUTSHEAD, 0);
990         allqueue(REDRAWBUTSEDIT, 0);
991         allqueue(REDRAWBUTSOBJECT, 0);
992         
993 //      BIF_undo_push("Delete bone");
994
995 }
996
997 /* Put object in EditMode */
998 void make_editArmature(void)
999 {
1000         bArmature       *arm;
1001         
1002         if (G.obedit==0) return;
1003         
1004         free_editArmature();
1005         
1006         arm= get_armature(G.obedit);
1007         if (!arm)
1008                 return;
1009         
1010         make_boneList (&G.edbo, &arm->bonebase,NULL);
1011 }
1012
1013 /* put EditMode back in Object */
1014 void load_editArmature(void)
1015 {
1016         bArmature               *arm;
1017
1018         arm= get_armature(G.obedit);
1019         if (!arm) return;
1020         
1021         editbones_to_armature(&G.edbo, G.obedit);
1022 }
1023
1024 /* toggle==0: deselect
1025    toggle==1: swap 
1026    toggle==2: only active tag
1027 */
1028 void deselectall_armature(int toggle)
1029 {
1030         EditBone        *eBone;
1031         int                     sel=1;
1032
1033         if(toggle==1) {
1034                 /*      Determine if there are any selected bones
1035                         And therefore whether we are selecting or deselecting */
1036                 for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1037                         if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1038                                 sel=0;
1039                                 break;
1040                         }
1041                 }
1042         }
1043         else sel= toggle;
1044         
1045         /*      Set the flags */
1046         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1047                 if (sel==1)
1048                         eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1049                 else if (sel==2)
1050                         eBone->flag &= ~(BONE_ACTIVE);
1051                 else
1052                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1053         }
1054         
1055         allqueue(REDRAWVIEW3D, 0);
1056         allqueue(REDRAWBUTSEDIT, 0);
1057         allqueue(REDRAWBUTSOBJECT, 0);
1058         allqueue(REDRAWOOPS, 0);
1059         
1060         countall(); // flushes selection!
1061 }
1062
1063 void auto_align_armature(void)
1064 /* Sets the roll value of selected bones so that their zaxes point upwards */
1065 {
1066         EditBone *ebone;
1067         float   xaxis[3]={1.0, 0.0, 0.0}, yaxis[3], zaxis[3]={0.0, 0.0, 1.0};
1068         float   targetmat[3][3], imat[3][3];
1069         float   curmat[3][3], diffmat[3][3];
1070         float   delta[3];
1071         
1072         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1073                 if (ebone->flag & BONE_SELECTED){
1074                         /* Find the current bone matrix */
1075                         VecSubf(delta, ebone->tail, ebone->head);
1076                         vec_roll_to_mat3(delta, 0.0, curmat);
1077                         
1078                         /* Make new matrix based on y axis & z-up */
1079                         VECCOPY (yaxis, curmat[1]);
1080                         
1081                         Mat3One(targetmat);
1082                         VECCOPY (targetmat[0], xaxis);
1083                         VECCOPY (targetmat[1], yaxis);
1084                         VECCOPY (targetmat[2], zaxis);
1085                         Mat3Ortho(targetmat);
1086                         
1087                         /* Find the difference between the two matrices */
1088                         Mat3Inv(imat, targetmat);
1089                         Mat3MulMat3(diffmat, imat, curmat);
1090                         
1091                         ebone->roll = atan(diffmat[2][0]/diffmat[2][2]);
1092                         
1093                 }
1094         }
1095 }
1096
1097 /* **************** undo for armatures ************** */
1098
1099 static void undoBones_to_editBones(void *lbv)
1100 {
1101         ListBase *lb= lbv;
1102         EditBone *ebo, *newebo;
1103         
1104         BLI_freelistN(&G.edbo);
1105         
1106         /* copy  */
1107         for(ebo= lb->first; ebo; ebo= ebo->next) {
1108                 newebo= MEM_dupallocN(ebo);
1109                 ebo->temp= newebo;
1110                 BLI_addtail(&G.edbo, newebo);
1111         }
1112         
1113         /* set pointers */
1114         for(newebo= G.edbo.first; newebo; newebo= newebo->next) {
1115                 if(newebo->parent) newebo->parent= newebo->parent->temp;
1116         }
1117         /* be sure they dont hang ever */
1118         for(newebo= G.edbo.first; newebo; newebo= newebo->next) {
1119                 newebo->temp= NULL;
1120         }
1121 }
1122
1123 static void *editBones_to_undoBones(void)
1124 {
1125         ListBase *lb;
1126         EditBone *ebo, *newebo;
1127         
1128         lb= MEM_callocN(sizeof(ListBase), "listbase undo");
1129         
1130         /* copy  */
1131         for(ebo= G.edbo.first; ebo; ebo= ebo->next) {
1132                 newebo= MEM_dupallocN(ebo);
1133                 ebo->temp= newebo;
1134                 BLI_addtail(lb, newebo);
1135         }
1136         
1137         /* set pointers */
1138         for(newebo= lb->first; newebo; newebo= newebo->next) {
1139                 if(newebo->parent) newebo->parent= newebo->parent->temp;
1140         }
1141         
1142         return lb;
1143 }
1144
1145 static void free_undoBones(void *lbv)
1146 {
1147         ListBase *lb= lbv;
1148         
1149         BLI_freelistN(lb);
1150         MEM_freeN(lb);
1151 }
1152
1153 /* and this is all the undo system needs to know */
1154 void undo_push_armature(char *name)
1155 {
1156         undo_editmode_push(name, free_undoBones, undoBones_to_editBones, editBones_to_undoBones);
1157 }
1158
1159
1160
1161 /* **************** END EditMode stuff ********************** */
1162 /* *************** Adding stuff in editmode *************** */
1163
1164 /* default bone add, returns it selected, but without tail set */
1165 static EditBone *add_editbone(void)
1166 {
1167         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
1168         
1169         strcpy (bone->name,"Bone");
1170         unique_editbone_name (bone->name);
1171         
1172         BLI_addtail(&G.edbo, bone);
1173         
1174         bone->flag |= BONE_TIPSEL;
1175         bone->weight= 1.0F;
1176         bone->dist= 0.25F;
1177         bone->xwidth= 0.1;
1178         bone->zwidth= 0.1;
1179         bone->ease1= 1.0;
1180         bone->ease2= 1.0;
1181         bone->rad_head= 0.10;
1182         bone->rad_tail= 0.05;
1183         bone->segments= 1;
1184         
1185         return bone;
1186 }
1187
1188 static void add_primitive_bone(Object *ob)
1189 {
1190         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
1191         EditBone        *bone;
1192         
1193         VECCOPY (curs, give_cursor());  
1194
1195         /* Get inverse point for head and orientation for tail */
1196         Mat4Invert(G.obedit->imat, G.obedit->obmat);
1197         Mat4MulVecfl(G.obedit->imat, curs);
1198
1199         Mat3CpyMat4(obmat, G.vd->viewmat);
1200         Mat3CpyMat4(viewmat, G.obedit->obmat);
1201         Mat3MulMat3(totmat, obmat, viewmat);
1202         Mat3Inv(imat, totmat);
1203         
1204         deselectall_armature(0);
1205         
1206         /*      Create a bone   */
1207         bone= add_editbone();
1208
1209         VECCOPY(bone->head, curs);
1210         VecAddf(bone->tail, bone->head, imat[1]);       // bone with unit length 1
1211         
1212 }
1213
1214 void add_primitiveArmature(int type)
1215 {
1216         if(G.scene->id.lib) return;
1217         
1218         /* this function also comes from an info window */
1219         if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
1220         if(G.vd==NULL) return;
1221         
1222         G.f &= ~(G_VERTEXPAINT+G_FACESELECT+G_TEXTUREPAINT+G_WEIGHTPAINT);
1223         setcursor_space(SPACE_VIEW3D, CURSOR_STD);
1224
1225         check_editmode(OB_ARMATURE);
1226         
1227         /* If we're not the "obedit", make a new object and enter editmode */
1228         if(G.obedit==NULL) {
1229                 add_object(OB_ARMATURE);
1230                 base_init_from_view3d(BASACT, G.vd);
1231                 G.obedit= BASACT->object;
1232                 
1233                 where_is_object(G.obedit);
1234                 
1235                 make_editArmature();
1236                 setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
1237         }
1238         
1239         /* no primitive support yet */
1240         add_primitive_bone(G.obedit);
1241         
1242         countall(); // flushes selection!
1243
1244         allqueue(REDRAWALL, 0);
1245         BIF_undo_push("Add primitive");
1246 }
1247
1248 /* the ctrl-click method */
1249 void addvert_armature(void)
1250 {
1251         EditBone *ebone, *newbone;
1252         float *curs, mat[3][3],imat[3][3];
1253         int to_root= 0;
1254         
1255         TEST_EDITARMATURE;
1256         
1257         /* find the active or selected bone */
1258         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1259                 if(ebone->flag & (BONE_ACTIVE|BONE_TIPSEL)) break;
1260         
1261         if(ebone==NULL) {
1262                 for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1263                         if(ebone->flag & (BONE_ACTIVE|BONE_ROOTSEL)) break;
1264                 
1265                 if(ebone==NULL) 
1266                         return;
1267                 to_root= 1;
1268         }
1269         
1270         deselectall_armature(0);
1271         newbone= add_editbone();
1272         newbone->flag |= BONE_ACTIVE;
1273         
1274         if(to_root) {
1275                 VECCOPY(newbone->head, ebone->head);
1276                 
1277                 newbone->parent= ebone->parent;
1278         }
1279         else {
1280                 VECCOPY(newbone->head, ebone->tail);
1281
1282                 newbone->parent= ebone;
1283                 newbone->flag |= BONE_CONNECTED;
1284         }
1285         
1286         curs= give_cursor();
1287         VECCOPY(newbone->tail, curs);
1288         VecSubf(newbone->tail, newbone->tail, G.obedit->obmat[3]);
1289         
1290         Mat3CpyMat4(mat, G.obedit->obmat);
1291         Mat3Inv(imat, mat);
1292         Mat3MulVecfl(imat, newbone->tail);
1293
1294         newbone->length= VecLenf(newbone->head, newbone->tail);
1295         newbone->rad_tail= newbone->length*0.05f;
1296         newbone->dist= newbone->length*0.1f;
1297         
1298         countall();
1299         
1300         BIF_undo_push("Add Bone");
1301         allqueue(REDRAWVIEW3D, 0);
1302         
1303         while(get_mbut()&R_MOUSE);
1304 }
1305
1306
1307 void adduplicate_armature(void)
1308 {
1309         EditBone        *eBone = NULL;
1310         EditBone        *curBone;
1311         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
1312         
1313         countall(); // flushes selection!
1314         
1315         /*      Find the selected bones and duplicate them as needed */
1316         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1317                 if (curBone->flag & BONE_SELECTED){
1318                         
1319                         eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
1320                         eBone->flag |= BONE_SELECTED;
1321                         
1322                         /*      Copy data from old bone to new bone */
1323                         memcpy (eBone, curBone, sizeof(EditBone));
1324                         
1325                         curBone->temp = eBone;
1326                         eBone->temp = curBone;
1327                         
1328                         unique_editbone_name (eBone->name);
1329                         BLI_addtail (&G.edbo, eBone);
1330                         if (!firstDup)
1331                                 firstDup=eBone;
1332                         
1333                         /* Lets duplicate the list of constraits that the
1334                                 * current bone has.
1335                                 */
1336                         /* temporal removed (ton) */
1337                 }
1338         }
1339
1340         /*      Run though the list and fix the pointers */
1341         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1342                 
1343                 if (curBone->flag & BONE_SELECTED){
1344                         eBone=(EditBone*) curBone->temp;
1345                         
1346                         /*      If this bone has no parent,
1347                         Set the duplicate->parent to NULL
1348                         */
1349                         if (!curBone->parent){
1350                                 eBone->parent = NULL;
1351                         }
1352                         /*      If this bone has a parent that IS selected,
1353                                 Set the duplicate->parent to the curBone->parent->duplicate
1354                                 */
1355                         else if (curBone->parent->flag & BONE_SELECTED){
1356                                 eBone->parent=(EditBone*) curBone->parent->temp;
1357                         }
1358                         /*      If this bone has a parent that IS not selected,
1359                                 Set the duplicate->parent to the curBone->parent
1360                                 */
1361                         else {
1362                                 eBone->parent=(EditBone*) curBone->parent; 
1363                                 eBone->flag &= ~BONE_CONNECTED;
1364                         }
1365                         
1366                         /* Lets try to fix any constraint subtargets that might
1367                                 have been duplicated */
1368                         /* temporal removed (ton) */
1369                         
1370                 }
1371         } 
1372         
1373         /*      Deselect the old bones and select the new ones */
1374         
1375         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1376                 curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1377         }
1378         
1379         BIF_TransformSetUndo("Add Duplicate");
1380         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1381         Transform();
1382         
1383         allqueue(REDRAWBUTSEDIT, 0);
1384         allqueue(REDRAWBUTSOBJECT, 0);
1385         allqueue(REDRAWOOPS, 0);
1386 }
1387
1388
1389
1390 /* *************** END Adding stuff in editmode *************** */
1391 /* *************** Tools in editmode *********** */
1392
1393
1394 void hide_selected_armature_bones(void)
1395 {
1396         EditBone *ebone;
1397         
1398         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1399                 if(ebone->flag & (BONE_SELECTED)) {
1400                         ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1401                         ebone->flag |= BONE_HIDDEN_A;
1402                 }
1403         }
1404         countall();
1405         allqueue(REDRAWVIEW3D, 0);
1406         allqueue(REDRAWBUTSEDIT, 0);
1407 }
1408
1409 void hide_unselected_armature_bones(void)
1410 {
1411         EditBone *ebone;
1412         
1413         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1414                 if(ebone->flag & (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL));
1415                 else {
1416                         ebone->flag &= ~BONE_ACTIVE;
1417                         ebone->flag |= BONE_HIDDEN_A;
1418                 }
1419         }
1420         countall();
1421         allqueue(REDRAWVIEW3D, 0);
1422         allqueue(REDRAWBUTSEDIT, 0);
1423 }
1424
1425 void show_all_armature_bones(void)
1426 {
1427         EditBone *ebone;
1428         
1429         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1430                 if(ebone->flag & BONE_HIDDEN_A) {
1431                         ebone->flag |= (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
1432                         ebone->flag &= ~BONE_HIDDEN_A;
1433                 }
1434         }
1435         countall();
1436         allqueue(REDRAWVIEW3D, 0);
1437         allqueue(REDRAWBUTSEDIT, 0);
1438 }
1439
1440 void make_bone_parent(void)
1441 {
1442         EditBone *ebone;
1443         float offset[3];
1444         short val;
1445         
1446         val= pupmenu("Make Parent%t|Connected%x1|Keep Offset%x2");
1447         
1448         if(val<1) return;
1449         
1450         /* find active */
1451         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1452                 if(ebone->flag & BONE_ACTIVE) break;
1453         if(ebone) {
1454                 EditBone *actbone= ebone, *selbone= NULL;
1455                 
1456                 /* find selected */
1457                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1458                         if(ebone->flag & BONE_SELECTED) {
1459                                 if(ebone!=actbone) {
1460                                         if(selbone==NULL) selbone= ebone;
1461                                         else {
1462                                                 error("Need one active and one selected bone");
1463                                                 return;
1464                                         }
1465                                 }
1466                         }
1467                 }
1468                 if(selbone==NULL) {
1469                         /* we make sure bone is connected */
1470                         if(val==1 && actbone->parent) {
1471                                 actbone->flag |= BONE_CONNECTED;
1472                                 VECCOPY(actbone->head, actbone->parent->tail);
1473                                 countall(); // checks selection
1474                                 allqueue(REDRAWVIEW3D, 0);
1475                                 BIF_undo_push("Connect to Parent");
1476                         }
1477                         else error("Need one active and one selected bone");
1478                 }
1479                 else {
1480                         /* if selbone had a parent we clear parent tip */
1481                         if(selbone->parent && (selbone->flag & BONE_CONNECTED))
1482                            selbone->parent->flag &= ~(BONE_TIPSEL);
1483                         
1484                         selbone->parent= actbone;
1485                         
1486                         /* in actbone tree we cannot have a loop */
1487                         for(ebone= actbone->parent; ebone; ebone= ebone->parent) {
1488                                 if(ebone->parent==selbone) {
1489                                         ebone->parent= NULL;
1490                                         ebone->flag &= ~BONE_CONNECTED;
1491                                 }
1492                         }
1493                         
1494                         if(val==1) {    // connected
1495                                 selbone->flag |= BONE_CONNECTED;
1496                                 VecSubf(offset, actbone->tail, selbone->head);
1497                                 
1498                                 VECCOPY(selbone->head, actbone->tail);
1499                                 VecAddf(selbone->tail, selbone->tail, offset);
1500                                 
1501                                 // offset for all its children 
1502                                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1503                                         EditBone *par;
1504                                         for(par= ebone->parent; par; par= par->parent) {
1505                                                 if(par==selbone) {
1506                                                         VecAddf(ebone->head, ebone->head, offset);
1507                                                         VecAddf(ebone->tail, ebone->tail, offset);
1508                                                         break;
1509                                                 }
1510                                         }
1511                                 }
1512                         }
1513                         else {
1514                                 selbone->flag &= ~BONE_CONNECTED;
1515                         }
1516                         
1517                         countall(); // checks selection
1518                         allqueue(REDRAWVIEW3D, 0);
1519                         allqueue(REDRAWBUTSEDIT, 0);
1520                         allqueue(REDRAWOOPS, 0);
1521                         BIF_undo_push("Make Parent");
1522                 }
1523         }
1524 }
1525
1526 void clear_bone_parent(void)
1527 {
1528         EditBone *ebone;
1529         short val;
1530         
1531         val= pupmenu("Clear Parent%t|Clear Parent%x1|Disconnect Bone%x2");
1532         
1533         if(val<1) return;
1534         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1535                 if(ebone->flag & BONE_SELECTED) {
1536                         if(ebone->parent) {
1537                                 /* for nice selection */
1538                                 ebone->parent->flag &= ~(BONE_TIPSEL);
1539                                 
1540                                 if(val==1) ebone->parent= NULL;
1541                                 ebone->flag &= ~BONE_CONNECTED;
1542                         }
1543                 }
1544         }
1545         countall(); // checks selection
1546         allqueue(REDRAWVIEW3D, 0);
1547         allqueue(REDRAWBUTSEDIT, 0);
1548         allqueue(REDRAWOOPS, 0);
1549         BIF_undo_push("Clear Parent");
1550 }
1551         
1552
1553 static EditBone *editbone_name_exists (char *name)
1554 {
1555         EditBone        *eBone;
1556         
1557         for (eBone=G.edbo.first; eBone; eBone=eBone->next){
1558                 if (!strcmp (name, eBone->name))
1559                         return eBone;
1560         }
1561         return NULL;
1562 }
1563
1564 /* note: there's a unique_bone_name() too! */
1565 void unique_editbone_name (char *name)
1566 {
1567         char            tempname[64];
1568         int                     number;
1569         char            *dot;
1570         
1571         
1572         if (editbone_name_exists(name)) {
1573                 
1574                 /*      Strip off the suffix, if it's a number */
1575                 number= strlen(name);
1576                 if(number && isdigit(name[number-1])) {
1577                         dot= strrchr(name, '.');        // last occurrance
1578                         if (dot)
1579                                 *dot=0;
1580                 }
1581                 
1582                 for (number = 1; number <=999; number++){
1583                         sprintf (tempname, "%s.%03d", name, number);
1584                         if (!editbone_name_exists(tempname)){
1585                                 strcpy (name, tempname);
1586                                 return;
1587                         }
1588                 }
1589         }
1590 }
1591
1592 /* context; editmode armature */
1593 /* if forked && mirror-edit: makes two bones with flipped names */
1594 void extrude_armature(int forked)
1595 {
1596         bArmature *arm= G.obedit->data;
1597         EditBone *newbone, *ebone, *flipbone, *first=NULL;
1598         int a, totbone= 0, do_extrude;
1599         
1600         TEST_EDITARMATURE;
1601         
1602         /* since we allow root extrude too, we have to make sure selection is OK */
1603         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1604                 if(ebone->flag & BONE_ROOTSEL) {
1605                         if(ebone->parent && (ebone->flag & BONE_CONNECTED)) {
1606                                 if(ebone->parent->flag & BONE_TIPSEL)
1607                                         ebone->flag &= ~BONE_ROOTSEL;
1608                         }
1609                 }
1610         }
1611         
1612         /* Duplicate the necessary bones */
1613         for (ebone = G.edbo.first; ((ebone) && (ebone!=first)); ebone=ebone->next){
1614                 
1615                 /* we extrude per definition the tip */
1616                 do_extrude= 0;
1617                 if (ebone->flag & (BONE_TIPSEL|BONE_SELECTED))
1618                         do_extrude= 1;
1619                 else if(ebone->flag & BONE_ROOTSEL) {
1620                         /* but, a bone with parent deselected we do the root... */
1621                         if(ebone->parent && (ebone->parent->flag & BONE_TIPSEL));
1622                         else do_extrude= 2;
1623                 }
1624                 
1625                 if (do_extrude) {
1626                         
1627                         /* we re-use code for mirror editing... */
1628                         flipbone= NULL;
1629                         if(arm->flag & ARM_MIRROR_EDIT) {
1630                                 flipbone= armature_bone_get_mirrored(ebone);
1631                                 if (flipbone) {
1632                                         forked= 0;      // we extrude 2 different bones
1633                                         if(flipbone->flag & (BONE_TIPSEL|BONE_ROOTSEL|BONE_SELECTED))
1634                                                 /* don't want this bone to be selected... */
1635                                                 flipbone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1636                                 }
1637                                 if(flipbone==NULL && forked)
1638                                         flipbone= ebone;
1639                         }
1640                         
1641                         for(a=0; a<2; a++) {
1642                                 if(a==1) {
1643                                         if(flipbone==NULL)
1644                                                 break;
1645                                         else {
1646                                                 SWAP(EditBone *, flipbone, ebone);
1647                                         }
1648                                 }
1649                                 
1650                                 totbone++;
1651                                 newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
1652                                 
1653                                 if(do_extrude==1) {
1654                                         VECCOPY (newbone->head, ebone->tail);
1655                                         VECCOPY (newbone->tail, newbone->head);
1656                                         newbone->parent = ebone;
1657                                         
1658                                         newbone->flag = ebone->flag & BONE_TIPSEL;      // copies it, in case mirrored bone
1659                                 }
1660                                 else {
1661                                         VECCOPY(newbone->head, ebone->head);
1662                                         VECCOPY(newbone->tail, ebone->head);
1663                                         newbone->parent= ebone->parent;
1664                                         
1665                                         newbone->flag= BONE_TIPSEL;
1666                                 }
1667
1668                                 newbone->weight= ebone->weight;
1669                                 newbone->dist= ebone->dist;
1670                                 newbone->xwidth= ebone->xwidth;
1671                                 newbone->zwidth= ebone->zwidth;
1672                                 newbone->ease1= ebone->ease1;
1673                                 newbone->ease2= ebone->ease2;
1674                                 newbone->rad_head= ebone->rad_tail;     // dont copy entire bone...
1675                                 newbone->rad_tail= ebone->rad_tail;
1676                                 newbone->segments= 1;
1677                                 newbone->boneclass= ebone->boneclass;
1678                                 
1679                                 if(newbone->parent) newbone->flag |= BONE_CONNECTED;
1680                                 
1681                                 strcpy (newbone->name, ebone->name);
1682                                 
1683                                 if(flipbone && forked) {        // only set if mirror edit
1684                                         if(strlen(newbone->name)<30) {
1685                                                 if(a==0) strcat(newbone->name, "_L");
1686                                                 else strcat(newbone->name, "_R");
1687                                         }
1688                                 }
1689                                 unique_editbone_name(newbone->name);
1690                                 
1691                                 /* Add the new bone to the list */
1692                                 BLI_addtail(&G.edbo, newbone);
1693                                 if (!first)
1694                                         first = newbone;
1695                                 
1696                                 /* restore ebone if we were flipping */
1697                                 if(a==1 && flipbone) 
1698                                         SWAP(EditBone *, flipbone, ebone);
1699
1700                         }
1701                 }
1702                 
1703                 /* Deselect the old bone */
1704                 ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1705                 
1706         }
1707         /* if only one bone, make this one active */
1708         if(totbone==1 && first) first->flag |= BONE_ACTIVE;
1709         
1710         /* Transform the endpoints */
1711         countall(); // flushes selection!
1712         BIF_TransformSetUndo("Extrude");
1713         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1714         Transform();
1715         
1716         allqueue(REDRAWBUTSEDIT, 0);
1717         allqueue(REDRAWBUTSOBJECT, 0);
1718         allqueue(REDRAWOOPS, 0);
1719 }
1720
1721 /* context; editmode armature */
1722 void subdivide_armature(void)
1723 {
1724         bArmature *arm= G.obedit->data;
1725         EditBone *ebone, *newbone, *tbone, *mbone;
1726         int a;
1727         
1728         for (mbone = G.edbo.last; mbone; mbone= mbone->prev) {
1729                 if(mbone->flag & BONE_SELECTED) {
1730                         
1731                         /* take care of mirrored stuff */
1732                         for(a=0; a<2; a++) {
1733                                 if(a==0) ebone= mbone;
1734                                 else {
1735                                         if(arm->flag & ARM_MIRROR_EDIT)
1736                                                 ebone= armature_bone_get_mirrored(mbone);
1737                                         else ebone= NULL;
1738                                 }
1739                                 if(ebone) {
1740
1741                                         newbone= MEM_mallocN(sizeof(EditBone), "ebone subdiv");
1742                                         *newbone = *ebone;
1743                                         BLI_addtail(&G.edbo, newbone);
1744                                         
1745                                         VecMidf(newbone->head, ebone->head, ebone->tail);
1746                                         VECCOPY(newbone->tail, ebone->tail);
1747                                         VECCOPY(ebone->tail, newbone->head);
1748                                         
1749                                         newbone->rad_head= 0.5*(ebone->rad_head+ebone->rad_tail);
1750                                         ebone->rad_tail= newbone->rad_head;
1751
1752                                         newbone->flag |= BONE_CONNECTED;
1753                                         
1754                                         unique_editbone_name (newbone->name);
1755                                         
1756                                         /* correct parent bones */
1757                                         for (tbone = G.edbo.first; tbone; tbone=tbone->next){
1758                                                 if(tbone->parent==ebone)
1759                                                         tbone->parent= newbone;
1760                                         }
1761                                         newbone->parent= ebone;
1762                                 }
1763                         }
1764                 }
1765         }
1766 }
1767
1768 /* ***************** Pose tools ********************* */
1769
1770 void clear_armature(Object *ob, char mode)
1771 {
1772         bPoseChannel *pchan;
1773         bArmature       *arm;
1774
1775         arm=get_armature(ob);
1776         
1777         if (!arm)
1778                 return;
1779         
1780         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1781                 if(pchan->bone && (pchan->bone->flag & BONE_SELECTED)) {
1782                         switch (mode){
1783                                 case 'r':
1784                                         pchan->quat[1]=pchan->quat[2]=pchan->quat[3]=0.0F; pchan->quat[0]=1.0F;
1785                                         break;
1786                                 case 'g':
1787                                         pchan->loc[0]=pchan->loc[1]=pchan->loc[2]=0.0F;
1788                                         break;
1789                                 case 's':
1790                                         pchan->size[0]=pchan->size[1]=pchan->size[2]=1.0F;
1791                                         break;
1792                                         
1793                         }
1794                 }
1795         }
1796         
1797         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
1798         /* no update for this object, this will execute the action again */
1799         /* is weak... like for ipo editing which uses ctime now... */
1800         where_is_pose (ob);
1801         ob->recalc= 0;
1802 }
1803
1804 /* helper for function below */
1805 static int clear_active_flag(Object *ob, Bone *bone, void *data) 
1806 {
1807         bone->flag &= ~BONE_ACTIVE;
1808         return 0;
1809 }
1810
1811
1812 /* called from editview.c, for mode-less pose selection */
1813 int do_pose_selectbuffer(Base *base, unsigned int *buffer, short hits)
1814 {
1815         Object *ob= base->object;
1816         Bone *nearBone;
1817         
1818         if (!ob || !ob->pose) return 0;
1819
1820         nearBone= get_bone_from_selectbuffer(base, buffer, hits, 1);
1821
1822         if (nearBone) {
1823                 if (!(G.qual & LR_SHIFTKEY)){
1824                         deselectall_posearmature(ob, 0);
1825                         nearBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1826                         select_actionchannel_by_name(ob->action, nearBone->name, 1);
1827                 }
1828                 else {
1829                         if (nearBone->flag & BONE_SELECTED) {
1830                                 /* if not active, we make it active */
1831                                 if((nearBone->flag & BONE_ACTIVE)==0) {
1832                                         bArmature *arm= ob->data;
1833                                         bone_looper(ob, arm->bonebase.first, NULL, clear_active_flag);
1834                                         
1835                                         nearBone->flag |= BONE_ACTIVE;
1836                                 }
1837                                 else {
1838                                         nearBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1839                                         select_actionchannel_by_name(ob->action, nearBone->name, 0);
1840                                 }
1841                         }
1842                         else{
1843                                 bArmature *arm= ob->data;
1844                                 bone_looper(ob, arm->bonebase.first, NULL, clear_active_flag);
1845                                 
1846                                 nearBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1847                                 select_actionchannel_by_name(ob->action, nearBone->name, 1);
1848                         }
1849                 }
1850                 
1851                 /* in weightpaint we select the associated vertex group too */
1852                 if(G.f & G_WEIGHTPAINT) {
1853                         if(nearBone->flag & BONE_ACTIVE) {
1854                                 vertexgroup_select_by_name(OBACT, nearBone->name);
1855                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
1856                         }
1857                 }
1858                 
1859                 allqueue(REDRAWVIEW3D, 0);
1860                 allqueue(REDRAWACTION, 0);
1861                 allqueue(REDRAWIPO, 0);         /* To force action/constraint ipo update */
1862                 allqueue(REDRAWBUTSEDIT, 0);
1863                 allqueue(REDRAWBUTSOBJECT, 0);
1864                 allqueue(REDRAWOOPS, 0);
1865         }
1866         
1867         return nearBone!=NULL;
1868         
1869 }
1870
1871 /*      mode==0: deselect
1872         mode==1: select
1873         mode==2: clear active tag 
1874 */
1875 static void deselect_bonechildren (Object *ob, Bone *bone, int mode)
1876 {
1877         Bone    *curBone;
1878
1879         if (!bone)
1880                 return;
1881
1882         if (mode==0)
1883                 bone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1884         else if (mode==1) {
1885                 if(!(bone->flag & BONE_HIDDEN_P))
1886                         bone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1887         }
1888         else bone->flag &= ~BONE_ACTIVE;
1889         
1890         if(mode!=2) select_actionchannel_by_name(ob->action, bone->name, mode);
1891
1892         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
1893                 deselect_bonechildren(ob, curBone, mode);
1894         }
1895 }
1896
1897 /* test==0: deselect all
1898    test==1: swap select
1899    test==2: only clear active tag 
1900 */
1901 void deselectall_posearmature (Object *ob, int test)
1902 {
1903         bArmature *arm;
1904         Bone *curBone;
1905         int     selectmode= 0;
1906         
1907         /* we call this from outliner too, but with OBACT set OK */
1908         if(!ob || !ob->pose) return;
1909         arm= get_armature(ob);
1910         
1911         /*      Determine if we're selecting or deselecting     */
1912         if (test==1) {
1913                 if (!count_bones (arm, BONE_SELECTED, 0))
1914                         selectmode= 1;
1915         }
1916         else if(test==2)
1917                 selectmode= 2;
1918         
1919         /*      Set the flags accordingly       */
1920         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next)
1921                 deselect_bonechildren (ob, curBone, selectmode);
1922         
1923         allqueue(REDRAWBUTSEDIT, 0);
1924         allqueue(REDRAWBUTSOBJECT, 0);
1925         allqueue(REDRAWVIEW3D, 0);
1926         allqueue(REDRAWOOPS, 0);
1927         allqueue(REDRAWACTION, 0);
1928
1929 }
1930
1931
1932 int bone_looper(Object *ob, Bone *bone, void *data,
1933                         int (*bone_func)(Object *, Bone *, void *)) 
1934 {
1935
1936     /* We want to apply the function bone_func to every bone 
1937      * in an armature -- feed bone_looper the first bone and 
1938      * a pointer to the bone_func and watch it go!. The int count 
1939      * can be useful for counting bones with a certain property
1940      * (e.g. skinnable)
1941      */
1942     int count = 0;
1943
1944     if (bone) {
1945
1946         /* only do bone_func if the bone is non null
1947          */
1948         count += bone_func(ob, bone, data);
1949
1950         /* try to execute bone_func for the first child
1951          */
1952         count += bone_looper(ob, bone->childbase.first, data,
1953                                     bone_func);
1954
1955         /* try to execute bone_func for the next bone at this
1956          * depth of the recursion.
1957          */
1958         count += bone_looper(ob, bone->next, data, bone_func);
1959     }
1960
1961     return count;
1962 }
1963
1964 int ik_chain_looper(Object *ob, Bone *bone, void *data,
1965                                    int (*bone_func)(Object *, Bone *, void *)) 
1966 {
1967
1968     /* We want to apply the function bone_func to every bone 
1969      * in an ik chain -- feed ikchain_looper a bone in the chain and 
1970      * a pointer to the bone_func and watch it go!. The int count 
1971      * can be useful for counting bones with a certain property
1972      * (e.g. skinnable)
1973      */
1974         Bone *curBone;
1975     int   count = 0;
1976
1977     if (bone) {
1978
1979         /* This bone */
1980         count += bone_func(ob, bone, data);
1981
1982         /* The parents */
1983                 for (curBone = bone; curBone; curBone=curBone->parent) {
1984                         if (!curBone->parent)
1985                                 break;
1986                         else if (!(curBone->flag & BONE_CONNECTED))
1987                                 break;
1988                         count += bone_func(ob, curBone->parent, data);
1989                 }
1990
1991                 /* The children */
1992                 for (curBone = bone->childbase.first; curBone; curBone=curBone->next){
1993                         if (curBone->flag & BONE_CONNECTED) {
1994                                 count += bone_func(ob, curBone, data);
1995                         }
1996                 }
1997     }
1998
1999     return count;
2000 }
2001
2002 static int bone_skinnable(Object *ob, Bone *bone, void *data)
2003 {
2004     /* Bones that are deforming
2005      * are regarded to be "skinnable" and are eligible for
2006      * auto-skinning.
2007      *
2008      * This function performs 2 functions:
2009      *
2010      *   a) It returns 1 if the bone is skinnable.
2011      *      If we loop over all bones with this 
2012      *      function, we can count the number of
2013      *      skinnable bones.
2014      *   b) If the pointer data is non null,
2015      *      it is treated like a handle to a
2016      *      bone pointer -- the bone pointer
2017      *      is set to point at this bone, and
2018      *      the pointer the handle points to
2019      *      is incremented to point to the
2020      *      next member of an array of pointers
2021      *      to bones. This way we can loop using
2022      *      this function to construct an array of
2023      *      pointers to bones that point to all
2024      *      skinnable bones.
2025      */
2026     Bone ***hbone;
2027
2028     if (!(bone->flag & BONE_NO_DEFORM)) {
2029                 if (data != NULL) {
2030                         hbone = (Bone ***) data;
2031             **hbone = bone;
2032             ++*hbone;
2033         }
2034         return 1;
2035     }
2036     return 0;
2037 }
2038
2039 static int add_defgroup_unique_bone(Object *ob, Bone *bone, void *data) 
2040 {
2041     /* This group creates a vertex group to ob that has the
2042      * same name as bone (provided the bone is skinnable). 
2043          * If such a vertex group aleady exist the routine exits.
2044      */
2045         if (!(bone->flag & BONE_NO_DEFORM)) {
2046                 if (!get_named_vertexgroup(ob,bone->name)) {
2047                         add_defgroup_name(ob, bone->name);
2048                         return 1;
2049                 }
2050     }
2051     return 0;
2052 }
2053
2054 static int dgroup_skinnable(Object *ob, Bone *bone, void *data) 
2055 {
2056     /* Bones that are not of boneclass BONE_UNSKINNABLE
2057      * are regarded to be "skinnable" and are eligible for
2058      * auto-skinning.
2059      *
2060      * This function performs 2 functions:
2061      *
2062      *   a) If the bone is skinnable, it creates 
2063      *      a vertex group for ob that has
2064      *      the name of the skinnable bone
2065      *      (if one doesn't exist already).
2066      *   b) If the pointer data is non null,
2067      *      it is treated like a handle to a
2068      *      bDeformGroup pointer -- the 
2069      *      bDeformGroup pointer is set to point
2070      *      to the deform group with the bone's
2071      *      name, and the pointer the handle 
2072      *      points to is incremented to point to the
2073      *      next member of an array of pointers
2074      *      to bDeformGroups. This way we can loop using
2075      *      this function to construct an array of
2076      *      pointers to bDeformGroups, all with names
2077      *      of skinnable bones.
2078      */
2079     bDeformGroup ***hgroup, *defgroup;
2080
2081     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2082         if ( !(defgroup = get_named_vertexgroup(ob, bone->name)) ) {
2083             defgroup = add_defgroup_name(ob, bone->name);
2084         }
2085
2086         if (data != NULL) {
2087             hgroup = (bDeformGroup ***) data;
2088             **hgroup = defgroup;
2089             ++*hgroup;
2090         }
2091         return 1;
2092     }
2093     return 0;
2094 }
2095
2096 static void add_verts_to_closest_dgroup(Object *ob, Object *par)
2097 {
2098     /* This function implements a crude form of 
2099      * auto-skinning: vertices are assigned to the
2100      * deformation groups associated with bones based
2101      * on thier proximity to a bone. Every vert is
2102      * given a weight of 1.0 to the weight group
2103      * cooresponding to the bone that it is
2104      * closest to. The vertex may also be assigned to
2105      * a deformation group associated to a bone
2106      * that is within 10% of the mninimum distance
2107      * between the bone and the nearest vert -- the
2108      * cooresponding weight will fall-off to zero
2109      * as the distance approaches the 10% tolerance mark.
2110          * If the mesh has subsurf enabled then the verts
2111          * on the subsurf limit surface is used to generate 
2112          * the weights rather than the verts on the cage
2113          * mesh.
2114          *
2115          * ("Limit surface" = same amount of vertices as mesh, but vertices 
2116      *   moved to the subsurfed position, like for 'optimal').
2117      */
2118
2119     bArmature *arm;
2120     Bone **bonelist, **bonehandle, *bone;
2121     bDeformGroup **dgrouplist, **dgrouphandle, *defgroup;
2122     float *distance;
2123     float   root[3];
2124     float   tip[3];
2125     float real_co[3];
2126         float *subverts = NULL;
2127     float *subvert;
2128     Mesh  *mesh;
2129     MVert *vert;
2130
2131     int numbones, i, j;
2132
2133     /* If the parent object is not an armature exit */
2134     arm = get_armature(par);
2135     if (!arm)
2136         return;
2137
2138     /* count the number of skinnable bones */
2139     numbones = bone_looper(ob, arm->bonebase.first, NULL,
2140                                   bone_skinnable);
2141
2142     /* create an array of pointer to bones that are skinnable
2143      * and fill it with all of the skinnable bones
2144      */
2145     bonelist = MEM_mallocN(numbones*sizeof(Bone *), "bonelist");
2146     bonehandle = bonelist;
2147     bone_looper(ob, arm->bonebase.first, &bonehandle,
2148                        bone_skinnable);
2149
2150     /* create an array of pointers to the deform groups that
2151      * coorespond to the skinnable bones (creating them
2152      * as necessary.
2153      */
2154     dgrouplist = MEM_mallocN(numbones*sizeof(bDeformGroup *), "dgrouplist");
2155     dgrouphandle = dgrouplist;
2156     bone_looper(ob, arm->bonebase.first, &dgrouphandle,
2157                        dgroup_skinnable);
2158
2159     /* create an array of floats that will be used for each vert
2160      * to hold the distance-factor to each bone.
2161      */
2162     distance = MEM_mallocN(numbones*sizeof(float), "distance");
2163
2164     mesh = (Mesh*)ob->data;
2165
2166         /* Is subsurf on? Lets use the verts on the limit surface then */
2167         if (modifiers_findByType(ob, eModifierType_Subsurf)) {
2168                 subverts = MEM_mallocN(3*mesh->totvert*sizeof(float), "subverts");
2169                 subsurf_calculate_limit_positions(mesh, (void *)subverts);      /* (ton) made void*, dunno how to cast */
2170         }
2171
2172     /* for each vertex in the mesh ...
2173      */
2174     for ( i=0 ; i < mesh->totvert ; ++i ) {
2175         /* get the vert in global coords
2176          */
2177                 
2178                 if (subverts) {
2179                         subvert = subverts + i*3;
2180                         VECCOPY (real_co, subvert);
2181                 }
2182                 else {
2183                         vert = mesh->mvert + i;
2184                         VECCOPY (real_co, vert->co);
2185                 }
2186         Mat4MulVecfl(ob->obmat, real_co);
2187
2188
2189         /* for each skinnable bone ...
2190          */
2191         for (j=0; j < numbones; ++j) {
2192             bone = bonelist[j];
2193
2194             /* get the root of the bone in global coords
2195              */
2196                         VECCOPY(root, bone->arm_head);
2197                         Mat4MulVecfl(par->obmat, root);
2198
2199             /* get the tip of the bone in global coords
2200              */
2201                         VECCOPY(tip, bone->arm_tail);
2202             Mat4MulVecfl(par->obmat, tip);
2203
2204             /* store the distance-factor from the vertex to
2205              * the bone
2206              */
2207                         distance[j]= distfactor_to_bone (real_co, root, tip, bone->rad_head, bone->rad_tail, bone->dist);
2208         }
2209
2210         /* for each deform group ...
2211          */
2212         for (j=0; j < numbones; ++j) {
2213             defgroup = dgrouplist[j];
2214
2215             /* add the vert to the deform group if weight!=0.0
2216              */
2217             if (distance[j]!=0.0)
2218                 add_vert_to_defgroup (ob, defgroup, i, distance[j], WEIGHT_REPLACE);
2219             else
2220                 remove_vert_defgroup (ob, defgroup, i);
2221         }
2222     }
2223
2224     /* free the memory allocated
2225      */
2226     MEM_freeN(bonelist);
2227     MEM_freeN(dgrouplist);
2228     MEM_freeN(distance);
2229         if (subverts) MEM_freeN(subverts);
2230 }
2231
2232 void create_vgroups_from_armature(Object *ob, Object *par)
2233 {
2234         /* Lets try to create some vertex groups 
2235          * based on the bones of the parent armature.
2236          */
2237
2238         bArmature *arm;
2239         short mode;
2240
2241         /* If the parent object is not an armature exit */
2242         arm = get_armature(par);
2243         if (!arm)
2244                 return;
2245
2246         /* Prompt the user on whether/how they want the vertex groups
2247          * added to the child mesh */
2248     mode= pupmenu("Create Vertex Groups? %t|"
2249                                   "Don't Create Groups %x1|"
2250                                   "Name Groups %x2|"
2251                   "Create From Closest Bones %x3");
2252         switch (mode){
2253         case 2:
2254                 /* Traverse the bone list, trying to create empty vertex 
2255                  * groups cooresponding to the bone.
2256                  */
2257                 bone_looper(ob, arm->bonebase.first, NULL,
2258                                         add_defgroup_unique_bone);
2259                 if (ob->type == OB_MESH)
2260                         create_dverts((Mesh*)ob->data);
2261
2262                 break;
2263
2264         case 3:
2265                 /* Traverse the bone list, trying to create vertex groups 
2266                  * that are populated with the vertices for which the
2267                  * bone is closest.
2268                  */
2269                 add_verts_to_closest_dgroup(ob, par);
2270                 break;
2271
2272         }
2273
2274
2275 static int hide_selected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2276 {
2277         if (bone->flag & BONE_SELECTED) {
2278                 bone->flag |= BONE_HIDDEN_P;
2279                 bone->flag &= ~BONE_SELECTED;
2280         }
2281         return 0;
2282 }
2283
2284 /* active object is armature */
2285 void hide_selected_pose_bones(void) 
2286 {
2287         bArmature               *arm;
2288
2289         arm= get_armature (OBACT);
2290
2291         if (!arm)
2292                 return;
2293
2294         bone_looper(OBACT, arm->bonebase.first, NULL, 
2295                                 hide_selected_pose_bone);
2296
2297         allqueue(REDRAWVIEW3D, 0);
2298         allqueue(REDRAWBUTSEDIT, 0);
2299 }
2300
2301 static int hide_unselected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2302 {
2303         if (~bone->flag & BONE_SELECTED) {
2304                 bone->flag |= BONE_HIDDEN_P;
2305         }
2306         return 0;
2307 }
2308
2309 /* active object is armature */
2310 void hide_unselected_pose_bones(void) 
2311 {
2312         bArmature               *arm;
2313
2314         arm=get_armature (OBACT);
2315
2316         if (!arm)
2317                 return;
2318
2319         bone_looper(OBACT, arm->bonebase.first, NULL, 
2320                                 hide_unselected_pose_bone);
2321
2322         allqueue(REDRAWVIEW3D, 0);
2323         allqueue(REDRAWBUTSEDIT, 0);
2324 }
2325
2326 static int show_pose_bone(Object *ob, Bone *bone, void *ptr) 
2327 {
2328         if (bone->flag & BONE_HIDDEN_P) {
2329                 bone->flag &= ~BONE_HIDDEN_P;
2330                 bone->flag |= BONE_SELECTED;
2331         }
2332
2333         return 0;
2334 }
2335
2336 /* active object is armature in posemode */
2337 void show_all_pose_bones(void) 
2338 {
2339         bArmature               *arm;
2340
2341         arm=get_armature (OBACT);
2342
2343         if (!arm)
2344                 return;
2345
2346         bone_looper(OBACT, arm->bonebase.first, NULL, 
2347                                 show_pose_bone);
2348
2349         allqueue(REDRAWVIEW3D, 0);
2350         allqueue(REDRAWBUTSEDIT, 0);
2351 }
2352
2353
2354 /* ************* RENAMING DISASTERS ************ */
2355
2356 /* note: there's a unique_editbone_name() too! */
2357 void unique_bone_name (bArmature *arm, char *name)
2358 {
2359         char            tempname[64];
2360         int                     number;
2361         char            *dot;
2362         
2363         if (get_named_bone(arm, name)) {
2364                 
2365                 /*      Strip off the suffix, if it's a number */
2366                 number= strlen(name);
2367                 if(number && isdigit(name[number-1])) {
2368                         dot= strrchr(name, '.');        // last occurrance
2369                         if (dot)
2370                                 *dot=0;
2371                 }
2372                 
2373                 for (number = 1; number <=999; number++){
2374                         sprintf (tempname, "%s.%03d", name, number);
2375                         if (!get_named_bone(arm, tempname)){
2376                                 strcpy (name, tempname);
2377                                 return;
2378                         }
2379                 }
2380         }
2381 }
2382
2383 #define MAXBONENAME 32
2384 /* helper call for below */
2385 static void constraint_bone_name_fix(Object *ob, ListBase *conlist, char *oldname, char *newname)
2386 {
2387         bConstraint *curcon;
2388         char *subtarget;
2389         
2390         for (curcon = conlist->first; curcon; curcon=curcon->next){
2391                 subtarget = get_con_subtarget_name(curcon, ob);
2392                 if (subtarget)
2393                         if (!strcmp(subtarget, oldname) )
2394                                 BLI_strncpy(subtarget, newname, MAXBONENAME);
2395         }
2396 }
2397
2398 /* called by UI for renaming a bone */
2399 /* warning: make sure the original bone was not renamed yet! */
2400 /* seems messy, but thats what you get with not using pointers but channel names :) */
2401 void armature_bone_rename(bArmature *arm, char *oldnamep, char *newnamep)
2402 {
2403         Object *ob, *modob;
2404         char newname[MAXBONENAME];
2405         char oldname[MAXBONENAME];
2406         
2407         /* names better differ! */
2408         if(strncmp(oldnamep, newnamep, MAXBONENAME)) {
2409                 
2410                 /* we alter newname string... so make copy */
2411                 BLI_strncpy(newname, newnamep, MAXBONENAME);
2412                 /* we use oldname for search... so make copy */
2413                 BLI_strncpy(oldname, oldnamep, MAXBONENAME);
2414                 
2415                 /* now check if we're in editmode, we need to find the unique name */
2416                 if(G.obedit && G.obedit->data==arm) {
2417                         EditBone        *eBone;
2418
2419                         eBone= editbone_name_exists(oldname);
2420                         if(eBone) {
2421                                 unique_editbone_name (newname);
2422                                 BLI_strncpy(eBone->name, newname, MAXBONENAME);
2423                         }
2424                         else return;
2425                 }
2426                 else {
2427                         Bone *bone= get_named_bone (arm, oldname);
2428
2429                         if(bone) {
2430                                 unique_bone_name (arm, newname);
2431                                 BLI_strncpy(bone->name, newname, MAXBONENAME);
2432                         }
2433                         else return;
2434                 }
2435                 
2436                 /* do entire dbase */
2437                 for(ob= G.main->object.first; ob; ob= ob->id.next) {
2438                         /* we have the object using the armature */
2439                         if(arm==ob->data) {
2440                                 Object *cob;
2441                                 bAction  *act;
2442                                 bActionChannel *chan;
2443
2444                                 /* Rename action channel if necessary */
2445                                 act = ob->action;
2446                                 if (act && !act->id.lib){
2447                                         /*      Find the appropriate channel */
2448                                         chan= get_named_actionchannel(act, oldname);
2449                                         if(chan) BLI_strncpy(chan->name, newname, MAXBONENAME);
2450                                 }
2451                 
2452                                 /* Rename the pose channel, if it exists */
2453                                 if (ob->pose) {
2454                                         bPoseChannel *pchan = get_pose_channel(ob->pose, oldname);
2455                                         if (pchan) {
2456                                                 BLI_strncpy (pchan->name, newname, MAXBONENAME);
2457                                         }
2458                                 }
2459                                 
2460                                 /* and actually do the NLA too */
2461                                 /* (todo) */
2462                                 
2463                                 /* Update any object constraints to use the new bone name */
2464                                 for(cob= G.main->object.first; cob; cob= cob->id.next) {
2465                                         if(cob->constraints.first)
2466                                                 constraint_bone_name_fix(ob, &cob->constraints, oldname, newname);
2467                                         if (cob->pose) {
2468                                                 bPoseChannel *pchan;
2469                                                 for (pchan = cob->pose->chanbase.first; pchan; pchan=pchan->next) {
2470                                                         constraint_bone_name_fix(ob, &pchan->constraints, oldname, newname);
2471                                                 }
2472                                         }
2473                                 }
2474                                 
2475                         }
2476                                         
2477                         /* See if an object is parented to this armature */
2478                         if (ob->parent && (ob->parent->data == arm)) {
2479                                 if(ob->partype==PARBONE) {
2480                                         /* bone name in object */
2481                                         if (!strcmp(ob->parsubstr, oldname))
2482                                                 BLI_strncpy(ob->parsubstr, newname, MAXBONENAME);
2483                                 }
2484                         }
2485                         /* or is there an armature deforming object */
2486                         modob = modifiers_isDeformedByArmature(ob);
2487                         if(modob) {
2488                                 bDeformGroup *dg;
2489                                 /* bone name in defgroup */
2490                                 for (dg=ob->defbase.first; dg; dg=dg->next) {
2491                                         if(!strcmp(dg->name, oldname))
2492                                            BLI_strncpy(dg->name, newname, MAXBONENAME);
2493                                 }
2494                         }
2495                 }
2496         }
2497 }
2498
2499 /* context editmode object */
2500 void armature_flip_names(void)
2501 {
2502         EditBone *ebone;
2503         char newname[32];
2504         
2505         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2506                 if(ebone->flag & BONE_SELECTED) {
2507                         BLI_strncpy(newname, ebone->name, sizeof(newname));
2508                         bone_flip_name(newname, 1);             // 1 = do strip off number extensions
2509                         armature_bone_rename(G.obedit->data, ebone->name, newname);
2510                 }
2511         }
2512         
2513         allqueue(REDRAWVIEW3D, 0);
2514         allqueue(REDRAWBUTSEDIT, 0);
2515         allqueue(REDRAWBUTSOBJECT, 0);
2516         allqueue (REDRAWACTION, 0);
2517         allqueue(REDRAWOOPS, 0);
2518         BIF_undo_push("Flip names");
2519         
2520 }
2521
2522 /* context; editmode armature */
2523 EditBone *armature_bone_get_mirrored(EditBone *ebo)
2524 {
2525         EditBone *eboflip= NULL;
2526         char name[32];
2527         
2528         BLI_strncpy(name, ebo->name, sizeof(name));
2529         bone_flip_name(name, 0);                // 0 = don't strip off number extensions
2530
2531         for (eboflip=G.edbo.first; eboflip; eboflip=eboflip->next)
2532                 if(ebo!=eboflip)
2533                         if (!strcmp (name, eboflip->name)) break;
2534         
2535         return eboflip;
2536 }
2537