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