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