f87eb321fc8c5f09dd78afcfcc7346d0746e7154
[blender.git] / source / blender / src / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * editarmature.c: Interface for creating and posing armature objects
29  */
30
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <math.h> 
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include "MEM_guardedalloc.h"
41
42 #include "BMF_Api.h"
43
44 #include "DNA_action_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_ID.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_nla_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_screen_types.h"
54 #include "DNA_space_types.h"
55 #include "DNA_userdef_types.h"
56 #include "DNA_view3d_types.h"
57 #include "DNA_modifier_types.h"
58
59 #include "BLI_blenlib.h"
60 #include "BLI_arithb.h"
61 #include "BLI_editVert.h"
62 #include "BLI_ghash.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_DerivedMesh.h"
70 #include "BKE_global.h"
71 #include "BKE_main.h"
72 #include "BKE_object.h"
73 #include "BKE_subsurf.h"
74 #include "BKE_utildefines.h"
75 #include "BKE_modifier.h"
76
77 #include "BIF_editaction.h"
78 #include "BIF_editmode_undo.h"
79 #include "BIF_editdeform.h"
80 #include "BIF_editarmature.h"
81 #include "BIF_editconstraint.h"
82 #include "BIF_gl.h"
83 #include "BIF_graphics.h"
84 #include "BIF_interface.h"
85 #include "BIF_meshlaplacian.h"
86 #include "BIF_meshtools.h"
87 #include "BIF_poseobject.h"
88 #include "BIF_mywindow.h"
89 #include "BIF_resources.h"
90 #include "BIF_screen.h"
91 #include "BIF_space.h"
92 #include "BIF_toolbox.h"
93 #include "BIF_transform.h"
94
95 #include "BDR_editobject.h"
96 #include "BDR_drawobject.h"
97
98 #include "BSE_edit.h"
99 #include "BSE_view.h"
100 #include "BSE_trans_types.h"
101
102 #include "PIL_time.h"
103
104 #include "reeb.h" // FIX ME
105
106 #include "mydevice.h"
107 #include "blendef.h"
108 #include "nla.h"
109
110 extern  float center[3], centroid[3];   /* Originally defined in editobject.c */
111
112 /*      Macros  */
113 #define TEST_EDITARMATURE {if(G.obedit==0) return; if( (G.vd->lay & G.obedit->lay)==0 ) return;}
114
115 /* prototypes for later */
116 static EditBone *editbone_name_exists (ListBase *ebones, char *name);   // proto for below
117
118 /* **************** tools on Editmode Armature **************** */
119
120 /* converts Bones to EditBone list, used for tools as well */
121 void make_boneList(ListBase *list, ListBase *bones, EditBone *parent)
122 {
123         EditBone        *eBone;
124         Bone            *curBone;
125         float delta[3];
126         float premat[3][3];
127         float postmat[3][3];
128         float imat[3][3];
129         float difmat[3][3];
130                 
131         for (curBone=bones->first; curBone; curBone=curBone->next) {
132                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
133                 
134                 /*      Copy relevant data from bone to eBone */
135                 eBone->parent= parent;
136                 BLI_strncpy(eBone->name, curBone->name, 32);
137                 eBone->flag = curBone->flag;
138                 
139                 /* fix selection flags */
140                 if (eBone->flag & BONE_SELECTED) {
141                         eBone->flag |= BONE_TIPSEL;
142                         if (eBone->parent && (eBone->flag & BONE_CONNECTED))
143                                 eBone->parent->flag |= BONE_TIPSEL;
144                         else 
145                                 eBone->flag |= BONE_ROOTSEL;
146                 }
147                 else 
148                         eBone->flag &= ~BONE_ROOTSEL;
149                 
150                 VECCOPY(eBone->head, curBone->arm_head);
151                 VECCOPY(eBone->tail, curBone->arm_tail);                
152                 
153                 eBone->roll= 0.0;
154                 
155                 /* roll fixing */
156                 VecSubf(delta, eBone->tail, eBone->head);
157                 vec_roll_to_mat3(delta, 0.0, postmat);
158                 
159                 Mat3CpyMat4(premat, curBone->arm_mat);
160                 
161                 Mat3Inv(imat, postmat);
162                 Mat3MulMat3(difmat, imat, premat);
163                 
164                 eBone->roll = atan2(difmat[2][0], difmat[2][2]);
165                 
166                 /* rest of stuff copy */
167                 eBone->length= curBone->length;
168                 eBone->dist= curBone->dist;
169                 eBone->weight= curBone->weight;
170                 eBone->xwidth= curBone->xwidth;
171                 eBone->zwidth= curBone->zwidth;
172                 eBone->ease1= curBone->ease1;
173                 eBone->ease2= curBone->ease2;
174                 eBone->rad_head= curBone->rad_head;
175                 eBone->rad_tail= curBone->rad_tail;
176                 eBone->segments = curBone->segments;            
177                 eBone->layer = curBone->layer;
178                 
179                 BLI_addtail(list, eBone);
180                 
181                 /*      Add children if necessary */
182                 if (curBone->childbase.first) 
183                         make_boneList(list, &curBone->childbase, eBone);
184         }
185 }
186
187 /* nasty stuff for converting roll in editbones into bones */
188 /* also sets restposition in armature (arm_mat) */
189 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
190 {
191         Bone *curBone;
192         EditBone *ebone;
193         float premat[3][3];
194         float postmat[3][3];
195         float difmat[3][3];
196         float imat[3][3];
197         float delta[3];
198         
199         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
200                 /* sets local matrix and arm_mat (restpos) */
201                 where_is_armature_bone(curBone, curBone->parent);
202                 
203                 /* Find the associated editbone */
204                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
205                         if ((Bone*)ebone->temp == curBone)
206                                 break;
207                 
208                 if (ebone) {
209                         /* Get the ebone premat */
210                         VecSubf(delta, ebone->tail, ebone->head);
211                         vec_roll_to_mat3(delta, ebone->roll, premat);
212                         
213                         /* Get the bone postmat */
214                         Mat3CpyMat4(postmat, curBone->arm_mat);
215                         
216                         Mat3Inv(imat, premat);
217                         Mat3MulMat3(difmat, imat, postmat);
218 #if 0
219                         printf ("Bone %s\n", curBone->name);
220                         printmatrix4("premat", premat);
221                         printmatrix4("postmat", postmat);
222                         printmatrix4("difmat", difmat);
223                         printf ("Roll = %f\n",  (-atan2(difmat[2][0], difmat[2][2]) * (180.0/M_PI)));
224 #endif
225                         curBone->roll = -atan2(difmat[2][0], difmat[2][2]);
226                         
227                         /* and set restposition again */
228                         where_is_armature_bone(curBone, curBone->parent);
229                 }
230                 fix_bonelist_roll(&curBone->childbase, editbonelist);
231         }
232 }
233
234 /* converts the editbones back to the armature */
235 void editbones_to_armature (ListBase *list, Object *ob)
236 {
237         bArmature *arm;
238         EditBone *eBone, *neBone;
239         Bone    *newBone;
240         Object *obt;
241         
242         arm = get_armature(ob);
243         if (!list) return;
244         if (!arm) return;
245         
246         /* armature bones */
247         free_bones(arm);
248         
249         /* remove zero sized bones, this gives instable restposes */
250         for (eBone=list->first; eBone; eBone= neBone) {
251                 float len= VecLenf(eBone->head, eBone->tail);
252                 neBone= eBone->next;
253                 if (len <= FLT_EPSILON) {
254                         EditBone *fBone;
255                         
256                         /*      Find any bones that refer to this bone  */
257                         for (fBone=list->first; fBone; fBone= fBone->next) {
258                                 if (fBone->parent==eBone)
259                                         fBone->parent= eBone->parent;
260                         }
261                         printf("Warning: removed zero sized bone: %s\n", eBone->name);
262                         BLI_freelinkN(list, eBone);
263                 }
264         }
265         
266         /*      Copy the bones from the editData into the armature */
267         for (eBone=list->first; eBone; eBone=eBone->next) {
268                 newBone= MEM_callocN(sizeof(Bone), "bone");
269                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
270                 
271                 BLI_strncpy(newBone->name, eBone->name, 32);
272                 memcpy(newBone->head, eBone->head, sizeof(float)*3);
273                 memcpy(newBone->tail, eBone->tail, sizeof(float)*3);
274                 newBone->flag= eBone->flag;
275                 if (eBone->flag & BONE_ACTIVE) 
276                         newBone->flag |= BONE_SELECTED; /* important, editbones can be active with only 1 point selected */
277                 newBone->roll = 0.0f;
278                 
279                 newBone->weight = eBone->weight;
280                 newBone->dist = eBone->dist;
281                 
282                 newBone->xwidth = eBone->xwidth;
283                 newBone->zwidth = eBone->zwidth;
284                 newBone->ease1= eBone->ease1;
285                 newBone->ease2= eBone->ease2;
286                 newBone->rad_head= eBone->rad_head;
287                 newBone->rad_tail= eBone->rad_tail;
288                 newBone->segments= eBone->segments;
289                 newBone->layer = eBone->layer;
290         }
291         
292         /*      Fix parenting in a separate pass to ensure ebone->bone connections
293                 are valid at this point */
294         for (eBone=list->first;eBone;eBone=eBone->next) {
295                 newBone= (Bone *)eBone->temp;
296                 if (eBone->parent) {
297                         newBone->parent= (Bone *)eBone->parent->temp;
298                         BLI_addtail(&newBone->parent->childbase, newBone);
299                         
300                         {
301                                 float M_boneRest[3][3];
302                                 float M_parentRest[3][3];
303                                 float iM_parentRest[3][3];
304                                 float   delta[3];
305                                 
306                                 /* Get the parent's  matrix (rotation only) */
307                                 VecSubf(delta, eBone->parent->tail, eBone->parent->head);
308                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
309                                 
310                                 /* Get this bone's  matrix (rotation only) */
311                                 VecSubf(delta, eBone->tail, eBone->head);
312                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
313                                 
314                                 /* Invert the parent matrix */
315                                 Mat3Inv(iM_parentRest, M_parentRest);
316                                 
317                                 /* Get the new head and tail */
318                                 VecSubf(newBone->head, eBone->head, eBone->parent->tail);
319                                 VecSubf(newBone->tail, eBone->tail, eBone->parent->tail);
320                                 
321                                 Mat3MulVecfl(iM_parentRest, newBone->head);
322                                 Mat3MulVecfl(iM_parentRest, newBone->tail);
323                         }
324                 }
325                 /*      ...otherwise add this bone to the armature's bonebase */
326                 else
327                         BLI_addtail(&arm->bonebase, newBone);
328         }
329         
330         /* Make a pass through the new armature to fix rolling */
331         /* also builds restposition again (like where_is_armature) */
332         fix_bonelist_roll(&arm->bonebase, list);
333         
334         /* so all users of this armature should get rebuilt */
335         for (obt= G.main->object.first; obt; obt= obt->id.next) {
336                 if (obt->data==arm)
337                         armature_rebuild_pose(obt, arm);
338         }
339         
340         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
341 }
342
343
344
345 void apply_rot_armature (Object *ob, float mat[3][3])
346 {
347         ListBase        list;
348         EditBone *ebone;
349         bArmature *arm;
350         float scale = Mat3ToScalef(mat);        /* store the scale of the matrix here to use on envelopes */
351         arm = get_armature(ob);
352
353         if (!arm)
354                 return; 
355         
356         /* Put the armature into editmode */
357         list.first= list.last = NULL;
358         make_boneList(&list, &arm->bonebase, NULL);
359
360         /* Do the rotations */
361         for (ebone = list.first; ebone; ebone=ebone->next){
362                 Mat3MulVecfl(mat, ebone->head);
363                 Mat3MulVecfl(mat, ebone->tail);
364                 
365                 ebone->rad_head *= scale;
366                 ebone->rad_tail *= scale;
367                 ebone->dist             *= scale;
368         }
369         
370         /* Turn the list into an armature */
371         editbones_to_armature(&list, ob);
372         
373         /* Free the editbones */
374         if (list.first){
375                 BLI_freelistN (&list);
376         }
377 }
378
379 /* 0 == do center, 1 == center new, 2 == center cursor */
380 void docenter_armature (Object *ob, int centermode)
381 {
382         ListBase        list;
383         EditBone *ebone;
384         bArmature *arm;
385         float cent[3] = {0.0f, 0.0f, 0.0f};
386         float min[3], max[3];
387         float omat[3][3];
388                 
389         arm = get_armature(ob);
390         if (!arm) return;
391
392         /* Put the armature into editmode */
393         list.first= list.last = NULL;
394         make_boneList(&list, &arm->bonebase, NULL);
395
396         /* Find the centerpoint */
397         if (centermode == 2) {
398                 VECCOPY(cent, give_cursor());
399                 Mat4Invert(ob->imat, ob->obmat);
400                 Mat4MulVecfl(ob->imat, cent);
401         }
402         else {
403                 INIT_MINMAX(min, max);
404                 
405                 for (ebone= list.first; ebone; ebone=ebone->next) {
406                         DO_MINMAX(ebone->head, min, max);
407                         DO_MINMAX(ebone->tail, min, max);
408                 }
409                 
410                 cent[0]= (min[0]+max[0])/2.0f;
411                 cent[1]= (min[1]+max[1])/2.0f;
412                 cent[2]= (min[2]+max[2])/2.0f;
413         }
414         
415         /* Do the adjustments */
416         for (ebone= list.first; ebone; ebone=ebone->next){
417                 VecSubf(ebone->head, ebone->head, cent);
418                 VecSubf(ebone->tail, ebone->tail, cent);
419         }
420         
421         /* Turn the list into an armature */
422         editbones_to_armature(&list, ob);
423         
424         /* Free the editbones */
425         if (list.first){
426                 BLI_freelistN(&list);
427         }
428         
429         /* Adjust object location for new centerpoint */
430         if(centermode && G.obedit==0) {
431                 Mat3CpyMat4(omat, ob->obmat);
432                 
433                 Mat3MulVecfl(omat, cent);
434                 ob->loc[0]+= cent[0];
435                 ob->loc[1]+= cent[1];
436                 ob->loc[2]+= cent[2];
437         }
438 }
439
440 /* Helper function for armature joining - link fixing */
441 static void joined_armature_fix_links(Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
442 {
443         Object *ob;
444         bPose *pose;
445         bPoseChannel *pchant;
446         bConstraint *con;
447         
448         /* let's go through all objects in database */
449         for (ob= G.main->object.first; ob; ob= ob->id.next) {
450                 /* do some object-type specific things */
451                 if (ob->type == OB_ARMATURE) {
452                         pose= ob->pose;
453                         for (pchant= pose->chanbase.first; pchant; pchant= pchant->next) {
454                                 for (con= pchant->constraints.first; con; con= con->next) {
455                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
456                                         ListBase targets = {NULL, NULL};
457                                         bConstraintTarget *ct;
458                                         
459                                         /* constraint targets */
460                                         if (cti && cti->get_constraint_targets) {
461                                                 cti->get_constraint_targets(con, &targets);
462                                                 
463                                                 for (ct= targets.first; ct; ct= ct->next) {
464                                                         if (ct->tar == srcArm) {
465                                                                 if (strcmp(ct->subtarget, "")==0) {
466                                                                         ct->tar = tarArm;
467                                                                 }
468                                                                 else if (strcmp(ct->subtarget, pchan->name)==0) {
469                                                                         ct->tar = tarArm;
470                                                                         strcpy(ct->subtarget, curbone->name);
471                                                                 }
472                                                         }
473                                                 }
474                                                 
475                                                 if (cti->flush_constraint_targets)
476                                                         cti->flush_constraint_targets(con, &targets, 0);
477                                         }
478                                         
479                                         /* action constraint? */
480                                         if (con->type == CONSTRAINT_TYPE_ACTION) {
481                                                 bActionConstraint *data= con->data;
482                                                 bAction *act;
483                                                 bActionChannel *achan;
484                                                 
485                                                 if (data->act) {
486                                                         act= data->act;
487                                                         
488                                                         for (achan= act->chanbase.first; achan; achan= achan->next) {
489                                                                 if (strcmp(achan->name, pchan->name)==0)
490                                                                         BLI_strncpy(achan->name, curbone->name, 32);
491                                                         }
492                                                 }
493                                         }
494                                         
495                                 }
496                         }
497                 }
498                         
499                 /* fix object-level constraints */
500                 if (ob != srcArm) {
501                         for (con= ob->constraints.first; con; con= con->next) {
502                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
503                                 ListBase targets = {NULL, NULL};
504                                 bConstraintTarget *ct;
505                                 
506                                 /* constraint targets */
507                                 if (cti && cti->get_constraint_targets) {
508                                         cti->get_constraint_targets(con, &targets);
509                                         
510                                         for (ct= targets.first; ct; ct= ct->next) {
511                                                 if (ct->tar == srcArm) {
512                                                         if (strcmp(ct->subtarget, "")==0) {
513                                                                 ct->tar = tarArm;
514                                                         }
515                                                         else if (strcmp(ct->subtarget, pchan->name)==0) {
516                                                                 ct->tar = tarArm;
517                                                                 strcpy(ct->subtarget, curbone->name);
518                                                         }
519                                                 }
520                                         }
521                                         
522                                         if (cti->flush_constraint_targets)
523                                                 cti->flush_constraint_targets(con, &targets, 0);
524                                 }
525                         }
526                 }
527                 
528                 /* See if an object is parented to this armature */
529                 if (ob->parent && (ob->parent == srcArm)) {
530                         /* Is object parented to a bone of this src armature? */
531                         if (ob->partype==PARBONE) {
532                                 /* bone name in object */
533                                 if (!strcmp(ob->parsubstr, pchan->name))
534                                         BLI_strncpy(ob->parsubstr, curbone->name, 32);
535                         }
536                         
537                         /* make tar armature be new parent */
538                         ob->parent = tarArm;
539                 }
540         }       
541 }
542
543 int join_armature(void)
544 {
545         Object  *ob;
546         bArmature *arm;
547         Base    *base, *nextbase;
548         bPose *pose, *opose;
549         bPoseChannel *pchan, *pchann;
550         ListBase ebbase, eblist;
551         EditBone *curbone;
552         float   mat[4][4], oimat[4][4];
553         
554         /*      Ensure we're not in editmode and that the active object is an armature*/
555         /* if(G.obedit) return; */ /* Alredy checked in join_menu() */
556         
557         ob= OBACT;
558         if (ob->type!=OB_ARMATURE) return 0;
559         if (object_data_is_libdata(ob)) {
560                 error_libdata();
561                 return 0;
562         }
563         arm= get_armature(ob); 
564         
565         /* Get editbones of active armature to add editbones to */
566         ebbase.first=ebbase.last= NULL;
567         make_boneList(&ebbase, &arm->bonebase, NULL);
568         
569         /* get pose of active object and move it out of posemode */
570         pose= ob->pose;
571         ob->flag &= ~OB_POSEMODE;
572         BASACT->flag &= ~OB_POSEMODE;
573         
574         for (base=FIRSTBASE; base; base=nextbase) {
575                 nextbase = base->next;
576                 if (TESTBASE(base)){
577                         if ((base->object->type==OB_ARMATURE) && (base->object!=ob)) {
578                                 /* Make a list of editbones in current armature */
579                                 eblist.first=eblist.last= NULL;
580                                 make_boneList(&eblist, &((bArmature *)base->object->data)->bonebase, NULL);
581                                 
582                                 /* Get Pose of current armature */
583                                 opose= base->object->pose;
584                                 base->object->flag &= ~OB_POSEMODE;
585                                 BASACT->flag &= ~OB_POSEMODE;
586                                 
587                                 /* Find the difference matrix */
588                                 Mat4Invert(oimat, ob->obmat);
589                                 Mat4MulMat4(mat, base->object->obmat, oimat);
590                                 
591                                 /* Copy bones and posechannels from the object to the edit armature */
592                                 for (pchan=opose->chanbase.first; pchan; pchan=pchann) {
593                                         pchann= pchan->next;
594                                         curbone= editbone_name_exists(&eblist, pchan->name);
595                                         
596                                         /* Get new name */
597                                         unique_editbone_name(&ebbase, curbone->name);
598                                         
599                                         /* Transform the bone */
600                                         {
601                                                 float premat[4][4];
602                                                 float postmat[4][4];
603                                                 float difmat[4][4];
604                                                 float imat[4][4];
605                                                 float temp[3][3];
606                                                 float delta[3];
607                                                 
608                                                 /* Get the premat */
609                                                 VecSubf(delta, curbone->tail, curbone->head);
610                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
611                                                 
612                                                 Mat4MulMat34(premat, temp, mat);
613                                                 
614                                                 Mat4MulVecfl(mat, curbone->head);
615                                                 Mat4MulVecfl(mat, curbone->tail);
616                                                 
617                                                 /* Get the postmat */
618                                                 VecSubf(delta, curbone->tail, curbone->head);
619                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
620                                                 Mat4CpyMat3(postmat, temp);
621                                                 
622                                                 /* Find the roll */
623                                                 Mat4Invert(imat, premat);
624                                                 Mat4MulMat4(difmat, postmat, imat);
625                                                 
626                                                 curbone->roll -= atan2(difmat[2][0], difmat[2][2]);
627                                         }
628                                         
629                                         /* Fix Constraints and Other Links to this Bone and Armature */
630                                         joined_armature_fix_links(ob, base->object, pchan, curbone);
631                                         
632                                         /* Rename pchan */
633                                         sprintf(pchan->name, curbone->name);
634                                         
635                                         /* Jump Ship! */
636                                         BLI_remlink(&eblist, curbone);
637                                         BLI_addtail(&ebbase, curbone);
638                                         
639                                         BLI_remlink(&opose->chanbase, pchan);
640                                         BLI_addtail(&pose->chanbase, pchan);
641                                 }
642                                 
643                                 free_and_unlink_base(base);
644                         }
645                 }
646         }
647         
648         DAG_scene_sort(G.scene);        // because we removed object(s)
649         
650         editbones_to_armature(&ebbase, ob);
651         if (ebbase.first) BLI_freelistN(&ebbase);
652         
653         allqueue(REDRAWVIEW3D, 0);
654         allqueue(REDRAWOOPS, 0);
655         return 1;
656 }
657
658 /* Helper function for armature separating - link fixing */
659 static void separated_armature_fix_links(Object *origArm, Object *newArm)
660 {
661         Object *ob;
662         bPoseChannel *pchan, *pcha, *pchb;
663         bConstraint *con;
664         ListBase *npchans;
665         
666         /* get reference to list of bones in new armature  */
667         npchans= &newArm->pose->chanbase;
668         
669         /* let's go through all objects in database */
670         for (ob= G.main->object.first; ob; ob= ob->id.next) {
671                 /* do some object-type specific things */
672                 if (ob->type == OB_ARMATURE) {
673                         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
674                                 for (con= pchan->constraints.first; con; con= con->next) {
675                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
676                                         ListBase targets = {NULL, NULL};
677                                         bConstraintTarget *ct;
678                                         
679                                         /* constraint targets */
680                                         if (cti && cti->get_constraint_targets) {
681                                                 cti->get_constraint_targets(con, &targets);
682                                                 
683                                                 for (ct= targets.first; ct; ct= ct->next) {
684                                                         /* any targets which point to original armature are redirected to the new one only if:
685                                                          *      - the target isn't the original armature itself
686                                                          *      - the target is one that can be found in newArm
687                                                          */
688                                                         if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
689                                                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
690                                                                         /* check if either one matches */
691                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
692                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
693                                                                         {
694                                                                                 ct->tar= newArm;
695                                                                                 break;
696                                                                         }
697                                                                         
698                                                                         /* check if both ends have met (to stop checking) */
699                                                                         if (pcha == pchb) break;
700                                                                 }                                                               
701                                                         }
702                                                 }
703                                                 
704                                                 if (cti->flush_constraint_targets)
705                                                         cti->flush_constraint_targets(con, &targets, 0);
706                                         }
707                                 }
708                         }
709                 }
710                         
711                 /* fix object-level constraints */
712                 if (ob != origArm) {
713                         for (con= ob->constraints.first; con; con= con->next) {
714                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
715                                 ListBase targets = {NULL, NULL};
716                                 bConstraintTarget *ct;
717                                 
718                                 /* constraint targets */
719                                 if (cti && cti->get_constraint_targets) {
720                                         cti->get_constraint_targets(con, &targets);
721                                         
722                                         for (ct= targets.first; ct; ct= ct->next) {
723                                                 /* any targets which point to original armature are redirected to the new one only if:
724                                                  *      - the target isn't the original armature itself
725                                                  *      - the target is one of the bones which were moved into newArm
726                                                  */
727                                                 if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
728                                                         for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
729                                                                 /* check if either one matches */
730                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
731                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
732                                                                 {
733                                                                         ct->tar= newArm;
734                                                                         break;
735                                                                 }
736                                                                 
737                                                                 /* check if both ends have met (to stop checking) */
738                                                                 if (pcha == pchb) break;
739                                                         }
740                                                 }
741                                         }
742                                         
743                                         if (cti->flush_constraint_targets)
744                                                 cti->flush_constraint_targets(con, &targets, 0);
745                                 }
746                         }
747                 }
748                 
749                 /* See if an object is parented to this armature */
750                 if ((ob->parent) && (ob->parent == origArm)) {
751                         /* Is object parented to a bone of this src armature? */
752                         if (ob->partype==PARBONE) {
753                                 /* bone name in object */
754                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
755                                         /* check if either one matches */
756                                         if ( (strcmp(pcha->name, ob->parsubstr)==0) ||
757                                                  (strcmp(pchb->name, ob->parsubstr)==0) )
758                                         {
759                                                 ob->parent= newArm;
760                                                 break;
761                                         }
762                                         
763                                         /* check if both ends have met (to stop checking) */
764                                         if (pcha == pchb) break;
765                                 }
766                         }
767                 }
768         }       
769 }
770
771 /* Helper function for armature separating - remove certain bones from the given armature 
772  *      sel: remove selected bones from the armature, otherwise the unselected bones are removed
773  */
774 static void separate_armature_bones (Object *ob, short sel) 
775 {
776         ListBase edbo = {NULL, NULL};
777         bArmature *arm= (bArmature *)ob->data;
778         bPoseChannel *pchan, *pchann;
779         EditBone *curbone;
780         
781         /* make local set of editbones to manipulate here */
782         make_boneList(&edbo, &arm->bonebase, NULL);
783         
784         /* go through pose-channels, checking if a bone should be removed */
785         for (pchan=ob->pose->chanbase.first; pchan; pchan=pchann) {
786                 pchann= pchan->next;
787                 curbone= editbone_name_exists(&edbo, pchan->name);
788                 
789                 /* check if bone needs to be removed */
790                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
791                          (!sel && !(curbone->flag & BONE_SELECTED)) )
792                 {
793                         EditBone *ebo;
794                         bPoseChannel *pchn;
795                         
796                         /* clear the bone->parent var of any bone that had this as its parent  */
797                         for (ebo= edbo.first; ebo; ebo= ebo->next) {
798                                 if (ebo->parent == curbone) {
799                                         ebo->parent= NULL;
800                                         ebo->temp= NULL; /* this is needed to prevent random crashes with in editbones_to_armature */
801                                         ebo->flag &= ~BONE_CONNECTED;
802                                 }
803                         }
804                         
805                         /* clear the pchan->parent var of any pchan that had this as its parent */
806                         for (pchn= ob->pose->chanbase.first; pchn; pchn=pchn->next) {
807                                 if (pchn->parent == pchan)
808                                         pchn->parent= NULL;
809                         }
810                         
811                         /* free any of the extra-data this pchan might have */
812                         if (pchan->path) MEM_freeN(pchan->path);
813                         free_constraints(&pchan->constraints);
814                         
815                         /* get rid of unneeded bone */
816                         BLI_freelinkN(&edbo, curbone);
817                         BLI_freelinkN(&ob->pose->chanbase, pchan);
818                 }
819         }
820         
821         /* exit editmode (recalculates pchans too) */
822         editbones_to_armature(&edbo, ob);
823         BLI_freelistN(&edbo);
824 }
825
826 void separate_armature (void)
827 {
828         Object *oldob, *newob;
829         Base *base, *oldbase, *newbase;
830         bArmature *arm;
831         
832         // 31 Mar 08 \ 11 May 08 - Aligorith:
833         // currently, this is still too unstable to be enabled for general consumption.
834         // remove the following two lines to test this tool... you have been warned!
835         //      okee("Not implemented (WIP)");
836         //      return;
837         
838         if ( G.vd==0 || (G.vd->lay & G.obedit->lay)==0 ) return;
839         if ( okee("Separate")==0 ) return;
840
841         waitcursor(1);
842         
843         arm= G.obedit->data;
844         
845         /* we are going to do this as follows (unlike every other instance of separate):
846          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
847          *      2. duplicate base - BASACT is the new one now
848          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
849          *      4. fix constraint links
850          *      5. make original armature active and enter editmode
851          */
852         
853         /* 1) only edit-base selected */
854         base= FIRSTBASE;
855         for (base= FIRSTBASE; base; base= base->next) {
856                 if (base->lay & G.vd->lay) {
857                         if (base->object==G.obedit) base->flag |= 1;
858                         else base->flag &= ~1;
859                 }
860         }
861         
862         /* 1) store starting settings and exit editmode */
863         oldob= G.obedit;
864         oldbase= BASACT;
865         oldob->flag &= ~OB_POSEMODE;
866         oldbase->flag &= ~OB_POSEMODE;
867         
868         load_editArmature();
869         free_editArmature();
870         
871         /* 2) duplicate base */
872         adduplicate(1, USER_DUP_ARM); /* no transform and zero so do get a linked dupli */
873         
874         newbase= BASACT; /* basact is set in adduplicate() */
875         newob= newbase->object;         
876         newbase->flag &= ~SELECT;
877         
878         
879         /* 3) remove bones that shouldn't still be around on both armatures */
880         separate_armature_bones(oldob, 1);
881         separate_armature_bones(newob, 0);
882         
883         
884         /* 4) fix links before depsgraph flushes */ // err... or after?
885         separated_armature_fix_links(oldob, newob);
886         
887         DAG_object_flush_update(G.scene, oldob, OB_RECALC_DATA);        /* this is the original one */
888         DAG_object_flush_update(G.scene, newob, OB_RECALC_DATA);        /* this is the separated one */
889         
890         
891         /* 5) restore original conditions */
892         G.obedit= oldob;
893         BASACT= oldbase;
894         BASACT->flag |= SELECT;
895         
896         make_editArmature();
897         
898         /* recalc/redraw + cleanup */
899         waitcursor(0);
900
901         countall();
902         allqueue(REDRAWVIEW3D, 0);
903         allqueue(REDRAWBUTSEDIT, 0);
904         allqueue(REDRAWOOPS, 0);
905         
906         BIF_undo_push("Separate Armature");
907 }
908
909 /* **************** END tools on Editmode Armature **************** */
910 /* **************** PoseMode & EditMode *************************** */
911
912 /* only for opengl selection indices */
913 Bone *get_indexed_bone (Object *ob, int index)
914 {
915         bPoseChannel *pchan;
916         int a= 0;
917         
918         if(ob->pose==NULL) return NULL;
919         index>>=16;             // bone selection codes use left 2 bytes
920         
921         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
922                 if(a==index) return pchan->bone;
923         }
924         return NULL;
925 }
926
927 /* See if there are any selected bones in this buffer */
928 static void *get_bone_from_selectbuffer(Base *base, unsigned int *buffer, short hits, short findunsel)
929 {
930         Object *ob= base->object;
931         Bone *bone;
932         EditBone *ebone;
933         void *firstunSel=NULL, *firstSel=NULL, *data;
934         unsigned int hitresult;
935         short i, takeNext=0, sel;
936         
937         for (i=0; i< hits; i++){
938                 hitresult = buffer[3+(i*4)];
939                 
940                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
941                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
942                                 
943                                 hitresult &= ~(BONESEL_ANY);
944                                 /* Determine what the current bone is */
945                                 if (G.obedit==NULL || base->object!=G.obedit) {
946                                         /* no singular posemode, so check for correct object */
947                                         if(base->selcol == (hitresult & 0xFFFF)) {
948                                                 bone = get_indexed_bone(ob, hitresult);
949
950                                                 if (findunsel)
951                                                         sel = (bone->flag & BONE_SELECTED);
952                                                 else
953                                                         sel = !(bone->flag & BONE_SELECTED);
954                                                 
955                                                 data = bone;
956                                         }
957                                         else {
958                                                 data= NULL;
959                                                 sel= 0;
960                                         }
961                                 }
962                                 else{
963                                         ebone = BLI_findlink(&G.edbo, hitresult);
964                                         if (findunsel)
965                                                 sel = (ebone->flag & BONE_SELECTED);
966                                         else
967                                                 sel = !(ebone->flag & BONE_SELECTED);
968                                         
969                                         data = ebone;
970                                 }
971                                 
972                                 if(data) {
973                                         if (sel) {
974                                                 if(!firstSel) firstSel= data;
975                                                 takeNext=1;
976                                         }
977                                         else {
978                                                 if (!firstunSel)
979                                                         firstunSel=data;
980                                                 if (takeNext)
981                                                         return data;
982                                         }
983                                 }
984                         }
985                 }
986         }
987         
988         if (firstunSel)
989                 return firstunSel;
990         else 
991                 return firstSel;
992 }
993
994 /* used by posemode as well editmode */
995 static void *get_nearest_bone (short findunsel)
996 {
997         unsigned int buffer[MAXPICKBUF];
998         short hits;
999         
1000         persp(PERSP_VIEW);
1001         
1002         glInitNames();
1003         hits= view3d_opengl_select(buffer, MAXPICKBUF, 0, 0, 0, 0);
1004
1005         if (hits>0)
1006                 return get_bone_from_selectbuffer(BASACT, buffer, hits, findunsel);
1007         
1008         return NULL;
1009 }
1010
1011 /* used by posemode and editmode */
1012 void select_bone_parent (void)
1013 {
1014         Object *ob;
1015         bArmature *arm; 
1016         
1017         /* get data */
1018         if (G.obedit)
1019                 ob= G.obedit;
1020         else if (OBACT)
1021                 ob= OBACT;
1022         else
1023                 return;
1024         arm= (bArmature *)ob->data;
1025         
1026         /* determine which mode armature is in */
1027         if ((!G.obedit) && (ob->flag & OB_POSEMODE)) {
1028                 /* deal with pose channels */
1029                 /* channels are sorted on dependency, so the loop below won't result in a flood-select */
1030                 bPoseChannel *pchan=NULL;
1031                 
1032                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1033                         /* check if bone in original selection */
1034                         if (pchan->bone->flag & BONE_SELECTED) {
1035                                 bPoseChannel *chanpar= pchan->parent;
1036                                 
1037                                 /* check if any parent */
1038                                 if ((chanpar) && ((chanpar->bone->flag & BONE_SELECTED)==0)) {
1039                                         chanpar->bone->flag |= BONE_SELECTED;
1040                                         select_actionchannel_by_name (ob->action, pchan->name, 1);
1041                                 }
1042                         }
1043                 }
1044         }
1045         else if (G.obedit) {
1046                 /* deal with editbones */
1047                 EditBone *curbone, *parbone, *parpar;
1048                 
1049                 /* prevent floods */
1050                 for (curbone= G.edbo.first; curbone; curbone= curbone->next)
1051                         curbone->temp= NULL;
1052                 
1053                 for (curbone= G.edbo.first; curbone; curbone= curbone->next) {
1054                         /* check if bone selected */
1055                         if ((curbone->flag & BONE_SELECTED) && curbone->temp==NULL) {
1056                                 parbone= curbone->parent;
1057                                 
1058                                 /* check if any parent */
1059                                 if ((parbone) && ((parbone->flag & BONE_SELECTED)==0)) {
1060                                         /* select the parent bone */
1061                                         parbone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1062                                         
1063                                         /* check if parent has parent */
1064                                         parpar= parbone->parent;
1065                                         
1066                                         if ((parpar) && (parbone->flag & BONE_CONNECTED)) {
1067                                                 parpar->flag |= BONE_TIPSEL;
1068                                         }
1069                                         /* tag this bone to not flood selection */
1070                                         parbone->temp= parbone;
1071                                 }
1072                         }
1073                 }
1074                 
1075                 /* to be sure... */
1076                 for (curbone= G.edbo.first; curbone; curbone= curbone->next)
1077                         curbone->temp= NULL;
1078                 
1079         }
1080         
1081         /* undo + redraw pushes */
1082         countall(); // flushes selection!
1083
1084         allqueue (REDRAWVIEW3D, 0);
1085         allqueue (REDRAWBUTSEDIT, 0);
1086         allqueue(REDRAWBUTSOBJECT, 0);
1087         allqueue(REDRAWOOPS, 0);
1088         
1089         BIF_undo_push("Select Parent");
1090 }
1091
1092 /* helper for setflag_sel_bone() */
1093 static void bone_setflag (int *bone, int flag, short mode)
1094 {
1095         if (bone && flag) {
1096                 /* exception for inverse flags */
1097                 if (flag == BONE_NO_DEFORM) {
1098                         if (mode == 2)
1099                                 *bone |= flag;
1100                         else if (mode == 1)
1101                                 *bone &= ~flag;
1102                         else
1103                                 *bone ^= flag;
1104
1105                 }
1106                 else {
1107                         if (mode == 2)
1108                                 *bone &= ~flag;
1109                         else if (mode == 1)
1110                                 *bone |= flag;
1111                         else
1112                                 *bone ^= flag;
1113                 }
1114         }
1115 }
1116
1117 /* used by posemode and editmode */
1118 void setflag_armature (short mode)
1119 {
1120         Object *ob;
1121         bArmature *arm; 
1122         int flag;
1123         
1124         /* get data */
1125         if (G.obedit)
1126                 ob= G.obedit;
1127         else if (OBACT)
1128                 ob= OBACT;
1129         else
1130                 return;
1131         arm= (bArmature *)ob->data;
1132         
1133         /* get flag to set (sync these with the ones used in eBone_Flag */
1134         if (mode == 2)
1135                 flag= pupmenu("Disable Setting%t|Draw Wire%x1|Deform%x2|Mult VG%x3|Hinge%x4|No Scale%x5");
1136         else if (mode == 1)
1137                 flag= pupmenu("Enable Setting%t|Draw Wire%x1|Deform%x2|Mult VG%x3|Hinge%x4|No Scale%x5");
1138         else
1139                 flag= pupmenu("Toggle Setting%t|Draw Wire%x1|Deform%x2|Mult VG%x3|Hinge%x4|No Scale%x5");
1140         switch (flag) {
1141                 case 1:         flag = BONE_DRAWWIRE;   break;
1142                 case 2:         flag = BONE_NO_DEFORM; break;
1143                 case 3:         flag = BONE_MULT_VG_ENV; break;
1144                 case 4:         flag = BONE_HINGE; break;
1145                 case 5:         flag = BONE_NO_SCALE; break;
1146                 default:        return;
1147         }
1148         
1149         /* determine which mode armature is in */
1150         if ((!G.obedit) && (ob->flag & OB_POSEMODE)) {
1151                 /* deal with pose channels */
1152                 bPoseChannel *pchan;
1153                 
1154                 /* set setting */
1155                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1156                         if ((pchan->bone) && (arm->layer & pchan->bone->layer)) {
1157                                 if (pchan->bone->flag & BONE_SELECTED) {
1158                                         bone_setflag(&pchan->bone->flag, flag, mode);
1159                                 }
1160                         }
1161                 }
1162         }
1163         else if (G.obedit) {
1164                 /* deal with editbones */
1165                 EditBone *curbone;
1166                 
1167                 /* set setting */
1168                 for (curbone= G.edbo.first; curbone; curbone= curbone->next) {
1169                         if (arm->layer & curbone->layer) {
1170                                 if (curbone->flag & BONE_SELECTED) {
1171                                         bone_setflag(&curbone->flag, flag, mode);
1172                                 }
1173                         }
1174                 }
1175         }
1176         
1177         allqueue(REDRAWVIEW3D, 0);
1178         allqueue(REDRAWBUTSEDIT, 0);
1179         allqueue(REDRAWBUTSOBJECT, 0);
1180         allqueue(REDRAWOOPS, 0);
1181         
1182         BIF_undo_push("Change Bone Setting");
1183 }
1184
1185 /* **************** END PoseMode & EditMode *************************** */
1186 /* **************** Posemode stuff ********************** */
1187
1188
1189 static void selectconnected_posebonechildren (Object *ob, Bone *bone)
1190 {
1191         Bone *curBone;
1192         
1193         if (!(bone->flag & BONE_CONNECTED))
1194                 return;
1195         
1196         select_actionchannel_by_name (ob->action, bone->name, !(G.qual & LR_SHIFTKEY));
1197         
1198         if (G.qual & LR_SHIFTKEY)
1199                 bone->flag &= ~BONE_SELECTED;
1200         else
1201                 bone->flag |= BONE_SELECTED;
1202         
1203         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
1204                 selectconnected_posebonechildren (ob, curBone);
1205         }
1206 }
1207
1208 /* within active object context */
1209 void selectconnected_posearmature(void)
1210 {
1211         Bone *bone, *curBone, *next;
1212         Object *ob= OBACT;
1213         
1214         if(!ob || !ob->pose) return;
1215         
1216         if (G.qual & LR_SHIFTKEY)
1217                 bone= get_nearest_bone(0);
1218         else
1219                 bone = get_nearest_bone(1);
1220         
1221         if (!bone)
1222                 return;
1223         
1224         /* Select parents */
1225         for (curBone=bone; curBone; curBone=next){
1226                 select_actionchannel_by_name (ob->action, curBone->name, !(G.qual & LR_SHIFTKEY));
1227                 if (G.qual & LR_SHIFTKEY)
1228                         curBone->flag &= ~BONE_SELECTED;
1229                 else
1230                         curBone->flag |= BONE_SELECTED;
1231                 
1232                 if (curBone->flag & BONE_CONNECTED)
1233                         next=curBone->parent;
1234                 else
1235                         next=NULL;
1236         }
1237         
1238         /* Select children */
1239         for (curBone=bone->childbase.first; curBone; curBone=next){
1240                 selectconnected_posebonechildren (ob, curBone);
1241         }
1242         
1243         countall(); // flushes selection!
1244
1245         allqueue (REDRAWVIEW3D, 0);
1246         allqueue(REDRAWBUTSEDIT, 0);
1247         allqueue(REDRAWBUTSOBJECT, 0);
1248         allqueue (REDRAWACTION, 0);
1249         allqueue(REDRAWOOPS, 0);
1250         BIF_undo_push("Select connected");
1251
1252 }
1253
1254 /* **************** END Posemode stuff ********************** */
1255 /* **************** EditMode stuff ********************** */
1256
1257 /* called in space.c */
1258 void selectconnected_armature(void)
1259 {
1260         EditBone *bone, *curBone, *next;
1261
1262         if (G.qual & LR_SHIFTKEY)
1263                 bone= get_nearest_bone(0);
1264         else
1265                 bone= get_nearest_bone(1);
1266
1267         if (!bone)
1268                 return;
1269
1270         /* Select parents */
1271         for (curBone=bone; curBone; curBone=next){
1272                 if (G.qual & LR_SHIFTKEY){
1273                         curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1274                 }
1275                 else{
1276                         curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1277                 }
1278
1279                 if (curBone->flag & BONE_CONNECTED)
1280                         next=curBone->parent;
1281                 else
1282                         next=NULL;
1283         }
1284
1285         /* Select children */
1286         while (bone){
1287                 for (curBone=G.edbo.first; curBone; curBone=next){
1288                         next = curBone->next;
1289                         if (curBone->parent == bone){
1290                                 if (curBone->flag & BONE_CONNECTED){
1291                                         if (G.qual & LR_SHIFTKEY)
1292                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1293                                         else
1294                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1295                                         bone=curBone;
1296                                         break;
1297                                 }
1298                                 else{ 
1299                                         bone=NULL;
1300                                         break;
1301                                 }
1302                         }
1303                 }
1304                 if (!curBone)
1305                         bone=NULL;
1306
1307         }
1308
1309         countall(); // flushes selection!
1310
1311         allqueue (REDRAWVIEW3D, 0);
1312         allqueue (REDRAWBUTSEDIT, 0);
1313         allqueue(REDRAWBUTSOBJECT, 0);
1314         allqueue(REDRAWOOPS, 0);
1315         
1316         BIF_undo_push("Select connected");
1317
1318 }
1319
1320 /* does bones and points */
1321 /* note that BONE ROOT only gets drawn for root bones (or without IK) */
1322 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask)
1323 {
1324         EditBone *ebone;
1325         unsigned int buffer[MAXPICKBUF];
1326         unsigned int hitresult, besthitresult=BONESEL_NOSEL;
1327         int i, mindep= 4;
1328         short hits, mval[2];
1329
1330         persp(PERSP_VIEW);
1331
1332         glInitNames();
1333         
1334         getmouseco_areawin(mval);
1335         hits= view3d_opengl_select(buffer, MAXPICKBUF, mval[0]-5, mval[1]-5, mval[0]+5, mval[1]+5);
1336         if(hits==0)
1337                 hits= view3d_opengl_select(buffer, MAXPICKBUF, mval[0]-12, mval[1]-12, mval[0]+12, mval[1]+12);
1338                 
1339         /* See if there are any selected bones in this group */
1340         if (hits>0) {
1341                 
1342                 if(hits==1) {
1343                         if (!(buffer[3] & BONESEL_NOSEL)) 
1344                                 besthitresult= buffer[3];
1345                 }
1346                 else {
1347                         for (i=0; i< hits; i++) {
1348                                 hitresult= buffer[3+(i*4)];
1349                                 if (!(hitresult & BONESEL_NOSEL)) {
1350                                         int dep;
1351                                         
1352                                         ebone = BLI_findlink(&G.edbo, hitresult & ~BONESEL_ANY);
1353                                         
1354                                         /* clicks on bone points get advantage */
1355                                         if( hitresult & (BONESEL_ROOT|BONESEL_TIP)) {
1356                                                 /* but also the unselected one */
1357                                                 if(findunsel) {
1358                                                         if( (hitresult & BONESEL_ROOT) && (ebone->flag & BONE_ROOTSEL)==0) 
1359                                                                 dep= 1;
1360                                                         else if( (hitresult & BONESEL_TIP) && (ebone->flag & BONE_TIPSEL)==0) 
1361                                                                 dep= 1;
1362                                                         else 
1363                                                                 dep= 2;
1364                                                 }
1365                                                 else dep= 2;
1366                                         }
1367                                         else {
1368                                                 /* bone found */
1369                                                 if(findunsel) {
1370                                                         if((ebone->flag & BONE_SELECTED)==0)
1371                                                                 dep= 2;
1372                                                         else
1373                                                                 dep= 3;
1374                                                 }
1375                                                 else dep= 3;
1376                                         }
1377                                         if(dep < mindep) {
1378                                                 mindep= dep;
1379                                                 besthitresult= hitresult;
1380                                         }
1381                                 }
1382                         }
1383                 }
1384                 
1385                 if (!(besthitresult & BONESEL_NOSEL)) {
1386                         
1387                         ebone= BLI_findlink(&G.edbo, besthitresult & ~BONESEL_ANY);
1388                         
1389                         *selmask = 0;
1390                         if (besthitresult & BONESEL_ROOT)
1391                                 *selmask |= BONE_ROOTSEL;
1392                         if (besthitresult & BONESEL_TIP)
1393                                 *selmask |= BONE_TIPSEL;
1394                         if (besthitresult & BONESEL_BONE)
1395                                 *selmask |= BONE_SELECTED;
1396                         return ebone;
1397                 }
1398         }
1399         *selmask = 0;
1400         return NULL;
1401 }
1402
1403 static void delete_bone(EditBone* exBone)
1404 {
1405         EditBone *curBone;
1406         
1407         /* Find any bones that refer to this bone */
1408         for (curBone=G.edbo.first;curBone;curBone=curBone->next) {
1409                 if (curBone->parent==exBone) {
1410                         curBone->parent=exBone->parent;
1411                         curBone->flag &= ~BONE_CONNECTED;
1412                 }
1413         }
1414         
1415         BLI_freelinkN(&G.edbo,exBone);
1416 }
1417
1418 /* only editmode! */
1419 void delete_armature(void)
1420 {
1421         bArmature *arm= G.obedit->data;
1422         EditBone        *curBone, *next;
1423         bConstraint *con;
1424         
1425         TEST_EDITARMATURE;
1426         if (okee("Erase selected bone(s)")==0) return;
1427
1428         /* Select mirrored bones */
1429         if (arm->flag & ARM_MIRROR_EDIT) {
1430                 for (curBone=G.edbo.first; curBone; curBone=curBone->next) {
1431                         if (arm->layer & curBone->layer) {
1432                                 if (curBone->flag & BONE_SELECTED) {
1433                                         next = armature_bone_get_mirrored(curBone);
1434                                         if (next)
1435                                                 next->flag |= BONE_SELECTED;
1436                                 }
1437                         }
1438                 }
1439         }
1440         
1441         /*  First erase any associated pose channel */
1442         if (G.obedit->pose) {
1443                 bPoseChannel *chan, *next;
1444                 for (chan=G.obedit->pose->chanbase.first; chan; chan=next) {
1445                         next= chan->next;
1446                         curBone = editbone_name_exists(&G.edbo, chan->name);
1447                         
1448                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1449                                 free_constraints(&chan->constraints);
1450                                 BLI_freelinkN (&G.obedit->pose->chanbase, chan);
1451                         }
1452                         else {
1453                                 for (con= chan->constraints.first; con; con= con->next) {
1454                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1455                                         ListBase targets = {NULL, NULL};
1456                                         bConstraintTarget *ct;
1457                                         
1458                                         if (cti && cti->get_constraint_targets) {
1459                                                 cti->get_constraint_targets(con, &targets);
1460                                                 
1461                                                 for (ct= targets.first; ct; ct= ct->next) {
1462                                                         if (ct->tar == G.obedit) {
1463                                                                 if (ct->subtarget[0]) {
1464                                                                         curBone = editbone_name_exists(&G.edbo, ct->subtarget);
1465                                                                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1466                                                                                 con->flag |= CONSTRAINT_DISABLE;
1467                                                                                 ct->subtarget[0]= 0;
1468                                                                         }
1469                                                                 }
1470                                                         }
1471                                                 }
1472                                                 
1473                                                 if (cti->flush_constraint_targets)
1474                                                         cti->flush_constraint_targets(con, &targets, 0);
1475                                         }
1476                                 }
1477                         }
1478                 }
1479         }
1480         
1481         
1482         for (curBone=G.edbo.first;curBone;curBone=next) {
1483                 next=curBone->next;
1484                 if (arm->layer & curBone->layer) {
1485                         if (curBone->flag & BONE_SELECTED)
1486                                 delete_bone(curBone);
1487                 }
1488         }
1489         
1490         
1491         allqueue(REDRAWVIEW3D, 0);
1492         allqueue(REDRAWBUTSEDIT, 0);
1493         allqueue(REDRAWBUTSOBJECT, 0);
1494         allqueue(REDRAWOOPS, 0);
1495         countall(); // flushes selection!
1496         
1497         BIF_undo_push("Delete bone(s)");
1498 }
1499
1500 /* context: editmode armature */
1501 void mouse_armature(void)
1502 {
1503         EditBone *nearBone = NULL, *ebone;
1504         int     selmask;
1505
1506         nearBone= get_nearest_editbonepoint(1, &selmask);
1507         if (nearBone) {
1508                 
1509                 if (!(G.qual & LR_SHIFTKEY)) {
1510                         deselectall_armature(0, 0);
1511                 }
1512                 
1513                 /* by definition the non-root connected bones have no root point drawn,
1514                so a root selection needs to be delivered to the parent tip,
1515                countall() (bad location) flushes these flags */
1516                 
1517                 if(selmask & BONE_SELECTED) {
1518                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
1519                                 /* click in a chain */
1520                                 if(G.qual & LR_SHIFTKEY) {
1521                                         /* hold shift inverts this bone's selection */
1522                                         if(nearBone->flag & BONE_SELECTED) {
1523                                                 /* deselect this bone */
1524                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
1525                                                 /* only deselect parent tip if it is not selected */
1526                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
1527                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
1528                                         }
1529                                         else {
1530                                                 /* select this bone */
1531                                                 nearBone->flag |= BONE_TIPSEL;
1532                                                 nearBone->parent->flag |= BONE_TIPSEL;
1533                                         }
1534                                 }
1535                                 else {
1536                                         /* select this bone */
1537                                         nearBone->flag |= BONE_TIPSEL;
1538                                         nearBone->parent->flag |= BONE_TIPSEL;
1539                                 }
1540                         }
1541                         else {
1542                                 if(G.qual & LR_SHIFTKEY) {
1543                                         /* hold shift inverts this bone's selection */
1544                                         if(nearBone->flag & BONE_SELECTED)
1545                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
1546                                         else
1547                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
1548                                 }
1549                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
1550                         }
1551                 }
1552                 else {
1553                         if ((G.qual & LR_SHIFTKEY) && (nearBone->flag & selmask))
1554                                 nearBone->flag &= ~selmask;
1555                         else
1556                                 nearBone->flag |= selmask;
1557                 }
1558
1559                 countall(); // flushes selection!
1560                 
1561                 if(nearBone) {
1562                         /* then now check for active status */
1563                         for (ebone=G.edbo.first;ebone;ebone=ebone->next) ebone->flag &= ~BONE_ACTIVE;
1564                         if(nearBone->flag & BONE_SELECTED) nearBone->flag |= BONE_ACTIVE;
1565                 }
1566                 
1567                 allqueue(REDRAWVIEW3D, 0);
1568                 allqueue(REDRAWBUTSEDIT, 0);
1569                 allqueue(REDRAWBUTSOBJECT, 0);
1570                 allqueue(REDRAWOOPS, 0);
1571         }
1572
1573         rightmouse_transform();
1574 }
1575
1576 void free_editArmature(void)
1577 {
1578         /*      Clear the editbones list */
1579         if (G.edbo.first)
1580                 BLI_freelistN(&G.edbo);
1581 }
1582
1583 void remake_editArmature(void)
1584 {
1585         if(okee("Reload original data")==0) return;
1586         
1587         make_editArmature();
1588         allqueue(REDRAWVIEW3D, 0);
1589         allqueue(REDRAWOOPS, 0);
1590         allqueue(REDRAWBUTSHEAD, 0);
1591         allqueue(REDRAWBUTSEDIT, 0);
1592         allqueue(REDRAWBUTSOBJECT, 0);
1593         
1594 //      BIF_undo_push("Delete bone");
1595 }
1596
1597 /* Put object in EditMode */
1598 void make_editArmature(void)
1599 {
1600         bArmature *arm;
1601         
1602         if (G.obedit==0) return;
1603         
1604         free_editArmature();
1605         
1606         arm= get_armature(G.obedit);
1607         if (!arm) return;
1608         
1609         make_boneList(&G.edbo, &arm->bonebase,NULL);
1610 }
1611
1612 /* put EditMode back in Object */
1613 void load_editArmature(void)
1614 {
1615         bArmature *arm;
1616
1617         arm= get_armature(G.obedit);
1618         if (!arm) return;
1619         
1620         editbones_to_armature(&G.edbo, G.obedit);
1621 }
1622
1623 /* toggle==0: deselect
1624    toggle==1: swap 
1625    toggle==2: only active tag
1626 */
1627 void deselectall_armature(int toggle, int doundo)
1628 {
1629         bArmature *arm= G.obedit->data;
1630         EditBone        *eBone;
1631         int                     sel=1;
1632
1633         if(toggle==1) {
1634                 /*      Determine if there are any selected bones
1635                         And therefore whether we are selecting or deselecting */
1636                 for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1637 //                      if(arm->layer & eBone->layer) {
1638                                 if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1639                                         sel=0;
1640                                         break;
1641                                 }
1642 //                      }
1643                 }
1644         }
1645         else sel= toggle;
1646         
1647         /*      Set the flags */
1648         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1649                 if (sel==1) {
1650                         if(arm->layer & eBone->layer && (eBone->flag & BONE_HIDDEN_A)==0) {
1651                                 eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1652                                 if(eBone->parent)
1653                                         eBone->parent->flag |= (BONE_TIPSEL);
1654                         }
1655                 }
1656                 else if (sel==2)
1657                         eBone->flag &= ~(BONE_ACTIVE);
1658                 else
1659                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1660         }
1661         
1662         allqueue(REDRAWVIEW3D, 0);
1663         allqueue(REDRAWBUTSEDIT, 0);
1664         allqueue(REDRAWBUTSOBJECT, 0);
1665         allqueue(REDRAWOOPS, 0);
1666         
1667         countall(); // flushes selection!
1668         if (doundo) {
1669                 if (sel==1) BIF_undo_push("Select All");
1670                 else BIF_undo_push("Deselect All");
1671         }
1672 }
1673
1674 /* Sets the roll value of selected bones, depending on the mode
1675  *      mode == 0: their z-axes point upwards 
1676  *      mode == 1: their z-axes point towards 3d-cursor
1677  */
1678 void auto_align_armature(short mode)
1679 {
1680         bArmature *arm= G.obedit->data;
1681         EditBone *ebone;
1682         EditBone *flipbone = NULL;
1683         float   delta[3];
1684         float   curmat[3][3];
1685         float   *cursor= give_cursor();
1686                 
1687         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1688                 if (arm->layer & ebone->layer) {
1689                         if (arm->flag & ARM_MIRROR_EDIT)
1690                                 flipbone = armature_bone_get_mirrored(ebone);
1691                         
1692                         if ((ebone->flag & BONE_SELECTED) || 
1693                                 (flipbone && flipbone->flag & BONE_SELECTED)) 
1694                         {
1695                                 /* specific method used to calculate roll depends on mode */
1696                                 if (mode == 1) {
1697                                         /* Z-Axis point towards cursor */
1698                                         float   mat[4][4], tmat[4][4], imat[4][4];
1699                                         float   rmat[4][4], rot[3];
1700                                         float   vec[3];
1701                                         
1702                                         /* find the current bone matrix as a 4x4 matrix (in Armature Space) */
1703                                         VecSubf(delta, ebone->tail, ebone->head);
1704                                         vec_roll_to_mat3(delta, ebone->roll, curmat);
1705                                         Mat4CpyMat3(mat, curmat);
1706                                         VECCOPY(mat[3], ebone->head);
1707                                         
1708                                         /* multiply bone-matrix by object matrix (so that bone-matrix is in WorldSpace) */
1709                                         Mat4MulMat4(tmat, mat, G.obedit->obmat);
1710                                         Mat4Invert(imat, tmat);
1711                                         
1712                                         /* find position of cursor relative to bone */
1713                                         VecMat4MulVecfl(vec, imat, cursor);
1714                                         
1715                                         /* check that cursor is in usable position */
1716                                         if ((IS_EQ(vec[0], 0)==0) && (IS_EQ(vec[2], 0)==0)) {
1717                                                 /* Compute a rotation matrix around y */
1718                                                 rot[1] = atan2(vec[0], vec[2]);
1719                                                 rot[0] = rot[2] = 0.0f;
1720                                                 EulToMat4(rot, rmat);
1721                                                 
1722                                                 /* Multiply the bone matrix by rotation matrix. This should be new bone-matrix */
1723                                                 Mat4MulMat4(tmat, rmat, mat);
1724                                                 Mat3CpyMat4(curmat, tmat);
1725                                                 
1726                                                 /* Now convert from new bone-matrix, back to a roll value (in radians) */
1727                                                 mat3_to_vec_roll(curmat, delta, &ebone->roll);
1728                                         }
1729                                 }
1730                                 else { 
1731                                         /* Z-Axis Point Up */
1732                                         float   xaxis[3]={1.0, 0.0, 0.0}, yaxis[3], zaxis[3]={0.0, 0.0, 1.0};
1733                                         float   targetmat[3][3], imat[3][3], diffmat[3][3];
1734                                         
1735                                         /* Find the current bone matrix */
1736                                         VecSubf(delta, ebone->tail, ebone->head);
1737                                         vec_roll_to_mat3(delta, 0.0, curmat);
1738                                         
1739                                         /* Make new matrix based on y axis & z-up */
1740                                         VECCOPY (yaxis, curmat[1]);
1741                                         
1742                                         Mat3One(targetmat);
1743                                         VECCOPY (targetmat[0], xaxis);
1744                                         VECCOPY (targetmat[1], yaxis);
1745                                         VECCOPY (targetmat[2], zaxis);
1746                                         Mat3Ortho(targetmat);
1747                                         
1748                                         /* Find the difference between the two matrices */
1749                                         Mat3Inv(imat, targetmat);
1750                                         Mat3MulMat3(diffmat, imat, curmat);
1751                                         
1752                                         ebone->roll = atan2(diffmat[2][0], diffmat[2][2]);
1753                                 }                               
1754                         }
1755                 }
1756         }
1757 }
1758
1759 /* **************** undo for armatures ************** */
1760
1761 static void undoBones_to_editBones(void *lbv)
1762 {
1763         ListBase *lb= lbv;
1764         EditBone *ebo, *newebo;
1765         
1766         BLI_freelistN(&G.edbo);
1767         
1768         /* copy  */
1769         for(ebo= lb->first; ebo; ebo= ebo->next) {
1770                 newebo= MEM_dupallocN(ebo);
1771                 ebo->temp= newebo;
1772                 BLI_addtail(&G.edbo, newebo);
1773         }
1774         
1775         /* set pointers */
1776         for(newebo= G.edbo.first; newebo; newebo= newebo->next) {
1777                 if(newebo->parent) newebo->parent= newebo->parent->temp;
1778         }
1779         /* be sure they dont hang ever */
1780         for(newebo= G.edbo.first; newebo; newebo= newebo->next) {
1781                 newebo->temp= NULL;
1782         }
1783 }
1784
1785 static void *editBones_to_undoBones(void)
1786 {
1787         ListBase *lb;
1788         EditBone *ebo, *newebo;
1789         
1790         lb= MEM_callocN(sizeof(ListBase), "listbase undo");
1791         
1792         /* copy */
1793         for(ebo= G.edbo.first; ebo; ebo= ebo->next) {
1794                 newebo= MEM_dupallocN(ebo);
1795                 ebo->temp= newebo;
1796                 BLI_addtail(lb, newebo);
1797         }
1798         
1799         /* set pointers */
1800         for(newebo= lb->first; newebo; newebo= newebo->next) {
1801                 if(newebo->parent) newebo->parent= newebo->parent->temp;
1802         }
1803         
1804         return lb;
1805 }
1806
1807 static void free_undoBones(void *lbv)
1808 {
1809         ListBase *lb= lbv;
1810         
1811         BLI_freelistN(lb);
1812         MEM_freeN(lb);
1813 }
1814
1815 /* and this is all the undo system needs to know */
1816 void undo_push_armature(char *name)
1817 {
1818         undo_editmode_push(name, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
1819 }
1820
1821
1822
1823 /* **************** END EditMode stuff ********************** */
1824 /* *************** Adding stuff in editmode *************** */
1825
1826 /* default bone add, returns it selected, but without tail set */
1827 static EditBone *add_editbone(char *name)
1828 {
1829         bArmature *arm= G.obedit->data;
1830         
1831         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
1832         
1833         BLI_strncpy(bone->name, name, 32);
1834         unique_editbone_name(&G.edbo, bone->name);
1835         
1836         BLI_addtail(&G.edbo, bone);
1837         
1838         bone->flag |= BONE_TIPSEL;
1839         bone->weight= 1.0F;
1840         bone->dist= 0.25F;
1841         bone->xwidth= 0.1;
1842         bone->zwidth= 0.1;
1843         bone->ease1= 1.0;
1844         bone->ease2= 1.0;
1845         bone->rad_head= 0.10;
1846         bone->rad_tail= 0.05;
1847         bone->segments= 1;
1848         bone->layer= arm->layer;
1849         
1850         return bone;
1851 }
1852
1853 static void add_primitive_bone(Object *ob, short newob)
1854 {
1855         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
1856         EditBone        *bone;
1857         
1858         VECCOPY(curs, give_cursor());   
1859
1860         /* Get inverse point for head and orientation for tail */
1861         Mat4Invert(G.obedit->imat, G.obedit->obmat);
1862         Mat4MulVecfl(G.obedit->imat, curs);
1863
1864         if ( !(newob) || (U.flag & USER_ADD_VIEWALIGNED) ) Mat3CpyMat4(obmat, G.vd->viewmat);
1865         else Mat3One(obmat);
1866         
1867         Mat3CpyMat4(viewmat, G.obedit->obmat);
1868         Mat3MulMat3(totmat, obmat, viewmat);
1869         Mat3Inv(imat, totmat);
1870         
1871         deselectall_armature(0, 0);
1872         
1873         /*      Create a bone   */
1874         bone= add_editbone("Bone");
1875
1876         VECCOPY(bone->head, curs);
1877         
1878         if ( !(newob) || (U.flag & USER_ADD_VIEWALIGNED) )
1879                 VecAddf(bone->tail, bone->head, imat[1]);       // bone with unit length 1
1880         else
1881                 VecAddf(bone->tail, bone->head, imat[2]);       // bone with unit length 1, pointing up Z
1882         
1883 }
1884
1885 void add_primitiveArmature(int type)
1886 {
1887         short newob=0;
1888         
1889         if(G.scene->id.lib) return;
1890         
1891         /* this function also comes from an info window */
1892         if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
1893         if (G.vd==NULL) return;
1894         
1895         G.f &= ~(G_VERTEXPAINT+G_TEXTUREPAINT+G_WEIGHTPAINT+G_SCULPTMODE);
1896         setcursor_space(SPACE_VIEW3D, CURSOR_STD);
1897
1898         check_editmode(OB_ARMATURE);
1899         
1900         /* If we're not the "obedit", make a new object and enter editmode */
1901         if (G.obedit==NULL) {
1902                 add_object(OB_ARMATURE);
1903                 base_init_from_view3d(BASACT, G.vd);
1904                 G.obedit= BASACT->object;
1905                 
1906                 where_is_object(G.obedit);
1907                 
1908                 make_editArmature();
1909                 setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
1910                 newob=1;
1911         }
1912         
1913         /* no primitive support yet */
1914         add_primitive_bone(G.obedit, newob);
1915         
1916         countall(); // flushes selection!
1917
1918         if ((newob) && !(U.flag & USER_ADD_EDITMODE)) {
1919                 exit_editmode(2);
1920         }
1921         
1922         allqueue(REDRAWALL, 0);
1923         BIF_undo_push("Add primitive");
1924 }
1925
1926 /* the ctrl-click method */
1927 void addvert_armature(void)
1928 {
1929         bArmature *arm= G.obedit->data;
1930         EditBone *ebone, *newbone, *flipbone;
1931         float *curs, mat[3][3],imat[3][3];
1932         int a, to_root= 0;
1933         
1934         TEST_EDITARMATURE;
1935         
1936         /* find the active or selected bone */
1937         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1938                 if (arm->layer & ebone->layer) {
1939                         if (ebone->flag & (BONE_ACTIVE|BONE_TIPSEL)) 
1940                                 break;
1941                 }
1942         }
1943         
1944         if (ebone==NULL) {
1945                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1946                         if (arm->layer & ebone->layer) {
1947                                 if (ebone->flag & (BONE_ACTIVE|BONE_ROOTSEL)) 
1948                                         break;
1949                         }
1950                 }
1951                 if (ebone == NULL) 
1952                         return;
1953                 
1954                 to_root= 1;
1955         }
1956         
1957         deselectall_armature(0, 0);
1958         
1959         /* we re-use code for mirror editing... */
1960         flipbone= NULL;
1961         if (arm->flag & ARM_MIRROR_EDIT)
1962                 flipbone= armature_bone_get_mirrored(ebone);
1963
1964         for (a=0; a<2; a++) {
1965                 if (a==1) {
1966                         if (flipbone==NULL)
1967                                 break;
1968                         else {
1969                                 SWAP(EditBone *, flipbone, ebone);
1970                         }
1971                 }
1972                 
1973                 newbone= add_editbone(ebone->name);
1974                 newbone->flag |= BONE_ACTIVE;
1975                 
1976                 if (to_root) {
1977                         VECCOPY(newbone->head, ebone->head);
1978                         newbone->rad_head= ebone->rad_tail;
1979                         newbone->parent= ebone->parent;
1980                 }
1981                 else {
1982                         VECCOPY(newbone->head, ebone->tail);
1983                         newbone->rad_head= ebone->rad_tail;
1984                         newbone->parent= ebone;
1985                         newbone->flag |= BONE_CONNECTED;
1986                 }
1987                 
1988                 curs= give_cursor();
1989                 VECCOPY(newbone->tail, curs);
1990                 VecSubf(newbone->tail, newbone->tail, G.obedit->obmat[3]);
1991                 
1992                 if (a==1) 
1993                         newbone->tail[0]= -newbone->tail[0];
1994                 
1995                 Mat3CpyMat4(mat, G.obedit->obmat);
1996                 Mat3Inv(imat, mat);
1997                 Mat3MulVecfl(imat, newbone->tail);
1998                 
1999                 newbone->length= VecLenf(newbone->head, newbone->tail);
2000                 newbone->rad_tail= newbone->length*0.05f;
2001                 newbone->dist= newbone->length*0.25f;
2002                 
2003         }
2004         
2005         countall();
2006         
2007         BIF_undo_push("Add Bone");
2008         allqueue(REDRAWVIEW3D, 0);
2009 }
2010
2011 /* adds an EditBone between the nominated locations (should be in the right space) */
2012 static EditBone *add_points_bone (float head[], float tail[]) 
2013 {
2014         EditBone *ebo;
2015         
2016         ebo= add_editbone("Bone");
2017         
2018         VECCOPY(ebo->head, head);
2019         VECCOPY(ebo->tail, tail);
2020         
2021         return ebo;
2022 }
2023
2024
2025 static EditBone *get_named_editbone(char *name)
2026 {
2027         EditBone  *eBone;
2028
2029         if (name)
2030                 for (eBone=G.edbo.first; eBone; eBone=eBone->next) {
2031                         if (!strcmp(name, eBone->name))
2032                                 return eBone;
2033                 }
2034
2035         return NULL;
2036 }
2037
2038 static void update_dup_subtarget(EditBone *dupBone)
2039 {
2040         /* If an edit bone has been duplicated, lets
2041          * update it's constraints if the subtarget
2042          * they point to has also been duplicated
2043          */
2044         EditBone     *oldtarget, *newtarget;
2045         bPoseChannel *chan;
2046         bConstraint  *curcon;
2047         ListBase     *conlist;
2048         
2049         if ( (chan = verify_pose_channel(OBACT->pose, dupBone->name)) ) {
2050                 if ( (conlist = &chan->constraints) ) {
2051                         for (curcon = conlist->first; curcon; curcon=curcon->next) {
2052                                 /* does this constraint have a subtarget in
2053                                  * this armature?
2054                                  */
2055                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
2056                                 ListBase targets = {NULL, NULL};
2057                                 bConstraintTarget *ct;
2058                                 
2059                                 if (cti && cti->get_constraint_targets) {
2060                                         cti->get_constraint_targets(curcon, &targets);
2061                                         
2062                                         for (ct= targets.first; ct; ct= ct->next) {
2063                                                 if ((ct->tar == G.obedit) && (ct->subtarget[0])) {
2064                                                         oldtarget = get_named_editbone(ct->subtarget);
2065                                                         if (oldtarget) {
2066                                                                 /* was the subtarget bone duplicated too? If
2067                                                                  * so, update the constraint to point at the 
2068                                                                  * duplicate of the old subtarget.
2069                                                                  */
2070                                                                 if (oldtarget->flag & BONE_SELECTED){
2071                                                                         newtarget = (EditBone *) oldtarget->temp;
2072                                                                         strcpy(ct->subtarget, newtarget->name);
2073                                                                 }
2074                                                         }
2075                                                 }
2076                                         }
2077                                         
2078                                         if (cti->flush_constraint_targets)
2079                                                 cti->flush_constraint_targets(curcon, &targets, 0);
2080                                 }
2081                         }
2082                 }
2083         }
2084 }
2085
2086
2087 void adduplicate_armature(void)
2088 {
2089         bArmature *arm= G.obedit->data;
2090         EditBone        *eBone = NULL;
2091         EditBone        *curBone;
2092         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
2093         
2094         countall(); // flushes selection!
2095
2096         /* Select mirrored bones */
2097         if (arm->flag & ARM_MIRROR_EDIT) {
2098                 for (curBone=G.edbo.first; curBone; curBone=curBone->next) {
2099                         if (arm->layer & curBone->layer) {
2100                                 if (curBone->flag & BONE_SELECTED) {
2101                                         eBone = armature_bone_get_mirrored(curBone);
2102                                         if (eBone)
2103                                                 eBone->flag |= BONE_SELECTED;
2104                                 }
2105                         }
2106                 }
2107         }
2108         
2109         /*      Find the selected bones and duplicate them as needed */
2110         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next) {
2111                 if (arm->layer & curBone->layer) {
2112                         if (curBone->flag & BONE_SELECTED) {
2113                                 eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
2114                                 eBone->flag |= BONE_SELECTED;
2115                                 
2116                                 /*      Copy data from old bone to new bone */
2117                                 memcpy (eBone, curBone, sizeof(EditBone));
2118                                 
2119                                 curBone->temp = eBone;
2120                                 eBone->temp = curBone;
2121                                 
2122                                 unique_editbone_name(&G.edbo, eBone->name);
2123                                 BLI_addtail(&G.edbo, eBone);
2124                                 if (!firstDup)
2125                                         firstDup=eBone;
2126                                 
2127                                 /* Lets duplicate the list of constraints that the
2128                                  * current bone has.
2129                                  */
2130                                 if (OBACT->pose) {
2131                                         bPoseChannel *chanold, *channew;
2132                                         ListBase     *listold, *listnew;
2133                                         
2134                                         chanold = verify_pose_channel (OBACT->pose, curBone->name);
2135                                         if (chanold) {
2136                                                 listold = &chanold->constraints;
2137                                                 if (listold) {
2138                                                         /* WARNING: this creates a new posechannel, but there will not be an attached bone 
2139                                                          *              yet as the new bones created here are still 'EditBones' not 'Bones'. 
2140                                                          */
2141                                                         channew = 
2142                                                                 verify_pose_channel(OBACT->pose, eBone->name);
2143                                                         if (channew) {
2144                                                                 /* copy transform locks */
2145                                                                 channew->protectflag = chanold->protectflag;
2146                                                                 
2147                                                                 /* ik (dof) settings */
2148                                                                 channew->ikflag = chanold->ikflag;
2149                                                                 VECCOPY(channew->limitmin, chanold->limitmin);
2150                                                                 VECCOPY(channew->limitmax, chanold->limitmax);
2151                                                                 VECCOPY(channew->stiffness, chanold->stiffness);
2152                                                                 channew->ikstretch= chanold->ikstretch;
2153                                                                 
2154                                                                 /* constraints */
2155                                                                 listnew = &channew->constraints;
2156                                                                 copy_constraints (listnew, listold);
2157                                                         }
2158                                                 }
2159                                         }
2160                                 }
2161                         }
2162                 }
2163         }
2164
2165         /*      Run though the list and fix the pointers */
2166         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next) {
2167                 if (arm->layer & curBone->layer) {
2168                         if (curBone->flag & BONE_SELECTED) {
2169                                 eBone=(EditBone*) curBone->temp;
2170                                 
2171                                 /*      If this bone has no parent,
2172                                 Set the duplicate->parent to NULL
2173                                 */
2174                                 if (!curBone->parent)
2175                                         eBone->parent = NULL;
2176                                 /*      If this bone has a parent that IS selected,
2177                                         Set the duplicate->parent to the curBone->parent->duplicate
2178                                         */
2179                                 else if (curBone->parent->flag & BONE_SELECTED)
2180                                         eBone->parent= (EditBone *)curBone->parent->temp;
2181                                 /*      If this bone has a parent that IS not selected,
2182                                         Set the duplicate->parent to the curBone->parent
2183                                         */
2184                                 else {
2185                                         eBone->parent=(EditBone*) curBone->parent; 
2186                                         eBone->flag &= ~BONE_CONNECTED;
2187                                 }
2188                                 
2189                                 /* Lets try to fix any constraint subtargets that might
2190                                         have been duplicated */
2191                                 update_dup_subtarget(eBone);
2192                         }
2193                 }
2194         } 
2195         
2196         /*      Deselect the old bones and select the new ones */
2197         
2198         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next) {
2199                 if (arm->layer & curBone->layer)
2200                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
2201         }
2202         
2203         BIF_TransformSetUndo("Add Duplicate");
2204         initTransform(TFM_TRANSLATION, CTX_NO_PET);
2205         Transform();
2206         
2207         allqueue(REDRAWBUTSEDIT, 0);
2208         allqueue(REDRAWBUTSOBJECT, 0);
2209         allqueue(REDRAWOOPS, 0);
2210 }
2211
2212
2213
2214 /* *************** END Adding stuff in editmode *************** */
2215 /* ************** Add/Remove stuff in editmode **************** */
2216
2217 /* temporary data-structure for merge/fill bones */
2218 typedef struct EditBonePoint {
2219         struct EditBonePoint *next, *prev;
2220         
2221         EditBone *head_owner;           /* EditBone which uses this point as a 'head' point */
2222         EditBone *tail_owner;           /* EditBone which uses this point as a 'tail' point */
2223         
2224         float vec[3];                           /* the actual location of the point in local/EditMode space */
2225 } EditBonePoint;
2226
2227 /* find chain-tips (i.e. bones without children) */
2228 static void chains_find_tips (ListBase *list)
2229 {
2230         EditBone *curBone, *ebo;
2231         LinkData *ld;
2232         
2233         /* note: this is potentially very slow ... there's got to be a better way */
2234         for (curBone= G.edbo.first; curBone; curBone= curBone->next) {
2235                 short stop= 0;
2236                 
2237                 /* is this bone contained within any existing chain? (skip if so) */
2238                 for (ld= list->first; ld; ld= ld->next) {
2239                         for (ebo= ld->data; ebo; ebo= ebo->parent) {
2240                                 if (ebo == curBone) {
2241                                         stop= 1;
2242                                         break;
2243                                 }
2244                         }
2245                         
2246                         if (stop) break;
2247                 }
2248                 /* skip current bone if it is part of an existing chain */
2249                 if (stop) continue;
2250                 
2251                 /* is any existing chain part of the chain formed by this bone? */
2252                 stop= 0;
2253                 for (ebo= curBone->parent; ebo; ebo= ebo->parent) {
2254                         for (ld= list->first; ld; ld= ld->next) {
2255                                 if (ld->data == ebo) {
2256                                         ld->data= curBone;
2257                                         stop= 1;
2258                                         break;
2259                                 }
2260                         }
2261                         
2262                         if (stop) break;
2263                 }
2264                 /* current bone has already been added to a chain? */
2265                 if (stop) continue;
2266                 
2267                 /* add current bone to a new chain */
2268                 ld= MEM_callocN(sizeof(LinkData), "BoneChain");
2269                 ld->data= curBone;
2270                 BLI_addtail(list, ld);
2271         }
2272 }
2273
2274
2275 static void fill_add_joint (EditBone *ebo, short eb_tail, ListBase *points)
2276 {
2277         EditBonePoint *ebp;
2278         float vec[3];
2279         short found= 0;
2280         
2281         if (eb_tail) {
2282                 VECCOPY(vec, ebo->tail);
2283         }
2284         else {
2285                 VECCOPY(vec, ebo->head);
2286         }
2287         
2288         for (ebp= points->first; ebp; ebp= ebp->next) {
2289                 if (VecEqual(ebp->vec, vec)) {                  
2290                         if (eb_tail) {
2291                                 if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
2292                                         /* so this bone's tail owner is this bone */
2293                                         ebp->tail_owner= ebo;
2294                                         found= 1;
2295                                         break;
2296                                 }
2297                         }
2298                         else {
2299                                 if ((ebp->tail_owner) && (ebo->parent == ebp->tail_owner)) {
2300                                         /* so this bone's head owner is this bone */
2301                                         ebp->head_owner= ebo;
2302                                         found = 1;
2303                                         break;
2304                                 }
2305                         }
2306                 }
2307         }
2308         
2309         /* allocate a new point if no existing point was related */
2310         if (found == 0) {
2311                 ebp= MEM_callocN(sizeof(EditBonePoint), "EditBonePoint");
2312                 
2313                 if (eb_tail) {
2314                         VECCOPY(ebp->vec, ebo->tail);
2315                         ebp->tail_owner= ebo;
2316                 }
2317                 else {
2318                         VECCOPY(ebp->vec, ebo->head);
2319                         ebp->head_owner= ebo;
2320                 }
2321                 
2322                 BLI_addtail(points, ebp);
2323         }
2324 }
2325
2326 /* bone adding between selected joints */
2327 void fill_bones_armature(void)
2328 {
2329         bArmature *arm= G.obedit->data;
2330         EditBone *ebo, *newbone=NULL;
2331         ListBase points = {NULL, NULL};
2332         int count;
2333         
2334         /* loop over all bones, and only consider if visible */
2335         for (ebo= G.edbo.first; ebo; ebo= ebo->next) {
2336                 if ((arm->layer & ebo->layer) && !(ebo->flag & BONE_HIDDEN_A)) {
2337                         if (!(ebo->flag & BONE_CONNECTED) && (ebo->flag & BONE_ROOTSEL))
2338                                 fill_add_joint(ebo, 0, &points);
2339                         if (ebo->flag & BONE_TIPSEL) 
2340                                 fill_add_joint(ebo, 1, &points);
2341                 }
2342         }
2343         
2344         /* the number of joints determines how we fill:
2345          *      1) between joint and cursor (joint=head, cursor=tail)
2346          *      2) between the two joints (order is dependent on active-bone/hierachy)
2347          *      3+) error (a smarter method involving finding chains needs to be worked out
2348          */
2349         count= BLI_countlist(&points);
2350         
2351         if (count == 0) {
2352                 error("No joints selected");
2353                 return;
2354         }
2355         else if (count == 1) {
2356                 EditBonePoint *ebp;
2357                 float curs[3];
2358                 
2359                 /* Get Points - selected joint */
2360                 ebp= (EditBonePoint *)points.first;
2361                 
2362                 /* Get points - cursor (tail) */
2363                 VECCOPY (curs, give_cursor());  
2364                 
2365                 Mat4Invert(G.obedit->imat, G.obedit->obmat);
2366                 Mat4MulVecfl(G.obedit->imat, curs);
2367                 
2368                 /* Create a bone */
2369                 newbone= add_points_bone(ebp->vec, curs);
2370         }
2371         else if (count == 2) {
2372                 EditBonePoint *ebp, *ebp2;
2373                 float head[3], tail[3];
2374                 
2375                 /* check that the points don't belong to the same bone */
2376                 ebp= (EditBonePoint *)points.first;
2377                 ebp2= ebp->next;
2378                 
2379                 if ((ebp->head_owner==ebp2->tail_owner) && (ebp->head_owner!=NULL)) {
2380                         error("Same bone selected...");
2381                         BLI_freelistN(&points);
2382                         return;
2383                 }
2384                 if ((ebp->tail_owner==ebp2->head_owner) && (ebp->tail_owner!=NULL)) {
2385                         error("Same bone selected...");
2386                         BLI_freelistN(&points);
2387                         return;
2388                 }
2389                 
2390                 /* find which one should be the 'head' */
2391                 if ((ebp->head_owner && ebp2->head_owner) || (ebp->tail_owner && ebp2->tail_owner)) {
2392                         /* rule: whichever one is closer to 3d-cursor */
2393                         float curs[3];
2394                         float vecA[3], vecB[3];
2395                         float distA, distB;
2396                         
2397                         /* get cursor location */
2398                         VECCOPY (curs, give_cursor());  
2399                         
2400                         Mat4Invert(G.obedit->imat, G.obedit->obmat);
2401                         Mat4MulVecfl(G.obedit->imat, curs);
2402                         
2403                         /* get distances */
2404                         VecSubf(vecA, ebp->vec, curs);
2405                         VecSubf(vecB, ebp2->vec, curs);
2406                         distA= VecLength(vecA);
2407                         distB= VecLength(vecB);
2408                         
2409                         /* compare distances - closer one therefore acts as direction for bone to go */
2410                         if (distA < distB) {
2411                                 VECCOPY(head, ebp2->vec);
2412                                 VECCOPY(tail, ebp->vec);
2413                         }
2414                         else {
2415                                 VECCOPY(head, ebp->vec);
2416                                 VECCOPY(tail, ebp2->vec);
2417                         }
2418                 }
2419                 else if (ebp->head_owner) {
2420                         VECCOPY(head, ebp->vec);
2421                         VECCOPY(tail, ebp2->vec);
2422                 }
2423                 else if (ebp2->head_owner) {
2424                         VECCOPY(head, ebp2->vec);
2425                         VECCOPY(tail, ebp->vec);
2426                 }
2427                 
2428                 /* add new bone */
2429                 newbone= add_points_bone(head, tail);
2430         }
2431         else {
2432                 // FIXME.. figure out a method for multiple bones
2433                 error("Too many points selected"); 
2434                 printf("Points selected: %d \n", count);
2435                 BLI_freelistN(&points);
2436                 return;
2437         }
2438         
2439         /* free points */
2440         BLI_freelistN(&points);
2441         
2442         /* undo + updates */
2443         allqueue(REDRAWVIEW3D, 0);
2444         allqueue(REDRAWBUTSEDIT, 0);
2445         BIF_undo_push("Fill Bones");
2446 }
2447
2448 /* this function merges between two bones, removes them and those in-between, 
2449  * and adjusts the parent relationships for those in-between
2450  */
2451 static void bones_merge(EditBone *start, EditBone *end, EditBone *endchild, ListBase *chains)
2452 {
2453         EditBone *ebo, *ebone, *newbone;
2454         LinkData *chain;
2455         float head[3], tail[3];
2456         
2457         /* check if same bone */
2458         if (start == end) {
2459                 printf("Error: same bone! \n");
2460                 printf("\tstart = %s, end = %s \n", start->name, end->name);
2461         }
2462         
2463         /* step 1: add a new bone
2464          *      - head = head/tail of start (default head)
2465          *      - tail = head/tail of end (default tail)
2466          *      - parent = parent of start
2467          */
2468         if ((start->flag & BONE_TIPSEL) && !(start->flag & (BONE_SELECTED|BONE_ACTIVE))) {
2469                 VECCOPY(head, start->tail);
2470         }
2471         else {
2472                 VECCOPY(head, start->head);
2473         }
2474         if ((end->flag & BONE_ROOTSEL) && !(end->flag & (BONE_SELECTED|BONE_ACTIVE))) {
2475                 VECCOPY(tail, end->head);
2476         }
2477         else {
2478                 VECCOPY(tail, end->tail);
2479         }
2480         newbone= add_points_bone(head, tail);
2481         newbone->parent = start->parent;
2482         
2483         /* step 2a: parent children of in-between bones to newbone */
2484         for (chain= chains->first; chain; chain= chain->next) {
2485                 /* ick: we need to check if parent of each bone in chain is one of the bones in the */
2486                 for (ebo= chain->data; ebo; ebo= ebo->parent) {
2487                         short found= 0;
2488                         
2489                         /* try to find which bone from the list to be removed, is the parent */
2490                         for (ebone= end; ebone; ebone= ebone->parent) {
2491                                 if (ebo->parent == ebone) {
2492                                         found= 1;
2493                                         break;
2494                                 }
2495                         }
2496                         
2497                         /* adjust this bone's parent to newbone then */
2498                         if (found) {
2499                                 ebo->parent= newbone;
2500                                 break;
2501                         }
2502                 }
2503         }
2504         
2505         /* step 2b: parent child of end to newbone (child from this chain) */
2506         if (endchild)
2507                 endchild->parent= newbone;
2508         
2509         /* step 3: delete all bones between and including start and end */
2510         for (ebo= end; ebo; ebo= ebone) {
2511                 ebone= (ebo == start) ? (NULL) : (ebo->parent);
2512                 BLI_freelinkN(&G.edbo, ebo);
2513         }
2514 }
2515
2516 /* bone merging - has a menu! */
2517 void merge_armature(void)
2518 {
2519         bArmature *arm= G.obedit->data;
2520         short val= 0;
2521         
2522         /* process a menu to determine how to merge */
2523         // TODO: there's room for more modes of merging stuff...
2524         val= pupmenu("Merge Selected Bones%t|Within Chains%x1");
2525         if (val <= 0) return;
2526         
2527         if (val == 1) {
2528                 /* go down chains, merging bones */
2529                 ListBase chains = {NULL, NULL};
2530                 LinkData *chain, *nchain;
2531                 EditBone *ebo;
2532                 
2533                 /* get chains (ends on chains) */
2534                 chains_find_tips(&chains);
2535                 if (chains.first == NULL) return;
2536                 
2537                 /* each 'chain' is the last bone in the chain (with no children) */
2538                 for (chain= chains.first; chain; chain= nchain) {
2539                         EditBone *bstart= NULL, *bend= NULL;
2540                         EditBone *bchild= NULL, *child=NULL;
2541                         
2542                         /* temporarily remove chain from list of chains */
2543                         nchain= chain->next;
2544                         BLI_remlink(&chains, chain);
2545                         
2546                         /* only consider bones that are visible and selected */
2547                         for (ebo=chain->data; ebo; child=ebo, ebo=ebo->parent) {
2548                                 /* check if visible + selected */
2549                                 if ( (arm->layer & ebo->layer) && !(ebo->flag & BONE_HIDDEN_A) &&
2550                                          ((ebo->flag & BONE_CONNECTED) || (ebo->parent==NULL)) &&
2551                                          (ebo->flag & (BONE_SELECTED|BONE_ACTIVE)) )
2552                                 {
2553                                         /* set either end or start (end gets priority, unless it is already set) */
2554                                         if (bend == NULL)  {
2555                                                 bend= ebo;
2556                                                 bchild= child;
2557                                         }
2558                                         else 
2559                                                 bstart= ebo;
2560                                 }
2561                                 else {
2562                                         /* chain is broken... merge any continous segments then clear */
2563                                         if (bstart && bend)
2564                                                 bones_merge(bstart, bend, bchild, &chains);
2565                                         
2566                                         bstart = NULL;
2567                                         bend = NULL;
2568                                         bchild = NULL;
2569                                 }
2570                         }
2571                         
2572                         /* merge from bstart to bend if something not merged */
2573                         if (bstart && bend)
2574                                 bones_merge(bstart, bend, bchild, &chains);
2575                         
2576                         /* put back link */
2577                         BLI_insertlinkbefore(&chains, nchain, chain);
2578                 }               
2579                 
2580                 BLI_freelistN(&chains);
2581         }
2582         
2583         /* undo + updates */
2584         countall();
2585         allqueue(REDRAWVIEW3D, 0);
2586         allqueue(REDRAWBUTSEDIT, 0);
2587         BIF_undo_push("Merge Bones");
2588 }
2589
2590 /* ************** END Add/Remove stuff in editmode ************ */
2591 /* *************** Tools in editmode *********** */
2592
2593
2594 void hide_selected_armature_bones(void)
2595 {
2596         bArmature *arm= G.obedit->data;
2597         EditBone *ebone;
2598         
2599         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2600                 if (arm->layer & ebone->layer) {
2601                         if (ebone->flag & (BONE_SELECTED)) {
2602                                 ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
2603                                 ebone->flag |= BONE_HIDDEN_A;
2604                         }
2605                 }
2606         }
2607         countall();
2608         allqueue(REDRAWVIEW3D, 0);
2609         allqueue(REDRAWBUTSEDIT, 0);
2610         BIF_undo_push("Hide Bones");
2611 }
2612
2613 void hide_unselected_armature_bones(void)
2614 {
2615         EditBone *ebone;
2616         
2617         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2618                 bArmature *arm= G.obedit->data;
2619                 if (arm->layer & ebone->layer) {
2620                         if (ebone->flag & (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL));
2621                         else {
2622                                 ebone->flag &= ~BONE_ACTIVE;
2623                                 ebone->flag |= BONE_HIDDEN_A;
2624                         }
2625                 }
2626         }
2627         countall();
2628         allqueue(REDRAWVIEW3D, 0);
2629         allqueue(REDRAWBUTSEDIT, 0);
2630         BIF_undo_push("Hide Unselected Bones");
2631 }
2632
2633 void show_all_armature_bones(void)
2634 {
2635         EditBone *ebone;
2636         
2637         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2638                 bArmature *arm= G.obedit->data;
2639                 if(arm->layer & ebone->layer) {
2640                         if (ebone->flag & BONE_HIDDEN_A) {
2641                                 ebone->flag |= (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
2642                                 ebone->flag &= ~BONE_HIDDEN_A;
2643                         }
2644                 }
2645         }
2646         countall();
2647         allqueue(REDRAWVIEW3D, 0);
2648         allqueue(REDRAWBUTSEDIT, 0);
2649         BIF_undo_push("Reveal Bones");
2650 }
2651
2652 /* check for null, before calling! */
2653 static void bone_connect_to_existing_parent(EditBone *bone)
2654 {
2655         bone->flag |= BONE_CONNECTED;
2656         VECCOPY(bone->head, bone->parent->tail);
2657         bone->rad_head = bone->parent->rad_tail;
2658 }
2659
2660 static void bone_connect_to_new_parent(EditBone *selbone, EditBone *actbone, short mode)
2661 {
2662         EditBone *ebone;
2663         float offset[3];
2664         
2665         if ((selbone->parent) && (selbone->flag & BONE_CONNECTED))
2666                 selbone->parent->flag &= ~(BONE_TIPSEL);
2667         
2668         /* make actbone the parent of selbone */
2669         selbone->parent= actbone;
2670         
2671         /* in actbone tree we cannot have a loop */
2672         for (ebone= actbone->parent; ebone; ebone= ebone->parent) {
2673                 if (ebone->parent==selbone) {
2674                         ebone->parent= NULL;
2675                         ebone->flag &= ~BONE_CONNECTED;
2676                 }
2677         }
2678         
2679         if (mode == 1) {        
2680                 /* Connected: Child bones will be moved to the parent tip */
2681                 selbone->flag |= BONE_CONNECTED;
2682                 VecSubf(offset, actbone->tail, selbone->head);
2683                 
2684                 VECCOPY(selbone->head, actbone->tail);
2685                 selbone->rad_head= actbone->rad_tail;
2686                 
2687                 VecAddf(selbone->tail, selbone->tail, offset);
2688                 
2689                 /* offset for all its children */
2690                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2691                         EditBone *par;
2692                         
2693                         for (par= ebone->parent; par; par= par->parent) {
2694                                 if (par==selbone) {
2695                                         VecAddf(ebone->head, ebone->head, offset);
2696                                         VecAddf(ebone->tail, ebone->tail, offset);
2697                                         break;
2698                                 }
2699                         }
2700                 }
2701         }
2702         else {
2703                 /* Offset: Child bones will retain their distance from the parent tip */
2704                 selbone->flag &= ~BONE_CONNECTED;
2705         }
2706 }
2707
2708 void make_bone_parent(void)
2709 {
2710         bArmature *arm= G.obedit->data;
2711         EditBone *actbone, *ebone, *selbone;
2712         EditBone *flipbone, *flippar;
2713         short allchildbones= 0, foundselbone= 0;
2714         short val;
2715         
2716         /* find active bone to parent to */
2717         for (actbone = G.edbo.first; actbone; actbone=actbone->next) {
2718                 if (arm->layer & actbone->layer) {
2719                         if (actbone->flag & BONE_ACTIVE)
2720                                 break;
2721                 }
2722         }
2723         if (actbone == NULL) {
2724                 error("Needs an active bone");
2725                 return; 
2726         }
2727
2728         /* find selected bones */
2729         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2730                 if (arm->layer & ebone->layer) {
2731                         if ((ebone->flag & BONE_SELECTED) && (ebone != actbone)) {
2732                                 foundselbone++;
2733                                 if (ebone->parent != actbone) allchildbones= 1; 
2734                         }       
2735                 }
2736         }
2737         /* abort if no selected bones, and active bone doesn't have a parent to work with instead */
2738         if (foundselbone==0 && actbone->parent==NULL) {
2739                 error("Need selected bone(s)");
2740                 return;
2741         }
2742         
2743         /* 'Keep Offset' option is only displayed if it's likely to be useful */
2744         if (allchildbones)
2745                 val= pupmenu("Make Parent%t|Connected%x1|Keep Offset%x2");
2746         else
2747                 val= pupmenu("Make Parent%t|Connected%x1");
2748         
2749         if (val < 1) return;
2750
2751         if (foundselbone==0 && actbone->parent) {
2752                 /* When only the active bone is selected, and it has a parent,
2753                  * connect it to the parent, as that is the only possible outcome. 
2754                  */
2755                 bone_connect_to_existing_parent(actbone);
2756                 
2757                 if (arm->flag & ARM_MIRROR_EDIT) {
2758                         flipbone = armature_bone_get_mirrored(actbone);
2759                         if (flipbone)
2760                                 bone_connect_to_existing_parent(flipbone);
2761                 }
2762         }
2763         else {
2764                 /* loop through all editbones, parenting all selected bones to the active bone */
2765                 for (selbone = G.edbo.first; selbone; selbone=selbone->next) {
2766                         if (arm->layer & selbone->layer) {
2767                                 if ((selbone->flag & BONE_SELECTED) && (selbone!=actbone)) {
2768                                         /* parent selbone to actbone */
2769                                         bone_connect_to_new_parent(selbone, actbone, val);
2770                                         
2771                                         if (arm->flag & ARM_MIRROR_EDIT) {
2772                                                 /* - if there's a mirrored copy of selbone, try to find a mirrored copy of actbone 
2773                                                  *      (i.e.  selbone="child.L" and actbone="parent.L", find "child.R" and "parent.R").
2774                                                  *      This is useful for arm-chains, for example parenting lower arm to upper arm
2775                                                  * - if there's no mirrored copy of actbone (i.e. actbone = "parent.C" or "parent")
2776                                                  *      then just use actbone. Useful when doing upper arm to spine.
2777                                                  */
2778                                                 flipbone = armature_bone_get_mirrored(selbone);
2779                                                 flippar = armature_bone_get_mirrored(actbone);
2780                                                 
2781                                                 if (flipbone) {
2782                                                         if (flippar)
2783                                                                 bone_connect_to_new_parent(flipbone, flippar, val);
2784                                                         else
2785                                                                 bone_connect_to_new_parent(flipbone, actbone, val);
2786                                                 }
2787                                         }
2788                                 }
2789                         }
2790                 }
2791         }
2792
2793         countall(); /* checks selection */
2794         allqueue(REDRAWVIEW3D, 0);
2795         allqueue(REDRAWBUTSEDIT, 0);
2796         allqueue(REDRAWOOPS, 0);
2797         BIF_undo_push("Make Parent");
2798
2799         return;
2800 }
2801
2802 static void editbone_clear_parent(EditBone *ebone, int mode)
2803 {
2804         if (ebone->parent) {
2805                 /* for nice selection */
2806                 ebone->parent->flag &= ~(BONE_TIPSEL);
2807         }
2808         
2809         if (mode==1) ebone->parent= NULL;
2810         ebone->flag &= ~BONE_CONNECTED;
2811 }
2812
2813 void clear_bone_parent(void)
2814 {
2815         bArmature *arm= G.obedit->data;
2816         EditBone *ebone;
2817         EditBone *flipbone = NULL;
2818         short val;
2819         
2820         val= pupmenu("Clear Parent%t|Clear Parent%x1|Disconnect Bone%x2");
2821         if (val<1) return;
2822         
2823         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2824                 if (arm->layer & ebone->layer) {
2825                         if (ebone->flag & BONE_SELECTED) {
2826                                 if (arm->flag & ARM_MIRROR_EDIT)
2827                                         flipbone = armature_bone_get_mirrored(ebone);
2828                                         
2829                                 if (flipbone)
2830                                         editbone_clear_parent(flipbone, val);
2831                                 editbone_clear_parent(ebone, val);
2832                         }
2833                 }
2834         }
2835         
2836         countall(); // checks selection
2837         allqueue(REDRAWVIEW3D, 0);
2838         allqueue(REDRAWBUTSEDIT, 0);
2839         allqueue(REDRAWOOPS, 0);
2840         BIF_undo_push("Clear Parent");
2841 }
2842         
2843
2844 static EditBone *editbone_name_exists (ListBase *ebones, char *name)
2845 {
2846         EditBone        *eBone;
2847         
2848         if (ebones == NULL) ebones = &G.edbo;
2849         
2850         for (eBone=ebones->first; eBone; eBone=eBone->next) {
2851                 if (!strcmp(name, eBone->name))
2852                         return eBone;
2853         }
2854         return NULL;
2855 }
2856
2857 /* note: there's a unique_bone_name() too! */
2858 void unique_editbone_name (ListBase *ebones, char *name)
2859 {
2860         char            tempname[64];
2861         int                     number;
2862         char            *dot;
2863         
2864         if (editbone_name_exists(ebones, name)) {
2865                 /*      Strip off the suffix, if it's a number */
2866                 number= strlen(name);
2867                 if (number && isdigit(name[number-1])) {
2868                         dot= strrchr(name, '.');        // last occurrance
2869                         if (dot)
2870                                 *dot=0;
2871                 }
2872                 
2873                 for (number = 1; number <=999; number++) {
2874                         sprintf (tempname, "%s.%03d", name, number);
2875                         if (!editbone_name_exists(ebones, tempname)) {
2876                                 BLI_strncpy(name, tempname, 32);
2877                                 return;
2878                         }
2879                 }
2880         }
2881 }
2882
2883 /* context; editmode armature */
2884 /* if forked && mirror-edit: makes two bones with flipped names */
2885 void extrude_armature(int forked)
2886 {
2887         bArmature *arm= G.obedit->data;
2888         EditBone *newbone, *ebone, *flipbone, *first=NULL;
2889         int a, totbone= 0, do_extrude;
2890         
2891         TEST_EDITARMATURE;
2892         
2893         /* since we allow root extrude too, we have to make sure selection is OK */
2894         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2895                 if (arm->layer & ebone->layer) {
2896                         if (ebone->flag & BONE_ROOTSEL) {
2897                                 if (ebone->parent && (ebone->flag & BONE_CONNECTED)) {
2898                                         if (ebone->parent->flag & BONE_TIPSEL)
2899                                                 ebone->flag &= ~BONE_ROOTSEL;
2900                                 }
2901                         }
2902                 }
2903         }
2904         
2905         /* Duplicate the necessary bones */
2906         for (ebone = G.edbo.first; ((ebone) && (ebone!=first)); ebone=ebone->next) {
2907                 if (arm->layer & ebone->layer) {
2908                         /* we extrude per definition the tip */
2909                         do_extrude= 0;
2910                         if (ebone->flag & (BONE_TIPSEL|BONE_SELECTED))
2911                                 do_extrude= 1;
2912                         else if (ebone->flag & BONE_ROOTSEL) {
2913                                 /* but, a bone with parent deselected we do the root... */
2914                                 if (ebone->parent && (ebone->parent->flag & BONE_TIPSEL));
2915                                 else do_extrude= 2;
2916                         }
2917                         
2918                         if (do_extrude) {
2919                                 /* we re-use code for mirror editing... */
2920                                 flipbone= NULL;
2921                                 if(arm->flag & ARM_MIRROR_EDIT) {