b1c23fb4cac1ea30ccac32a144d34dfd012a9af5
[blender.git] / source / blender / editors / armature / armature_edit.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2002-2009 full recode.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * Armature EditMode tools - transforms, chain based editing, and other settings
26  */
27
28 /** \file blender/editors/armature/armature_edit.c
29  *  \ingroup edarmature
30  */
31
32 #include <assert.h> 
33
34 #include "DNA_armature_types.h"
35 #include "DNA_constraint_types.h"
36 #include "DNA_object_types.h"
37 #include "DNA_scene_types.h"
38
39 #include "MEM_guardedalloc.h"
40
41 #include "BLT_translation.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_math.h"
45 #include "BLI_ghash.h"
46
47 #include "BKE_action.h"
48 #include "BKE_armature.h"
49 #include "BKE_constraint.h"
50 #include "BKE_context.h"
51 #include "BKE_global.h"
52 #include "BKE_report.h"
53
54 #include "RNA_access.h"
55 #include "RNA_define.h"
56
57 #include "WM_api.h"
58 #include "WM_types.h"
59
60 #include "ED_armature.h"
61 #include "ED_screen.h"
62 #include "ED_view3d.h"
63
64 #include "armature_intern.h"
65
66 /* ************************** Object Tools Exports ******************************* */
67 /* NOTE: these functions are exported to the Object module to be called from the tools there */
68
69 void ED_armature_apply_transform(Object *ob, float mat[4][4])
70 {
71         bArmature *arm = ob->data;
72
73         /* Put the armature into editmode */
74         ED_armature_to_edit(arm);
75
76         /* Transform the bones */
77         ED_armature_transform_bones(arm, mat);
78
79         /* Turn the list into an armature */
80         ED_armature_from_edit(arm);
81         ED_armature_edit_free(arm);
82 }
83
84 void ED_armature_transform_bones(struct bArmature *arm, float mat[4][4])
85 {
86         EditBone *ebone;
87         float scale = mat4_to_scale(mat);   /* store the scale of the matrix here to use on envelopes */
88         float mat3[3][3];
89
90         copy_m3_m4(mat3, mat);
91         normalize_m3(mat3);
92         /* Do the rotations */
93         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
94                 float tmat[3][3];
95                 
96                 /* find the current bone's roll matrix */
97                 ED_armature_ebone_to_mat3(ebone, tmat);
98                 
99                 /* transform the roll matrix */
100                 mul_m3_m3m3(tmat, mat3, tmat);
101                 
102                 /* transform the bone */
103                 mul_m4_v3(mat, ebone->head);
104                 mul_m4_v3(mat, ebone->tail);
105
106                 /* apply the transformed roll back */
107                 mat3_to_vec_roll(tmat, NULL, &ebone->roll);
108                 
109                 ebone->rad_head *= scale;
110                 ebone->rad_tail *= scale;
111                 ebone->dist     *= scale;
112                 
113                 /* we could be smarter and scale by the matrix along the x & z axis */
114                 ebone->xwidth   *= scale;
115                 ebone->zwidth   *= scale;
116         }
117 }
118
119 void ED_armature_transform(struct bArmature *arm, float mat[4][4])
120 {
121         if (arm->edbo) {
122                 ED_armature_transform_bones(arm, mat);
123         }
124         else {
125                 /* Put the armature into editmode */
126                 ED_armature_to_edit(arm);
127
128                 /* Transform the bones */
129                 ED_armature_transform_bones(arm, mat);
130
131                 /* Go back to object mode*/
132                 ED_armature_from_edit(arm);
133                 ED_armature_edit_free(arm);
134         }
135 }
136
137 /* exported for use in editors/object/ */
138 /* 0 == do center, 1 == center new, 2 == center cursor */
139 void ED_armature_origin_set(Scene *scene, Object *ob, float cursor[3], int centermode, int around)
140 {
141         Object *obedit = scene->obedit; // XXX get from context
142         EditBone *ebone;
143         bArmature *arm = ob->data;
144         float cent[3];
145
146         /* Put the armature into editmode */
147         if (ob != obedit) {
148                 ED_armature_to_edit(arm);
149                 obedit = NULL; /* we cant use this so behave as if there is no obedit */
150         }
151
152         /* Find the centerpoint */
153         if (centermode == 2) {
154                 copy_v3_v3(cent, cursor);
155                 invert_m4_m4(ob->imat, ob->obmat);
156                 mul_m4_v3(ob->imat, cent);
157         }
158         else {
159                 if (around == V3D_AROUND_CENTER_MEAN) {
160                         int total = 0;
161                         zero_v3(cent);
162                         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
163                                 total += 2;
164                                 add_v3_v3(cent, ebone->head);
165                                 add_v3_v3(cent, ebone->tail);
166                         }
167                         if (total) {
168                                 mul_v3_fl(cent, 1.0f / (float)total);
169                         }
170                 }
171                 else {
172                         float min[3], max[3];
173                         INIT_MINMAX(min, max);
174                         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
175                                 minmax_v3v3_v3(min, max, ebone->head);
176                                 minmax_v3v3_v3(min, max, ebone->tail);
177                         }
178                         mid_v3_v3v3(cent, min, max);
179                 }
180         }
181         
182         /* Do the adjustments */
183         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
184                 sub_v3_v3(ebone->head, cent);
185                 sub_v3_v3(ebone->tail, cent);
186         }
187         
188         /* Turn the list into an armature */
189         if (obedit == NULL) {
190                 ED_armature_from_edit(arm);
191                 ED_armature_edit_free(arm);
192         }
193
194         /* Adjust object location for new centerpoint */
195         if (centermode && obedit == NULL) {
196                 mul_mat3_m4_v3(ob->obmat, cent); /* omit translation part */
197                 add_v3_v3(ob->loc, cent);
198         }
199 }
200
201 /* ********************************* Roll ******************************* */
202
203 /* adjust bone roll to align Z axis with vector
204  * vec is in local space and is normalized
205  */
206 float ED_rollBoneToVector(EditBone *bone, const float align_axis[3], const bool axis_only)
207 {
208         float mat[3][3], nor[3];
209         float vec[3], align_axis_proj[3], roll = 0.0f;
210
211         BLI_ASSERT_UNIT_V3(align_axis);
212
213         sub_v3_v3v3(nor, bone->tail, bone->head);
214
215         /* If tail == head or the bone is aligned with the axis... */
216         if (normalize_v3(nor) <= FLT_EPSILON || (fabsf(dot_v3v3(align_axis, nor)) >= (1.0f - FLT_EPSILON))) {
217                 return roll;
218         }
219
220         vec_roll_to_mat3_normalized(nor, 0.0f, mat);
221
222         /* project the new_up_axis along the normal */
223         project_v3_v3v3(vec, align_axis, nor);
224         sub_v3_v3v3(align_axis_proj, align_axis, vec);
225
226         if (axis_only) {
227                 if (angle_v3v3(align_axis_proj, mat[2]) > (float)(M_PI_2)) {
228                         negate_v3(align_axis_proj);
229                 }
230         }
231
232         roll = angle_v3v3(align_axis_proj, mat[2]);
233
234         cross_v3_v3v3(vec, mat[2], align_axis_proj);
235
236         if (dot_v3v3(vec, nor) < 0.0f) {
237                 return -roll;
238         }
239         return roll;
240 }
241
242 /* note, ranges arithmatic is used below */
243 typedef enum eCalcRollTypes {
244         /* pos */
245         CALC_ROLL_POS_X = 0,
246         CALC_ROLL_POS_Y,
247         CALC_ROLL_POS_Z,
248
249         CALC_ROLL_TAN_POS_X,
250         CALC_ROLL_TAN_POS_Z,
251
252         /* neg */
253         CALC_ROLL_NEG_X,
254         CALC_ROLL_NEG_Y,
255         CALC_ROLL_NEG_Z,
256
257         CALC_ROLL_TAN_NEG_X,
258         CALC_ROLL_TAN_NEG_Z,
259
260         /* no sign */
261         CALC_ROLL_ACTIVE,
262         CALC_ROLL_VIEW,
263         CALC_ROLL_CURSOR,
264 } eCalcRollTypes;
265
266 static EnumPropertyItem prop_calc_roll_types[] = {
267         {0, "", 0, N_("Positive"), ""},
268         {CALC_ROLL_TAN_POS_X, "POS_X", 0, "Local +X Tangent", ""},
269         {CALC_ROLL_TAN_POS_Z, "POS_Z", 0, "Local +Z Tangent", ""},
270
271         {CALC_ROLL_POS_X, "GLOBAL_POS_X", 0, "Global +X Axis", ""},
272         {CALC_ROLL_POS_Y, "GLOBAL_POS_Y", 0, "Global +Y Axis", ""},
273         {CALC_ROLL_POS_Z, "GLOBAL_POS_Z", 0, "Global +Z Axis", ""},
274
275         {0, "", 0, N_("Negative"), ""},
276
277         {CALC_ROLL_TAN_NEG_X, "NEG_X", 0, "Local -X Tangent", ""},
278         {CALC_ROLL_TAN_NEG_Z, "NEG_Z", 0, "Local -Z Tangent", ""},
279
280         {CALC_ROLL_NEG_X, "GLOBAL_NEG_X", 0, "Global -X Axis", ""},
281         {CALC_ROLL_NEG_Y, "GLOBAL_NEG_Y", 0, "Global -Y Axis", ""},
282         {CALC_ROLL_NEG_Z, "GLOBAL_NEG_Z", 0, "Global -Z Axis", ""},
283
284         {0, "", 0, N_("Other"), ""},
285         {CALC_ROLL_ACTIVE, "ACTIVE", 0, "Active Bone", ""},
286         {CALC_ROLL_VIEW, "VIEW", 0, "View Axis", ""},
287         {CALC_ROLL_CURSOR, "CURSOR", 0, "Cursor", ""},
288         {0, NULL, 0, NULL, NULL}
289 };
290
291
292 static int armature_calc_roll_exec(bContext *C, wmOperator *op) 
293 {
294         Object *ob = CTX_data_edit_object(C);
295         eCalcRollTypes type = RNA_enum_get(op->ptr, "type");
296         const bool axis_only = RNA_boolean_get(op->ptr, "axis_only");
297         /* axis_flip when matching the active bone never makes sense */
298         bool axis_flip = ((type >= CALC_ROLL_ACTIVE) ? RNA_boolean_get(op->ptr, "axis_flip") :
299                           (type >= CALC_ROLL_TAN_NEG_X) ? true : false);
300
301         float imat[3][3];
302
303         bArmature *arm = ob->data;
304         EditBone *ebone;
305
306         if ((type >= CALC_ROLL_NEG_X) && (type <= CALC_ROLL_TAN_NEG_Z)) {
307                 type -= (CALC_ROLL_ACTIVE - CALC_ROLL_NEG_X);
308                 axis_flip = true;
309         }
310
311         copy_m3_m4(imat, ob->obmat);
312         invert_m3(imat);
313
314         if (type == CALC_ROLL_CURSOR) { /* Cursor */
315                 Scene *scene = CTX_data_scene(C);
316                 View3D *v3d = CTX_wm_view3d(C); /* can be NULL */
317                 float cursor_local[3];
318                 const float   *cursor = ED_view3d_cursor3d_get(scene, v3d);
319                 
320                 
321                 copy_v3_v3(cursor_local, cursor);
322                 mul_m3_v3(imat, cursor_local);
323                 
324                 /* cursor */
325                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
326                         if (EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) {
327                                 float cursor_rel[3];
328                                 sub_v3_v3v3(cursor_rel, cursor_local, ebone->head);
329                                 if (axis_flip) negate_v3(cursor_rel);
330                                 if (normalize_v3(cursor_rel) != 0.0f) {
331                                         ebone->roll = ED_rollBoneToVector(ebone, cursor_rel, axis_only);
332                                 }
333                         }
334                 }
335         }
336         else if (ELEM(type, CALC_ROLL_TAN_POS_X, CALC_ROLL_TAN_POS_Z)) {
337                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
338                         if (ebone->parent) {
339                                 bool is_edit        = (EBONE_VISIBLE(arm, ebone)         && EBONE_EDITABLE(ebone));
340                                 bool is_edit_parent = (EBONE_VISIBLE(arm, ebone->parent) && EBONE_EDITABLE(ebone->parent));
341
342                                 if (is_edit || is_edit_parent) {
343                                         EditBone *ebone_other = ebone->parent;
344                                         float dir_a[3];
345                                         float dir_b[3];
346                                         float vec[3];
347                                         bool is_vec_zero;
348
349                                         sub_v3_v3v3(dir_a, ebone->tail, ebone->head);
350                                         normalize_v3(dir_a);
351
352                                         /* find the first bone in the chane with a different direction */
353                                         do {
354                                                 sub_v3_v3v3(dir_b, ebone_other->head, ebone_other->tail);
355                                                 normalize_v3(dir_b);
356
357                                                 if (type == CALC_ROLL_TAN_POS_Z) {
358                                                         cross_v3_v3v3(vec, dir_a, dir_b);
359                                                 }
360                                                 else {
361                                                         add_v3_v3v3(vec, dir_a, dir_b);
362                                                 }
363                                         } while ((is_vec_zero = (normalize_v3(vec) < 0.00001f)) &&
364                                                  (ebone_other = ebone_other->parent));
365
366                                         if (!is_vec_zero) {
367                                                 if (axis_flip) negate_v3(vec);
368
369                                                 if (is_edit) {
370                                                         ebone->roll = ED_rollBoneToVector(ebone, vec, axis_only);
371                                                 }
372
373                                                 /* parentless bones use cross product with child */
374                                                 if (is_edit_parent) {
375                                                         if (ebone->parent->parent == NULL) {
376                                                                 ebone->parent->roll = ED_rollBoneToVector(ebone->parent, vec, axis_only);
377                                                         }
378                                                 }
379                                         }
380                                 }
381                         }
382                 }
383         }
384         else {
385                 float vec[3] = {0.0f, 0.0f, 0.0f};
386                 if (type == CALC_ROLL_VIEW) { /* View */
387                         RegionView3D *rv3d = CTX_wm_region_view3d(C);
388                         if (rv3d == NULL) {
389                                 BKE_report(op->reports, RPT_ERROR, "No region view3d available");
390                                 return OPERATOR_CANCELLED;
391                         }
392                         
393                         copy_v3_v3(vec, rv3d->viewinv[2]);
394                         mul_m3_v3(imat, vec);
395                 }
396                 else if (type == CALC_ROLL_ACTIVE) {
397                         float mat[3][3];
398                         ebone = (EditBone *)arm->act_edbone;
399                         if (ebone == NULL) {
400                                 BKE_report(op->reports, RPT_ERROR, "No active bone set");
401                                 return OPERATOR_CANCELLED;
402                         }
403                         
404                         ED_armature_ebone_to_mat3(ebone, mat);
405                         copy_v3_v3(vec, mat[2]);
406                 }
407                 else { /* Axis */
408                         assert(type <= 5);
409                         if (type < 3) vec[type] = 1.0f;
410                         else vec[type - 2] = -1.0f;
411                         mul_m3_v3(imat, vec);
412                 }
413                 
414                 if (axis_flip) negate_v3(vec);
415                 
416                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
417                         if (EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) {
418                                 /* roll func is a callback which assumes that all is well */
419                                 ebone->roll = ED_rollBoneToVector(ebone, vec, axis_only);
420                         }
421                 }
422         }
423         
424         if (arm->flag & ARM_MIRROR_EDIT) {
425                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
426                         if ((EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) == 0) {
427                                 EditBone *ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, ebone);
428                                 if (ebone_mirr && (EBONE_VISIBLE(arm, ebone_mirr) && EBONE_EDITABLE(ebone_mirr))) {
429                                         ebone->roll = -ebone_mirr->roll;
430                                 }
431                         }
432                 }
433         }
434         
435         /* note, notifier might evolve */
436         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
437         
438         return OPERATOR_FINISHED;
439 }
440
441 void ARMATURE_OT_calculate_roll(wmOperatorType *ot)
442 {
443         /* identifiers */
444         ot->name = "Recalculate Roll";
445         ot->idname = "ARMATURE_OT_calculate_roll";
446         ot->description = "Automatically fix alignment of select bones' axes";
447         
448         /* api callbacks */
449         ot->invoke = WM_menu_invoke;
450         ot->exec = armature_calc_roll_exec;
451         ot->poll = ED_operator_editarmature;
452         
453         /* flags */
454         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
455
456         /* properties */
457         ot->prop = RNA_def_enum(ot->srna, "type", prop_calc_roll_types, CALC_ROLL_TAN_POS_X, "Type", "");
458         RNA_def_boolean(ot->srna, "axis_flip", 0, "Flip Axis", "Negate the alignment axis");
459         RNA_def_boolean(ot->srna, "axis_only", 0, "Shortest Rotation", "Ignore the axis direction, use the shortest rotation to align");
460 }
461
462 static int armature_roll_clear_exec(bContext *C, wmOperator *op)
463 {
464         Object *ob = CTX_data_edit_object(C);
465
466         bArmature *arm = ob->data;
467         EditBone *ebone;
468
469         const float roll = RNA_float_get(op->ptr, "roll");
470
471         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
472                 if (EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) {
473                         /* roll func is a callback which assumes that all is well */
474                         ebone->roll = roll;
475                 }
476         }
477
478         if (arm->flag & ARM_MIRROR_EDIT) {
479                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
480                         if ((EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) == 0) {
481                                 EditBone *ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, ebone);
482                                 if (ebone_mirr && (EBONE_VISIBLE(arm, ebone_mirr) && EBONE_EDITABLE(ebone_mirr))) {
483                                         ebone->roll = -ebone_mirr->roll;
484                                 }
485                         }
486                 }
487         }
488
489         /* note, notifier might evolve */
490         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
491
492         return OPERATOR_FINISHED;
493 }
494
495 void ARMATURE_OT_roll_clear(wmOperatorType *ot)
496 {
497         /* identifiers */
498         ot->name = "Clear Roll";
499         ot->idname = "ARMATURE_OT_roll_clear";
500         ot->description = "Clear roll for selected bones";
501
502         /* api callbacks */
503         ot->exec = armature_roll_clear_exec;
504         ot->poll = ED_operator_editarmature;
505
506         /* flags */
507         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
508
509         RNA_def_float_rotation(
510                 ot->srna, "roll", 0, NULL, DEG2RADF(-360.0f), DEG2RADF(360.0f),
511                 "Roll", "", DEG2RADF(-360.0f), DEG2RADF(360.0f));
512 }
513
514 /* ******************************** Chain-Based Tools ********************************* */
515
516 /* temporary data-structure for merge/fill bones */
517 typedef struct EditBonePoint {
518         struct EditBonePoint *next, *prev;
519         
520         EditBone *head_owner;       /* EditBone which uses this point as a 'head' point */
521         EditBone *tail_owner;       /* EditBone which uses this point as a 'tail' point */
522         
523         float vec[3];               /* the actual location of the point in local/EditMode space */
524 } EditBonePoint;
525
526 /* find chain-tips (i.e. bones without children) */
527 static void chains_find_tips(ListBase *edbo, ListBase *list)
528 {
529         EditBone *curBone, *ebo;
530         LinkData *ld;
531         
532         /* note: this is potentially very slow ... there's got to be a better way */
533         for (curBone = edbo->first; curBone; curBone = curBone->next) {
534                 short stop = 0;
535                 
536                 /* is this bone contained within any existing chain? (skip if so) */
537                 for (ld = list->first; ld; ld = ld->next) {
538                         for (ebo = ld->data; ebo; ebo = ebo->parent) {
539                                 if (ebo == curBone) {
540                                         stop = 1;
541                                         break;
542                                 }
543                         }
544                         
545                         if (stop) break;
546                 }
547                 /* skip current bone if it is part of an existing chain */
548                 if (stop) continue;
549                 
550                 /* is any existing chain part of the chain formed by this bone? */
551                 stop = 0;
552                 for (ebo = curBone->parent; ebo; ebo = ebo->parent) {
553                         for (ld = list->first; ld; ld = ld->next) {
554                                 if (ld->data == ebo) {
555                                         ld->data = curBone;
556                                         stop = 1;
557                                         break;
558                                 }
559                         }
560                         
561                         if (stop) break;
562                 }
563                 /* current bone has already been added to a chain? */
564                 if (stop) continue;
565                 
566                 /* add current bone to a new chain */
567                 ld = MEM_callocN(sizeof(LinkData), "BoneChain");
568                 ld->data = curBone;
569                 BLI_addtail(list, ld);
570         }
571 }
572
573 /* --------------------- */
574
575 static void fill_add_joint(EditBone *ebo, short eb_tail, ListBase *points)
576 {
577         EditBonePoint *ebp;
578         float vec[3];
579         short found = 0;
580         
581         if (eb_tail) {
582                 copy_v3_v3(vec, ebo->tail);
583         }
584         else {
585                 copy_v3_v3(vec, ebo->head);
586         }
587         
588         for (ebp = points->first; ebp; ebp = ebp->next) {
589                 if (equals_v3v3(ebp->vec, vec)) {
590                         if (eb_tail) {
591                                 if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
592                                         /* so this bone's tail owner is this bone */
593                                         ebp->tail_owner = ebo;
594                                         found = 1;
595                                         break;
596                                 }
597                         }
598                         else {
599                                 if ((ebp->tail_owner) && (ebo->parent == ebp->tail_owner)) {
600                                         /* so this bone's head owner is this bone */
601                                         ebp->head_owner = ebo;
602                                         found = 1;
603                                         break;
604                                 }
605                         }
606                 }
607         }
608         
609         /* allocate a new point if no existing point was related */
610         if (found == 0) {
611                 ebp = MEM_callocN(sizeof(EditBonePoint), "EditBonePoint");
612                 
613                 if (eb_tail) {
614                         copy_v3_v3(ebp->vec, ebo->tail);
615                         ebp->tail_owner = ebo;
616                 }
617                 else {
618                         copy_v3_v3(ebp->vec, ebo->head);
619                         ebp->head_owner = ebo;
620                 }
621                 
622                 BLI_addtail(points, ebp);
623         }
624 }
625
626 /* bone adding between selected joints */
627 static int armature_fill_bones_exec(bContext *C, wmOperator *op)
628 {
629         Object *obedit = CTX_data_edit_object(C);
630         bArmature *arm = (obedit) ? obedit->data : NULL;
631         Scene *scene = CTX_data_scene(C);
632         View3D *v3d = CTX_wm_view3d(C);
633         ListBase points = {NULL, NULL};
634         EditBone *newbone = NULL;
635         int count;
636
637         /* sanity checks */
638         if (ELEM(NULL, obedit, arm))
639                 return OPERATOR_CANCELLED;
640
641         /* loop over all bones, and only consider if visible */
642         CTX_DATA_BEGIN(C, EditBone *, ebone, visible_bones)
643         {
644                 if (!(ebone->flag & BONE_CONNECTED) && (ebone->flag & BONE_ROOTSEL))
645                         fill_add_joint(ebone, 0, &points);
646                 if (ebone->flag & BONE_TIPSEL) 
647                         fill_add_joint(ebone, 1, &points);
648         }
649         CTX_DATA_END;
650         
651         /* the number of joints determines how we fill:
652          *  1) between joint and cursor (joint=head, cursor=tail)
653          *  2) between the two joints (order is dependent on active-bone/hierarchy)
654          *  3+) error (a smarter method involving finding chains needs to be worked out
655          */
656         count = BLI_listbase_count(&points);
657         
658         if (count == 0) {
659                 BKE_report(op->reports, RPT_ERROR, "No joints selected");
660                 return OPERATOR_CANCELLED;
661         }
662         else if (count == 1) {
663                 EditBonePoint *ebp;
664                 float curs[3];
665                 
666                 /* Get Points - selected joint */
667                 ebp = points.first;
668                 
669                 /* Get points - cursor (tail) */
670                 invert_m4_m4(obedit->imat, obedit->obmat);
671                 mul_v3_m4v3(curs, obedit->imat, ED_view3d_cursor3d_get(scene, v3d));
672                 
673                 /* Create a bone */
674                 newbone = add_points_bone(obedit, ebp->vec, curs);
675         }
676         else if (count == 2) {
677                 EditBonePoint *ebp_a, *ebp_b;
678                 float head[3], tail[3];
679                 short headtail = 0;
680                 
681                 /* check that the points don't belong to the same bone */
682                 ebp_a = (EditBonePoint *)points.first;
683                 ebp_b = ebp_a->next;
684                 
685                 if (((ebp_a->head_owner == ebp_b->tail_owner) && (ebp_a->head_owner != NULL)) ||
686                     ((ebp_a->tail_owner == ebp_b->head_owner) && (ebp_a->tail_owner != NULL)))
687                 {
688                         BKE_report(op->reports, RPT_ERROR, "Same bone selected...");
689                         BLI_freelistN(&points);
690                         return OPERATOR_CANCELLED;
691                 }
692                 
693                 /* find which one should be the 'head' */
694                 if ((ebp_a->head_owner && ebp_b->head_owner) || (ebp_a->tail_owner && ebp_b->tail_owner)) {
695                         /* use active, nice predictable */
696                         if (arm->act_edbone && ELEM(arm->act_edbone, ebp_a->head_owner, ebp_a->tail_owner)) {
697                                 headtail = 1;
698                         }
699                         else if (arm->act_edbone && ELEM(arm->act_edbone, ebp_b->head_owner, ebp_b->tail_owner)) {
700                                 headtail = 2;
701                         }
702                         else {
703                                 /* rule: whichever one is closer to 3d-cursor */
704                                 float curs[3];
705                                 float dist_sq_a, dist_sq_b;
706
707                                 /* get cursor location */
708                                 invert_m4_m4(obedit->imat, obedit->obmat);
709                                 mul_v3_m4v3(curs, obedit->imat, ED_view3d_cursor3d_get(scene, v3d));
710
711                                 /* get distances */
712                                 dist_sq_a = len_squared_v3v3(ebp_a->vec, curs);
713                                 dist_sq_b = len_squared_v3v3(ebp_b->vec, curs);
714
715                                 /* compare distances - closer one therefore acts as direction for bone to go */
716                                 headtail = (dist_sq_a < dist_sq_b) ? 2 : 1;
717                         }
718                 }
719                 else if (ebp_a->head_owner) {
720                         headtail = 1;
721                 }
722                 else if (ebp_b->head_owner) {
723                         headtail = 2;
724                 }
725                 
726                 /* assign head/tail combinations */
727                 if (headtail == 2) {
728                         copy_v3_v3(head, ebp_a->vec);
729                         copy_v3_v3(tail, ebp_b->vec);
730                 }
731                 else if (headtail == 1) {
732                         copy_v3_v3(head, ebp_b->vec);
733                         copy_v3_v3(tail, ebp_a->vec);
734                 }
735                 
736                 /* add new bone and parent it to the appropriate end */
737                 if (headtail) {
738                         newbone = add_points_bone(obedit, head, tail);
739                         
740                         /* do parenting (will need to set connected flag too) */
741                         if (headtail == 2) {
742                                 /* ebp tail or head - tail gets priority */
743                                 if (ebp_a->tail_owner)
744                                         newbone->parent = ebp_a->tail_owner;
745                                 else
746                                         newbone->parent = ebp_a->head_owner;
747                         }
748                         else {
749                                 /* ebp_b tail or head - tail gets priority */
750                                 if (ebp_b->tail_owner)
751                                         newbone->parent = ebp_b->tail_owner;
752                                 else
753                                         newbone->parent = ebp_b->head_owner;
754                         }
755
756                         /* don't set for bone connecting two head points of bones */
757                         if (ebp_a->tail_owner || ebp_b->tail_owner) {
758                                 newbone->flag |= BONE_CONNECTED;
759                         }
760                 }
761         }
762         else {
763                 /* FIXME.. figure out a method for multiple bones */
764                 BKE_reportf(op->reports, RPT_ERROR, "Too many points selected: %d", count);
765                 BLI_freelistN(&points);
766                 return OPERATOR_CANCELLED;
767         }
768
769         if (newbone) {
770                 ED_armature_deselect_all(obedit);
771                 arm->act_edbone = newbone;
772                 newbone->flag |= BONE_TIPSEL;
773         }
774         
775         /* updates */
776         WM_event_add_notifier(C, NC_OBJECT | ND_POSE, obedit);
777         
778         /* free points */
779         BLI_freelistN(&points);
780         
781         return OPERATOR_FINISHED;
782 }
783
784 void ARMATURE_OT_fill(wmOperatorType *ot)
785 {
786         /* identifiers */
787         ot->name = "Fill Between Joints";
788         ot->idname = "ARMATURE_OT_fill";
789         ot->description = "Add bone between selected joint(s) and/or 3D-Cursor";
790         
791         /* callbacks */
792         ot->exec = armature_fill_bones_exec;
793         ot->poll = ED_operator_editarmature;
794         
795         /* flags */
796         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
797 }
798
799 /* --------------------- */
800
801 /* this function merges between two bones, removes them and those in-between, 
802  * and adjusts the parent relationships for those in-between
803  */
804 static void bones_merge(Object *obedit, EditBone *start, EditBone *end, EditBone *endchild, ListBase *chains)
805 {
806         bArmature *arm = obedit->data;
807         EditBone *ebo, *ebone, *newbone;
808         LinkData *chain;
809         float head[3], tail[3];
810         
811         /* check if same bone */
812         if (start == end) {
813                 if (G.debug & G_DEBUG) {
814                         printf("Error: same bone!\n");
815                         printf("\tstart = %s, end = %s\n", start->name, end->name);
816                 }
817         }
818         
819         /* step 1: add a new bone
820          *      - head = head/tail of start (default head)
821          *      - tail = head/tail of end (default tail)
822          *      - parent = parent of start
823          */
824         if ((start->flag & BONE_TIPSEL) && (start->flag & BONE_SELECTED) == 0) {
825                 copy_v3_v3(head, start->tail);
826         }
827         else {
828                 copy_v3_v3(head, start->head);
829         }
830         if ((end->flag & BONE_ROOTSEL) && (end->flag & BONE_SELECTED) == 0) {
831                 copy_v3_v3(tail, end->head);
832         }
833         else {
834                 copy_v3_v3(tail, end->tail);
835         }
836         newbone = add_points_bone(obedit, head, tail);
837         newbone->parent = start->parent;
838
839         /* TODO, copy more things to the new bone */
840         newbone->flag = start->flag & (BONE_HINGE | BONE_NO_DEFORM | BONE_NO_SCALE |
841                                        BONE_NO_CYCLICOFFSET | BONE_NO_LOCAL_LOCATION | BONE_DONE);
842         
843         /* step 2a: reparent any side chains which may be parented to any bone in the chain of bones to merge 
844          *      - potentially several tips for side chains leading to some tree exist...
845          */
846         for (chain = chains->first; chain; chain = chain->next) {
847                 /* traverse down chain until we hit the bottom or if we run into the tip of the chain of bones we're 
848                  * merging (need to stop in this case to avoid corrupting this chain too!) 
849                  */
850                 for (ebone = chain->data; (ebone) && (ebone != end); ebone = ebone->parent) {
851                         short found = 0;
852                         
853                         /* check if this bone is parented to one in the merging chain
854                          * ! WATCHIT: must only go check until end of checking chain
855                          */
856                         for (ebo = end; (ebo) && (ebo != start->parent); ebo = ebo->parent) {
857                                 /* side-chain found? --> remap parent to new bone, then we're done with this chain :) */
858                                 if (ebone->parent == ebo) {
859                                         ebone->parent = newbone;
860                                         found = 1;
861                                         break;
862                                 }
863                         }
864                         
865                         /* carry on to the next tip now  */
866                         if (found) 
867                                 break;
868                 }
869         }
870         
871         /* step 2b: parent child of end to newbone (child from this chain) */
872         if (endchild)
873                 endchild->parent = newbone;
874         
875         /* step 3: delete all bones between and including start and end */
876         for (ebo = end; ebo; ebo = ebone) {
877                 ebone = (ebo == start) ? (NULL) : (ebo->parent);
878                 bone_free(arm, ebo);
879         }
880         
881         newbone->flag |= (BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
882         ED_armature_sync_selection(arm->edbo);
883 }
884
885
886 static int armature_merge_exec(bContext *C, wmOperator *op)
887 {
888         Object *obedit = CTX_data_edit_object(C);
889         bArmature *arm = (obedit) ? obedit->data : NULL;
890         short type = RNA_enum_get(op->ptr, "type");
891         
892         /* sanity checks */
893         if (ELEM(NULL, obedit, arm))
894                 return OPERATOR_CANCELLED;
895         
896         /* for now, there's only really one type of merging that's performed... */
897         if (type == 1) {
898                 /* go down chains, merging bones */
899                 ListBase chains = {NULL, NULL};
900                 LinkData *chain, *nchain;
901                 EditBone *ebo;
902                 
903                 armature_tag_select_mirrored(arm);
904                 
905                 /* get chains (ends on chains) */
906                 chains_find_tips(arm->edbo, &chains);
907                 if (BLI_listbase_is_empty(&chains)) return OPERATOR_CANCELLED;
908                 
909                 /* each 'chain' is the last bone in the chain (with no children) */
910                 for (chain = chains.first; chain; chain = nchain) {
911                         EditBone *bstart = NULL, *bend = NULL;
912                         EditBone *bchild = NULL, *child = NULL;
913                         
914                         /* temporarily remove chain from list of chains */
915                         nchain = chain->next;
916                         BLI_remlink(&chains, chain);
917                         
918                         /* only consider bones that are visible and selected */
919                         for (ebo = chain->data; ebo; child = ebo, ebo = ebo->parent) {
920                                 /* check if visible + selected */
921                                 if (EBONE_VISIBLE(arm, ebo) &&
922                                     ((ebo->flag & BONE_CONNECTED) || (ebo->parent == NULL)) &&
923                                     (ebo->flag & BONE_SELECTED) )
924                                 {
925                                         /* set either end or start (end gets priority, unless it is already set) */
926                                         if (bend == NULL) {
927                                                 bend = ebo;
928                                                 bchild = child;
929                                         }
930                                         else 
931                                                 bstart = ebo;
932                                 }
933                                 else {
934                                         /* chain is broken... merge any continous segments then clear */
935                                         if (bstart && bend)
936                                                 bones_merge(obedit, bstart, bend, bchild, &chains);
937                                         
938                                         bstart = NULL;
939                                         bend = NULL;
940                                         bchild = NULL;
941                                 }
942                         }
943                         
944                         /* merge from bstart to bend if something not merged */
945                         if (bstart && bend)
946                                 bones_merge(obedit, bstart, bend, bchild, &chains);
947                         
948                         /* put back link */
949                         BLI_insertlinkbefore(&chains, nchain, chain);
950                 }
951                 
952                 armature_tag_unselect(arm);
953                 
954                 BLI_freelistN(&chains);
955         }
956         
957         /* updates */
958         ED_armature_sync_selection(arm->edbo);
959         WM_event_add_notifier(C, NC_OBJECT | ND_POSE, obedit);
960         
961         return OPERATOR_FINISHED;
962 }
963
964 void ARMATURE_OT_merge(wmOperatorType *ot)
965 {
966         static EnumPropertyItem merge_types[] = {
967                 {1, "WITHIN_CHAIN", 0, "Within Chains", ""},
968                 {0, NULL, 0, NULL, NULL}
969         };
970
971         /* identifiers */
972         ot->name = "Merge Bones";
973         ot->idname = "ARMATURE_OT_merge";
974         ot->description = "Merge continuous chains of selected bones";
975         
976         /* callbacks */
977         ot->invoke = WM_menu_invoke;
978         ot->exec = armature_merge_exec;
979         ot->poll = ED_operator_editarmature;
980         
981         /* flags */
982         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
983         
984         /* properties */
985         ot->prop = RNA_def_enum(ot->srna, "type", merge_types, 0, "Type", "");
986 }
987
988 /* --------------------- */
989
990 /* Switch Direction operator:
991  * Currently, this does not use context loops, as context loops do not make it
992  * easy to retrieve any hierarchical/chain relationships which are necessary for
993  * this to be done easily.
994  */
995  
996 /* helper to clear BONE_TRANSFORM flags */
997 static void armature_clear_swap_done_flags(bArmature *arm)
998 {
999         EditBone *ebone;
1000         
1001         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1002                 ebone->flag &= ~BONE_TRANSFORM;
1003         }
1004 }
1005
1006 static int armature_switch_direction_exec(bContext *C, wmOperator *UNUSED(op)) 
1007 {
1008         Object *ob = CTX_data_edit_object(C);
1009         bArmature *arm = (bArmature *)ob->data;
1010         ListBase chains = {NULL, NULL};
1011         LinkData *chain;
1012         
1013         /* get chains of bones (ends on chains) */
1014         chains_find_tips(arm->edbo, &chains);
1015         if (BLI_listbase_is_empty(&chains)) return OPERATOR_CANCELLED;
1016         
1017         /* ensure that mirror bones will also be operated on */
1018         armature_tag_select_mirrored(arm);
1019         
1020         /* clear BONE_TRANSFORM flags 
1021          * - used to prevent duplicate/canceling operations from occurring [#34123]
1022          * - BONE_DONE cannot be used here as that's already used for mirroring
1023          */
1024         armature_clear_swap_done_flags(arm);
1025         
1026         /* loop over chains, only considering selected and visible bones */
1027         for (chain = chains.first; chain; chain = chain->next) {
1028                 EditBone *ebo, *child = NULL, *parent = NULL;
1029                 
1030                 /* loop over bones in chain */
1031                 for (ebo = chain->data; ebo; ebo = parent) {
1032                         /* parent is this bone's original parent
1033                          *      - we store this, as the next bone that is checked is this one
1034                          *        but the value of ebo->parent may change here...
1035                          */
1036                         parent = ebo->parent;
1037                         
1038                         /* skip bone if already handled... [#34123] */
1039                         if ((ebo->flag & BONE_TRANSFORM) == 0) {
1040                                 /* only if selected and editable */
1041                                 if (EBONE_VISIBLE(arm, ebo) && EBONE_EDITABLE(ebo)) {
1042                                         /* swap head and tail coordinates */
1043                                         swap_v3_v3(ebo->head, ebo->tail);
1044                                         
1045                                         /* do parent swapping:
1046                                          *      - use 'child' as new parent
1047                                          *      - connected flag is only set if points are coincidental
1048                                          */
1049                                         ebo->parent = child;
1050                                         if ((child) && equals_v3v3(ebo->head, child->tail))
1051                                                 ebo->flag |= BONE_CONNECTED;
1052                                         else
1053                                                 ebo->flag &= ~BONE_CONNECTED;
1054                                         
1055                                         /* get next bones 
1056                                          *      - child will become the new parent of next bone
1057                                          */
1058                                         child = ebo;
1059                                 }
1060                                 else {
1061                                         /* not swapping this bone, however, if its 'parent' got swapped, unparent us from it 
1062                                          * as it will be facing in opposite direction
1063                                          */
1064                                         if ((parent) && (EBONE_VISIBLE(arm, parent) && EBONE_EDITABLE(parent))) {
1065                                                 ebo->parent = NULL;
1066                                                 ebo->flag &= ~BONE_CONNECTED;
1067                                         }
1068                                         
1069                                         /* get next bones
1070                                          *      - child will become new parent of next bone (not swapping occurred, 
1071                                          *        so set to NULL to prevent infinite-loop)
1072                                          */
1073                                         child = NULL;
1074                                 }
1075                                 
1076                                 /* tag as done (to prevent double-swaps) */
1077                                 ebo->flag |= BONE_TRANSFORM;
1078                         }
1079                 }
1080         }
1081         
1082         /* free chains */
1083         BLI_freelistN(&chains);
1084         
1085         /* clear temp flags */
1086         armature_clear_swap_done_flags(arm);
1087         armature_tag_unselect(arm);
1088         
1089         /* note, notifier might evolve */
1090         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
1091         
1092         return OPERATOR_FINISHED;
1093 }
1094
1095 void ARMATURE_OT_switch_direction(wmOperatorType *ot)
1096 {
1097         /* identifiers */
1098         ot->name = "Switch Direction";
1099         ot->idname = "ARMATURE_OT_switch_direction";
1100         ot->description = "Change the direction that a chain of bones points in (head <-> tail swap)";
1101         
1102         /* api callbacks */
1103         ot->exec = armature_switch_direction_exec;
1104         ot->poll = ED_operator_editarmature;
1105         
1106         /* flags */
1107         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1108 }
1109
1110 /* ********************************* Align ******************************* */
1111
1112 /* helper to fix a ebone position if its parent has moved due to alignment*/
1113 static void fix_connected_bone(EditBone *ebone)
1114 {
1115         float diff[3];
1116         
1117         if (!(ebone->parent) || !(ebone->flag & BONE_CONNECTED) || equals_v3v3(ebone->parent->tail, ebone->head))
1118                 return;
1119         
1120         /* if the parent has moved we translate child's head and tail accordingly */
1121         sub_v3_v3v3(diff, ebone->parent->tail, ebone->head);
1122         add_v3_v3(ebone->head, diff);
1123         add_v3_v3(ebone->tail, diff);
1124 }
1125
1126 /* helper to recursively find chains of connected bones starting at ebone and fix their position */
1127 static void fix_editbone_connected_children(ListBase *edbo, EditBone *ebone)
1128 {
1129         EditBone *selbone;
1130         
1131         for (selbone = edbo->first; selbone; selbone = selbone->next) {
1132                 if ((selbone->parent) && (selbone->parent == ebone) && (selbone->flag & BONE_CONNECTED)) {
1133                         fix_connected_bone(selbone);
1134                         fix_editbone_connected_children(edbo, selbone);
1135                 }
1136         }
1137 }                       
1138
1139 static void bone_align_to_bone(ListBase *edbo, EditBone *selbone, EditBone *actbone)
1140 {
1141         float selboneaxis[3], actboneaxis[3], length;
1142
1143         sub_v3_v3v3(actboneaxis, actbone->tail, actbone->head);
1144         normalize_v3(actboneaxis);
1145
1146         sub_v3_v3v3(selboneaxis, selbone->tail, selbone->head);
1147         length =  len_v3(selboneaxis);
1148
1149         mul_v3_fl(actboneaxis, length);
1150         add_v3_v3v3(selbone->tail, selbone->head, actboneaxis);
1151         selbone->roll = actbone->roll;
1152         
1153         /* if the bone being aligned has connected descendants they must be moved
1154          * according to their parent new position, otherwise they would be left
1155          * in an inconsistent state: connected but away from the parent*/
1156         fix_editbone_connected_children(edbo, selbone);
1157 }
1158
1159 static int armature_align_bones_exec(bContext *C, wmOperator *op) 
1160 {
1161         Object *ob = CTX_data_edit_object(C);
1162         bArmature *arm = (bArmature *)ob->data;
1163         EditBone *actbone = CTX_data_active_bone(C);
1164         EditBone *actmirb = NULL;
1165         int num_selected_bones;
1166         
1167         /* there must be an active bone */
1168         if (actbone == NULL) {
1169                 BKE_report(op->reports, RPT_ERROR, "Operation requires an active bone");
1170                 return OPERATOR_CANCELLED;
1171         }
1172         else if (arm->flag & ARM_MIRROR_EDIT) {
1173                 /* For X-Axis Mirror Editing option, we may need a mirror copy of actbone
1174                  * - if there's a mirrored copy of selbone, try to find a mirrored copy of actbone 
1175                  *   (i.e.  selbone="child.L" and actbone="parent.L", find "child.R" and "parent.R").
1176                  *   This is useful for arm-chains, for example parenting lower arm to upper arm
1177                  * - if there's no mirrored copy of actbone (i.e. actbone = "parent.C" or "parent")
1178                  *   then just use actbone. Useful when doing upper arm to spine.
1179                  */
1180                 actmirb = ED_armature_bone_get_mirrored(arm->edbo, actbone);
1181                 if (actmirb == NULL) 
1182                         actmirb = actbone;
1183         }
1184         
1185         /* if there is only 1 selected bone, we assume that that is the active bone, 
1186          * since a user will need to have clicked on a bone (thus selecting it) to make it active
1187          */
1188         num_selected_bones = CTX_DATA_COUNT(C, selected_editable_bones);
1189         if (num_selected_bones <= 1) {
1190                 /* When only the active bone is selected, and it has a parent,
1191                  * align it to the parent, as that is the only possible outcome. 
1192                  */
1193                 if (actbone->parent) {
1194                         bone_align_to_bone(arm->edbo, actbone, actbone->parent);
1195                         
1196                         if ((arm->flag & ARM_MIRROR_EDIT) && (actmirb->parent))
1197                                 bone_align_to_bone(arm->edbo, actmirb, actmirb->parent);
1198
1199                         BKE_reportf(op->reports, RPT_INFO, "Aligned bone '%s' to parent", actbone->name);
1200                 }
1201         }
1202         else {
1203                 /* Align 'selected' bones to the active one
1204                  * - the context iterator contains both selected bones and their mirrored copies,
1205                  *   so we assume that unselected bones are mirrored copies of some selected bone
1206                  * - since the active one (and/or its mirror) will also be selected, we also need 
1207                  *   to check that we are not trying to operate on them, since such an operation
1208                  *   would cause errors
1209                  */
1210                 
1211                 /* align selected bones to the active one */
1212                 CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
1213                 {
1214                         if (ELEM(ebone, actbone, actmirb) == 0) {
1215                                 if (ebone->flag & BONE_SELECTED)
1216                                         bone_align_to_bone(arm->edbo, ebone, actbone);
1217                                 else
1218                                         bone_align_to_bone(arm->edbo, ebone, actmirb);
1219                         }
1220                 }
1221                 CTX_DATA_END;
1222
1223                 BKE_reportf(op->reports, RPT_INFO, "%d bones aligned to bone '%s'", num_selected_bones, actbone->name);
1224         }
1225
1226         /* note, notifier might evolve */
1227         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
1228         
1229         return OPERATOR_FINISHED;
1230 }
1231
1232 void ARMATURE_OT_align(wmOperatorType *ot)
1233 {
1234         /* identifiers */
1235         ot->name = "Align Bones";
1236         ot->idname = "ARMATURE_OT_align";
1237         ot->description = "Align selected bones to the active bone (or to their parent)";
1238         
1239         /* api callbacks */
1240         ot->exec = armature_align_bones_exec;
1241         ot->poll = ED_operator_editarmature;
1242         
1243         /* flags */
1244         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1245 }
1246
1247 /* ********************************* Split ******************************* */
1248
1249 static int armature_split_exec(bContext *C, wmOperator *UNUSED(op))
1250 {
1251         Object *ob = CTX_data_edit_object(C);
1252         bArmature *arm = (bArmature *)ob->data;
1253         EditBone *bone;
1254
1255         for (bone = arm->edbo->first; bone; bone = bone->next) {
1256                 if (bone->parent && (bone->flag & BONE_SELECTED) != (bone->parent->flag & BONE_SELECTED)) {
1257                         bone->parent = NULL;
1258                         bone->flag &= ~BONE_CONNECTED;
1259                 }
1260         }
1261         for (bone = arm->edbo->first; bone; bone = bone->next) {
1262                 ED_armature_ebone_select_set(bone, (bone->flag & BONE_SELECTED) != 0);
1263         }
1264
1265         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
1266
1267         return OPERATOR_FINISHED;
1268 }
1269
1270 void ARMATURE_OT_split(wmOperatorType *ot)
1271 {
1272         /* identifiers */
1273         ot->name = "Split";
1274         ot->idname = "ARMATURE_OT_split";
1275         ot->description = "Split off selected bones from connected unselected bones";
1276
1277         /* api callbacks */
1278         ot->exec = armature_split_exec;
1279         ot->poll = ED_operator_editarmature;
1280
1281         /* flags */
1282         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1283 }
1284
1285 /* ********************************* Delete ******************************* */
1286
1287 static bool armature_delete_ebone_cb(const char *bone_name, void *arm_p)
1288 {
1289         bArmature *arm = arm_p;
1290         EditBone *ebone;
1291
1292         ebone = ED_armature_bone_find_name(arm->edbo, bone_name);
1293         return (ebone && (ebone->flag & BONE_SELECTED) && (arm->layer & ebone->layer));
1294 }
1295
1296 /* previously delete_armature */
1297 /* only editmode! */
1298 static int armature_delete_selected_exec(bContext *C, wmOperator *UNUSED(op))
1299 {
1300         bArmature *arm;
1301         EditBone *curBone, *ebone_next;
1302         Object *obedit = CTX_data_edit_object(C); // XXX get from context
1303         bool changed = false;
1304         arm = obedit->data;
1305
1306         /* cancel if nothing selected */
1307         if (CTX_DATA_COUNT(C, selected_bones) == 0)
1308                 return OPERATOR_CANCELLED;
1309         
1310         armature_select_mirrored(arm);
1311         
1312         BKE_pose_channels_remove(obedit, armature_delete_ebone_cb, arm);
1313
1314         for (curBone = arm->edbo->first; curBone; curBone = ebone_next) {
1315                 ebone_next = curBone->next;
1316                 if (arm->layer & curBone->layer) {
1317                         if (curBone->flag & BONE_SELECTED) {
1318                                 if (curBone == arm->act_edbone) arm->act_edbone = NULL;
1319                                 ED_armature_edit_bone_remove(arm, curBone);
1320                                 changed = true;
1321                         }
1322                 }
1323         }
1324         
1325         if (!changed)
1326                 return OPERATOR_CANCELLED;
1327         
1328         ED_armature_sync_selection(arm->edbo);
1329
1330         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
1331
1332         return OPERATOR_FINISHED;
1333 }
1334
1335 void ARMATURE_OT_delete(wmOperatorType *ot)
1336 {
1337         /* identifiers */
1338         ot->name = "Delete Selected Bone(s)";
1339         ot->idname = "ARMATURE_OT_delete";
1340         ot->description = "Remove selected bones from the armature";
1341         
1342         /* api callbacks */
1343         ot->invoke = WM_operator_confirm;
1344         ot->exec = armature_delete_selected_exec;
1345         ot->poll = ED_operator_editarmature;
1346         
1347         /* flags */
1348         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1349 }
1350
1351 static bool armature_dissolve_ebone_cb(const char *bone_name, void *arm_p)
1352 {
1353         bArmature *arm = arm_p;
1354         EditBone *ebone;
1355
1356         ebone = ED_armature_bone_find_name(arm->edbo, bone_name);
1357         return (ebone && (ebone->flag & BONE_DONE));
1358 }
1359
1360 static int armature_dissolve_selected_exec(bContext *C, wmOperator *UNUSED(op))
1361 {
1362         bArmature *arm;
1363         EditBone *ebone, *ebone_next;
1364         Object *obedit = CTX_data_edit_object(C);
1365         bool changed = false;
1366
1367         /* store for mirror */
1368         GHash *ebone_flag_orig = NULL;
1369         int ebone_num = 0;
1370
1371         arm = obedit->data;
1372
1373         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1374                 ebone->temp.p = NULL;
1375                 ebone->flag &= ~BONE_DONE;
1376                 ebone_num++;
1377         }
1378
1379         if (arm->flag & ARM_MIRROR_EDIT) {
1380                 GHashIterator gh_iter;
1381
1382                 ebone_flag_orig = BLI_ghash_ptr_new_ex(__func__, ebone_num);
1383                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1384                         union { int flag; void *p; } val = {0};
1385                         val.flag = ebone->flag;
1386                         BLI_ghash_insert(ebone_flag_orig, ebone, val.p);
1387                 }
1388
1389                 armature_select_mirrored_ex(arm, BONE_SELECTED | BONE_ROOTSEL | BONE_TIPSEL);
1390
1391                 GHASH_ITER (gh_iter, ebone_flag_orig) {
1392                         union { int flag; void *p; } *val_p = (void *)BLI_ghashIterator_getValue_p(&gh_iter);
1393                         ebone = BLI_ghashIterator_getKey(&gh_iter);
1394                         val_p->flag = ebone->flag & ~val_p->flag;
1395                 }
1396         }
1397
1398         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1399                 if (ebone->parent && ebone->flag & BONE_CONNECTED) {
1400                         if (ebone->parent->temp.ebone == ebone->parent) {
1401                                 /* ignore */
1402                         }
1403                         else if (ebone->parent->temp.ebone) {
1404                                 /* set ignored */
1405                                 ebone->parent->temp.ebone = ebone->parent;
1406                         }
1407                         else {
1408                                 /* set child */
1409                                 ebone->parent->temp.ebone = ebone;
1410                         }
1411                 }
1412         }
1413
1414         /* cleanup multiple used bones */
1415         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1416                 if (ebone->temp.ebone == ebone) {
1417                         ebone->temp.ebone = NULL;
1418                 }
1419         }
1420
1421         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1422                 /* break connections for unseen bones */
1423                 if (((arm->layer & ebone->layer) &&
1424                      ((ED_armature_ebone_selectflag_get(ebone) & (BONE_TIPSEL | BONE_SELECTED)))) == 0)
1425                 {
1426                         ebone->temp.ebone = NULL;
1427                 }
1428
1429                 if (((arm->layer & ebone->layer) &&
1430                     ((ED_armature_ebone_selectflag_get(ebone) & (BONE_ROOTSEL | BONE_SELECTED)))) == 0)
1431                 {
1432                         if (ebone->parent && (ebone->flag & BONE_CONNECTED)) {
1433                                 ebone->parent->temp.ebone = NULL;
1434                         }
1435
1436                 }
1437         }
1438
1439         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1440
1441                 if (ebone->parent &&
1442                     (ebone->parent->temp.ebone == ebone))
1443                 {
1444                         ebone->flag |= BONE_DONE;
1445                 }
1446         }
1447
1448         BKE_pose_channels_remove(obedit, armature_dissolve_ebone_cb, arm);
1449
1450         for (ebone = arm->edbo->first; ebone; ebone = ebone_next) {
1451                 ebone_next = ebone->next;
1452
1453                 if (ebone->flag & BONE_DONE) {
1454                         copy_v3_v3(ebone->parent->tail, ebone->tail);
1455                         ebone->parent->rad_tail = ebone->rad_tail;
1456
1457                         ED_armature_edit_bone_remove(arm, ebone);
1458                         changed = true;
1459                 }
1460         }
1461
1462         if (changed) {
1463                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1464                         if (ebone->parent &&
1465                             ebone->parent->temp.ebone &&
1466                             (ebone->flag & BONE_CONNECTED) == 0)
1467                         {
1468                                 ebone->flag |= BONE_CONNECTED;
1469                                 ebone->rad_head = ebone->parent->rad_head;
1470                         }
1471                 }
1472
1473                 if (arm->flag & ARM_MIRROR_EDIT) {
1474                         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1475                                 union { int flag; void *p; } *val_p = (void *)BLI_ghash_lookup_p(ebone_flag_orig, ebone);
1476                                 if (val_p && val_p->flag) {
1477                                         ebone->flag &= ~val_p->flag;
1478                                 }
1479                         }
1480                 }
1481         }
1482
1483         if (arm->flag & ARM_MIRROR_EDIT) {
1484                 BLI_ghash_free(ebone_flag_orig, NULL, NULL);
1485         }
1486
1487         if (!changed) {
1488                 return OPERATOR_CANCELLED;
1489         }
1490
1491         ED_armature_sync_selection(arm->edbo);
1492
1493         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
1494
1495         return OPERATOR_FINISHED;
1496 }
1497
1498 void ARMATURE_OT_dissolve(wmOperatorType *ot)
1499 {
1500         /* identifiers */
1501         ot->name = "Dissolve Selected Bone(s)";
1502         ot->idname = "ARMATURE_OT_dissolve";
1503         ot->description = "Dissolve selected bones from the armature";
1504
1505         /* api callbacks */
1506         ot->exec = armature_dissolve_selected_exec;
1507         ot->poll = ED_operator_editarmature;
1508
1509         /* flags */
1510         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1511 }
1512
1513
1514
1515 /* ********************************* Show/Hide ******************************* */
1516
1517 static int armature_hide_exec(bContext *C, wmOperator *op)
1518 {
1519         Object *obedit = CTX_data_edit_object(C);
1520         bArmature *arm = obedit->data;
1521         EditBone *ebone;
1522         const int invert = RNA_boolean_get(op->ptr, "unselected") ? BONE_SELECTED : 0;
1523
1524         /* cancel if nothing selected */
1525         if (CTX_DATA_COUNT(C, selected_bones) == 0)
1526                 return OPERATOR_CANCELLED;
1527
1528         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1529                 if (EBONE_VISIBLE(arm, ebone)) {
1530                         if ((ebone->flag & BONE_SELECTED) != invert) {
1531                                 ebone->flag &= ~(BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL);
1532                                 ebone->flag |= BONE_HIDDEN_A;
1533                         }
1534                 }
1535         }
1536         ED_armature_validate_active(arm);
1537         ED_armature_sync_selection(arm->edbo);
1538
1539         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
1540
1541         return OPERATOR_FINISHED;
1542 }
1543
1544 void ARMATURE_OT_hide(wmOperatorType *ot)
1545 {
1546         /* identifiers */
1547         ot->name = "Hide Selected Bones";
1548         ot->idname = "ARMATURE_OT_hide";
1549         ot->description = "Tag selected bones to not be visible in Edit Mode";
1550         
1551         /* api callbacks */
1552         ot->exec = armature_hide_exec;
1553         ot->poll = ED_operator_editarmature;
1554         
1555         /* flags */
1556         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1557
1558         /* props */
1559         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
1560 }
1561
1562 static int armature_reveal_exec(bContext *C, wmOperator *UNUSED(op))
1563 {
1564         Object *obedit = CTX_data_edit_object(C);
1565         bArmature *arm = obedit->data;
1566         EditBone *ebone;
1567         
1568         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
1569                 if (arm->layer & ebone->layer) {
1570                         if (ebone->flag & BONE_HIDDEN_A) {
1571                                 if (!(ebone->flag & BONE_UNSELECTABLE)) {
1572                                         ebone->flag |= (BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL);
1573                                 }
1574                                 ebone->flag &= ~BONE_HIDDEN_A;
1575                         }
1576                 }
1577         }
1578         ED_armature_validate_active(arm);
1579         ED_armature_sync_selection(arm->edbo);
1580
1581         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
1582
1583         return OPERATOR_FINISHED;
1584 }
1585
1586 void ARMATURE_OT_reveal(wmOperatorType *ot)
1587 {
1588         /* identifiers */
1589         ot->name = "Reveal Bones";
1590         ot->idname = "ARMATURE_OT_reveal";
1591         ot->description = "Unhide all bones that have been tagged to be hidden in Edit Mode";
1592         
1593         /* api callbacks */
1594         ot->exec = armature_reveal_exec;
1595         ot->poll = ED_operator_editarmature;
1596         
1597         /* flags */
1598         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1599
1600 }