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