A couple of smaller fixes;
[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_IK_TOPARENT))
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_IK_TOPARENT))
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_IK_TOPARENT)
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_IK_TOPARENT)
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_IK_TOPARENT){
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_IK_TOPARENT;
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-IK 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_IK_TOPARENT)) {
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.5F;
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.25;
1182         bone->rad_tail= 0.1;
1183         bone->segments= 1;
1184         bone->boneclass = BONE_SKINNABLE;
1185         
1186         return bone;
1187 }
1188
1189 static void add_primitive_bone(Object *ob)
1190 {
1191         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
1192         EditBone        *bone;
1193         
1194         VECCOPY (curs, give_cursor());  
1195
1196         /* Get inverse point for head and orientation for tail */
1197         Mat4Invert(G.obedit->imat, G.obedit->obmat);
1198         Mat4MulVecfl(G.obedit->imat, curs);
1199
1200         Mat3CpyMat4(obmat, G.vd->viewmat);
1201         Mat3CpyMat4(viewmat, G.obedit->obmat);
1202         Mat3MulMat3(totmat, obmat, viewmat);
1203         Mat3Inv(imat, totmat);
1204         
1205         deselectall_armature(0);
1206         
1207         /*      Create a bone   */
1208         bone= add_editbone();
1209
1210         VECCOPY(bone->head, curs);
1211         VecAddf(bone->tail, bone->head, imat[1]);       // bone with unit length 1
1212         
1213 }
1214
1215 void add_primitiveArmature(int type)
1216 {
1217         if(G.scene->id.lib) return;
1218         
1219         /* this function also comes from an info window */
1220         if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
1221         if(G.vd==NULL) return;
1222         
1223         G.f &= ~(G_VERTEXPAINT+G_FACESELECT+G_TEXTUREPAINT+G_WEIGHTPAINT);
1224         setcursor_space(SPACE_VIEW3D, CURSOR_STD);
1225
1226         check_editmode(OB_ARMATURE);
1227         
1228         /* If we're not the "obedit", make a new object and enter editmode */
1229         if(G.obedit==NULL) {
1230                 add_object(OB_ARMATURE);
1231                 base_init_from_view3d(BASACT, G.vd);
1232                 G.obedit= BASACT->object;
1233                 
1234                 where_is_object(G.obedit);
1235                 
1236                 make_editArmature();
1237                 setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
1238         }
1239         
1240         /* no primitive support yet */
1241         add_primitive_bone(G.obedit);
1242         
1243         countall(); // flushes selection!
1244
1245         allqueue(REDRAWALL, 0);
1246         BIF_undo_push("Add primitive");
1247 }
1248
1249 /* the ctrl-click method */
1250 void addvert_armature(void)
1251 {
1252         EditBone *ebone, *newbone, *partest;
1253         float *curs, mat[3][3],imat[3][3];
1254         int to_root= 0;
1255         
1256         TEST_EDITARMATURE;
1257         
1258         /* find the active or selected bone */
1259         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1260                 if(ebone->flag & (BONE_ACTIVE|BONE_TIPSEL)) break;
1261         
1262         if(ebone==NULL) {
1263                 for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1264                         if(ebone->flag & (BONE_ACTIVE|BONE_ROOTSEL)) break;
1265                 
1266                 if(ebone==NULL) 
1267                         return;
1268                 to_root= 1;
1269         }
1270         
1271         deselectall_armature(0);
1272         newbone= add_editbone();
1273         newbone->flag |= BONE_ACTIVE;
1274         
1275         if(to_root) {
1276                 VECCOPY(newbone->head, ebone->head);
1277                 
1278                 newbone->parent= ebone->parent;
1279         }
1280         else {
1281                 VECCOPY(newbone->head, ebone->tail);
1282
1283                 
1284                 /* See if there are any ik children of the parent */
1285                 for (partest = G.edbo.first; partest; partest= partest->next){
1286                         if ((partest->parent == ebone) && (partest->flag & BONE_IK_TOPARENT))
1287                                 break;
1288                 }
1289                 if(!partest)
1290                         newbone->flag |= BONE_IK_TOPARENT;
1291                 
1292                 newbone->parent= ebone;
1293         }
1294         
1295         curs= give_cursor();
1296         VECCOPY(newbone->tail, curs);
1297         VecSubf(newbone->tail, newbone->tail, G.obedit->obmat[3]);
1298         
1299         Mat3CpyMat4(mat, G.obedit->obmat);
1300         Mat3Inv(imat, mat);
1301         Mat3MulVecfl(imat, newbone->tail);
1302
1303         newbone->length= VecLenf(newbone->head, newbone->tail);
1304         newbone->rad_tail= newbone->length*0.1f;
1305         newbone->dist= newbone->length*0.25f;
1306         
1307         countall();
1308         
1309         BIF_undo_push("Add Bone");
1310         allqueue(REDRAWVIEW3D, 0);
1311         
1312         while(get_mbut()&R_MOUSE);
1313 }
1314
1315
1316 void adduplicate_armature(void)
1317 {
1318         EditBone        *eBone = NULL;
1319         EditBone        *curBone;
1320         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
1321         
1322         countall(); // flushes selection!
1323         
1324         /*      Find the selected bones and duplicate them as needed */
1325         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1326                 if (curBone->flag & BONE_SELECTED){
1327                         
1328                         eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
1329                         eBone->flag |= BONE_SELECTED;
1330                         
1331                         /*      Copy data from old bone to new bone */
1332                         memcpy (eBone, curBone, sizeof(EditBone));
1333                         
1334                         curBone->temp = eBone;
1335                         eBone->temp = curBone;
1336                         
1337                         unique_editbone_name (eBone->name);
1338                         BLI_addtail (&G.edbo, eBone);
1339                         if (!firstDup)
1340                                 firstDup=eBone;
1341                         
1342                         /* Lets duplicate the list of constraits that the
1343                                 * current bone has.
1344                                 */
1345                         /* temporal removed (ton) */
1346                 }
1347         }
1348         
1349         if (eBone){
1350                 /*      Fix the head and tail */        
1351                 if (eBone->parent && !eBone->parent->flag & BONE_SELECTED){
1352                         VecSubf (eBone->tail, eBone->tail, eBone->head);
1353                         VecSubf (eBone->head, eBone->head, eBone->head);
1354                 }
1355         }
1356         
1357         /*      Run though the list and fix the pointers */
1358         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1359                 
1360                 if (curBone->flag & BONE_SELECTED){
1361                         eBone=(EditBone*) curBone->temp;
1362                         
1363                         /*      If this bone has no parent,
1364                         Set the duplicate->parent to NULL
1365                         */
1366                         if (!curBone->parent){
1367                                 eBone->parent = NULL;
1368                         }
1369                         /*      If this bone has a parent that IS selected,
1370                                 Set the duplicate->parent to the curBone->parent->duplicate
1371                                 */
1372                         else if (curBone->parent->flag & BONE_SELECTED){
1373                                 eBone->parent=(EditBone*) curBone->parent->temp;
1374                         }
1375                         /*      If this bone has a parent that IS not selected,
1376                                 Set the duplicate->parent to the curBone->parent
1377                                 */
1378                         else {
1379                                 eBone->parent=(EditBone*) curBone->parent; 
1380                                 eBone->flag &= ~BONE_IK_TOPARENT;
1381                         }
1382                         
1383                         /* Lets try to fix any constraint subtargets that might
1384                                 have been duplicated */
1385                         /* temporal removed (ton) */
1386                         
1387                 }
1388         } 
1389         
1390         /*      Deselect the old bones and select the new ones */
1391         
1392         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1393                 curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1394         }
1395         
1396         BIF_TransformSetUndo("Add Duplicate");
1397         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1398         Transform();
1399         
1400         allqueue(REDRAWBUTSEDIT, 0);
1401         allqueue(REDRAWBUTSOBJECT, 0);
1402         allqueue(REDRAWOOPS, 0);
1403 }
1404
1405
1406
1407 /* *************** END Adding stuff in editmode *************** */
1408 /* *************** Tools in editmode *********** */
1409
1410
1411 void hide_selected_armature_bones(void)
1412 {
1413         EditBone *ebone;
1414         
1415         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1416                 if(ebone->flag & (BONE_SELECTED)) {
1417                         ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1418                         ebone->flag |= BONE_HIDDEN_A;
1419                 }
1420         }
1421         countall();
1422         allqueue(REDRAWVIEW3D, 0);
1423         allqueue(REDRAWBUTSEDIT, 0);
1424 }
1425
1426 void hide_unselected_armature_bones(void)
1427 {
1428         EditBone *ebone;
1429         
1430         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1431                 if(ebone->flag & (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL));
1432                 else {
1433                         ebone->flag &= ~BONE_ACTIVE;
1434                         ebone->flag |= BONE_HIDDEN_A;
1435                 }
1436         }
1437         countall();
1438         allqueue(REDRAWVIEW3D, 0);
1439         allqueue(REDRAWBUTSEDIT, 0);
1440 }
1441
1442 void show_all_armature_bones(void)
1443 {
1444         EditBone *ebone;
1445         
1446         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1447                 if(ebone->flag & BONE_HIDDEN_A) {
1448                         ebone->flag |= (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
1449                         ebone->flag &= ~BONE_HIDDEN_A;
1450                 }
1451         }
1452         countall();
1453         allqueue(REDRAWVIEW3D, 0);
1454         allqueue(REDRAWBUTSEDIT, 0);
1455 }
1456
1457
1458
1459 /* the "IK" button in editbuttons */
1460 void attach_bone_to_parent_cb(void *bonev, void *arg2_unused)
1461 {
1462         EditBone *ebone= bonev;
1463         attach_bone_to_parent(ebone);
1464 }
1465
1466 void attach_bone_to_parent(EditBone *bone)
1467 {
1468         EditBone *ebone;
1469
1470         if (bone->flag & BONE_IK_TOPARENT) {
1471
1472                 /* See if there are any other bones that refer to the same 
1473                  * parent and disconnect them 
1474                  */
1475                 for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1476                         if (ebone!=bone){
1477                                 if (ebone->parent && (ebone->parent == bone->parent) && 
1478                                         (ebone->flag & BONE_IK_TOPARENT))
1479                                                 ebone->flag &= ~BONE_IK_TOPARENT;
1480                         }
1481                 }
1482
1483         /* Attach this bone to its parent */
1484                 VECCOPY(bone->head, bone->parent->tail);
1485         }
1486 }
1487
1488 void make_bone_parent(void)
1489 {
1490         EditBone *ebone;
1491         float offset[3];
1492         short val;
1493         
1494         val= pupmenu("Make Parent%t|Connected%x1|Keep Offset%x2");
1495         
1496         if(val<1) return;
1497         
1498         /* find active */
1499         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1500                 if(ebone->flag & BONE_ACTIVE) break;
1501         if(ebone) {
1502                 EditBone *actbone= ebone, *selbone= NULL;
1503                 
1504                 /* find selected */
1505                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1506                         if(ebone->flag & BONE_SELECTED) {
1507                                 if(ebone!=actbone) {
1508                                         if(selbone==NULL) selbone= ebone;
1509                                         else {
1510                                                 error("Need one active and one selected bone");
1511                                                 return;
1512                                         }
1513                                 }
1514                         }
1515                 }
1516                 if(selbone==NULL) error("Need one active and one selected bone");
1517                 else {
1518                         /* if selbone had a parent we clear parent tip */
1519                         if(selbone->parent && (selbone->flag & BONE_IK_TOPARENT))
1520                            selbone->parent->flag &= ~(BONE_TIPSEL);
1521                         
1522                         selbone->parent= actbone;
1523                         
1524                         /* in actbone tree we cannot have a loop */
1525                         for(ebone= actbone->parent; ebone; ebone= ebone->parent) {
1526                                 if(ebone->parent==selbone) {
1527                                         ebone->parent= NULL;
1528                                         ebone->flag &= ~BONE_IK_TOPARENT;
1529                                 }
1530                         }
1531                         
1532                         if(val==1) {    // connected
1533                                 selbone->flag |= BONE_IK_TOPARENT;
1534                                 VecSubf(offset, actbone->tail, selbone->head);
1535                                 
1536                                 VECCOPY(selbone->head, actbone->tail);
1537                                 VecAddf(selbone->tail, selbone->tail, offset);
1538                                 
1539                                 // offset for all its children 
1540                                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1541                                         EditBone *par;
1542                                         for(par= ebone->parent; par; par= par->parent) {
1543                                                 if(par==selbone) {
1544                                                         VecAddf(ebone->head, ebone->head, offset);
1545                                                         VecAddf(ebone->tail, ebone->tail, offset);
1546                                                         break;
1547                                                 }
1548                                         }
1549                                 }
1550                         }
1551                         else {
1552                                 selbone->flag &= ~BONE_IK_TOPARENT;
1553                         }
1554                         
1555                         countall(); // checks selection
1556                         allqueue(REDRAWVIEW3D, 0);
1557                         allqueue(REDRAWBUTSEDIT, 0);
1558                         allqueue(REDRAWOOPS, 0);
1559                 }
1560         }
1561         return;
1562 }
1563
1564 void clear_bone_parent(void)
1565 {
1566         EditBone *ebone;
1567         short val;
1568         
1569         val= pupmenu("Clear Parent%t|Clear Parent%x1|Disconnect IK%x2");
1570         
1571         if(val<1) return;
1572         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1573                 if(ebone->flag & BONE_SELECTED) {
1574                         if(ebone->parent) {
1575                                 /* for nice selection */
1576                                 ebone->parent->flag &= ~(BONE_TIPSEL);
1577                                 
1578                                 if(val==1) ebone->parent= NULL;
1579                                 ebone->flag &= ~BONE_IK_TOPARENT;
1580                                 
1581                         }
1582                 }
1583         }
1584         countall(); // checks selection
1585         allqueue(REDRAWVIEW3D, 0);
1586         allqueue(REDRAWBUTSEDIT, 0);
1587         allqueue(REDRAWOOPS, 0);
1588 }
1589         
1590
1591 static EditBone *editbone_name_exists (char *name)
1592 {
1593         EditBone        *eBone;
1594         
1595         for (eBone=G.edbo.first; eBone; eBone=eBone->next){
1596                 if (!strcmp (name, eBone->name))
1597                         return eBone;
1598         }
1599         return NULL;
1600 }
1601
1602 /* note: there's a unique_bone_name() too! */
1603 void unique_editbone_name (char *name)
1604 {
1605         char            tempname[64];
1606         int                     number;
1607         char            *dot;
1608         
1609         
1610         if (editbone_name_exists(name)) {
1611                 
1612                 /*      Strip off the suffix, if it's a number */
1613                 number= strlen(name);
1614                 if(number && isdigit(name[number-1])) {
1615                         dot= strrchr(name, '.');        // last occurrance
1616                         if (dot)
1617                                 *dot=0;
1618                 }
1619                 
1620                 for (number = 1; number <=999; number++){
1621                         sprintf (tempname, "%s.%03d", name, number);
1622                         if (!editbone_name_exists(tempname)){
1623                                 strcpy (name, tempname);
1624                                 return;
1625                         }
1626                 }
1627         }
1628 }
1629
1630 /* context; editmode armature */
1631 /* if forked && mirror-edit: makes two bones with flipped names */
1632 void extrude_armature(int forked)
1633 {
1634         bArmature *arm= G.obedit->data;
1635         EditBone *newbone, *ebone, *flipbone, *first=NULL, *partest;
1636         int a, totbone= 0, do_extrude;
1637         
1638         TEST_EDITARMATURE;
1639         
1640         /* since we allow root extrude too, we have to make sure selection is OK */
1641         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1642                 if(ebone->flag & BONE_ROOTSEL) {
1643                         if(ebone->parent && (ebone->flag & BONE_IK_TOPARENT)) {
1644                                 if(ebone->parent->flag & BONE_TIPSEL)
1645                                         ebone->flag &= ~BONE_ROOTSEL;
1646                         }
1647                 }
1648         }
1649         
1650         /* Duplicate the necessary bones */
1651         for (ebone = G.edbo.first; ((ebone) && (ebone!=first)); ebone=ebone->next){
1652                 
1653                 /* we extrude per definition the tip */
1654                 do_extrude= 0;
1655                 if (ebone->flag & (BONE_TIPSEL|BONE_SELECTED))
1656                         do_extrude= 1;
1657                 else if(ebone->flag & BONE_ROOTSEL) {
1658                         /* but, a bone with parent deselected we do the root... */
1659                         if(ebone->parent && (ebone->parent->flag & BONE_TIPSEL));
1660                         else do_extrude= 2;
1661                 }
1662                 
1663                 if (do_extrude) {
1664                         
1665                         /* we re-use code for mirror editing... */
1666                         flipbone= NULL;
1667                         if(arm->flag & ARM_MIRROR_EDIT) {
1668                                 flipbone= armature_bone_get_mirrored(ebone);
1669                                 if (flipbone) {
1670                                         forked= 0;      // we extrude 2 different bones
1671                                         if(flipbone->flag & (BONE_TIPSEL|BONE_ROOTSEL|BONE_SELECTED))
1672                                                 /* don't want this bone to be selected... */
1673                                                 flipbone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1674                                 }
1675                                 if(flipbone==NULL && forked)
1676                                         flipbone= ebone;
1677                         }
1678                         
1679                         for(a=0; a<2; a++) {
1680                                 if(a==1) {
1681                                         if(flipbone==NULL)
1682                                                 break;
1683                                         else {
1684                                                 SWAP(EditBone *, flipbone, ebone);
1685                                         }
1686                                 }
1687                                 
1688                                 totbone++;
1689                                 newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
1690                                 
1691                                 if(do_extrude==1) {
1692                                         VECCOPY (newbone->head, ebone->tail);
1693                                         VECCOPY (newbone->tail, newbone->head);
1694                                         newbone->parent = ebone;
1695                                         
1696                                         newbone->flag = ebone->flag & BONE_TIPSEL;      // copies it, in case mirrored bone
1697                                 }
1698                                 else {
1699                                         VECCOPY(newbone->head, ebone->head);
1700                                         VECCOPY(newbone->tail, ebone->head);
1701                                         newbone->parent= ebone->parent;
1702                                         
1703                                         newbone->flag= BONE_TIPSEL;
1704                                 }
1705
1706                                 newbone->weight= ebone->weight;
1707                                 newbone->dist= ebone->dist;
1708                                 newbone->xwidth= ebone->xwidth;
1709                                 newbone->zwidth= ebone->zwidth;
1710                                 newbone->ease1= ebone->ease1;
1711                                 newbone->ease2= ebone->ease2;
1712                                 newbone->rad_head= ebone->rad_tail;     // dont copy entire bone...
1713                                 newbone->rad_tail= ebone->rad_tail;
1714                                 newbone->segments= 1;
1715                                 newbone->boneclass= ebone->boneclass;
1716                                 
1717                                 /* See if there are any ik children of the parent */
1718                                 if(do_extrude==1) {
1719                                         for (partest = G.edbo.first; partest; partest=partest->next){
1720                                                 if ((partest->parent == ebone) && (partest->flag & BONE_IK_TOPARENT))
1721                                                         break;
1722                                         }
1723                                         
1724                                         if (!partest)
1725                                                 newbone->flag |= BONE_IK_TOPARENT;
1726                                 }
1727                                 
1728                                 strcpy (newbone->name, ebone->name);
1729                                 
1730                                 if(flipbone && forked) {        // only set if mirror edit
1731                                         if(strlen(newbone->name)<30) {
1732                                                 if(a==0) strcat(newbone->name, "_L");
1733                                                 else strcat(newbone->name, "_R");
1734                                         }
1735                                 }
1736                                 unique_editbone_name(newbone->name);
1737                                 
1738                                 /* Add the new bone to the list */
1739                                 BLI_addtail(&G.edbo, newbone);
1740                                 if (!first)
1741                                         first = newbone;
1742                                 
1743                                 /* restore ebone if we were flipping */
1744                                 if(a==1 && flipbone) 
1745                                         SWAP(EditBone *, flipbone, ebone);
1746
1747                         }
1748                 }
1749                 
1750                 /* Deselect the old bone */
1751                 ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1752                 
1753         }
1754         /* if only one bone, make this one active */
1755         if(totbone==1 && first) first->flag |= BONE_ACTIVE;
1756         
1757         /* Transform the endpoints */
1758         countall(); // flushes selection!
1759         BIF_TransformSetUndo("Extrude");
1760         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1761         Transform();
1762         
1763         allqueue(REDRAWBUTSEDIT, 0);
1764         allqueue(REDRAWBUTSOBJECT, 0);
1765         allqueue(REDRAWOOPS, 0);
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                         }
1856                 }
1857                 
1858                 allqueue(REDRAWVIEW3D, 0);
1859                 allqueue(REDRAWACTION, 0);
1860                 allqueue(REDRAWIPO, 0);         /* To force action ipo update */
1861                 allqueue(REDRAWBUTSEDIT, 0);
1862                 allqueue(REDRAWBUTSOBJECT, 0);
1863                 allqueue(REDRAWOOPS, 0);
1864         }
1865         
1866         return nearBone!=NULL;
1867         
1868 }
1869
1870 /*      mode==0: deselect
1871         mode==1: select
1872         mode==2: clear active tag 
1873 */
1874 static void deselect_bonechildren (Object *ob, Bone *bone, int mode)
1875 {
1876         Bone    *curBone;
1877
1878         if (!bone)
1879                 return;
1880
1881         if (mode==0)
1882                 bone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1883         else if (mode==1) {
1884                 if(!(bone->flag & BONE_HIDDEN_P))
1885                         bone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1886         }
1887         else bone->flag &= ~BONE_ACTIVE;
1888         
1889         if(mode!=2) select_actionchannel_by_name(ob->action, bone->name, mode);
1890
1891         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
1892                 deselect_bonechildren(ob, curBone, mode);
1893         }
1894 }
1895
1896 /* test==0: deselect all
1897    test==1: swap select
1898    test==2: only clear active tag 
1899 */
1900 void deselectall_posearmature (Object *ob, int test)
1901 {
1902         bArmature *arm;
1903         Bone *curBone;
1904         int     selectmode= 0;
1905         
1906         /* we call this from outliner too, but with OBACT set OK */
1907         if(!ob || !ob->pose) return;
1908         arm= get_armature(ob);
1909         
1910         /*      Determine if we're selecting or deselecting     */
1911         if (test==1) {
1912                 if (!count_bones (arm, BONE_SELECTED, 0))
1913                         selectmode= 1;
1914         }
1915         else if(test==2)
1916                 selectmode= 2;
1917         
1918         /*      Set the flags accordingly       */
1919         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next)
1920                 deselect_bonechildren (ob, curBone, selectmode);
1921         
1922         allqueue(REDRAWBUTSEDIT, 0);
1923         allqueue(REDRAWBUTSOBJECT, 0);
1924         allqueue(REDRAWVIEW3D, 0);
1925         allqueue(REDRAWOOPS, 0);
1926         allqueue(REDRAWACTION, 0);
1927
1928 }
1929
1930
1931 int bone_looper(Object *ob, Bone *bone, void *data,
1932                         int (*bone_func)(Object *, Bone *, void *)) 
1933 {
1934
1935     /* We want to apply the function bone_func to every bone 
1936      * in an armature -- feed bone_looper the first bone and 
1937      * a pointer to the bone_func and watch it go!. The int count 
1938      * can be useful for counting bones with a certain property
1939      * (e.g. skinnable)
1940      */
1941     int count = 0;
1942
1943     if (bone) {
1944
1945         /* only do bone_func if the bone is non null
1946          */
1947         count += bone_func(ob, bone, data);
1948
1949         /* try to execute bone_func for the first child
1950          */
1951         count += bone_looper(ob, bone->childbase.first, data,
1952                                     bone_func);
1953
1954         /* try to execute bone_func for the next bone at this
1955          * depth of the recursion.
1956          */
1957         count += bone_looper(ob, bone->next, data, bone_func);
1958     }
1959
1960     return count;
1961 }
1962
1963 int ik_chain_looper(Object *ob, Bone *bone, void *data,
1964                                    int (*bone_func)(Object *, Bone *, void *)) 
1965 {
1966
1967     /* We want to apply the function bone_func to every bone 
1968      * in an ik chain -- feed ikchain_looper a bone in the chain and 
1969      * a pointer to the bone_func and watch it go!. The int count 
1970      * can be useful for counting bones with a certain property
1971      * (e.g. skinnable)
1972      */
1973         Bone *curBone;
1974     int   count = 0;
1975
1976     if (bone) {
1977
1978         /* This bone */
1979         count += bone_func(ob, bone, data);
1980
1981         /* The parents */
1982                 for (curBone = bone; curBone; curBone=curBone->parent) {
1983                         if (!curBone->parent)
1984                                 break;
1985                         else if (!(curBone->flag & BONE_IK_TOPARENT))
1986                                 break;
1987                         count += bone_func(ob, curBone->parent, data);
1988                 }
1989
1990                 /* The children */
1991                 for (curBone = bone->childbase.first; curBone; curBone=curBone->next){
1992                         if (curBone->flag & BONE_IK_TOPARENT) {
1993                                 count += bone_func(ob, curBone, data);
1994                         }
1995                 }
1996     }
1997
1998     return count;
1999 }
2000
2001 static int bone_skinnable(Object *ob, Bone *bone, void *data)
2002 {
2003     /* Bones that are not of boneclass BONE_UNSKINNABLE
2004      * are regarded to be "skinnable" and are eligible for
2005      * auto-skinning.
2006      *
2007      * This function performs 2 functions:
2008      *
2009      *   a) It returns 1 if the bone is skinnable.
2010      *      If we loop over all bones with this 
2011      *      function, we can count the number of
2012      *      skinnable bones.
2013      *   b) If the pointer data is non null,
2014      *      it is treated like a handle to a
2015      *      bone pointer -- the bone pointer
2016      *      is set to point at this bone, and
2017      *      the pointer the handle points to
2018      *      is incremented to point to the
2019      *      next member of an array of pointers
2020      *      to bones. This way we can loop using
2021      *      this function to construct an array of
2022      *      pointers to bones that point to all
2023      *      skinnable bones.
2024      */
2025     Bone ***hbone;
2026
2027     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2028                 if (data != NULL) {
2029                         hbone = (Bone ***) data;
2030             **hbone = bone;
2031             ++*hbone;
2032         }
2033         return 1;
2034     }
2035     return 0;
2036 }
2037
2038 static int add_defgroup_unique_bone(Object *ob, Bone *bone, void *data) 
2039 {
2040     /* This group creates a vertex group to ob that has the
2041      * same name as bone (provided the bone is skinnable). 
2042          * If such a vertex group aleady exist the routine exits.
2043      */
2044         if ( bone_skinnable(ob, bone, NULL) ) {
2045                 if (!get_named_vertexgroup(ob,bone->name)) {
2046                         add_defgroup_name(ob, bone->name);
2047                         return 1;
2048                 }
2049     }
2050     return 0;
2051 }
2052
2053 static int dgroup_skinnable(Object *ob, Bone *bone, void *data) 
2054 {
2055     /* Bones that are not of boneclass BONE_UNSKINNABLE
2056      * are regarded to be "skinnable" and are eligible for
2057      * auto-skinning.
2058      *
2059      * This function performs 2 functions:
2060      *
2061      *   a) If the bone is skinnable, it creates 
2062      *      a vertex group for ob that has
2063      *      the name of the skinnable bone
2064      *      (if one doesn't exist already).
2065      *   b) If the pointer data is non null,
2066      *      it is treated like a handle to a
2067      *      bDeformGroup pointer -- the 
2068      *      bDeformGroup pointer is set to point
2069      *      to the deform group with the bone's
2070      *      name, and the pointer the handle 
2071      *      points to is incremented to point to the
2072      *      next member of an array of pointers
2073      *      to bDeformGroups. This way we can loop using
2074      *      this function to construct an array of
2075      *      pointers to bDeformGroups, all with names
2076      *      of skinnable bones.
2077      */
2078     bDeformGroup ***hgroup, *defgroup;
2079
2080     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2081         if ( !(defgroup = get_named_vertexgroup(ob, bone->name)) ) {
2082             defgroup = add_defgroup_name(ob, bone->name);
2083         }
2084
2085         if (data != NULL) {
2086             hgroup = (bDeformGroup ***) data;
2087             **hgroup = defgroup;
2088             ++*hgroup;
2089         }
2090         return 1;
2091     }
2092     return 0;
2093 }
2094
2095 static void add_verts_to_closest_dgroup(Object *ob, Object *par)
2096 {
2097     /* This function implements a crude form of 
2098      * auto-skinning: vertices are assigned to the
2099      * deformation groups associated with bones based
2100      * on thier proximity to a bone. Every vert is
2101      * given a weight of 1.0 to the weight group
2102      * cooresponding to the bone that it is
2103      * closest to. The vertex may also be assigned to
2104      * a deformation group associated to a bone
2105      * that is within 10% of the mninimum distance
2106      * between the bone and the nearest vert -- the
2107      * cooresponding weight will fall-off to zero
2108      * as the distance approaches the 10% tolerance mark.
2109          * If the mesh has subsurf enabled then the verts
2110          * on the subsurf limit surface is used to generate 
2111          * the weights rather than the verts on the cage
2112          * mesh.
2113          *
2114          * ("Limit surface" = same amount of vertices as mesh, but vertices 
2115      *   moved to the subsurfed position, like for 'optimal').
2116      */
2117
2118     bArmature *arm;
2119     Bone **bonelist, **bonehandle, *bone;
2120     bDeformGroup **dgrouplist, **dgrouphandle, *defgroup;
2121     float *distance;
2122     float   root[3];
2123     float   tip[3];
2124     float real_co[3];
2125         float *subverts = NULL;
2126     float *subvert;
2127     Mesh  *mesh;
2128     MVert *vert;
2129
2130     int numbones, i, j;
2131
2132     /* If the parent object is not an armature exit */
2133     arm = get_armature(par);
2134     if (!arm)
2135         return;
2136
2137     /* count the number of skinnable bones */
2138     numbones = bone_looper(ob, arm->bonebase.first, NULL,
2139                                   bone_skinnable);
2140
2141     /* create an array of pointer to bones that are skinnable
2142      * and fill it with all of the skinnable bones
2143      */
2144     bonelist = MEM_mallocN(numbones*sizeof(Bone *), "bonelist");
2145     bonehandle = bonelist;
2146     bone_looper(ob, arm->bonebase.first, &bonehandle,
2147                        bone_skinnable);
2148
2149     /* create an array of pointers to the deform groups that
2150      * coorespond to the skinnable bones (creating them
2151      * as necessary.
2152      */
2153     dgrouplist = MEM_mallocN(numbones*sizeof(bDeformGroup *), "dgrouplist");
2154     dgrouphandle = dgrouplist;
2155     bone_looper(ob, arm->bonebase.first, &dgrouphandle,
2156                        dgroup_skinnable);
2157
2158     /* create an array of floats that will be used for each vert
2159      * to hold the distance-factor to each bone.
2160      */
2161     distance = MEM_mallocN(numbones*sizeof(float), "distance");
2162
2163     mesh = (Mesh*)ob->data;
2164
2165         /* Is subsurf on? Lets use the verts on the limit surface then */
2166         if (modifiers_findByType(ob, eModifierType_Subsurf)) {
2167                 subverts = MEM_mallocN(3*mesh->totvert*sizeof(float), "subverts");
2168                 subsurf_calculate_limit_positions(mesh, (void *)subverts);      /* (ton) made void*, dunno how to cast */
2169         }
2170
2171     /* for each vertex in the mesh ...
2172      */
2173     for ( i=0 ; i < mesh->totvert ; ++i ) {
2174         /* get the vert in global coords
2175          */
2176                 
2177                 if (subverts) {
2178                         subvert = subverts + i*3;
2179                         VECCOPY (real_co, subvert);
2180                 }
2181                 else {
2182                         vert = mesh->mvert + i;
2183                         VECCOPY (real_co, vert->co);
2184                 }
2185         Mat4MulVecfl(ob->obmat, real_co);
2186
2187
2188         /* for each skinnable bone ...
2189          */
2190         for (j=0; j < numbones; ++j) {
2191             bone = bonelist[j];
2192
2193             /* get the root of the bone in global coords
2194              */
2195                         VECCOPY(root, bone->arm_head);
2196                         Mat4MulVecfl(par->obmat, root);
2197
2198             /* get the tip of the bone in global coords
2199              */
2200                         VECCOPY(tip, bone->arm_tail);
2201             Mat4MulVecfl(par->obmat, tip);
2202
2203             /* store the distance-factor from the vertex to
2204              * the bone
2205              */
2206                         distance[j]= distfactor_to_bone (real_co, root, tip, bone->rad_head, bone->rad_tail, bone->dist);
2207         }
2208
2209         /* for each deform group ...
2210          */
2211         for (j=0; j < numbones; ++j) {
2212             defgroup = dgrouplist[j];
2213
2214             /* add the vert to the deform group if weight!=0.0
2215              */
2216             if (distance[j]!=0.0)
2217                 add_vert_to_defgroup (ob, defgroup, i, distance[j], WEIGHT_REPLACE);
2218             else
2219                 remove_vert_defgroup (ob, defgroup, i);
2220         }
2221     }
2222
2223     /* free the memory allocated
2224      */
2225     MEM_freeN(bonelist);
2226     MEM_freeN(dgrouplist);
2227     MEM_freeN(distance);
2228         if (subverts) MEM_freeN(subverts);
2229 }
2230
2231 void create_vgroups_from_armature(Object *ob, Object *par)
2232 {
2233         /* Lets try to create some vertex groups 
2234          * based on the bones of the parent armature.
2235          */
2236
2237         bArmature *arm;
2238         short mode;
2239
2240         /* If the parent object is not an armature exit */
2241         arm = get_armature(par);
2242         if (!arm)
2243                 return;
2244
2245         /* Prompt the user on whether/how they want the vertex groups
2246          * added to the child mesh */
2247     mode= pupmenu("Create Vertex Groups? %t|"
2248                                   "Don't Create Groups %x1|"
2249                                   "Name Groups %x2|"
2250                   "Create From Closest Bones %x3");
2251         switch (mode){
2252         case 2:
2253                 /* Traverse the bone list, trying to create empty vertex 
2254                  * groups cooresponding to the bone.
2255                  */
2256                 bone_looper(ob, arm->bonebase.first, NULL,
2257                                         add_defgroup_unique_bone);
2258                 if (ob->type == OB_MESH)
2259                         create_dverts((Mesh*)ob->data);
2260
2261                 break;
2262
2263         case 3:
2264                 /* Traverse the bone list, trying to create vertex groups 
2265                  * that are populated with the vertices for which the
2266                  * bone is closest.
2267                  */
2268                 add_verts_to_closest_dgroup(ob, par);
2269                 break;
2270
2271         }
2272
2273
2274 static int hide_selected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2275 {
2276         if (bone->flag & BONE_SELECTED) {
2277                 bone->flag |= BONE_HIDDEN_P;
2278                 bone->flag &= ~BONE_SELECTED;
2279         }
2280         return 0;
2281 }
2282
2283 /* active object is armature */
2284 void hide_selected_pose_bones(void) 
2285 {
2286         bArmature               *arm;
2287
2288         arm= get_armature (OBACT);
2289
2290         if (!arm)
2291                 return;
2292
2293         bone_looper(OBACT, arm->bonebase.first, NULL, 
2294                                 hide_selected_pose_bone);
2295
2296         allqueue(REDRAWVIEW3D, 0);
2297         allqueue(REDRAWBUTSEDIT, 0);
2298 }
2299
2300 static int hide_unselected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2301 {
2302         if (~bone->flag & BONE_SELECTED) {
2303                 bone->flag |= BONE_HIDDEN_P;
2304         }
2305         return 0;
2306 }
2307
2308 /* active object is armature */
2309 void hide_unselected_pose_bones(void) 
2310 {
2311         bArmature               *arm;
2312
2313         arm=get_armature (OBACT);
2314
2315         if (!arm)
2316                 return;
2317
2318         bone_looper(OBACT, arm->bonebase.first, NULL, 
2319                                 hide_unselected_pose_bone);
2320
2321         allqueue(REDRAWVIEW3D, 0);
2322         allqueue(REDRAWBUTSEDIT, 0);
2323 }
2324
2325 static int show_pose_bone(Object *ob, Bone *bone, void *ptr) 
2326 {
2327         if (bone->flag & BONE_HIDDEN_P) {
2328                 bone->flag &= ~BONE_HIDDEN_P;
2329                 bone->flag |= BONE_SELECTED;
2330         }
2331
2332         return 0;
2333 }
2334
2335 /* active object is armature in posemode */
2336 void show_all_pose_bones(void) 
2337 {
2338         bArmature               *arm;
2339
2340         arm=get_armature (OBACT);
2341
2342         if (!arm)
2343                 return;
2344
2345         bone_looper(OBACT, arm->bonebase.first, NULL, 
2346                                 show_pose_bone);
2347
2348         allqueue(REDRAWVIEW3D, 0);
2349         allqueue(REDRAWBUTSEDIT, 0);
2350 }
2351
2352
2353 /* ************* RENAMING DISASTERS ************ */
2354
2355 /* note: there's a unique_editbone_name() too! */
2356 void unique_bone_name (bArmature *arm, char *name)
2357 {
2358         char            tempname[64];
2359         int                     number;
2360         char            *dot;
2361         
2362         if (get_named_bone(arm, name)) {
2363                 
2364                 /*      Strip off the suffix, if it's a number */
2365                 number= strlen(name);
2366                 if(number && isdigit(name[number-1])) {
2367                         dot= strrchr(name, '.');        // last occurrance
2368                         if (dot)
2369                                 *dot=0;
2370                 }
2371                 
2372                 for (number = 1; number <=999; number++){
2373                         sprintf (tempname, "%s.%03d", name, number);
2374                         if (!get_named_bone(arm, tempname)){
2375                                 strcpy (name, tempname);
2376                                 return;
2377                         }
2378                 }
2379         }
2380 }
2381
2382 #define MAXBONENAME 32
2383 /* helper call for below */
2384 static void constraint_bone_name_fix(Object *ob, ListBase *conlist, char *oldname, char *newname)
2385 {
2386         bConstraint *curcon;
2387         char *subtarget;
2388         
2389         for (curcon = conlist->first; curcon; curcon=curcon->next){
2390                 subtarget = get_con_subtarget_name(curcon, ob);
2391                 if (subtarget)
2392                         if (!strcmp(subtarget, oldname) )
2393                                 BLI_strncpy(subtarget, newname, MAXBONENAME);
2394         }
2395 }
2396
2397 /* called by UI for renaming a bone */
2398 /* warning: make sure the original bone was not renamed yet! */
2399 /* seems messy, but thats what you get with not using pointers but channel names :) */
2400 void armature_bone_rename(bArmature *arm, char *oldnamep, char *newnamep)
2401 {
2402         Object *ob;
2403         char newname[MAXBONENAME];
2404         char oldname[MAXBONENAME];
2405         
2406         /* names better differ! */
2407         if(strncmp(oldnamep, newnamep, MAXBONENAME)) {
2408                 
2409                 /* we alter newname string... so make copy */
2410                 BLI_strncpy(newname, newnamep, MAXBONENAME);
2411                 /* we use oldname for search... so make copy */
2412                 BLI_strncpy(oldname, oldnamep, MAXBONENAME);
2413                 
2414                 /* now check if we're in editmode, we need to find the unique name */
2415                 if(G.obedit && G.obedit->data==arm) {
2416                         EditBone        *eBone;
2417
2418                         eBone= editbone_name_exists(oldname);
2419                         if(eBone) {
2420                                 unique_editbone_name (newname);
2421                                 BLI_strncpy(eBone->name, newname, MAXBONENAME);
2422                         }
2423                         else return;
2424                 }
2425                 else {
2426                         Bone *bone= get_named_bone (arm, oldname);
2427
2428                         if(bone) {
2429                                 unique_bone_name (arm, newname);
2430                                 BLI_strncpy(bone->name, newname, MAXBONENAME);
2431                         }
2432                         else return;
2433                 }
2434                 
2435                 /* do entire dbase */
2436                 for(ob= G.main->object.first; ob; ob= ob->id.next) {
2437                         /* we have the object using the armature */
2438                         if(arm==ob->data) {
2439                                 Object *cob;
2440                                 bAction  *act;
2441                                 bActionChannel *chan;
2442
2443                                 /* Rename action channel if necessary */
2444                                 act = ob->action;
2445                                 if (act && !act->id.lib){
2446                                         /*      Find the appropriate channel */
2447                                         chan= get_named_actionchannel(act, oldname);
2448                                         if(chan) BLI_strncpy(chan->name, newname, MAXBONENAME);
2449                                 }
2450                 
2451                                 /* Rename the pose channel, if it exists */
2452                                 if (ob->pose) {
2453                                         bPoseChannel *pchan = get_pose_channel(ob->pose, oldname);
2454                                         if (pchan) {
2455                                                 BLI_strncpy (pchan->name, newname, MAXBONENAME);
2456                                         }
2457                                 }
2458                                 
2459                                 /* and actually do the NLA too */
2460                                 /* (todo) */
2461                                 
2462                                 /* Update any object constraints to use the new bone name */
2463                                 for(cob= G.main->object.first; cob; cob= cob->id.next) {
2464                                         if(cob->constraints.first)
2465                                                 constraint_bone_name_fix(ob, &cob->constraints, oldname, newname);
2466                                         if (cob->pose) {
2467                                                 bPoseChannel *pchan;
2468                                                 for (pchan = cob->pose->chanbase.first; pchan; pchan=pchan->next) {
2469                                                         constraint_bone_name_fix(ob, &pchan->constraints, oldname, newname);
2470                                                 }
2471                                         }
2472                                 }
2473                                 
2474                         }
2475                                         
2476                         /* See if an object is parented to this armature */
2477                         if (ob->parent && (ob->parent->data == arm)) {
2478                                 if(ob->partype==PARBONE) {
2479                                         /* bone name in object */
2480                                         if (!strcmp(ob->parsubstr, oldname))
2481                                                 BLI_strncpy(ob->parsubstr, newname, MAXBONENAME);
2482                                 }
2483                                 else if(ob->partype==PARSKEL) {
2484                                         bDeformGroup *dg;
2485                                         /* bone name in defgroup */
2486                                         for (dg=ob->defbase.first; dg; dg=dg->next) {
2487                                                 if(!strcmp(dg->name, oldname))
2488                                                    BLI_strncpy(dg->name, newname, MAXBONENAME);
2489                                         }
2490                                 }
2491                         }
2492                 }
2493         }
2494 }
2495
2496 /* context editmode object */
2497 void armature_flip_names(void)
2498 {
2499         EditBone *ebone;
2500         char newname[32];
2501         
2502         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2503                 if(ebone->flag & BONE_SELECTED) {
2504                         BLI_strncpy(newname, ebone->name, sizeof(newname));
2505                         bone_flip_name(newname, 1);             // 1 = do strip off number extensions
2506                         armature_bone_rename(G.obedit->data, ebone->name, newname);
2507                 }
2508         }
2509         
2510         allqueue(REDRAWVIEW3D, 0);
2511         allqueue(REDRAWBUTSEDIT, 0);
2512         allqueue(REDRAWBUTSOBJECT, 0);
2513         allqueue (REDRAWACTION, 0);
2514         allqueue(REDRAWOOPS, 0);
2515         BIF_undo_push("Flip names");
2516         
2517 }
2518
2519 /* context; editmode armature */
2520 EditBone *armature_bone_get_mirrored(EditBone *ebo)
2521 {
2522         EditBone *eboflip= NULL;
2523         char name[32];
2524         
2525         BLI_strncpy(name, ebo->name, sizeof(name));
2526         bone_flip_name(name, 0);                // 0 = don't strip off number extensions
2527
2528         for (eboflip=G.edbo.first; eboflip; eboflip=eboflip->next)
2529                 if(ebo!=eboflip)
2530                         if (!strcmp (name, eboflip->name)) break;
2531         
2532         return eboflip;
2533 }
2534