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