bugfix [#24907] bone roll z up broken and python script showing correct method to...
[blender.git] / source / blender / editors / armature / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation, 2002-2009 full recode.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <stddef.h>
31 #include <string.h>
32 #include <math.h> 
33 #include <float.h> 
34 #include <assert.h> 
35
36
37 #include "DNA_anim_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_constraint_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_scene_types.h"
42
43 #include "MEM_guardedalloc.h"
44
45 #include "BLI_blenlib.h"
46 #include "BLI_math.h"
47 #include "BLI_editVert.h"
48 #include "BLI_ghash.h"
49
50 #include "BKE_animsys.h"
51 #include "BKE_action.h"
52 #include "BKE_armature.h"
53 #include "BKE_constraint.h"
54 #include "BKE_context.h"
55 #include "BKE_deform.h"
56 #include "BKE_depsgraph.h"
57 #include "BKE_DerivedMesh.h"
58 #include "BKE_global.h"
59 #include "BKE_idprop.h"
60 #include "BKE_main.h"
61 #include "BKE_object.h"
62 #include "BKE_report.h"
63 #include "BKE_subsurf.h"
64 #include "BKE_modifier.h"
65 #include "DNA_object_types.h"
66
67 #include "BIF_gl.h"
68
69 #include "RNA_access.h"
70 #include "RNA_define.h"
71
72 #include "WM_api.h"
73 #include "WM_types.h"
74
75 #include "ED_armature.h"
76 #include "ED_keyframing.h"
77 #include "ED_mesh.h"
78 #include "ED_object.h"
79 #include "ED_screen.h"
80 #include "ED_util.h"
81 #include "ED_view3d.h"
82
83 #include "UI_interface.h"
84
85 #include "armature_intern.h"
86 #include "meshlaplacian.h"
87
88 #if 0
89 #include "reeb.h"
90 #endif
91
92 /* **************** tools on Editmode Armature **************** */
93
94 /* Sync selection to parent for connected children */
95 void ED_armature_sync_selection(ListBase *edbo)
96 {
97         EditBone *ebo;
98         
99         for (ebo=edbo->first; ebo; ebo= ebo->next) {
100                 /* if bone is not selectable, we shouldn't alter this setting... */
101                 if ((ebo->flag & BONE_UNSELECTABLE) == 0) {
102                         if ((ebo->flag & BONE_CONNECTED) && (ebo->parent)) {
103                                 if (ebo->parent->flag & BONE_TIPSEL)
104                                         ebo->flag |= BONE_ROOTSEL;
105                                 else
106                                         ebo->flag &= ~BONE_ROOTSEL;
107                         }
108                         
109                         if ((ebo->flag & BONE_TIPSEL) && (ebo->flag & BONE_ROOTSEL))
110                                 ebo->flag |= BONE_SELECTED;
111                         else
112                                 ebo->flag &= ~BONE_SELECTED;
113                 }
114         }                               
115 }
116
117 void ED_armature_validate_active(struct bArmature *arm)
118 {
119         EditBone *ebone= arm->act_edbone;
120
121         if(ebone) { 
122                 if(ebone->flag & BONE_HIDDEN_A || (ebone->flag & BONE_SELECTED)==0)
123                         arm->act_edbone= NULL;
124         }
125 }
126
127 static void bone_free(bArmature *arm, EditBone *bone)
128 {
129         if(arm->act_edbone==bone)
130                 arm->act_edbone= NULL;
131
132         if(bone->prop) {
133                 IDP_FreeProperty(bone->prop);
134                 MEM_freeN(bone->prop);
135         }
136
137         BLI_freelinkN(arm->edbo, bone);
138 }
139
140 void ED_armature_edit_bone_remove(bArmature *arm, EditBone *exBone)
141 {
142         EditBone *curBone;
143
144         /* Find any bones that refer to this bone */
145         for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
146                 if (curBone->parent==exBone) {
147                         curBone->parent=exBone->parent;
148                         curBone->flag &= ~BONE_CONNECTED;
149                 }
150         }
151
152         bone_free(arm, exBone);
153 }
154
155
156 /* converts Bones to EditBone list, used for tools as well */
157 EditBone *make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent, Bone *actBone)
158 {
159         EditBone        *eBone;
160         EditBone        *eBoneAct= NULL;
161         EditBone        *eBoneTest= NULL;
162         Bone            *curBone;
163         float delta[3];
164         float premat[3][3];
165         float postmat[3][3];
166         float imat[3][3];
167         float difmat[3][3];
168                 
169         for (curBone=bones->first; curBone; curBone=curBone->next) {
170                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
171                 
172                 /*      Copy relevant data from bone to eBone */
173                 eBone->parent= parent;
174                 BLI_strncpy(eBone->name, curBone->name, sizeof(eBone->name));
175                 eBone->flag = curBone->flag;
176                 
177                 /* fix selection flags */
178
179                 if (eBone->flag & BONE_SELECTED) {
180                         /* if the bone is selected the copy its root selection to the parents tip */
181                         eBone->flag |= BONE_TIPSEL;
182                         if (eBone->parent && (eBone->flag & BONE_CONNECTED)) {
183                                 eBone->parent->flag |= BONE_TIPSEL;
184                                 eBone->flag &= ~BONE_ROOTSEL; /* this is ignored when there is a connected parent, so unset it */
185                         }
186                         else {
187                                 eBone->flag |= BONE_ROOTSEL;
188                         }
189                 }
190                 else {
191                         /* if the bone is not selected, but connected to its parent
192                          *  copy the parents tip selection state */
193                         if(eBone->parent &&  (eBone->flag & BONE_CONNECTED)) {
194                                 /* selecting with the mouse gives this behavior */
195                                 if(eBone->parent->flag & BONE_TIPSEL) {
196                                         eBone->flag |= BONE_ROOTSEL;
197                                 }
198                                 else {
199                                         eBone->flag &= ~BONE_ROOTSEL;
200                                 }
201
202                                 /* probably not selected but just incase */
203                                 eBone->flag &= ~BONE_TIPSEL;
204                         }
205                 }
206
207                 copy_v3_v3(eBone->head, curBone->arm_head);
208                 copy_v3_v3(eBone->tail, curBone->arm_tail);             
209                 
210                 eBone->roll= 0.0f;
211                 
212                 /* roll fixing */
213                 sub_v3_v3v3(delta, eBone->tail, eBone->head);
214                 vec_roll_to_mat3(delta, 0.0f, postmat);
215                 
216                 copy_m3_m4(premat, curBone->arm_mat);
217                 
218                 invert_m3_m3(imat, postmat);
219                 mul_m3_m3m3(difmat, imat, premat);
220                 
221                 eBone->roll = (float)atan2(difmat[2][0], difmat[2][2]);
222                 
223                 /* rest of stuff copy */
224                 eBone->length= curBone->length;
225                 eBone->dist= curBone->dist;
226                 eBone->weight= curBone->weight;
227                 eBone->xwidth= curBone->xwidth;
228                 eBone->zwidth= curBone->zwidth;
229                 eBone->ease1= curBone->ease1;
230                 eBone->ease2= curBone->ease2;
231                 eBone->rad_head= curBone->rad_head;
232                 eBone->rad_tail= curBone->rad_tail;
233                 eBone->segments = curBone->segments;            
234                 eBone->layer = curBone->layer;
235
236                 if(curBone->prop)
237                         eBone->prop= IDP_CopyProperty(curBone->prop);
238                 
239                 BLI_addtail(edbo, eBone);
240                 
241                 /*      Add children if necessary */
242                 if (curBone->childbase.first) {
243                         eBoneTest= make_boneList(edbo, &curBone->childbase, eBone, actBone);
244                         if(eBoneTest)
245                                 eBoneAct= eBoneTest;
246                 }
247
248                 if(curBone==actBone)
249                         eBoneAct= eBone;
250         }
251
252         return eBoneAct;
253 }
254
255 /* nasty stuff for converting roll in editbones into bones */
256 /* also sets restposition in armature (arm_mat) */
257 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
258 {
259         Bone *curBone;
260         EditBone *ebone;
261         float premat[3][3];
262         float postmat[3][3];
263         float difmat[3][3];
264         float imat[3][3];
265         float delta[3];
266         
267         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
268                 /* sets local matrix and arm_mat (restpos) */
269                 where_is_armature_bone(curBone, curBone->parent);
270                 
271                 /* Find the associated editbone */
272                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
273                         if ((Bone*)ebone->temp == curBone)
274                                 break;
275                 
276                 if (ebone) {
277                         /* Get the ebone premat */
278                         sub_v3_v3v3(delta, ebone->tail, ebone->head);
279                         vec_roll_to_mat3(delta, ebone->roll, premat);
280                         
281                         /* Get the bone postmat */
282                         copy_m3_m4(postmat, curBone->arm_mat);
283                         
284                         invert_m3_m3(imat, premat);
285                         mul_m3_m3m3(difmat, imat, postmat);
286 #if 0
287                         printf ("Bone %s\n", curBone->name);
288                         print_m4("premat", premat);
289                         print_m4("postmat", postmat);
290                         print_m4("difmat", difmat);
291                         printf ("Roll = %f\n",  (-atan2(difmat[2][0], difmat[2][2]) * (180.0/M_PI)));
292 #endif
293                         curBone->roll = (float)-atan2(difmat[2][0], difmat[2][2]);
294                         
295                         /* and set restposition again */
296                         where_is_armature_bone(curBone, curBone->parent);
297                 }
298                 fix_bonelist_roll(&curBone->childbase, editbonelist);
299         }
300 }
301
302 /* put EditMode back in Object */
303 void ED_armature_from_edit(Object *obedit)
304 {
305         bArmature *arm= obedit->data;
306         EditBone *eBone, *neBone;
307         Bone    *newBone;
308         Object *obt;
309         
310         /* armature bones */
311         free_bonelist(&arm->bonebase);
312         
313         /* remove zero sized bones, this gives instable restposes */
314         for (eBone=arm->edbo->first; eBone; eBone= neBone) {
315                 float len= len_v3v3(eBone->head, eBone->tail);
316                 neBone= eBone->next;
317                 if (len <= 0.000001f) {         /* FLT_EPSILON is too large? */
318                         EditBone *fBone;
319                         
320                         /*      Find any bones that refer to this bone  */
321                         for (fBone=arm->edbo->first; fBone; fBone= fBone->next) {
322                                 if (fBone->parent==eBone)
323                                         fBone->parent= eBone->parent;
324                         }
325                         if (G.f & G_DEBUG)
326                                 printf("Warning: removed zero sized bone: %s\n", eBone->name);
327                         bone_free(arm, eBone);
328                 }
329         }
330         
331         /*      Copy the bones from the editData into the armature */
332         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
333                 newBone= MEM_callocN(sizeof(Bone), "bone");
334                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
335                 
336                 BLI_strncpy(newBone->name, eBone->name, sizeof(newBone->name));
337                 memcpy(newBone->head, eBone->head, sizeof(newBone->head));
338                 memcpy(newBone->tail, eBone->tail, sizeof(newBone->tail));
339                 newBone->flag= eBone->flag;
340                 
341                 if (eBone == arm->act_edbone) {
342                         newBone->flag |= BONE_SELECTED; /* important, editbones can be active with only 1 point selected */
343                         arm->act_edbone= NULL;
344                         arm->act_bone= newBone;
345                 }
346                 newBone->roll = 0.0f;
347                 
348                 newBone->weight = eBone->weight;
349                 newBone->dist = eBone->dist;
350                 
351                 newBone->xwidth = eBone->xwidth;
352                 newBone->zwidth = eBone->zwidth;
353                 newBone->ease1= eBone->ease1;
354                 newBone->ease2= eBone->ease2;
355                 newBone->rad_head= eBone->rad_head;
356                 newBone->rad_tail= eBone->rad_tail;
357                 newBone->segments= eBone->segments;
358                 newBone->layer = eBone->layer;
359                 
360                 if(eBone->prop)
361                         newBone->prop= IDP_CopyProperty(eBone->prop);
362         }
363         
364         /*      Fix parenting in a separate pass to ensure ebone->bone connections
365                 are valid at this point */
366         for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
367                 newBone= (Bone *)eBone->temp;
368                 if (eBone->parent) {
369                         newBone->parent= (Bone *)eBone->parent->temp;
370                         BLI_addtail(&newBone->parent->childbase, newBone);
371                         
372                         {
373                                 float M_boneRest[3][3];
374                                 float M_parentRest[3][3];
375                                 float iM_parentRest[3][3];
376                                 float   delta[3];
377                                 
378                                 /* Get the parent's  matrix (rotation only) */
379                                 sub_v3_v3v3(delta, eBone->parent->tail, eBone->parent->head);
380                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
381                                 
382                                 /* Get this bone's  matrix (rotation only) */
383                                 sub_v3_v3v3(delta, eBone->tail, eBone->head);
384                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
385                                 
386                                 /* Invert the parent matrix */
387                                 invert_m3_m3(iM_parentRest, M_parentRest);
388                                 
389                                 /* Get the new head and tail */
390                                 sub_v3_v3v3(newBone->head, eBone->head, eBone->parent->tail);
391                                 sub_v3_v3v3(newBone->tail, eBone->tail, eBone->parent->tail);
392                                 
393                                 mul_m3_v3(iM_parentRest, newBone->head);
394                                 mul_m3_v3(iM_parentRest, newBone->tail);
395                         }
396                 }
397                 /*      ...otherwise add this bone to the armature's bonebase */
398                 else
399                         BLI_addtail(&arm->bonebase, newBone);
400         }
401         
402         /* Make a pass through the new armature to fix rolling */
403         /* also builds restposition again (like where_is_armature) */
404         fix_bonelist_roll(&arm->bonebase, arm->edbo);
405         
406         /* so all users of this armature should get rebuilt */
407         for (obt= G.main->object.first; obt; obt= obt->id.next) {
408                 if (obt->data==arm)
409                         armature_rebuild_pose(obt, arm);
410         }
411         
412         DAG_id_flush_update(&obedit->id, OB_RECALC_DATA);
413 }
414
415 void ED_armature_apply_transform(Object *ob, float mat[4][4])
416 {
417         EditBone *ebone;
418         bArmature *arm= ob->data;
419         float scale = mat4_to_scale(mat);       /* store the scale of the matrix here to use on envelopes */
420         
421         /* Put the armature into editmode */
422         ED_armature_to_edit(ob);
423
424         /* Do the rotations */
425         for (ebone = arm->edbo->first; ebone; ebone=ebone->next){
426                 mul_m4_v3(mat, ebone->head);
427                 mul_m4_v3(mat, ebone->tail);
428                 
429                 ebone->rad_head *= scale;
430                 ebone->rad_tail *= scale;
431                 ebone->dist             *= scale;
432         }
433         
434         /* Turn the list into an armature */
435         ED_armature_from_edit(ob);
436         ED_armature_edit_free(ob);
437 }
438
439 /* exported for use in editors/object/ */
440 /* 0 == do center, 1 == center new, 2 == center cursor */
441 void docenter_armature (Scene *scene, Object *ob, float cursor[3], int centermode, int around)
442 {
443         Object *obedit= scene->obedit; // XXX get from context
444         EditBone *ebone;
445         bArmature *arm= ob->data;
446         float cent[3];
447
448         /* Put the armature into editmode */
449         if(ob != obedit) {
450                 ED_armature_to_edit(ob);
451                 obedit= NULL; /* we cant use this so behave as if there is no obedit */
452         }
453
454         /* Find the centerpoint */
455         if (centermode == 2) {
456                 copy_v3_v3(cent, cursor);
457                 invert_m4_m4(ob->imat, ob->obmat);
458                 mul_m4_v3(ob->imat, cent);
459         }
460         else {
461                 if(around==V3D_CENTROID) {
462                         int total= 0;
463                         zero_v3(cent);
464                         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
465                                 total+=2;
466                                 add_v3_v3(cent, ebone->head);
467                                 add_v3_v3(cent, ebone->tail);
468                         }
469                         mul_v3_fl(cent, 1.0f/(float)total);
470                 }
471                 else {
472                         float min[3], max[3];
473                         INIT_MINMAX(min, max);
474                         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
475                                 DO_MINMAX(ebone->head, min, max);
476                                 DO_MINMAX(ebone->tail, min, max);
477                         }
478                         mid_v3_v3v3(cent, min, max);
479                 }
480         }
481         
482         /* Do the adjustments */
483         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
484                 sub_v3_v3(ebone->head, cent);
485                 sub_v3_v3(ebone->tail, cent);
486         }
487         
488         /* Turn the list into an armature */
489         if(obedit==NULL) {
490                 ED_armature_from_edit(ob);
491                 ED_armature_edit_free(ob);
492         }
493
494         /* Adjust object location for new centerpoint */
495         if(centermode && obedit==NULL) {
496                 mul_mat3_m4_v3(ob->obmat, cent); /* ommit translation part */
497                 add_v3_v3(ob->loc, cent);
498         }
499 }
500
501 /* ---------------------- */
502
503 /* checks if an EditBone with a matching name already, returning the matching bone if it exists */
504 static EditBone *editbone_name_exists (ListBase *edbo, const char *name)
505 {
506         return BLI_findstring(edbo, name, offsetof(EditBone, name));
507 }
508
509 /* note: there's a unique_bone_name() too! */
510 static int editbone_unique_check(void *arg, const char *name)
511 {
512         struct {ListBase *lb;void *bone;} *data= arg;
513         EditBone *dupli= editbone_name_exists(data->lb, name);
514         return dupli && dupli != data->bone;
515 }
516
517 void unique_editbone_name (ListBase *edbo, char *name, EditBone *bone)
518 {
519         struct {ListBase *lb; void *bone;} data;
520         data.lb= edbo;
521         data.bone= bone;
522
523         BLI_uniquename_cb(editbone_unique_check, &data, "Bone", '.', name, sizeof(bone->name));
524 }
525
526 /* helper for apply_armature_pose2bones - fixes parenting of objects that are bone-parented to armature */
527 static void applyarmature_fix_boneparents (Scene *scene, Object *armob)
528 {
529         Object workob, *ob;
530         
531         /* go through all objects in database */
532         for (ob= G.main->object.first; ob; ob= ob->id.next) {
533                 /* if parent is bone in this armature, apply corrections */
534                 if ((ob->parent == armob) && (ob->partype == PARBONE)) {
535                         /* apply current transform from parent (not yet destroyed), 
536                          * then calculate new parent inverse matrix
537                          */
538                         object_apply_mat4(ob, ob->obmat, FALSE, FALSE);
539                         
540                         what_does_parent(scene, ob, &workob);
541                         invert_m4_m4(ob->parentinv, workob.obmat);
542                 }
543         }
544 }
545
546 /* set the current pose as the restpose */
547 static int apply_armature_pose2bones_exec (bContext *C, wmOperator *op)
548 {
549         Scene *scene= CTX_data_scene(C);
550         Object *ob= ED_object_pose_armature(CTX_data_active_object(C)); // must be active object, not edit-object
551         bArmature *arm= get_armature(ob);
552         bPose *pose;
553         bPoseChannel *pchan;
554         EditBone *curbone;
555         
556         /* don't check if editmode (should be done by caller) */
557         if (ob->type!=OB_ARMATURE)
558                 return OPERATOR_CANCELLED;
559         if (object_data_is_libdata(ob)) {
560                 BKE_report(op->reports, RPT_ERROR, "Cannot apply pose to lib-linked armature."); //error_libdata();
561                 return OPERATOR_CANCELLED;
562         }
563         
564         /* helpful warnings... */
565         // TODO: add warnings to be careful about actions, applying deforms first, etc.
566         
567         /* Get editbones of active armature to alter */
568         ED_armature_to_edit(ob);        
569         
570         /* get pose of active object and move it out of posemode */
571         pose= ob->pose;
572         
573         for (pchan=pose->chanbase.first; pchan; pchan=pchan->next) {
574                 curbone= editbone_name_exists(arm->edbo, pchan->name);
575                 
576                 /* simply copy the head/tail values from pchan over to curbone */
577                 copy_v3_v3(curbone->head, pchan->pose_head);
578                 copy_v3_v3(curbone->tail, pchan->pose_tail);
579                 
580                 /* fix roll:
581                  *      1. find auto-calculated roll value for this bone now
582                  *      2. remove this from the 'visual' y-rotation
583                  */
584                 {
585                         float premat[3][3], imat[3][3],pmat[3][3], tmat[3][3];
586                         float delta[3], eul[3];
587                         
588                         /* obtain new auto y-rotation */
589                         sub_v3_v3v3(delta, curbone->tail, curbone->head);
590                         vec_roll_to_mat3(delta, 0.0f, premat);
591                         invert_m3_m3(imat, premat);
592                         
593                         /* get pchan 'visual' matrix */
594                         copy_m3_m4(pmat, pchan->pose_mat);
595                         
596                         /* remove auto from visual and get euler rotation */
597                         mul_m3_m3m3(tmat, imat, pmat);
598                         mat3_to_eul( eul,tmat);
599                         
600                         /* just use this euler-y as new roll value */
601                         curbone->roll= eul[1];
602                 }
603                 
604                 /* clear transform values for pchan */
605                 pchan->loc[0]= pchan->loc[1]= pchan->loc[2]= 0.0f;
606                 pchan->eul[0]= pchan->eul[1]= pchan->eul[2]= 0.0f;
607                 pchan->quat[1]= pchan->quat[2]= pchan->quat[3]= 0.0f;
608                 pchan->quat[0]= pchan->size[0]= pchan->size[1]= pchan->size[2]= 1.0f;
609                 
610                 /* set anim lock */
611                 curbone->flag |= BONE_UNKEYED;
612         }
613         
614         /* convert editbones back to bones, and then free the edit-data */
615         ED_armature_from_edit(ob);
616         ED_armature_edit_free(ob);
617         
618         /* flush positions of posebones */
619         where_is_pose(scene, ob);
620         
621         /* fix parenting of objects which are bone-parented */
622         applyarmature_fix_boneparents(scene, ob);
623         
624         /* note, notifier might evolve */
625         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
626         
627         return OPERATOR_FINISHED;
628 }
629
630 void POSE_OT_armature_apply (wmOperatorType *ot)
631 {
632         /* identifiers */
633         ot->name= "Apply Pose as Rest Pose";
634         ot->idname= "POSE_OT_armature_apply";
635         ot->description= "Apply the current pose as the new rest pose";
636         
637         /* callbacks */
638         ot->exec= apply_armature_pose2bones_exec;
639         ot->poll= ED_operator_posemode;
640         
641         /* flags */
642         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
643 }
644
645
646 /* set the current pose as the restpose */
647 static int pose_visual_transform_apply_exec (bContext *C, wmOperator *UNUSED(op))
648 {
649         Scene *scene= CTX_data_scene(C);
650         Object *ob= ED_object_pose_armature(CTX_data_active_object(C)); // must be active object, not edit-object
651
652         /* don't check if editmode (should be done by caller) */
653         if (ob->type!=OB_ARMATURE)
654                 return OPERATOR_CANCELLED;
655
656         /* loop over all selected pchans
657          *
658          * TODO, loop over children before parents if multiple bones
659          * at once are to be predictable*/
660         CTX_DATA_BEGIN(C, bPoseChannel *, pchan, selected_pose_bones)
661         {
662                 float delta_mat[4][4], imat[4][4], mat[4][4];
663
664                 where_is_pose_bone(scene, ob, pchan, CFRA, 1);
665
666                 copy_m4_m4(mat, pchan->pose_mat);
667
668                 /* calculate pchan->pose_mat without loc/size/rot & constraints applied */
669                 where_is_pose_bone(scene, ob, pchan, CFRA, 0);
670                 invert_m4_m4(imat, pchan->pose_mat);
671                 mul_m4_m4m4(delta_mat, mat, imat);
672
673                 pchan_apply_mat4(pchan, delta_mat, TRUE);
674
675                 where_is_pose_bone(scene, ob, pchan, CFRA, 1);
676         }
677         CTX_DATA_END;
678
679         // ob->pose->flag |= (POSE_LOCKED|POSE_DO_UNLOCK);
680         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
681
682         /* note, notifier might evolve */
683         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
684
685         return OPERATOR_FINISHED;
686 }
687
688 void POSE_OT_visual_transform_apply (wmOperatorType *ot)
689 {
690         /* identifiers */
691         ot->name= "Apply Visual Transform to Pose";
692         ot->idname= "POSE_OT_visual_transform_apply";
693         ot->description= "Apply final constrained position of pose bones to their transform.";
694         
695         /* callbacks */
696         ot->exec= pose_visual_transform_apply_exec;
697         ot->poll= ED_operator_posemode;
698         
699         /* flags */
700         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
701 }
702
703 /* ---------------------- */
704
705 /* Helper function for armature joining - link fixing */
706 static void joined_armature_fix_links(Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
707 {
708         Object *ob;
709         bPose *pose;
710         bPoseChannel *pchant;
711         bConstraint *con;
712         
713         /* let's go through all objects in database */
714         for (ob= G.main->object.first; ob; ob= ob->id.next) {
715                 /* do some object-type specific things */
716                 if (ob->type == OB_ARMATURE) {
717                         pose= ob->pose;
718                         for (pchant= pose->chanbase.first; pchant; pchant= pchant->next) {
719                                 for (con= pchant->constraints.first; con; con= con->next) {
720                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
721                                         ListBase targets = {NULL, NULL};
722                                         bConstraintTarget *ct;
723                                         
724                                         /* constraint targets */
725                                         if (cti && cti->get_constraint_targets) {
726                                                 cti->get_constraint_targets(con, &targets);
727                                                 
728                                                 for (ct= targets.first; ct; ct= ct->next) {
729                                                         if (ct->tar == srcArm) {
730                                                                 if (strcmp(ct->subtarget, "")==0) {
731                                                                         ct->tar = tarArm;
732                                                                 }
733                                                                 else if (strcmp(ct->subtarget, pchan->name)==0) {
734                                                                         ct->tar = tarArm;
735                                                                         strcpy(ct->subtarget, curbone->name);
736                                                                 }
737                                                         }
738                                                 }
739                                                 
740                                                 if (cti->flush_constraint_targets)
741                                                         cti->flush_constraint_targets(con, &targets, 0);
742                                         }
743                                         
744                                         /* action constraint? */
745                                         if (con->type == CONSTRAINT_TYPE_ACTION) {
746                                                 bActionConstraint *data= con->data; // XXX old animation system
747                                                 bAction *act;
748                                                 bActionChannel *achan;
749                                                 
750                                                 if (data->act) {
751                                                         act= data->act;
752                                                         
753                                                         for (achan= act->chanbase.first; achan; achan= achan->next) {
754                                                                 if (strcmp(achan->name, pchan->name)==0)
755                                                                         BLI_strncpy(achan->name, curbone->name, sizeof(achan->name));
756                                                         }
757                                                 }
758                                         }
759                                         
760                                 }
761                         }
762                 }
763                         
764                 /* fix object-level constraints */
765                 if (ob != srcArm) {
766                         for (con= ob->constraints.first; con; con= con->next) {
767                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
768                                 ListBase targets = {NULL, NULL};
769                                 bConstraintTarget *ct;
770                                 
771                                 /* constraint targets */
772                                 if (cti && cti->get_constraint_targets) {
773                                         cti->get_constraint_targets(con, &targets);
774                                         
775                                         for (ct= targets.first; ct; ct= ct->next) {
776                                                 if (ct->tar == srcArm) {
777                                                         if (strcmp(ct->subtarget, "")==0) {
778                                                                 ct->tar = tarArm;
779                                                         }
780                                                         else if (strcmp(ct->subtarget, pchan->name)==0) {
781                                                                 ct->tar = tarArm;
782                                                                 strcpy(ct->subtarget, curbone->name);
783                                                         }
784                                                 }
785                                         }
786                                         
787                                         if (cti->flush_constraint_targets)
788                                                 cti->flush_constraint_targets(con, &targets, 0);
789                                 }
790                         }
791                 }
792                 
793                 /* See if an object is parented to this armature */
794                 if (ob->parent && (ob->parent == srcArm)) {
795                         /* Is object parented to a bone of this src armature? */
796                         if (ob->partype==PARBONE) {
797                                 /* bone name in object */
798                                 if (!strcmp(ob->parsubstr, pchan->name))
799                                         BLI_strncpy(ob->parsubstr, curbone->name, sizeof(ob->parsubstr));
800                         }
801                         
802                         /* make tar armature be new parent */
803                         ob->parent = tarArm;
804                 }
805         }       
806 }
807
808 /* join armature exec is exported for use in object->join objects operator... */
809 int join_armature_exec(bContext *C, wmOperator *UNUSED(op))
810 {
811         Main *bmain= CTX_data_main(C);
812         Scene *scene= CTX_data_scene(C);
813         Object  *ob= CTX_data_active_object(C);
814         bArmature *arm= (ob)? ob->data: NULL;
815         bPose *pose, *opose;
816         bPoseChannel *pchan, *pchann;
817         EditBone *curbone;
818         float   mat[4][4], oimat[4][4];
819         
820         /*      Ensure we're not in editmode and that the active object is an armature*/
821         if (!ob || ob->type!=OB_ARMATURE)
822                 return OPERATOR_CANCELLED;
823         if (!arm || arm->edbo)
824                 return OPERATOR_CANCELLED;
825         
826         /* Get editbones of active armature to add editbones to */
827         ED_armature_to_edit(ob);
828         
829         /* get pose of active object and move it out of posemode */
830         pose= ob->pose;
831         ob->mode &= ~OB_MODE_POSE;
832
833         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
834                 if ((base->object->type==OB_ARMATURE) && (base->object!=ob)) {
835                         bArmature *curarm= base->object->data;
836                         
837                         /* Make a list of editbones in current armature */
838                         ED_armature_to_edit(base->object);
839                         
840                         /* Get Pose of current armature */
841                         opose= base->object->pose;
842                         base->object->mode &= ~OB_MODE_POSE;
843                         //BASACT->flag &= ~OB_MODE_POSE;
844                         
845                         /* Find the difference matrix */
846                         invert_m4_m4(oimat, ob->obmat);
847                         mul_m4_m4m4(mat, base->object->obmat, oimat);
848                         
849                         /* Copy bones and posechannels from the object to the edit armature */
850                         for (pchan=opose->chanbase.first; pchan; pchan=pchann) {
851                                 pchann= pchan->next;
852                                 curbone= editbone_name_exists(curarm->edbo, pchan->name);
853                                 
854                                 /* Get new name */
855                                 unique_editbone_name(arm->edbo, curbone->name, NULL);
856                                 
857                                 /* Transform the bone */
858                                 {
859                                         float premat[4][4];
860                                         float postmat[4][4];
861                                         float difmat[4][4];
862                                         float imat[4][4];
863                                         float temp[3][3];
864                                         float delta[3];
865                                         
866                                         /* Get the premat */
867                                         sub_v3_v3v3(delta, curbone->tail, curbone->head);
868                                         vec_roll_to_mat3(delta, curbone->roll, temp);
869                                         
870                                         unit_m4(premat); /* Mat4MulMat34 only sets 3x3 part */
871                                         mul_m4_m3m4(premat, temp, mat);
872                                         
873                                         mul_m4_v3(mat, curbone->head);
874                                         mul_m4_v3(mat, curbone->tail);
875                                         
876                                         /* Get the postmat */
877                                         sub_v3_v3v3(delta, curbone->tail, curbone->head);
878                                         vec_roll_to_mat3(delta, curbone->roll, temp);
879                                         copy_m4_m3(postmat, temp);
880                                         
881                                         /* Find the roll */
882                                         invert_m4_m4(imat, premat);
883                                         mul_m4_m4m4(difmat, postmat, imat);
884                                         
885                                         curbone->roll -= (float)atan2(difmat[2][0], difmat[2][2]);
886                                 }
887                                 
888                                 /* Fix Constraints and Other Links to this Bone and Armature */
889                                 joined_armature_fix_links(ob, base->object, pchan, curbone);
890                                 
891                                 /* Rename pchan */
892                                 BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
893                                 
894                                 /* Jump Ship! */
895                                 BLI_remlink(curarm->edbo, curbone);
896                                 BLI_addtail(arm->edbo, curbone);
897                                 
898                                 BLI_remlink(&opose->chanbase, pchan);
899                                 BLI_addtail(&pose->chanbase, pchan);
900                                 free_pose_channels_hash(opose);
901                                 free_pose_channels_hash(pose);
902                         }
903                         
904                         ED_base_object_free_and_unlink(bmain, scene, base);
905                 }
906         }
907         CTX_DATA_END;
908         
909         DAG_scene_sort(bmain, scene);   // because we removed object(s)
910
911         ED_armature_from_edit(ob);
912         ED_armature_edit_free(ob);
913
914         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
915         
916         return OPERATOR_FINISHED;
917 }
918
919 /* ---------------------- */
920
921 /* Helper function for armature separating - link fixing */
922 static void separated_armature_fix_links(Object *origArm, Object *newArm)
923 {
924         Object *ob;
925         bPoseChannel *pchan, *pcha, *pchb;
926         bConstraint *con;
927         ListBase *opchans, *npchans;
928         
929         /* get reference to list of bones in original and new armatures  */
930         opchans= &origArm->pose->chanbase;
931         npchans= &newArm->pose->chanbase;
932         
933         /* let's go through all objects in database */
934         for (ob= G.main->object.first; ob; ob= ob->id.next) {
935                 /* do some object-type specific things */
936                 if (ob->type == OB_ARMATURE) {
937                         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
938                                 for (con= pchan->constraints.first; con; con= con->next) {
939                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
940                                         ListBase targets = {NULL, NULL};
941                                         bConstraintTarget *ct;
942                                         
943                                         /* constraint targets */
944                                         if (cti && cti->get_constraint_targets) {
945                                                 cti->get_constraint_targets(con, &targets);
946                                                 
947                                                 for (ct= targets.first; ct; ct= ct->next) {
948                                                         /* any targets which point to original armature are redirected to the new one only if:
949                                                          *      - the target isn't origArm/newArm itself
950                                                          *      - the target is one that can be found in newArm/origArm
951                                                          */
952                                                         if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
953                                                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
954                                                                         /* check if either one matches */
955                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
956                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
957                                                                         {
958                                                                                 ct->tar= newArm;
959                                                                                 break;
960                                                                         }
961                                                                         
962                                                                         /* check if both ends have met (to stop checking) */
963                                                                         if (pcha == pchb) break;
964                                                                 }                                                               
965                                                         }
966                                                         else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
967                                                                 for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
968                                                                         /* check if either one matches */
969                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
970                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
971                                                                         {
972                                                                                 ct->tar= origArm;
973                                                                                 break;
974                                                                         }
975                                                                         
976                                                                         /* check if both ends have met (to stop checking) */
977                                                                         if (pcha == pchb) break;
978                                                                 }                                                               
979                                                         }
980                                                 }
981                                                 
982                                                 if (cti->flush_constraint_targets)
983                                                         cti->flush_constraint_targets(con, &targets, 0);
984                                         }
985                                 }
986                         }
987                 }
988                         
989                 /* fix object-level constraints */
990                 if (ob != origArm) {
991                         for (con= ob->constraints.first; con; con= con->next) {
992                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
993                                 ListBase targets = {NULL, NULL};
994                                 bConstraintTarget *ct;
995                                 
996                                 /* constraint targets */
997                                 if (cti && cti->get_constraint_targets) {
998                                         cti->get_constraint_targets(con, &targets);
999                                         
1000                                         for (ct= targets.first; ct; ct= ct->next) {
1001                                                 /* any targets which point to original armature are redirected to the new one only if:
1002                                                  *      - the target isn't origArm/newArm itself
1003                                                  *      - the target is one that can be found in newArm/origArm
1004                                                  */
1005                                                 if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
1006                                                         for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
1007                                                                 /* check if either one matches */
1008                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
1009                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
1010                                                                 {
1011                                                                         ct->tar= newArm;
1012                                                                         break;
1013                                                                 }
1014                                                                 
1015                                                                 /* check if both ends have met (to stop checking) */
1016                                                                 if (pcha == pchb) break;
1017                                                         }                                                               
1018                                                 }
1019                                                 else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
1020                                                         for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
1021                                                                 /* check if either one matches */
1022                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
1023                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
1024                                                                 {
1025                                                                         ct->tar= origArm;
1026                                                                         break;
1027                                                                 }
1028                                                                 
1029                                                                 /* check if both ends have met (to stop checking) */
1030                                                                 if (pcha == pchb) break;
1031                                                         }                                                               
1032                                                 }
1033                                         }
1034                                         
1035                                         if (cti->flush_constraint_targets)
1036                                                 cti->flush_constraint_targets(con, &targets, 0);
1037                                 }
1038                         }
1039                 }
1040                 
1041                 /* See if an object is parented to this armature */
1042                 if ((ob->parent) && (ob->parent == origArm)) {
1043                         /* Is object parented to a bone of this src armature? */
1044                         if (ob->partype==PARBONE) {
1045                                 /* bone name in object */
1046                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
1047                                         /* check if either one matches */
1048                                         if ( (strcmp(pcha->name, ob->parsubstr)==0) ||
1049                                                  (strcmp(pchb->name, ob->parsubstr)==0) )
1050                                         {
1051                                                 ob->parent= newArm;
1052                                                 break;
1053                                         }
1054                                         
1055                                         /* check if both ends have met (to stop checking) */
1056                                         if (pcha == pchb) break;
1057                                 }
1058                         }
1059                 }
1060         }       
1061 }
1062
1063 /* Helper function for armature separating - remove certain bones from the given armature 
1064  *      sel: remove selected bones from the armature, otherwise the unselected bones are removed
1065  *  (ob is not in editmode)
1066  */
1067 static void separate_armature_bones(Object *ob, short sel) 
1068 {
1069         bArmature *arm= (bArmature *)ob->data;
1070         bPoseChannel *pchan, *pchann;
1071         EditBone *curbone;
1072         
1073         /* make local set of editbones to manipulate here */
1074         ED_armature_to_edit(ob);
1075         
1076         /* go through pose-channels, checking if a bone should be removed */
1077         for (pchan=ob->pose->chanbase.first; pchan; pchan=pchann) {
1078                 pchann= pchan->next;
1079                 curbone= editbone_name_exists(arm->edbo, pchan->name);
1080                 
1081                 /* check if bone needs to be removed */
1082                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
1083                          (!sel && !(curbone->flag & BONE_SELECTED)) )
1084                 {
1085                         EditBone *ebo;
1086                         bPoseChannel *pchn;
1087                         
1088                         /* clear the bone->parent var of any bone that had this as its parent  */
1089                         for (ebo= arm->edbo->first; ebo; ebo= ebo->next) {
1090                                 if (ebo->parent == curbone) {
1091                                         ebo->parent= NULL;
1092                                         ebo->temp= NULL; /* this is needed to prevent random crashes with in ED_armature_from_edit */
1093                                         ebo->flag &= ~BONE_CONNECTED;
1094                                 }
1095                         }
1096                         
1097                         /* clear the pchan->parent var of any pchan that had this as its parent */
1098                         for (pchn= ob->pose->chanbase.first; pchn; pchn=pchn->next) {
1099                                 if (pchn->parent == pchan)
1100                                         pchn->parent= NULL;
1101                         }
1102                         
1103                         /* free any of the extra-data this pchan might have */
1104                         free_pose_channel(pchan);
1105                         free_pose_channels_hash(ob->pose);
1106                         
1107                         /* get rid of unneeded bone */
1108                         bone_free(arm, curbone);
1109                         BLI_freelinkN(&ob->pose->chanbase, pchan);
1110                 }
1111         }
1112         
1113         /* exit editmode (recalculates pchans too) */
1114         ED_armature_from_edit(ob);
1115         ED_armature_edit_free(ob);
1116 }
1117
1118 /* separate selected bones into their armature */
1119 static int separate_armature_exec (bContext *C, wmOperator *UNUSED(op))
1120 {
1121         Main *bmain= CTX_data_main(C);
1122         Scene *scene= CTX_data_scene(C);
1123         Object *obedit= CTX_data_edit_object(C);
1124         Object *oldob, *newob;
1125         Base *oldbase, *newbase;
1126         bArmature *arm;
1127         
1128         /* sanity checks */
1129         if (obedit == NULL)
1130                 return OPERATOR_CANCELLED;
1131         arm= obedit->data;
1132         
1133         /* set wait cursor in case this takes a while */
1134         WM_cursor_wait(1);
1135         
1136         /* we are going to do this as follows (unlike every other instance of separate):
1137          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
1138          *      2. duplicate base - BASACT is the new one now
1139          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
1140          *      4. fix constraint links
1141          *      5. make original armature active and enter editmode
1142          */
1143         
1144         /* 1) only edit-base selected */
1145         // TODO: use context iterators for this?
1146         CTX_DATA_BEGIN(C, Base *, base, visible_bases) {
1147                 if (base->object==obedit) base->flag |= 1;
1148                 else base->flag &= ~1;
1149         }
1150         CTX_DATA_END;
1151         
1152         /* 1) store starting settings and exit editmode */
1153         oldob= obedit;
1154         oldbase= BASACT;
1155         oldob->mode &= ~OB_MODE_POSE;
1156         //oldbase->flag &= ~OB_POSEMODE;
1157         
1158         ED_armature_from_edit(obedit);
1159         ED_armature_edit_free(obedit);
1160         
1161         /* 2) duplicate base */
1162         newbase= ED_object_add_duplicate(bmain, scene, oldbase, USER_DUP_ARM); /* only duplicate linked armature */
1163         newob= newbase->object;         
1164         newbase->flag &= ~SELECT;
1165         
1166         
1167         /* 3) remove bones that shouldn't still be around on both armatures */
1168         separate_armature_bones(oldob, 1);
1169         separate_armature_bones(newob, 0);
1170         
1171         
1172         /* 4) fix links before depsgraph flushes */ // err... or after?
1173         separated_armature_fix_links(oldob, newob);
1174         
1175         DAG_id_flush_update(&oldob->id, OB_RECALC_DATA);        /* this is the original one */
1176         DAG_id_flush_update(&newob->id, OB_RECALC_DATA);        /* this is the separated one */
1177         
1178         
1179         /* 5) restore original conditions */
1180         obedit= oldob;
1181         
1182         ED_armature_to_edit(obedit);
1183         
1184         /* note, notifier might evolve */
1185         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, obedit);
1186         
1187         /* recalc/redraw + cleanup */
1188         WM_cursor_wait(0);
1189         
1190         return OPERATOR_FINISHED;
1191 }
1192
1193 void ARMATURE_OT_separate (wmOperatorType *ot)
1194 {
1195         /* identifiers */
1196         ot->name= "Separate Bones";
1197         ot->idname= "ARMATURE_OT_separate";
1198         ot->description= "Isolate selected bones into a separate armature";
1199         
1200         /* callbacks */
1201         ot->invoke= WM_operator_confirm;
1202         ot->exec= separate_armature_exec;
1203         ot->poll= ED_operator_editarmature;
1204         
1205         /* flags */
1206         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1207 }
1208
1209 /* **************** END tools on Editmode Armature **************** */
1210 /* **************** PoseMode & EditMode *************************** */
1211
1212 /* only for opengl selection indices */
1213 Bone *get_indexed_bone (Object *ob, int index)
1214 {
1215         bPoseChannel *pchan;
1216         int a= 0;
1217         
1218         if(ob->pose==NULL) return NULL;
1219         index>>=16;             // bone selection codes use left 2 bytes
1220         
1221         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
1222                 if(a==index) return pchan->bone;
1223         }
1224         return NULL;
1225 }
1226
1227 /* See if there are any selected bones in this buffer */
1228 /* only bones from base are checked on */
1229 static void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short findunsel)
1230 {
1231         Object *obedit= scene->obedit; // XXX get from context
1232         Bone *bone;
1233         EditBone *ebone;
1234         void *firstunSel=NULL, *firstSel=NULL, *data;
1235         unsigned int hitresult;
1236         short i, takeNext=0, sel;
1237         
1238         for (i=0; i< hits; i++){
1239                 hitresult = buffer[3+(i*4)];
1240                 
1241                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
1242                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
1243                                 
1244                                 hitresult &= ~(BONESEL_ANY);
1245                                 /* Determine what the current bone is */
1246                                 if (obedit==NULL || base->object!=obedit) {
1247                                         /* no singular posemode, so check for correct object */
1248                                         if(base->selcol == (hitresult & 0xFFFF)) {
1249                                                 bone = get_indexed_bone(base->object, hitresult);
1250                                                 
1251                                                 if (findunsel)
1252                                                         sel = (bone->flag & BONE_SELECTED);
1253                                                 else
1254                                                         sel = !(bone->flag & BONE_SELECTED);
1255                                                 
1256                                                 data = bone;
1257                                         }
1258                                         else {
1259                                                 data= NULL;
1260                                                 sel= 0;
1261                                         }
1262                                 }
1263                                 else{
1264                                         bArmature *arm= obedit->data;
1265                                         
1266                                         ebone = BLI_findlink(arm->edbo, hitresult);
1267                                         if (findunsel)
1268                                                 sel = (ebone->flag & BONE_SELECTED);
1269                                         else
1270                                                 sel = !(ebone->flag & BONE_SELECTED);
1271                                         
1272                                         data = ebone;
1273                                 }
1274                                 
1275                                 if(data) {
1276                                         if (sel) {
1277                                                 if(!firstSel) firstSel= data;
1278                                                 takeNext=1;
1279                                         }
1280                                         else {
1281                                                 if (!firstunSel)
1282                                                         firstunSel=data;
1283                                                 if (takeNext)
1284                                                         return data;
1285                                         }
1286                                 }
1287                         }
1288                 }
1289         }
1290         
1291         if (firstunSel)
1292                 return firstunSel;
1293         else 
1294                 return firstSel;
1295 }
1296
1297
1298
1299 /* used by posemode as well editmode */
1300 /* only checks scene->basact! */
1301 /* x and y are mouse coords (area space) */
1302 static void *get_nearest_bone (bContext *C, short findunsel, int x, int y)
1303 {
1304         ViewContext vc;
1305         rcti rect;
1306         unsigned int buffer[MAXPICKBUF];
1307         short hits;
1308         
1309         view3d_set_viewcontext(C, &vc);
1310         
1311         // rect.xmin= ... mouseco!
1312         rect.xmin= rect.xmax= x;
1313         rect.ymin= rect.ymax= y;
1314         
1315         glInitNames();
1316         hits= view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
1317
1318         if (hits>0)
1319                 return get_bone_from_selectbuffer(vc.scene, vc.scene->basact, buffer, hits, findunsel);
1320         
1321         return NULL;
1322 }
1323
1324 /* helper for setflag_sel_bone() */
1325 static void bone_setflag (int *bone, int flag, short mode)
1326 {
1327         if (bone && flag) {
1328                 /* exception for inverse flags */
1329                 if (flag == BONE_NO_DEFORM) {
1330                         if (mode == 2)
1331                                 *bone |= flag;
1332                         else if (mode == 1)
1333                                 *bone &= ~flag;
1334                         else
1335                                 *bone ^= flag;
1336                 }
1337                 else {
1338                         if (mode == 2)
1339                                 *bone &= ~flag;
1340                         else if (mode == 1)
1341                                 *bone |= flag;
1342                         else
1343                                 *bone ^= flag;
1344                 }
1345         }
1346 }
1347
1348 /* Get the first available child of an editbone */
1349 static EditBone *editbone_get_child(bArmature *arm, EditBone *pabone, short use_visibility)
1350 {
1351         EditBone *curbone, *chbone=NULL;
1352         
1353         for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1354                 if (curbone->parent == pabone) {
1355                         if (use_visibility) {
1356                                 if ((arm->layer & curbone->layer) && !(pabone->flag & BONE_HIDDEN_A)) {
1357                                         chbone = curbone;
1358                                 }
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, ED_object_pose_armature(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 *UNUSED(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_deselect_all(Object *obedit, int toggle)
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(EBONE_VISIBLE(arm, eBone)) {
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(EBONE_VISIBLE(arm, eBone)) {
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 void ED_armature_deselect_all_visible(Object *obedit)
1939 {
1940         bArmature *arm= obedit->data;
1941         EditBone        *ebone;
1942
1943         for (ebone= arm->edbo->first; ebone; ebone= ebone->next) {
1944                 /* first and foremost, bone must be visible and selected */
1945                 if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE)==0) {
1946                         ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1947                 }
1948         }
1949
1950         ED_armature_sync_selection(arm->edbo);
1951 }
1952
1953 /* context: editmode armature in view3d */
1954 int mouse_armature(bContext *C, short mval[2], int extend)
1955 {
1956         Object *obedit= CTX_data_edit_object(C);
1957         bArmature *arm= obedit->data;
1958         ViewContext vc;
1959         EditBone *nearBone = NULL;
1960         int     selmask;
1961
1962         view3d_set_viewcontext(C, &vc);
1963         
1964         BIF_sk_selectStroke(C, mval, extend);
1965         
1966         nearBone= get_nearest_editbonepoint(&vc, mval, arm->edbo, 1, &selmask);
1967         if (nearBone) {
1968
1969                 if (!extend)
1970                         ED_armature_deselect_all(obedit, 0);
1971                 
1972                 /* by definition the non-root connected bones have no root point drawn,
1973                    so a root selection needs to be delivered to the parent tip */
1974                 
1975                 if(selmask & BONE_SELECTED) {
1976                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
1977                                 /* click in a chain */
1978                                 if(extend) {
1979                                         /* hold shift inverts this bone's selection */
1980                                         if(nearBone->flag & BONE_SELECTED) {
1981                                                 /* deselect this bone */
1982                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
1983                                                 /* only deselect parent tip if it is not selected */
1984                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
1985                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
1986                                         }
1987                                         else {
1988                                                 /* select this bone */
1989                                                 nearBone->flag |= BONE_TIPSEL;
1990                                                 nearBone->parent->flag |= BONE_TIPSEL;
1991                                         }
1992                                 }
1993                                 else {
1994                                         /* select this bone */
1995                                         nearBone->flag |= BONE_TIPSEL;
1996                                         nearBone->parent->flag |= BONE_TIPSEL;
1997                                 }
1998                         }
1999                         else {
2000                                 if(extend) {
2001                                         /* hold shift inverts this bone's selection */
2002                                         if(nearBone->flag & BONE_SELECTED)
2003                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
2004                                         else
2005                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
2006                                 }
2007                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
2008                         }
2009                 }
2010                 else {
2011                         if (extend && (nearBone->flag & selmask))
2012                                 nearBone->flag &= ~selmask;
2013                         else
2014                                 nearBone->flag |= selmask;
2015                 }
2016                 
2017                 ED_armature_sync_selection(arm->edbo);
2018                 
2019                 if(nearBone) {
2020                         /* then now check for active status */
2021                         if(nearBone->flag & BONE_SELECTED) arm->act_edbone= nearBone;
2022                 }
2023                 
2024                 WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, vc.obedit);
2025                 return 1;
2026         }
2027
2028         return 0;
2029 }
2030
2031 void ED_armature_edit_free(struct Object *ob)
2032 {
2033         bArmature *arm= ob->data;
2034         EditBone *eBone;
2035         
2036         /*      Clear the editbones list */
2037         if (arm->edbo) {
2038                 if (arm->edbo->first) {
2039                         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
2040                                 if (eBone->prop) {
2041                                         IDP_FreeProperty(eBone->prop);
2042                                         MEM_freeN(eBone->prop);
2043                                 }
2044                         }
2045
2046                         BLI_freelistN(arm->edbo);
2047                 }
2048                 MEM_freeN(arm->edbo);
2049                 arm->edbo= NULL;
2050         }
2051 }
2052
2053 /* Put armature in EditMode */
2054 void ED_armature_to_edit(Object *ob)
2055 {
2056         bArmature *arm= ob->data;
2057         
2058         ED_armature_edit_free(ob);
2059         arm->edbo= MEM_callocN(sizeof(ListBase), "edbo armature");
2060         arm->act_edbone= make_boneList(arm->edbo, &arm->bonebase, NULL, arm->act_bone);
2061         arm->act_bone= NULL;
2062
2063 //      BIF_freeTemplates(); /* force template update when entering editmode */
2064 }
2065
2066
2067 /* adjust bone roll to align Z axis with vector
2068  * vec is in local space and is normalized
2069  */
2070
2071 float ED_rollBoneToVector(EditBone *bone, const float align_axis[3], const short axis_only)
2072 {
2073         float mat[3][3], nor[3];
2074
2075         sub_v3_v3v3(nor, bone->tail, bone->head);
2076         vec_roll_to_mat3(nor, 0.0f, mat);
2077
2078         /* check the bone isnt aligned with the axis */
2079         if(!is_zero_v3(align_axis) && angle_v3v3(align_axis, mat[2]) > FLT_EPSILON) {
2080                 float vec[3], align_axis_proj[3], roll;
2081
2082                 /* project the new_up_axis along the normal */
2083                 project_v3_v3v3(vec, align_axis, nor);
2084                 sub_v3_v3v3(align_axis_proj, align_axis, vec);
2085                 
2086                 if(axis_only) {
2087                         if(angle_v3v3(align_axis_proj, mat[2]) > M_PI/2) {
2088                                 negate_v3(align_axis_proj);
2089                         }
2090                 }
2091                 
2092                 roll = angle_v3v3(align_axis_proj, mat[2]);
2093                 
2094                 cross_v3_v3v3(vec, mat[2], align_axis_proj);
2095                 
2096                 if (dot_v3v3(vec, nor) < 0) {
2097                         roll = -roll;
2098                 }
2099
2100                 return roll;
2101         }
2102
2103         return 0.0f;
2104 }
2105
2106
2107 static EnumPropertyItem prop_calc_roll_types[] = {
2108         {0, "X", 0, "X Axis", ""},
2109         {1, "Y", 0, "Y Axis", ""},
2110         {2, "Z", 0, "Z Axis", ""},
2111         {6, "VIEW", 0, "View Axis", ""},
2112         {7, "CURSOR", 0, "Cursor", ""},
2113         {0, NULL, 0, NULL, NULL}
2114 };
2115
2116
2117 static int armature_calc_roll_exec(bContext *C, wmOperator *op) 
2118 {
2119         Object *ob= CTX_data_edit_object(C);
2120         const short type= RNA_enum_get(op->ptr, "type");
2121         const short axis_only= RNA_boolean_get(op->ptr, "axis_only");
2122         const short axis_flip= RNA_boolean_get(op->ptr, "axis_flip");
2123
2124         float imat[3][3];
2125
2126         copy_m3_m4(imat, ob->obmat);
2127         invert_m3(imat);
2128
2129         if(type==7) { /* Cursor */
2130                 Scene *scene= CTX_data_scene(C);
2131                 View3D *v3d= CTX_wm_view3d(C); /* can be NULL */
2132                 float cursor_local[3];
2133                 float   *cursor= give_cursor(scene, v3d);
2134         
2135
2136                 copy_v3_v3(cursor_local, cursor);
2137                 mul_m3_v3(imat, cursor_local);
2138
2139                 /* cursor */
2140                 CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones) {
2141                         float cursor_rel[3];
2142                         sub_v3_v3v3(cursor_rel, cursor_local, ebone->head);
2143                         if(axis_flip) negate_v3(cursor_rel);
2144                         ebone->roll= ED_rollBoneToVector(ebone, cursor_rel, axis_only);
2145                 }
2146                 CTX_DATA_END;
2147         }
2148         else {
2149                 float vec[3]= {0.0f, 0.0f, 0.0f};
2150                 if(type==6) { /* View */
2151                         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2152                         if(rv3d==NULL) {
2153                                 BKE_report(op->reports, RPT_ERROR, "No region view3d available");
2154                                 return OPERATOR_CANCELLED;
2155                         }
2156
2157                         copy_v3_v3(vec, rv3d->viewinv[2]);
2158                 }
2159                 else { /* Axis */
2160                         assert(type >= 0 && type <= 5);
2161                         if(type<3)      vec[type]= 1.0f; 
2162                         else            vec[type-2]= -1.0f; 
2163                 }
2164
2165                 mul_m3_v3(imat, vec);
2166                 if(axis_flip) negate_v3(vec);
2167
2168                 CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones) {
2169                         /* roll func is a callback which assumes that all is well */
2170                         ebone->roll= ED_rollBoneToVector(ebone, vec, axis_only);
2171                 }
2172                 CTX_DATA_END;
2173         }
2174
2175         /* note, notifier might evolve */
2176         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
2177         
2178         return OPERATOR_FINISHED;
2179 }
2180
2181 void ARMATURE_OT_calculate_roll(wmOperatorType *ot)
2182 {
2183         /* identifiers */
2184         ot->name= "Recalculate Roll";
2185         ot->idname= "ARMATURE_OT_calculate_roll";
2186         
2187         /* api callbacks */
2188         ot->invoke = WM_menu_invoke;
2189         ot->exec = armature_calc_roll_exec;
2190         ot->poll = ED_operator_editarmature;
2191         
2192         /* flags */
2193         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2194
2195         /* properties */
2196         ot->prop= RNA_def_enum(ot->srna, "type", prop_calc_roll_types, 0, "Type", "");
2197         RNA_def_boolean(ot->srna, "axis_flip", 0, "Flip Axis", "Negate the alignment axis.");
2198         RNA_def_boolean(ot->srna, "axis_only", 0, "Shortest Rotation", "Ignore the axis direction, use the shortest rotation to align.");
2199 }
2200
2201 /* **************** undo for armatures ************** */
2202
2203 typedef struct UndoArmature {
2204         EditBone *act_edbone;
2205         ListBase lb;
2206 } UndoArmature;
2207
2208 static void undoBones_to_editBones(void *uarmv, void *armv)
2209 {
2210         UndoArmature *uarm= uarmv;
2211         bArmature *arm= armv;
2212         EditBone *ebo, *newebo;
2213         
2214         BLI_freelistN(arm->edbo);
2215         
2216         /* copy  */
2217         for(ebo= uarm->lb.first; ebo; ebo= ebo->next) {
2218                 newebo= MEM_dupallocN(ebo);
2219                 ebo->temp= newebo;
2220                 BLI_addtail(arm->edbo, newebo);
2221         }
2222         
2223         /* active bone */
2224         if(uarm->act_edbone) {
2225                 ebo= uarm->act_edbone;
2226                 arm->act_edbone= ebo->temp;
2227         }
2228         else
2229                 arm->act_edbone= NULL;
2230
2231         /* set pointers */
2232         for(newebo= arm->edbo->first; newebo; newebo= newebo->next) {
2233                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2234         }
2235         /* be sure they dont hang ever */
2236         for(newebo= arm->edbo->first; newebo; newebo= newebo->next) {
2237                 newebo->temp= NULL;
2238         }
2239 }
2240
2241 static void *editBones_to_undoBones(void *armv)
2242 {
2243         bArmature *arm= armv;
2244         UndoArmature *uarm;
2245         EditBone *ebo, *newebo;
2246         
2247         uarm= MEM_callocN(sizeof(UndoArmature), "listbase undo");
2248         
2249         /* copy */
2250         for(ebo= arm->edbo->first; ebo; ebo= ebo->next) {
2251                 newebo= MEM_dupallocN(ebo);
2252                 ebo->temp= newebo;
2253                 BLI_addtail(&uarm->lb, newebo);
2254         }
2255         
2256         /* active bone */
2257         if(arm->act_edbone) {
2258                 ebo= arm->act_edbone;
2259                 uarm->act_edbone= ebo->temp;
2260         }
2261
2262         /* set pointers */
2263         for(newebo= uarm->lb.first; newebo; newebo= newebo->next) {
2264                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2265         }
2266         
2267         return uarm;
2268 }
2269
2270 static void free_undoBones(void *uarmv)
2271 {
2272         UndoArmature *uarm= uarmv;
2273         
2274         BLI_freelistN(&uarm->lb);
2275         MEM_freeN(uarm);
2276 }
2277
2278 static void *get_armature_edit(bContext *C)
2279 {
2280         Object *obedit= CTX_data_edit_object(C);
2281         if(obedit && obedit->type==OB_ARMATURE) {
2282                 return obedit->data;
2283         }
2284         return NULL;
2285 }
2286
2287 /* and this is all the undo system needs to know */
2288 void undo_push_armature(bContext *C, const char *name)
2289 {
2290         // XXX solve getdata()
2291         undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
2292 }
2293
2294
2295
2296 /* **************** END EditMode stuff ********************** */
2297 /* *************** Adding stuff in editmode *************** */
2298
2299 /* default bone add, returns it selected, but without tail set */
2300 EditBone *ED_armature_edit_bone_add(bArmature *arm, const char *name)
2301 {
2302         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
2303         
2304         BLI_strncpy(bone->name, name, sizeof(bone->name));
2305         unique_editbone_name(arm->edbo, bone->name, NULL);
2306         
2307         BLI_addtail(arm->edbo, bone);
2308         
2309         bone->flag |= BONE_TIPSEL;
2310         bone->weight= 1.0f;
2311         bone->dist= 0.25f;
2312         bone->xwidth= 0.1f;
2313         bone->zwidth= 0.1f;
2314         bone->ease1= 1.0f;
2315         bone->ease2= 1.0f;
2316         bone->rad_head= 0.10f;
2317         bone->rad_tail= 0.05f;
2318         bone->segments= 1;
2319         bone->layer= arm->layer;
2320         
2321         return bone;
2322 }
2323
2324 /* v3d and rv3d are allowed to be NULL */
2325 void add_primitive_bone(Scene *scene, View3D *v3d, RegionView3D *rv3d)
2326 {
2327         Object *obedit= scene->obedit; // XXX get from context
2328         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
2329         EditBone        *bone;
2330
2331         /* Get inverse point for head and orientation for tail */
2332         invert_m4_m4(obedit->imat, obedit->obmat);
2333         mul_v3_m4v3(curs, obedit->imat, give_cursor(scene, v3d));
2334
2335         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2336                 copy_m3_m4(obmat, rv3d->viewmat);
2337         else unit_m3(obmat);
2338         
2339         copy_m3_m4(viewmat, obedit->obmat);
2340         mul_m3_m3m3(totmat, obmat, viewmat);
2341         invert_m3_m3(imat, totmat);
2342         
2343         ED_armature_deselect_all(obedit, 0);
2344         
2345         /*      Create a bone   */
2346         bone= ED_armature_edit_bone_add(obedit->data, "Bone");
2347
2348         copy_v3_v3(bone->head, curs);
2349         
2350         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2351                 add_v3_v3v3(bone->tail, bone->head, imat[1]);   // bone with unit length 1
2352         else
2353                 add_v3_v3v3(bone->tail, bone->head, imat[2]);   // bone with unit length 1, pointing up Z
2354         
2355 }
2356
2357
2358 /* previously addvert_armature */
2359 /* the ctrl-click method */
2360 static int armature_click_extrude_exec(bContext *C, wmOperator *UNUSED(op))
2361 {
2362         View3D *v3d;
2363         bArmature *arm;
2364         EditBone *ebone, *newbone, *flipbone;
2365         float *curs, mat[3][3],imat[3][3];
2366         int a, to_root= 0;
2367         Object *obedit;
2368         Scene *scene;
2369
2370         scene = CTX_data_scene(C);
2371         v3d= CTX_wm_view3d(C);
2372         obedit= CTX_data_edit_object(C);
2373         arm= obedit->data;
2374         
2375         /* find the active or selected bone */
2376         for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2377                 if (EBONE_VISIBLE(arm, ebone)) {
2378                         if (ebone->flag & BONE_TIPSEL || arm->act_edbone == ebone)
2379                                 break;
2380                 }
2381         }
2382         
2383         if (ebone==NULL) {
2384                 for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2385                         if (EBONE_VISIBLE(arm, ebone)) {
2386                                 if (ebone->flag & BONE_ROOTSEL || arm->act_edbone == ebone)
2387                                         break;
2388                         }
2389                 }
2390                 if (ebone == NULL) 
2391                         return OPERATOR_CANCELLED;
2392                 
2393                 to_root= 1;
2394         }
2395         
2396         ED_armature_deselect_all(obedit, 0);
2397         
2398         /* we re-use code for mirror editing... */
2399         flipbone= NULL;
2400         if (arm->flag & ARM_MIRROR_EDIT)
2401                 flipbone= ED_armature_bone_get_mirrored(arm->edbo, ebone);
2402
2403         for (a=0; a<2; a++) {
2404                 if (a==1) {
2405                         if (flipbone==NULL)
2406                                 break;
2407                         else {
2408                                 SWAP(EditBone *, flipbone, ebone);
2409                         }
2410                 }
2411                 
2412                 newbone= ED_armature_edit_bone_add(arm, ebone->name);
2413                 arm->act_edbone= newbone;
2414                 
2415                 if (to_root) {
2416                         copy_v3_v3(newbone->head, ebone->head);
2417                         newbone->rad_head= ebone->rad_tail;
2418                         newbone->parent= ebone->parent;
2419                 }
2420                 else {
2421                         copy_v3_v3(newbone->head, ebone->tail);
2422                         newbone->rad_head= ebone->rad_tail;
2423                         newbone->parent= ebone;
2424                         newbone->flag |= BONE_CONNECTED;
2425                 }
2426                 
2427                 curs= give_cursor(scene, v3d);
2428                 copy_v3_v3(newbone->tail, curs);
2429                 sub_v3_v3v3(newbone->tail, newbone->tail, obedit->obmat[3]);
2430                 
2431                 if (a==1) 
2432                         newbone->tail[0]= -newbone->tail[0];
2433                 
2434                 copy_m3_m4(mat, obedit->obmat);
2435                 invert_m3_m3(imat, mat);
2436                 mul_m3_v3(imat, newbone->tail);
2437                 
2438                 newbone->length= len_v3v3(newbone->head, newbone->tail);
2439                 newbone->rad_tail= newbone->length*0.05f;
2440                 newbone->dist= newbone->length*0.25f;
2441                 
2442         }
2443         
2444         ED_armature_sync_selection(arm->edbo);
2445
2446         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2447         
2448         return OPERATOR_FINISHED;
2449 }
2450
2451 static int armature_click_extrude_invoke(bContext *C, wmOperator *op, wmEvent *event)
2452 {
2453         /* TODO most of this code is copied from set3dcursor_invoke,
2454            it would be better to reuse code in set3dcursor_invoke */
2455
2456         /* temporarily change 3d cursor position */
2457         Scene *scene;
2458         ARegion *ar;
2459         View3D *v3d;
2460         RegionView3D *rv3d;
2461         float dx, dy, fz, *fp = NULL, dvec[3], oldcurs[3];
2462         short mx, my, mval[2];
2463         int retv;
2464
2465         scene= CTX_data_scene(C);
2466         ar= CTX_wm_region(C);
2467         v3d = CTX_wm_view3d(C);
2468         rv3d= CTX_wm_region_view3d(C);
2469         
2470         fp= give_cursor(scene, v3d);
2471         
2472         copy_v3_v3(oldcurs, fp);
2473         
2474         mx= event->x - ar->winrct.xmin;
2475         my= event->y - ar->winrct.ymin;
2476         project_short_noclip(ar, fp, mval);
2477         
2478         initgrabz(rv3d, fp[0], fp[1], fp[2]);
2479         
2480         if(mval[0]!=IS_CLIPPED) {
2481                 
2482                 window_to_3d_delta(ar, dvec, mval[0]-mx, mval[1]-my);
2483                 sub_v3_v3v3(fp, fp, dvec);
2484         }
2485         else {
2486                 
2487                 dx= ((float)(mx-(ar->winx/2)))*rv3d->zfac/(ar->winx/2);
2488                 dy= ((float)(my-(ar->winy/2)))*rv3d->zfac/(ar->winy/2);
2489                 
2490                 fz= rv3d->persmat[0][3]*fp[0]+ rv3d->persmat[1][3]*fp[1]+ rv3d->persmat[2][3]*fp[2]+ rv3d->persmat[3][3];
2491                 fz= fz/rv3d->zfac;
2492                 
2493                 fp[0]= (rv3d->persinv[0][0]*dx + rv3d->persinv[1][0]*dy+ rv3d->persinv[2][0]*fz)-rv3d->ofs[0];
2494                 fp[1]= (rv3d->persinv[0][1]*dx + rv3d->persinv[1][1]*dy+ rv3d->persinv[2][1]*fz)-rv3d->ofs[1];
2495                 fp[2]= (rv3d->persinv[0][2]*dx + rv3d->persinv[1][2]*dy+ rv3d->persinv[2][2]*fz)-rv3d->ofs[2];
2496         }
2497
2498         /* extrude to the where new cursor is and store the operation result */
2499         retv= armature_click_extrude_exec(C, op);
2500
2501         /* restore previous 3d cursor position */
2502         copy_v3_v3(fp, oldcurs);
2503
2504         return retv;
2505 }
2506
2507 void ARMATURE_OT_click_extrude(wmOperatorType *ot)
2508 {
2509         /* identifiers */
2510         ot->name= "Click-Extrude";
2511         ot->idname= "ARMATURE_OT_click_extrude";
2512         
2513         /* api callbacks */
2514         ot->invoke = armature_click_extrude_invoke;
2515         ot->exec = armature_click_extrude_exec;
2516         ot->poll = ED_operator_editarmature;
2517         
2518         /* flags */
2519         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2520
2521         /* props */
2522 }
2523
2524 /* adds an EditBone between the nominated locations (should be in the right space) */
2525 static EditBone *add_points_bone (Object *obedit, float head[], float tail[]) 
2526 {
2527         EditBone *ebo;
2528         
2529         ebo= ED_armature_edit_bone_add(obedit->data, "Bone");
2530         
2531         copy_v3_v3(ebo->head, head);
2532         copy_v3_v3(ebo->tail, tail);
2533         
2534         return ebo;
2535 }
2536
2537
2538 static EditBone *get_named_editbone(ListBase *edbo, char *name)
2539 {
2540         EditBone  *eBone;
2541
2542         if (name) {
2543                 for (eBone=edbo->first; eBone; eBone=eBone->next) {
2544                         if (!strcmp(name, eBone->name))
2545                                 return eBone;
2546                 }
2547         }
2548
2549         return NULL;
2550 }
2551
2552 /* Call this before doing any duplications
2553  * */
2554 void preEditBoneDuplicate(ListBase *editbones)
2555 {
2556         EditBone *eBone;
2557         
2558         /* clear temp */
2559         for (eBone = editbones->first; eBone; eBone = eBone->next)
2560         {
2561                 eBone->temp = NULL;
2562         }
2563 }
2564
2565 /*
2566  * Note: When duplicating cross objects, editbones here is the list of bones
2567  * from the SOURCE object but ob is the DESTINATION object
2568  * */
2569 void updateDuplicateSubtargetObjects(EditBone *dupBone, ListBase *editbones, Object *src_ob, Object *dst_ob)
2570 {
2571         /* If an edit bone has been duplicated, lets
2572          * update it's constraints if the subtarget
2573          * they point to has also been duplicated
2574          */
2575         EditBone     *oldtarget, *newtarget;
2576         bPoseChannel *pchan;
2577         bConstraint  *curcon;
2578         ListBase     *conlist;
2579         
2580         if ( (pchan = verify_pose_channel(dst_ob->pose, dupBone->name)) ) {
2581                 if ( (conlist = &pchan->constraints) ) {
2582                         for (curcon = conlist->first; curcon; curcon=curcon->next) {
2583                                 /* does this constraint have a subtarget in
2584                                  * this armature?
2585                                  */
2586                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
2587                                 ListBase targets = {NULL, NULL};
2588                                 bConstraintTarget *ct;
2589                                 
2590                                 if (cti && cti->get_constraint_targets) {
2591                                         cti->get_constraint_targets(curcon, &targets);
2592                                         
2593                                         for (ct= targets.first; ct; ct= ct->next) {
2594                                                 if ((ct->tar == src_ob) && (ct->subtarget[0])) {
2595                                                         ct->tar = dst_ob; /* update target */ 
2596                                                         oldtarget = get_named_editbone(editbones, ct->subtarget);
2597                                                         if (oldtarget) {
2598                                                                 /* was the subtarget bone duplicated too? If
2599                                                                  * so, update the constraint to point at the 
2600                                                                  * duplicate of the old subtarget.
2601                                                                  */
2602                                                                 if (oldtarget->temp) {
2603                                                                         newtarget = (EditBone *) oldtarget->temp;
2604                                                                         strcpy(ct->subtarget, newtarget->name);
2605                                                                 }
2606                                                         }
2607                                                 }
2608                                         }
2609                                         
2610                                         if (cti->flush_constraint_targets)
2611                                                 cti->flush_constraint_targets(curcon, &targets, 0);
2612                                 }
2613                         }
2614                 }
2615         }
2616 }
2617
2618 void updateDuplicateSubtarget(EditBone *dupBone, ListBase *editbones, Object *ob)
2619 {
2620         updateDuplicateSubtargetObjects(dupBone, editbones, ob, ob);
2621 }
2622
2623
2624 EditBone *duplicateEditBoneObjects(EditBone *curBone, char *name, ListBase *editbones, Object *src_ob, Object *dst_ob)
2625 {
2626         EditBone *eBone = MEM_mallocN(sizeof(EditBone), "addup_editbone");
2627         
2628         /*      Copy data from old bone to new bone */
2629         memcpy(eBone, curBone, sizeof(EditBone));
2630         
2631         curBone->temp = eBone;
2632         eBone->temp = curBone;
2633         
2634         if (name != NULL)
2635         {
2636                 BLI_strncpy(eBone->name, name, sizeof(eBone->name));
2637         }
2638
2639         unique_editbone_name(editbones, eBone->name, NULL);
2640         BLI_addtail(editbones, eBone);
2641         
2642         /* copy the ID property */
2643         if(curBone->prop)
2644                 eBone->prop= IDP_CopyProperty(curBone->prop);
2645
2646         /* Lets duplicate the list of constraints that the
2647          * current bone has.
2648          */
2649         if (src_ob->pose) {
2650                 bPoseChannel *chanold, *channew;
2651                 
2652                 chanold = verify_pose_channel(src_ob->pose, curBone->name);
2653                 if (chanold) {
2654                         /* WARNING: this creates a new posechannel, but there will not be an attached bone
2655                          *              yet as the new bones created here are still 'EditBones' not 'Bones'.
2656                          */
2657                         channew= verify_pose_channel(dst_ob->pose, eBone->name);
2658
2659                         if(channew) {
2660                                 duplicate_pose_channel_data(channew, chanold);
2661                         }
2662                 }
2663         }
2664         
2665         return eBone;
2666 }
2667
2668 EditBone *duplicateEditBone(EditBone *curBone, char *name, ListBase *editbones, Object *ob)
2669 {
2670         return duplicateEditBoneObjects(curBone, name, editbones, ob, ob);
2671 }
2672
2673 /* previously adduplicate_armature */
2674 static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
2675 {
2676         bArmature *arm;
2677         EditBone        *eBone = NULL;
2678         EditBone        *curBone;
2679         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
2680
2681         Object *obedit= CTX_data_edit_object(C);
2682         arm= obedit->data;
2683
2684         /* cancel if nothing selected */
2685         if (CTX_DATA_COUNT(C, selected_bones) == 0)
2686           return OPERATOR_CANCELLED;
2687         
2688         ED_armature_sync_selection(arm->edbo); // XXX why is this needed?
2689
2690         preEditBoneDuplicate(arm->edbo);
2691
2692         /* Select mirrored bones */
2693         if (arm->flag & ARM_MIRROR_EDIT) {
2694                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
2695                         if (EBONE_VISIBLE(arm, curBone)) {
2696                                 if (curBone->flag & BONE_SELECTED) {
2697                                         eBone = ED_armature_bone_get_mirrored(arm->edbo, curBone);
2698                                         if (eBone)
2699                                                 eBone->flag |= BONE_SELECTED;
2700                                 }
2701                         }
2702                 }
2703         }
2704
2705         
2706         /*      Find the selected bones and duplicate them as needed */
2707         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2708                 if (EBONE_VISIBLE(arm, curBone)) {
2709                         if (curBone->flag & BONE_SELECTED) {
2710                                 
2711                                 eBone= duplicateEditBone(curBone, curBone->name, arm->edbo, obedit);
2712                                 
2713                                 if (!firstDup)
2714                                         firstDup=eBone;
2715
2716                         }
2717                 }
2718         }
2719
2720         /*      Run though the list and fix the pointers */
2721         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2722                 if (EBONE_VISIBLE(arm, curBone)) {
2723                         if (curBone->flag & BONE_SELECTED) {
2724                                 eBone=(EditBone*) curBone->temp;
2725                                 
2726                                 if (!curBone->parent) {
2727                                         /* If this bone has no parent,
2728                                          * Set the duplicate->parent to NULL
2729                                          */
2730                                         eBone->parent = NULL;
2731                                 }
2732                                 else if (curBone->parent->temp) {
2733                                         /* If this bone has a parent that was duplicated,
2734                                          * Set the duplicate->parent to the curBone->parent->temp
2735                                          */
2736                                         eBone->parent= (EditBone *)curBone->parent->temp;
2737                                 }
2738                                 else {
2739                                         /* If this bone has a parent that IS not selected,
2740                                          * Set the duplicate->parent to the curBone->parent
2741                                          */
2742                                         eBone->parent=(EditBone*) curBone->parent; 
2743                                         eBone->flag &= ~BONE_CONNECTED;
2744                                 }
2745                                 
2746                                 /* Lets try to fix any constraint subtargets that might
2747                                  * have been duplicated 
2748                                  */
2749                                 updateDuplicateSubtarget(eBone, arm->edbo, obedit);
2750                         }
2751                 }
2752         } 
2753         
2754         /* correct the active bone */
2755         if(arm->act_edbone) {
2756                 eBone= arm->act_edbone;
2757                 if(eBone->temp)
2758                         arm->act_edbone= eBone->temp;
2759         }
2760
2761         /*      Deselect the old bones and select the new ones */
2762         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2763                 if (EBONE_VISIBLE(arm, curBone))
2764                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2765         }
2766
2767         ED_armature_validate_active(arm);
2768
2769         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2770         
2771         return OPERATOR_FINISHED;
2772 }
2773
2774
2775 void ARMATURE_OT_duplicate(wmOperatorType *ot)
2776 {
2777         /* identifiers */
2778         ot->name= "Duplicate Selected Bone(s)";
2779         ot->idname= "ARMATURE_OT_duplicate";
2780         
2781         /* api callbacks */
2782         ot->exec = armature_duplicate_selected_exec;
2783         ot->poll = ED_operator_editarmature;
2784         
2785         /* flags */
2786         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2787 }
2788
2789
2790 /* *************** END Adding stuff in editmode *************** */
2791 /* ************** Add/Remove stuff in editmode **************** */
2792
2793 /* temporary data-structure for merge/fill bones */
2794 typedef struct EditBonePoint {
2795         struct EditBonePoint *next, *prev;
2796         
2797         EditBone *head_owner;           /* EditBone which uses this point as a 'head' point */
2798         EditBone *tail_owner;           /* EditBone which uses this point as a 'tail' point */
2799         
2800         float vec[3];                           /* the actual location of the point in local/EditMode space */
2801 } EditBonePoint;
2802
2803 /* find chain-tips (i.e. bones without children) */
2804 static void chains_find_tips (ListBase *edbo, ListBase *list)
2805 {
2806         EditBone *curBone, *ebo;
2807         LinkData *ld;
2808         
2809         /* note: this is potentially very slow ... there's got to be a better way */
2810         for (curBone= edbo->first; curBone; curBone= curBone->next) {
2811                 short stop= 0;
2812                 
2813                 /* is this bone contained within any existing chain? (skip if so) */
2814                 for (ld= list->first; ld; ld= ld->next) {
2815                         for (ebo= ld->data; ebo; ebo= ebo->parent) {
2816                                 if (ebo == curBone) {
2817                                         stop= 1;
2818                                         break;
2819                                 }
2820                         }
2821                         
2822                         if (stop) break;
2823                 }
2824                 /* skip current bone if it is part of an existing chain */
2825                 if (stop) continue;
2826                 
2827                 /* is any existing chain part of the chain formed by this bone? */
2828                 stop= 0;
2829                 for (ebo= curBone->parent; ebo; ebo= ebo->parent) {
2830                         for (ld= list->first; ld; ld= ld->next) {
2831                                 if (ld->data == ebo) {
2832                                         ld->data= curBone;
2833                                         stop= 1;
2834                                         break;
2835                                 }
2836                         }
2837                         
2838                         if (stop) break;
2839                 }
2840                 /* current bone has already been added to a chain? */
2841                 if (stop) continue;
2842                 
2843                 /* add current bone to a new chain */
2844                 ld= MEM_callocN(sizeof(LinkData), "BoneChain");
2845                 ld->data= curBone;
2846                 BLI_addtail(list, ld);
2847         }
2848 }
2849
2850 /* --------------------- */
2851
2852 static void fill_add_joint (EditBone *ebo, short eb_tail, ListBase *points)
2853 {
2854         EditBonePoint *ebp;
2855         float vec[3];
2856         short found= 0;
2857         
2858         if (eb_tail) {
2859                 copy_v3_v3(vec, ebo->tail);
2860         }
2861         else {
2862                 copy_v3_v3(vec, ebo->head);
2863         }
2864         
2865         for (ebp= points->first; ebp; ebp= ebp->next) {
2866                 if (equals_v3v3(ebp->vec, vec)) {                       
2867                         if (eb_tail) {
2868                                 if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
2869                                         /* so this bone's tail owner is this bone */
2870                                         ebp->tail_owner= ebo;
2871                                         found= 1;
2872                                         break;
2873                                 }
2874                         }
2875                         else {
2876                                 if ((ebp->tail_owner) && (ebo->parent == ebp->tail_owner)) {
2877                                         /* so this bone's head owner is this bone */
2878                                         ebp->head_owner= ebo;
2879                                         found = 1;
2880                                         break;
2881                                 }
2882                         }
2883                 }
2884         }
2885         
2886         /* allocate a new point if no existing point was related */
2887         if (found == 0) {
2888                 ebp= MEM_callocN(sizeof(EditBonePoint), "EditBonePoint");
2889                 
2890                 if (eb_tail) {
2891                         copy_v3_v3(ebp->vec, ebo->tail);
2892                         ebp->tail_owner= ebo;
2893                 }
2894                 else {
2895                         copy_v3_v3(ebp->vec, ebo->head);
2896                         ebp->head_owner= ebo;
2897                 }
2898                 
2899                 BLI_addtail(points, ebp);
2900         }
2901 }
2902
2903 /* bone adding between selected joints */
2904 static int armature_fill_bones_exec (bContext *C, wmOperator *op)
2905 {
2906         Object *obedit= CTX_data_edit_object(C);
2907         bArmature *arm= (obedit) ? obedit->data : NULL;
2908         Scene *scene= CTX_data_scene(C);
2909         View3D *v3d= CTX_wm_view3d(C);
2910         EditBone *newbone=NULL;
2911         ListBase points = {NULL, NULL};
2912         int count;
2913         
2914         /* sanity checks */
2915         if ELEM(NULL, obedit, arm)
2916                 return OPERATOR_CANCELLED;
2917         
2918         /* loop over all bones, and only consider if visible */
2919         CTX_DATA_BEGIN(C, EditBone *, ebone, visible_bones)
2920         {