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