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