949decb117118f062445b4165e53ac317928b68d
[blender-staging.git] / source / blender / src / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * editarmature.c: Interface for creating and posing armature objects
32  */
33
34 #include <ctype.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <math.h> 
38
39 #ifdef HAVE_CONFIG_H
40 #include <config.h>
41 #endif
42
43 #include "MEM_guardedalloc.h"
44
45 #include "BMF_Api.h"
46
47 #include "DNA_action_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_constraint_types.h"
50 #include "DNA_ID.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_nla_types.h"
54 #include "DNA_object_types.h"
55 #include "DNA_scene_types.h"
56 #include "DNA_screen_types.h"
57 #include "DNA_space_types.h"
58 #include "DNA_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 constraints 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                                                         /* WARNING: this creates a new posechannel, but there will not be an attached bone 
1630                                                          *              yet as the new bones created here are still 'EditBones' not 'Bones'. 
1631                                                          */
1632                                                         channew = 
1633                                                                 verify_pose_channel(OBACT->pose, eBone->name);
1634                                                         if (channew) {
1635                                                                 /* copy transform locks */
1636                                                                 channew->protectflag = chanold->protectflag;
1637                                                                 
1638                                                                 /* ik (dof) settings */
1639                                                                 channew->ikflag = chanold->ikflag;
1640                                                                 VECCOPY(channew->limitmin, chanold->limitmin);
1641                                                                 VECCOPY(channew->limitmax, chanold->limitmax);
1642                                                                 VECCOPY(channew->stiffness, chanold->stiffness);
1643                                                                 channew->ikstretch= chanold->ikstretch;
1644                                                                 
1645                                                                 /* constraints */
1646                                                                 listnew = &channew->constraints;
1647                                                                 copy_constraints (listnew, listold);
1648                                                         }
1649                                                 }
1650                                         }
1651                                 }
1652                         }
1653                 }
1654         }
1655
1656         /*      Run though the list and fix the pointers */
1657         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1658                 if(arm->layer & curBone->layer) {
1659                         if (curBone->flag & BONE_SELECTED){
1660                                 eBone=(EditBone*) curBone->temp;
1661                                 
1662                                 /*      If this bone has no parent,
1663                                 Set the duplicate->parent to NULL
1664                                 */
1665                                 if (!curBone->parent){
1666                                         eBone->parent = NULL;
1667                                 }
1668                                 /*      If this bone has a parent that IS selected,
1669                                         Set the duplicate->parent to the curBone->parent->duplicate
1670                                         */
1671                                 else if (curBone->parent->flag & BONE_SELECTED){
1672                                         eBone->parent=(EditBone*) curBone->parent->temp;
1673                                 }
1674                                 /*      If this bone has a parent that IS not selected,
1675                                         Set the duplicate->parent to the curBone->parent
1676                                         */
1677                                 else {
1678                                         eBone->parent=(EditBone*) curBone->parent; 
1679                                         eBone->flag &= ~BONE_CONNECTED;
1680                                 }
1681                                 
1682                                 /* Lets try to fix any constraint subtargets that might
1683                                         have been duplicated */
1684                                 update_dup_subtarget(eBone);
1685                         }
1686                 }
1687         } 
1688         
1689         /*      Deselect the old bones and select the new ones */
1690         
1691         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1692                 if(arm->layer & curBone->layer)
1693                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1694         }
1695         
1696         BIF_TransformSetUndo("Add Duplicate");
1697         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1698         Transform();
1699         
1700         allqueue(REDRAWBUTSEDIT, 0);
1701         allqueue(REDRAWBUTSOBJECT, 0);
1702         allqueue(REDRAWOOPS, 0);
1703 }
1704
1705
1706
1707 /* *************** END Adding stuff in editmode *************** */
1708 /* *************** Tools in editmode *********** */
1709
1710
1711 void hide_selected_armature_bones(void)
1712 {
1713         bArmature *arm= G.obedit->data;
1714         EditBone *ebone;
1715         
1716         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1717                 if(arm->layer & ebone->layer) {
1718                         if(ebone->flag & (BONE_SELECTED)) {
1719                                 ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1720                                 ebone->flag |= BONE_HIDDEN_A;
1721                         }
1722                 }
1723         }
1724         countall();
1725         allqueue(REDRAWVIEW3D, 0);
1726         allqueue(REDRAWBUTSEDIT, 0);
1727         BIF_undo_push("Hide Bones");
1728 }
1729
1730 void hide_unselected_armature_bones(void)
1731 {
1732         EditBone *ebone;
1733         
1734         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1735                 bArmature *arm= G.obedit->data;
1736                 if(arm->layer & ebone->layer) {
1737                         if(ebone->flag & (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL));
1738                         else {
1739                                 ebone->flag &= ~BONE_ACTIVE;
1740                                 ebone->flag |= BONE_HIDDEN_A;
1741                         }
1742                 }
1743         }
1744         countall();
1745         allqueue(REDRAWVIEW3D, 0);
1746         allqueue(REDRAWBUTSEDIT, 0);
1747         BIF_undo_push("Hide Unselected Bones");
1748 }
1749
1750 void show_all_armature_bones(void)
1751 {
1752         EditBone *ebone;
1753         
1754         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1755                 bArmature *arm= G.obedit->data;
1756                 if(arm->layer & ebone->layer) {
1757                         if(ebone->flag & BONE_HIDDEN_A) {
1758                                 ebone->flag |= (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
1759                                 ebone->flag &= ~BONE_HIDDEN_A;
1760                         }
1761                 }
1762         }
1763         countall();
1764         allqueue(REDRAWVIEW3D, 0);
1765         allqueue(REDRAWBUTSEDIT, 0);
1766         BIF_undo_push("Reveal Bones");
1767 }
1768
1769 void make_bone_parent(void)
1770 {
1771         bArmature *arm= G.obedit->data;
1772         EditBone *ebone;
1773         float offset[3];
1774         short val;
1775         
1776         val= pupmenu("Make Parent%t|Connected%x1|Keep Offset%x2");
1777         
1778         if(val<1) return;
1779         
1780         /* find active */
1781         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1782                 if(arm->layer & ebone->layer)
1783                         if(ebone->flag & BONE_ACTIVE) break;
1784         
1785         if(ebone) {
1786                 EditBone *actbone= ebone, *selbone= NULL;
1787                 
1788                 /* find selected */
1789                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1790                         if(arm->layer & ebone->layer) {
1791                                 if(ebone->flag & BONE_SELECTED) {
1792                                         if(ebone!=actbone) {
1793                                                 if(selbone==NULL) selbone= ebone;
1794                                                 else {
1795                                                         error("Need one active and one selected bone");
1796                                                         return;
1797                                                 }
1798                                         }
1799                                 }
1800                         }
1801                 }
1802                 if(selbone==NULL) {
1803                         /* we make sure bone is connected */
1804                         if(val==1 && actbone->parent) {
1805                                 actbone->flag |= BONE_CONNECTED;
1806                                 VECCOPY(actbone->head, actbone->parent->tail);
1807                                 actbone->rad_head= actbone->parent->rad_tail;
1808                                 countall(); // checks selection
1809                                 allqueue(REDRAWVIEW3D, 0);
1810                                 BIF_undo_push("Connect to Parent");
1811                         }
1812                         else error("Need one active and one selected bone");
1813                 }
1814                 else {
1815                         /* if selbone had a parent we clear parent tip */
1816                         if(selbone->parent && (selbone->flag & BONE_CONNECTED))
1817                            selbone->parent->flag &= ~(BONE_TIPSEL);
1818                         
1819                         selbone->parent= actbone;
1820                         
1821                         /* in actbone tree we cannot have a loop */
1822                         for(ebone= actbone->parent; ebone; ebone= ebone->parent) {
1823                                 if(ebone->parent==selbone) {
1824                                         ebone->parent= NULL;
1825                                         ebone->flag &= ~BONE_CONNECTED;
1826                                 }
1827                         }
1828                         
1829                         if(val==1) {    // connected
1830                                 selbone->flag |= BONE_CONNECTED;
1831                                 VecSubf(offset, actbone->tail, selbone->head);
1832                                 
1833                                 VECCOPY(selbone->head, actbone->tail);
1834                                 selbone->rad_head= actbone->rad_tail;
1835
1836                                 VecAddf(selbone->tail, selbone->tail, offset);
1837                                 
1838                                 // offset for all its children 
1839                                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1840                                         EditBone *par;
1841                                         for(par= ebone->parent; par; par= par->parent) {
1842                                                 if(par==selbone) {
1843                                                         VecAddf(ebone->head, ebone->head, offset);
1844                                                         VecAddf(ebone->tail, ebone->tail, offset);
1845                                                         break;
1846                                                 }
1847                                         }
1848                                 }
1849                         }
1850                         else {
1851                                 selbone->flag &= ~BONE_CONNECTED;
1852                         }
1853                         
1854                         countall(); // checks selection
1855                         allqueue(REDRAWVIEW3D, 0);
1856                         allqueue(REDRAWBUTSEDIT, 0);
1857                         allqueue(REDRAWOOPS, 0);
1858                         BIF_undo_push("Make Parent");
1859                 }
1860         }
1861 }
1862
1863 void clear_bone_parent(void)
1864 {
1865         bArmature *arm= G.obedit->data;
1866         EditBone *ebone;
1867         short val;
1868         
1869         val= pupmenu("Clear Parent%t|Clear Parent%x1|Disconnect Bone%x2");
1870         
1871         if(val<1) return;
1872         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1873                 if(arm->layer & ebone->layer) {
1874                         if(ebone->flag & BONE_SELECTED) {
1875                                 if(ebone->parent) {
1876                                         /* for nice selection */
1877                                         ebone->parent->flag &= ~(BONE_TIPSEL);
1878                                         
1879                                         if(val==1) ebone->parent= NULL;
1880                                         ebone->flag &= ~BONE_CONNECTED;
1881                                 }
1882                         }
1883                 }
1884         }
1885         countall(); // checks selection
1886         allqueue(REDRAWVIEW3D, 0);
1887         allqueue(REDRAWBUTSEDIT, 0);
1888         allqueue(REDRAWOOPS, 0);
1889         BIF_undo_push("Clear Parent");
1890 }
1891         
1892
1893 static EditBone *editbone_name_exists (ListBase *ebones, char *name)
1894 {
1895         EditBone        *eBone;
1896         
1897         if (ebones == NULL) ebones = &G.edbo;
1898         
1899         for (eBone=ebones->first; eBone; eBone=eBone->next){
1900                 if (!strcmp (name, eBone->name))
1901                         return eBone;
1902         }
1903         return NULL;
1904 }
1905
1906 /* note: there's a unique_bone_name() too! */
1907 void unique_editbone_name (ListBase *ebones, char *name)
1908 {
1909         char            tempname[64];
1910         int                     number;
1911         char            *dot;
1912         
1913         
1914         if (editbone_name_exists(ebones, name)) {
1915                 
1916                 /*      Strip off the suffix, if it's a number */
1917                 number= strlen(name);
1918                 if(number && isdigit(name[number-1])) {
1919                         dot= strrchr(name, '.');        // last occurrance
1920                         if (dot)
1921                                 *dot=0;
1922                 }
1923                 
1924                 for (number = 1; number <=999; number++){
1925                         sprintf (tempname, "%s.%03d", name, number);
1926                         if (!editbone_name_exists(ebones, tempname)){
1927                                 BLI_strncpy (name, tempname, 32);
1928                                 return;
1929                         }
1930                 }
1931         }
1932 }
1933
1934 /* context; editmode armature */
1935 /* if forked && mirror-edit: makes two bones with flipped names */
1936 void extrude_armature(int forked)
1937 {
1938         bArmature *arm= G.obedit->data;
1939         EditBone *newbone, *ebone, *flipbone, *first=NULL;
1940         int a, totbone= 0, do_extrude;
1941         
1942         TEST_EDITARMATURE;
1943         
1944         /* since we allow root extrude too, we have to make sure selection is OK */
1945         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1946                 if(arm->layer & ebone->layer) {
1947                         if(ebone->flag & BONE_ROOTSEL) {
1948                                 if(ebone->parent && (ebone->flag & BONE_CONNECTED)) {
1949                                         if(ebone->parent->flag & BONE_TIPSEL)
1950                                                 ebone->flag &= ~BONE_ROOTSEL;
1951                                 }
1952                         }
1953                 }
1954         }
1955         
1956         /* Duplicate the necessary bones */
1957         for (ebone = G.edbo.first; ((ebone) && (ebone!=first)); ebone=ebone->next){
1958                 if(arm->layer & ebone->layer) {
1959
1960                         /* we extrude per definition the tip */
1961                         do_extrude= 0;
1962                         if (ebone->flag & (BONE_TIPSEL|BONE_SELECTED))
1963                                 do_extrude= 1;
1964                         else if(ebone->flag & BONE_ROOTSEL) {
1965                                 /* but, a bone with parent deselected we do the root... */
1966                                 if(ebone->parent && (ebone->parent->flag & BONE_TIPSEL));
1967                                 else do_extrude= 2;
1968                         }
1969                         
1970                         if (do_extrude) {
1971                                 
1972                                 /* we re-use code for mirror editing... */
1973                                 flipbone= NULL;
1974                                 if(arm->flag & ARM_MIRROR_EDIT) {
1975                                         flipbone= armature_bone_get_mirrored(ebone);
1976                                         if (flipbone) {
1977                                                 forked= 0;      // we extrude 2 different bones
1978                                                 if(flipbone->flag & (BONE_TIPSEL|BONE_ROOTSEL|BONE_SELECTED))
1979                                                         /* don't want this bone to be selected... */
1980                                                         flipbone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1981                                         }
1982                                         if(flipbone==NULL && forked)
1983                                                 flipbone= ebone;
1984                                 }
1985                                 
1986                                 for(a=0; a<2; a++) {
1987                                         if(a==1) {
1988                                                 if(flipbone==NULL)
1989                                                         break;
1990                                                 else {
1991                                                         SWAP(EditBone *, flipbone, ebone);
1992                                                 }
1993                                         }
1994                                         
1995                                         totbone++;
1996                                         newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
1997                                         
1998                                         if(do_extrude==1) {
1999                                                 VECCOPY (newbone->head, ebone->tail);
2000                                                 VECCOPY (newbone->tail, newbone->head);
2001                                                 newbone->parent = ebone;
2002                                                 
2003                                                 newbone->flag = ebone->flag & BONE_TIPSEL;      // copies it, in case mirrored bone
2004                                         }
2005                                         else {
2006                                                 VECCOPY(newbone->head, ebone->head);
2007                                                 VECCOPY(newbone->tail, ebone->head);
2008                                                 newbone->parent= ebone->parent;
2009                                                 
2010                                                 newbone->flag= BONE_TIPSEL;
2011                                         }
2012
2013                                         newbone->weight= ebone->weight;
2014                                         newbone->dist= ebone->dist;
2015                                         newbone->xwidth= ebone->xwidth;
2016                                         newbone->zwidth= ebone->zwidth;
2017                                         newbone->ease1= ebone->ease1;
2018                                         newbone->ease2= ebone->ease2;
2019                                         newbone->rad_head= ebone->rad_tail;     // dont copy entire bone...
2020                                         newbone->rad_tail= ebone->rad_tail;
2021                                         newbone->segments= 1;
2022                                         newbone->layer= ebone->layer;
2023                                         
2024                                         if(newbone->parent) newbone->flag |= BONE_CONNECTED;
2025                                         
2026                                         BLI_strncpy (newbone->name, ebone->name, 32);
2027                                         
2028                                         if(flipbone && forked) {        // only set if mirror edit
2029                                                 if(strlen(newbone->name)<30) {
2030                                                         if(a==0) strcat(newbone->name, "_L");
2031                                                         else strcat(newbone->name, "_R");
2032                                                 }
2033                                         }
2034                                         unique_editbone_name(&G.edbo, newbone->name);
2035                                         
2036                                         /* Add the new bone to the list */
2037                                         BLI_addtail(&G.edbo, newbone);
2038                                         if (!first)
2039                                                 first = newbone;
2040                                         
2041                                         /* restore ebone if we were flipping */
2042                                         if(a==1 && flipbone) 
2043                                                 SWAP(EditBone *, flipbone, ebone);
2044
2045                                 }
2046                         }
2047                         
2048                         /* Deselect the old bone */
2049                         ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
2050                 }               
2051         }
2052         /* if only one bone, make this one active */
2053         if(totbone==1 && first) first->flag |= BONE_ACTIVE;
2054         
2055         /* Transform the endpoints */
2056         countall(); // flushes selection!
2057         BIF_TransformSetUndo("Extrude");
2058         initTransform(TFM_TRANSLATION, CTX_NO_PET);
2059         Transform();
2060         
2061         allqueue(REDRAWBUTSEDIT, 0);
2062         allqueue(REDRAWBUTSOBJECT, 0);
2063         allqueue(REDRAWOOPS, 0);
2064 }
2065
2066 /* context; editmode armature */
2067 void subdivide_armature(void)
2068 {
2069         bArmature *arm= G.obedit->data;
2070         EditBone *ebone, *newbone, *tbone, *mbone;
2071         int a;
2072         
2073         for (mbone = G.edbo.last; mbone; mbone= mbone->prev) {
2074                 if(arm->layer & mbone->layer) {
2075                         if(mbone->flag & BONE_SELECTED) {
2076                                 
2077                                 /* take care of mirrored stuff */
2078                                 for(a=0; a<2; a++) {
2079                                         if(a==0) ebone= mbone;
2080                                         else {
2081                                                 if(arm->flag & ARM_MIRROR_EDIT)
2082                                                         ebone= armature_bone_get_mirrored(mbone);
2083                                                 else ebone= NULL;
2084                                         }
2085                                         if(ebone) {
2086
2087                                                 newbone= MEM_mallocN(sizeof(EditBone), "ebone subdiv");
2088                                                 *newbone = *ebone;
2089                                                 BLI_addtail(&G.edbo, newbone);
2090                                                 
2091                                                 VecMidf(newbone->head, ebone->head, ebone->tail);
2092                                                 VECCOPY(newbone->tail, ebone->tail);
2093                                                 VECCOPY(ebone->tail, newbone->head);
2094                                                 
2095                                                 newbone->rad_head= 0.5*(ebone->rad_head+ebone->rad_tail);
2096                                                 ebone->rad_tail= newbone->rad_head;
2097
2098                                                 newbone->flag |= BONE_CONNECTED;
2099                                                 
2100                                                 unique_editbone_name (&G.edbo, newbone->name);
2101                                                 
2102                                                 /* correct parent bones */
2103                                                 for (tbone = G.edbo.first; tbone; tbone=tbone->next){
2104                                                         if(tbone->parent==ebone)
2105                                                                 tbone->parent= newbone;
2106                                                 }
2107                                                 newbone->parent= ebone;
2108                                         }
2109                                 }
2110                         }
2111                 }
2112         }
2113         BIF_undo_push("Subdivide");
2114 }
2115
2116 /* ***************** Pose tools ********************* */
2117
2118 void clear_armature(Object *ob, char mode)
2119 {
2120         bPoseChannel *pchan;
2121         bArmature       *arm;
2122
2123         arm=get_armature(ob);
2124         
2125         if (!arm)
2126                 return;
2127         
2128         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2129                 if(pchan->bone && (pchan->bone->flag & BONE_SELECTED)) {
2130                         if(arm->layer & pchan->bone->layer) {
2131                                 switch (mode){
2132                                         case 'r':
2133                                                 pchan->quat[1]=pchan->quat[2]=pchan->quat[3]=0.0F; pchan->quat[0]=1.0F;
2134                                                 break;
2135                                         case 'g':
2136                                                 pchan->loc[0]=pchan->loc[1]=pchan->loc[2]=0.0F;
2137                                                 break;
2138                                         case 's':
2139                                                 pchan->size[0]=pchan->size[1]=pchan->size[2]=1.0F;
2140                                                 break;
2141                                                 
2142                                 }
2143                         }
2144                 }
2145         }
2146         
2147         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2148         /* no update for this object, this will execute the action again */
2149         /* is weak... like for ipo editing which uses ctime now... */
2150         where_is_pose (ob);
2151         ob->recalc= 0;
2152 }
2153
2154 /* helper for function below */
2155 static int clear_active_flag(Object *ob, Bone *bone, void *data) 
2156 {
2157         bone->flag &= ~BONE_ACTIVE;
2158         return 0;
2159 }
2160
2161
2162 /* called from editview.c, for mode-less pose selection */
2163 int do_pose_selectbuffer(Base *base, unsigned int *buffer, short hits)
2164 {
2165         Object *ob= base->object;
2166         Bone *nearBone;
2167         
2168         if (!ob || !ob->pose) return 0;
2169
2170         nearBone= get_bone_from_selectbuffer(base, buffer, hits, 1);
2171
2172         if (nearBone) {
2173                 /* since we do unified select, we don't shift+select a bone if the armature object was not active yet */
2174                 if (!(G.qual & LR_SHIFTKEY) || base!=BASACT){
2175                         deselectall_posearmature(ob, 0, 0);
2176                         nearBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
2177                         select_actionchannel_by_name(ob->action, nearBone->name, 1);
2178                 }
2179                 else {
2180                         if (nearBone->flag & BONE_SELECTED) {
2181                                 /* if not active, we make it active */
2182                                 if((nearBone->flag & BONE_ACTIVE)==0) {
2183                                         bArmature *arm= ob->data;
2184                                         bone_looper(ob, arm->bonebase.first, NULL, clear_active_flag);
2185                                         
2186                                         nearBone->flag |= BONE_ACTIVE;
2187                                 }
2188                                 else {
2189                                         nearBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
2190                                         select_actionchannel_by_name(ob->action, nearBone->name, 0);
2191                                 }
2192                         }
2193                         else{
2194                                 bArmature *arm= ob->data;
2195                                 bone_looper(ob, arm->bonebase.first, NULL, clear_active_flag);
2196                                 
2197                                 nearBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
2198                                 select_actionchannel_by_name(ob->action, nearBone->name, 1);
2199                         }
2200                 }
2201                 
2202                 /* in weightpaint we select the associated vertex group too */
2203                 if(G.f & G_WEIGHTPAINT) {
2204                         if(nearBone->flag & BONE_ACTIVE) {
2205                                 vertexgroup_select_by_name(OBACT, nearBone->name);
2206                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2207                         }
2208                 }
2209                 
2210                 allqueue(REDRAWVIEW3D, 0);
2211                 allqueue(REDRAWACTION, 0);
2212                 allqueue(REDRAWIPO, 0);         /* To force action/constraint ipo update */
2213                 allqueue(REDRAWBUTSEDIT, 0);
2214                 allqueue(REDRAWBUTSOBJECT, 0);
2215                 allqueue(REDRAWOOPS, 0);
2216         }
2217         
2218         return nearBone!=NULL;
2219         
2220 }
2221
2222 /* test==0: deselect all
2223    test==1: swap select
2224    test==2: only clear active tag 
2225 */
2226 void deselectall_posearmature (Object *ob, int test, int doundo)
2227 {
2228         bArmature *arm;
2229         bPoseChannel *pchan;
2230         int     selectmode= 0;
2231         
2232         /* we call this from outliner too, but with OBACT set OK */
2233         if(!ob || !ob->pose) return;
2234         arm= get_armature(ob);
2235         
2236         /*      Determine if we're selecting or deselecting     */
2237         if (test==1) {
2238                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next)
2239                         if(pchan->bone->layer & arm->layer && !(pchan->bone->flag & BONE_HIDDEN_P))
2240                                 if(pchan->bone->flag & BONE_SELECTED)
2241                                         break;
2242                 
2243                 if (pchan==NULL)
2244                         selectmode= 1;
2245         }
2246         else if(test==2)
2247                 selectmode= 2;
2248         
2249         /*      Set the flags accordingly       */
2250         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2251                 if(pchan->bone->layer & arm->layer && !(pchan->bone->flag & BONE_HIDDEN_P)) {
2252                         if(selectmode==0) pchan->bone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
2253                         else if(selectmode==1) pchan->bone->flag |= BONE_SELECTED;
2254                         else pchan->bone->flag &= ~BONE_ACTIVE;
2255                 }
2256         }
2257         
2258         /* action editor */
2259         deselect_actionchannels(ob->action, 0); /* deselects for sure */
2260         if(selectmode==1)
2261                 deselect_actionchannels(ob->action, 1); /* swaps */
2262         
2263         allqueue(REDRAWBUTSEDIT, 0);
2264         allqueue(REDRAWBUTSOBJECT, 0);
2265         allqueue(REDRAWVIEW3D, 0);
2266         allqueue(REDRAWOOPS, 0);
2267         allqueue(REDRAWACTION, 0);
2268         
2269         countall();
2270         
2271         if (doundo) {
2272                 if (selectmode==1) BIF_undo_push("Select All");
2273                 else BIF_undo_push("Deselect All");
2274         }
2275 }
2276
2277
2278 int bone_looper(Object *ob, Bone *bone, void *data,
2279                         int (*bone_func)(Object *, Bone *, void *)) 
2280 {
2281
2282     /* We want to apply the function bone_func to every bone 
2283      * in an armature -- feed bone_looper the first bone and 
2284      * a pointer to the bone_func and watch it go!. The int count 
2285      * can be useful for counting bones with a certain property
2286      * (e.g. skinnable)
2287      */
2288     int count = 0;
2289
2290     if (bone) {
2291
2292         /* only do bone_func if the bone is non null
2293          */
2294         count += bone_func(ob, bone, data);
2295
2296         /* try to execute bone_func for the first child
2297          */
2298         count += bone_looper(ob, bone->childbase.first, data,
2299                                     bone_func);
2300
2301         /* try to execute bone_func for the next bone at this
2302          * depth of the recursion.
2303          */
2304         count += bone_looper(ob, bone->next, data, bone_func);
2305     }
2306
2307     return count;
2308 }
2309
2310
2311 static int bone_skinnable(Object *ob, Bone *bone, void *data)
2312 {
2313     /* Bones that are deforming
2314      * are regarded to be "skinnable" and are eligible for
2315      * auto-skinning.
2316      *
2317      * This function performs 2 functions:
2318      *
2319      *   a) It returns 1 if the bone is skinnable.
2320      *      If we loop over all bones with this 
2321      *      function, we can count the number of
2322      *      skinnable bones.
2323      *   b) If the pointer data is non null,
2324      *      it is treated like a handle to a
2325      *      bone pointer -- the bone pointer
2326      *      is set to point at this bone, and
2327      *      the pointer the handle points to
2328      *      is incremented to point to the
2329      *      next member of an array of pointers
2330      *      to bones. This way we can loop using
2331      *      this function to construct an array of
2332      *      pointers to bones that point to all
2333      *      skinnable bones.
2334      */
2335     Bone ***hbone;
2336
2337     if (!(bone->flag & BONE_NO_DEFORM)) {
2338                 if (data != NULL) {
2339                         hbone = (Bone ***) data;
2340             **hbone = bone;
2341             ++*hbone;
2342         }
2343         return 1;
2344     }
2345     return 0;
2346 }
2347
2348 static int add_defgroup_unique_bone(Object *ob, Bone *bone, void *data) 
2349 {
2350     /* This group creates a vertex group to ob that has the
2351      * same name as bone (provided the bone is skinnable). 
2352          * If such a vertex group aleady exist the routine exits.
2353      */
2354         if (!(bone->flag & BONE_NO_DEFORM)) {
2355                 if (!get_named_vertexgroup(ob,bone->name)) {
2356                         add_defgroup_name(ob, bone->name);
2357                         return 1;
2358                 }
2359     }
2360     return 0;
2361 }
2362
2363 static int dgroup_skinnable(Object *ob, Bone *bone, void *data) 
2364 {
2365     /* Bones that are deforming
2366      * are regarded to be "skinnable" and are eligible for
2367      * auto-skinning.
2368      *
2369      * This function performs 2 functions:
2370      *
2371      *   a) If the bone is skinnable, it creates 
2372      *      a vertex group for ob that has
2373      *      the name of the skinnable bone
2374      *      (if one doesn't exist already).
2375      *   b) If the pointer data is non null,
2376      *      it is treated like a handle to a
2377      *      bDeformGroup pointer -- the 
2378      *      bDeformGroup pointer is set to point
2379      *      to the deform group with the bone's
2380      *      name, and the pointer the handle 
2381      *      points to is incremented to point to the
2382      *      next member of an array of pointers
2383      *      to bDeformGroups. This way we can loop using
2384      *      this function to construct an array of
2385      *      pointers to bDeformGroups, all with names
2386      *      of skinnable bones.
2387      */
2388     bDeformGroup ***hgroup, *defgroup;
2389
2390    if (!(bone->flag & BONE_NO_DEFORM)) {
2391         if ( !(defgroup = get_named_vertexgroup(ob, bone->name)) ) {
2392             defgroup = add_defgroup_name(ob, bone->name);
2393         }
2394
2395         if (data != NULL) {
2396             hgroup = (bDeformGroup ***) data;
2397             **hgroup = defgroup;
2398             ++*hgroup;
2399         }
2400         return 1;
2401     }
2402     return 0;
2403 }
2404
2405 static void add_verts_to_closest_dgroup(Object *ob, Object *par)
2406 {
2407     /* This function implements a crude form of 
2408      * auto-skinning: vertices are assigned to the
2409      * deformation groups associated with bones based
2410      * on thier proximity to a bone. Every vert is
2411      * given a weight of 1.0 to the weight group
2412      * cooresponding to the bone that it is
2413      * closest to. The vertex may also be assigned to
2414      * a deformation group associated to a bone
2415      * that is within 10% of the mninimum distance
2416      * between the bone and the nearest vert -- the
2417      * cooresponding weight will fall-off to zero
2418      * as the distance approaches the 10% tolerance mark.
2419          * If the mesh has subsurf enabled then the verts
2420          * on the subsurf limit surface is used to generate 
2421          * the weights rather than the verts on the cage
2422          * mesh.
2423          *
2424          * ("Limit surface" = same amount of vertices as mesh, but vertices 
2425      *   moved to the subsurfed position, like for 'optimal').
2426      */
2427
2428     bArmature *arm;
2429     Bone **bonelist, **bonehandle, *bone;
2430     bDeformGroup **dgrouplist, **dgrouphandle, *defgroup;
2431     float *distance;
2432     float   root[3];
2433     float   tip[3];
2434     float real_co[3];
2435         float *subverts = NULL;
2436     float *subvert;
2437     Mesh  *mesh;
2438     MVert *vert;
2439
2440     int numbones, i, j;
2441
2442     /* If the parent object is not an armature exit */
2443     arm = get_armature(par);
2444     if (!arm)
2445         return;
2446
2447     /* count the number of skinnable bones */
2448     numbones = bone_looper(ob, arm->bonebase.first, NULL,
2449                                   bone_skinnable);
2450         
2451     /* create an array of pointer to bones that are skinnable
2452      * and fill it with all of the skinnable bones
2453      */
2454     bonelist = MEM_mallocN(numbones*sizeof(Bone *), "bonelist");
2455     bonehandle = bonelist;
2456     bone_looper(ob, arm->bonebase.first, &bonehandle,
2457                        bone_skinnable);
2458
2459     /* create an array of pointers to the deform groups that
2460      * coorespond to the skinnable bones (creating them
2461      * as necessary.
2462      */
2463     dgrouplist = MEM_mallocN(numbones*sizeof(bDeformGroup *), "dgrouplist");
2464     dgrouphandle = dgrouplist;
2465     bone_looper(ob, arm->bonebase.first, &dgrouphandle,
2466                        dgroup_skinnable);
2467
2468     /* create an array of floats that will be used for each vert
2469      * to hold the distance-factor to each bone.
2470      */
2471     distance = MEM_mallocN(numbones*sizeof(float), "distance");
2472
2473     mesh = (Mesh*)ob->data;
2474
2475         /* Is subsurf on? Lets use the verts on the limit surface then */
2476         if (modifiers_findByType(ob, eModifierType_Subsurf)) {
2477                 subverts = MEM_mallocN(3*mesh->totvert*sizeof(float), "subverts");
2478                 subsurf_calculate_limit_positions(mesh, (void *)subverts);      /* (ton) made void*, dunno how to cast */
2479         }
2480
2481     /* for each vertex in the mesh ...
2482      */
2483     for ( i=0 ; i < mesh->totvert ; ++i ) {
2484         /* get the vert in global coords
2485          */
2486                 
2487                 if (subverts) {
2488                         subvert = subverts + i*3;
2489                         VECCOPY (real_co, subvert);
2490                 }
2491                 else {
2492                         vert = mesh->mvert + i;
2493                         VECCOPY (real_co, vert->co);
2494                 }
2495         Mat4MulVecfl(ob->obmat, real_co);
2496
2497
2498         /* for each skinnable bone ...
2499          */
2500         for (j=0; j < numbones; ++j) {
2501             bone = bonelist[j];
2502
2503             /* get the root of the bone in global coords
2504              */
2505                         VECCOPY(root, bone->arm_head);
2506                         Mat4MulVecfl(par->obmat, root);
2507
2508             /* get the tip of the bone in global coords
2509              */
2510                         VECCOPY(tip, bone->arm_tail);
2511             Mat4MulVecfl(par->obmat, tip);
2512
2513             /* store the distance-factor from the vertex to
2514              * the bone
2515              */
2516                         distance[j]= distfactor_to_bone (real_co, root, tip, bone->rad_head, bone->rad_tail, bone->dist);
2517         }
2518
2519         /* for each deform group ...
2520          */
2521         for (j=0; j < numbones; ++j) {
2522             defgroup = dgrouplist[j];
2523
2524             /* add the vert to the deform group if weight!=0.0
2525              */
2526             if (distance[j]!=0.0)
2527                 add_vert_to_defgroup (ob, defgroup, i, distance[j], WEIGHT_REPLACE);
2528             else
2529                 remove_vert_defgroup (ob, defgroup, i);
2530         }
2531     }
2532
2533     /* free the memory allocated
2534      */
2535     MEM_freeN(bonelist);
2536     MEM_freeN(dgrouplist);
2537     MEM_freeN(distance);
2538         if (subverts) MEM_freeN(subverts);
2539 }
2540
2541 void create_vgroups_from_armature(Object *ob, Object *par)
2542 {
2543         /* Lets try to create some vertex groups 
2544          * based on the bones of the parent armature.
2545          */
2546
2547         bArmature *arm;
2548         short mode;
2549
2550         /* If the parent object is not an armature exit */
2551         arm = get_armature(par);
2552         if (!arm)
2553                 return;
2554
2555         /* Prompt the user on whether/how they want the vertex groups
2556          * added to the child mesh */
2557     mode= pupmenu("Create Vertex Groups? %t|"
2558                                   "Don't Create Groups %x1|"
2559                                   "Name Groups %x2|"
2560                   "Create From Closest Bones %x3");
2561         switch (mode){
2562         case 2:
2563                 /* Traverse the bone list, trying to create empty vertex 
2564                  * groups cooresponding to the bone.
2565                  */
2566                 bone_looper(ob, arm->bonebase.first, NULL,
2567                                         add_defgroup_unique_bone);
2568                 if (ob->type == OB_MESH)
2569                         create_dverts(ob->data);
2570
2571                 break;
2572
2573         case 3:
2574                 /* Traverse the bone list, trying to create vertex groups 
2575                  * that are populated with the vertices for which the
2576                  * bone is closest.
2577                  */
2578                 add_verts_to_closest_dgroup(ob, par);
2579                 break;
2580
2581         }
2582
2583
2584 static int hide_selected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2585 {
2586         bArmature *arm= ob->data;
2587         
2588         if(arm->layer & bone->layer) {
2589                 if (bone->flag & BONE_SELECTED) {
2590                         bone->flag |= BONE_HIDDEN_P;
2591                         bone->flag &= ~BONE_SELECTED;
2592                 }
2593         }
2594         return 0;
2595 }
2596
2597 /* active object is armature */
2598 void hide_selected_pose_bones(void) 
2599 {
2600         bArmature *arm= OBACT->data;
2601
2602         if (!arm)
2603                 return;
2604
2605         bone_looper(OBACT, arm->bonebase.first, NULL, 
2606                                 hide_selected_pose_bone);
2607
2608         allqueue(REDRAWVIEW3D, 0);
2609         allqueue(REDRAWBUTSEDIT, 0);
2610         allqueue(REDRAWACTION, 0);
2611         BIF_undo_push("Hide Bones");
2612 }
2613
2614 static int hide_unselected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2615 {
2616         bArmature *arm= ob->data;
2617         
2618         if(arm->layer & bone->layer) {
2619                 if (~bone->flag & BONE_SELECTED) {
2620                         bone->flag |= BONE_HIDDEN_P;
2621                 }
2622         }
2623         return 0;
2624 }
2625
2626 /* active object is armature */
2627 void hide_unselected_pose_bones(void) 
2628 {
2629         bArmature               *arm;
2630
2631         arm=get_armature (OBACT);
2632
2633         if (!arm)
2634                 return;
2635
2636         bone_looper(OBACT, arm->bonebase.first, NULL, 
2637                                 hide_unselected_pose_bone);
2638
2639         allqueue(REDRAWVIEW3D, 0);
2640         allqueue(REDRAWBUTSEDIT, 0);
2641         BIF_undo_push("Hide Unselected Bone");
2642 }
2643
2644 static int show_pose_bone(Object *ob, Bone *bone, void *ptr) 
2645 {
2646         bArmature *arm= ob->data;
2647         
2648         if(arm->layer & bone->layer) {
2649                 if (bone->flag & BONE_HIDDEN_P) {
2650                         bone->flag &= ~BONE_HIDDEN_P;
2651                         bone->flag |= BONE_SELECTED;
2652                 }
2653         }
2654
2655         return 0;
2656 }
2657
2658 /* active object is armature in posemode */
2659 void show_all_pose_bones(void) 
2660 {
2661         bArmature               *arm;
2662
2663         arm=get_armature (OBACT);
2664
2665         if (!arm)
2666                 return;
2667
2668         bone_looper(OBACT, arm->bonebase.first, NULL, 
2669                                 show_pose_bone);
2670
2671         allqueue(REDRAWVIEW3D, 0);
2672         allqueue(REDRAWBUTSEDIT, 0);
2673         BIF_undo_push("Reveal Bones");
2674 }
2675
2676
2677 /* ************* RENAMING DISASTERS ************ */
2678
2679 /* note: there's a unique_editbone_name() too! */
2680 void unique_bone_name (bArmature *arm, char *name)
2681 {
2682         char            tempname[64];
2683         int                     number;
2684         char            *dot;
2685         
2686         if (get_named_bone(arm, name)) {
2687                 
2688                 /*      Strip off the suffix, if it's a number */
2689                 number= strlen(name);
2690                 if(number && isdigit(name[number-1])) {
2691                         dot= strrchr(name, '.');        // last occurrance
2692                         if (dot)
2693                                 *dot=0;
2694                 }
2695                 
2696                 for (number = 1; number <=999; number++){
2697                         sprintf (tempname, "%s.%03d", name, number);
2698                         if (!get_named_bone(arm, tempname)){
2699                                 BLI_strncpy (name, tempname, 32);
2700                                 return;
2701                         }
2702                 }
2703         }
2704 }
2705
2706 #define MAXBONENAME 32
2707 /* helper call for below */
2708 static void constraint_bone_name_fix(Object *ob, ListBase *conlist, char *oldname, char *newname)
2709 {
2710         bConstraint *curcon;
2711         char *subtarget;
2712         
2713         for (curcon = conlist->first; curcon; curcon=curcon->next){
2714                 subtarget = get_con_subtarget_name(curcon, ob);
2715                 if (subtarget)
2716                         if (!strcmp(subtarget, oldname) )
2717                                 BLI_strncpy(subtarget, newname, MAXBONENAME);
2718         }
2719 }
2720
2721 /* called by UI for renaming a bone */
2722 /* warning: make sure the original bone was not renamed yet! */
2723 /* seems messy, but thats what you get with not using pointers but channel names :) */
2724 void armature_bone_rename(bArmature *arm, char *oldnamep, char *newnamep)
2725 {
2726         Object *ob;
2727         char newname[MAXBONENAME];
2728         char oldname[MAXBONENAME];
2729         
2730         /* names better differ! */
2731         if(strncmp(oldnamep, newnamep, MAXBONENAME)) {
2732                 
2733                 /* we alter newname string... so make copy */
2734                 BLI_strncpy(newname, newnamep, MAXBONENAME);
2735                 /* we use oldname for search... so make copy */
2736                 BLI_strncpy(oldname, oldnamep, MAXBONENAME);
2737                 
2738                 /* now check if we're in editmode, we need to find the unique name */
2739                 if(G.obedit && G.obedit->data==arm) {
2740                         EditBone        *eBone;
2741
2742                         eBone= editbone_name_exists(&G.edbo, oldname);
2743                         if(eBone) {
2744                                 unique_editbone_name (&G.edbo, newname);
2745                                 BLI_strncpy(eBone->name, newname, MAXBONENAME);
2746                         }
2747                         else return;
2748                 }
2749                 else {
2750                         Bone *bone= get_named_bone (arm, oldname);
2751
2752                         if(bone) {
2753                                 unique_bone_name (arm, newname);
2754                                 BLI_strncpy(bone->name, newname, MAXBONENAME);
2755                         }
2756                         else return;
2757                 }
2758                 
2759                 /* do entire dbase */
2760                 for(ob= G.main->object.first; ob; ob= ob->id.next) {
2761                         /* we have the object using the armature */
2762                         if(arm==ob->data) {
2763                                 Object *cob;
2764                                 bAction  *act;
2765                                 bActionChannel *achan;
2766                                 bActionStrip *strip;
2767
2768                                 /* Rename action channel if necessary */
2769                                 act = ob->action;
2770                                 if (act && !act->id.lib) {
2771                                         /*      Find the appropriate channel */
2772                                         achan= get_action_channel(act, oldname);
2773                                         if(achan) BLI_strncpy(achan->name, newname, MAXBONENAME);
2774                                 }
2775                 
2776                                 /* Rename the pose channel, if it exists */
2777                                 if (ob->pose) {
2778                                         bPoseChannel *pchan = get_pose_channel(ob->pose, oldname);
2779                                         if (pchan) {
2780                                                 BLI_strncpy (pchan->name, newname, MAXBONENAME);
2781                                         }
2782                                 }
2783                                 
2784                                 /* check all nla-strips too */
2785                                 for (strip= ob->nlastrips.first; strip; strip= strip->next) {
2786                                         /* Rename action channel if necessary */
2787                                         act = strip->act;
2788                                         if (act && !act->id.lib) {
2789                                                 /*      Find the appropriate channel */
2790                                                 achan= get_action_channel(act, oldname);
2791                                                 if(achan) BLI_strncpy(achan->name, newname, MAXBONENAME);
2792                                         }
2793                                 }
2794                                 
2795                                 /* Update any object constraints to use the new bone name */
2796                                 for(cob= G.main->object.first; cob; cob= cob->id.next) {
2797                                         if(cob->constraints.first)
2798                                                 constraint_bone_name_fix(ob, &cob->constraints, oldname, newname);
2799                                         if (cob->pose) {
2800                                                 bPoseChannel *pchan;
2801                                                 for (pchan = cob->pose->chanbase.first; pchan; pchan=pchan->next) {
2802                                                         constraint_bone_name_fix(ob, &pchan->constraints, oldname, newname);
2803                                                 }
2804                                         }
2805                                 }
2806                         }
2807                                         
2808                         /* See if an object is parented to this armature */
2809                         if (ob->parent && (ob->parent->data == arm)) {
2810                                 if(ob->partype==PARBONE) {
2811                                         /* bone name in object */
2812                                         if (!strcmp(ob->parsubstr, oldname))
2813                                                 BLI_strncpy(ob->parsubstr, newname, MAXBONENAME);
2814                                 }
2815                         }
2816                         
2817                         if(modifiers_usesArmature(ob, arm)) { 
2818                                 bDeformGroup *dg;
2819                                 /* bone name in defgroup */
2820                                 for (dg=ob->defbase.first; dg; dg=dg->next) {
2821                                         if(!strcmp(dg->name, oldname))
2822                                            BLI_strncpy(dg->name, newname, MAXBONENAME);
2823                                 }
2824                         }
2825                 }
2826         }
2827 }
2828
2829 /* context editmode object */
2830 void armature_flip_names(void)
2831 {
2832         bArmature *arm= G.obedit->data;
2833         EditBone *ebone;
2834         char newname[32];
2835         
2836         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2837                 if(arm->layer & ebone->layer) {
2838                         if(ebone->flag & BONE_SELECTED) {
2839                                 BLI_strncpy(newname, ebone->name, sizeof(newname));
2840                                 bone_flip_name(newname, 1);             // 1 = do strip off number extensions
2841                                 armature_bone_rename(G.obedit->data, ebone->name, newname);
2842                         }
2843                 }
2844         }
2845         
2846         allqueue(REDRAWVIEW3D, 0);
2847         allqueue(REDRAWBUTSEDIT, 0);
2848         allqueue(REDRAWBUTSOBJECT, 0);
2849         allqueue (REDRAWACTION, 0);
2850         allqueue(REDRAWOOPS, 0);
2851         BIF_undo_push("Flip names");
2852         
2853 }
2854
2855 /* context; editmode armature */
2856 EditBone *armature_bone_get_mirrored(EditBone *ebo)
2857 {
2858         EditBone *eboflip= NULL;
2859         char name[32];
2860         
2861         BLI_strncpy(name, ebo->name, sizeof(name));
2862         bone_flip_name(name, 0);                // 0 = don't strip off number extensions
2863
2864         for (eboflip=G.edbo.first; eboflip; eboflip=eboflip->next)
2865                 if(ebo!=eboflip)
2866                         if (!strcmp (name, eboflip->name)) break;
2867         
2868         return eboflip;
2869 }
2870
2871 /* if editbone (partial) selected, copy data */
2872 /* context; editmode armature, with mirror editing enabled */
2873 void transform_armature_mirror_update(void)
2874 {
2875         EditBone *ebo, *eboflip;
2876         
2877         for (ebo=G.edbo.first; ebo; ebo=ebo->next) {
2878                 /* no layer check, correct mirror is more important */
2879                 if(ebo->flag & (BONE_TIPSEL|BONE_ROOTSEL)) {
2880                         
2881                         eboflip= armature_bone_get_mirrored(ebo);
2882                         
2883                         if(eboflip) {
2884                                 /* we assume X-axis flipping for now */
2885                                 if(ebo->flag & BONE_TIPSEL) {
2886                                         eboflip->tail[0]= -ebo->tail[0];
2887                                         eboflip->tail[1]= ebo->tail[1];
2888                                         eboflip->tail[2]= ebo->tail[2];
2889                                         eboflip->rad_tail= ebo->rad_tail;
2890                                 }
2891                                 if(ebo->flag & BONE_ROOTSEL) {
2892                                         eboflip->head[0]= -ebo->head[0];
2893                                         eboflip->head[1]= ebo->head[1];
2894                                         eboflip->head[2]= ebo->head[2];
2895                                         eboflip->rad_head= ebo->rad_head;
2896                                 }
2897                                 if(ebo->flag & BONE_SELECTED) {
2898                                         eboflip->dist= ebo->dist;
2899                                         eboflip->xwidth= ebo->xwidth;
2900                                         eboflip->zwidth= ebo->zwidth;
2901                                 }
2902                         }
2903                 }
2904         }
2905 }
2906