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