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