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