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