Merge branch 'master' into blender2.8
[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_sca.h"
102 #include "BKE_speaker.h"
103 #include "BKE_sound.h"
104 #include "BKE_screen.h"
105 #include "BKE_scene.h"
106 #include "BKE_text.h"
107 #include "BKE_texture.h"
108 #include "BKE_world.h"
109
110 #ifdef WITH_PYTHON
111 #include "BPY_extern.h"
112 #endif
113
114 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
115
116 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
117 {
118         free_windowmanager_cb = func;
119 }
120
121 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
122
123 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
124 {
125         free_notifier_reference_cb = func;
126 }
127
128 static BKE_library_remap_editor_id_reference_cb remap_editor_id_reference_cb = NULL;
129
130 void BKE_library_callback_remap_editor_id_reference_set(BKE_library_remap_editor_id_reference_cb func)
131 {
132         remap_editor_id_reference_cb = func;
133 }
134
135 typedef struct IDRemap {
136         Main *bmain;  /* Only used to trigger depsgraph updates in the right bmain. */
137         ID *old_id;
138         ID *new_id;
139         ID *id;  /* The ID in which we are replacing old_id by new_id usages. */
140         short flag;
141
142         /* 'Output' data. */
143         short status;
144         int skipped_direct;  /* Number of direct usecases that could not be remapped (e.g.: obdata when in edit mode). */
145         int skipped_indirect;  /* Number of indirect usecases that could not be remapped. */
146         int skipped_refcounted;  /* Number of skipped usecases that refcount the datablock. */
147 } IDRemap;
148
149 /* IDRemap->flag enums defined in BKE_library.h */
150
151 /* IDRemap->status */
152 enum {
153         /* *** Set by callback. *** */
154         ID_REMAP_IS_LINKED_DIRECT       = 1 << 0,  /* new_id is directly linked in current .blend. */
155         ID_REMAP_IS_USER_ONE_SKIPPED    = 1 << 1,  /* There was some skipped 'user_one' usages of old_id. */
156 };
157
158 static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id_p, int cb_flag)
159 {
160         IDRemap *id_remap_data = user_data;
161         ID *old_id = id_remap_data->old_id;
162         ID *new_id = id_remap_data->new_id;
163         ID *id = id_remap_data->id;
164
165         if (!old_id) {  /* Used to cleanup all IDs used by a specific one. */
166                 BLI_assert(!new_id);
167                 old_id = *id_p;
168         }
169
170         if (*id_p && (*id_p == old_id)) {
171                 const bool is_indirect = (cb_flag & IDWALK_INDIRECT_USAGE) != 0;
172                 const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
173                 /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct,
174                  *       on the other hand since they get reset to lib data on file open/reload it is indirect too...
175                  *       Edit Mode is also a 'skip direct' case. */
176                 const bool is_obj = (GS(id->name) == ID_OB);
177                 const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id));
178                 const bool is_never_null = ((cb_flag & IDWALK_NEVER_NULL) && (new_id == NULL) &&
179                                             (id_remap_data->flag & ID_REMAP_FORCE_NEVER_NULL_USAGE) == 0);
180                 const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0;
181
182 #ifdef DEBUG_PRINT
183                 printf("In %s: Remapping %s (%p) to %s (%p) (skip_indirect: %d)\n",
184                        id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, skip_indirect);
185 #endif
186
187                 if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_NEVER_NULL)) {
188                         id->tag |= LIB_TAG_DOIT;
189                 }
190
191                 /* Special hack in case it's Object->data and we are in edit mode (skipped_direct too). */
192                 if ((is_never_null && skip_never_null) ||
193                     (is_obj_editmode && (((Object *)id)->data == *id_p)) ||
194                     (skip_indirect && is_indirect))
195                 {
196                         if (is_indirect) {
197                                 id_remap_data->skipped_indirect++;
198                         }
199                         else if (is_never_null || is_obj_editmode) {
200                                 id_remap_data->skipped_direct++;
201                         }
202                         else {
203                                 BLI_assert(0);
204                         }
205                         if (cb_flag & IDWALK_USER) {
206                                 id_remap_data->skipped_refcounted++;
207                         }
208                         else if (cb_flag & IDWALK_USER_ONE) {
209                                 /* No need to count number of times this happens, just a flag is enough. */
210                                 id_remap_data->status |= ID_REMAP_IS_USER_ONE_SKIPPED;
211                         }
212                 }
213                 else {
214                         if (!is_never_null) {
215                                 *id_p = new_id;
216                                 DAG_id_tag_update_ex(id_remap_data->bmain, id_self, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
217                         }
218                         if (cb_flag & IDWALK_USER) {
219                                 id_us_min(old_id);
220                                 /* We do not want to handle LIB_TAG_INDIRECT/LIB_TAG_EXTERN here. */
221                                 if (new_id)
222                                         new_id->us++;
223                         }
224                         else if (cb_flag & IDWALK_USER_ONE) {
225                                 id_us_ensure_real(new_id);
226                                 /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed,
227                                  * that extra user is processed in final handling... */
228                         }
229                         if (!is_indirect) {
230                                 id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
231                         }
232                 }
233         }
234
235         return IDWALK_RET_NOP;
236 }
237
238 /* Some reamapping unfortunately require extra and/or specific handling, tackle those here. */
239 static void libblock_remap_data_preprocess_scene_base_unlink(
240         IDRemap *r_id_remap_data, Scene *sce, Base *base, const bool skip_indirect, const bool is_indirect)
241 {
242         if (skip_indirect && is_indirect) {
243                 r_id_remap_data->skipped_indirect++;
244                 r_id_remap_data->skipped_refcounted++;
245         }
246         else {
247                 id_us_min((ID *)base->object);
248                 BKE_scene_base_unlink(sce, base);
249                 MEM_freeN(base);
250                 if (!is_indirect) {
251                         r_id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
252                 }
253         }
254 }
255
256 static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
257 {
258         switch (GS(r_id_remap_data->id->name)) {
259                 case ID_SCE:
260                 {
261                         Scene *sce = (Scene *)r_id_remap_data->id;
262
263                         if (!r_id_remap_data->new_id) {
264                                 const bool is_indirect = (sce->id.lib != NULL);
265                                 const bool skip_indirect = (r_id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
266
267                                 /* In case we are unlinking... */
268                                 if (!r_id_remap_data->old_id) {
269                                         /* ... everything from scene. */
270                                         Base *base, *base_next;
271                                         for (base = sce->base.first; base; base = base_next) {
272                                                 base_next = base->next;
273                                                 libblock_remap_data_preprocess_scene_base_unlink(
274                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
275                                         }
276                                 }
277                                 else if (GS(r_id_remap_data->old_id->name) == ID_OB) {
278                                         /* ... a specific object from scene. */
279                                         Object *old_ob = (Object *)r_id_remap_data->old_id;
280                                         Base *base = BKE_scene_base_find(sce, old_ob);
281
282                                         if (base) {
283                                                 libblock_remap_data_preprocess_scene_base_unlink(
284                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
285                                         }
286                                 }
287                         }
288                         break;
289                 }
290                 case ID_OB:
291                 {
292                         ID *old_id = r_id_remap_data->old_id;
293                         if (!old_id || GS(old_id->name) == ID_AR) {
294                                 Object *ob = (Object *)r_id_remap_data->id;
295                                 /* Object's pose holds reference to armature bones... sic */
296                                 /* Note that in theory, we should have to bother about linked/non-linked/never-null/etc. flags/states.
297                                  * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, and avoid
298                                  * another complex and risky condition nightmare like the one we have in
299                                  * foreach_libblock_remap_callback()... */
300                                 if (ob->pose && (!old_id || ob->data == old_id)) {
301                                         BLI_assert(ob->type == OB_ARMATURE);
302                                         ob->pose->flag |= POSE_RECALC;
303                                         /* We need to clear pose bone pointers immediately, things like undo writefile may be called
304                                          * before pose is actually recomputed, can lead to segfault... */
305                                         BKE_pose_clear_pointers(ob->pose);
306                                 }
307                         }
308                         break;
309                 }
310                 default:
311                         break;
312         }
313 }
314
315 static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain, Object *old_ob, Object *new_ob)
316 {
317         if (old_ob->flag & OB_FROMGROUP) {
318                 /* Note that for Scene's BaseObject->flag, either we:
319                  *     - unlinked old_ob (i.e. new_ob is NULL), in which case scenes' bases have been removed already.
320                  *     - remapped old_ob by new_ob, in which case scenes' bases are still valid as is.
321                  * So in any case, no need to update them here. */
322                 if (BKE_group_object_find(NULL, old_ob) == NULL) {
323                         old_ob->flag &= ~OB_FROMGROUP;
324                 }
325                 if (new_ob == NULL) {  /* We need to remove NULL-ified groupobjects... */
326                         for (Group *group = bmain->group.first; group; group = group->id.next) {
327                                 BKE_group_object_unlink(group, NULL, NULL, NULL);
328                         }
329                 }
330                 else {
331                         new_ob->flag |= OB_FROMGROUP;
332                 }
333         }
334 }
335
336 static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id)
337 {
338         /* Note that here we assume no object has no base (i.e. all objects are assumed instanced
339          * in one scene...). */
340         for (Base *base = sce->base.first; base; base = base->next) {
341                 if (base->flag & OB_FROMGROUP) {
342                         Object *ob = base->object;
343
344                         if (ob->flag & OB_FROMGROUP) {
345                                 Group *grp = BKE_group_object_find(NULL, ob);
346
347                                 /* Unlinked group (old_id) is still in bmain... */
348                                 if (grp && (&grp->id == old_id || grp->id.us == 0)) {
349                                         grp = BKE_group_object_find(grp, ob);
350                                 }
351                                 if (!grp) {
352                                         ob->flag &= ~OB_FROMGROUP;
353                                 }
354                         }
355                         if (!(ob->flag & OB_FROMGROUP)) {
356                                 base->flag &= ~OB_FROMGROUP;
357                         }
358                 }
359         }
360 }
361
362 static void libblock_remap_data_postprocess_obdata_relink(Main *UNUSED(bmain), Object *ob, ID *new_id)
363 {
364         if (ob->data == new_id) {
365                 switch (GS(new_id->name)) {
366                         case ID_ME:
367                                 multires_force_update(ob);
368                                 break;
369                         case ID_CU:
370                                 BKE_curve_type_test(ob);
371                                 break;
372                         default:
373                                 break;
374                 }
375                 test_object_modifiers(ob);
376                 test_object_materials(ob, new_id);
377         }
378 }
379
380 static void libblock_remap_data_postprocess_nodetree_update(Main *bmain, ID *new_id)
381 {
382         /* Verify all nodetree user nodes. */
383         ntreeVerifyNodes(bmain, new_id);
384
385         /* Update node trees as necessary. */
386         FOREACH_NODETREE(bmain, ntree, id) {
387                 /* make an update call for the tree */
388                 ntreeUpdateTree(bmain, ntree);
389         } FOREACH_NODETREE_END
390 }
391
392 /**
393  * Execute the 'data' part of the remapping (that is, all ID pointers from other ID datablocks).
394  *
395  * Behavior differs depending on whether given \a id is NULL or not:
396  * - \a id NULL: \a old_id must be non-NULL, \a new_id may be NULL (unlinking \a old_id) or not
397  *   (remapping \a old_id to \a new_id). The whole \a bmain database is checked, and all pointers to \a old_id
398  *   are remapped to \a new_id.
399  * - \a id is non-NULL:
400  *   + 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
401  *     does not references any other datablock anymore).
402  *   + If \a old_id is non-NULL, behavior is as with a NULL \a id, but only within given \a id.
403  *
404  * \param bmain: the Main data storage to operate on (must never be NULL).
405  * \param id: the datablock to operate on (can be NULL, in which case we operate over all IDs from given bmain).
406  * \param old_id: the datablock to dereference (may be NULL if \a id is non-NULL).
407  * \param new_id: the new datablock to replace \a old_id references with (may be NULL).
408  * \param r_id_remap_data: if non-NULL, the IDRemap struct to use (uselful to retrieve info about remapping process).
409  */
410 ATTR_NONNULL(1) static void libblock_remap_data(
411         Main *bmain, ID *id, ID *old_id, ID *new_id, const short remap_flags, IDRemap *r_id_remap_data)
412 {
413         IDRemap id_remap_data;
414         ListBase *lb_array[MAX_LIBARRAY];
415         int i;
416
417         if (r_id_remap_data == NULL) {
418                 r_id_remap_data = &id_remap_data;
419         }
420         r_id_remap_data->bmain = bmain;
421         r_id_remap_data->old_id = old_id;
422         r_id_remap_data->new_id = new_id;
423         r_id_remap_data->id = NULL;
424         r_id_remap_data->flag = remap_flags;
425         r_id_remap_data->status = 0;
426         r_id_remap_data->skipped_direct = 0;
427         r_id_remap_data->skipped_indirect = 0;
428         r_id_remap_data->skipped_refcounted = 0;
429
430         if (id) {
431 #ifdef DEBUG_PRINT
432                 printf("\tchecking id %s (%p, %p)\n", id->name, id, id->lib);
433 #endif
434                 r_id_remap_data->id = id;
435                 libblock_remap_data_preprocess(r_id_remap_data);
436                 BKE_library_foreach_ID_link(id, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
437         }
438         else {
439                 i = set_listbasepointers(bmain, lb_array);
440
441                 /* Note that this is a very 'bruteforce' approach, maybe we could use some depsgraph to only process
442                  * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
443
444                 while (i--) {
445                         ID *id_curr = lb_array[i]->first;
446
447                         if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(old_id->name))) {
448                                 continue;
449                         }
450
451                         for (; id_curr; id_curr = id_curr->next) {
452                                 /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
453                                  * the user count handling...
454                                  * XXX No more true (except for debug usage of those skipping counters). */
455                                 r_id_remap_data->id = id_curr;
456                                 libblock_remap_data_preprocess(r_id_remap_data);
457                                 BKE_library_foreach_ID_link(
458                                             id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
459                         }
460                 }
461         }
462
463         if (old_id && GS(old_id->name) == ID_OB) {
464                 BKE_sca_logic_links_remap(bmain, (Object *)old_id, (Object *)new_id);
465         }
466
467         /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior
468          *     though, we can always add an option (flag) to control this later if needed. */
469         if (old_id && (old_id->flag & LIB_FAKEUSER)) {
470                 id_fake_user_clear(old_id);
471                 id_fake_user_set(new_id);
472         }
473
474         id_us_clear_real(old_id);
475
476         if (new_id && (new_id->tag & LIB_TAG_INDIRECT) && (r_id_remap_data->status & ID_REMAP_IS_LINKED_DIRECT)) {
477                 new_id->tag &= ~LIB_TAG_INDIRECT;
478                 new_id->tag |= LIB_TAG_EXTERN;
479         }
480
481 #ifdef DEBUG_PRINT
482         printf("%s: %d occurences skipped (%d direct and %d indirect ones)\n", __func__,
483                r_id_remap_data->skipped_direct + r_id_remap_data->skipped_indirect,
484                r_id_remap_data->skipped_direct, r_id_remap_data->skipped_indirect);
485 #endif
486 }
487
488 /**
489  * Replace all references in given Main to \a old_id by \a new_id
490  * (if \a new_id is NULL, it unlinks \a old_id).
491  */
492 void BKE_libblock_remap_locked(
493         Main *bmain, void *old_idv, void *new_idv,
494         const short remap_flags)
495 {
496         IDRemap id_remap_data;
497         ID *old_id = old_idv;
498         ID *new_id = new_idv;
499         int skipped_direct, skipped_refcounted;
500
501         BLI_assert(old_id != NULL);
502         BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
503         BLI_assert(old_id != new_id);
504
505         libblock_remap_data(bmain, NULL, old_id, new_id, remap_flags, &id_remap_data);
506
507         if (free_notifier_reference_cb) {
508                 free_notifier_reference_cb(old_id);
509         }
510
511         /* We assume editors do not hold references to their IDs... This is false in some cases
512          * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */
513         if (remap_editor_id_reference_cb) {
514                 remap_editor_id_reference_cb(old_id, new_id);
515         }
516
517         skipped_direct = id_remap_data.skipped_direct;
518         skipped_refcounted = id_remap_data.skipped_refcounted;
519
520         /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually
521          * been incremented for that, we have to decrease once more its user count... unless we had to skip
522          * some 'user_one' cases. */
523         if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) {
524                 id_us_min(old_id);
525                 old_id->tag &= ~LIB_TAG_EXTRAUSER_SET;
526         }
527
528         BLI_assert(old_id->us - skipped_refcounted >= 0);
529         UNUSED_VARS_NDEBUG(skipped_refcounted);
530
531         if (skipped_direct == 0) {
532                 /* old_id is assumed to not be used directly anymore... */
533                 if (old_id->lib && (old_id->tag & LIB_TAG_EXTERN)) {
534                         old_id->tag &= ~LIB_TAG_EXTERN;
535                         old_id->tag |= LIB_TAG_INDIRECT;
536                 }
537         }
538
539         /* Some after-process updates.
540          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
541          */
542         switch (GS(old_id->name)) {
543                 case ID_OB:
544                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, (Object *)old_id, (Object *)new_id);
545                         break;
546                 case ID_GR:
547                         if (!new_id) {  /* Only affects us in case group was unlinked. */
548                                 for (Scene *sce = bmain->scene.first; sce; sce = sce->id.next) {
549                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
550                                 }
551                         }
552                         break;
553                 case ID_ME:
554                 case ID_CU:
555                 case ID_MB:
556                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
557                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
558                                         libblock_remap_data_postprocess_obdata_relink(bmain, ob, new_id);
559                                 }
560                         }
561                         break;
562                 default:
563                         break;
564         }
565         /* Node trees may virtually use any kind of data-block... */
566         libblock_remap_data_postprocess_nodetree_update(bmain, new_id);
567
568         /* Full rebuild of DAG! */
569         DAG_relations_tag_update(bmain);
570 }
571
572 void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short remap_flags)
573 {
574         BKE_main_lock(bmain);
575
576         BKE_libblock_remap_locked(bmain, old_idv, new_idv, remap_flags);
577
578         BKE_main_unlock(bmain);
579 }
580
581 /**
582  * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID).
583  *
584  * \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
585  * (quite obviously, 'non-NULL' usages can never be unlinked by this function...).
586  */
587 void BKE_libblock_unlink(Main *bmain, void *idv, const bool do_flag_never_null, const bool do_skip_indirect)
588 {
589         const short remap_flags = (do_skip_indirect ? ID_REMAP_SKIP_INDIRECT_USAGE : 0) |
590                                   (do_flag_never_null ? ID_REMAP_FLAG_NEVER_NULL_USAGE : 0);
591
592         BKE_main_lock(bmain);
593
594         BKE_libblock_remap_locked(bmain, idv, NULL, remap_flags);
595
596         BKE_main_unlock(bmain);
597 }
598
599 /** Similar to libblock_remap, but only affects IDs used by given \a idv ID.
600  *
601  * \param old_idv: Unlike BKE_libblock_remap, can be NULL,
602  * in which case all ID usages by given \a idv will be cleared.
603  * \param us_min_never_null: If \a true and new_id is NULL,
604  * 'NEVER_NULL' ID usages keep their old id, but this one still gets its user count decremented
605  * (needed when given \a idv is going to be deleted right after being unlinked).
606  */
607 /* Should be able to replace all _relink() funcs (constraints, rigidbody, etc.) ? */
608 /* XXX Arg! Naming... :(
609  *     _relink? avoids confusion with _remap, but is confusing with _unlink
610  *     _remap_used_ids?
611  *     _remap_datablocks?
612  *     BKE_id_remap maybe?
613  *     ... sigh
614  */
615 void BKE_libblock_relink_ex(
616         Main *bmain, void *idv, void *old_idv, void *new_idv, const bool us_min_never_null)
617 {
618         ID *id = idv;
619         ID *old_id = old_idv;
620         ID *new_id = new_idv;
621         int remap_flags = us_min_never_null ? 0 : ID_REMAP_SKIP_NEVER_NULL_USAGE;
622
623         /* No need to lock here, we are only affecting given ID, not bmain database. */
624
625         BLI_assert(id);
626         if (old_id) {
627                 BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
628                 BLI_assert(old_id != new_id);
629         }
630         else {
631                 BLI_assert(new_id == NULL);
632         }
633
634         libblock_remap_data(bmain, id, old_id, new_id, remap_flags, NULL);
635
636         /* Some after-process updates.
637          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
638          */
639         switch (GS(id->name)) {
640                 case ID_SCE:
641                 {
642                         Scene *sce = (Scene *)id;
643
644                         if (old_id) {
645                                 switch (GS(old_id->name)) {
646                                         case ID_OB:
647                                         {
648                                                 libblock_remap_data_postprocess_object_fromgroup_update(
649                                                             bmain, (Object *)old_id, (Object *)new_id);
650                                                 break;
651                                         }
652                                         case ID_GR:
653                                                 if (!new_id) {  /* Only affects us in case group was unlinked. */
654                                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
655                                                 }
656                                                 break;
657                                         default:
658                                                 break;
659                                 }
660                         }
661                         else {
662                                 /* No choice but to check whole objects/groups. */
663                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
664                                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, ob, NULL);
665                                 }
666                                 for (Group *grp = bmain->group.first; grp; grp = grp->id.next) {
667                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL);
668                                 }
669                         }
670                         break;
671                 }
672                 case ID_OB:
673                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
674                                 libblock_remap_data_postprocess_obdata_relink(bmain, (Object *)id, new_id);
675                         }
676                         break;
677                 default:
678                         break;
679         }
680 }
681
682 void BKE_libblock_free_data(Main *UNUSED(bmain), ID *id)
683 {
684         if (id->properties) {
685                 IDP_FreeProperty(id->properties);
686                 MEM_freeN(id->properties);
687         }
688 }
689
690 /**
691  * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
692  *
693  * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
694  *                    (only applies to main database)
695  * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to
696  *                    \a id.
697  */
698 void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user)
699 {
700         ID *id = idv;
701         short type = GS(id->name);
702         ListBase *lb = which_libbase(bmain, type);
703
704         DAG_id_type_tag(bmain, type);
705
706 #ifdef WITH_PYTHON
707         BPY_id_release(id);
708 #endif
709
710         if (do_id_user) {
711                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
712         }
713
714         switch (type) {
715                 case ID_SCE:
716                         BKE_scene_free((Scene *)id);
717                         break;
718                 case ID_LI:
719                         BKE_library_free((Library *)id);
720                         break;
721                 case ID_OB:
722                         BKE_object_free((Object *)id);
723                         break;
724                 case ID_ME:
725                         BKE_mesh_free((Mesh *)id);
726                         break;
727                 case ID_CU:
728                         BKE_curve_free((Curve *)id);
729                         break;
730                 case ID_MB:
731                         BKE_mball_free((MetaBall *)id);
732                         break;
733                 case ID_MA:
734                         BKE_material_free((Material *)id);
735                         break;
736                 case ID_TE:
737                         BKE_texture_free((Tex *)id);
738                         break;
739                 case ID_IM:
740                         BKE_image_free((Image *)id);
741                         break;
742                 case ID_LT:
743                         BKE_lattice_free((Lattice *)id);
744                         break;
745                 case ID_LA:
746                         BKE_lamp_free((Lamp *)id);
747                         break;
748                 case ID_CA:
749                         BKE_camera_free((Camera *) id);
750                         break;
751                 case ID_IP:  /* Deprecated. */
752                         BKE_ipo_free((Ipo *)id);
753                         break;
754                 case ID_KE:
755                         BKE_key_free((Key *)id);
756                         break;
757                 case ID_WO:
758                         BKE_world_free((World *)id);
759                         break;
760                 case ID_SCR:
761                         BKE_screen_free((bScreen *)id);
762                         break;
763                 case ID_VF:
764                         BKE_vfont_free((VFont *)id);
765                         break;
766                 case ID_TXT:
767                         BKE_text_free((Text *)id);
768                         break;
769                 case ID_SPK:
770                         BKE_speaker_free((Speaker *)id);
771                         break;
772                 case ID_SO:
773                         BKE_sound_free((bSound *)id);
774                         break;
775                 case ID_GR:
776                         BKE_group_free((Group *)id);
777                         break;
778                 case ID_AR:
779                         BKE_armature_free((bArmature *)id);
780                         break;
781                 case ID_AC:
782                         BKE_action_free((bAction *)id);
783                         break;
784                 case ID_NT:
785                         ntreeFreeTree((bNodeTree *)id);
786                         break;
787                 case ID_BR:
788                         BKE_brush_free((Brush *)id);
789                         break;
790                 case ID_WM:
791                         if (free_windowmanager_cb)
792                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
793                         break;
794                 case ID_GD:
795                         BKE_gpencil_free((bGPdata *)id, true);
796                         break;
797                 case ID_MC:
798                         BKE_movieclip_free((MovieClip *)id);
799                         break;
800                 case ID_MSK:
801                         BKE_mask_free((Mask *)id);
802                         break;
803                 case ID_LS:
804                         BKE_linestyle_free((FreestyleLineStyle *)id);
805                         break;
806                 case ID_PAL:
807                         BKE_palette_free((Palette *)id);
808                         break;
809                 case ID_PC:
810                         BKE_paint_curve_free((PaintCurve *)id);
811                         break;
812                 case ID_CF:
813                         BKE_cachefile_free((CacheFile *)id);
814                         break;
815         }
816
817         /* avoid notifying on removed data */
818         BKE_main_lock(bmain);
819
820         if (do_ui_user) {
821                 if (free_notifier_reference_cb) {
822                         free_notifier_reference_cb(id);
823                 }
824
825                 if (remap_editor_id_reference_cb) {
826                         remap_editor_id_reference_cb(id, NULL);
827                 }
828         }
829
830         BLI_remlink(lb, id);
831
832         BKE_libblock_free_data(bmain, id);
833         BKE_main_unlock(bmain);
834
835         MEM_freeN(id);
836 }
837
838 void BKE_libblock_free(Main *bmain, void *idv)
839 {
840         BKE_libblock_free_ex(bmain, idv, true, true);
841 }
842
843 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
844 {
845         ID *id = idv;
846         
847         id_us_min(id);
848
849         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
850          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
851          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
852          *     fully unlinked.
853          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
854          */
855         if ((GS(id->name) == ID_OB) && (id->us == 1)) {
856                 id_us_clear_real(id);
857         }
858
859         if (id->us == 0) {
860                 BKE_libblock_unlink(bmain, id, false, false);
861                 
862                 BKE_libblock_free(bmain, id);
863         }
864 }
865
866 void BKE_libblock_delete(Main *bmain, void *idv)
867 {
868         ListBase *lbarray[MAX_LIBARRAY];
869         int base_count, i;
870
871         base_count = set_listbasepointers(bmain, lbarray);
872         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
873
874         /* First tag all datablocks directly from target lib.
875          * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
876          * Avoids to have to loop twice. */
877         for (i = 0; i < base_count; i++) {
878                 ListBase *lb = lbarray[i];
879                 ID *id;
880
881                 for (id = lb->first; id; id = id->next) {
882                         /* Note: in case we delete a library, we also delete all its datablocks! */
883                         if ((id == (ID *)idv) || (id->lib == (Library *)idv) || (id->tag & LIB_TAG_DOIT)) {
884                                 id->tag |= LIB_TAG_DOIT;
885                                 /* Will tag 'never NULL' users of this ID too.
886                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
887                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
888                                  * Also, this will also flag users of deleted data that cannot be unlinked
889                                  * (object using deleted obdata, etc.), so that they also get deleted. */
890                                 BKE_libblock_remap(bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
891                         }
892                 }
893         }
894
895         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
896          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
897          * over meshes when we come to freeing obdata). */
898         for (i = base_count; i--; ) {
899                 ListBase *lb = lbarray[i];
900                 ID *id, *id_next;
901
902                 for (id = lb->first; id; id = id_next) {
903                         id_next = id->next;
904                         if (id->tag & LIB_TAG_DOIT) {
905                                 if (id->us != 0) {
906 #ifdef DEBUG_PRINT
907                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
908 #endif
909                                         BLI_assert(id->us == 0);
910                                 }
911                                 BKE_libblock_free(bmain, id);
912                         }
913                 }
914         }
915 }