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