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