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