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