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