1794d74576738b9a01c299acef0e78475e273cde
[blender.git] / source / blender / blenkernel / intern / library_remap.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/blenkernel/intern/library_remap.c
22  *  \ingroup bke
23  *
24  * Contains management of ID's and libraries remap, unlink and free logic.
25  */
26
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stddef.h>
32 #include <assert.h>
33
34 #include "MEM_guardedalloc.h"
35
36 /* all types are needed here, in order to do memory operations */
37 #include "DNA_anim_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_brush_types.h"
40 #include "DNA_camera_types.h"
41 #include "DNA_cachefile_types.h"
42 #include "DNA_group_types.h"
43 #include "DNA_gpencil_types.h"
44 #include "DNA_ipo_types.h"
45 #include "DNA_key_types.h"
46 #include "DNA_lamp_types.h"
47 #include "DNA_lattice_types.h"
48 #include "DNA_linestyle_types.h"
49 #include "DNA_material_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_meta_types.h"
52 #include "DNA_movieclip_types.h"
53 #include "DNA_mask_types.h"
54 #include "DNA_node_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_screen_types.h"
58 #include "DNA_speaker_types.h"
59 #include "DNA_sound_types.h"
60 #include "DNA_text_types.h"
61 #include "DNA_vfont_types.h"
62 #include "DNA_windowmanager_types.h"
63 #include "DNA_world_types.h"
64
65 #include "BLI_blenlib.h"
66 #include "BLI_utildefines.h"
67
68 #include "BKE_action.h"
69 #include "BKE_animsys.h"
70 #include "BKE_armature.h"
71 #include "BKE_brush.h"
72 #include "BKE_camera.h"
73 #include "BKE_cachefile.h"
74 #include "BKE_curve.h"
75 #include "BKE_depsgraph.h"
76 #include "BKE_fcurve.h"
77 #include "BKE_font.h"
78 #include "BKE_group.h"
79 #include "BKE_gpencil.h"
80 #include "BKE_idprop.h"
81 #include "BKE_image.h"
82 #include "BKE_ipo.h"
83 #include "BKE_key.h"
84 #include "BKE_lamp.h"
85 #include "BKE_lattice.h"
86 #include "BKE_library.h"
87 #include "BKE_library_query.h"
88 #include "BKE_library_remap.h"
89 #include "BKE_linestyle.h"
90 #include "BKE_mesh.h"
91 #include "BKE_material.h"
92 #include "BKE_main.h"
93 #include "BKE_mask.h"
94 #include "BKE_mball.h"
95 #include "BKE_modifier.h"
96 #include "BKE_movieclip.h"
97 #include "BKE_multires.h"
98 #include "BKE_node.h"
99 #include "BKE_object.h"
100 #include "BKE_paint.h"
101 #include "BKE_particle.h"
102 #include "BKE_sca.h"
103 #include "BKE_speaker.h"
104 #include "BKE_sound.h"
105 #include "BKE_screen.h"
106 #include "BKE_scene.h"
107 #include "BKE_text.h"
108 #include "BKE_texture.h"
109 #include "BKE_world.h"
110
111 #ifdef WITH_PYTHON
112 #include "BPY_extern.h"
113 #endif
114
115 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
116
117 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
118 {
119         free_windowmanager_cb = func;
120 }
121
122 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
123
124 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
125 {
126         free_notifier_reference_cb = func;
127 }
128
129 static BKE_library_remap_editor_id_reference_cb remap_editor_id_reference_cb = NULL;
130
131 void BKE_library_callback_remap_editor_id_reference_set(BKE_library_remap_editor_id_reference_cb func)
132 {
133         remap_editor_id_reference_cb = func;
134 }
135
136 typedef struct IDRemap {
137         Main *bmain;  /* Only used to trigger depsgraph updates in the right bmain. */
138         ID *old_id;
139         ID *new_id;
140         ID *id;  /* The ID in which we are replacing old_id by new_id usages. */
141         short flag;
142
143         /* 'Output' data. */
144         short status;
145         int skipped_direct;  /* Number of direct usecases that could not be remapped (e.g.: obdata when in edit mode). */
146         int skipped_indirect;  /* Number of indirect usecases that could not be remapped. */
147         int skipped_refcounted;  /* Number of skipped usecases that refcount the datablock. */
148 } IDRemap;
149
150 /* IDRemap->flag enums defined in BKE_library.h */
151
152 /* IDRemap->status */
153 enum {
154         /* *** Set by callback. *** */
155         ID_REMAP_IS_LINKED_DIRECT       = 1 << 0,  /* new_id is directly linked in current .blend. */
156         ID_REMAP_IS_USER_ONE_SKIPPED    = 1 << 1,  /* There was some skipped 'user_one' usages of old_id. */
157 };
158
159 static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id_p, int cb_flag)
160 {
161         if (cb_flag & IDWALK_CB_PRIVATE) {
162                 return IDWALK_RET_NOP;
163         }
164
165         IDRemap *id_remap_data = user_data;
166         ID *old_id = id_remap_data->old_id;
167         ID *new_id = id_remap_data->new_id;
168         ID *id = id_remap_data->id;
169
170         if (!old_id) {  /* Used to cleanup all IDs used by a specific one. */
171                 BLI_assert(!new_id);
172                 old_id = *id_p;
173         }
174
175         if (*id_p && (*id_p == old_id)) {
176                 const bool is_indirect = (cb_flag & IDWALK_CB_INDIRECT_USAGE) != 0;
177                 const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
178                 /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct,
179                  *       on the other hand since they get reset to lib data on file open/reload it is indirect too...
180                  *       Edit Mode is also a 'skip direct' case. */
181                 const bool is_obj = (GS(id->name) == ID_OB);
182                 const bool is_obj_proxy = (is_obj && (((Object *)id)->proxy || ((Object *)id)->proxy_group));
183                 const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id));
184                 const bool is_never_null = ((cb_flag & IDWALK_CB_NEVER_NULL) && (new_id == NULL) &&
185                                             (id_remap_data->flag & ID_REMAP_FORCE_NEVER_NULL_USAGE) == 0);
186                 const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0;
187
188 #ifdef DEBUG_PRINT
189                 printf("In %s: Remapping %s (%p) to %s (%p) (skip_indirect: %d)\n",
190                        id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, skip_indirect);
191 #endif
192
193                 if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_CB_NEVER_NULL)) {
194                         id->tag |= LIB_TAG_DOIT;
195                 }
196
197                 /* Special hack in case it's Object->data and we are in edit mode (skipped_direct too). */
198                 if ((is_never_null && skip_never_null) ||
199                     (is_obj_editmode && (((Object *)id)->data == *id_p)) ||
200                     (skip_indirect && is_indirect))
201                 {
202                         if (is_indirect) {
203                                 id_remap_data->skipped_indirect++;
204                         }
205                         else if (is_never_null || is_obj_editmode) {
206                                 id_remap_data->skipped_direct++;
207                         }
208                         else {
209                                 BLI_assert(0);
210                         }
211                         if (cb_flag & IDWALK_CB_USER) {
212                                 id_remap_data->skipped_refcounted++;
213                         }
214                         else if (cb_flag & IDWALK_CB_USER_ONE) {
215                                 /* No need to count number of times this happens, just a flag is enough. */
216                                 id_remap_data->status |= ID_REMAP_IS_USER_ONE_SKIPPED;
217                         }
218                 }
219                 else {
220                         if (!is_never_null) {
221                                 *id_p = new_id;
222                                 DAG_id_tag_update_ex(id_remap_data->bmain, id_self, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
223                         }
224                         if (cb_flag & IDWALK_CB_USER) {
225                                 id_us_min(old_id);
226                                 /* We do not want to handle LIB_TAG_INDIRECT/LIB_TAG_EXTERN here. */
227                                 if (new_id)
228                                         new_id->us++;
229                         }
230                         else if (cb_flag & IDWALK_CB_USER_ONE) {
231                                 id_us_ensure_real(new_id);
232                                 /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed,
233                                  * that extra user is processed in final handling... */
234                         }
235                         if (!is_indirect || is_obj_proxy) {
236                                 id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
237                         }
238                 }
239         }
240
241         return IDWALK_RET_NOP;
242 }
243
244 /* Some remapping unfortunately require extra and/or specific handling, tackle those here. */
245 static void libblock_remap_data_preprocess_scene_base_unlink(
246         IDRemap *r_id_remap_data, Scene *sce, Base *base, const bool skip_indirect, const bool is_indirect)
247 {
248         if (skip_indirect && is_indirect) {
249                 r_id_remap_data->skipped_indirect++;
250                 r_id_remap_data->skipped_refcounted++;
251         }
252         else {
253                 id_us_min((ID *)base->object);
254                 BKE_scene_base_unlink(sce, base);
255                 MEM_freeN(base);
256                 if (!is_indirect) {
257                         r_id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
258                 }
259         }
260 }
261
262 static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
263 {
264         switch (GS(r_id_remap_data->id->name)) {
265                 case ID_SCE:
266                 {
267                         Scene *sce = (Scene *)r_id_remap_data->id;
268
269                         if (!r_id_remap_data->new_id) {
270                                 const bool is_indirect = (sce->id.lib != NULL);
271                                 const bool skip_indirect = (r_id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
272
273                                 /* In case we are unlinking... */
274                                 if (!r_id_remap_data->old_id) {
275                                         /* ... everything from scene. */
276                                         Base *base, *base_next;
277                                         for (base = sce->base.first; base; base = base_next) {
278                                                 base_next = base->next;
279                                                 libblock_remap_data_preprocess_scene_base_unlink(
280                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
281                                         }
282                                 }
283                                 else if (GS(r_id_remap_data->old_id->name) == ID_OB) {
284                                         /* ... a specific object from scene. */
285                                         Object *old_ob = (Object *)r_id_remap_data->old_id;
286                                         Base *base = BKE_scene_base_find(sce, old_ob);
287
288                                         if (base) {
289                                                 libblock_remap_data_preprocess_scene_base_unlink(
290                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
291                                         }
292                                 }
293                         }
294                         break;
295                 }
296                 case ID_OB:
297                 {
298                         ID *old_id = r_id_remap_data->old_id;
299                         if (!old_id || GS(old_id->name) == ID_AR) {
300                                 Object *ob = (Object *)r_id_remap_data->id;
301                                 /* Object's pose holds reference to armature bones... sic */
302                                 /* Note that in theory, we should have to bother about linked/non-linked/never-null/etc. flags/states.
303                                  * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, and avoid
304                                  * another complex and risky condition nightmare like the one we have in
305                                  * foreach_libblock_remap_callback()... */
306                                 if (ob->pose && (!old_id || ob->data == old_id)) {
307                                         BLI_assert(ob->type == OB_ARMATURE);
308                                         ob->pose->flag |= POSE_RECALC;
309                                         /* We need to clear pose bone pointers immediately, things like undo writefile may be called
310                                          * before pose is actually recomputed, can lead to segfault... */
311                                         BKE_pose_clear_pointers(ob->pose);
312                                 }
313                         }
314                         break;
315                 }
316                 default:
317                         break;
318         }
319 }
320
321 static void libblock_remap_data_postprocess_object_update(Main *bmain, Object *old_ob, Object *new_ob)
322 {
323         if (old_ob->flag & OB_FROMGROUP) {
324                 /* Note that for Scene's BaseObject->flag, either we:
325                  *     - unlinked old_ob (i.e. new_ob is NULL), in which case scenes' bases have been removed already.
326                  *     - remapped old_ob by new_ob, in which case scenes' bases are still valid as is.
327                  * So in any case, no need to update them here. */
328                 if (BKE_group_object_find(NULL, old_ob) == NULL) {
329                         old_ob->flag &= ~OB_FROMGROUP;
330                 }
331                 if (new_ob == NULL) {  /* We need to remove NULL-ified groupobjects... */
332                         for (Group *group = bmain->group.first; group; group = group->id.next) {
333                                 BKE_group_object_unlink(group, NULL, NULL, NULL);
334                         }
335                 }
336                 else {
337                         new_ob->flag |= OB_FROMGROUP;
338                 }
339         }
340         if (old_ob->type == OB_MBALL) {
341                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
342                         if (ob->type == OB_MBALL && BKE_mball_is_basis_for(ob, old_ob)) {
343                                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
344                         }
345                 }
346         }
347 }
348
349 static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id)
350 {
351         /* Note that here we assume no object has no base (i.e. all objects are assumed instanced
352          * in one scene...). */
353         for (Base *base = sce->base.first; base; base = base->next) {
354                 if (base->flag & OB_FROMGROUP) {
355                         Object *ob = base->object;
356
357                         if (ob->flag & OB_FROMGROUP) {
358                                 Group *grp = BKE_group_object_find(NULL, ob);
359
360                                 /* Unlinked group (old_id) is still in bmain... */
361                                 if (grp && (&grp->id == old_id || grp->id.us == 0)) {
362                                         grp = BKE_group_object_find(grp, ob);
363                                 }
364                                 if (!grp) {
365                                         ob->flag &= ~OB_FROMGROUP;
366                                 }
367                         }
368                         if (!(ob->flag & OB_FROMGROUP)) {
369                                 base->flag &= ~OB_FROMGROUP;
370                         }
371                 }
372         }
373 }
374
375 static void libblock_remap_data_postprocess_obdata_relink(Main *UNUSED(bmain), Object *ob, ID *new_id)
376 {
377         if (ob->data == new_id) {
378                 switch (GS(new_id->name)) {
379                         case ID_ME:
380                                 multires_force_update(ob);
381                                 break;
382                         case ID_CU:
383                                 BKE_curve_type_test(ob);
384                                 break;
385                         default:
386                                 break;
387                 }
388                 test_object_modifiers(ob);
389                 test_object_materials(ob, new_id);
390         }
391 }
392
393 static void libblock_remap_data_postprocess_nodetree_update(Main *bmain, ID *new_id)
394 {
395         /* Verify all nodetree user nodes. */
396         ntreeVerifyNodes(bmain, new_id);
397
398         /* Update node trees as necessary. */
399         FOREACH_NODETREE(bmain, ntree, id) {
400                 /* make an update call for the tree */
401                 ntreeUpdateTree(bmain, ntree);
402         } FOREACH_NODETREE_END
403 }
404
405 /**
406  * Execute the 'data' part of the remapping (that is, all ID pointers from other ID datablocks).
407  *
408  * Behavior differs depending on whether given \a id is NULL or not:
409  * - \a id NULL: \a old_id must be non-NULL, \a new_id may be NULL (unlinking \a old_id) or not
410  *   (remapping \a old_id to \a new_id). The whole \a bmain database is checked, and all pointers to \a old_id
411  *   are remapped to \a new_id.
412  * - \a id is non-NULL:
413  *   + If \a old_id is NULL, \a new_id must also be NULL, and all ID pointers from \a id are cleared (i.e. \a id
414  *     does not references any other datablock anymore).
415  *   + If \a old_id is non-NULL, behavior is as with a NULL \a id, but only within given \a id.
416  *
417  * \param bmain: the Main data storage to operate on (must never be NULL).
418  * \param id: the datablock to operate on (can be NULL, in which case we operate over all IDs from given bmain).
419  * \param old_id: the datablock to dereference (may be NULL if \a id is non-NULL).
420  * \param new_id: the new datablock to replace \a old_id references with (may be NULL).
421  * \param r_id_remap_data: if non-NULL, the IDRemap struct to use (uselful to retrieve info about remapping process).
422  */
423 ATTR_NONNULL(1) static void libblock_remap_data(
424         Main *bmain, ID *id, ID *old_id, ID *new_id, const short remap_flags, IDRemap *r_id_remap_data)
425 {
426         IDRemap id_remap_data;
427         ListBase *lb_array[MAX_LIBARRAY];
428         int i;
429         const int foreach_id_flags = (remap_flags & ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE) != 0 ? IDWALK_NO_INDIRECT_PROXY_DATA_USAGE : IDWALK_NOP;
430
431         if (r_id_remap_data == NULL) {
432                 r_id_remap_data = &id_remap_data;
433         }
434         r_id_remap_data->bmain = bmain;
435         r_id_remap_data->old_id = old_id;
436         r_id_remap_data->new_id = new_id;
437         r_id_remap_data->id = NULL;
438         r_id_remap_data->flag = remap_flags;
439         r_id_remap_data->status = 0;
440         r_id_remap_data->skipped_direct = 0;
441         r_id_remap_data->skipped_indirect = 0;
442         r_id_remap_data->skipped_refcounted = 0;
443
444         if (id) {
445 #ifdef DEBUG_PRINT
446                 printf("\tchecking id %s (%p, %p)\n", id->name, id, id->lib);
447 #endif
448                 r_id_remap_data->id = id;
449                 libblock_remap_data_preprocess(r_id_remap_data);
450                 BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
451         }
452         else {
453                 i = set_listbasepointers(bmain, lb_array);
454
455                 /* Note that this is a very 'bruteforce' approach, maybe we could use some depsgraph to only process
456                  * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
457
458                 while (i--) {
459                         for (ID *id_curr = lb_array[i]->first; id_curr; id_curr = id_curr->next) {
460                                 if (BKE_library_id_can_use_idtype(id_curr, GS(old_id->name))) {
461                                         /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
462                                          * the user count handling...
463                                          * XXX No more true (except for debug usage of those skipping counters). */
464                                         r_id_remap_data->id = id_curr;
465                                         libblock_remap_data_preprocess(r_id_remap_data);
466                                         BKE_library_foreach_ID_link(
467                                                     NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
468                                 }
469                         }
470                 }
471         }
472
473         if (old_id && GS(old_id->name) == ID_OB) {
474                 BKE_sca_logic_links_remap(bmain, (Object *)old_id, (Object *)new_id);
475         }
476
477         /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior
478          *     though, we can always add an option (flag) to control this later if needed. */
479         if (old_id && (old_id->flag & LIB_FAKEUSER)) {
480                 id_fake_user_clear(old_id);
481                 id_fake_user_set(new_id);
482         }
483
484         id_us_clear_real(old_id);
485
486         if (new_id && (new_id->tag & LIB_TAG_INDIRECT) && (r_id_remap_data->status & ID_REMAP_IS_LINKED_DIRECT)) {
487                 new_id->tag &= ~LIB_TAG_INDIRECT;
488                 new_id->tag |= LIB_TAG_EXTERN;
489         }
490
491 #ifdef DEBUG_PRINT
492         printf("%s: %d occurences skipped (%d direct and %d indirect ones)\n", __func__,
493                r_id_remap_data->skipped_direct + r_id_remap_data->skipped_indirect,
494                r_id_remap_data->skipped_direct, r_id_remap_data->skipped_indirect);
495 #endif
496 }
497
498 /**
499  * Replace all references in given Main to \a old_id by \a new_id
500  * (if \a new_id is NULL, it unlinks \a old_id).
501  */
502 void BKE_libblock_remap_locked(
503         Main *bmain, void *old_idv, void *new_idv,
504         const short remap_flags)
505 {
506         IDRemap id_remap_data;
507         ID *old_id = old_idv;
508         ID *new_id = new_idv;
509         int skipped_direct, skipped_refcounted;
510
511         BLI_assert(old_id != NULL);
512         BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
513         BLI_assert(old_id != new_id);
514
515         libblock_remap_data(bmain, NULL, old_id, new_id, remap_flags, &id_remap_data);
516
517         if (free_notifier_reference_cb) {
518                 free_notifier_reference_cb(old_id);
519         }
520
521         /* We assume editors do not hold references to their IDs... This is false in some cases
522          * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */
523         if (remap_editor_id_reference_cb) {
524                 remap_editor_id_reference_cb(old_id, new_id);
525         }
526
527         skipped_direct = id_remap_data.skipped_direct;
528         skipped_refcounted = id_remap_data.skipped_refcounted;
529
530         /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually
531          * been incremented for that, we have to decrease once more its user count... unless we had to skip
532          * some 'user_one' cases. */
533         if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) {
534                 id_us_clear_real(old_id);
535         }
536
537         if (old_id->us - skipped_refcounted < 0) {
538                 printf("Error in remapping process from '%s' (%p) to '%s' (%p): "
539                        "wrong user count in old ID after process (summing up to %d)\n",
540                        old_id->name, old_id, new_id ? new_id->name : "<NULL>", new_id, old_id->us - skipped_refcounted);
541                 BLI_assert(0);
542         }
543
544         if (skipped_direct == 0) {
545                 /* old_id is assumed to not be used directly anymore... */
546                 if (old_id->lib && (old_id->tag & LIB_TAG_EXTERN)) {
547                         old_id->tag &= ~LIB_TAG_EXTERN;
548                         old_id->tag |= LIB_TAG_INDIRECT;
549                 }
550         }
551
552         /* Some after-process updates.
553          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
554          */
555         switch (GS(old_id->name)) {
556                 case ID_OB:
557                         libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id);
558                         break;
559                 case ID_GR:
560                         if (!new_id) {  /* Only affects us in case group was unlinked. */
561                                 for (Scene *sce = bmain->scene.first; sce; sce = sce->id.next) {
562                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
563                                 }
564                         }
565                         break;
566                 case ID_ME:
567                 case ID_CU:
568                 case ID_MB:
569                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
570                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
571                                         libblock_remap_data_postprocess_obdata_relink(bmain, ob, new_id);
572                                 }
573                         }
574                         break;
575                 default:
576                         break;
577         }
578
579         /* Node trees may virtually use any kind of data-block... */
580         /* XXX Yuck!!!! nodetree update can do pretty much any thing when talking about py nodes,
581          *     including creating new data-blocks (see T50385), so we need to unlock main here. :(
582          *     Why can't we have re-entrent locks? */
583         BKE_main_unlock(bmain);
584         libblock_remap_data_postprocess_nodetree_update(bmain, new_id);
585         BKE_main_lock(bmain);
586
587         /* Full rebuild of DAG! */
588         DAG_relations_tag_update(bmain);
589 }
590
591 void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short remap_flags)
592 {
593         BKE_main_lock(bmain);
594
595         BKE_libblock_remap_locked(bmain, old_idv, new_idv, remap_flags);
596
597         BKE_main_unlock(bmain);
598 }
599
600 /**
601  * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID).
602  *
603  * \param do_flag_never_null: If true, all IDs using \a idv in a 'non-NULL' way are flagged by \a LIB_TAG_DOIT flag
604  * (quite obviously, 'non-NULL' usages can never be unlinked by this function...).
605  */
606 void BKE_libblock_unlink(Main *bmain, void *idv, const bool do_flag_never_null, const bool do_skip_indirect)
607 {
608         const short remap_flags = (do_skip_indirect ? ID_REMAP_SKIP_INDIRECT_USAGE : 0) |
609                                   (do_flag_never_null ? ID_REMAP_FLAG_NEVER_NULL_USAGE : 0);
610
611         BKE_main_lock(bmain);
612
613         BKE_libblock_remap_locked(bmain, idv, NULL, remap_flags);
614
615         BKE_main_unlock(bmain);
616 }
617
618 /** Similar to libblock_remap, but only affects IDs used by given \a idv ID.
619  *
620  * \param old_idv: Unlike BKE_libblock_remap, can be NULL,
621  * in which case all ID usages by given \a idv will be cleared.
622  * \param us_min_never_null: If \a true and new_id is NULL,
623  * 'NEVER_NULL' ID usages keep their old id, but this one still gets its user count decremented
624  * (needed when given \a idv is going to be deleted right after being unlinked).
625  */
626 /* Should be able to replace all _relink() funcs (constraints, rigidbody, etc.) ? */
627 /* XXX Arg! Naming... :(
628  *     _relink? avoids confusion with _remap, but is confusing with _unlink
629  *     _remap_used_ids?
630  *     _remap_datablocks?
631  *     BKE_id_remap maybe?
632  *     ... sigh
633  */
634 void BKE_libblock_relink_ex(
635         Main *bmain, void *idv, void *old_idv, void *new_idv, const bool us_min_never_null)
636 {
637         ID *id = idv;
638         ID *old_id = old_idv;
639         ID *new_id = new_idv;
640         int remap_flags = us_min_never_null ? 0 : ID_REMAP_SKIP_NEVER_NULL_USAGE;
641
642         /* No need to lock here, we are only affecting given ID, not bmain database. */
643
644         BLI_assert(id);
645         if (old_id) {
646                 BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
647                 BLI_assert(old_id != new_id);
648         }
649         else {
650                 BLI_assert(new_id == NULL);
651         }
652
653         libblock_remap_data(bmain, id, old_id, new_id, remap_flags, NULL);
654
655         /* Some after-process updates.
656          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
657          */
658         switch (GS(id->name)) {
659                 case ID_SCE:
660                 {
661                         Scene *sce = (Scene *)id;
662
663                         if (old_id) {
664                                 switch (GS(old_id->name)) {
665                                         case ID_OB:
666                                         {
667                                                 libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id);
668                                                 break;
669                                         }
670                                         case ID_GR:
671                                                 if (!new_id) {  /* Only affects us in case group was unlinked. */
672                                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
673                                                 }
674                                                 break;
675                                         default:
676                                                 break;
677                                 }
678                         }
679                         else {
680                                 /* No choice but to check whole objects/groups. */
681                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
682                                         libblock_remap_data_postprocess_object_update(bmain, ob, NULL);
683                                 }
684                                 for (Group *grp = bmain->group.first; grp; grp = grp->id.next) {
685                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL);
686                                 }
687                         }
688                         break;
689                 }
690                 case ID_OB:
691                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
692                                 libblock_remap_data_postprocess_obdata_relink(bmain, (Object *)id, new_id);
693                         }
694                         break;
695                 default:
696                         break;
697         }
698 }
699
700 static int id_relink_to_newid_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cb_flag)
701 {
702         if (cb_flag & IDWALK_CB_PRIVATE) {
703                 return IDWALK_RET_NOP;
704         }
705
706         ID *id = *id_pointer;
707         if (id) {
708                 /* See: NEW_ID macro */
709                 if (id->newid) {
710                         BKE_library_update_ID_link_user(id->newid, id, cb_flag);
711                         *id_pointer = id->newid;
712                 }
713                 else if (id->tag & LIB_TAG_NEW) {
714                         id->tag &= ~LIB_TAG_NEW;
715                         BKE_libblock_relink_to_newid(id);
716                 }
717         }
718         return IDWALK_RET_NOP;
719 }
720
721 /** Similar to libblock_relink_ex, but is remapping IDs to their newid value if non-NULL, in given \a id.
722  *
723  * Very specific usage, not sure we'll keep it on the long run, currently only used in Object duplication code...
724  */
725 void BKE_libblock_relink_to_newid(ID *id)
726 {
727         if (ID_IS_LINKED_DATABLOCK(id))
728                 return;
729
730         BKE_library_foreach_ID_link(NULL, id, id_relink_to_newid_looper, NULL, 0);
731 }
732
733 void BKE_libblock_free_data(ID *id, const bool do_id_user)
734 {
735         if (id->properties) {
736                 IDP_FreeProperty_ex(id->properties, do_id_user);
737                 MEM_freeN(id->properties);
738         }
739
740         /* XXX TODO remove animdata handling from each type's freeing func, and do it here, like for copy! */
741 }
742
743 void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag))
744 {
745         const short type = GS(id->name);
746         switch (type) {
747                 case ID_SCE:
748                         BKE_scene_free((Scene *)id);
749                         break;
750                 case ID_LI:
751                         BKE_library_free((Library *)id);
752                         break;
753                 case ID_OB:
754                         BKE_object_free((Object *)id);
755                         break;
756                 case ID_ME:
757                         BKE_mesh_free((Mesh *)id);
758                         break;
759                 case ID_CU:
760                         BKE_curve_free((Curve *)id);
761                         break;
762                 case ID_MB:
763                         BKE_mball_free((MetaBall *)id);
764                         break;
765                 case ID_MA:
766                         BKE_material_free((Material *)id);
767                         break;
768                 case ID_TE:
769                         BKE_texture_free((Tex *)id);
770                         break;
771                 case ID_IM:
772                         BKE_image_free((Image *)id);
773                         break;
774                 case ID_LT:
775                         BKE_lattice_free((Lattice *)id);
776                         break;
777                 case ID_LA:
778                         BKE_lamp_free((Lamp *)id);
779                         break;
780                 case ID_CA:
781                         BKE_camera_free((Camera *) id);
782                         break;
783                 case ID_IP:  /* Deprecated. */
784                         BKE_ipo_free((Ipo *)id);
785                         break;
786                 case ID_KE:
787                         BKE_key_free((Key *)id);
788                         break;
789                 case ID_WO:
790                         BKE_world_free((World *)id);
791                         break;
792                 case ID_SCR:
793                         BKE_screen_free((bScreen *)id);
794                         break;
795                 case ID_VF:
796                         BKE_vfont_free((VFont *)id);
797                         break;
798                 case ID_TXT:
799                         BKE_text_free((Text *)id);
800                         break;
801                 case ID_SPK:
802                         BKE_speaker_free((Speaker *)id);
803                         break;
804                 case ID_SO:
805                         BKE_sound_free((bSound *)id);
806                         break;
807                 case ID_GR:
808                         BKE_group_free((Group *)id);
809                         break;
810                 case ID_AR:
811                         BKE_armature_free((bArmature *)id);
812                         break;
813                 case ID_AC:
814                         BKE_action_free((bAction *)id);
815                         break;
816                 case ID_NT:
817                         ntreeFreeTree((bNodeTree *)id);
818                         break;
819                 case ID_BR:
820                         BKE_brush_free((Brush *)id);
821                         break;
822                 case ID_PA:
823                         BKE_particlesettings_free((ParticleSettings *)id);
824                         break;
825                 case ID_WM:
826                         if (free_windowmanager_cb)
827                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
828                         break;
829                 case ID_GD:
830                         BKE_gpencil_free((bGPdata *)id, true);
831                         break;
832                 case ID_MC:
833                         BKE_movieclip_free((MovieClip *)id);
834                         break;
835                 case ID_MSK:
836                         BKE_mask_free((Mask *)id);
837                         break;
838                 case ID_LS:
839                         BKE_linestyle_free((FreestyleLineStyle *)id);
840                         break;
841                 case ID_PAL:
842                         BKE_palette_free((Palette *)id);
843                         break;
844                 case ID_PC:
845                         BKE_paint_curve_free((PaintCurve *)id);
846                         break;
847                 case ID_CF:
848                         BKE_cachefile_free((CacheFile *)id);
849                         break;
850         }
851 }
852
853
854 void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_idtag)
855 {
856         ID *id = idv;
857
858         if (use_flag_from_idtag) {
859                 if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
860                         flag |= LIB_ID_FREE_NO_MAIN;
861                 }
862                 else {
863                         flag &= ~LIB_ID_FREE_NO_MAIN;
864                 }
865
866                 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
867                         flag |= LIB_ID_FREE_NO_USER_REFCOUNT;
868                 }
869                 else {
870                         flag &= ~LIB_ID_FREE_NO_USER_REFCOUNT;
871                 }
872
873                 if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
874                         flag |= LIB_ID_FREE_NOT_ALLOCATED;
875                 }
876                 else {
877                         flag &= ~LIB_ID_FREE_NOT_ALLOCATED;
878                 }
879         }
880
881         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || bmain != NULL);
882         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NOT_ALLOCATED) == 0);
883         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
884
885         const short type = GS(id->name);
886
887         if (bmain && (flag & LIB_ID_FREE_NO_DEG_TAG) == 0) {
888                 DAG_id_type_tag(bmain, type);
889         }
890
891 #ifdef WITH_PYTHON
892         BPY_id_release(id);
893 #endif
894
895         if ((flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0) {
896                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
897         }
898
899         BKE_libblock_free_datablock(id, flag);
900
901         /* avoid notifying on removed data */
902         if (bmain) {
903                 BKE_main_lock(bmain);
904         }
905
906         if ((flag & LIB_ID_FREE_NO_UI_USER) == 0) {
907                 if (free_notifier_reference_cb) {
908                         free_notifier_reference_cb(id);
909                 }
910
911                 if (remap_editor_id_reference_cb) {
912                         remap_editor_id_reference_cb(id, NULL);
913                 }
914         }
915
916         if ((flag & LIB_ID_FREE_NO_MAIN) == 0) {
917                 ListBase *lb = which_libbase(bmain, type);
918                 BLI_remlink(lb, id);
919         }
920
921         BKE_libblock_free_data(id, (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
922
923         if (bmain) {
924                 BKE_main_unlock(bmain);
925         }
926
927         if ((flag & LIB_ID_FREE_NOT_ALLOCATED) == 0) {
928                 MEM_freeN(id);
929         }
930 }
931
932 void BKE_id_free(Main *bmain, void *idv)
933 {
934         BKE_id_free_ex(bmain, idv, 0, true);
935 }
936
937 /**
938  * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
939  *
940  * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
941  *                    (only applies to main database)
942  * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to
943  *                    \a id.
944  */
945 void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user)
946 {
947         ID *id = idv;
948         short type = GS(id->name);
949         ListBase *lb = which_libbase(bmain, type);
950
951         DAG_id_type_tag(bmain, type);
952
953 #ifdef WITH_PYTHON
954         BPY_id_release(id);
955 #endif
956
957         if (do_id_user) {
958                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
959         }
960
961         BKE_libblock_free_datablock(id, 0);
962
963         /* avoid notifying on removed data */
964         BKE_main_lock(bmain);
965
966         if (do_ui_user) {
967                 if (free_notifier_reference_cb) {
968                         free_notifier_reference_cb(id);
969                 }
970
971                 if (remap_editor_id_reference_cb) {
972                         remap_editor_id_reference_cb(id, NULL);
973                 }
974         }
975
976         BLI_remlink(lb, id);
977
978         BKE_libblock_free_data(id, do_id_user);
979         BKE_main_unlock(bmain);
980
981         MEM_freeN(id);
982 }
983
984 void BKE_libblock_free(Main *bmain, void *idv)
985 {
986         BKE_libblock_free_ex(bmain, idv, true, true);
987 }
988
989 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
990 {
991         ID *id = idv;
992         
993         id_us_min(id);
994
995         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
996          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
997          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
998          *     fully unlinked.
999          *     But only for local objects, not linked ones!
1000          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
1001          */
1002         if ((GS(id->name) == ID_OB) && (id->us == 1) && (id->lib == NULL)) {
1003                 id_us_clear_real(id);
1004         }
1005
1006         if (id->us == 0) {
1007                 BKE_libblock_unlink(bmain, id, false, false);
1008                 
1009                 BKE_libblock_free(bmain, id);
1010         }
1011 }
1012
1013 void BKE_libblock_delete(Main *bmain, void *idv)
1014 {
1015         ListBase *lbarray[MAX_LIBARRAY];
1016         int base_count, i;
1017
1018         base_count = set_listbasepointers(bmain, lbarray);
1019         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
1020
1021         /* First tag all datablocks directly from target lib.
1022          * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
1023          * Avoids to have to loop twice. */
1024         for (i = 0; i < base_count; i++) {
1025                 ListBase *lb = lbarray[i];
1026                 ID *id;
1027
1028                 for (id = lb->first; id; id = id->next) {
1029                         /* Note: in case we delete a library, we also delete all its datablocks! */
1030                         if ((id == (ID *)idv) || (id->lib == (Library *)idv) || (id->tag & LIB_TAG_DOIT)) {
1031                                 id->tag |= LIB_TAG_DOIT;
1032                                 /* Will tag 'never NULL' users of this ID too.
1033                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
1034                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
1035                                  * Also, this will also flag users of deleted data that cannot be unlinked
1036                                  * (object using deleted obdata, etc.), so that they also get deleted. */
1037                                 BKE_libblock_remap(bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
1038                         }
1039                 }
1040         }
1041
1042         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
1043          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
1044          * over meshes when we come to freeing obdata). */
1045         for (i = base_count; i--; ) {
1046                 ListBase *lb = lbarray[i];
1047                 ID *id, *id_next;
1048
1049                 for (id = lb->first; id; id = id_next) {
1050                         id_next = id->next;
1051                         if (id->tag & LIB_TAG_DOIT) {
1052                                 if (id->us != 0) {
1053 #ifdef DEBUG_PRINT
1054                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
1055 #endif
1056                                         BLI_assert(id->us == 0);
1057                                 }
1058                                 BKE_libblock_free(bmain, id);
1059                         }
1060                 }
1061         }
1062 }