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