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