doxygen: add newline after \file
[blender.git] / source / blender / editors / armature / armature_relations.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  * Operators for relations between bones and for transferring bones between armature objects
19  */
20
21 /** \file
22  * \ingroup edarmature
23  */
24
25 #include "MEM_guardedalloc.h"
26
27 #include "DNA_anim_types.h"
28 #include "DNA_armature_types.h"
29 #include "DNA_constraint_types.h"
30 #include "DNA_object_types.h"
31 #include "DNA_scene_types.h"
32
33 #include "BLI_blenlib.h"
34 #include "BLI_ghash.h"
35 #include "BLI_math.h"
36
37 #include "BLT_translation.h"
38
39 #include "BKE_action.h"
40 #include "BKE_animsys.h"
41 #include "BKE_constraint.h"
42 #include "BKE_context.h"
43 #include "BKE_fcurve.h"
44 #include "BKE_layer.h"
45 #include "BKE_main.h"
46 #include "BKE_report.h"
47
48 #include "DEG_depsgraph.h"
49 #include "DEG_depsgraph_build.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_object.h"
59 #include "ED_screen.h"
60
61 #include "UI_interface.h"
62 #include "UI_resources.h"
63
64 #include "armature_intern.h"
65
66 /* *************************************** Join *************************************** */
67 /* NOTE: no operator define here as this is exported to the Object-level operator */
68
69 static void joined_armature_fix_links_constraints(
70         Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone,
71         ListBase *lb)
72 {
73         bConstraint *con;
74
75         for (con = lb->first; con; con = con->next) {
76                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
77                 ListBase targets = {NULL, NULL};
78                 bConstraintTarget *ct;
79
80                 /* constraint targets */
81                 if (cti && cti->get_constraint_targets) {
82                         cti->get_constraint_targets(con, &targets);
83
84                         for (ct = targets.first; ct; ct = ct->next) {
85                                 if (ct->tar == srcArm) {
86                                         if (ct->subtarget[0] == '\0') {
87                                                 ct->tar = tarArm;
88                                         }
89                                         else if (STREQ(ct->subtarget, pchan->name)) {
90                                                 ct->tar = tarArm;
91                                                 BLI_strncpy(ct->subtarget, curbone->name, sizeof(ct->subtarget));
92                                         }
93                                 }
94                         }
95
96                         if (cti->flush_constraint_targets)
97                                 cti->flush_constraint_targets(con, &targets, 0);
98                 }
99
100                 /* action constraint? (pose constraints only) */
101                 if (con->type == CONSTRAINT_TYPE_ACTION) {
102                         bActionConstraint *data = con->data;
103
104                         if (data->act) {
105                                 BKE_action_fix_paths_rename(&tarArm->id, data->act, "pose.bones[",
106                                                             pchan->name, curbone->name, 0, 0, false);
107                         }
108                 }
109
110         }
111 }
112
113 /* userdata for joined_armature_fix_animdata_cb() */
114 typedef struct tJoinArmature_AdtFixData {
115         Object *srcArm;
116         Object *tarArm;
117
118         GHash *names_map;
119 } tJoinArmature_AdtFixData;
120
121 /* Callback to pass to BKE_animdata_main_cb() for fixing driver ID's to point to the new ID */
122 /* FIXME: For now, we only care about drivers here. When editing rigs, it's very rare to have animation
123  *        on the rigs being edited already, so it should be safe to skip these.
124  */
125 static void joined_armature_fix_animdata_cb(ID *id, FCurve *fcu, void *user_data)
126 {
127         tJoinArmature_AdtFixData *afd = (tJoinArmature_AdtFixData *)user_data;
128         ID *src_id = &afd->srcArm->id;
129         ID *dst_id = &afd->tarArm->id;
130
131         GHashIterator gh_iter;
132
133         /* Fix paths - If this is the target object, it will have some "dirty" paths */
134         if ((id == src_id) && strstr(fcu->rna_path, "pose.bones[")) {
135                 GHASH_ITER(gh_iter, afd->names_map) {
136                         const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
137                         const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
138
139                         /* only remap if changed; this still means there will be some
140                          * waste if there aren't many drivers/keys */
141                         if (!STREQ(old_name, new_name) && strstr(fcu->rna_path, old_name)) {
142                                 fcu->rna_path = BKE_animsys_fix_rna_path_rename(id, fcu->rna_path, "pose.bones",
143                                                                                 old_name, new_name, 0, 0, false);
144
145                                 /* we don't want to apply a second remapping on this driver now,
146                                  * so stop trying names, but keep fixing drivers
147                                  */
148                                 break;
149                         }
150                 }
151         }
152
153
154         /* Driver targets */
155         if (fcu->driver) {
156                 ChannelDriver *driver = fcu->driver;
157                 DriverVar *dvar;
158
159                 /* Fix driver references to invalid ID's */
160                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
161                         /* only change the used targets, since the others will need fixing manually anyway */
162                         DRIVER_TARGETS_USED_LOOPER_BEGIN(dvar)
163                         {
164                                 /* change the ID's used... */
165                                 if (dtar->id == src_id) {
166                                         dtar->id = dst_id;
167
168                                         /* also check on the subtarget...
169                                          * XXX: We duplicate the logic from drivers_path_rename_fix() here, with our own
170                                          *      little twists so that we know that it isn't going to clobber the wrong data
171                                          */
172                                         if ((dtar->rna_path && strstr(dtar->rna_path, "pose.bones[")) || (dtar->pchan_name[0])) {
173                                                 GHASH_ITER(gh_iter, afd->names_map) {
174                                                         const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
175                                                         const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
176
177                                                         /* only remap if changed */
178                                                         if (!STREQ(old_name, new_name)) {
179                                                                 if ((dtar->rna_path) && strstr(dtar->rna_path, old_name)) {
180                                                                         /* Fix up path */
181                                                                         dtar->rna_path = BKE_animsys_fix_rna_path_rename(id, dtar->rna_path, "pose.bones",
182                                                                                                                          old_name, new_name, 0, 0, false);
183                                                                         break; /* no need to try any more names for bone path */
184                                                                 }
185                                                                 else if (STREQ(dtar->pchan_name, old_name)) {
186                                                                         /* Change target bone name */
187                                                                         BLI_strncpy(dtar->pchan_name, new_name, sizeof(dtar->pchan_name));
188                                                                         break; /* no need to try any more names for bone subtarget */
189                                                                 }
190                                                         }
191                                                 }
192                                         }
193                                 }
194                         }
195                         DRIVER_TARGETS_LOOPER_END;
196                 }
197         }
198 }
199
200 /* Helper function for armature joining - link fixing */
201 static void joined_armature_fix_links(Main *bmain, Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
202 {
203         Object *ob;
204         bPose *pose;
205         bPoseChannel *pchant;
206
207         /* let's go through all objects in database */
208         for (ob = bmain->object.first; ob; ob = ob->id.next) {
209                 /* do some object-type specific things */
210                 if (ob->type == OB_ARMATURE) {
211                         pose = ob->pose;
212                         for (pchant = pose->chanbase.first; pchant; pchant = pchant->next) {
213                                 joined_armature_fix_links_constraints(tarArm, srcArm, pchan, curbone, &pchant->constraints);
214                         }
215                 }
216
217                 /* fix object-level constraints */
218                 if (ob != srcArm) {
219                         joined_armature_fix_links_constraints(tarArm, srcArm, pchan, curbone, &ob->constraints);
220                 }
221
222                 /* See if an object is parented to this armature */
223                 if (ob->parent && (ob->parent == srcArm)) {
224                         /* Is object parented to a bone of this src armature? */
225                         if (ob->partype == PARBONE) {
226                                 /* bone name in object */
227                                 if (STREQ(ob->parsubstr, pchan->name)) {
228                                         BLI_strncpy(ob->parsubstr, curbone->name, sizeof(ob->parsubstr));
229                                 }
230                         }
231
232                         /* make tar armature be new parent */
233                         ob->parent = tarArm;
234                 }
235         }
236 }
237
238 /* join armature exec is exported for use in object->join objects operator... */
239 int join_armature_exec(bContext *C, wmOperator *op)
240 {
241         Main *bmain = CTX_data_main(C);
242         Scene *scene = CTX_data_scene(C);
243         Object  *ob_active = CTX_data_active_object(C);
244         bArmature *arm = (ob_active) ? ob_active->data : NULL;
245         bPose *pose, *opose;
246         bPoseChannel *pchan, *pchann;
247         EditBone *curbone;
248         float mat[4][4], oimat[4][4];
249         bool ok = false;
250
251         /*      Ensure we're not in editmode and that the active object is an armature*/
252         if (!ob_active || ob_active->type != OB_ARMATURE)
253                 return OPERATOR_CANCELLED;
254         if (!arm || arm->edbo)
255                 return OPERATOR_CANCELLED;
256
257         CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects)
258         {
259                 if (ob_iter == ob_active) {
260                         ok = true;
261                         break;
262                 }
263         }
264         CTX_DATA_END;
265
266         /* that way the active object is always selected */
267         if (ok == false) {
268                 BKE_report(op->reports, RPT_WARNING, "Active object is not a selected armature");
269                 return OPERATOR_CANCELLED;
270         }
271
272         /* Get editbones of active armature to add editbones to */
273         ED_armature_to_edit(arm);
274
275         /* get pose of active object and move it out of posemode */
276         pose = ob_active->pose;
277         ob_active->mode &= ~OB_MODE_POSE;
278
279         CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects)
280         {
281                 if ((ob_iter->type == OB_ARMATURE) && (ob_iter != ob_active)) {
282                         tJoinArmature_AdtFixData afd = {NULL};
283                         bArmature *curarm = ob_iter->data;
284
285                         /* we assume that each armature datablock is only used in a single place */
286                         BLI_assert(ob_active->data != ob_iter->data);
287
288                         /* init callback data for fixing up AnimData links later */
289                         afd.srcArm = ob_iter;
290                         afd.tarArm = ob_active;
291                         afd.names_map = BLI_ghash_str_new("join_armature_adt_fix");
292
293                         /* Make a list of editbones in current armature */
294                         ED_armature_to_edit(ob_iter->data);
295
296                         /* Get Pose of current armature */
297                         opose = ob_iter->pose;
298                         ob_iter->mode &= ~OB_MODE_POSE;
299                         //BASACT->flag &= ~OB_MODE_POSE;
300
301                         /* Find the difference matrix */
302                         invert_m4_m4(oimat, ob_active->obmat);
303                         mul_m4_m4m4(mat, oimat, ob_iter->obmat);
304
305                         /* Copy bones and posechannels from the object to the edit armature */
306                         for (pchan = opose->chanbase.first; pchan; pchan = pchann) {
307                                 pchann = pchan->next;
308                                 curbone = ED_armature_ebone_find_name(curarm->edbo, pchan->name);
309
310                                 /* Get new name */
311                                 ED_armature_ebone_unique_name(arm->edbo, curbone->name, NULL);
312                                 BLI_ghash_insert(afd.names_map, BLI_strdup(pchan->name), curbone->name);
313
314                                 /* Transform the bone */
315                                 {
316                                         float premat[4][4];
317                                         float postmat[4][4];
318                                         float difmat[4][4];
319                                         float imat[4][4];
320                                         float temp[3][3];
321
322                                         /* Get the premat */
323                                         ED_armature_ebone_to_mat3(curbone, temp);
324
325                                         unit_m4(premat); /* mul_m4_m3m4 only sets 3x3 part */
326                                         mul_m4_m3m4(premat, temp, mat);
327
328                                         mul_m4_v3(mat, curbone->head);
329                                         mul_m4_v3(mat, curbone->tail);
330
331                                         /* Get the postmat */
332                                         ED_armature_ebone_to_mat3(curbone, temp);
333                                         copy_m4_m3(postmat, temp);
334
335                                         /* Find the roll */
336                                         invert_m4_m4(imat, premat);
337                                         mul_m4_m4m4(difmat, imat, postmat);
338
339                                         curbone->roll -= atan2f(difmat[2][0], difmat[2][2]);
340                                 }
341
342                                 /* Fix Constraints and Other Links to this Bone and Armature */
343                                 joined_armature_fix_links(bmain, ob_active, ob_iter, pchan, curbone);
344
345                                 /* Rename pchan */
346                                 BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
347
348                                 /* Jump Ship! */
349                                 BLI_remlink(curarm->edbo, curbone);
350                                 BLI_addtail(arm->edbo, curbone);
351
352                                 BLI_remlink(&opose->chanbase, pchan);
353                                 BLI_addtail(&pose->chanbase, pchan);
354                                 BKE_pose_channels_hash_free(opose);
355                                 BKE_pose_channels_hash_free(pose);
356                         }
357
358                         /* Fix all the drivers (and animation data) */
359                         BKE_fcurves_main_cb(bmain, joined_armature_fix_animdata_cb, &afd);
360                         BLI_ghash_free(afd.names_map, MEM_freeN, NULL);
361
362                         /* Only copy over animdata now, after all the remapping has been done,
363                          * so that we don't have to worry about ambiguities re which armature
364                          * a bone came from!
365                          */
366                         if (ob_iter->adt) {
367                                 if (ob_active->adt == NULL) {
368                                         /* no animdata, so just use a copy of the whole thing */
369                                         ob_active->adt = BKE_animdata_copy(bmain, ob_iter->adt, 0);
370                                 }
371                                 else {
372                                         /* merge in data - we'll fix the drivers manually */
373                                         BKE_animdata_merge_copy(bmain, &ob_active->id, &ob_iter->id, ADT_MERGECOPY_KEEP_DST, false);
374                                 }
375                         }
376
377                         if (curarm->adt) {
378                                 if (arm->adt == NULL) {
379                                         /* no animdata, so just use a copy of the whole thing */
380                                         arm->adt = BKE_animdata_copy(bmain, curarm->adt, 0);
381                                 }
382                                 else {
383                                         /* merge in data - we'll fix the drivers manually */
384                                         BKE_animdata_merge_copy(bmain, &arm->id, &curarm->id, ADT_MERGECOPY_KEEP_DST, false);
385                                 }
386                         }
387
388                         /* Free the old object data */
389                         ED_object_base_free_and_unlink(bmain, scene, ob_iter);
390                 }
391         }
392         CTX_DATA_END;
393
394         DEG_relations_tag_update(bmain);  /* because we removed object(s) */
395
396         ED_armature_from_edit(bmain, arm);
397         ED_armature_edit_free(arm);
398
399         DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
400         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
401
402         return OPERATOR_FINISHED;
403 }
404
405 /* *********************************** Separate *********************************************** */
406
407 /* Helper function for armature separating - link fixing */
408 static void separated_armature_fix_links(Main *bmain, Object *origArm, Object *newArm)
409 {
410         Object *ob;
411         bPoseChannel *pchan;
412         bConstraint *con;
413         ListBase *opchans, *npchans;
414
415         /* get reference to list of bones in original and new armatures  */
416         opchans = &origArm->pose->chanbase;
417         npchans = &newArm->pose->chanbase;
418
419         /* let's go through all objects in database */
420         for (ob = bmain->object.first; ob; ob = ob->id.next) {
421                 /* do some object-type specific things */
422                 if (ob->type == OB_ARMATURE) {
423                         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
424                                 for (con = pchan->constraints.first; con; con = con->next) {
425                                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
426                                         ListBase targets = {NULL, NULL};
427                                         bConstraintTarget *ct;
428
429                                         /* constraint targets */
430                                         if (cti && cti->get_constraint_targets) {
431                                                 cti->get_constraint_targets(con, &targets);
432
433                                                 for (ct = targets.first; ct; ct = ct->next) {
434                                                         /* any targets which point to original armature are redirected to the new one only if:
435                                                          * - the target isn't origArm/newArm itself
436                                                          * - the target is one that can be found in newArm/origArm
437                                                          */
438                                                         if (ct->subtarget[0] != 0) {
439                                                                 if (ct->tar == origArm) {
440                                                                         if (BLI_findstring(npchans, ct->subtarget, offsetof(bPoseChannel, name))) {
441                                                                                 ct->tar = newArm;
442                                                                         }
443                                                                 }
444                                                                 else if (ct->tar == newArm) {
445                                                                         if (BLI_findstring(opchans, ct->subtarget, offsetof(bPoseChannel, name))) {
446                                                                                 ct->tar = origArm;
447                                                                         }
448                                                                 }
449                                                         }
450                                                 }
451
452                                                 if (cti->flush_constraint_targets) {
453                                                         cti->flush_constraint_targets(con, &targets, 0);
454                                                 }
455                                         }
456                                 }
457                         }
458                 }
459
460                 /* fix object-level constraints */
461                 if (ob != origArm) {
462                         for (con = ob->constraints.first; con; con = con->next) {
463                                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
464                                 ListBase targets = {NULL, NULL};
465                                 bConstraintTarget *ct;
466
467                                 /* constraint targets */
468                                 if (cti && cti->get_constraint_targets) {
469                                         cti->get_constraint_targets(con, &targets);
470
471                                         for (ct = targets.first; ct; ct = ct->next) {
472                                                 /* any targets which point to original armature are redirected to the new one only if:
473                                                  * - the target isn't origArm/newArm itself
474                                                  * - the target is one that can be found in newArm/origArm
475                                                  */
476                                                 if (ct->subtarget[0] != '\0') {
477                                                         if (ct->tar == origArm) {
478                                                                 if (BLI_findstring(npchans, ct->subtarget, offsetof(bPoseChannel, name))) {
479                                                                         ct->tar = newArm;
480                                                                 }
481                                                         }
482                                                         else if (ct->tar == newArm) {
483                                                                 if (BLI_findstring(opchans, ct->subtarget, offsetof(bPoseChannel, name))) {
484                                                                         ct->tar = origArm;
485                                                                 }
486                                                         }
487                                                 }
488                                         }
489
490                                         if (cti->flush_constraint_targets) {
491                                                 cti->flush_constraint_targets(con, &targets, 0);
492                                         }
493                                 }
494                         }
495                 }
496
497                 /* See if an object is parented to this armature */
498                 if (ob->parent && (ob->parent == origArm)) {
499                         /* Is object parented to a bone of this src armature? */
500                         if ((ob->partype == PARBONE) && (ob->parsubstr[0] != '\0')) {
501                                 if (BLI_findstring(npchans, ob->parsubstr, offsetof(bPoseChannel, name))) {
502                                         ob->parent = newArm;
503                                 }
504                         }
505                 }
506         }
507 }
508
509 /* Helper function for armature separating - remove certain bones from the given armature
510  * sel: remove selected bones from the armature, otherwise the unselected bones are removed
511  * (ob is not in editmode)
512  */
513 static void separate_armature_bones(Main *bmain, Object *ob, short sel)
514 {
515         bArmature *arm = (bArmature *)ob->data;
516         bPoseChannel *pchan, *pchann;
517         EditBone *curbone;
518
519         /* make local set of editbones to manipulate here */
520         ED_armature_to_edit(arm);
521
522         /* go through pose-channels, checking if a bone should be removed */
523         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchann) {
524                 pchann = pchan->next;
525                 curbone = ED_armature_ebone_find_name(arm->edbo, pchan->name);
526
527                 /* check if bone needs to be removed */
528                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
529                      (!sel && !(curbone->flag & BONE_SELECTED)) )
530                 {
531                         EditBone *ebo;
532                         bPoseChannel *pchn;
533
534                         /* clear the bone->parent var of any bone that had this as its parent  */
535                         for (ebo = arm->edbo->first; ebo; ebo = ebo->next) {
536                                 if (ebo->parent == curbone) {
537                                         ebo->parent = NULL;
538                                         /* this is needed to prevent random crashes with in ED_armature_from_edit */
539                                         ebo->temp.p = NULL;
540                                         ebo->flag &= ~BONE_CONNECTED;
541                                 }
542                         }
543
544                         /* clear the pchan->parent var of any pchan that had this as its parent */
545                         for (pchn = ob->pose->chanbase.first; pchn; pchn = pchn->next) {
546                                 if (pchn->parent == pchan) {
547                                         pchn->parent = NULL;
548                                 }
549                                 if (pchn->bbone_next == pchan) {
550                                         pchn->bbone_next = NULL;
551                                 }
552                                 if (pchn->bbone_prev == pchan) {
553                                         pchn->bbone_prev = NULL;
554                                 }
555                         }
556
557                         /* free any of the extra-data this pchan might have */
558                         BKE_pose_channel_free(pchan);
559                         BKE_pose_channels_hash_free(ob->pose);
560
561                         /* get rid of unneeded bone */
562                         bone_free(arm, curbone);
563                         BLI_freelinkN(&ob->pose->chanbase, pchan);
564                 }
565         }
566
567         /* exit editmode (recalculates pchans too) */
568         ED_armature_from_edit(bmain, ob->data);
569         ED_armature_edit_free(ob->data);
570 }
571
572 /* separate selected bones into their armature */
573 static int separate_armature_exec(bContext *C, wmOperator *op)
574 {
575         Main *bmain = CTX_data_main(C);
576         Scene *scene = CTX_data_scene(C);
577         ViewLayer *view_layer = CTX_data_view_layer(C);
578         bool ok = false;
579
580         /* set wait cursor in case this takes a while */
581         WM_cursor_wait(1);
582
583         uint bases_len = 0;
584         Base **bases = BKE_view_layer_array_from_bases_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &bases_len);
585
586         CTX_DATA_BEGIN(C, Base *, base, visible_bases)
587         {
588                 ED_object_base_select(base, BA_DESELECT);
589         }
590         CTX_DATA_END;
591
592         for (uint base_index = 0; base_index < bases_len; base_index++) {
593                 Base *base_iter = bases[base_index];
594                 Object *obedit = base_iter->object;
595
596                 Object *oldob, *newob;
597                 Base *oldbase, *newbase;
598
599                 /* we are going to do this as follows (unlike every other instance of separate):
600                  * 1. exit editmode +posemode for active armature/base. Take note of what this is.
601                  * 2. duplicate base - BASACT is the new one now
602                  * 3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
603                  * 4. fix constraint links
604                  * 5. make original armature active and enter editmode
605                  */
606
607                 /* 1) only edit-base selected */
608                 ED_object_base_select(base_iter, BA_SELECT);
609
610                 /* 1) store starting settings and exit editmode */
611                 oldob = obedit;
612                 oldbase = base_iter;
613                 oldob->mode &= ~OB_MODE_POSE;
614                 //oldbase->flag &= ~OB_POSEMODE;
615
616                 ED_armature_from_edit(bmain, obedit->data);
617                 ED_armature_edit_free(obedit->data);
618
619                 /* 2) duplicate base */
620
621                 /* only duplicate linked armature */
622                 newbase = ED_object_add_duplicate(bmain, scene, view_layer, oldbase, USER_DUP_ARM);
623
624                 DEG_relations_tag_update(bmain);
625
626                 newob = newbase->object;
627                 newbase->flag &= ~BASE_SELECTED;
628
629
630                 /* 3) remove bones that shouldn't still be around on both armatures */
631                 separate_armature_bones(bmain, oldob, 1);
632                 separate_armature_bones(bmain, newob, 0);
633
634
635                 /* 4) fix links before depsgraph flushes */ // err... or after?
636                 separated_armature_fix_links(bmain, oldob, newob);
637
638                 DEG_id_tag_update(&oldob->id, ID_RECALC_GEOMETRY);  /* this is the original one */
639                 DEG_id_tag_update(&newob->id, ID_RECALC_GEOMETRY);  /* this is the separated one */
640
641
642                 /* 5) restore original conditions */
643                 obedit = oldob;
644
645                 ED_armature_to_edit(obedit->data);
646
647                 /* parents tips remain selected when connected children are removed. */
648                 ED_armature_edit_deselect_all(obedit);
649
650                 ok = true;
651
652                 /* note, notifier might evolve */
653                 WM_event_add_notifier(C, NC_OBJECT | ND_POSE, obedit);
654         }
655         MEM_freeN(bases);
656
657         /* recalc/redraw + cleanup */
658         WM_cursor_wait(0);
659
660         if (ok) {
661                 BKE_report(op->reports, RPT_INFO, "Separated bones");
662         }
663
664         return OPERATOR_FINISHED;
665 }
666
667 void ARMATURE_OT_separate(wmOperatorType *ot)
668 {
669         /* identifiers */
670         ot->name = "Separate Bones";
671         ot->idname = "ARMATURE_OT_separate";
672         ot->description = "Isolate selected bones into a separate armature";
673
674         /* callbacks */
675         ot->invoke = WM_operator_confirm;
676         ot->exec = separate_armature_exec;
677         ot->poll = ED_operator_editarmature;
678
679         /* flags */
680         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
681 }
682
683 /* ******************************************** Parenting ************************************************* */
684
685 /* armature parenting options */
686 #define ARM_PAR_CONNECT 1
687 #define ARM_PAR_OFFSET  2
688
689
690 /* check for null, before calling! */
691 static void bone_connect_to_existing_parent(EditBone *bone)
692 {
693         bone->flag |= BONE_CONNECTED;
694         copy_v3_v3(bone->head, bone->parent->tail);
695         bone->rad_head = bone->parent->rad_tail;
696 }
697
698 static void bone_connect_to_new_parent(ListBase *edbo, EditBone *selbone, EditBone *actbone, short mode)
699 {
700         EditBone *ebone;
701         float offset[3];
702
703         if ((selbone->parent) && (selbone->flag & BONE_CONNECTED))
704                 selbone->parent->flag &= ~(BONE_TIPSEL);
705
706         /* make actbone the parent of selbone */
707         selbone->parent = actbone;
708
709         /* in actbone tree we cannot have a loop */
710         for (ebone = actbone->parent; ebone; ebone = ebone->parent) {
711                 if (ebone->parent == selbone) {
712                         ebone->parent = NULL;
713                         ebone->flag &= ~BONE_CONNECTED;
714                 }
715         }
716
717         if (mode == ARM_PAR_CONNECT) {
718                 /* Connected: Child bones will be moved to the parent tip */
719                 selbone->flag |= BONE_CONNECTED;
720                 sub_v3_v3v3(offset, actbone->tail, selbone->head);
721
722                 copy_v3_v3(selbone->head, actbone->tail);
723                 selbone->rad_head = actbone->rad_tail;
724
725                 add_v3_v3(selbone->tail, offset);
726
727                 /* offset for all its children */
728                 for (ebone = edbo->first; ebone; ebone = ebone->next) {
729                         EditBone *par;
730
731                         for (par = ebone->parent; par; par = par->parent) {
732                                 if (par == selbone) {
733                                         add_v3_v3(ebone->head, offset);
734                                         add_v3_v3(ebone->tail, offset);
735                                         break;
736                                 }
737                         }
738                 }
739         }
740         else {
741                 /* Offset: Child bones will retain their distance from the parent tip */
742                 selbone->flag &= ~BONE_CONNECTED;
743         }
744 }
745
746
747 static const EnumPropertyItem prop_editarm_make_parent_types[] = {
748         {ARM_PAR_CONNECT, "CONNECTED", 0, "Connected", ""},
749         {ARM_PAR_OFFSET, "OFFSET", 0, "Keep Offset", ""},
750         {0, NULL, 0, NULL, NULL},
751 };
752
753 static int armature_parent_set_exec(bContext *C, wmOperator *op)
754 {
755         Object *ob = CTX_data_edit_object(C);
756         bArmature *arm = (bArmature *)ob->data;
757         EditBone *actbone = CTX_data_active_bone(C);
758         EditBone *actmirb = NULL;
759         short val = RNA_enum_get(op->ptr, "type");
760
761         /* there must be an active bone */
762         if (actbone == NULL) {
763                 BKE_report(op->reports, RPT_ERROR, "Operation requires an active bone");
764                 return OPERATOR_CANCELLED;
765         }
766         else if (arm->flag & ARM_MIRROR_EDIT) {
767                 /* For X-Axis Mirror Editing option, we may need a mirror copy of actbone
768                  * - if there's a mirrored copy of selbone, try to find a mirrored copy of actbone
769                  *   (i.e.  selbone="child.L" and actbone="parent.L", find "child.R" and "parent.R").
770                  * This is useful for arm-chains, for example parenting lower arm to upper arm
771                  * - if there's no mirrored copy of actbone (i.e. actbone = "parent.C" or "parent")
772                  *   then just use actbone. Useful when doing upper arm to spine.
773                  */
774                 actmirb = ED_armature_ebone_get_mirrored(arm->edbo, actbone);
775                 if (actmirb == NULL)
776                         actmirb = actbone;
777         }
778
779         /* if there is only 1 selected bone, we assume that that is the active bone,
780          * since a user will need to have clicked on a bone (thus selecting it) to make it active
781          */
782         if (CTX_DATA_COUNT(C, selected_editable_bones) <= 1) {
783                 /* When only the active bone is selected, and it has a parent,
784                  * connect it to the parent, as that is the only possible outcome.
785                  */
786                 if (actbone->parent) {
787                         bone_connect_to_existing_parent(actbone);
788
789                         if ((arm->flag & ARM_MIRROR_EDIT) && (actmirb->parent))
790                                 bone_connect_to_existing_parent(actmirb);
791                 }
792         }
793         else {
794                 /* Parent 'selected' bones to the active one
795                  * - the context iterator contains both selected bones and their mirrored copies,
796                  *   so we assume that unselected bones are mirrored copies of some selected bone
797                  * - since the active one (and/or its mirror) will also be selected, we also need
798                  *   to check that we are not trying to operate on them, since such an operation
799                  *   would cause errors
800                  */
801
802                 /* parent selected bones to the active one */
803                 CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
804                 {
805                         if (ELEM(ebone, actbone, actmirb) == 0) {
806                                 if (ebone->flag & BONE_SELECTED)
807                                         bone_connect_to_new_parent(arm->edbo, ebone, actbone, val);
808                                 else
809                                         bone_connect_to_new_parent(arm->edbo, ebone, actmirb, val);
810                         }
811                 }
812                 CTX_DATA_END;
813         }
814
815
816         /* note, notifier might evolve */
817         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
818
819         return OPERATOR_FINISHED;
820 }
821
822 static int armature_parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
823 {
824         EditBone *actbone = CTX_data_active_bone(C);
825         uiPopupMenu *pup = UI_popup_menu_begin(C, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Make Parent"), ICON_NONE);
826         uiLayout *layout = UI_popup_menu_layout(pup);
827         int allchildbones = 0;
828
829         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
830         {
831                 if (ebone != actbone) {
832                         if (ebone->parent != actbone) allchildbones = 1;
833                 }
834         }
835         CTX_DATA_END;
836
837         uiItemEnumO(layout, "ARMATURE_OT_parent_set", NULL, 0, "type", ARM_PAR_CONNECT);
838
839         /* ob becomes parent, make the associated menus */
840         if (allchildbones)
841                 uiItemEnumO(layout, "ARMATURE_OT_parent_set", NULL, 0, "type", ARM_PAR_OFFSET);
842
843         UI_popup_menu_end(C, pup);
844
845         return OPERATOR_INTERFACE;
846 }
847
848 void ARMATURE_OT_parent_set(wmOperatorType *ot)
849 {
850         /* identifiers */
851         ot->name = "Make Parent";
852         ot->idname = "ARMATURE_OT_parent_set";
853         ot->description = "Set the active bone as the parent of the selected bones";
854
855         /* api callbacks */
856         ot->invoke = armature_parent_set_invoke;
857         ot->exec = armature_parent_set_exec;
858         ot->poll = ED_operator_editarmature;
859
860         /* flags */
861         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
862
863         RNA_def_enum(ot->srna, "type", prop_editarm_make_parent_types, 0, "ParentType", "Type of parenting");
864 }
865
866
867
868 static const EnumPropertyItem prop_editarm_clear_parent_types[] = {
869         {1, "CLEAR", 0, "Clear Parent", ""},
870         {2, "DISCONNECT", 0, "Disconnect Bone", ""},
871         {0, NULL, 0, NULL, NULL},
872 };
873
874 static void editbone_clear_parent(EditBone *ebone, int mode)
875 {
876         if (ebone->parent) {
877                 /* for nice selection */
878                 ebone->parent->flag &= ~(BONE_TIPSEL);
879         }
880
881         if (mode == 1) ebone->parent = NULL;
882         ebone->flag &= ~BONE_CONNECTED;
883 }
884
885 static int armature_parent_clear_exec(bContext *C, wmOperator *op)
886 {
887         ViewLayer *view_layer = CTX_data_view_layer(C);
888         const int val = RNA_enum_get(op->ptr, "type");
889
890         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
891         {
892                 editbone_clear_parent(ebone, val);
893         }
894         CTX_DATA_END;
895
896         uint objects_len = 0;
897         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
898         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
899                 Object *ob = objects[ob_index];
900                 bArmature *arm = ob->data;
901                 bool changed = false;
902
903                 for (EditBone *ebone = arm->edbo->first; ebone; ebone = ebone->next) {
904                         if (EBONE_EDITABLE(ebone)) {
905                                 changed = true;
906                                 break;
907                         }
908                 }
909
910                 if (!changed) {
911                         continue;
912                 }
913
914                 ED_armature_edit_sync_selection(arm->edbo);
915
916                 /* Note, notifier might evolve. */
917                 WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
918         }
919         MEM_freeN(objects);
920
921         return OPERATOR_FINISHED;
922 }
923
924 void ARMATURE_OT_parent_clear(wmOperatorType *ot)
925 {
926         /* identifiers */
927         ot->name = "Clear Parent";
928         ot->idname = "ARMATURE_OT_parent_clear";
929         ot->description = "Remove the parent-child relationship between selected bones and their parents";
930
931         /* api callbacks */
932         ot->invoke = WM_menu_invoke;
933         ot->exec = armature_parent_clear_exec;
934         ot->poll = ED_operator_editarmature;
935
936         /* flags */
937         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
938
939         ot->prop = RNA_def_enum(ot->srna, "type", prop_editarm_clear_parent_types, 0, "ClearType", "What way to clear parenting");
940 }