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