merge with 2.5 at r18679
[blender.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 /* ************* XXX *************** */
103
104 /* **************** tools on Editmode Armature **************** */
105
106 /* Sync selection to parent for connected children */
107 static void armature_sync_selection(ListBase *edbo)
108 {
109         EditBone *ebo;
110         
111         for (ebo=edbo->first; ebo; ebo= ebo->next) {
112                 if ((ebo->flag & BONE_CONNECTED) && ebo->parent){
113                         if (ebo->parent->flag & BONE_TIPSEL)
114                                 ebo->flag |= BONE_ROOTSEL;
115                         else
116                                 ebo->flag &= ~BONE_ROOTSEL;
117                 }
118                 if ((ebo->flag & BONE_TIPSEL) && (ebo->flag & BONE_ROOTSEL))
119                         ebo->flag |= BONE_SELECTED;
120                 else
121                         ebo->flag &= ~BONE_SELECTED;
122         }                               
123 }
124
125 /* converts Bones to EditBone list, used for tools as well */
126 void make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent)
127 {
128         EditBone        *eBone;
129         Bone            *curBone;
130         float delta[3];
131         float premat[3][3];
132         float postmat[3][3];
133         float imat[3][3];
134         float difmat[3][3];
135                 
136         for (curBone=bones->first; curBone; curBone=curBone->next) {
137                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
138                 
139                 /*      Copy relevant data from bone to eBone */
140                 eBone->parent= parent;
141                 BLI_strncpy(eBone->name, curBone->name, 32);
142                 eBone->flag = curBone->flag;
143                 
144                 /* fix selection flags */
145                 if (eBone->flag & BONE_SELECTED) {
146                         eBone->flag |= BONE_TIPSEL;
147                         if (eBone->parent && (eBone->flag & BONE_CONNECTED))
148                                 eBone->parent->flag |= BONE_TIPSEL;
149                         else 
150                                 eBone->flag |= BONE_ROOTSEL;
151                 }
152                 else 
153                         eBone->flag &= ~BONE_ROOTSEL;
154                 
155                 VECCOPY(eBone->head, curBone->arm_head);
156                 VECCOPY(eBone->tail, curBone->arm_tail);                
157                 
158                 eBone->roll= 0.0;
159                 
160                 /* roll fixing */
161                 VecSubf(delta, eBone->tail, eBone->head);
162                 vec_roll_to_mat3(delta, 0.0, postmat);
163                 
164                 Mat3CpyMat4(premat, curBone->arm_mat);
165                 
166                 Mat3Inv(imat, postmat);
167                 Mat3MulMat3(difmat, imat, premat);
168                 
169                 eBone->roll = atan2(difmat[2][0], difmat[2][2]);
170                 
171                 /* rest of stuff copy */
172                 eBone->length= curBone->length;
173                 eBone->dist= curBone->dist;
174                 eBone->weight= curBone->weight;
175                 eBone->xwidth= curBone->xwidth;
176                 eBone->zwidth= curBone->zwidth;
177                 eBone->ease1= curBone->ease1;
178                 eBone->ease2= curBone->ease2;
179                 eBone->rad_head= curBone->rad_head;
180                 eBone->rad_tail= curBone->rad_tail;
181                 eBone->segments = curBone->segments;            
182                 eBone->layer = curBone->layer;
183                 
184                 BLI_addtail(edbo, eBone);
185                 
186                 /*      Add children if necessary */
187                 if (curBone->childbase.first) 
188                         make_boneList(edbo, &curBone->childbase, eBone);
189         }
190 }
191
192 /* nasty stuff for converting roll in editbones into bones */
193 /* also sets restposition in armature (arm_mat) */
194 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
195 {
196         Bone *curBone;
197         EditBone *ebone;
198         float premat[3][3];
199         float postmat[3][3];
200         float difmat[3][3];
201         float imat[3][3];
202         float delta[3];
203         
204         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
205                 /* sets local matrix and arm_mat (restpos) */
206                 where_is_armature_bone(curBone, curBone->parent);
207                 
208                 /* Find the associated editbone */
209                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
210                         if ((Bone*)ebone->temp == curBone)
211                                 break;
212                 
213                 if (ebone) {
214                         /* Get the ebone premat */
215                         VecSubf(delta, ebone->tail, ebone->head);
216                         vec_roll_to_mat3(delta, ebone->roll, premat);
217                         
218                         /* Get the bone postmat */
219                         Mat3CpyMat4(postmat, curBone->arm_mat);
220                         
221                         Mat3Inv(imat, premat);
222                         Mat3MulMat3(difmat, imat, postmat);
223 #if 0
224                         printf ("Bone %s\n", curBone->name);
225                         printmatrix4("premat", premat);
226                         printmatrix4("postmat", postmat);
227                         printmatrix4("difmat", difmat);
228                         printf ("Roll = %f\n",  (-atan2(difmat[2][0], difmat[2][2]) * (180.0/M_PI)));
229 #endif
230                         curBone->roll = -atan2(difmat[2][0], difmat[2][2]);
231                         
232                         /* and set restposition again */
233                         where_is_armature_bone(curBone, curBone->parent);
234                 }
235                 fix_bonelist_roll(&curBone->childbase, editbonelist);
236         }
237 }
238
239 /* put EditMode back in Object */
240 void ED_armature_from_edit(Scene *scene, Object *obedit)
241 {
242         bArmature *arm= obedit->data;
243         EditBone *eBone, *neBone;
244         Bone    *newBone;
245         Object *obt;
246         
247         /* armature bones */
248         free_bones(arm);
249         
250         /* remove zero sized bones, this gives instable restposes */
251         for (eBone=arm->edbo->first; eBone; eBone= neBone) {
252                 float len= VecLenf(eBone->head, eBone->tail);
253                 neBone= eBone->next;
254                 if (len <= 0.000001f) {         /* FLT_EPSILON is too large? */
255                         EditBone *fBone;
256                         
257                         /*      Find any bones that refer to this bone  */
258                         for (fBone=arm->edbo->first; fBone; fBone= fBone->next) {
259                                 if (fBone->parent==eBone)
260                                         fBone->parent= eBone->parent;
261                         }
262                         printf("Warning: removed zero sized bone: %s\n", eBone->name);
263                         BLI_freelinkN(arm->edbo, eBone);
264                 }
265         }
266         
267         /*      Copy the bones from the editData into the armature */
268         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
269                 newBone= MEM_callocN(sizeof(Bone), "bone");
270                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
271                 
272                 BLI_strncpy(newBone->name, eBone->name, 32);
273                 memcpy(newBone->head, eBone->head, sizeof(float)*3);
274                 memcpy(newBone->tail, eBone->tail, sizeof(float)*3);
275                 newBone->flag= eBone->flag;
276                 if (eBone->flag & BONE_ACTIVE) 
277                         newBone->flag |= BONE_SELECTED; /* important, editbones can be active with only 1 point selected */
278                 newBone->roll = 0.0f;
279                 
280                 newBone->weight = eBone->weight;
281                 newBone->dist = eBone->dist;
282                 
283                 newBone->xwidth = eBone->xwidth;
284                 newBone->zwidth = eBone->zwidth;
285                 newBone->ease1= eBone->ease1;
286                 newBone->ease2= eBone->ease2;
287                 newBone->rad_head= eBone->rad_head;
288                 newBone->rad_tail= eBone->rad_tail;
289                 newBone->segments= eBone->segments;
290                 newBone->layer = eBone->layer;
291         }
292         
293         /*      Fix parenting in a separate pass to ensure ebone->bone connections
294                 are valid at this point */
295         for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
296                 newBone= (Bone *)eBone->temp;
297                 if (eBone->parent) {
298                         newBone->parent= (Bone *)eBone->parent->temp;
299                         BLI_addtail(&newBone->parent->childbase, newBone);
300                         
301                         {
302                                 float M_boneRest[3][3];
303                                 float M_parentRest[3][3];
304                                 float iM_parentRest[3][3];
305                                 float   delta[3];
306                                 
307                                 /* Get the parent's  matrix (rotation only) */
308                                 VecSubf(delta, eBone->parent->tail, eBone->parent->head);
309                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
310                                 
311                                 /* Get this bone's  matrix (rotation only) */
312                                 VecSubf(delta, eBone->tail, eBone->head);
313                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
314                                 
315                                 /* Invert the parent matrix */
316                                 Mat3Inv(iM_parentRest, M_parentRest);
317                                 
318                                 /* Get the new head and tail */
319                                 VecSubf(newBone->head, eBone->head, eBone->parent->tail);
320                                 VecSubf(newBone->tail, eBone->tail, eBone->parent->tail);
321                                 
322                                 Mat3MulVecfl(iM_parentRest, newBone->head);
323                                 Mat3MulVecfl(iM_parentRest, newBone->tail);
324                         }
325                 }
326                 /*      ...otherwise add this bone to the armature's bonebase */
327                 else
328                         BLI_addtail(&arm->bonebase, newBone);
329         }
330         
331         /* Make a pass through the new armature to fix rolling */
332         /* also builds restposition again (like where_is_armature) */
333         fix_bonelist_roll(&arm->bonebase, arm->edbo);
334         
335         /* so all users of this armature should get rebuilt */
336         for (obt= G.main->object.first; obt; obt= obt->id.next) {
337                 if (obt->data==arm)
338                         armature_rebuild_pose(obt, arm);
339         }
340         
341         DAG_object_flush_update(scene, obedit, OB_RECALC_DATA);
342 }
343
344
345
346 void apply_rot_armature (Scene *scene, Object *ob, float mat[3][3])
347 {
348         EditBone *ebone;
349         bArmature *arm= ob->data;
350         float scale = Mat3ToScalef(mat);        /* store the scale of the matrix here to use on envelopes */
351         
352         /* Put the armature into editmode */
353         ED_armature_to_edit(ob);
354
355         /* Do the rotations */
356         for (ebone = arm->edbo->first; ebone; ebone=ebone->next){
357                 Mat3MulVecfl(mat, ebone->head);
358                 Mat3MulVecfl(mat, ebone->tail);
359                 
360                 ebone->rad_head *= scale;
361                 ebone->rad_tail *= scale;
362                 ebone->dist             *= scale;
363         }
364         
365         /* Turn the list into an armature */
366         ED_armature_from_edit(scene, ob);
367         ED_armature_edit_free(ob);
368 }
369
370 /* 0 == do center, 1 == center new, 2 == center cursor */
371 void docenter_armature (Scene *scene, View3D *v3d, Object *ob, int centermode)
372 {
373         Object *obedit= scene->obedit; // XXX get from context
374         EditBone *ebone;
375         bArmature *arm= ob->data;
376         float cent[3] = {0.0f, 0.0f, 0.0f};
377         float min[3], max[3];
378         float omat[3][3];
379
380         /* Put the armature into editmode */
381         if(ob!=obedit)
382                 ED_armature_to_edit(ob);
383
384         /* Find the centerpoint */
385         if (centermode == 2) {
386                 float *fp= give_cursor(scene, v3d);
387                 VECCOPY(cent, fp);
388                 Mat4Invert(ob->imat, ob->obmat);
389                 Mat4MulVecfl(ob->imat, cent);
390         }
391         else {
392                 INIT_MINMAX(min, max);
393                 
394                 for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
395                         DO_MINMAX(ebone->head, min, max);
396                         DO_MINMAX(ebone->tail, min, max);
397                 }
398                 
399                 cent[0]= (min[0]+max[0])/2.0f;
400                 cent[1]= (min[1]+max[1])/2.0f;
401                 cent[2]= (min[2]+max[2])/2.0f;
402         }
403         
404         /* Do the adjustments */
405         for (ebone= arm->edbo->first; ebone; ebone=ebone->next){
406                 VecSubf(ebone->head, ebone->head, cent);
407                 VecSubf(ebone->tail, ebone->tail, cent);
408         }
409         
410         /* Turn the list into an armature */
411         ED_armature_from_edit(scene, ob);
412         
413         /* Adjust object location for new centerpoint */
414         if(centermode && obedit==NULL) {
415                 Mat3CpyMat4(omat, ob->obmat);
416                 
417                 Mat3MulVecfl(omat, cent);
418                 ob->loc[0]+= cent[0];
419                 ob->loc[1]+= cent[1];
420                 ob->loc[2]+= cent[2];
421         }
422         else 
423                 ED_armature_edit_free(ob);
424 }
425
426 /* helper for apply_armature_pose2bones - fixes parenting of objects that are bone-parented to armature */
427 static void applyarmature_fix_boneparents (Scene *scene, Object *armob)
428 {
429         Object workob, *ob;
430         
431         /* go through all objects in database */
432         for (ob= G.main->object.first; ob; ob= ob->id.next) {
433                 /* if parent is bone in this armature, apply corrections */
434                 if ((ob->parent == armob) && (ob->partype == PARBONE)) {
435                         /* apply current transform from parent (not yet destroyed), 
436                          * then calculate new parent inverse matrix
437                          */
438                         ED_object_apply_obmat(ob);
439                         
440                         what_does_parent(scene, ob, &workob);
441                         Mat4Invert(ob->parentinv, workob.obmat);
442                 }
443         }
444 }
445
446 static EditBone *editbone_name_exists (ListBase *edbo, char *name)
447 {
448         EditBone        *eBone;
449         
450         for (eBone=edbo->first; eBone; eBone=eBone->next) {
451                 if (!strcmp(name, eBone->name))
452                         return eBone;
453         }
454         return NULL;
455 }
456
457 /* note: there's a unique_bone_name() too! */
458 void unique_editbone_name (ListBase *edbo, char *name)
459 {
460         char            tempname[64];
461         int                     number;
462         char            *dot;
463         
464         if (editbone_name_exists(edbo, name)) {
465                 /*      Strip off the suffix, if it's a number */
466                 number= strlen(name);
467                 if (number && isdigit(name[number-1])) {
468                         dot= strrchr(name, '.');        // last occurrance
469                         if (dot)
470                                 *dot=0;
471                 }
472                 
473                 for (number = 1; number <=999; number++) {
474                         sprintf(tempname, "%s.%03d", name, number);
475                         if (!editbone_name_exists(edbo, tempname)) {
476                                 BLI_strncpy(name, tempname, 32);
477                                 return;
478                         }
479                 }
480         }
481 }
482
483 /* set the current pose as the restpose */
484 void apply_armature_pose2bones(Scene *scene, Object *obedit)
485 {
486         bArmature *arm= obedit->data;
487         bPose *pose;
488         bPoseChannel *pchan;
489         EditBone *curbone;
490         
491         /* don't check if editmode (should be done by caller) */
492         if (object_data_is_libdata(obedit)) {
493                 error_libdata();
494                 return;
495         }
496         
497         /* helpful warnings... */
498         // TODO: add warnings to be careful about actions, applying deforms first, etc.
499         
500         /* Get editbones of active armature to alter */
501         ED_armature_to_edit(obedit);    
502         
503         /* get pose of active object and move it out of posemode */
504         pose= obedit->pose;
505         
506         for (pchan=pose->chanbase.first; pchan; pchan=pchan->next) {
507                 curbone= editbone_name_exists(arm->edbo, pchan->name);
508                 
509                 /* simply copy the head/tail values from pchan over to curbone */
510                 VECCOPY(curbone->head, pchan->pose_head);
511                 VECCOPY(curbone->tail, pchan->pose_tail);
512                 
513                 /* fix roll:
514                  *      1. find auto-calculated roll value for this bone now
515                  *      2. remove this from the 'visual' y-rotation
516                  */
517                 {
518                         float premat[3][3], imat[3][3],pmat[3][3], tmat[3][3];
519                         float delta[3], eul[3];
520                         
521                         /* obtain new auto y-rotation */
522                         VecSubf(delta, curbone->tail, curbone->head);
523                         vec_roll_to_mat3(delta, 0.0, premat);
524                         Mat3Inv(imat, premat);
525                         
526                         /* get pchan 'visual' matrix */
527                         Mat3CpyMat4(pmat, pchan->pose_mat);
528                         
529                         /* remove auto from visual and get euler rotation */
530                         Mat3MulMat3(tmat, imat, pmat);
531                         Mat3ToEul(tmat, eul);
532                         
533                         /* just use this euler-y as new roll value */
534                         curbone->roll= eul[1];
535                 }
536                 
537                 /* clear transform values for pchan */
538                 pchan->loc[0]= pchan->loc[1]= pchan->loc[2]= 0;
539                 pchan->quat[1]= pchan->quat[2]= pchan->quat[3]= 0;
540                 pchan->quat[0]= pchan->size[0]= pchan->size[1]= pchan->size[2]= 1;
541                 
542                 /* set anim lock */
543                 curbone->flag |= BONE_UNKEYED;
544         }
545         
546         /* convert editbones back to bones */
547         ED_armature_from_edit(scene, obedit);
548         
549         /* flush positions of posebones */
550         where_is_pose(scene, obedit);
551         
552         /* fix parenting of objects which are bone-parented */
553         applyarmature_fix_boneparents(scene, obedit);
554         
555         BIF_undo_push("Apply new restpose");
556 }
557
558
559 /* Helper function for armature joining - link fixing */
560 static void joined_armature_fix_links(Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
561 {
562         Object *ob;
563         bPose *pose;
564         bPoseChannel *pchant;
565         bConstraint *con;
566         
567         /* let's go through all objects in database */
568         for (ob= G.main->object.first; ob; ob= ob->id.next) {
569                 /* do some object-type specific things */
570                 if (ob->type == OB_ARMATURE) {
571                         pose= ob->pose;
572                         for (pchant= pose->chanbase.first; pchant; pchant= pchant->next) {
573                                 for (con= pchant->constraints.first; con; con= con->next) {
574                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
575                                         ListBase targets = {NULL, NULL};
576                                         bConstraintTarget *ct;
577                                         
578                                         /* constraint targets */
579                                         if (cti && cti->get_constraint_targets) {
580                                                 cti->get_constraint_targets(con, &targets);
581                                                 
582                                                 for (ct= targets.first; ct; ct= ct->next) {
583                                                         if (ct->tar == srcArm) {
584                                                                 if (strcmp(ct->subtarget, "")==0) {
585                                                                         ct->tar = tarArm;
586                                                                 }
587                                                                 else if (strcmp(ct->subtarget, pchan->name)==0) {
588                                                                         ct->tar = tarArm;
589                                                                         strcpy(ct->subtarget, curbone->name);
590                                                                 }
591                                                         }
592                                                 }
593                                                 
594                                                 if (cti->flush_constraint_targets)
595                                                         cti->flush_constraint_targets(con, &targets, 0);
596                                         }
597                                         
598                                         /* action constraint? */
599                                         if (con->type == CONSTRAINT_TYPE_ACTION) {
600                                                 bActionConstraint *data= con->data; // XXX old animation system
601                                                 bAction *act;
602                                                 bActionChannel *achan;
603                                                 
604                                                 if (data->act) {
605                                                         act= data->act;
606                                                         
607                                                         for (achan= act->chanbase.first; achan; achan= achan->next) {
608                                                                 if (strcmp(achan->name, pchan->name)==0)
609                                                                         BLI_strncpy(achan->name, curbone->name, 32);
610                                                         }
611                                                 }
612                                         }
613                                         
614                                 }
615                         }
616                 }
617                         
618                 /* fix object-level constraints */
619                 if (ob != srcArm) {
620                         for (con= ob->constraints.first; con; con= con->next) {
621                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
622                                 ListBase targets = {NULL, NULL};
623                                 bConstraintTarget *ct;
624                                 
625                                 /* constraint targets */
626                                 if (cti && cti->get_constraint_targets) {
627                                         cti->get_constraint_targets(con, &targets);
628                                         
629                                         for (ct= targets.first; ct; ct= ct->next) {
630                                                 if (ct->tar == srcArm) {
631                                                         if (strcmp(ct->subtarget, "")==0) {
632                                                                 ct->tar = tarArm;
633                                                         }
634                                                         else if (strcmp(ct->subtarget, pchan->name)==0) {
635                                                                 ct->tar = tarArm;
636                                                                 strcpy(ct->subtarget, curbone->name);
637                                                         }
638                                                 }
639                                         }
640                                         
641                                         if (cti->flush_constraint_targets)
642                                                 cti->flush_constraint_targets(con, &targets, 0);
643                                 }
644                         }
645                 }
646                 
647                 /* See if an object is parented to this armature */
648                 if (ob->parent && (ob->parent == srcArm)) {
649                         /* Is object parented to a bone of this src armature? */
650                         if (ob->partype==PARBONE) {
651                                 /* bone name in object */
652                                 if (!strcmp(ob->parsubstr, pchan->name))
653                                         BLI_strncpy(ob->parsubstr, curbone->name, 32);
654                         }
655                         
656                         /* make tar armature be new parent */
657                         ob->parent = tarArm;
658                 }
659         }       
660 }
661
662 int join_armature(Scene *scene, View3D *v3d)
663 {
664         Object  *ob= scene->basact->object; // XXX context
665         bArmature *arm= ob->data;
666         Base    *base, *nextbase;
667         bPose *pose, *opose;
668         bPoseChannel *pchan, *pchann;
669         EditBone *curbone;
670         float   mat[4][4], oimat[4][4];
671         
672         /*      Ensure we're not in editmode and that the active object is an armature*/
673         if (ob->type!=OB_ARMATURE) return 0;
674         if(arm->edbo) return 0;
675         
676         if (object_data_is_libdata(ob)) {
677                 error_libdata();
678                 return 0;
679         }
680         
681         /* Get editbones of active armature to add editbones to */
682         ED_armature_to_edit(ob);
683         
684         /* get pose of active object and move it out of posemode */
685         pose= ob->pose;
686         ob->flag &= ~OB_POSEMODE;
687         
688         for (base=FIRSTBASE; base; base=nextbase) {
689                 nextbase = base->next;
690                 if (TESTBASE(v3d, base)){
691                         if ((base->object->type==OB_ARMATURE) && (base->object!=ob)) {
692                                 bArmature *curarm= base->object->data;
693                                 
694                                 /* Make a list of editbones in current armature */
695                                 ED_armature_to_edit(base->object);
696                                 
697                                 /* Get Pose of current armature */
698                                 opose= base->object->pose;
699                                 base->object->flag &= ~OB_POSEMODE;
700                                 BASACT->flag &= ~OB_POSEMODE;
701                                 
702                                 /* Find the difference matrix */
703                                 Mat4Invert(oimat, ob->obmat);
704                                 Mat4MulMat4(mat, base->object->obmat, oimat);
705                                 
706                                 /* Copy bones and posechannels from the object to the edit armature */
707                                 for (pchan=opose->chanbase.first; pchan; pchan=pchann) {
708                                         pchann= pchan->next;
709                                         curbone= editbone_name_exists(curarm->edbo, pchan->name);
710                                         
711                                         /* Get new name */
712                                         unique_editbone_name(arm->edbo, curbone->name);
713                                         
714                                         /* Transform the bone */
715                                         {
716                                                 float premat[4][4];
717                                                 float postmat[4][4];
718                                                 float difmat[4][4];
719                                                 float imat[4][4];
720                                                 float temp[3][3];
721                                                 float delta[3];
722                                                 
723                                                 /* Get the premat */
724                                                 VecSubf(delta, curbone->tail, curbone->head);
725                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
726                                                 
727                                                 Mat4MulMat34(premat, temp, mat);
728                                                 
729                                                 Mat4MulVecfl(mat, curbone->head);
730                                                 Mat4MulVecfl(mat, curbone->tail);
731                                                 
732                                                 /* Get the postmat */
733                                                 VecSubf(delta, curbone->tail, curbone->head);
734                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
735                                                 Mat4CpyMat3(postmat, temp);
736                                                 
737                                                 /* Find the roll */
738                                                 Mat4Invert(imat, premat);
739                                                 Mat4MulMat4(difmat, postmat, imat);
740                                                 
741                                                 curbone->roll -= atan2(difmat[2][0], difmat[2][2]);
742                                         }
743                                         
744                                         /* Fix Constraints and Other Links to this Bone and Armature */
745                                         joined_armature_fix_links(ob, base->object, pchan, curbone);
746                                         
747                                         /* Rename pchan */
748                                         BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
749                                         
750                                         /* Jump Ship! */
751                                         BLI_remlink(curarm->edbo, curbone);
752                                         BLI_addtail(arm->edbo, curbone);
753                                         
754                                         BLI_remlink(&opose->chanbase, pchan);
755                                         BLI_addtail(&pose->chanbase, pchan);
756                                 }
757                                 
758                                 ED_base_object_free_and_unlink(scene, base);
759                         }
760                 }
761         }
762         
763         DAG_scene_sort(scene);  // because we removed object(s)
764
765         ED_armature_from_edit(scene, ob);
766         ED_armature_edit_free(ob);
767         
768         return 1;
769 }
770
771 /* Helper function for armature separating - link fixing */
772 static void separated_armature_fix_links(Object *origArm, Object *newArm)
773 {
774         Object *ob;
775         bPoseChannel *pchan, *pcha, *pchb;
776         bConstraint *con;
777         ListBase *opchans, *npchans;
778         
779         /* get reference to list of bones in original and new armatures  */
780         opchans= &origArm->pose->chanbase;
781         npchans= &newArm->pose->chanbase;
782         
783         /* let's go through all objects in database */
784         for (ob= G.main->object.first; ob; ob= ob->id.next) {
785                 /* do some object-type specific things */
786                 if (ob->type == OB_ARMATURE) {
787                         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
788                                 for (con= pchan->constraints.first; con; con= con->next) {
789                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
790                                         ListBase targets = {NULL, NULL};
791                                         bConstraintTarget *ct;
792                                         
793                                         /* constraint targets */
794                                         if (cti && cti->get_constraint_targets) {
795                                                 cti->get_constraint_targets(con, &targets);
796                                                 
797                                                 for (ct= targets.first; ct; ct= ct->next) {
798                                                         /* any targets which point to original armature are redirected to the new one only if:
799                                                          *      - the target isn't origArm/newArm itself
800                                                          *      - the target is one that can be found in newArm/origArm
801                                                          */
802                                                         if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
803                                                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
804                                                                         /* check if either one matches */
805                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
806                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
807                                                                         {
808                                                                                 ct->tar= newArm;
809                                                                                 break;
810                                                                         }
811                                                                         
812                                                                         /* check if both ends have met (to stop checking) */
813                                                                         if (pcha == pchb) break;
814                                                                 }                                                               
815                                                         }
816                                                         else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
817                                                                 for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
818                                                                         /* check if either one matches */
819                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
820                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
821                                                                         {
822                                                                                 ct->tar= origArm;
823                                                                                 break;
824                                                                         }
825                                                                         
826                                                                         /* check if both ends have met (to stop checking) */
827                                                                         if (pcha == pchb) break;
828                                                                 }                                                               
829                                                         }
830                                                 }
831                                                 
832                                                 if (cti->flush_constraint_targets)
833                                                         cti->flush_constraint_targets(con, &targets, 0);
834                                         }
835                                 }
836                         }
837                 }
838                         
839                 /* fix object-level constraints */
840                 if (ob != origArm) {
841                         for (con= ob->constraints.first; con; con= con->next) {
842                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
843                                 ListBase targets = {NULL, NULL};
844                                 bConstraintTarget *ct;
845                                 
846                                 /* constraint targets */
847                                 if (cti && cti->get_constraint_targets) {
848                                         cti->get_constraint_targets(con, &targets);
849                                         
850                                         for (ct= targets.first; ct; ct= ct->next) {
851                                                 /* any targets which point to original armature are redirected to the new one only if:
852                                                  *      - the target isn't origArm/newArm itself
853                                                  *      - the target is one that can be found in newArm/origArm
854                                                  */
855                                                 if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
856                                                         for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
857                                                                 /* check if either one matches */
858                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
859                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
860                                                                 {
861                                                                         ct->tar= newArm;
862                                                                         break;
863                                                                 }
864                                                                 
865                                                                 /* check if both ends have met (to stop checking) */
866                                                                 if (pcha == pchb) break;
867                                                         }                                                               
868                                                 }
869                                                 else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
870                                                         for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
871                                                                 /* check if either one matches */
872                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
873                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
874                                                                 {
875                                                                         ct->tar= origArm;
876                                                                         break;
877                                                                 }
878                                                                 
879                                                                 /* check if both ends have met (to stop checking) */
880                                                                 if (pcha == pchb) break;
881                                                         }                                                               
882                                                 }
883                                         }
884                                         
885                                         if (cti->flush_constraint_targets)
886                                                 cti->flush_constraint_targets(con, &targets, 0);
887                                 }
888                         }
889                 }
890                 
891                 /* See if an object is parented to this armature */
892                 if ((ob->parent) && (ob->parent == origArm)) {
893                         /* Is object parented to a bone of this src armature? */
894                         if (ob->partype==PARBONE) {
895                                 /* bone name in object */
896                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
897                                         /* check if either one matches */
898                                         if ( (strcmp(pcha->name, ob->parsubstr)==0) ||
899                                                  (strcmp(pchb->name, ob->parsubstr)==0) )
900                                         {
901                                                 ob->parent= newArm;
902                                                 break;
903                                         }
904                                         
905                                         /* check if both ends have met (to stop checking) */
906                                         if (pcha == pchb) break;
907                                 }
908                         }
909                 }
910         }       
911 }
912
913 /* Helper function for armature separating - remove certain bones from the given armature 
914  *      sel: remove selected bones from the armature, otherwise the unselected bones are removed
915  *  (ob is not in editmode)
916  */
917 static void separate_armature_bones (Scene *scene, Object *ob, short sel) 
918 {
919         bArmature *arm= (bArmature *)ob->data;
920         bPoseChannel *pchan, *pchann;
921         EditBone *curbone;
922         
923         /* make local set of editbones to manipulate here */
924         ED_armature_to_edit(ob);
925         
926         /* go through pose-channels, checking if a bone should be removed */
927         for (pchan=ob->pose->chanbase.first; pchan; pchan=pchann) {
928                 pchann= pchan->next;
929                 curbone= editbone_name_exists(arm->edbo, pchan->name);
930                 
931                 /* check if bone needs to be removed */
932                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
933                          (!sel && !(curbone->flag & BONE_SELECTED)) )
934                 {
935                         EditBone *ebo;
936                         bPoseChannel *pchn;
937                         
938                         /* clear the bone->parent var of any bone that had this as its parent  */
939                         for (ebo= arm->edbo->first; ebo; ebo= ebo->next) {
940                                 if (ebo->parent == curbone) {
941                                         ebo->parent= NULL;
942                                         ebo->temp= NULL; /* this is needed to prevent random crashes with in ED_armature_from_edit */
943                                         ebo->flag &= ~BONE_CONNECTED;
944                                 }
945                         }
946                         
947                         /* clear the pchan->parent var of any pchan that had this as its parent */
948                         for (pchn= ob->pose->chanbase.first; pchn; pchn=pchn->next) {
949                                 if (pchn->parent == pchan)
950                                         pchn->parent= NULL;
951                         }
952                         
953                         /* free any of the extra-data this pchan might have */
954                         if (pchan->path) MEM_freeN(pchan->path);
955                         free_constraints(&pchan->constraints);
956                         
957                         /* get rid of unneeded bone */
958                         BLI_freelinkN(arm->edbo, curbone);
959                         BLI_freelinkN(&ob->pose->chanbase, pchan);
960                 }
961         }
962         
963         /* exit editmode (recalculates pchans too) */
964         ED_armature_from_edit(scene, ob);
965         ED_armature_edit_free(ob);
966 }
967
968 /* separate selected bones into their armature */
969 void separate_armature (Scene *scene, View3D *v3d)
970 {
971         Object *obedit= scene->obedit; // XXX get from context
972         Object *oldob, *newob;
973         Base *base, *oldbase, *newbase;
974         bArmature *arm;
975         
976         if ( okee("Separate")==0 ) return;
977
978         waitcursor(1);
979         
980         arm= obedit->data;
981         
982         /* we are going to do this as follows (unlike every other instance of separate):
983          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
984          *      2. duplicate base - BASACT is the new one now
985          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
986          *      4. fix constraint links
987          *      5. make original armature active and enter editmode
988          */
989         
990         /* 1) only edit-base selected */
991         base= FIRSTBASE;
992         for (base= FIRSTBASE; base; base= base->next) {
993                 if (base->lay & v3d->lay) {
994                         if (base->object==obedit) base->flag |= 1;
995                         else base->flag &= ~1;
996                 }
997         }
998         
999         /* 1) store starting settings and exit editmode */
1000         oldob= obedit;
1001         oldbase= BASACT;
1002         oldob->flag &= ~OB_POSEMODE;
1003         oldbase->flag &= ~OB_POSEMODE;
1004         
1005         ED_armature_from_edit(scene, obedit);
1006         ED_armature_edit_free(obedit);
1007         
1008         /* 2) duplicate base */
1009         adduplicate(1, USER_DUP_ARM); /* no transform and zero so do get a linked dupli */
1010         
1011         newbase= BASACT; /* basact is set in adduplicate() */
1012         newob= newbase->object;         
1013         newbase->flag &= ~SELECT;
1014         
1015         
1016         /* 3) remove bones that shouldn't still be around on both armatures */
1017         separate_armature_bones(scene, oldob, 1);
1018         separate_armature_bones(scene, newob, 0);
1019         
1020         
1021         /* 4) fix links before depsgraph flushes */ // err... or after?
1022         separated_armature_fix_links(oldob, newob);
1023         
1024         DAG_object_flush_update(scene, oldob, OB_RECALC_DATA);  /* this is the original one */
1025         DAG_object_flush_update(scene, newob, OB_RECALC_DATA);  /* this is the separated one */
1026         
1027         
1028         /* 5) restore original conditions */
1029         obedit= oldob;
1030         BASACT= oldbase;
1031         BASACT->flag |= SELECT;
1032         
1033         ED_armature_to_edit(obedit);
1034         
1035         /* recalc/redraw + cleanup */
1036         waitcursor(0);
1037
1038         countall(); // flush!
1039         
1040         BIF_undo_push("Separate Armature");
1041 }
1042
1043 /* **************** END tools on Editmode Armature **************** */
1044 /* **************** PoseMode & EditMode *************************** */
1045
1046 /* only for opengl selection indices */
1047 Bone *get_indexed_bone (Object *ob, int index)
1048 {
1049         bPoseChannel *pchan;
1050         int a= 0;
1051         
1052         if(ob->pose==NULL) return NULL;
1053         index>>=16;             // bone selection codes use left 2 bytes
1054         
1055         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
1056                 if(a==index) return pchan->bone;
1057         }
1058         return NULL;
1059 }
1060
1061 /* See if there are any selected bones in this buffer */
1062 /* only bones from base are checked on */
1063 static void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short findunsel)
1064 {
1065         Object *obedit= scene->obedit; // XXX get from context
1066         Bone *bone;
1067         EditBone *ebone;
1068         void *firstunSel=NULL, *firstSel=NULL, *data;
1069         unsigned int hitresult;
1070         short i, takeNext=0, sel;
1071         
1072         for (i=0; i< hits; i++){
1073                 hitresult = buffer[3+(i*4)];
1074                 
1075                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
1076                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
1077                                 
1078                                 hitresult &= ~(BONESEL_ANY);
1079                                 /* Determine what the current bone is */
1080                                 if (obedit==NULL || base->object!=obedit) {
1081                                         /* no singular posemode, so check for correct object */
1082                                         if(base->selcol == (hitresult & 0xFFFF)) {
1083                                                 bone = get_indexed_bone(base->object, hitresult);
1084
1085                                                 if (findunsel)
1086                                                         sel = (bone->flag & BONE_SELECTED);
1087                                                 else
1088                                                         sel = !(bone->flag & BONE_SELECTED);
1089                                                 
1090                                                 data = bone;
1091                                         }
1092                                         else {
1093                                                 data= NULL;
1094                                                 sel= 0;
1095                                         }
1096                                 }
1097                                 else{
1098                                         bArmature *arm= obedit->data;
1099                                         
1100                                         ebone = BLI_findlink(arm->edbo, hitresult);
1101                                         if (findunsel)
1102                                                 sel = (ebone->flag & BONE_SELECTED);
1103                                         else
1104                                                 sel = !(ebone->flag & BONE_SELECTED);
1105                                         
1106                                         data = ebone;
1107                                 }
1108                                 
1109                                 if(data) {
1110                                         if (sel) {
1111                                                 if(!firstSel) firstSel= data;
1112                                                 takeNext=1;
1113                                         }
1114                                         else {
1115                                                 if (!firstunSel)
1116                                                         firstunSel=data;
1117                                                 if (takeNext)
1118                                                         return data;
1119                                         }
1120                                 }
1121                         }
1122                 }
1123         }
1124         
1125         if (firstunSel)
1126                 return firstunSel;
1127         else 
1128                 return firstSel;
1129 }
1130
1131
1132
1133 /* used by posemode as well editmode */
1134 /* only checks scene->basact! */
1135 static void *get_nearest_bone (bContext *C, short findunsel)
1136 {
1137         ViewContext vc;
1138         rcti rect;
1139         unsigned int buffer[MAXPICKBUF];
1140         short hits;
1141         
1142         view3d_set_viewcontext(C, &vc);
1143         
1144         // rect.xmin= ... mouseco!
1145         
1146         glInitNames();
1147         hits= view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
1148
1149         if (hits>0)
1150                 return get_bone_from_selectbuffer(vc.scene, vc.scene->basact, buffer, hits, findunsel);
1151         
1152         return NULL;
1153 }
1154
1155 /* helper for setflag_sel_bone() */
1156 static void bone_setflag (int *bone, int flag, short mode)
1157 {
1158         if (bone && flag) {
1159                 /* exception for inverse flags */
1160                 if (flag == BONE_NO_DEFORM) {
1161                         if (mode == 2)
1162                                 *bone |= flag;
1163                         else if (mode == 1)
1164                                 *bone &= ~flag;
1165                         else
1166                                 *bone ^= flag;
1167
1168                 }
1169                 else {
1170                         if (mode == 2)
1171                                 *bone &= ~flag;
1172                         else if (mode == 1)
1173                                 *bone |= flag;
1174                         else
1175                                 *bone ^= flag;
1176                 }
1177         }
1178 }
1179
1180 /* Get the first available child of an editbone */
1181 static EditBone *editbone_get_child(bArmature *arm, EditBone *pabone, short use_visibility)
1182 {
1183         EditBone *curbone, *chbone=NULL;
1184         
1185         for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1186                 if (curbone->parent == pabone) {
1187                         if (use_visibility) {
1188                                 if ((arm->layer & curbone->layer) && !(pabone->flag & BONE_HIDDEN_A))
1189                                         chbone = curbone;
1190                         }
1191                         else
1192                                 chbone = curbone;
1193                 }
1194         }
1195         
1196         return chbone;
1197 }
1198
1199 void armature_select_hierarchy(Scene *scene, short direction, short add_to_sel)
1200 {
1201         Object *obedit= scene->obedit; // XXX get from context
1202         Object *ob;
1203         bArmature *arm;
1204         EditBone *curbone, *pabone, *chbone;
1205
1206         if (!obedit) return;
1207         else ob= obedit;
1208         arm= (bArmature *)ob->data;
1209         
1210         for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1211                 if (EBONE_VISIBLE(arm, curbone)) {
1212                         if (curbone->flag & (BONE_ACTIVE)) {
1213                                 if (direction == BONE_SELECT_PARENT) {
1214                                         if (curbone->parent == NULL) continue;
1215                                         else pabone = curbone->parent;
1216                                         
1217                                         if (EBONE_VISIBLE(arm, pabone)) {
1218                                                 pabone->flag |= (BONE_ACTIVE|BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1219                                                 if (pabone->parent)     pabone->parent->flag |= BONE_TIPSEL;
1220                                                 
1221                                                 if (!add_to_sel) curbone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1222                                                 curbone->flag &= ~BONE_ACTIVE;
1223                                                 break;
1224                                         }
1225                                         
1226                                 } 
1227                                 else { // BONE_SELECT_CHILD
1228                                         chbone = editbone_get_child(arm, curbone, 1);
1229                                         if (chbone == NULL) continue;
1230                                         
1231                                         if (EBONE_VISIBLE(arm, chbone)) {
1232                                                 chbone->flag |= (BONE_ACTIVE|BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1233                                                 
1234                                                 if (!add_to_sel) {
1235                                                         curbone->flag &= ~(BONE_SELECTED|BONE_ROOTSEL);
1236                                                         if (curbone->parent) curbone->parent->flag &= ~BONE_TIPSEL;
1237                                                 }
1238                                                 curbone->flag &= ~BONE_ACTIVE;
1239                                                 break;
1240                                         }
1241                                 }
1242                         }
1243                 }
1244         }
1245
1246         countall(); // flushes selection!
1247         
1248         if (direction==BONE_SELECT_PARENT)
1249                 BIF_undo_push("Select edit bone parent");
1250         if (direction==BONE_SELECT_CHILD)
1251                 BIF_undo_push("Select edit bone child");
1252 }
1253
1254 /* used by posemode and editmode */
1255 void setflag_armature (Scene *scene, short mode)
1256 {
1257         Object *obedit= scene->obedit; // XXX get from context
1258         Object *ob;
1259         bArmature *arm; 
1260         int flag;
1261         
1262         /* get data */
1263         if (obedit)
1264                 ob= obedit;
1265         else if (OBACT)
1266                 ob= OBACT;
1267         else
1268                 return;
1269         arm= (bArmature *)ob->data;
1270         
1271         /* get flag to set (sync these with the ones used in eBone_Flag */
1272         if (mode == 2)
1273                 flag= pupmenu("Disable Setting%t|Draw Wire%x1|Deform%x2|Mult VG%x3|Hinge%x4|No Scale%x5|Locked%x6");
1274         else if (mode == 1)
1275                 flag= pupmenu("Enable Setting%t|Draw Wire%x1|Deform%x2|Mult VG%x3|Hinge%x4|No Scale%x5|Locked%x6");
1276         else
1277                 flag= pupmenu("Toggle Setting%t|Draw Wire%x1|Deform%x2|Mult VG%x3|Hinge%x4|No Scale%x5|Locked%x6");
1278         switch (flag) {
1279                 case 1:         flag = BONE_DRAWWIRE;   break;
1280                 case 2:         flag = BONE_NO_DEFORM; break;
1281                 case 3:         flag = BONE_MULT_VG_ENV; break;
1282                 case 4:         flag = BONE_HINGE; break;
1283                 case 5:         flag = BONE_NO_SCALE; break;
1284                 case 6:         flag = BONE_EDITMODE_LOCKED; break;
1285                 default:        return;
1286         }
1287         
1288         /* determine which mode armature is in */
1289         if ((!obedit) && (ob->flag & OB_POSEMODE)) {
1290                 /* deal with pose channels */
1291                 bPoseChannel *pchan;
1292                 
1293                 /* set setting */
1294                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1295                         if ((pchan->bone) && (arm->layer & pchan->bone->layer)) {
1296                                 if (pchan->bone->flag & BONE_SELECTED) {
1297                                         bone_setflag(&pchan->bone->flag, flag, mode);
1298                                 }
1299                         }
1300                 }
1301         }
1302         else if (obedit) {
1303                 /* deal with editbones */
1304                 EditBone *curbone;
1305                 
1306                 /* set setting */
1307                 for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1308                         if (arm->layer & curbone->layer) {
1309                                 if (curbone->flag & BONE_SELECTED) {
1310                                         bone_setflag(&curbone->flag, flag, mode);
1311                                 }
1312                         }
1313                 }
1314         }
1315         
1316         BIF_undo_push("Change Bone Setting");
1317 }
1318
1319 /* **************** END PoseMode & EditMode *************************** */
1320 /* **************** Posemode stuff ********************** */
1321
1322
1323 static void selectconnected_posebonechildren (Object *ob, Bone *bone)
1324 {
1325         Bone *curBone;
1326         int shift= 0; // XXX
1327         
1328         if (!(bone->flag & BONE_CONNECTED))
1329                 return;
1330         
1331                 // XXX old cruft! use notifiers instead
1332         //select_actionchannel_by_name (ob->action, bone->name, !(shift));
1333         
1334         if (shift)
1335                 bone->flag &= ~BONE_SELECTED;
1336         else
1337                 bone->flag |= BONE_SELECTED;
1338         
1339         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
1340                 selectconnected_posebonechildren (ob, curBone);
1341         }
1342 }
1343
1344 /* within active object context */
1345 void selectconnected_posearmature(bContext *C)
1346 {
1347         Object *ob= CTX_data_edit_object(C);
1348         Bone *bone, *curBone, *next;
1349         int shift= 0; // XXX
1350         
1351         if (shift)
1352                 bone= get_nearest_bone(C, 0);
1353         else
1354                 bone = get_nearest_bone(C, 1);
1355         
1356         if (!bone)
1357                 return;
1358         
1359         /* Select parents */
1360         for (curBone=bone; curBone; curBone=next){
1361                         // XXX old cruft! use notifiers instead
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 static void *get_armature_edit(bContext *C)
1988 {
1989         Object *obedit= CTX_data_edit_object(C);
1990         if(obedit && obedit->type==OB_ARMATURE) {
1991                 bArmature *arm= obedit->data;
1992                 return arm->edbo;
1993         }
1994         return NULL;
1995 }
1996
1997 /* and this is all the undo system needs to know */
1998 void undo_push_armature(bContext *C, char *name)
1999 {
2000         // XXX solve getdata()
2001         undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
2002 }
2003
2004
2005
2006 /* **************** END EditMode stuff ********************** */
2007 /* *************** Adding stuff in editmode *************** */
2008
2009 /* default bone add, returns it selected, but without tail set */
2010 static EditBone *add_editbone(Object *obedit, char *name)
2011 {
2012         bArmature *arm= obedit->data;
2013         
2014         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
2015         
2016         BLI_strncpy(bone->name, name, 32);
2017         unique_editbone_name(arm->edbo, bone->name);
2018         
2019         BLI_addtail(arm->edbo, bone);
2020         
2021         bone->flag |= BONE_TIPSEL;
2022         bone->weight= 1.0F;
2023         bone->dist= 0.25F;
2024         bone->xwidth= 0.1;
2025         bone->zwidth= 0.1;
2026         bone->ease1= 1.0;
2027         bone->ease2= 1.0;
2028         bone->rad_head= 0.10;
2029         bone->rad_tail= 0.05;
2030         bone->segments= 1;
2031         bone->layer= arm->layer;
2032         
2033         return bone;
2034 }
2035
2036 static void add_primitive_bone(Scene *scene, View3D *v3d, RegionView3D *rv3d, short newob)
2037 {
2038         Object *obedit= scene->obedit; // XXX get from context
2039         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
2040         EditBone        *bone;
2041         
2042         VECCOPY(curs, give_cursor(scene, v3d)); 
2043
2044         /* Get inverse point for head and orientation for tail */
2045         Mat4Invert(obedit->imat, obedit->obmat);
2046         Mat4MulVecfl(obedit->imat, curs);
2047
2048         if ( !(newob) || (U.flag & USER_ADD_VIEWALIGNED) ) 
2049                 Mat3CpyMat4(obmat, rv3d->viewmat);
2050         else Mat3One(obmat);
2051         
2052         Mat3CpyMat4(viewmat, obedit->obmat);
2053         Mat3MulMat3(totmat, obmat, viewmat);
2054         Mat3Inv(imat, totmat);
2055         
2056         deselectall_armature(obedit, 0, 0);
2057         
2058         /*      Create a bone   */
2059         bone= add_editbone(obedit, "Bone");
2060
2061         VECCOPY(bone->head, curs);
2062         
2063         if ( !(newob) || (U.flag & USER_ADD_VIEWALIGNED) )
2064                 VecAddf(bone->tail, bone->head, imat[1]);       // bone with unit length 1
2065         else
2066                 VecAddf(bone->tail, bone->head, imat[2]);       // bone with unit length 1, pointing up Z
2067         
2068 }
2069
2070 void add_primitiveArmature(Scene *scene, View3D *v3d, int type)
2071 {
2072         RegionView3D *rv3d= NULL; // XXX get from context
2073         Object *obedit= scene->obedit; // XXX get from context
2074         short newob=0;
2075         
2076         if(scene->id.lib) return;
2077         
2078         G.f &= ~(G_VERTEXPAINT+G_TEXTUREPAINT+G_WEIGHTPAINT+G_SCULPTMODE);
2079 //      setcursor_space(SPACE_VIEW3D, CURSOR_STD);
2080
2081 // XXX  check_editmode(OB_ARMATURE);
2082         
2083         /* If we're not the "obedit", make a new object and enter editmode */
2084         if (obedit==NULL) {
2085                 add_object(scene, OB_ARMATURE);
2086                 ED_object_base_init_from_view(NULL, BASACT);    // XXX NULL is C
2087                 obedit= BASACT->object;
2088                 
2089                 where_is_object(scene, obedit);
2090                 
2091                 ED_armature_to_edit(obedit);
2092 //              setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
2093                 newob=1;
2094         }
2095         
2096         /* no primitive support yet */
2097         add_primitive_bone(scene, v3d, rv3d, newob);
2098         
2099         countall(); // flushes selection!
2100
2101         if ((newob) && !(U.flag & USER_ADD_EDITMODE)) {
2102                 ED_armature_from_edit(scene, obedit);
2103                 ED_armature_edit_free(obedit);
2104         }
2105         
2106         BIF_undo_push("Add primitive");
2107 }
2108
2109 /* the ctrl-click method */
2110 void addvert_armature(Scene *scene, View3D *v3d)
2111 {
2112         Object *obedit= scene->obedit; // XXX get from context
2113         bArmature *arm= obedit->data;
2114         EditBone *ebone, *newbone, *flipbone;
2115         float *curs, mat[3][3],imat[3][3];
2116         int a, to_root= 0;
2117         
2118         /* find the active or selected bone */
2119         for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2120                 if (EBONE_VISIBLE(arm, ebone)) {
2121                         if (ebone->flag & (BONE_ACTIVE|BONE_TIPSEL)) 
2122                                 break;
2123                 }
2124         }
2125         
2126         if (ebone==NULL) {
2127                 for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2128                         if (EBONE_VISIBLE(arm, ebone)) {
2129                                 if (ebone->flag & (BONE_ACTIVE|BONE_ROOTSEL)) 
2130                                         break;
2131                         }
2132                 }
2133                 if (ebone == NULL) 
2134                         return;
2135                 
2136                 to_root= 1;
2137         }
2138         
2139         deselectall_armature(obedit, 0, 0);
2140         
2141         /* we re-use code for mirror editing... */
2142         flipbone= NULL;
2143         if (arm->flag & ARM_MIRROR_EDIT)
2144                 flipbone= armature_bone_get_mirrored(arm->edbo, ebone);
2145
2146         for (a=0; a<2; a++) {
2147                 if (a==1) {
2148                         if (flipbone==NULL)
2149                                 break;
2150                         else {
2151                                 SWAP(EditBone *, flipbone, ebone);
2152                         }
2153                 }
2154                 
2155                 newbone= add_editbone(obedit, ebone->name);
2156                 newbone->flag |= BONE_ACTIVE;
2157                 
2158                 if (to_root) {
2159                         VECCOPY(newbone->head, ebone->head);
2160                         newbone->rad_head= ebone->rad_tail;
2161                         newbone->parent= ebone->parent;
2162                 }
2163                 else {
2164                         VECCOPY(newbone->head, ebone->tail);
2165                         newbone->rad_head= ebone->rad_tail;
2166                         newbone->parent= ebone;
2167                         newbone->flag |= BONE_CONNECTED;
2168                 }
2169                 
2170                 curs= give_cursor(scene, v3d);
2171                 VECCOPY(newbone->tail, curs);
2172                 VecSubf(newbone->tail, newbone->tail, obedit->obmat[3]);
2173                 
2174                 if (a==1) 
2175                         newbone->tail[0]= -newbone->tail[0];
2176                 
2177                 Mat3CpyMat4(mat, obedit->obmat);
2178                 Mat3Inv(imat, mat);
2179                 Mat3MulVecfl(imat, newbone->tail);
2180                 
2181                 newbone->length= VecLenf(newbone->head, newbone->tail);
2182                 newbone->rad_tail= newbone->length*0.05f;
2183                 newbone->dist= newbone->length*0.25f;
2184                 
2185         }
2186         
2187         countall();
2188         
2189         BIF_undo_push("Add Bone");
2190 }
2191
2192 /* adds an EditBone between the nominated locations (should be in the right space) */
2193 static EditBone *add_points_bone (Object *obedit, float head[], float tail[]) 
2194 {
2195         EditBone *ebo;
2196         
2197         ebo= add_editbone(obedit, "Bone");
2198         
2199         VECCOPY(ebo->head, head);
2200         VECCOPY(ebo->tail, tail);
2201         
2202         return ebo;
2203 }
2204
2205
2206 static EditBone *get_named_editbone(ListBase *edbo, char *name)
2207 {
2208         EditBone  *eBone;
2209
2210         if (name) {
2211                 for (eBone=edbo->first; eBone; eBone=eBone->next) {
2212                         if (!strcmp(name, eBone->name))
2213                                 return eBone;
2214                 }
2215         }
2216
2217         return NULL;
2218 }
2219
2220 static void update_dup_subtarget(Object *obedit, EditBone *dupBone)
2221 {
2222         /* If an edit bone has been duplicated, lets
2223          * update it's constraints if the subtarget
2224          * they point to has also been duplicated
2225          */
2226         bArmature    *arm = obedit->data;
2227         EditBone     *oldtarget, *newtarget;
2228         bPoseChannel *chan;
2229         bConstraint  *curcon;
2230         ListBase     *conlist;
2231         
2232         if ( (chan = verify_pose_channel(obedit->pose, dupBone->name)) ) {
2233                 if ( (conlist = &chan->constraints) ) {
2234                         for (curcon = conlist->first; curcon; curcon=curcon->next) {
2235                                 /* does this constraint have a subtarget in
2236                                  * this armature?
2237                                  */
2238                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
2239                                 ListBase targets = {NULL, NULL};
2240                                 bConstraintTarget *ct;
2241                                 
2242                                 if (cti && cti->get_constraint_targets) {
2243                                         cti->get_constraint_targets(curcon, &targets);
2244                                         
2245                                         for (ct= targets.first; ct; ct= ct->next) {
2246                                                 if ((ct->tar == obedit) && (ct->subtarget[0])) {
2247                                                         oldtarget = get_named_editbone(arm->edbo, ct->subtarget);
2248                                                         if (oldtarget) {
2249                                                                 /* was the subtarget bone duplicated too? If
2250                                                                  * so, update the constraint to point at the 
2251                                                                  * duplicate of the old subtarget.
2252                                                                  */
2253                                                                 if (oldtarget->flag & BONE_SELECTED){
2254                                                                         newtarget = (EditBone *) oldtarget->temp;
2255                                                                         strcpy(ct->subtarget, newtarget->name);
2256                                                                 }
2257                                                         }
2258                                                 }
2259                                         }
2260                                         
2261                                         if (cti->flush_constraint_targets)
2262                                                 cti->flush_constraint_targets(curcon, &targets, 0);
2263                                 }
2264                         }
2265                 }
2266         }
2267 }
2268
2269
2270 void adduplicate_armature(Scene *scene)
2271 {
2272         Object *obedit= scene->obedit; // XXX get from context
2273         bArmature *arm= obedit->data;
2274         EditBone        *eBone = NULL;
2275         EditBone        *curBone;
2276         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
2277         
2278         countall(); // flushes selection!
2279
2280         /* Select mirrored bones */
2281         if (arm->flag & ARM_MIRROR_EDIT) {
2282                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
2283                         if (EBONE_VISIBLE(arm, curBone)) {
2284                                 if (curBone->flag & BONE_SELECTED) {
2285                                         eBone = armature_bone_get_mirrored(arm->edbo, curBone);
2286                                         if (eBone)
2287                                                 eBone->flag |= BONE_SELECTED;
2288                                 }
2289                         }
2290                 }
2291         }
2292         
2293         /*      Find the selected bones and duplicate them as needed */
2294         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2295                 if (EBONE_VISIBLE(arm, curBone)) {
2296                         if (curBone->flag & BONE_SELECTED) {
2297                                 eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
2298                                 eBone->flag |= BONE_SELECTED;
2299                                 
2300                                 /*      Copy data from old bone to new bone */
2301                                 memcpy(eBone, curBone, sizeof(EditBone));
2302                                 
2303                                 curBone->temp = eBone;
2304                                 eBone->temp = curBone;
2305                                 
2306                                 unique_editbone_name(arm->edbo, eBone->name);
2307                                 BLI_addtail(arm->edbo, eBone);
2308                                 if (!firstDup)
2309                                         firstDup=eBone;
2310                                 
2311                                 /* Lets duplicate the list of constraints that the
2312                                  * current bone has.
2313                                  */
2314                                 if (OBACT->pose) {
2315                                         bPoseChannel *chanold, *channew;
2316                                         ListBase     *listold, *listnew;
2317                                         
2318                                         chanold = verify_pose_channel(OBACT->pose, curBone->name);
2319                                         if (chanold) {
2320                                                 listold = &chanold->constraints;
2321                                                 if (listold) {
2322                                                         /* WARNING: this creates a new posechannel, but there will not be an attached bone 
2323                                                          *              yet as the new bones created here are still 'EditBones' not 'Bones'. 
2324                                                          */
2325                                                         channew = 
2326                                                                 verify_pose_channel(OBACT->pose, eBone->name);
2327                                                         if (channew) {
2328                                                                 /* copy transform locks */
2329                                                                 channew->protectflag = chanold->protectflag;
2330                                                                 
2331                                                                 /* copy bone group */
2332                                                                 channew->agrp_index= chanold->agrp_index;
2333                                                                 
2334                                                                 /* ik (dof) settings */
2335                                                                 channew->ikflag = chanold->ikflag;
2336                                                                 VECCOPY(channew->limitmin, chanold->limitmin);
2337                                                                 VECCOPY(channew->limitmax, chanold->limitmax);
2338                                                                 VECCOPY(channew->stiffness, chanold->stiffness);
2339                                                                 channew->ikstretch= chanold->ikstretch;
2340                                                                 
2341                                                                 /* constraints */
2342                                                                 listnew = &channew->constraints;
2343                                                                 copy_constraints(listnew, listold);
2344                                                                 
2345                                                                 /* custom shape */
2346                                                                 channew->custom= chanold->custom;
2347                                                         }
2348                                                 }
2349                                         }
2350                                 }
2351                         }
2352                 }
2353         }
2354
2355         /*      Run though the list and fix the pointers */
2356         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2357                 if (EBONE_VISIBLE(arm, curBone)) {
2358                         if (curBone->flag & BONE_SELECTED) {
2359                                 eBone=(EditBone*) curBone->temp;
2360                                 
2361                                 /*      If this bone has no parent,
2362                                 Set the duplicate->parent to NULL
2363                                 */
2364                                 if (!curBone->parent)
2365                                         eBone->parent = NULL;
2366                                 /*      If this bone has a parent that IS selected,
2367                                         Set the duplicate->parent to the curBone->parent->duplicate
2368                                         */
2369                                 else if (curBone->parent->flag & BONE_SELECTED)
2370                                         eBone->parent= (EditBone *)curBone->parent->temp;
2371                                 /*      If this bone has a parent that IS not selected,
2372                                         Set the duplicate->parent to the curBone->parent
2373                                         */
2374                                 else {
2375                                         eBone->parent=(EditBone*) curBone->parent; 
2376                                         eBone->flag &= ~BONE_CONNECTED;
2377                                 }
2378                                 
2379                                 /* Lets try to fix any constraint subtargets that might
2380                                         have been duplicated */
2381                                 update_dup_subtarget(obedit, eBone);
2382                         }
2383                 }
2384         } 
2385         
2386         /*      Deselect the old bones and select the new ones */
2387         
2388         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2389                 if (EBONE_VISIBLE(arm, curBone))
2390                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
2391         }
2392         
2393 // XXX  BIF_TransformSetUndo("Add Duplicate");
2394 //      initTransform(TFM_TRANSLATION, CTX_NO_PET);
2395 //      Transform();
2396 }
2397
2398
2399
2400 /* *************** END Adding stuff in editmode *************** */
2401 /* ************** Add/Remove stuff in editmode **************** */
2402
2403 /* temporary data-structure for merge/fill bones */
2404 typedef struct EditBonePoint {
2405         struct EditBonePoint *next, *prev;
2406         
2407         EditBone *head_owner;           /* EditBone which uses this point as a 'head' point */
2408         EditBone *tail_owner;           /* EditBone which uses this point as a 'tail' point */
2409         
2410         float vec[3];                           /* the actual location of the point in local/EditMode space */
2411 } EditBonePoint;
2412
2413 /* find chain-tips (i.e. bones without children) */
2414 static void chains_find_tips (ListBase *edbo, ListBase *list)
2415 {
2416         EditBone *curBone, *ebo;
2417         LinkData *ld;
2418         
2419         /* note: this is potentially very slow ... there's got to be a better way */
2420         for (curBone= edbo->first; curBone; curBone= curBone->next) {
2421                 short stop= 0;
2422                 
2423                 /* is this bone contained within any existing chain? (skip if so) */
2424                 for (ld= list->first; ld; ld= ld->next) {
2425                         for (ebo= ld->data; ebo; ebo= ebo->parent) {
2426                                 if (ebo == curBone) {
2427                                         stop= 1;
2428                                         break;
2429                                 }
2430                         }
2431                         
2432                         if (stop) break;
2433                 }
2434                 /* skip current bone if it is part of an existing chain */
2435                 if (stop) continue;
2436                 
2437                 /* is any existing chain part of the chain formed by this bone? */
2438                 stop= 0;
2439                 for (ebo= curBone->parent; ebo; ebo= ebo->parent) {
2440                         for (ld= list->first; ld; ld= ld->next) {
2441                                 if (ld->data == ebo) {
2442                                         ld->data= curBone;
2443                                         stop= 1;
2444                                         break;
2445                                 }
2446                         }
2447                         
2448                         if (stop) break;
2449                 }
2450                 /* current bone has already been added to a chain? */
2451                 if (stop) continue;
2452                 
2453                 /* add current bone to a new chain */
2454                 ld= MEM_callocN(sizeof(LinkData), "BoneChain");
2455                 ld->data= curBone;
2456                 BLI_addtail(list, ld);
2457         }
2458 }
2459
2460
2461 static void fill_add_joint (EditBone *ebo, short eb_tail, ListBase *points)
2462 {
2463         EditBonePoint *ebp;
2464         float vec[3];
2465         short found= 0;
2466         
2467         if (eb_tail) {
2468                 VECCOPY(vec, ebo->tail);
2469         }
2470         else {
2471                 VECCOPY(vec, ebo->head);
2472         }
2473         
2474         for (ebp= points->first; ebp; ebp= ebp->next) {
2475                 if (VecEqual(ebp->vec, vec)) {                  
2476                         if (eb_tail) {
2477                                 if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
2478                                         /* so this bone's tail owner is this bone */
2479                                         ebp->tail_owner= ebo;
2480                                         found= 1;
2481                                         break;
2482                                 }
2483                         }
2484                         else {
2485                                 if ((ebp->tail_owner) && (ebo->parent == ebp->tail_owner)) {
2486                                         /* so this bone's head owner is this bone */
2487                                         ebp->head_owner= ebo;
2488                                         found = 1;
2489                                         break;
2490                                 }
2491                         }
2492                 }
2493         }
2494         
2495         /* allocate a new point if no existing point was related */
2496         if (found == 0) {
2497                 ebp= MEM_callocN(sizeof(EditBonePoint), "EditBonePoint");
2498                 
2499                 if (eb_tail) {
2500                         VECCOPY(ebp->vec, ebo->tail);
2501                         ebp->tail_owner= ebo;
2502                 }
2503                 else {
2504                         VECCOPY(ebp->vec, ebo->head);
2505                         ebp->head_owner= ebo;
2506                 }
2507                 
2508                 BLI_addtail(points, ebp);
2509         }
2510 }
2511
2512 /* bone adding between selected joints */
2513 void fill_bones_armature(Scene *scene, View3D *v3d)
2514 {
2515         Object *obedit= scene->obedit; // XXX get from context
2516         bArmature *arm= obedit->data;
2517         EditBone *ebo, *newbone=NULL;
2518         ListBase points = {NULL, NULL};
2519         int count;
2520         
2521         /* loop over all bones, and only consider if visible */
2522         for (ebo= arm->edbo->first; ebo; ebo= ebo->next) {
2523                 if (EBONE_VISIBLE(arm, ebo)) {
2524                         if (!(ebo->flag & BONE_CONNECTED) && (ebo->flag & BONE_ROOTSEL))
2525                                 fill_add_joint(ebo, 0, &points);
2526                         if (ebo->flag & BONE_TIPSEL) 
2527                                 fill_add_joint(ebo, 1, &points);
2528                 }
2529         }
2530         
2531         /* the number of joints determines how we fill:
2532          *      1) between joint and cursor (joint=head, cursor=tail)
2533          *      2) between the two joints (order is dependent on active-bone/hierachy)
2534          *      3+) error (a smarter method involving finding chains needs to be worked out
2535          */
2536         count= BLI_countlist(&points);
2537         
2538         if (count == 0) {
2539                 error("No joints selected");
2540                 return;
2541         }
2542         else if (count == 1) {
2543                 EditBonePoint *ebp;
2544                 float *fp, curs[3];
2545                 
2546                 /* Get Points - selected joint */
2547                 ebp= (EditBonePoint *)points.first;
2548                 
2549                 /* Get points - cursor (tail) */
2550                 fp= give_cursor(scene, v3d);
2551                 VECCOPY (curs, fp);     
2552                 
2553                 Mat4Invert(obedit->imat, obedit->obmat);
2554                 Mat4MulVecfl(obedit->imat, curs);
2555                 
2556                 /* Create a bone */
2557                 newbone= add_points_bone(obedit, ebp->vec, curs);
2558         }
2559         else if (count == 2) {
2560                 EditBonePoint *ebp, *ebp2;
2561                 float head[3], tail[3];
2562                 short headtail = 0;
2563                 
2564                 /* check that the points don't belong to the same bone */
2565                 ebp= (EditBonePoint *)points.first;
2566                 ebp2= ebp->next;
2567                 
2568                 if ((ebp->head_owner==ebp2->tail_owner) && (ebp->head_owner!=NULL)) {
2569                         error("Same bone selected...");
2570                         BLI_freelistN(&points);
2571                         return;
2572                 }
2573                 if ((ebp->tail_owner==ebp2->head_owner) && (ebp->tail_owner!=NULL)) {
2574                         error("Same bone selected...");
2575                         BLI_freelistN(&points);
2576                         return;
2577                 }
2578                 
2579                 /* find which one should be the 'head' */
2580                 if ((ebp->head_owner && ebp2->head_owner) || (ebp->tail_owner && ebp2->tail_owner)) {
2581                         /* rule: whichever one is closer to 3d-cursor */
2582                         float curs[3], *fp= give_cursor(scene, v3d);
2583                         float vecA[3], vecB[3];
2584                         float distA, distB;
2585                         
2586                         /* get cursor location */
2587                         VECCOPY(curs, fp);      
2588                         
2589                         Mat4Invert(obedit->imat, obedit->obmat);
2590                         Mat4MulVecfl(obedit->imat, curs);
2591                         
2592                         /* get distances */
2593                         VecSubf(vecA, ebp->vec, curs);
2594                         VecSubf(vecB, ebp2->vec, curs);
2595                         distA= VecLength(vecA);
2596                         distB= VecLength(vecB);
2597                         
2598                         /* compare distances - closer one therefore acts as direction for bone to go */
2599                         headtail= (distA < distB) ? 2 : 1;
2600                 }
2601                 else if (ebp->head_owner) {
2602                         headtail = 1;
2603                 }
2604                 else if (ebp2->head_owner) {
2605                         headtail = 2;
2606                 }
2607                 
2608                 /* assign head/tail combinations */
2609                 if (headtail == 2) {
2610                         VECCOPY(head, ebp->vec);
2611                         VECCOPY(tail, ebp2->vec);
2612                 }
2613                 else if (headtail == 1) {
2614                         VECCOPY(head, ebp2->vec);
2615                         VECCOPY(tail, ebp->vec);
2616                 }
2617                 
2618                 /* add new bone and parent it to the appropriate end */
2619                 if (headtail) {
2620                         newbone= add_points_bone(obedit, head, tail);
2621                         
2622                         /* do parenting (will need to set connected flag too) */
2623                         if (headtail == 2) {
2624                                 /* ebp tail or head - tail gets priority */
2625                                 if (ebp->tail_owner)
2626                                         newbone->parent= ebp->tail_owner;
2627                                 else
2628                                         newbone->parent= ebp->head_owner;
2629                         }
2630                         else {
2631                                 /* ebp2 tail or head - tail gets priority */
2632                                 if (ebp2->tail_owner)
2633                                         newbone->parent= ebp2->tail_owner;
2634                                 else
2635                                         newbone->parent= ebp2->head_owner;
2636                         }
2637                         
2638                         newbone->flag |= BONE_CONNECTED;
2639                 }
2640         }
2641         else {
2642                 // FIXME.. figure out a method for multiple bones
2643                 error("Too many points selected"); 
2644                 printf("Points selected: %d \n", count);
2645                 BLI_freelistN(&points);
2646                 return;
2647         }
2648         
2649         /* free points */
2650         BLI_freelistN(&points);
2651         
2652         /* undo + updates */
2653         BIF_undo_push("Fill Bones");
2654 }
2655
2656 /* this function merges between two bones, removes them and those in-between, 
2657  * and adjusts the parent relationships for those in-between
2658  */
2659 static void bones_merge(Object *obedit, EditBone *start, EditBone *end, EditBone *endchild, ListBase *chains)
2660 {
2661         bArmature *arm= obedit->data;
2662         EditBone *ebo, *ebone, *newbone;
2663         LinkData *chain;
2664         float head[3], tail[3];
2665         
2666         /* check if same bone */
2667         if (start == end) {
2668                 printf("Error: same bone! \n");
2669                 printf("\tstart = %s, end = %s \n", start->name, end->name);
2670         }
2671         
2672         /* step 1: add a new bone
2673          *      - head = head/tail of start (default head)
2674          *      - tail = head/tail of end (default tail)
2675          *      - parent = parent of start
2676          */
2677         if ((start->flag & BONE_TIPSEL) && !(start->flag & (BONE_SELECTED|BONE_ACTIVE))) {
2678                 VECCOPY(head, start->tail);
2679         }
2680         else {
2681                 VECCOPY(head, start->head);
2682         }
2683         if ((end->flag & BONE_ROOTSEL) && !(end->flag & (BONE_SELECTED|BONE_ACTIVE))) {
2684                 VECCOPY(tail, end->head);
2685         }
2686         else {
2687                 VECCOPY(tail, end->tail);
2688         }
2689         newbone= add_points_bone(obedit, head, tail);
2690         newbone->parent = start->parent;
2691         
2692         /* step 2a: parent children of in-between bones to newbone */
2693         for (chain= chains->first; chain; chain= chain->next) {
2694                 /* ick: we need to check if parent of each bone in chain is one of the bones in the */
2695                 for (ebo= chain->data; ebo; ebo= ebo->parent) {
2696                         short found= 0;
2697                         
2698                         /* try to find which bone from the list to be removed, is the parent */
2699                         for (ebone= end; ebone; ebone= ebone->parent) {
2700                                 if (ebo->parent == ebone) {
2701                                         found= 1;
2702                                         break;
2703                                 }
2704                         }
2705                         
2706                         /* adjust this bone's parent to newbone then */
2707                         if (found) {
2708                                 ebo->parent= newbone;
2709                                 break;
2710                         }
2711                 }
2712         }
2713         
2714         /* step 2b: parent child of end to newbone (child from this chain) */
2715         if (endchild)
2716                 endchild->parent= newbone;
2717         
2718         /* step 3: delete all bones between and including start and end */
2719         for (ebo= end; ebo; ebo= ebone) {
2720                 ebone= (ebo == start) ? (NULL) : (ebo->parent);
2721                 BLI_freelinkN(arm->edbo, ebo);
2722         }
2723 }
2724
2725 /* bone merging - has a menu! */
2726 void merge_armature(Scene *scene)
2727 {
2728         Object *obedit= scene->obedit; // XXX get from context
2729         bArmature *arm= obedit->data;
2730         short val= 0;
2731         
2732         /* process a menu to determine how to merge */
2733         // TODO: there's room for more modes of merging stuff...
2734         val= pupmenu("Merge Selected Bones%t|Within Chains%x1");
2735         if (val <= 0) return;
2736         
2737         if (val == 1) {
2738                 /* go down chains, merging bones */
2739                 ListBase chains = {NULL, NULL};
2740                 LinkData *chain, *nchain;
2741                 EditBone *ebo;
2742                 
2743                 /* get chains (ends on chains) */
2744                 chains_find_tips(arm->edbo, &chains);
2745                 if (chains.first == NULL) return;
2746                 
2747                 /* each 'chain' is the last bone in the chain (with no children) */
2748                 for (chain= chains.first; chain; chain= nchain) {
2749                         EditBone *bstart= NULL, *bend= NULL;
2750                         EditBone *bchild= NULL, *child=NULL;
2751                         
2752                         /* temporarily remove chain from list of chains */
2753                         nchain= chain->next;
2754                         BLI_remlink(&chains, chain);
2755                         
2756                         /* only consider bones that are visible and selected */
2757                         for (ebo=chain->data; ebo; child=ebo, ebo=ebo->parent) {
2758                                 /* check if visible + selected */
2759                                 if ( EBONE_VISIBLE(arm, ebo) &&
2760                                          ((ebo->flag & BONE_CONNECTED) || (ebo->parent==NULL)) &&
2761                                          (ebo->flag & (BONE_SELECTED|BONE_ACTIVE)) )
2762                                 {
2763                                         /* set either end or start (end gets priority, unless it is already set) */
2764                                         if (bend == NULL)  {
2765                                                 bend= ebo;
2766                                                 bchild= child;
2767                                         }
2768                                         else 
2769                                                 bstart= ebo;
2770                                 }
2771                                 else {
2772                                         /* chain is broken... merge any continous segments then clear */
2773