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