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