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