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