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