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