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