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