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