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