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