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