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