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