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