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