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