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