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