Fix T59673: wrong B-Bone handle references when duplicating bones.
[blender.git] / source / blender / editors / armature / armature_add.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  * Operators and API's for creating bones
26  */
27
28 /** \file blender/editors/armature/armature_add.c
29  *  \ingroup edarmature
30  */
31
32 #include "DNA_armature_types.h"
33 #include "DNA_constraint_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_scene_types.h"
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_ghash.h"
42 #include "BLI_string_utils.h"
43
44 #include "BKE_action.h"
45 #include "BKE_constraint.h"
46 #include "BKE_context.h"
47 #include "BKE_idprop.h"
48 #include "BKE_deform.h"
49 #include "BKE_layer.h"
50
51 #include "RNA_access.h"
52 #include "RNA_define.h"
53
54 #include "WM_api.h"
55 #include "WM_types.h"
56
57 #include "ED_armature.h"
58 #include "ED_screen.h"
59 #include "ED_view3d.h"
60
61 #include "armature_intern.h"
62
63 /* *************** Adding stuff in editmode *************** */
64
65 /* default bone add, returns it selected, but without tail set */
66 /* XXX should be used everywhere, now it mallocs bones still locally in functions */
67 EditBone *ED_armature_ebone_add(bArmature *arm, const char *name)
68 {
69         EditBone *bone = MEM_callocN(sizeof(EditBone), "eBone");
70
71         BLI_strncpy(bone->name, name, sizeof(bone->name));
72         ED_armature_ebone_unique_name(arm->edbo, bone->name, NULL);
73
74         BLI_addtail(arm->edbo, bone);
75
76         bone->flag |= BONE_TIPSEL;
77         bone->weight = 1.0f;
78         bone->dist = 0.25f;
79         bone->xwidth = 0.1f;
80         bone->zwidth = 0.1f;
81         bone->rad_head = 0.10f;
82         bone->rad_tail = 0.05f;
83         bone->segments = 1;
84         bone->layer = arm->layer;
85
86         /* Bendy-Bone parameters */
87         bone->roll1 = 0.0f;
88         bone->roll2 = 0.0f;
89         bone->curveInX = 0.0f;
90         bone->curveInY = 0.0f;
91         bone->curveOutX = 0.0f;
92         bone->curveOutY = 0.0f;
93         bone->ease1 = 1.0f;
94         bone->ease2 = 1.0f;
95         bone->scaleIn = 1.0f;
96         bone->scaleOut = 1.0f;
97
98         return bone;
99 }
100
101 EditBone *ED_armature_ebone_add_primitive(Object *obedit_arm, float length, bool view_aligned)
102 {
103         bArmature *arm = obedit_arm->data;
104         EditBone *bone;
105
106         ED_armature_edit_deselect_all(obedit_arm);
107
108         /* Create a bone */
109         bone = ED_armature_ebone_add(arm, "Bone");
110
111         arm->act_edbone = bone;
112
113         zero_v3(bone->head);
114         zero_v3(bone->tail);
115
116         bone->tail[view_aligned ? 1 : 2] = length;
117
118         return bone;
119 }
120
121
122 /* previously addvert_armature */
123 /* the ctrl-click method */
124
125 /** Note this is already ported to multi-objects as it is.
126  * Since only the active bone is extruded even for single objects,
127  * it makes sense to stick to the active object here.
128  *
129  * If we want the support to be expanded we should something like the
130  * offset we do for mesh click extrude.
131  */
132 static int armature_click_extrude_exec(bContext *C, wmOperator *UNUSED(op))
133 {
134         bArmature *arm;
135         EditBone *ebone, *newbone, *flipbone;
136         float mat[3][3], imat[3][3];
137         int a, to_root = 0;
138         Object *obedit;
139         Scene *scene;
140
141         scene = CTX_data_scene(C);
142         obedit = CTX_data_edit_object(C);
143         arm = obedit->data;
144
145         /* find the active or selected bone */
146         for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
147                 if (EBONE_VISIBLE(arm, ebone)) {
148                         if (ebone->flag & BONE_TIPSEL || arm->act_edbone == ebone)
149                                 break;
150                 }
151         }
152
153         if (ebone == NULL) {
154                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
155                         if (EBONE_VISIBLE(arm, ebone)) {
156                                 if (ebone->flag & BONE_ROOTSEL || arm->act_edbone == ebone)
157                                         break;
158                         }
159                 }
160                 if (ebone == NULL)
161                         return OPERATOR_CANCELLED;
162
163                 to_root = 1;
164         }
165
166         ED_armature_edit_deselect_all(obedit);
167
168         /* we re-use code for mirror editing... */
169         flipbone = NULL;
170         if (arm->flag & ARM_MIRROR_EDIT)
171                 flipbone = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
172
173         for (a = 0; a < 2; a++) {
174                 if (a == 1) {
175                         if (flipbone == NULL)
176                                 break;
177                         else {
178                                 SWAP(EditBone *, flipbone, ebone);
179                         }
180                 }
181
182                 newbone = ED_armature_ebone_add(arm, ebone->name);
183                 arm->act_edbone = newbone;
184
185                 if (to_root) {
186                         copy_v3_v3(newbone->head, ebone->head);
187                         newbone->rad_head = ebone->rad_tail;
188                         newbone->parent = ebone->parent;
189                 }
190                 else {
191                         copy_v3_v3(newbone->head, ebone->tail);
192                         newbone->rad_head = ebone->rad_tail;
193                         newbone->parent = ebone;
194                         newbone->flag |= BONE_CONNECTED;
195                 }
196
197                 const View3DCursor *curs = &scene->cursor;
198                 copy_v3_v3(newbone->tail, curs->location);
199                 sub_v3_v3v3(newbone->tail, newbone->tail, obedit->obmat[3]);
200
201                 if (a == 1)
202                         newbone->tail[0] = -newbone->tail[0];
203
204                 copy_m3_m4(mat, obedit->obmat);
205                 invert_m3_m3(imat, mat);
206                 mul_m3_v3(imat, newbone->tail);
207
208                 newbone->length = len_v3v3(newbone->head, newbone->tail);
209                 newbone->rad_tail = newbone->length * 0.05f;
210                 newbone->dist = newbone->length * 0.25f;
211
212         }
213
214         ED_armature_edit_sync_selection(arm->edbo);
215
216         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
217
218         return OPERATOR_FINISHED;
219 }
220
221 static int armature_click_extrude_invoke(bContext *C, wmOperator *op, const wmEvent *event)
222 {
223         /* TODO most of this code is copied from set3dcursor_invoke,
224          * it would be better to reuse code in set3dcursor_invoke */
225
226         /* temporarily change 3d cursor position */
227         Scene *scene;
228         ARegion *ar;
229         View3D *v3d;
230         float tvec[3], oldcurs[3], mval_f[2];
231         int retv;
232
233         scene = CTX_data_scene(C);
234         ar = CTX_wm_region(C);
235         v3d = CTX_wm_view3d(C);
236
237         View3DCursor *cursor = &scene->cursor;
238
239         copy_v3_v3(oldcurs, cursor->location);
240
241         VECCOPY2D(mval_f, event->mval);
242         ED_view3d_win_to_3d(v3d, ar, cursor->location, mval_f, tvec);
243         copy_v3_v3(cursor->location, tvec);
244
245         /* extrude to the where new cursor is and store the operation result */
246         retv = armature_click_extrude_exec(C, op);
247
248         /* restore previous 3d cursor position */
249         copy_v3_v3(cursor->location, oldcurs);
250
251         return retv;
252 }
253
254 void ARMATURE_OT_click_extrude(wmOperatorType *ot)
255 {
256         /* identifiers */
257         ot->name = "Click-Extrude";
258         ot->idname = "ARMATURE_OT_click_extrude";
259         ot->description = "Create a new bone going from the last selected joint to the mouse position";
260
261         /* api callbacks */
262         ot->invoke = armature_click_extrude_invoke;
263         ot->exec = armature_click_extrude_exec;
264         ot->poll = ED_operator_editarmature;
265
266         /* flags */
267         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
268
269         /* props */
270 }
271
272 /* adds an EditBone between the nominated locations (should be in the right space) */
273 EditBone *add_points_bone(Object *obedit, float head[3], float tail[3])
274 {
275         EditBone *ebo;
276
277         ebo = ED_armature_ebone_add(obedit->data, "Bone");
278
279         copy_v3_v3(ebo->head, head);
280         copy_v3_v3(ebo->tail, tail);
281
282         return ebo;
283 }
284
285
286 static EditBone *get_named_editbone(ListBase *edbo, const char *name)
287 {
288         EditBone  *eBone;
289
290         if (name) {
291                 for (eBone = edbo->first; eBone; eBone = eBone->next) {
292                         if (STREQ(name, eBone->name))
293                                 return eBone;
294                 }
295         }
296
297         return NULL;
298 }
299
300 /* Call this before doing any duplications
301  * */
302 void preEditBoneDuplicate(ListBase *editbones)
303 {
304         /* clear temp */
305         ED_armature_ebone_listbase_temp_clear(editbones);
306 }
307
308 /**
309  * Helper function for #postEditBoneDuplicate,
310  * return the destination pchan from the original.
311  */
312 static bPoseChannel *pchan_duplicate_map(const bPose *pose, GHash *name_map, bPoseChannel *pchan_src)
313 {
314         bPoseChannel *pchan_dst = NULL;
315         const char *name_src = pchan_src->name;
316         const char *name_dst = BLI_ghash_lookup(name_map, name_src);
317         if (name_dst) {
318                 pchan_dst = BKE_pose_channel_find_name(pose, name_dst);
319         }
320
321         if (pchan_dst == NULL) {
322                 pchan_dst = pchan_src;
323         }
324
325         return pchan_dst;
326 }
327
328 void postEditBoneDuplicate(struct ListBase *editbones, Object *ob)
329 {
330         if (ob->pose == NULL) {
331                 return;
332         }
333
334         BKE_pose_channels_hash_free(ob->pose);
335         BKE_pose_channels_hash_make(ob->pose);
336
337         GHash *name_map = BLI_ghash_str_new(__func__);
338
339         for (EditBone *ebone_src = editbones->first; ebone_src; ebone_src = ebone_src->next) {
340                 EditBone *ebone_dst = ebone_src->temp.ebone;
341                 if (!ebone_dst) {
342                         ebone_dst = ED_armature_ebone_get_mirrored(editbones, ebone_src);
343                 }
344                 if (ebone_dst) {
345                         BLI_ghash_insert(name_map, ebone_src->name, ebone_dst->name);
346                 }
347         }
348
349         for (EditBone *ebone_src = editbones->first; ebone_src; ebone_src = ebone_src->next) {
350                 EditBone *ebone_dst = ebone_src->temp.ebone;
351                 if (ebone_dst) {
352                         bPoseChannel *pchan_src = BKE_pose_channel_find_name(ob->pose, ebone_src->name);
353                         if (pchan_src) {
354                                 bPoseChannel *pchan_dst = BKE_pose_channel_find_name(ob->pose, ebone_dst->name);
355                                 if (pchan_dst) {
356                                         if (pchan_src->custom_tx) {
357                                                 pchan_dst->custom_tx = pchan_duplicate_map(ob->pose, name_map, pchan_src->custom_tx);
358                                         }
359                                         if (pchan_src->bbone_prev) {
360                                                 pchan_dst->bbone_prev = pchan_duplicate_map(ob->pose, name_map, pchan_src->bbone_prev);
361                                         }
362                                         if (pchan_src->bbone_next) {
363                                                 pchan_dst->bbone_next = pchan_duplicate_map(ob->pose, name_map, pchan_src->bbone_next);
364                                         }
365                                 }
366                         }
367                 }
368         }
369
370         BLI_ghash_free(name_map, NULL, NULL);
371 }
372
373 /*
374  * Note: When duplicating cross objects, editbones here is the list of bones
375  * from the SOURCE object but ob is the DESTINATION object
376  * */
377 void updateDuplicateSubtargetObjects(EditBone *dupBone, ListBase *editbones, Object *src_ob, Object *dst_ob)
378 {
379         /* If an edit bone has been duplicated, lets
380          * update it's constraints if the subtarget
381          * they point to has also been duplicated
382          */
383         EditBone     *oldtarget, *newtarget;
384         bPoseChannel *pchan;
385         bConstraint  *curcon;
386         ListBase     *conlist;
387
388         if ((pchan = BKE_pose_channel_verify(dst_ob->pose, dupBone->name))) {
389                 if ((conlist = &pchan->constraints)) {
390                         for (curcon = conlist->first; curcon; curcon = curcon->next) {
391                                 /* does this constraint have a subtarget in
392                                  * this armature?
393                                  */
394                                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(curcon);
395                                 ListBase targets = {NULL, NULL};
396                                 bConstraintTarget *ct;
397
398                                 if (cti && cti->get_constraint_targets) {
399                                         cti->get_constraint_targets(curcon, &targets);
400
401                                         for (ct = targets.first; ct; ct = ct->next) {
402                                                 if ((ct->tar == src_ob) && (ct->subtarget[0])) {
403                                                         ct->tar = dst_ob; /* update target */
404                                                         oldtarget = get_named_editbone(editbones, ct->subtarget);
405                                                         if (oldtarget) {
406                                                                 /* was the subtarget bone duplicated too? If
407                                                                  * so, update the constraint to point at the
408                                                                  * duplicate of the old subtarget.
409                                                                  */
410                                                                 if (oldtarget->temp.ebone) {
411                                                                         newtarget = oldtarget->temp.ebone;
412                                                                         BLI_strncpy(ct->subtarget, newtarget->name, sizeof(ct->subtarget));
413                                                                 }
414                                                         }
415                                                 }
416                                         }
417
418                                         if (cti->flush_constraint_targets)
419                                                 cti->flush_constraint_targets(curcon, &targets, 0);
420                                 }
421                         }
422                 }
423         }
424 }
425
426 void updateDuplicateSubtarget(EditBone *dupBone, ListBase *editbones, Object *ob)
427 {
428         updateDuplicateSubtargetObjects(dupBone, editbones, ob, ob);
429 }
430
431
432 EditBone *duplicateEditBoneObjects(EditBone *curBone, const char *name, ListBase *editbones,
433                                    Object *src_ob, Object *dst_ob)
434 {
435         EditBone *eBone = MEM_mallocN(sizeof(EditBone), "addup_editbone");
436
437         /* Copy data from old bone to new bone */
438         memcpy(eBone, curBone, sizeof(EditBone));
439
440         curBone->temp.ebone = eBone;
441         eBone->temp.ebone = curBone;
442
443         if (name != NULL) {
444                 BLI_strncpy(eBone->name, name, sizeof(eBone->name));
445         }
446
447         ED_armature_ebone_unique_name(editbones, eBone->name, NULL);
448         BLI_addtail(editbones, eBone);
449
450         /* copy the ID property */
451         if (curBone->prop)
452                 eBone->prop = IDP_CopyProperty(curBone->prop);
453
454         /* Lets duplicate the list of constraints that the
455          * current bone has.
456          */
457         if (src_ob->pose) {
458                 bPoseChannel *chanold, *channew;
459
460                 chanold = BKE_pose_channel_verify(src_ob->pose, curBone->name);
461                 if (chanold) {
462                         /* WARNING: this creates a new posechannel, but there will not be an attached bone
463                          * yet as the new bones created here are still 'EditBones' not 'Bones'.
464                          */
465                         channew = BKE_pose_channel_verify(dst_ob->pose, eBone->name);
466
467                         if (channew) {
468                                 BKE_pose_channel_copy_data(channew, chanold);
469                         }
470                 }
471         }
472
473         return eBone;
474 }
475
476 EditBone *duplicateEditBone(EditBone *curBone, const char *name, ListBase *editbones, Object *ob)
477 {
478         return duplicateEditBoneObjects(curBone, name, editbones, ob, ob);
479 }
480
481 static int armature_duplicate_selected_exec(bContext *C, wmOperator *op)
482 {
483         ViewLayer *view_layer = CTX_data_view_layer(C);
484         const bool do_flip_names = RNA_boolean_get(op->ptr, "do_flip_names");
485
486         /* cancel if nothing selected */
487         if (CTX_DATA_COUNT(C, selected_bones) == 0)
488                 return OPERATOR_CANCELLED;
489
490         uint objects_len = 0;
491         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
492         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
493                 EditBone *ebone_iter;
494                 EditBone *ebone_first_dupe = NULL;  /* The beginning of the duplicated bones in the edbo list */
495                 Object *ob = objects[ob_index];
496                 bArmature *arm = ob->data;
497
498                 ED_armature_edit_sync_selection(arm->edbo); // XXX why is this needed?
499
500                 preEditBoneDuplicate(arm->edbo);
501
502                 /* Select mirrored bones */
503                 if (arm->flag & ARM_MIRROR_EDIT) {
504                         for (ebone_iter = arm->edbo->first; ebone_iter; ebone_iter = ebone_iter->next) {
505                                 if (EBONE_VISIBLE(arm, ebone_iter) &&
506                                     (ebone_iter->flag & BONE_SELECTED))
507                                 {
508                                         EditBone *ebone;
509
510                                         ebone = ED_armature_ebone_get_mirrored(arm->edbo, ebone_iter);
511                                         if (ebone) {
512                                                 ebone->flag |= BONE_SELECTED;
513                                         }
514                                 }
515                         }
516                 }
517
518                 /* Find the selected bones and duplicate them as needed */
519                 for (ebone_iter = arm->edbo->first; ebone_iter && ebone_iter != ebone_first_dupe; ebone_iter = ebone_iter->next) {
520                         if (EBONE_VISIBLE(arm, ebone_iter) &&
521                             (ebone_iter->flag & BONE_SELECTED))
522                         {
523                                 EditBone *ebone;
524                                 char new_bone_name_buff[MAXBONENAME];
525                                 char *new_bone_name = ebone_iter->name;
526
527                                 if (do_flip_names) {
528                                         BLI_string_flip_side_name(new_bone_name_buff, ebone_iter->name, false, sizeof(new_bone_name_buff));
529
530                                         /* Only use flipped name if not yet in use. Otherwise we'd get again inconsistent namings
531                                          * (different numbers), better keep default behavior in this case. */
532                                         if (ED_armature_ebone_find_name(arm->edbo, new_bone_name_buff) == NULL) {
533                                                 new_bone_name = new_bone_name_buff;
534                                         }
535                                 }
536
537                                 ebone = duplicateEditBone(ebone_iter, new_bone_name, arm->edbo, ob);
538
539                                 if (!ebone_first_dupe) {
540                                         ebone_first_dupe = ebone;
541                                 }
542                         }
543                 }
544
545                 /* Run though the list and fix the pointers */
546                 for (ebone_iter = arm->edbo->first; ebone_iter && ebone_iter != ebone_first_dupe; ebone_iter = ebone_iter->next) {
547                         if (EBONE_VISIBLE(arm, ebone_iter) &&
548                             (ebone_iter->flag & BONE_SELECTED))
549                         {
550                                 EditBone *ebone = ebone_iter->temp.ebone;
551
552                                 if (!ebone_iter->parent) {
553                                         /* If this bone has no parent,
554                                          * Set the duplicate->parent to NULL
555                                          */
556                                         ebone->parent = NULL;
557                                 }
558                                 else if (ebone_iter->parent->temp.ebone) {
559                                         /* If this bone has a parent that was duplicated,
560                                          * Set the duplicate->parent to the curBone->parent->temp
561                                          */
562                                         ebone->parent = ebone_iter->parent->temp.ebone;
563                                 }
564                                 else {
565                                         /* If this bone has a parent that IS not selected,
566                                          * Set the duplicate->parent to the curBone->parent
567                                          */
568                                         ebone->parent = (EditBone *) ebone_iter->parent;
569                                         ebone->flag &= ~BONE_CONNECTED;
570                                 }
571
572                                 /* Update custom handle links. */
573                                 if (ebone_iter->bbone_prev && ebone_iter->bbone_prev->temp.ebone) {
574                                         ebone->bbone_prev = ebone_iter->bbone_prev->temp.ebone;
575                                 }
576                                 if (ebone_iter->bbone_next && ebone_iter->bbone_next->temp.ebone) {
577                                         ebone->bbone_next = ebone_iter->bbone_next->temp.ebone;
578                                 }
579
580                                 /* Lets try to fix any constraint subtargets that might
581                                  * have been duplicated
582                                  */
583                                 updateDuplicateSubtarget(ebone, arm->edbo, ob);
584                         }
585                 }
586
587                 /* correct the active bone */
588                 if (arm->act_edbone && arm->act_edbone->temp.ebone) {
589                         arm->act_edbone = arm->act_edbone->temp.ebone;
590                 }
591
592                 /* Deselect the old bones and select the new ones */
593                 for (ebone_iter = arm->edbo->first; ebone_iter && ebone_iter != ebone_first_dupe; ebone_iter = ebone_iter->next) {
594                         if (EBONE_VISIBLE(arm, ebone_iter)) {
595                                 ebone_iter->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
596                         }
597                 }
598
599                 postEditBoneDuplicate(arm->edbo, ob);
600
601                 ED_armature_edit_validate_active(arm);
602
603                 WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
604         }
605         MEM_freeN(objects);
606
607         return OPERATOR_FINISHED;
608 }
609
610
611 void ARMATURE_OT_duplicate(wmOperatorType *ot)
612 {
613         /* identifiers */
614         ot->name = "Duplicate Selected Bone(s)";
615         ot->idname = "ARMATURE_OT_duplicate";
616         ot->description = "Make copies of the selected bones within the same armature";
617
618         /* api callbacks */
619         ot->exec = armature_duplicate_selected_exec;
620         ot->poll = ED_operator_editarmature;
621
622         /* flags */
623         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
624
625         RNA_def_boolean(
626                 ot->srna, "do_flip_names", false,
627                 "Flip Names", "Try to flip names of the bones, if possible, instead of adding a number extension");
628 }
629
630 /* Get the duplicated or existing mirrored copy of the bone. */
631 static EditBone *get_symmetrized_bone(bArmature *arm, EditBone *bone)
632 {
633         if (bone == NULL) {
634                 return NULL;
635         }
636         else if (bone->temp.ebone != NULL) {
637                 return bone->temp.ebone;
638         }
639         else {
640                 EditBone *mirror = ED_armature_ebone_get_mirrored(arm->edbo, bone);
641                 return (mirror != NULL) ? mirror : bone;
642         }
643 }
644
645 /**
646  * near duplicate of #armature_duplicate_selected_exec,
647  * except for parenting part (keep in sync)
648  */
649 static int armature_symmetrize_exec(bContext *C, wmOperator *op)
650 {
651         ViewLayer *view_layer = CTX_data_view_layer(C);
652         const int direction = RNA_enum_get(op->ptr, "direction");
653         const int axis = 0;
654
655         /* cancel if nothing selected */
656         if (CTX_DATA_COUNT(C, selected_bones) == 0) {
657                 return OPERATOR_CANCELLED;
658         }
659
660         uint objects_len = 0;
661         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
662         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
663                 Object *obedit = objects[ob_index];
664                 bArmature *arm = obedit->data;
665
666                 EditBone *ebone_iter;
667                 EditBone *ebone_first_dupe = NULL;  /* The beginning of the duplicated mirrored bones in the edbo list */
668
669                 ED_armature_edit_sync_selection(arm->edbo); // XXX why is this needed?
670
671                 preEditBoneDuplicate(arm->edbo);
672
673                 /* Select mirrored bones */
674                 for (ebone_iter = arm->edbo->first; ebone_iter; ebone_iter = ebone_iter->next) {
675                         if (EBONE_VISIBLE(arm, ebone_iter) &&
676                             (ebone_iter->flag & BONE_SELECTED))
677                         {
678                                 char name_flip[MAXBONENAME];
679
680                                 BLI_string_flip_side_name(name_flip, ebone_iter->name, false, sizeof(name_flip));
681
682                                 if (STREQ(name_flip, ebone_iter->name)) {
683                                         /* if the name matches, we don't have the potential to be mirrored, just skip */
684                                         ebone_iter->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
685                                 }
686                                 else {
687                                         EditBone *ebone = ED_armature_ebone_find_name(arm->edbo, name_flip);
688
689                                         if (ebone) {
690                                                 if ((ebone->flag & BONE_SELECTED) == 0) {
691                                                         /* simple case, we're selected, the other bone isn't! */
692                                                         ebone_iter->temp.ebone = ebone;
693                                                 }
694                                                 else {
695                                                         /* complicated - choose which direction to copy */
696                                                         float axis_delta;
697
698                                                         axis_delta = ebone->head[axis] - ebone_iter->head[axis];
699                                                         if (axis_delta == 0.0f) {
700                                                                 axis_delta = ebone->tail[axis] - ebone_iter->tail[axis];
701                                                         }
702
703                                                         if (axis_delta == 0.0f) {
704                                                                 /* both mirrored bones exist and point to eachother and overlap exactly.
705                                                                  *
706                                                                  * in this case there's no well defined solution, so de-select both and skip.
707                                                                  */
708                                                                 ebone->flag      &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
709                                                                 ebone_iter->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
710                                                         }
711                                                         else {
712                                                                 EditBone *ebone_src, *ebone_dst;
713                                                                 if (((axis_delta < 0.0f) ? -1 : 1) == direction) {
714                                                                         ebone_src = ebone;
715                                                                         ebone_dst = ebone_iter;
716                                                                 }
717                                                                 else {
718                                                                         ebone_src = ebone_iter;
719                                                                         ebone_dst = ebone;
720                                                                 }
721
722                                                                 ebone_src->temp.ebone = ebone_dst;
723                                                                 ebone_dst->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
724                                                         }
725                                                 }
726                                         }
727                                 }
728                         }
729                 }
730
731                 /*      Find the selected bones and duplicate them as needed, with mirrored name */
732                 for (ebone_iter = arm->edbo->first; ebone_iter && ebone_iter != ebone_first_dupe; ebone_iter = ebone_iter->next) {
733                         if (EBONE_VISIBLE(arm, ebone_iter) &&
734                             (ebone_iter->flag & BONE_SELECTED) &&
735                             /* will be set if the mirror bone already exists (no need to make a new one) */
736                             (ebone_iter->temp.ebone == NULL))
737                         {
738                                 char name_flip[MAXBONENAME];
739
740                                 BLI_string_flip_side_name(name_flip, ebone_iter->name, false, sizeof(name_flip));
741
742                                 /* bones must have a side-suffix */
743                                 if (!STREQ(name_flip, ebone_iter->name)) {
744                                         EditBone *ebone;
745
746                                         ebone = duplicateEditBone(ebone_iter, name_flip, arm->edbo, obedit);
747
748                                         if (!ebone_first_dupe) {
749                                                 ebone_first_dupe = ebone;
750                                         }
751                                 }
752                         }
753                 }
754
755                 /*      Run through the list and fix the pointers */
756                 for (ebone_iter = arm->edbo->first; ebone_iter && ebone_iter != ebone_first_dupe; ebone_iter = ebone_iter->next) {
757                         if (ebone_iter->temp.ebone) {
758                                 /* copy all flags except for ... */
759                                 const int flag_copy = ((int)~0) & ~(BONE_SELECTED | BONE_ROOTSEL | BONE_TIPSEL);
760
761                                 EditBone *ebone = ebone_iter->temp.ebone;
762
763                                 /* copy flags incase bone is pre-existing data */
764                                 ebone->flag = (ebone->flag & ~flag_copy) | (ebone_iter->flag & flag_copy);
765
766                                 if (ebone_iter->parent == NULL) {
767                                         /* If this bone has no parent,
768                                          * Set the duplicate->parent to NULL
769                                          */
770                                         ebone->parent = NULL;
771                                         ebone->flag &= ~BONE_CONNECTED;
772                                 }
773                                 else {
774                                         /* the parent may have been duplicated, if not lookup the mirror parent */
775                                         EditBone *ebone_parent = get_symmetrized_bone(arm, ebone_iter->parent);
776
777                                         if (ebone_parent == ebone_iter->parent) {
778                                                 /* If the mirror lookup failed, (but the current bone has a parent)
779                                                  * then we can assume the parent has no L/R but is a center bone.
780                                                  * So just use the same parent for both.
781                                                  */
782                                                 ebone->flag &= ~BONE_CONNECTED;
783                                         }
784
785                                         ebone->parent = ebone_parent;
786                                 }
787
788                                 /* Update custom handle links. */
789                                 ebone->bbone_prev = get_symmetrized_bone(arm, ebone_iter->bbone_prev);
790                                 ebone->bbone_next = get_symmetrized_bone(arm, ebone_iter->bbone_next);
791
792                                 /* Lets try to fix any constraint subtargets that might
793                                  * have been duplicated
794                                  */
795                                 updateDuplicateSubtarget(ebone, arm->edbo, obedit);
796                         }
797                 }
798
799                 ED_armature_edit_transform_mirror_update(obedit);
800
801                 /* Selected bones now have their 'temp' pointer set,
802                  * so we don't need this anymore */
803
804                 /* Deselect the old bones and select the new ones */
805                 for (ebone_iter = arm->edbo->first;
806                      ebone_iter && ebone_iter != ebone_first_dupe;
807                      ebone_iter = ebone_iter->next)
808                 {
809                         if (EBONE_VISIBLE(arm, ebone_iter)) {
810                                 ebone_iter->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
811                         }
812                 }
813
814                 /* New bones will be selected, but some of the bones may already exist */
815                 for (ebone_iter = arm->edbo->first;
816                      ebone_iter && ebone_iter != ebone_first_dupe;
817                      ebone_iter = ebone_iter->next)
818                 {
819                         EditBone *ebone = ebone_iter->temp.ebone;
820                         if (ebone && EBONE_SELECTABLE(arm, ebone)) {
821                                 ED_armature_ebone_select_set(ebone, true);
822                         }
823                 }
824
825                 /* correct the active bone */
826                 if (arm->act_edbone && arm->act_edbone->temp.ebone) {
827                         arm->act_edbone = arm->act_edbone->temp.ebone;
828                 }
829
830                 postEditBoneDuplicate(arm->edbo, obedit);
831
832                 ED_armature_edit_validate_active(arm);
833
834                 WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
835         }
836         MEM_freeN(objects);
837
838         return OPERATOR_FINISHED;
839 }
840
841 /* following conventions from #MESH_OT_symmetrize */
842 void ARMATURE_OT_symmetrize(wmOperatorType *ot)
843 {
844         /* subset of 'rna_enum_symmetrize_direction_items' */
845         static const EnumPropertyItem arm_symmetrize_direction_items[] = {
846                 {-1, "NEGATIVE_X", 0, "-X to +X", ""},
847                 {+1, "POSITIVE_X", 0, "+X to -X", ""},
848                 {0, NULL, 0, NULL, NULL}
849         };
850
851         /* identifiers */
852         ot->name = "Symmetrize";
853         ot->idname = "ARMATURE_OT_symmetrize";
854         ot->description = "Enforce symmetry, make copies of the selection or use existing";
855
856         /* api callbacks */
857         ot->exec = armature_symmetrize_exec;
858         ot->poll = ED_operator_editarmature;
859
860         /* flags */
861         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
862
863         ot->prop = RNA_def_enum(
864                 ot->srna, "direction", arm_symmetrize_direction_items, -1,
865                 "Direction", "Which sides to copy from and to (when both are selected)");
866 }
867
868 /* ------------------------------------------ */
869
870 /* previously extrude_armature */
871 /* context; editmode armature */
872 /* if forked && mirror-edit: makes two bones with flipped names */
873 static int armature_extrude_exec(bContext *C, wmOperator *op)
874 {
875         ViewLayer *view_layer = CTX_data_view_layer(C);
876         const bool forked = RNA_boolean_get(op->ptr, "forked");
877         bool changed_multi = false;
878
879         uint objects_len = 0;
880         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
881         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
882                 Object *ob = objects[ob_index];
883                 bArmature *arm = ob->data;
884                 bool forked_iter = forked;
885
886                 EditBone *newbone = NULL, *ebone, *flipbone, *first = NULL;
887                 int a, totbone = 0, do_extrude;
888
889                 /* since we allow root extrude too, we have to make sure selection is OK */
890                 for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
891                         if (EBONE_VISIBLE(arm, ebone)) {
892                                 if (ebone->flag & BONE_ROOTSEL) {
893                                         if (ebone->parent && (ebone->flag & BONE_CONNECTED)) {
894                                                 if (ebone->parent->flag & BONE_TIPSEL)
895                                                         ebone->flag &= ~BONE_ROOTSEL;
896                                         }
897                                 }
898                         }
899                 }
900
901                 /* Duplicate the necessary bones */
902                 for (ebone = arm->edbo->first; ((ebone) && (ebone != first)); ebone = ebone->next) {
903                         if (EBONE_VISIBLE(arm, ebone)) {
904                                 /* we extrude per definition the tip */
905                                 do_extrude = false;
906                                 if (ebone->flag & (BONE_TIPSEL | BONE_SELECTED)) {
907                                         do_extrude = true;
908                                 }
909                                 else if (ebone->flag & BONE_ROOTSEL) {
910                                         /* but, a bone with parent deselected we do the root... */
911                                         if (ebone->parent && (ebone->parent->flag & BONE_TIPSEL)) {
912                                                 /* pass */
913                                         }
914                                         else {
915                                                 do_extrude = 2;
916                                         }
917                                 }
918
919                                 if (do_extrude) {
920                                         /* we re-use code for mirror editing... */
921                                         flipbone = NULL;
922                                         if (arm->flag & ARM_MIRROR_EDIT) {
923                                                 flipbone = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
924                                                 if (flipbone) {
925                                                         forked_iter = 0;  // we extrude 2 different bones
926                                                         if (flipbone->flag & (BONE_TIPSEL | BONE_ROOTSEL | BONE_SELECTED))
927                                                                 /* don't want this bone to be selected... */
928                                                                 flipbone->flag &= ~(BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL);
929                                                 }
930                                                 if ((flipbone == NULL) && (forked_iter))
931                                                         flipbone = ebone;
932                                         }
933
934                                         for (a = 0; a < 2; a++) {
935                                                 if (a == 1) {
936                                                         if (flipbone == NULL)
937                                                                 break;
938                                                         else {
939                                                                 SWAP(EditBone *, flipbone, ebone);
940                                                         }
941                                                 }
942
943                                                 totbone++;
944                                                 newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
945
946                                                 if (do_extrude == true) {
947                                                         copy_v3_v3(newbone->head, ebone->tail);
948                                                         copy_v3_v3(newbone->tail, newbone->head);
949                                                         newbone->parent = ebone;
950
951                                                         /* copies it, in case mirrored bone */
952                                                         newbone->flag = ebone->flag & (BONE_TIPSEL | BONE_RELATIVE_PARENTING);
953
954                                                         if (newbone->parent) newbone->flag |= BONE_CONNECTED;
955                                                 }
956                                                 else {
957                                                         copy_v3_v3(newbone->head, ebone->head);
958                                                         copy_v3_v3(newbone->tail, ebone->head);
959                                                         newbone->parent = ebone->parent;
960
961                                                         newbone->flag = BONE_TIPSEL;
962
963                                                         if (newbone->parent && (ebone->flag & BONE_CONNECTED)) {
964                                                                 newbone->flag |= BONE_CONNECTED;
965                                                         }
966                                                 }
967
968                                                 newbone->weight = ebone->weight;
969                                                 newbone->dist = ebone->dist;
970                                                 newbone->xwidth = ebone->xwidth;
971                                                 newbone->zwidth = ebone->zwidth;
972                                                 newbone->rad_head = ebone->rad_tail; // don't copy entire bone...
973                                                 newbone->rad_tail = ebone->rad_tail;
974                                                 newbone->segments = 1;
975                                                 newbone->layer = ebone->layer;
976
977                                                 /* Bendy-Bone parameters */
978                                                 newbone->roll1 = ebone->roll1;
979                                                 newbone->roll2 = ebone->roll2;
980                                                 newbone->curveInX = ebone->curveInX;
981                                                 newbone->curveInY = ebone->curveInY;
982                                                 newbone->curveOutX = ebone->curveOutX;
983                                                 newbone->curveOutY = ebone->curveOutY;
984                                                 newbone->ease1 = ebone->ease1;
985                                                 newbone->ease2 = ebone->ease2;
986                                                 newbone->scaleIn = ebone->scaleIn;
987                                                 newbone->scaleOut = ebone->scaleOut;
988
989
990                                                 BLI_strncpy(newbone->name, ebone->name, sizeof(newbone->name));
991
992                                                 if (flipbone && forked_iter) {   // only set if mirror edit
993                                                         if (strlen(newbone->name) < (MAXBONENAME - 2)) {
994                                                                 if (a == 0) strcat(newbone->name, "_L");
995                                                                 else strcat(newbone->name, "_R");
996                                                         }
997                                                 }
998                                                 ED_armature_ebone_unique_name(arm->edbo, newbone->name, NULL);
999
1000                                                 /* Add the new bone to the list */
1001                                                 BLI_addtail(arm->edbo, newbone);
1002                                                 if (!first)
1003                                                         first = newbone;
1004
1005                                                 /* restore ebone if we were flipping */
1006                                                 if (a == 1 && flipbone)
1007                                                         SWAP(EditBone *, flipbone, ebone);
1008                                         }
1009                                 }
1010
1011                                 /* Deselect the old bone */
1012                                 ebone->flag &= ~(BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL);
1013                         }
1014                 }
1015                 /* if only one bone, make this one active */
1016                 if (totbone == 1 && first) {
1017                         arm->act_edbone = first;
1018                 }
1019                 else {
1020                         arm->act_edbone = newbone;
1021                 }
1022
1023                 if (totbone == 0) {
1024                         continue;
1025                 }
1026
1027                 changed_multi = true;
1028
1029                 /* Transform the endpoints */
1030                 ED_armature_edit_sync_selection(arm->edbo);
1031
1032                 WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
1033         }
1034         MEM_freeN(objects);
1035
1036         return changed_multi ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1037 }
1038
1039 void ARMATURE_OT_extrude(wmOperatorType *ot)
1040 {
1041         /* identifiers */
1042         ot->name = "Extrude";
1043         ot->idname = "ARMATURE_OT_extrude";
1044         ot->description = "Create new bones from the selected joints";
1045
1046         /* api callbacks */
1047         ot->exec = armature_extrude_exec;
1048         ot->poll = ED_operator_editarmature;
1049
1050         /* flags */
1051         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1052
1053         /* props */
1054         RNA_def_boolean(ot->srna, "forked", 0, "Forked", "");
1055 }
1056
1057 /* ********************** Bone Add *************************************/
1058
1059 /*op makes a new bone and returns it with its tip selected */
1060
1061 static int armature_bone_primitive_add_exec(bContext *C, wmOperator *op)
1062 {
1063         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1064         Object *obedit = CTX_data_edit_object(C);
1065         EditBone *bone;
1066         float obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
1067         char name[MAXBONENAME];
1068
1069         RNA_string_get(op->ptr, "name", name);
1070
1071         copy_v3_v3(curs, CTX_data_scene(C)->cursor.location);
1072
1073         /* Get inverse point for head and orientation for tail */
1074         invert_m4_m4(obedit->imat, obedit->obmat);
1075         mul_m4_v3(obedit->imat, curs);
1076
1077         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
1078                 copy_m3_m4(obmat, rv3d->viewmat);
1079         else unit_m3(obmat);
1080
1081         copy_m3_m4(viewmat, obedit->obmat);
1082         mul_m3_m3m3(totmat, obmat, viewmat);
1083         invert_m3_m3(imat, totmat);
1084
1085         ED_armature_edit_deselect_all(obedit);
1086
1087         /*      Create a bone */
1088         bone = ED_armature_ebone_add(obedit->data, name);
1089
1090         copy_v3_v3(bone->head, curs);
1091
1092         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
1093                 add_v3_v3v3(bone->tail, bone->head, imat[1]);   // bone with unit length 1
1094         else
1095                 add_v3_v3v3(bone->tail, bone->head, imat[2]);   // bone with unit length 1, pointing up Z
1096
1097         /* note, notifier might evolve */
1098         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
1099
1100         return OPERATOR_FINISHED;
1101 }
1102
1103 void ARMATURE_OT_bone_primitive_add(wmOperatorType *ot)
1104 {
1105         /* identifiers */
1106         ot->name = "Add Bone";
1107         ot->idname = "ARMATURE_OT_bone_primitive_add";
1108         ot->description = "Add a new bone located at the 3D-Cursor";
1109
1110         /* api callbacks */
1111         ot->exec = armature_bone_primitive_add_exec;
1112         ot->poll = ED_operator_editarmature;
1113
1114         /* flags */
1115         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1116
1117         RNA_def_string(ot->srna, "name", "Bone", MAXBONENAME, "Name", "Name of the newly created bone");
1118
1119 }
1120
1121 /* ********************** Subdivide *******************************/
1122
1123 /* Subdivide Operators:
1124  * This group of operators all use the same 'exec' callback, but they are called
1125  * through several different operators - a combined menu (which just calls the exec in the
1126  * appropriate ways), and two separate ones.
1127  */
1128
1129 static int armature_subdivide_exec(bContext *C, wmOperator *op)
1130 {
1131         Object *obedit = CTX_data_edit_object(C);
1132         EditBone *newbone, *tbone;
1133         int cuts, i;
1134
1135         /* there may not be a number_cuts property defined (for 'simple' subdivide) */
1136         cuts = RNA_int_get(op->ptr, "number_cuts");
1137
1138         /* loop over all editable bones */
1139         // XXX the old code did this in reverse order though!
1140         CTX_DATA_BEGIN_WITH_ID(C, EditBone *, ebone, selected_editable_bones, bArmature *, arm)
1141         {
1142                 for (i = cuts + 1; i > 1; i--) {
1143                         /* compute cut ratio first */
1144                         float cutratio = 1.0f / (float)i;
1145                         float cutratioI = 1.0f - cutratio;
1146
1147                         float val1[3];
1148                         float val2[3];
1149                         float val3[3];
1150
1151                         newbone = MEM_mallocN(sizeof(EditBone), "ebone subdiv");
1152                         *newbone = *ebone;
1153                         BLI_addtail(arm->edbo, newbone);
1154
1155                         /* calculate location of newbone->head */
1156                         copy_v3_v3(val1, ebone->head);
1157                         copy_v3_v3(val2, ebone->tail);
1158                         copy_v3_v3(val3, newbone->head);
1159
1160                         val3[0] = val1[0] * cutratio + val2[0] * cutratioI;
1161                         val3[1] = val1[1] * cutratio + val2[1] * cutratioI;
1162                         val3[2] = val1[2] * cutratio + val2[2] * cutratioI;
1163
1164                         copy_v3_v3(newbone->head, val3);
1165                         copy_v3_v3(newbone->tail, ebone->tail);
1166                         copy_v3_v3(ebone->tail, newbone->head);
1167
1168                         newbone->rad_head = ((ebone->rad_head * cutratio) + (ebone->rad_tail * cutratioI));
1169                         ebone->rad_tail = newbone->rad_head;
1170
1171                         newbone->flag |= BONE_CONNECTED;
1172
1173                         newbone->prop = NULL;
1174
1175                         ED_armature_ebone_unique_name(arm->edbo, newbone->name, NULL);
1176
1177                         /* correct parent bones */
1178                         for (tbone = arm->edbo->first; tbone; tbone = tbone->next) {
1179                                 if (tbone->parent == ebone)
1180                                         tbone->parent = newbone;
1181                         }
1182                         newbone->parent = ebone;
1183                 }
1184         }
1185         CTX_DATA_END;
1186
1187         /* note, notifier might evolve */
1188         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
1189
1190         return OPERATOR_FINISHED;
1191 }
1192
1193 void ARMATURE_OT_subdivide(wmOperatorType *ot)
1194 {
1195         PropertyRNA *prop;
1196
1197         /* identifiers */
1198         ot->name = "Subdivide Multi";
1199         ot->idname = "ARMATURE_OT_subdivide";
1200         ot->description = "Break selected bones into chains of smaller bones";
1201
1202         /* api callbacks */
1203         ot->exec = armature_subdivide_exec;
1204         ot->poll = ED_operator_editarmature;
1205
1206         /* flags */
1207         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1208
1209         /* Properties */
1210         prop = RNA_def_int(ot->srna, "number_cuts", 1, 1, 1000, "Number of Cuts", "", 1, 10);
1211         /* avoid re-using last var because it can cause _very_ high poly meshes and annoy users (or worse crash) */
1212         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1213 }