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