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