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