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