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