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