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