Fix combined pose + weight paint mode, was using wrong object
[blender.git] / source / blender / editors / armature / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL 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.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation, 2002-2009 full recode.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <math.h> 
32 #include <float.h> 
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_action_types.h"
37 #include "DNA_armature_types.h"
38 #include "DNA_constraint_types.h"
39 #include "DNA_ID.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_nla_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_userdef_types.h"
48 #include "DNA_view3d_types.h"
49 #include "DNA_modifier_types.h"
50 #include "DNA_ipo_types.h"
51 #include "DNA_curve_types.h"
52
53 #include "BLI_blenlib.h"
54 #include "BLI_arithb.h"
55 #include "BLI_editVert.h"
56 #include "BLI_ghash.h"
57
58 #include "BKE_action.h"
59 #include "BKE_armature.h"
60 #include "BKE_constraint.h"
61 #include "BKE_context.h"
62 #include "BKE_deform.h"
63 #include "BKE_depsgraph.h"
64 #include "BKE_DerivedMesh.h"
65 #include "BKE_global.h"
66 #include "BKE_main.h"
67 #include "BKE_object.h"
68 #include "BKE_report.h"
69 #include "BKE_subsurf.h"
70 #include "BKE_utildefines.h"
71 #include "BKE_modifier.h"
72 #include "PIL_time.h"
73
74 #include "BIF_gl.h"
75 #include "BIF_generate.h"
76
77 #include "RNA_access.h"
78 #include "RNA_define.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 #include "ED_armature.h"
84 #include "ED_mesh.h"
85 #include "ED_object.h"
86 #include "ED_screen.h"
87 #include "ED_transform.h"
88 #include "ED_util.h"
89 #include "ED_view3d.h"
90
91 #include "UI_interface.h"
92
93 #include "armature_intern.h"
94 #include "meshlaplacian.h"
95
96 #if 0
97 #include "reeb.h"
98 #endif
99
100 /* ************* XXX *************** */
101 static int okee() {return 0;}
102 static void BIF_undo_push(const char *msg) {}
103 /* ************* XXX *************** */
104
105 /* **************** tools on Editmode Armature **************** */
106
107 /* Sync selection to parent for connected children */
108 void ED_armature_sync_selection(ListBase *edbo)
109 {
110         EditBone *ebo;
111         
112         for (ebo=edbo->first; ebo; ebo= ebo->next) {
113                 if ((ebo->flag & BONE_CONNECTED) && (ebo->parent)) {
114                         if (ebo->parent->flag & BONE_TIPSEL)
115                                 ebo->flag |= BONE_ROOTSEL;
116                         else
117                                 ebo->flag &= ~BONE_ROOTSEL;
118                 }
119                 
120                 if ((ebo->flag & BONE_TIPSEL) && (ebo->flag & BONE_ROOTSEL))
121                         ebo->flag |= BONE_SELECTED;
122                 else
123                         ebo->flag &= ~BONE_SELECTED;
124         }                               
125 }
126
127 /* converts Bones to EditBone list, used for tools as well */
128 void make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent)
129 {
130         EditBone        *eBone;
131         Bone            *curBone;
132         float delta[3];
133         float premat[3][3];
134         float postmat[3][3];
135         float imat[3][3];
136         float difmat[3][3];
137                 
138         for (curBone=bones->first; curBone; curBone=curBone->next) {
139                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
140                 
141                 /*      Copy relevant data from bone to eBone */
142                 eBone->parent= parent;
143                 BLI_strncpy(eBone->name, curBone->name, 32);
144                 eBone->flag = curBone->flag;
145                 
146                 /* fix selection flags */
147                 if (eBone->flag & BONE_SELECTED) {
148                         eBone->flag |= BONE_TIPSEL;
149                         if (eBone->parent && (eBone->flag & BONE_CONNECTED))
150                                 eBone->parent->flag |= BONE_TIPSEL;
151                         else 
152                                 eBone->flag |= BONE_ROOTSEL;
153                 }
154                 else 
155                         eBone->flag &= ~BONE_ROOTSEL;
156                 
157                 VECCOPY(eBone->head, curBone->arm_head);
158                 VECCOPY(eBone->tail, curBone->arm_tail);                
159                 
160                 eBone->roll= 0.0f;
161                 
162                 /* roll fixing */
163                 VecSubf(delta, eBone->tail, eBone->head);
164                 vec_roll_to_mat3(delta, 0.0f, postmat);
165                 
166                 Mat3CpyMat4(premat, curBone->arm_mat);
167                 
168                 Mat3Inv(imat, postmat);
169                 Mat3MulMat3(difmat, imat, premat);
170                 
171                 eBone->roll = (float)atan2(difmat[2][0], difmat[2][2]);
172                 
173                 /* rest of stuff copy */
174                 eBone->length= curBone->length;
175                 eBone->dist= curBone->dist;
176                 eBone->weight= curBone->weight;
177                 eBone->xwidth= curBone->xwidth;
178                 eBone->zwidth= curBone->zwidth;
179                 eBone->ease1= curBone->ease1;
180                 eBone->ease2= curBone->ease2;
181                 eBone->rad_head= curBone->rad_head;
182                 eBone->rad_tail= curBone->rad_tail;
183                 eBone->segments = curBone->segments;            
184                 eBone->layer = curBone->layer;
185                 
186                 BLI_addtail(edbo, eBone);
187                 
188                 /*      Add children if necessary */
189                 if (curBone->childbase.first) 
190                         make_boneList(edbo, &curBone->childbase, eBone);
191         }
192 }
193
194 /* nasty stuff for converting roll in editbones into bones */
195 /* also sets restposition in armature (arm_mat) */
196 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
197 {
198         Bone *curBone;
199         EditBone *ebone;
200         float premat[3][3];
201         float postmat[3][3];
202         float difmat[3][3];
203         float imat[3][3];
204         float delta[3];
205         
206         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
207                 /* sets local matrix and arm_mat (restpos) */
208                 where_is_armature_bone(curBone, curBone->parent);
209                 
210                 /* Find the associated editbone */
211                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
212                         if ((Bone*)ebone->temp == curBone)
213                                 break;
214                 
215                 if (ebone) {
216                         /* Get the ebone premat */
217                         VecSubf(delta, ebone->tail, ebone->head);
218                         vec_roll_to_mat3(delta, ebone->roll, premat);
219                         
220                         /* Get the bone postmat */
221                         Mat3CpyMat4(postmat, curBone->arm_mat);
222                         
223                         Mat3Inv(imat, premat);
224                         Mat3MulMat3(difmat, imat, postmat);
225 #if 0
226                         printf ("Bone %s\n", curBone->name);
227                         printmatrix4("premat", premat);
228                         printmatrix4("postmat", postmat);
229                         printmatrix4("difmat", difmat);
230                         printf ("Roll = %f\n",  (-atan2(difmat[2][0], difmat[2][2]) * (180.0/M_PI)));
231 #endif
232                         curBone->roll = (float)-atan2(difmat[2][0], difmat[2][2]);
233                         
234                         /* and set restposition again */
235                         where_is_armature_bone(curBone, curBone->parent);
236                 }
237                 fix_bonelist_roll(&curBone->childbase, editbonelist);
238         }
239 }
240
241 /* put EditMode back in Object */
242 void ED_armature_from_edit(Object *obedit)
243 {
244         bArmature *arm= obedit->data;
245         EditBone *eBone, *neBone;
246         Bone    *newBone;
247         Object *obt;
248         
249         /* armature bones */
250         free_bones(arm);
251         
252         /* remove zero sized bones, this gives instable restposes */
253         for (eBone=arm->edbo->first; eBone; eBone= neBone) {
254                 float len= VecLenf(eBone->head, eBone->tail);
255                 neBone= eBone->next;
256                 if (len <= 0.000001f) {         /* FLT_EPSILON is too large? */
257                         EditBone *fBone;
258                         
259                         /*      Find any bones that refer to this bone  */
260                         for (fBone=arm->edbo->first; fBone; fBone= fBone->next) {
261                                 if (fBone->parent==eBone)
262                                         fBone->parent= eBone->parent;
263                         }
264                         printf("Warning: removed zero sized bone: %s\n", eBone->name);
265                         BLI_freelinkN(arm->edbo, eBone);
266                 }
267         }
268         
269         /*      Copy the bones from the editData into the armature */
270         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
271                 newBone= MEM_callocN(sizeof(Bone), "bone");
272                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
273                 
274                 BLI_strncpy(newBone->name, eBone->name, 32);
275                 memcpy(newBone->head, eBone->head, sizeof(float)*3);
276                 memcpy(newBone->tail, eBone->tail, sizeof(float)*3);
277                 newBone->flag= eBone->flag;
278                 if (eBone->flag & BONE_ACTIVE) 
279                         newBone->flag |= BONE_SELECTED; /* important, editbones can be active with only 1 point selected */
280                 newBone->roll = 0.0f;
281                 
282                 newBone->weight = eBone->weight;
283                 newBone->dist = eBone->dist;
284                 
285                 newBone->xwidth = eBone->xwidth;
286                 newBone->zwidth = eBone->zwidth;
287                 newBone->ease1= eBone->ease1;
288                 newBone->ease2= eBone->ease2;
289                 newBone->rad_head= eBone->rad_head;
290                 newBone->rad_tail= eBone->rad_tail;
291                 newBone->segments= eBone->segments;
292                 newBone->layer = eBone->layer;
293         }
294         
295         /*      Fix parenting in a separate pass to ensure ebone->bone connections
296                 are valid at this point */
297         for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
298                 newBone= (Bone *)eBone->temp;
299                 if (eBone->parent) {
300                         newBone->parent= (Bone *)eBone->parent->temp;
301                         BLI_addtail(&newBone->parent->childbase, newBone);
302                         
303                         {
304                                 float M_boneRest[3][3];
305                                 float M_parentRest[3][3];
306                                 float iM_parentRest[3][3];
307                                 float   delta[3];
308                                 
309                                 /* Get the parent's  matrix (rotation only) */
310                                 VecSubf(delta, eBone->parent->tail, eBone->parent->head);
311                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
312                                 
313                                 /* Get this bone's  matrix (rotation only) */
314                                 VecSubf(delta, eBone->tail, eBone->head);
315                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
316                                 
317                                 /* Invert the parent matrix */
318                                 Mat3Inv(iM_parentRest, M_parentRest);
319                                 
320                                 /* Get the new head and tail */
321                                 VecSubf(newBone->head, eBone->head, eBone->parent->tail);
322                                 VecSubf(newBone->tail, eBone->tail, eBone->parent->tail);
323                                 
324                                 Mat3MulVecfl(iM_parentRest, newBone->head);
325                                 Mat3MulVecfl(iM_parentRest, newBone->tail);
326                         }
327                 }
328                 /*      ...otherwise add this bone to the armature's bonebase */
329                 else
330                         BLI_addtail(&arm->bonebase, newBone);
331         }
332         
333         /* Make a pass through the new armature to fix rolling */
334         /* also builds restposition again (like where_is_armature) */
335         fix_bonelist_roll(&arm->bonebase, arm->edbo);
336         
337         /* so all users of this armature should get rebuilt */
338         for (obt= G.main->object.first; obt; obt= obt->id.next) {
339                 if (obt->data==arm)
340                         armature_rebuild_pose(obt, arm);
341         }
342         
343         DAG_id_flush_update(&obedit->id, OB_RECALC_DATA);
344 }
345
346 void ED_armature_apply_transform(Object *ob, float mat[4][4])
347 {
348         EditBone *ebone;
349         bArmature *arm= ob->data;
350         float scale = Mat4ToScalef(mat);        /* store the scale of the matrix here to use on envelopes */
351         
352         /* Put the armature into editmode */
353         ED_armature_to_edit(ob);
354
355         /* Do the rotations */
356         for (ebone = arm->edbo->first; ebone; ebone=ebone->next){
357                 Mat4MulVecfl(mat, ebone->head);
358                 Mat4MulVecfl(mat, ebone->tail);
359                 
360                 ebone->rad_head *= scale;
361                 ebone->rad_tail *= scale;
362                 ebone->dist             *= scale;
363         }
364         
365         /* Turn the list into an armature */
366         ED_armature_from_edit(ob);
367         ED_armature_edit_free(ob);
368 }
369
370 /* exported for use in editors/object/ */
371 /* 0 == do center, 1 == center new, 2 == center cursor */
372 void docenter_armature (Scene *scene, View3D *v3d, Object *ob, int centermode)
373 {
374         Object *obedit= scene->obedit; // XXX get from context
375         EditBone *ebone;
376         bArmature *arm= ob->data;
377         float cent[3] = {0.0f, 0.0f, 0.0f};
378         float min[3], max[3];
379         float omat[3][3];
380
381         /* Put the armature into editmode */
382         if(ob!=obedit)
383                 ED_armature_to_edit(ob);
384
385         /* Find the centerpoint */
386         if (centermode == 2) {
387                 float *fp= give_cursor(scene, v3d);
388                 VECCOPY(cent, fp);
389                 Mat4Invert(ob->imat, ob->obmat);
390                 Mat4MulVecfl(ob->imat, cent);
391         }
392         else {
393                 INIT_MINMAX(min, max);
394                 
395                 for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
396                         DO_MINMAX(ebone->head, min, max);
397                         DO_MINMAX(ebone->tail, min, max);
398                 }
399                 
400                 cent[0]= (min[0] + max[0]) / 2.0f;
401                 cent[1]= (min[1] + max[1]) / 2.0f;
402                 cent[2]= (min[2] + max[2]) / 2.0f;
403         }
404         
405         /* Do the adjustments */
406         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
407                 VecSubf(ebone->head, ebone->head, cent);
408                 VecSubf(ebone->tail, ebone->tail, cent);
409         }
410         
411         /* Turn the list into an armature */
412         ED_armature_from_edit(ob);
413         
414         /* Adjust object location for new centerpoint */
415         if(centermode && obedit==NULL) {
416                 Mat3CpyMat4(omat, ob->obmat);
417                 
418                 Mat3MulVecfl(omat, cent);
419                 ob->loc[0] += cent[0];
420                 ob->loc[1] += cent[1];
421                 ob->loc[2] += cent[2];
422         }
423         else 
424                 ED_armature_edit_free(ob);
425 }
426
427 /* ---------------------- */
428
429 static EditBone *editbone_name_exists (ListBase *edbo, char *name)
430 {
431         EditBone        *eBone;
432         
433         for (eBone=edbo->first; eBone; eBone=eBone->next) {
434                 if (!strcmp(name, eBone->name))
435                         return eBone;
436         }
437         return NULL;
438 }
439
440 /* note: there's a unique_bone_name() too! */
441 void unique_editbone_name (ListBase *edbo, char *name, EditBone *bone)
442 {
443         EditBone *dupli;
444         char            tempname[64];
445         int                     number;
446         char            *dot;
447
448         dupli = editbone_name_exists(edbo, name);
449         
450         if (dupli && bone != dupli) {
451                 /*      Strip off the suffix, if it's a number */
452                 number= strlen(name);
453                 if (number && isdigit(name[number-1])) {
454                         dot= strrchr(name, '.');        // last occurrance
455                         if (dot)
456                                 *dot=0;
457                 }
458                 
459                 for (number = 1; number <= 999; number++) {
460                         sprintf(tempname, "%s.%03d", name, number);
461                         if (!editbone_name_exists(edbo, tempname)) {
462                                 BLI_strncpy(name, tempname, 32);
463                                 return;
464                         }
465                 }
466         }
467 }
468
469 /* helper for apply_armature_pose2bones - fixes parenting of objects that are bone-parented to armature */
470 static void applyarmature_fix_boneparents (Scene *scene, Object *armob)
471 {
472         Object workob, *ob;
473         
474         /* go through all objects in database */
475         for (ob= G.main->object.first; ob; ob= ob->id.next) {
476                 /* if parent is bone in this armature, apply corrections */
477                 if ((ob->parent == armob) && (ob->partype == PARBONE)) {
478                         /* apply current transform from parent (not yet destroyed), 
479                          * then calculate new parent inverse matrix
480                          */
481                         ED_object_apply_obmat(ob);
482                         
483                         what_does_parent(scene, ob, &workob);
484                         Mat4Invert(ob->parentinv, workob.obmat);
485                 }
486         }
487 }
488
489 /* set the current pose as the restpose */
490 static int apply_armature_pose2bones_exec (bContext *C, wmOperator *op)
491 {
492         Scene *scene= CTX_data_scene(C);
493         Object *ob= CTX_data_active_object(C); // must be active object, not edit-object
494         bArmature *arm= get_armature(ob);
495         bPose *pose;
496         bPoseChannel *pchan;
497         EditBone *curbone;
498         
499         /* don't check if editmode (should be done by caller) */
500         if (ob->type!=OB_ARMATURE)
501                 return OPERATOR_CANCELLED;
502         if (object_data_is_libdata(ob)) {
503                 BKE_report(op->reports, RPT_ERROR, "Cannot apply pose to lib-linked armature."); //error_libdata();
504                 return OPERATOR_CANCELLED;
505         }
506         
507         /* helpful warnings... */
508         // TODO: add warnings to be careful about actions, applying deforms first, etc.
509         
510         /* Get editbones of active armature to alter */
511         ED_armature_to_edit(ob);        
512         
513         /* get pose of active object and move it out of posemode */
514         pose= ob->pose;
515         
516         for (pchan=pose->chanbase.first; pchan; pchan=pchan->next) {
517                 curbone= editbone_name_exists(arm->edbo, pchan->name);
518                 
519                 /* simply copy the head/tail values from pchan over to curbone */
520                 VECCOPY(curbone->head, pchan->pose_head);
521                 VECCOPY(curbone->tail, pchan->pose_tail);
522                 
523                 /* fix roll:
524                  *      1. find auto-calculated roll value for this bone now
525                  *      2. remove this from the 'visual' y-rotation
526                  */
527                 {
528                         float premat[3][3], imat[3][3],pmat[3][3], tmat[3][3];
529                         float delta[3], eul[3];
530                         
531                         /* obtain new auto y-rotation */
532                         VecSubf(delta, curbone->tail, curbone->head);
533                         vec_roll_to_mat3(delta, 0.0f, premat);
534                         Mat3Inv(imat, premat);
535                         
536                         /* get pchan 'visual' matrix */
537                         Mat3CpyMat4(pmat, pchan->pose_mat);
538                         
539                         /* remove auto from visual and get euler rotation */
540                         Mat3MulMat3(tmat, imat, pmat);
541                         Mat3ToEul(tmat, eul);
542                         
543                         /* just use this euler-y as new roll value */
544                         curbone->roll= eul[1];
545                 }
546                 
547                 /* clear transform values for pchan */
548                 pchan->loc[0]= pchan->loc[1]= pchan->loc[2]= 0.0f;
549                 pchan->eul[0]= pchan->eul[1]= pchan->eul[2]= 0.0f;
550                 pchan->quat[1]= pchan->quat[2]= pchan->quat[3]= 0.0f;
551                 pchan->quat[0]= pchan->size[0]= pchan->size[1]= pchan->size[2]= 1.0f;
552                 
553                 /* set anim lock */
554                 curbone->flag |= BONE_UNKEYED;
555         }
556         
557         /* convert editbones back to bones */
558         ED_armature_from_edit(ob);
559         
560         /* flush positions of posebones */
561         where_is_pose(scene, ob);
562         
563         /* fix parenting of objects which are bone-parented */
564         applyarmature_fix_boneparents(scene, ob);
565         
566         /* note, notifier might evolve */
567         WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, ob);
568         
569         return OPERATOR_FINISHED;
570 }
571
572 void POSE_OT_apply (wmOperatorType *ot)
573 {
574         /* identifiers */
575         ot->name= "Apply Pose as Rest Pose";
576         ot->idname= "POSE_OT_apply";
577         ot->description= "Apply the current pose as the new rest pose.";
578         
579         /* callbacks */
580         ot->exec= apply_armature_pose2bones_exec;
581         ot->poll= ED_operator_posemode;
582         
583         /* flags */
584         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
585 }
586
587 /* ---------------------- */
588
589 /* Helper function for armature joining - link fixing */
590 static void joined_armature_fix_links(Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
591 {
592         Object *ob;
593         bPose *pose;
594         bPoseChannel *pchant;
595         bConstraint *con;
596         
597         /* let's go through all objects in database */
598         for (ob= G.main->object.first; ob; ob= ob->id.next) {
599                 /* do some object-type specific things */
600                 if (ob->type == OB_ARMATURE) {
601                         pose= ob->pose;
602                         for (pchant= pose->chanbase.first; pchant; pchant= pchant->next) {
603                                 for (con= pchant->constraints.first; con; con= con->next) {
604                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
605                                         ListBase targets = {NULL, NULL};
606                                         bConstraintTarget *ct;
607                                         
608                                         /* constraint targets */
609                                         if (cti && cti->get_constraint_targets) {
610                                                 cti->get_constraint_targets(con, &targets);
611                                                 
612                                                 for (ct= targets.first; ct; ct= ct->next) {
613                                                         if (ct->tar == srcArm) {
614                                                                 if (strcmp(ct->subtarget, "")==0) {
615                                                                         ct->tar = tarArm;
616                                                                 }
617                                                                 else if (strcmp(ct->subtarget, pchan->name)==0) {
618                                                                         ct->tar = tarArm;
619                                                                         strcpy(ct->subtarget, curbone->name);
620                                                                 }
621                                                         }
622                                                 }
623                                                 
624                                                 if (cti->flush_constraint_targets)
625                                                         cti->flush_constraint_targets(con, &targets, 0);
626                                         }
627                                         
628                                         /* action constraint? */
629                                         if (con->type == CONSTRAINT_TYPE_ACTION) {
630                                                 bActionConstraint *data= con->data; // XXX old animation system
631                                                 bAction *act;
632                                                 bActionChannel *achan;
633                                                 
634                                                 if (data->act) {
635                                                         act= data->act;
636                                                         
637                                                         for (achan= act->chanbase.first; achan; achan= achan->next) {
638                                                                 if (strcmp(achan->name, pchan->name)==0)
639                                                                         BLI_strncpy(achan->name, curbone->name, 32);
640                                                         }
641                                                 }
642                                         }
643                                         
644                                 }
645                         }
646                 }
647                         
648                 /* fix object-level constraints */
649                 if (ob != srcArm) {
650                         for (con= ob->constraints.first; con; con= con->next) {
651                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
652                                 ListBase targets = {NULL, NULL};
653                                 bConstraintTarget *ct;
654                                 
655                                 /* constraint targets */
656                                 if (cti && cti->get_constraint_targets) {
657                                         cti->get_constraint_targets(con, &targets);
658                                         
659                                         for (ct= targets.first; ct; ct= ct->next) {
660                                                 if (ct->tar == srcArm) {
661                                                         if (strcmp(ct->subtarget, "")==0) {
662                                                                 ct->tar = tarArm;
663                                                         }
664                                                         else if (strcmp(ct->subtarget, pchan->name)==0) {
665                                                                 ct->tar = tarArm;
666                                                                 strcpy(ct->subtarget, curbone->name);
667                                                         }
668                                                 }
669                                         }
670                                         
671                                         if (cti->flush_constraint_targets)
672                                                 cti->flush_constraint_targets(con, &targets, 0);
673                                 }
674                         }
675                 }
676                 
677                 /* See if an object is parented to this armature */
678                 if (ob->parent && (ob->parent == srcArm)) {
679                         /* Is object parented to a bone of this src armature? */
680                         if (ob->partype==PARBONE) {
681                                 /* bone name in object */
682                                 if (!strcmp(ob->parsubstr, pchan->name))
683                                         BLI_strncpy(ob->parsubstr, curbone->name, 32);
684                         }
685                         
686                         /* make tar armature be new parent */
687                         ob->parent = tarArm;
688                 }
689         }       
690 }
691
692 /* join armature exec is exported for use in object->join objects operator... */
693 int join_armature_exec(bContext *C, wmOperator *op)
694 {
695         Scene *scene= CTX_data_scene(C);
696         Object  *ob= CTX_data_active_object(C);
697         bArmature *arm= (ob)? ob->data: NULL;
698         bPose *pose, *opose;
699         bPoseChannel *pchan, *pchann;
700         EditBone *curbone;
701         float   mat[4][4], oimat[4][4];
702         
703         /*      Ensure we're not in editmode and that the active object is an armature*/
704         if (!ob || ob->type!=OB_ARMATURE)
705                 return OPERATOR_CANCELLED;
706         if (!arm || arm->edbo)
707                 return OPERATOR_CANCELLED;
708         
709         /* Get editbones of active armature to add editbones to */
710         ED_armature_to_edit(ob);
711         
712         /* get pose of active object and move it out of posemode */
713         pose= ob->pose;
714         ob->mode &= ~OB_MODE_POSE;
715
716         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
717                 if ((base->object->type==OB_ARMATURE) && (base->object!=ob)) {
718                         bArmature *curarm= base->object->data;
719                         
720                         /* Make a list of editbones in current armature */
721                         ED_armature_to_edit(base->object);
722                         
723                         /* Get Pose of current armature */
724                         opose= base->object->pose;
725                         base->object->mode &= ~OB_MODE_POSE;
726                         //BASACT->flag &= ~OB_MODE_POSE;
727                         
728                         /* Find the difference matrix */
729                         Mat4Invert(oimat, ob->obmat);
730                         Mat4MulMat4(mat, base->object->obmat, oimat);
731                         
732                         /* Copy bones and posechannels from the object to the edit armature */
733                         for (pchan=opose->chanbase.first; pchan; pchan=pchann) {
734                                 pchann= pchan->next;
735                                 curbone= editbone_name_exists(curarm->edbo, pchan->name);
736                                 
737                                 /* Get new name */
738                                 unique_editbone_name(arm->edbo, curbone->name, NULL);
739                                 
740                                 /* Transform the bone */
741                                 {
742                                         float premat[4][4];
743                                         float postmat[4][4];
744                                         float difmat[4][4];
745                                         float imat[4][4];
746                                         float temp[3][3];
747                                         float delta[3];
748                                         
749                                         /* Get the premat */
750                                         VecSubf(delta, curbone->tail, curbone->head);
751                                         vec_roll_to_mat3(delta, curbone->roll, temp);
752                                         
753                                         Mat4One(premat); /* Mat4MulMat34 only sets 3x3 part */
754                                         Mat4MulMat34(premat, temp, mat);
755                                         
756                                         Mat4MulVecfl(mat, curbone->head);
757                                         Mat4MulVecfl(mat, curbone->tail);
758                                         
759                                         /* Get the postmat */
760                                         VecSubf(delta, curbone->tail, curbone->head);
761                                         vec_roll_to_mat3(delta, curbone->roll, temp);
762                                         Mat4CpyMat3(postmat, temp);
763                                         
764                                         /* Find the roll */
765                                         Mat4Invert(imat, premat);
766                                         Mat4MulMat4(difmat, postmat, imat);
767                                         
768                                         curbone->roll -= (float)atan2(difmat[2][0], difmat[2][2]);
769                                 }
770                                 
771                                 /* Fix Constraints and Other Links to this Bone and Armature */
772                                 joined_armature_fix_links(ob, base->object, pchan, curbone);
773                                 
774                                 /* Rename pchan */
775                                 BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
776                                 
777                                 /* Jump Ship! */
778                                 BLI_remlink(curarm->edbo, curbone);
779                                 BLI_addtail(arm->edbo, curbone);
780                                 
781                                 BLI_remlink(&opose->chanbase, pchan);
782                                 BLI_addtail(&pose->chanbase, pchan);
783                         }
784                         
785                         ED_base_object_free_and_unlink(scene, base);
786                 }
787         }
788         CTX_DATA_END;
789         
790         DAG_scene_sort(scene);  // because we removed object(s)
791
792         ED_armature_from_edit(ob);
793         ED_armature_edit_free(ob);
794
795         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
796         
797         return OPERATOR_FINISHED;
798 }
799
800 /* ---------------------- */
801
802 /* Helper function for armature separating - link fixing */
803 static void separated_armature_fix_links(Object *origArm, Object *newArm)
804 {
805         Object *ob;
806         bPoseChannel *pchan, *pcha, *pchb;
807         bConstraint *con;
808         ListBase *opchans, *npchans;
809         
810         /* get reference to list of bones in original and new armatures  */
811         opchans= &origArm->pose->chanbase;
812         npchans= &newArm->pose->chanbase;
813         
814         /* let's go through all objects in database */
815         for (ob= G.main->object.first; ob; ob= ob->id.next) {
816                 /* do some object-type specific things */
817                 if (ob->type == OB_ARMATURE) {
818                         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
819                                 for (con= pchan->constraints.first; con; con= con->next) {
820                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
821                                         ListBase targets = {NULL, NULL};
822                                         bConstraintTarget *ct;
823                                         
824                                         /* constraint targets */
825                                         if (cti && cti->get_constraint_targets) {
826                                                 cti->get_constraint_targets(con, &targets);
827                                                 
828                                                 for (ct= targets.first; ct; ct= ct->next) {
829                                                         /* any targets which point to original armature are redirected to the new one only if:
830                                                          *      - the target isn't origArm/newArm itself
831                                                          *      - the target is one that can be found in newArm/origArm
832                                                          */
833                                                         if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
834                                                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
835                                                                         /* check if either one matches */
836                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
837                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
838                                                                         {
839                                                                                 ct->tar= newArm;
840                                                                                 break;
841                                                                         }
842                                                                         
843                                                                         /* check if both ends have met (to stop checking) */
844                                                                         if (pcha == pchb) break;
845                                                                 }                                                               
846                                                         }
847                                                         else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
848                                                                 for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
849                                                                         /* check if either one matches */
850                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
851                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
852                                                                         {
853                                                                                 ct->tar= origArm;
854                                                                                 break;
855                                                                         }
856                                                                         
857                                                                         /* check if both ends have met (to stop checking) */
858                                                                         if (pcha == pchb) break;
859                                                                 }                                                               
860                                                         }
861                                                 }
862                                                 
863                                                 if (cti->flush_constraint_targets)
864                                                         cti->flush_constraint_targets(con, &targets, 0);
865                                         }
866                                 }
867                         }
868                 }
869                         
870                 /* fix object-level constraints */
871                 if (ob != origArm) {
872                         for (con= ob->constraints.first; con; con= con->next) {
873                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
874                                 ListBase targets = {NULL, NULL};
875                                 bConstraintTarget *ct;
876                                 
877                                 /* constraint targets */
878                                 if (cti && cti->get_constraint_targets) {
879                                         cti->get_constraint_targets(con, &targets);
880                                         
881                                         for (ct= targets.first; ct; ct= ct->next) {
882                                                 /* any targets which point to original armature are redirected to the new one only if:
883                                                  *      - the target isn't origArm/newArm itself
884                                                  *      - the target is one that can be found in newArm/origArm
885                                                  */
886                                                 if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
887                                                         for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
888                                                                 /* check if either one matches */
889                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
890                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
891                                                                 {
892                                                                         ct->tar= newArm;
893                                                                         break;
894                                                                 }
895                                                                 
896                                                                 /* check if both ends have met (to stop checking) */
897                                                                 if (pcha == pchb) break;
898                                                         }                                                               
899                                                 }
900                                                 else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
901                                                         for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
902                                                                 /* check if either one matches */
903                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
904                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
905                                                                 {
906                                                                         ct->tar= origArm;
907                                                                         break;
908                                                                 }
909                                                                 
910                                                                 /* check if both ends have met (to stop checking) */
911                                                                 if (pcha == pchb) break;
912                                                         }                                                               
913                                                 }
914                                         }
915                                         
916                                         if (cti->flush_constraint_targets)
917                                                 cti->flush_constraint_targets(con, &targets, 0);
918                                 }
919                         }
920                 }
921                 
922                 /* See if an object is parented to this armature */
923                 if ((ob->parent) && (ob->parent == origArm)) {
924                         /* Is object parented to a bone of this src armature? */
925                         if (ob->partype==PARBONE) {
926                                 /* bone name in object */
927                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
928                                         /* check if either one matches */
929                                         if ( (strcmp(pcha->name, ob->parsubstr)==0) ||
930                                                  (strcmp(pchb->name, ob->parsubstr)==0) )
931                                         {
932                                                 ob->parent= newArm;
933                                                 break;
934                                         }
935                                         
936                                         /* check if both ends have met (to stop checking) */
937                                         if (pcha == pchb) break;
938                                 }
939                         }
940                 }
941         }       
942 }
943
944 /* Helper function for armature separating - remove certain bones from the given armature 
945  *      sel: remove selected bones from the armature, otherwise the unselected bones are removed
946  *  (ob is not in editmode)
947  */
948 static void separate_armature_bones (Scene *scene, Object *ob, short sel) 
949 {
950         bArmature *arm= (bArmature *)ob->data;
951         bPoseChannel *pchan, *pchann;
952         EditBone *curbone;
953         
954         /* make local set of editbones to manipulate here */
955         ED_armature_to_edit(ob);
956         
957         /* go through pose-channels, checking if a bone should be removed */
958         for (pchan=ob->pose->chanbase.first; pchan; pchan=pchann) {
959                 pchann= pchan->next;
960                 curbone= editbone_name_exists(arm->edbo, pchan->name);
961                 
962                 /* check if bone needs to be removed */
963                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
964                          (!sel && !(curbone->flag & BONE_SELECTED)) )
965                 {
966                         EditBone *ebo;
967                         bPoseChannel *pchn;
968                         
969                         /* clear the bone->parent var of any bone that had this as its parent  */
970                         for (ebo= arm->edbo->first; ebo; ebo= ebo->next) {
971                                 if (ebo->parent == curbone) {
972                                         ebo->parent= NULL;
973                                         ebo->temp= NULL; /* this is needed to prevent random crashes with in ED_armature_from_edit */
974                                         ebo->flag &= ~BONE_CONNECTED;
975                                 }
976                         }
977                         
978                         /* clear the pchan->parent var of any pchan that had this as its parent */
979                         for (pchn= ob->pose->chanbase.first; pchn; pchn=pchn->next) {
980                                 if (pchn->parent == pchan)
981                                         pchn->parent= NULL;
982                         }
983                         
984                         /* free any of the extra-data this pchan might have */
985                         if (pchan->path) MEM_freeN(pchan->path);
986                         free_constraints(&pchan->constraints);
987                         
988                         /* get rid of unneeded bone */
989                         BLI_freelinkN(arm->edbo, curbone);
990                         BLI_freelinkN(&ob->pose->chanbase, pchan);
991                 }
992         }
993         
994         /* exit editmode (recalculates pchans too) */
995         ED_armature_from_edit(ob);
996         ED_armature_edit_free(ob);
997 }
998
999 /* separate selected bones into their armature */
1000 static int separate_armature_exec (bContext *C, wmOperator *op)
1001 {
1002         Scene *scene= CTX_data_scene(C);
1003         Object *obedit= CTX_data_edit_object(C);
1004         Object *oldob, *newob;
1005         Base *oldbase, *newbase;
1006         bArmature *arm;
1007         
1008         /* sanity checks */
1009         if (obedit == NULL)
1010                 return OPERATOR_CANCELLED;
1011         arm= obedit->data;
1012         
1013         /* set wait cursor in case this takes a while */
1014         WM_cursor_wait(1);
1015         
1016         /* we are going to do this as follows (unlike every other instance of separate):
1017          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
1018          *      2. duplicate base - BASACT is the new one now
1019          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
1020          *      4. fix constraint links
1021          *      5. make original armature active and enter editmode
1022          */
1023         
1024         /* 1) only edit-base selected */
1025         // TODO: use context iterators for this?
1026         CTX_DATA_BEGIN(C, Base *, base, visible_bases) {
1027                 if (base->object==obedit) base->flag |= 1;
1028                 else base->flag &= ~1;
1029         }
1030         CTX_DATA_END;
1031         
1032         /* 1) store starting settings and exit editmode */
1033         oldob= obedit;
1034         oldbase= BASACT;
1035         oldob->mode &= ~OB_MODE_POSE;
1036         //oldbase->flag &= ~OB_POSEMODE;
1037         
1038         ED_armature_from_edit(obedit);
1039         ED_armature_edit_free(obedit);
1040         
1041         /* 2) duplicate base */
1042         newbase= ED_object_add_duplicate(scene, oldbase, USER_DUP_ARM); /* only duplicate linked armature */
1043         newob= newbase->object;         
1044         newbase->flag &= ~SELECT;
1045         
1046         
1047         /* 3) remove bones that shouldn't still be around on both armatures */
1048         separate_armature_bones(scene, oldob, 1);
1049         separate_armature_bones(scene, newob, 0);
1050         
1051         
1052         /* 4) fix links before depsgraph flushes */ // err... or after?
1053         separated_armature_fix_links(oldob, newob);
1054         
1055         DAG_id_flush_update(&oldob->id, OB_RECALC_DATA);        /* this is the original one */
1056         DAG_id_flush_update(&newob->id, OB_RECALC_DATA);        /* this is the separated one */
1057         
1058         
1059         /* 5) restore original conditions */
1060         obedit= oldob;
1061         
1062         ED_armature_to_edit(obedit);
1063         
1064         /* note, notifier might evolve */
1065         WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, obedit);
1066         
1067         /* recalc/redraw + cleanup */
1068         WM_cursor_wait(0);
1069         
1070         return OPERATOR_FINISHED;
1071 }
1072
1073 void ARMATURE_OT_separate (wmOperatorType *ot)
1074 {
1075         /* identifiers */
1076         ot->name= "Separate Armature";
1077         ot->idname= "ARMATURE_OT_separate";
1078         ot->description= "Isolate selected bones into a separate armature.";
1079         
1080         /* callbacks */
1081         ot->invoke= WM_operator_confirm;
1082         ot->exec= separate_armature_exec;
1083         ot->poll= ED_operator_editarmature;
1084         
1085         /* flags */
1086         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1087 }
1088
1089 /* **************** END tools on Editmode Armature **************** */
1090 /* **************** PoseMode & EditMode *************************** */
1091
1092 /* only for opengl selection indices */
1093 Bone *get_indexed_bone (Object *ob, int index)
1094 {
1095         bPoseChannel *pchan;
1096         int a= 0;
1097         
1098         if(ob->pose==NULL) return NULL;
1099         index>>=16;             // bone selection codes use left 2 bytes
1100         
1101         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
1102                 if(a==index) return pchan->bone;
1103         }
1104         return NULL;
1105 }
1106
1107 /* See if there are any selected bones in this buffer */
1108 /* only bones from base are checked on */
1109 static void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short findunsel)
1110 {
1111         Object *obedit= scene->obedit; // XXX get from context
1112         Bone *bone;
1113         EditBone *ebone;
1114         void *firstunSel=NULL, *firstSel=NULL, *data;
1115         unsigned int hitresult;
1116         short i, takeNext=0, sel;
1117         
1118         for (i=0; i< hits; i++){
1119                 hitresult = buffer[3+(i*4)];
1120                 
1121                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
1122                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
1123                                 
1124                                 hitresult &= ~(BONESEL_ANY);
1125                                 /* Determine what the current bone is */
1126                                 if (obedit==NULL || base->object!=obedit) {
1127                                         /* no singular posemode, so check for correct object */
1128                                         if(base->selcol == (hitresult & 0xFFFF)) {
1129                                                 bone = get_indexed_bone(base->object, hitresult);
1130
1131                                                 if (findunsel)
1132                                                         sel = (bone->flag & BONE_SELECTED);
1133                                                 else
1134                                                         sel = !(bone->flag & BONE_SELECTED);
1135                                                 
1136                                                 data = bone;
1137                                         }
1138                                         else {
1139                                                 data= NULL;
1140                                                 sel= 0;
1141                                         }
1142                                 }
1143                                 else{
1144                                         bArmature *arm= obedit->data;
1145                                         
1146                                         ebone = BLI_findlink(arm->edbo, hitresult);
1147                                         if (findunsel)
1148                                                 sel = (ebone->flag & BONE_SELECTED);
1149                                         else
1150                                                 sel = !(ebone->flag & BONE_SELECTED);
1151                                         
1152                                         data = ebone;
1153                                 }
1154                                 
1155                                 if(data) {
1156                                         if (sel) {
1157                                                 if(!firstSel) firstSel= data;
1158                                                 takeNext=1;
1159                                         }
1160                                         else {
1161                                                 if (!firstunSel)
1162                                                         firstunSel=data;
1163                                                 if (takeNext)
1164                                                         return data;
1165                                         }
1166                                 }
1167                         }
1168                 }
1169         }
1170         
1171         if (firstunSel)
1172                 return firstunSel;
1173         else 
1174                 return firstSel;
1175 }
1176
1177
1178
1179 /* used by posemode as well editmode */
1180 /* only checks scene->basact! */
1181 /* x and y are mouse coords (area space) */
1182 static void *get_nearest_bone (bContext *C, short findunsel, int x, int y)
1183 {
1184         ViewContext vc;
1185         rcti rect;
1186         unsigned int buffer[MAXPICKBUF];
1187         short hits;
1188         
1189         view3d_set_viewcontext(C, &vc);
1190         
1191         // rect.xmin= ... mouseco!
1192         rect.xmin= rect.xmax= x;
1193         rect.ymin= rect.ymax= y;
1194         
1195         glInitNames();
1196         hits= view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
1197
1198         if (hits>0)
1199                 return get_bone_from_selectbuffer(vc.scene, vc.scene->basact, buffer, hits, findunsel);
1200         
1201         return NULL;
1202 }
1203
1204 /* helper for setflag_sel_bone() */
1205 static void bone_setflag (int *bone, int flag, short mode)
1206 {
1207         if (bone && flag) {
1208                 /* exception for inverse flags */
1209                 if (flag == BONE_NO_DEFORM) {
1210                         if (mode == 2)
1211                                 *bone |= flag;
1212                         else if (mode == 1)
1213                                 *bone &= ~flag;
1214                         else
1215                                 *bone ^= flag;
1216                 }
1217                 else {
1218                         if (mode == 2)
1219                                 *bone &= ~flag;
1220                         else if (mode == 1)
1221                                 *bone |= flag;
1222                         else
1223                                 *bone ^= flag;
1224                 }
1225         }
1226 }
1227
1228 /* Get the first available child of an editbone */
1229 static EditBone *editbone_get_child(bArmature *arm, EditBone *pabone, short use_visibility)
1230 {
1231         EditBone *curbone, *chbone=NULL;
1232         
1233         for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1234                 if (curbone->parent == pabone) {
1235                         if (use_visibility) {
1236                                 if ((arm->layer & curbone->layer) && !(pabone->flag & BONE_HIDDEN_A))
1237                                         chbone = curbone;
1238                         }
1239                         else
1240                                 chbone = curbone;
1241                 }
1242         }
1243         
1244         return chbone;
1245 }
1246
1247 /* callback for posemode setflag */
1248 static int pose_setflag_exec (bContext *C, wmOperator *op)
1249 {
1250         int flag= RNA_enum_get(op->ptr, "type");
1251         int mode= RNA_enum_get(op->ptr, "mode");
1252         
1253         /* loop over all selected pchans */
1254         CTX_DATA_BEGIN(C, bPoseChannel *, pchan, selected_pchans) 
1255         {
1256                 bone_setflag(&pchan->bone->flag, flag, mode);
1257         }
1258         CTX_DATA_END;
1259         
1260         /* note, notifier might evolve */
1261         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, CTX_data_active_object(C));
1262         
1263         return OPERATOR_FINISHED;
1264 }
1265
1266 /* callback for editbones setflag */
1267 static int armature_bones_setflag_exec (bContext *C, wmOperator *op)
1268 {
1269         int flag= RNA_enum_get(op->ptr, "type");
1270         int mode= RNA_enum_get(op->ptr, "mode");
1271         
1272         /* loop over all selected pchans */
1273         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_bones) 
1274         {
1275                 bone_setflag(&ebone->flag, flag, mode);
1276         }
1277         CTX_DATA_END;
1278         
1279         /* note, notifier might evolve */
1280         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, CTX_data_edit_object(C));
1281         
1282         return OPERATOR_FINISHED;
1283 }
1284
1285 /* settings that can be changed */
1286 static EnumPropertyItem prop_bone_setting_types[] = {
1287         {BONE_DRAWWIRE, "DRAWWIRE", 0, "Draw Wire", ""},
1288         {BONE_NO_DEFORM, "DEFORM", 0, "Deform", ""},
1289         {BONE_MULT_VG_ENV, "MULT_VG", 0, "Multiply Vertex Groups", ""},
1290         {BONE_HINGE, "HINGE", 0, "Hinge", ""},
1291         {BONE_NO_SCALE, "NO_SCALE", 0, "No Scale", ""},
1292         {BONE_EDITMODE_LOCKED, "LOCKED", 0, "Locked", "(For EditMode only)"},
1293         {0, NULL, 0, NULL, NULL}
1294 };
1295
1296 /* ways that settings can be changed */
1297 static EnumPropertyItem prop_bone_setting_modes[] = {
1298         {0, "CLEAR", 0, "Clear", ""},
1299         {1, "ENABLE", 0, "Enable", ""},
1300         {2, "TOGGLE", 0, "Toggle", ""},
1301         {0, NULL, 0, NULL, NULL}
1302 };
1303
1304
1305 void ARMATURE_OT_flags_set (wmOperatorType *ot)
1306 {
1307         /* identifiers */
1308         ot->name= "Set Bone Flags";
1309         ot->idname= "ARMATURE_OT_flags_set";
1310         ot->description= "Set flags for armature bones.";
1311         
1312         /* callbacks */
1313         ot->invoke= WM_menu_invoke;
1314         ot->exec= armature_bones_setflag_exec;
1315         ot->poll= ED_operator_editarmature;
1316         
1317         /* flags */
1318         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1319         
1320         /* properties */
1321         RNA_def_enum(ot->srna, "type", prop_bone_setting_types, 0, "Type", "");
1322         RNA_def_enum(ot->srna, "mode", prop_bone_setting_modes, 0, "Mode", "");
1323 }
1324
1325 void POSE_OT_flags_set (wmOperatorType *ot)
1326 {
1327         /* identifiers */
1328         ot->name= "Set Bone Flags";
1329         ot->idname= "POSE_OT_flags_set";
1330         ot->description= "Set flags for armature bones.";
1331         
1332         /* callbacks */
1333         ot->invoke= WM_menu_invoke;
1334         ot->exec= pose_setflag_exec;
1335         ot->poll= ED_operator_posemode;
1336         
1337         /* flags */
1338         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1339         
1340         /* properties */
1341         RNA_def_enum(ot->srna, "type", prop_bone_setting_types, 0, "Type", "");
1342         RNA_def_enum(ot->srna, "mode", prop_bone_setting_modes, 0, "Mode", "");
1343 }
1344
1345
1346 /* **************** END PoseMode & EditMode *************************** */
1347 /* **************** Posemode stuff ********************** */
1348
1349
1350 static void selectconnected_posebonechildren (Object *ob, Bone *bone)
1351 {
1352         Bone *curBone;
1353         int shift= 0; // XXX
1354         
1355         if (!(bone->flag & BONE_CONNECTED))
1356                 return;
1357         
1358                 // XXX old cruft! use notifiers instead
1359         //select_actionchannel_by_name (ob->action, bone->name, !(shift));
1360         
1361         if (shift)
1362                 bone->flag &= ~BONE_SELECTED;
1363         else
1364                 bone->flag |= BONE_SELECTED;
1365         
1366         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
1367                 selectconnected_posebonechildren (ob, curBone);
1368         }
1369 }
1370
1371 /* within active object context */
1372 /* previously known as "selectconnected_posearmature" */
1373 static int pose_select_connected_invoke(bContext *C, wmOperator *op, wmEvent *event)
1374 {  
1375         Bone *bone, *curBone, *next= NULL;
1376         int shift= 0; // XXX in pose mode, Shift+L is bound to another command
1377                                   // named "PoseLib Add Current Pose"
1378         int x, y;
1379         ARegion *ar;
1380         Object *ob= CTX_data_edit_object(C);
1381         ar= CTX_wm_region(C);
1382
1383         x= event->x - ar->winrct.xmin;
1384         y= event->y - ar->winrct.ymin;
1385
1386         view3d_operator_needs_opengl(C);
1387         
1388         if (shift)
1389                 bone= get_nearest_bone(C, 0, x, y);
1390         else
1391                 bone= get_nearest_bone(C, 1, x, y);
1392         
1393         if (!bone)
1394                 return OPERATOR_CANCELLED;
1395         
1396         /* Select parents */
1397         for (curBone=bone; curBone; curBone=next){
1398                         // XXX old cruft! use notifiers instead
1399                 //select_actionchannel_by_name (ob->action, curBone->name, !(shift));
1400                 if (shift)
1401                         curBone->flag &= ~BONE_SELECTED;
1402                 else
1403                         curBone->flag |= BONE_SELECTED;
1404                 
1405                 if (curBone->flag & BONE_CONNECTED)
1406                         next=curBone->parent;
1407                 else
1408                         next=NULL;
1409         }
1410         
1411         /* Select children */
1412         for (curBone=bone->childbase.first; curBone; curBone=next){
1413                 selectconnected_posebonechildren (ob, curBone);
1414         }
1415         
1416         // XXX this only counted the number of pose channels selected
1417         //countall(); // flushes selection!
1418         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, ob);
1419
1420         return OPERATOR_FINISHED;
1421 }
1422
1423 void POSE_OT_select_linked(wmOperatorType *ot)
1424 {
1425         /* identifiers */
1426         ot->name= "Select Connected";
1427         ot->idname= "POSE_OT_select_linked";
1428         
1429         /* api callbacks */
1430         ot->exec= NULL;
1431         ot->invoke= pose_select_connected_invoke;
1432         ot->poll= ED_operator_posemode;
1433         
1434         /* flags */
1435         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1436         
1437         /* props */     
1438 }
1439
1440 /* **************** END Posemode stuff ********************** */
1441 /* **************** EditMode stuff ********************** */
1442
1443 /* called in space.c */
1444 /* previously "selectconnected_armature" */
1445 static int armature_select_linked_invoke(bContext *C, wmOperator *op, wmEvent *event)
1446 {
1447         bArmature *arm;
1448         EditBone *bone, *curBone, *next;
1449         int shift= 0; // XXX
1450         int x, y;
1451         ARegion *ar;
1452         Object *obedit= CTX_data_edit_object(C);
1453         arm= obedit->data;
1454         ar= CTX_wm_region(C);
1455
1456         x= event->x - ar->winrct.xmin;
1457         y= event->y - ar->winrct.ymin;
1458
1459         view3d_operator_needs_opengl(C);
1460
1461         if (shift)
1462                 bone= get_nearest_bone(C, 0, x, y);
1463         else
1464                 bone= get_nearest_bone(C, 1, x, y);
1465
1466         if (!bone)
1467                 return OPERATOR_CANCELLED;
1468
1469         /* Select parents */
1470         for (curBone=bone; curBone; curBone=next){
1471                 if (shift){
1472                         curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1473                 }
1474                 else{
1475                         curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1476                 }
1477
1478                 if (curBone->flag & BONE_CONNECTED)
1479                         next=curBone->parent;
1480                 else
1481                         next=NULL;
1482         }
1483
1484         /* Select children */
1485         while (bone){
1486                 for (curBone=arm->edbo->first; curBone; curBone=next){
1487                         next = curBone->next;
1488                         if (curBone->parent == bone){
1489                                 if (curBone->flag & BONE_CONNECTED){
1490                                         if (shift)
1491                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1492                                         else
1493                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1494                                         bone=curBone;
1495                                         break;
1496                                 }
1497                                 else{ 
1498                                         bone=NULL;
1499                                         break;
1500                                 }
1501                         }
1502                 }
1503                 if (!curBone)
1504                         bone=NULL;
1505
1506         }
1507
1508         ED_armature_sync_selection(arm->edbo);
1509
1510         /* BIF_undo_push("Select connected"); */
1511
1512         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
1513
1514         return OPERATOR_FINISHED;
1515 }
1516
1517 void ARMATURE_OT_select_linked(wmOperatorType *ot)
1518 {
1519         /* identifiers */
1520         ot->name= "Select Connected";
1521         ot->idname= "ARMATURE_OT_select_linked";
1522         
1523         /* api callbacks */
1524         ot->exec= NULL;
1525         ot->invoke= armature_select_linked_invoke;
1526         ot->poll= ED_operator_editarmature;
1527         
1528         /* flags */
1529         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1530 }
1531
1532 /* does bones and points */
1533 /* note that BONE ROOT only gets drawn for root bones (or without IK) */
1534 static EditBone *get_nearest_editbonepoint (ViewContext *vc, short mval[2], ListBase *edbo, int findunsel, int *selmask)
1535 {
1536         EditBone *ebone;
1537         rcti rect;
1538         unsigned int buffer[MAXPICKBUF];
1539         unsigned int hitresult, besthitresult=BONESEL_NOSEL;
1540         int i, mindep= 4;
1541         short hits;
1542
1543         glInitNames();
1544         
1545         rect.xmin= mval[0]-5;
1546         rect.xmax= mval[0]+5;
1547         rect.ymin= mval[1]-5;
1548         rect.ymax= mval[1]+5;
1549         
1550         hits= view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1551         if(hits==0) {
1552                 rect.xmin= mval[0]-12;
1553                 rect.xmax= mval[0]+12;
1554                 rect.ymin= mval[1]-12;
1555                 rect.ymax= mval[1]+12;
1556                 hits= view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1557         }
1558         /* See if there are any selected bones in this group */
1559         if (hits>0) {
1560                 
1561                 if(hits==1) {
1562                         if (!(buffer[3] & BONESEL_NOSEL)) 
1563                                 besthitresult= buffer[3];
1564                 }
1565                 else {
1566                         for (i=0; i< hits; i++) {
1567                                 hitresult= buffer[3+(i*4)];
1568                                 if (!(hitresult & BONESEL_NOSEL)) {
1569                                         int dep;
1570                                         
1571                                         ebone = BLI_findlink(edbo, hitresult & ~BONESEL_ANY);
1572                                         
1573                                         /* clicks on bone points get advantage */
1574                                         if( hitresult & (BONESEL_ROOT|BONESEL_TIP)) {
1575                                                 /* but also the unselected one */
1576                                                 if(findunsel) {
1577                                                         if( (hitresult & BONESEL_ROOT) && (ebone->flag & BONE_ROOTSEL)==0) 
1578                                                                 dep= 1;
1579                                                         else if( (hitresult & BONESEL_TIP) && (ebone->flag & BONE_TIPSEL)==0) 
1580                                                                 dep= 1;
1581                                                         else 
1582                                                                 dep= 2;
1583                                                 }
1584                                                 else dep= 2;
1585                                         }
1586                                         else {
1587                                                 /* bone found */
1588                                                 if(findunsel) {
1589                                                         if((ebone->flag & BONE_SELECTED)==0)
1590                                                                 dep= 2;
1591                                                         else
1592                                                                 dep= 3;
1593                                                 }
1594                                                 else dep= 3;
1595                                         }
1596                                         if(dep < mindep) {
1597                                                 mindep= dep;
1598                                                 besthitresult= hitresult;
1599                                         }
1600                                 }
1601                         }
1602                 }
1603                 
1604                 if (!(besthitresult & BONESEL_NOSEL)) {
1605                         
1606                         ebone= BLI_findlink(edbo, besthitresult & ~BONESEL_ANY);
1607                         
1608                         *selmask = 0;
1609                         if (besthitresult & BONESEL_ROOT)
1610                                 *selmask |= BONE_ROOTSEL;
1611                         if (besthitresult & BONESEL_TIP)
1612                                 *selmask |= BONE_TIPSEL;
1613                         if (besthitresult & BONESEL_BONE)
1614                                 *selmask |= BONE_SELECTED;
1615                         return ebone;
1616                 }
1617         }
1618         *selmask = 0;
1619         return NULL;
1620 }
1621
1622 static void delete_bone(ListBase *edbo, EditBone* exBone)
1623 {
1624         EditBone *curBone;
1625         
1626         /* Find any bones that refer to this bone */
1627         for (curBone=edbo->first;curBone;curBone=curBone->next) {
1628                 if (curBone->parent==exBone) {
1629                         curBone->parent=exBone->parent;
1630                         curBone->flag &= ~BONE_CONNECTED;
1631                 }
1632         }
1633         
1634         BLI_freelinkN(edbo, exBone);
1635 }
1636
1637 /* context: editmode armature */
1638 EditBone *ED_armature_bone_get_mirrored(ListBase *edbo, EditBone *ebo)
1639 {
1640         EditBone *eboflip= NULL;
1641         char name[32];
1642         
1643         if (ebo == NULL)
1644                 return NULL;
1645         
1646         BLI_strncpy(name, ebo->name, sizeof(name));
1647         bone_flip_name(name, 0);                // 0 = don't strip off number extensions
1648         
1649         for (eboflip= edbo->first; eboflip; eboflip=eboflip->next) {
1650                 if (ebo != eboflip) {
1651                         if (!strcmp (name, eboflip->name)) 
1652                                 break;
1653                 }
1654         }
1655         
1656         return eboflip;
1657 }
1658
1659
1660 /* previously delete_armature */
1661 /* only editmode! */
1662 static int armature_delete_selected_exec(bContext *C, wmOperator *op)
1663 {
1664         bArmature *arm;
1665         EditBone        *curBone, *next;
1666         bConstraint *con;
1667         Object *obedit= CTX_data_edit_object(C); // XXX get from context
1668         arm = obedit->data;
1669
1670         /* cancel if nothing selected */
1671         if (CTX_DATA_COUNT(C, selected_bones) == 0)
1672                 return OPERATOR_CANCELLED;
1673         
1674         /* Select mirrored bones */
1675         if (arm->flag & ARM_MIRROR_EDIT) {
1676                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
1677                         if (arm->layer & curBone->layer) {
1678                                 if (curBone->flag & BONE_SELECTED) {
1679                                         next = ED_armature_bone_get_mirrored(arm->edbo, curBone);
1680                                         if (next)
1681                                                 next->flag |= BONE_SELECTED;
1682                                 }
1683                         }
1684                 }
1685         }
1686         
1687         /*  First erase any associated pose channel */
1688         if (obedit->pose) {
1689                 bPoseChannel *chan, *next;
1690                 for (chan=obedit->pose->chanbase.first; chan; chan=next) {
1691                         next= chan->next;
1692                         curBone = editbone_name_exists(arm->edbo, chan->name);
1693                         
1694                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1695                                 free_constraints(&chan->constraints);
1696                                 BLI_freelinkN (&obedit->pose->chanbase, chan);
1697                         }
1698                         else {
1699                                 for (con= chan->constraints.first; con; con= con->next) {
1700                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1701                                         ListBase targets = {NULL, NULL};
1702                                         bConstraintTarget *ct;
1703                                         
1704                                         if (cti && cti->get_constraint_targets) {
1705                                                 cti->get_constraint_targets(con, &targets);
1706                                                 
1707                                                 for (ct= targets.first; ct; ct= ct->next) {
1708                                                         if (ct->tar == obedit) {
1709                                                                 if (ct->subtarget[0]) {
1710                                                                         curBone = editbone_name_exists(arm->edbo, ct->subtarget);
1711                                                                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1712                                                                                 con->flag |= CONSTRAINT_DISABLE;
1713                                                                                 ct->subtarget[0]= 0;
1714                                                                         }
1715                                                                 }
1716                                                         }
1717                                                 }
1718                                                 
1719                                                 if (cti->flush_constraint_targets)
1720                                                         cti->flush_constraint_targets(con, &targets, 0);
1721                                         }
1722                                 }
1723                         }
1724                 }
1725         }
1726         
1727         
1728         for (curBone=arm->edbo->first;curBone;curBone=next) {
1729                 next=curBone->next;
1730                 if (arm->layer & curBone->layer) {
1731                         if (curBone->flag & BONE_SELECTED)
1732                                 delete_bone(arm->edbo, curBone);
1733                 }
1734         }
1735         
1736         
1737         ED_armature_sync_selection(arm->edbo);
1738
1739         WM_event_add_notifier(C, NC_OBJECT, obedit);
1740
1741         return OPERATOR_FINISHED;
1742 }
1743
1744 void ARMATURE_OT_delete(wmOperatorType *ot)
1745 {
1746         /* identifiers */
1747         ot->name= "Delete Selected Bone(s)";
1748         ot->idname= "ARMATURE_OT_delete";
1749         
1750         /* api callbacks */
1751         ot->invoke = WM_operator_confirm;
1752         ot->exec = armature_delete_selected_exec;
1753         ot->poll = ED_operator_editarmature;
1754         
1755         /* flags */
1756         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1757 }
1758
1759 /* toggle==0: deselect
1760  * toggle==1: swap (based on test)
1761  * toggle==2: only active tag
1762  * toggle==3: swap (no test)
1763  */
1764 void ED_armature_deselectall(Object *obedit, int toggle, int doundo)
1765 {
1766         bArmature *arm= obedit->data;
1767         EditBone        *eBone;
1768         int                     sel=1;
1769         
1770         if(toggle==1) {
1771                 /*      Determine if there are any selected bones
1772                 And therefore whether we are selecting or deselecting */
1773                 for (eBone=arm->edbo->first;eBone;eBone=eBone->next){
1774                         //                      if(arm->layer & eBone->layer) {
1775                         if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1776                                 sel=0;
1777                                 break;
1778                         }
1779                         //                      }
1780                 }
1781         }
1782         else sel= toggle;
1783         
1784         /*      Set the flags */
1785         for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
1786                 if (sel==3) {
1787                         /* invert selection of bone */
1788                         if ((arm->layer & eBone->layer) && (eBone->flag & BONE_HIDDEN_A)==0) {
1789                                 eBone->flag ^= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1790                                 eBone->flag &= ~BONE_ACTIVE;
1791                         }
1792                 }
1793                 else if (sel==1) {
1794                         /* select bone */
1795                         if(arm->layer & eBone->layer && (eBone->flag & BONE_HIDDEN_A)==0) {
1796                                 eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1797                                 if(eBone->parent)
1798                                         eBone->parent->flag |= (BONE_TIPSEL);
1799                         }
1800                 }
1801                 else if (sel==2) {
1802                         /* clear active flag */
1803                         eBone->flag &= ~(BONE_ACTIVE);
1804                 }
1805                 else {
1806                         /* deselect bone */
1807                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1808                 }
1809         }
1810         
1811         ED_armature_sync_selection(arm->edbo);
1812         if (doundo) {
1813                 if (sel==1) BIF_undo_push("Select All");
1814                 else BIF_undo_push("Deselect All");
1815         }
1816 }
1817
1818
1819 /* context: editmode armature in view3d */
1820 void mouse_armature(bContext *C, short mval[2], int extend)
1821 {
1822         Object *obedit= CTX_data_edit_object(C);
1823         bArmature *arm= obedit->data;
1824         ViewContext vc;
1825         EditBone *nearBone = NULL, *ebone;
1826         int     selmask;
1827
1828         view3d_set_viewcontext(C, &vc);
1829         
1830         BIF_sk_selectStroke(C, mval, extend);
1831         
1832         nearBone= get_nearest_editbonepoint(&vc, mval, arm->edbo, 1, &selmask);
1833         if (nearBone) {
1834
1835                 if (!extend)
1836                         ED_armature_deselectall(obedit, 0, 0);
1837                 
1838                 /* by definition the non-root connected bones have no root point drawn,
1839                so a root selection needs to be delivered to the parent tip */
1840                 
1841                 if(selmask & BONE_SELECTED) {
1842                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
1843                                 /* click in a chain */
1844                                 if(extend) {
1845                                         /* hold shift inverts this bone's selection */
1846                                         if(nearBone->flag & BONE_SELECTED) {
1847                                                 /* deselect this bone */
1848                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
1849                                                 /* only deselect parent tip if it is not selected */
1850                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
1851                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
1852                                         }
1853                                         else {
1854                                                 /* select this bone */
1855                                                 nearBone->flag |= BONE_TIPSEL;
1856                                                 nearBone->parent->flag |= BONE_TIPSEL;
1857                                         }
1858                                 }
1859                                 else {
1860                                         /* select this bone */
1861                                         nearBone->flag |= BONE_TIPSEL;
1862                                         nearBone->parent->flag |= BONE_TIPSEL;
1863                                 }
1864                         }
1865                         else {
1866                                 if(extend) {
1867                                         /* hold shift inverts this bone's selection */
1868                                         if(nearBone->flag & BONE_SELECTED)
1869                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
1870                                         else
1871                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
1872                                 }
1873                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
1874                         }
1875                 }
1876                 else {
1877                         if (extend && (nearBone->flag & selmask))
1878                                 nearBone->flag &= ~selmask;
1879                         else
1880                                 nearBone->flag |= selmask;
1881                 }
1882                 
1883                 ED_armature_sync_selection(arm->edbo);
1884                 
1885                 if(nearBone) {
1886                         /* then now check for active status */
1887                         for (ebone=arm->edbo->first;ebone;ebone=ebone->next) ebone->flag &= ~BONE_ACTIVE;
1888                         if(nearBone->flag & BONE_SELECTED) nearBone->flag |= BONE_ACTIVE;
1889                 }
1890                 
1891                 WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, vc.obedit);
1892         }
1893 }
1894
1895 void ED_armature_edit_free(struct Object *ob)
1896 {
1897         bArmature *arm= ob->data;
1898         
1899         /*      Clear the editbones list */
1900         if (arm->edbo) {
1901                 if (arm->edbo->first)
1902                         BLI_freelistN(arm->edbo);
1903                 MEM_freeN(arm->edbo);
1904                 arm->edbo= NULL;
1905         }
1906 }
1907
1908 void ED_armature_edit_remake(Object *obedit)
1909 {
1910         if(okee("Reload original data")==0) return;
1911         
1912         ED_armature_to_edit(obedit);
1913         
1914 //      BIF_undo_push("Delete bone");
1915 }
1916
1917 /* Put armature in EditMode */
1918 void ED_armature_to_edit(Object *ob)
1919 {
1920         bArmature *arm= ob->data;
1921         
1922         ED_armature_edit_free(ob);
1923         arm->edbo= MEM_callocN(sizeof(ListBase), "edbo armature");
1924         make_boneList(arm->edbo, &arm->bonebase,NULL);
1925
1926 //      BIF_freeTemplates(); /* force template update when entering editmode */
1927 }
1928
1929
1930 /* adjust bone roll to align Z axis with vector
1931  * vec is in local space and is normalized
1932  */
1933 float ED_rollBoneToVector(EditBone *bone, float new_up_axis[3])
1934 {
1935         float mat[3][3], nor[3], up_axis[3], vec[3];
1936         float roll;
1937
1938         VecSubf(nor, bone->tail, bone->head);
1939         
1940         vec_roll_to_mat3(nor, 0, mat);
1941         VECCOPY(up_axis, mat[2]);
1942         
1943         roll = NormalizedVecAngle2(new_up_axis, up_axis);
1944         
1945         Crossf(vec, up_axis, new_up_axis);
1946         
1947         if (Inpf(vec, nor) < 0)
1948         {
1949                 roll = -roll;
1950         }
1951         
1952         return roll;
1953 }
1954
1955
1956 /* Set roll value for given bone -> Z-Axis Point up (original method) */
1957 void auto_align_ebone_zaxisup(Scene *scene, View3D *v3d, EditBone *ebone)
1958 {
1959         float   delta[3], curmat[3][3];
1960         float   xaxis[3]={1.0f, 0.0f, 0.0f}, yaxis[3], zaxis[3]={0.0f, 0.0f, 1.0f};
1961         float   targetmat[3][3], imat[3][3], diffmat[3][3];
1962         
1963         /* Find the current bone matrix */
1964         VecSubf(delta, ebone->tail, ebone->head);
1965         vec_roll_to_mat3(delta, 0.0f, curmat);
1966         
1967         /* Make new matrix based on y axis & z-up */
1968         VECCOPY(yaxis, curmat[1]);
1969         
1970         Mat3One(targetmat);
1971         VECCOPY(targetmat[0], xaxis);
1972         VECCOPY(targetmat[1], yaxis);
1973         VECCOPY(targetmat[2], zaxis);
1974         Mat3Ortho(targetmat);
1975         
1976         /* Find the difference between the two matrices */
1977         Mat3Inv(imat, targetmat);
1978         Mat3MulMat3(diffmat, imat, curmat);
1979         
1980         // old-method... let's see if using mat3_to_vec_roll is more accurate
1981         //ebone->roll = atan2(diffmat[2][0], diffmat[2][2]);  
1982         mat3_to_vec_roll(diffmat, delta, &ebone->roll);
1983 }
1984
1985 /* Set roll value for given bone -> Z-Axis point towards cursor */
1986 void auto_align_ebone_tocursor(Scene *scene, View3D *v3d, EditBone *ebone)
1987 {
1988         Object *obedit= scene->obedit; // XXX get from context
1989         float   *cursor= give_cursor(scene, v3d);
1990         float   delta[3], curmat[3][3];
1991         float   mat[4][4], tmat[4][4], imat[4][4];
1992         float   rmat[4][4], rot[3];
1993         float   vec[3];
1994         
1995         /* find the current bone matrix as a 4x4 matrix (in Armature Space) */
1996         VecSubf(delta, ebone->tail, ebone->head);
1997         vec_roll_to_mat3(delta, ebone->roll, curmat);
1998         Mat4CpyMat3(mat, curmat);
1999         VECCOPY(mat[3], ebone->head);
2000         
2001         /* multiply bone-matrix by object matrix (so that bone-matrix is in WorldSpace) */
2002         Mat4MulMat4(tmat, mat, obedit->obmat);
2003         Mat4Invert(imat, tmat);
2004         
2005         /* find position of cursor relative to bone */
2006         VecMat4MulVecfl(vec, imat, cursor);
2007         
2008         /* check that cursor is in usable position */
2009         if ((IS_EQ(vec[0], 0)==0) && (IS_EQ(vec[2], 0)==0)) {
2010                 /* Compute a rotation matrix around y */
2011                 rot[1] = (float)atan2(vec[0], vec[2]);
2012                 rot[0] = rot[2] = 0.0f;
2013                 EulToMat4(rot, rmat);
2014                 
2015                 /* Multiply the bone matrix by rotation matrix. This should be new bone-matrix */
2016                 Mat4MulMat4(tmat, rmat, mat);
2017                 Mat3CpyMat4(curmat, tmat);
2018                 
2019                 /* Now convert from new bone-matrix, back to a roll value (in radians) */
2020                 mat3_to_vec_roll(curmat, delta, &ebone->roll);
2021         }
2022 }
2023
2024
2025 static EnumPropertyItem prop_calc_roll_types[] = {
2026         {0, "GLOBALUP", 0, "Z-Axis Up", ""},
2027         {1, "CURSOR", 0, "Z-Axis to Cursor", ""},
2028         {0, NULL, 0, NULL, NULL}
2029 };
2030
2031 static int armature_calc_roll_exec(bContext *C, wmOperator *op) 
2032 {
2033         Scene *scene= CTX_data_scene(C);
2034         View3D *v3d= CTX_wm_view3d(C);
2035         Object *ob= CTX_data_edit_object(C);
2036         void (*roll_func)(Scene *, View3D *, EditBone *) = NULL;
2037         
2038         /* specific method used to calculate roll depends on mode */
2039         switch (RNA_enum_get(op->ptr, "type")) {
2040                 case 1:  /* Z-Axis point towards cursor */
2041                         roll_func= auto_align_ebone_tocursor;
2042                         break;
2043                 default: /* Z-Axis Point Up */
2044                         roll_func= auto_align_ebone_zaxisup;
2045                         break;
2046         }
2047         
2048         /* recalculate roll on selected bones */
2049         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones) {
2050                 /* roll func is a callback which assumes that all is well */
2051                 roll_func(scene, v3d, ebone);
2052         }
2053         CTX_DATA_END;
2054         
2055
2056         /* note, notifier might evolve */
2057         WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, ob);
2058         
2059         return OPERATOR_FINISHED;
2060 }
2061
2062 void ARMATURE_OT_calculate_roll(wmOperatorType *ot)
2063 {
2064         /* identifiers */
2065         ot->name= "Recalculate Roll";
2066         ot->idname= "ARMATURE_OT_calculate_roll";
2067         
2068         /* api callbacks */
2069         ot->invoke = WM_menu_invoke;
2070         ot->exec = armature_calc_roll_exec;
2071         ot->poll = ED_operator_editarmature;
2072         
2073         /* flags */
2074         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2075         
2076         /* properties */
2077         RNA_def_enum(ot->srna, "type", prop_calc_roll_types, 0, "Type", "");
2078 }
2079
2080 /* **************** undo for armatures ************** */
2081
2082 static void undoBones_to_editBones(void *lbuv, void *lbev)
2083 {
2084         ListBase *lbu= lbuv;
2085         ListBase *edbo= lbev;
2086         EditBone *ebo, *newebo;
2087         
2088         BLI_freelistN(edbo);
2089         
2090         /* copy  */
2091         for(ebo= lbu->first; ebo; ebo= ebo->next) {
2092                 newebo= MEM_dupallocN(ebo);
2093                 ebo->temp= newebo;
2094                 BLI_addtail(edbo, newebo);
2095         }
2096         
2097         /* set pointers */
2098         for(newebo= edbo->first; newebo; newebo= newebo->next) {
2099                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2100         }
2101         /* be sure they dont hang ever */
2102         for(newebo= edbo->first; newebo; newebo= newebo->next) {
2103                 newebo->temp= NULL;
2104         }
2105 }
2106
2107 static void *editBones_to_undoBones(void *lbev)
2108 {
2109         ListBase *edbo= lbev;
2110         ListBase *lb;
2111         EditBone *ebo, *newebo;
2112         
2113         lb= MEM_callocN(sizeof(ListBase), "listbase undo");
2114         
2115         /* copy */
2116         for(ebo= edbo->first; ebo; ebo= ebo->next) {
2117                 newebo= MEM_dupallocN(ebo);
2118                 ebo->temp= newebo;
2119                 BLI_addtail(lb, newebo);
2120         }
2121         
2122         /* set pointers */
2123         for(newebo= lb->first; newebo; newebo= newebo->next) {
2124                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2125         }
2126         
2127         return lb;
2128 }
2129
2130 static void free_undoBones(void *lbv)
2131 {
2132         ListBase *lb= lbv;
2133         
2134         BLI_freelistN(lb);
2135         MEM_freeN(lb);
2136 }
2137
2138 static void *get_armature_edit(bContext *C)
2139 {
2140         Object *obedit= CTX_data_edit_object(C);
2141         if(obedit && obedit->type==OB_ARMATURE) {
2142                 bArmature *arm= obedit->data;
2143                 return arm->edbo;
2144         }
2145         return NULL;
2146 }
2147
2148 /* and this is all the undo system needs to know */
2149 void undo_push_armature(bContext *C, char *name)
2150 {
2151         // XXX solve getdata()
2152         undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
2153 }
2154
2155
2156
2157 /* **************** END EditMode stuff ********************** */
2158 /* *************** Adding stuff in editmode *************** */
2159
2160 /* default bone add, returns it selected, but without tail set */
2161 EditBone *addEditBone(bArmature *arm, char *name)
2162 {
2163         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
2164         
2165         BLI_strncpy(bone->name, name, 32);
2166         unique_editbone_name(arm->edbo, bone->name, NULL);
2167         
2168         BLI_addtail(arm->edbo, bone);
2169         
2170         bone->flag |= BONE_TIPSEL;
2171         bone->weight= 1.0f;
2172         bone->dist= 0.25f;
2173         bone->xwidth= 0.1f;
2174         bone->zwidth= 0.1f;
2175         bone->ease1= 1.0f;
2176         bone->ease2= 1.0f;
2177         bone->rad_head= 0.10f;
2178         bone->rad_tail= 0.05f;
2179         bone->segments= 1;
2180         bone->layer= arm->layer;
2181         
2182         return bone;
2183 }
2184
2185 /* default bone add, returns it selected, but without tail set */
2186 static EditBone *add_editbone(Object *obedit, char *name)
2187 {
2188         bArmature *arm= obedit->data;
2189
2190         return addEditBone(arm, name);
2191 }
2192
2193 /* v3d and rv3d are allowed to be NULL */
2194 void add_primitive_bone(Scene *scene, View3D *v3d, RegionView3D *rv3d)
2195 {
2196         Object *obedit= scene->obedit; // XXX get from context
2197         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
2198         EditBone        *bone;
2199         
2200         VECCOPY(curs, give_cursor(scene, v3d)); 
2201
2202         /* Get inverse point for head and orientation for tail */
2203         Mat4Invert(obedit->imat, obedit->obmat);
2204         Mat4MulVecfl(obedit->imat, curs);
2205
2206         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2207                 Mat3CpyMat4(obmat, rv3d->viewmat);
2208         else Mat3One(obmat);
2209         
2210         Mat3CpyMat4(viewmat, obedit->obmat);
2211         Mat3MulMat3(totmat, obmat, viewmat);
2212         Mat3Inv(imat, totmat);
2213         
2214         ED_armature_deselectall(obedit, 0, 0);
2215         
2216         /*      Create a bone   */
2217         bone= add_editbone(obedit, "Bone");
2218
2219         VECCOPY(bone->head, curs);
2220         
2221         if ( (U.flag & USER_ADD_VIEWALIGNED) )
2222                 VecAddf(bone->tail, bone->head, imat[1]);       // bone with unit length 1
2223         else
2224                 VecAddf(bone->tail, bone->head, imat[2]);       // bone with unit length 1, pointing up Z
2225         
2226 }
2227
2228
2229 /* previously addvert_armature */
2230 /* the ctrl-click method */
2231 static int armature_click_extrude_exec(bContext *C, wmOperator *op)
2232 {
2233         View3D *v3d;
2234         bArmature *arm;
2235         EditBone *ebone, *newbone, *flipbone;
2236         float *curs, mat[3][3],imat[3][3];
2237         int a, to_root= 0;
2238         Object *obedit;
2239         Scene *scene;
2240
2241         scene = CTX_data_scene(C);
2242         v3d= CTX_wm_view3d(C);
2243         obedit= CTX_data_edit_object(C);
2244         arm= obedit->data;
2245         
2246         /* find the active or selected bone */
2247         for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2248                 if (EBONE_VISIBLE(arm, ebone)) {
2249                         if (ebone->flag & (BONE_ACTIVE|BONE_TIPSEL)) 
2250                                 break;
2251                 }
2252         }
2253         
2254         if (ebone==NULL) {
2255                 for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2256                         if (EBONE_VISIBLE(arm, ebone)) {
2257                                 if (ebone->flag & (BONE_ACTIVE|BONE_ROOTSEL)) 
2258                                         break;
2259                         }
2260                 }
2261                 if (ebone == NULL) 
2262                         return OPERATOR_CANCELLED;
2263                 
2264                 to_root= 1;
2265         }
2266         
2267         ED_armature_deselectall(obedit, 0, 0);
2268         
2269         /* we re-use code for mirror editing... */
2270         flipbone= NULL;
2271         if (arm->flag & ARM_MIRROR_EDIT)
2272                 flipbone= ED_armature_bone_get_mirrored(arm->edbo, ebone);
2273
2274         for (a=0; a<2; a++) {
2275                 if (a==1) {
2276                         if (flipbone==NULL)
2277                                 break;
2278                         else {
2279                                 SWAP(EditBone *, flipbone, ebone);
2280                         }
2281                 }
2282                 
2283                 newbone= add_editbone(obedit, ebone->name);
2284                 newbone->flag |= BONE_ACTIVE;
2285                 
2286                 if (to_root) {
2287                         VECCOPY(newbone->head, ebone->head);
2288                         newbone->rad_head= ebone->rad_tail;
2289                         newbone->parent= ebone->parent;
2290                 }
2291                 else {
2292                         VECCOPY(newbone->head, ebone->tail);
2293                         newbone->rad_head= ebone->rad_tail;
2294                         newbone->parent= ebone;
2295                         newbone->flag |= BONE_CONNECTED;
2296                 }
2297                 
2298                 curs= give_cursor(scene, v3d);
2299                 VECCOPY(newbone->tail, curs);
2300                 VecSubf(newbone->tail, newbone->tail, obedit->obmat[3]);
2301                 
2302                 if (a==1) 
2303                         newbone->tail[0]= -newbone->tail[0];
2304                 
2305                 Mat3CpyMat4(mat, obedit->obmat);
2306                 Mat3Inv(imat, mat);
2307                 Mat3MulVecfl(imat, newbone->tail);
2308                 
2309                 newbone->length= VecLenf(newbone->head, newbone->tail);
2310                 newbone->rad_tail= newbone->length*0.05f;
2311                 newbone->dist= newbone->length*0.25f;
2312                 
2313         }
2314         
2315         ED_armature_sync_selection(arm->edbo);
2316
2317         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2318         
2319         return OPERATOR_FINISHED;
2320 }
2321
2322 static int armature_click_extrude_invoke(bContext *C, wmOperator *op, wmEvent *event)
2323 {
2324         /* TODO most of this code is copied from set3dcursor_invoke,
2325            it would be better to reuse code in set3dcursor_invoke */
2326
2327         /* temporarily change 3d cursor position */
2328         Scene *scene;
2329         ARegion *ar;
2330         View3D *v3d;
2331         RegionView3D *rv3d;
2332         float dx, dy, fz, *fp = NULL, dvec[3], oldcurs[3];
2333         short mx, my, mval[2];
2334         int retv;
2335
2336         scene= CTX_data_scene(C);
2337         ar= CTX_wm_region(C);
2338         v3d = CTX_wm_view3d(C);
2339         rv3d= CTX_wm_region_view3d(C);
2340         
2341         fp= give_cursor(scene, v3d);
2342         
2343         VECCOPY(oldcurs, fp);
2344         
2345         mx= event->x - ar->winrct.xmin;
2346         my= event->y - ar->winrct.ymin;
2347         project_short_noclip(ar, fp, mval);
2348         
2349         initgrabz(rv3d, fp[0], fp[1], fp[2]);
2350         
2351         if(mval[0]!=IS_CLIPPED) {
2352                 
2353                 window_to_3d_delta(ar, dvec, mval[0]-mx, mval[1]-my);
2354                 VecSubf(fp, fp, dvec);
2355         }
2356         else {
2357                 
2358                 dx= ((float)(mx-(ar->winx/2)))*rv3d->zfac/(ar->winx/2);
2359                 dy= ((float)(my-(ar->winy/2)))*rv3d->zfac/(ar->winy/2);
2360                 
2361                 fz= rv3d->persmat[0][3]*fp[0]+ rv3d->persmat[1][3]*fp[1]+ rv3d->persmat[2][3]*fp[2]+ rv3d->persmat[3][3];
2362                 fz= fz/rv3d->zfac;
2363                 
2364                 fp[0]= (rv3d->persinv[0][0]*dx + rv3d->persinv[1][0]*dy+ rv3d->persinv[2][0]*fz)-rv3d->ofs[0];
2365                 fp[1]= (rv3d->persinv[0][1]*dx + rv3d->persinv[1][1]*dy+ rv3d->persinv[2][1]*fz)-rv3d->ofs[1];
2366                 fp[2]= (rv3d->persinv[0][2]*dx + rv3d->persinv[1][2]*dy+ rv3d->persinv[2][2]*fz)-rv3d->ofs[2];
2367         }
2368
2369         /* extrude to the where new cursor is and store the operation result */
2370         retv= armature_click_extrude_exec(C, op);
2371
2372         /* restore previous 3d cursor position */
2373         VECCOPY(fp, oldcurs);
2374
2375         return retv;
2376 }
2377
2378 void ARMATURE_OT_click_extrude(wmOperatorType *ot)
2379 {
2380         /* identifiers */
2381         ot->name= "Click-Extrude";
2382         ot->idname= "ARMATURE_OT_click_extrude";
2383         
2384         /* api callbacks */
2385         ot->invoke = armature_click_extrude_invoke;
2386         ot->exec = armature_click_extrude_exec;
2387         ot->poll = ED_operator_editarmature;
2388         
2389         /* flags */
2390         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2391
2392         /* props */
2393 }
2394
2395 /* adds an EditBone between the nominated locations (should be in the right space) */
2396 static EditBone *add_points_bone (Object *obedit, float head[], float tail[]) 
2397 {
2398         EditBone *ebo;
2399         
2400         ebo= add_editbone(obedit, "Bone");
2401         
2402         VECCOPY(ebo->head, head);
2403         VECCOPY(ebo->tail, tail);
2404         
2405         return ebo;
2406 }
2407
2408
2409 static EditBone *get_named_editbone(ListBase *edbo, char *name)
2410 {
2411         EditBone  *eBone;
2412
2413         if (name) {
2414                 for (eBone=edbo->first; eBone; eBone=eBone->next) {
2415                         if (!strcmp(name, eBone->name))
2416                                 return eBone;
2417                 }
2418         }
2419
2420         return NULL;
2421 }
2422
2423 /* Call this before doing any duplications
2424  * */
2425 void preEditBoneDuplicate(ListBase *editbones)
2426 {
2427         EditBone *eBone;
2428         
2429         /* clear temp */
2430         for (eBone = editbones->first; eBone; eBone = eBone->next)
2431         {
2432                 eBone->temp = NULL;
2433         }
2434 }
2435
2436 /*
2437  * Note: When duplicating cross objects, editbones here is the list of bones
2438  * from the SOURCE object but ob is the DESTINATION object
2439  * */
2440 void updateDuplicateSubtargetObjects(EditBone *dupBone, ListBase *editbones, Object *src_ob, Object *dst_ob)
2441 {
2442         /* If an edit bone has been duplicated, lets
2443          * update it's constraints if the subtarget
2444          * they point to has also been duplicated
2445          */
2446         EditBone     *oldtarget, *newtarget;
2447         bPoseChannel *chan;
2448         bConstraint  *curcon;
2449         ListBase     *conlist;
2450         
2451         if ( (chan = verify_pose_channel(dst_ob->pose, dupBone->name)) ) {
2452                 if ( (conlist = &chan->constraints) ) {
2453                         for (curcon = conlist->first; curcon; curcon=curcon->next) {
2454                                 /* does this constraint have a subtarget in
2455                                  * this armature?
2456                                  */
2457                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
2458                                 ListBase targets = {NULL, NULL};
2459                                 bConstraintTarget *ct;
2460                                 
2461                                 if (cti && cti->get_constraint_targets) {
2462                                         cti->get_constraint_targets(curcon, &targets);
2463                                         
2464                                         for (ct= targets.first; ct; ct= ct->next) {
2465                                                 if ((ct->tar == src_ob) && (ct->subtarget[0])) {
2466                                                         ct->tar = dst_ob; /* update target */ 
2467                                                         oldtarget = get_named_editbone(editbones, ct->subtarget);
2468                                                         if (oldtarget) {
2469                                                                 /* was the subtarget bone duplicated too? If
2470                                                                  * so, update the constraint to point at the 
2471                                                                  * duplicate of the old subtarget.
2472                                                                  */
2473                                                                 if (oldtarget->temp) {
2474                                                                         newtarget = (EditBone *) oldtarget->temp;
2475                                                                         strcpy(ct->subtarget, newtarget->name);
2476                                                                 }
2477                                                         }
2478                                                 }
2479                                         }
2480                                         
2481                                         if (cti->flush_constraint_targets)
2482                                                 cti->flush_constraint_targets(curcon, &targets, 0);
2483                                 }
2484                         }
2485                 }
2486         }
2487 }
2488
2489 void updateDuplicateSubtarget(EditBone *dupBone, ListBase *editbones, Object *ob)
2490 {
2491         updateDuplicateSubtargetObjects(dupBone, editbones, ob, ob);
2492 }
2493
2494
2495 EditBone *duplicateEditBoneObjects(EditBone *curBone, char *name, ListBase *editbones, Object *src_ob, Object *dst_ob)
2496 {
2497         EditBone *eBone = MEM_callocN(sizeof(EditBone), "addup_editbone");
2498         
2499         /*      Copy data from old bone to new bone */
2500         memcpy(eBone, curBone, sizeof(EditBone));
2501         
2502         curBone->temp = eBone;
2503         eBone->temp = curBone;
2504         
2505         if (name != NULL)
2506         {
2507                 BLI_strncpy(eBone->name, name, 32);
2508         }
2509
2510         unique_editbone_name(editbones, eBone->name, NULL);
2511         BLI_addtail(editbones, eBone);
2512         
2513         /* Lets duplicate the list of constraints that the
2514          * current bone has.
2515          */
2516         if (src_ob->pose) {
2517                 bPoseChannel *chanold, *channew;
2518                 ListBase     *listold, *listnew;
2519                 
2520                 chanold = verify_pose_channel(src_ob->pose, curBone->name);
2521                 if (chanold) {
2522                         listold = &chanold->constraints;
2523                         if (listold) {
2524                                 /* WARNING: this creates a new posechannel, but there will not be an attached bone 
2525                                  *              yet as the new bones created here are still 'EditBones' not 'Bones'. 
2526                                  */
2527                                 channew = 
2528                                         verify_pose_channel(dst_ob->pose, eBone->name);
2529                                 if (channew) {
2530                                         /* copy transform locks */
2531                                         channew->protectflag = chanold->protectflag;
2532                                         
2533                                         /* copy bone group */
2534                                         channew->agrp_index= chanold->agrp_index;
2535                                         
2536                                         /* ik (dof) settings */
2537                                         channew->ikflag = chanold->ikflag;
2538                                         VECCOPY(channew->limitmin, chanold->limitmin);
2539                                         VECCOPY(channew->limitmax, chanold->limitmax);
2540                                         VECCOPY(channew->stiffness, chanold->stiffness);
2541                                         channew->ikstretch= chanold->ikstretch;
2542                                         
2543                                         /* constraints */
2544                                         listnew = &channew->constraints;
2545                                         copy_constraints(listnew, listold);
2546                                         
2547                                         /* custom shape */
2548                                         channew->custom= chanold->custom;
2549                                 }
2550                         }
2551                 }
2552         }
2553         
2554         return eBone;
2555 }
2556
2557 EditBone *duplicateEditBone(EditBone *curBone, char *name, ListBase *editbones, Object *ob)
2558 {
2559         return duplicateEditBoneObjects(curBone, name, editbones, ob, ob);
2560 }
2561
2562 /* previously adduplicate_armature */
2563 static int armature_duplicate_selected_exec(bContext *C, wmOperator *op)
2564 {
2565         bArmature *arm;
2566         EditBone        *eBone = NULL;
2567         EditBone        *curBone;
2568         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
2569
2570         Object *obedit= CTX_data_edit_object(C);
2571         arm= obedit->data;
2572
2573         /* cancel if nothing selected */
2574         if (CTX_DATA_COUNT(C, selected_bones) == 0)
2575           return OPERATOR_CANCELLED;
2576         
2577         ED_armature_sync_selection(arm->edbo); // XXX why is this needed?
2578
2579         preEditBoneDuplicate(arm->edbo);
2580
2581         /* Select mirrored bones */
2582         if (arm->flag & ARM_MIRROR_EDIT) {
2583                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
2584                         if (EBONE_VISIBLE(arm, curBone)) {
2585                                 if (curBone->flag & BONE_SELECTED) {
2586                                         eBone = ED_armature_bone_get_mirrored(arm->edbo, curBone);
2587                                         if (eBone)
2588                                                 eBone->flag |= BONE_SELECTED;
2589                                 }
2590                         }
2591                 }
2592         }
2593
2594         
2595         /*      Find the selected bones and duplicate them as needed */
2596         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2597                 if (EBONE_VISIBLE(arm, curBone)) {
2598                         if (curBone->flag & BONE_SELECTED) {
2599                                 eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
2600                                 eBone->flag |= BONE_SELECTED;
2601                                 
2602                                 /* Copy data from old bone to new bone */
2603                                 memcpy(eBone, curBone, sizeof(EditBone));
2604                                 
2605                                 curBone->temp = eBone;
2606                                 eBone->temp = curBone;
2607                                 
2608                                 unique_editbone_name(arm->edbo, eBone->name, NULL);
2609                                 BLI_addtail(arm->edbo, eBone);
2610                                 if (!firstDup)
2611                                         firstDup=eBone;
2612                                 
2613                                 /* Lets duplicate the list of constraints that the
2614                                  * current bone has.
2615                                  */
2616                                 if (obedit->pose) {
2617                                         bPoseChannel *chanold, *channew;
2618                                         ListBase     *listold, *listnew;
2619                                         
2620                                         chanold = verify_pose_channel(obedit->pose, curBone->name);
2621                                         if (chanold) {
2622                                                 listold = &chanold->constraints;
2623                                                 if (listold) {
2624                                                         /* WARNING: this creates a new posechannel, but there will not be an attached bone 
2625                                                          *              yet as the new bones created here are still 'EditBones' not 'Bones'. 
2626                                                          */
2627                                                         channew = 
2628                                                                 verify_pose_channel(obedit->pose, eBone->name);
2629                                                         if (channew) {
2630                                                                 /* copy transform locks */
2631                                                                 channew->protectflag = chanold->protectflag;
2632                                                                 
2633                                                                 /* copy rotation mode */
2634                                                                 channew->rotmode = chanold->rotmode;
2635                                                                 
2636                                                                 /* copy bone group */
2637                                                                 channew->agrp_index= chanold->agrp_index;
2638                                                                 
2639                                                                 /* ik (dof) settings */
2640                                                                 channew->ikflag = chanold->ikflag;
2641                                                                 VECCOPY(channew->limitmin, chanold->limitmin);
2642                                                                 VECCOPY(channew->limitmax, chanold->limitmax);
2643                                                                 VECCOPY(channew->stiffness, chanold->stiffness);
2644                                                                 channew->ikstretch= chanold->ikstretch;
2645                                                                 
2646                                                                 /* constraints */
2647                                                                 listnew = &channew->constraints;
2648                                                                 copy_constraints(listnew, listold);
2649                                                                 
2650                                                                 /* custom shape */
2651                                                                 channew->custom= chanold->custom;
2652                                                         }
2653                                                 }
2654                                         }
2655                                 }
2656                         }
2657                 }
2658         }
2659
2660         /*      Run though the list and fix the pointers */
2661         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2662                 if (EBONE_VISIBLE(arm, curBone)) {
2663                         if (curBone->flag & BONE_SELECTED) {
2664                                 eBone=(EditBone*) curBone->temp;
2665                                 
2666                                 if (!curBone->parent) {
2667                                         /* If this bone has no parent,
2668                                          * Set the duplicate->parent to NULL
2669                                          */
2670                                         eBone->parent = NULL;
2671                                 }
2672                                 else if (curBone->parent->temp) {
2673                                         /* If this bone has a parent that was duplicated,
2674                                          * Set the duplicate->parent to the curBone->parent->temp
2675                                          */
2676                                         eBone->parent= (EditBone *)curBone->parent->temp;
2677                                 }
2678                                 else {
2679                                         /* If this bone has a parent that IS not selected,
2680                                          * Set the duplicate->parent to the curBone->parent
2681                                          */
2682                                         eBone->parent=(EditBone*) curBone->parent; 
2683                                         eBone->flag &= ~BONE_CONNECTED;
2684                                 }
2685                                 
2686                                 /* Lets try to fix any constraint subtargets that might
2687                                  * have been duplicated 
2688                                  */
2689                                 updateDuplicateSubtarget(eBone, arm->edbo, obedit);
2690                         }
2691                 }
2692         } 
2693         
2694         /*      Deselect the old bones and select the new ones */
2695         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2696                 if (EBONE_VISIBLE(arm, curBone))
2697                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
2698         }
2699
2700         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2701         
2702         return OPERATOR_FINISHED;
2703 }
2704
2705 static int armature_duplicate_selected_invoke(bContext *C, wmOperator *op, wmEvent *event)
2706 {
2707         int retv= armature_duplicate_selected_exec(C, op);
2708
2709         if (retv == OPERATOR_FINISHED) {
2710                 RNA_int_set(op->ptr, "mode", TFM_TRANSLATION);
2711                 WM_operator_name_call(C, "TFM_OT_transform", WM_OP_INVOKE_REGION_WIN, op->ptr);
2712         }
2713
2714         return retv;
2715 }
2716
2717 void ARMATURE_OT_duplicate(wmOperatorType *ot)
2718 {
2719         /* identifiers */
2720         ot->name= "Duplicate Selected Bone(s)";
2721         ot->idname= "ARMATURE_OT_duplicate";
2722         
2723         /* api callbacks */
2724         ot->invoke = armature_duplicate_selected_invoke;
2725         ot->exec = armature_duplicate_selected_exec;
2726         ot->poll = ED_operator_editarmature;
2727         
2728         /* flags */
2729         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2730
2731         /* to give to transform */
2732         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
2733 }
2734
2735
2736 /* *************** END Adding stuff in editmode *************** */
2737 /* ************** Add/Remove stuff in editmode **************** */
2738
2739 /* temporary data-structure for merge/fill bones */
2740 typedef struct EditBonePoint {
2741         struct EditBonePoint *next, *prev;
2742         
2743         EditBone *head_owner;           /* EditBone which uses this point as a 'head' point */
2744         EditBone *tail_owner;           /* EditBone which uses this point as a 'tail' point */
2745         
2746         float vec[3];                           /* the actual location of the point in local/EditMode space */
2747 } EditBonePoint;
2748
2749 /* find chain-tips (i.e. bones without children) */
2750 static void chains_find_tips (ListBase *edbo, ListBase *list)
2751 {
2752         EditBone *curBone, *ebo;
2753         LinkData *ld;
2754         
2755         /* note: this is potentially very slow ... there's got to be a better way */
2756         for (curBone= edbo->first; curBone; curBone= curBone->next) {
2757                 short stop= 0;
2758                 
2759                 /* is this bone contained within any existing chain? (skip if so) */
2760                 for (ld= list->first; ld; ld= ld->next) {
2761                         for (ebo= ld->data; ebo; ebo= ebo->parent) {
2762                                 if (ebo == curBone) {
2763                                         stop= 1;
2764                                         break;
2765                                 }
2766                         }
2767                         
2768                         if (stop) break;
2769                 }
2770                 /* skip current bone if it is part of an existing chain */
2771                 if (stop) continue;
2772                 
2773                 /* is any existing chain part of the chain formed by this bone? */
2774                 stop= 0;
2775                 for (ebo= curBone->parent; ebo; ebo= ebo->parent) {
2776                         for (ld= list->first; ld; ld= ld->next) {
2777                                 if (ld->data == ebo) {
2778                                         ld->data= curBone;
2779                                         stop= 1;
2780                                         break;
2781                                 }
2782                         }
2783                         
2784                         if (stop) break;
2785                 }
2786                 /* current bone has already been added to a chain? */
2787                 if (stop) continue;
2788                 
2789                 /* add current bone to a new chain */
2790                 ld= MEM_callocN(sizeof(LinkData), "BoneChain");
2791                 ld->data= curBone;
2792                 BLI_addtail(list, ld);
2793         }
2794 }
2795
2796 /* --------------------- */
2797
2798 static void fill_add_joint (EditBone *ebo, short eb_tail, ListBase *points)
2799 {
2800         EditBonePoint *ebp;
2801         float vec[3];
2802         short found= 0;
2803         
2804         if (eb_tail) {
2805                 VECCOPY(vec, ebo->tail);
2806         }
2807         else {
2808                 VECCOPY(vec, ebo->head);
2809         }
2810         
2811         for (ebp= points->first; ebp; ebp= ebp->next) {
2812                 if (VecEqual(ebp->vec, vec)) {                  
2813                         if (eb_tail) {
2814                                 if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
2815                                         /* so this bone's tail owner is this bone */
2816                                         ebp->tail_owner= ebo;
2817                                         found= 1;
2818                                         break;
2819                                 }
2820                         }
2821                         else {
2822                                 if ((ebp->tail_owner) && (ebo->parent == ebp->tail_owner)) {
2823                                         /* so this bone's head owner is this bone */
2824                                         ebp->head_owner= ebo;
2825                                         found = 1;
2826                                         break;
2827                                 }
2828                         }
2829                 }
2830         }
2831         
2832         /* allocate a new point if no existing point was related */
2833         if (found == 0) {
2834                 ebp= MEM_callocN(sizeof(EditBonePoint), "EditBonePoint");
2835                 
2836                 if (eb_tail) {
2837                         VECCOPY(ebp->vec, ebo->tail);
2838                         ebp->tail_owner= ebo;
2839                 }
2840                 else {
2841                         VECCOPY(ebp->vec, ebo->head);
2842                         ebp->head_owner= ebo;
2843                 }
2844                 
2845                 BLI_addtail(points, ebp);
2846         }
2847 }
2848
2849 /* bone adding between selected joints */
2850 static int armature_fill_bones_exec (bContext *C, wmOperator *op)
2851 {
2852         Object *obedit= CTX_data_edit_object(C);
2853         bArmature *arm= (obedit) ? obedit->data : NULL;
2854         Scene *scene= CTX_data_scene(C);
2855         View3D *v3d= CTX_wm_view3d(C);
2856         EditBone *newbone=NULL;
2857         ListBase points = {NULL, NULL};
2858         int count;
2859         
2860         /* sanity checks */
2861         if ELEM(NULL, obedit, arm)
2862                 return OPERATOR_CANCELLED;
2863         
2864         /* loop over all bones, and only consider if visible */
2865         CTX_DATA_BEGIN(C, EditBone *, ebone, visible_bones)
2866         {
2867                 if (!(ebone->flag & BONE_CONNECTED) && (ebone->flag & BONE_ROOTSEL))
2868                         fill_add_joint(ebone, 0, &points);
2869                 if (ebone->flag & BONE_TIPSEL) 
2870                         fill_add_joint(ebone, 1, &points);
2871         }
2872         CTX_DATA_END;
2873         
2874         /* the number of joints determines how we fill:
2875          *      1) between joint and cursor (joint=head, cursor=tail)
2876          *      2) between the two joints (order is dependent on active-bone/hierachy)
2877          *      3+) error (a smarter method involving finding chains needs to be worked out
2878          */
2879         count= BLI_countlist(&points);
2880         
2881         if (count == 0) {
2882                 BKE_report(op->reports, RPT_ERROR, "No joints selected");
2883                 return OPERATOR_CANCELLED;
2884         }
2885         else if (count == 1) {
2886                 EditBonePoint *ebp;
2887                 float *fp, curs[3];
2888                 
2889                 /* Get Points - selected joint */
2890                 ebp= (EditBonePoint *)points.first;
2891