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