2 * This program is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU General Public License
4 * as published by the Free Software Foundation; either version 2
5 * of the License, or (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software Foundation,
14 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17 * All rights reserved.
23 * Contains management of ID's and libraries
24 * allocate and free of all library data
36 #include "MEM_guardedalloc.h"
38 /* all types are needed here, in order to do memory operations */
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_brush_types.h"
42 #include "DNA_cachefile_types.h"
43 #include "DNA_camera_types.h"
44 #include "DNA_collection_types.h"
45 #include "DNA_gpencil_types.h"
46 #include "DNA_ipo_types.h"
47 #include "DNA_key_types.h"
48 #include "DNA_light_types.h"
49 #include "DNA_lattice_types.h"
50 #include "DNA_linestyle_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_meta_types.h"
54 #include "DNA_modifier_types.h"
55 #include "DNA_movieclip_types.h"
56 #include "DNA_mask_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_lightprobe_types.h"
60 #include "DNA_rigidbody_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_screen_types.h"
63 #include "DNA_speaker_types.h"
64 #include "DNA_sound_types.h"
65 #include "DNA_text_types.h"
66 #include "DNA_vfont_types.h"
67 #include "DNA_windowmanager_types.h"
68 #include "DNA_world_types.h"
69 #include "DNA_workspace_types.h"
71 #include "BLI_utildefines.h"
73 #include "BLI_bitmap.h"
74 #include "BLI_blenlib.h"
75 #include "BLI_ghash.h"
76 #include "BLI_linklist.h"
77 #include "BLI_memarena.h"
78 #include "BLI_string_utils.h"
80 #include "BLT_translation.h"
82 #include "BKE_action.h"
83 #include "BKE_animsys.h"
84 #include "BKE_armature.h"
85 #include "BKE_bpath.h"
86 #include "BKE_brush.h"
87 #include "BKE_camera.h"
88 #include "BKE_cachefile.h"
89 #include "BKE_collection.h"
90 #include "BKE_context.h"
91 #include "BKE_curve.h"
93 #include "BKE_global.h"
94 #include "BKE_gpencil.h"
95 #include "BKE_idcode.h"
96 #include "BKE_idprop.h"
97 #include "BKE_image.h"
99 #include "BKE_light.h"
100 #include "BKE_lattice.h"
101 #include "BKE_lib_id.h"
102 #include "BKE_lib_query.h"
103 #include "BKE_lib_remap.h"
104 #include "BKE_linestyle.h"
105 #include "BKE_mesh.h"
106 #include "BKE_mesh_runtime.h"
107 #include "BKE_material.h"
108 #include "BKE_main.h"
109 #include "BKE_mball.h"
110 #include "BKE_mask.h"
111 #include "BKE_movieclip.h"
112 #include "BKE_node.h"
113 #include "BKE_object.h"
114 #include "BKE_paint.h"
115 #include "BKE_particle.h"
116 #include "BKE_packedFile.h"
117 #include "BKE_lightprobe.h"
118 #include "BKE_rigidbody.h"
119 #include "BKE_sound.h"
120 #include "BKE_speaker.h"
121 #include "BKE_scene.h"
122 #include "BKE_text.h"
123 #include "BKE_texture.h"
124 #include "BKE_world.h"
126 #include "DEG_depsgraph.h"
128 #include "RNA_access.h"
130 #include "IMB_imbuf.h"
131 #include "IMB_imbuf_types.h"
133 #include "atomic_ops.h"
138 # include "PIL_time_utildefines.h"
141 static CLG_LogRef LOG = {.identifier = "bke.lib_id"};
143 /* GS reads the memory pointed at in a specific ordering.
144 * only use this definition, makes little and big endian systems
145 * work fine, in conjunction with MAKE_ID */
147 /* ************* general ************************ */
149 /* this has to be called from each make_local_* func, we could call
150 * from id_make_local() but then the make local functions would not be self
152 * also note that the id _must_ have a library - campbell */
153 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
155 const char *bpath_user_data[2] = {BKE_main_blendfile_path(bmain), lib->filepath};
157 BKE_bpath_traverse_id(bmain,
159 BKE_bpath_relocate_visitor,
160 BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
161 (void *)bpath_user_data);
164 void id_lib_extern(ID *id)
166 if (id && ID_IS_LINKED(id)) {
167 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
168 if (id->tag & LIB_TAG_INDIRECT) {
169 id->tag &= ~LIB_TAG_INDIRECT;
170 id->flag &= ~LIB_INDIRECT_WEAK_LINK;
171 id->tag |= LIB_TAG_EXTERN;
172 id->lib->parent = NULL;
177 void id_lib_indirect_weak_link(ID *id)
179 if (id && ID_IS_LINKED(id)) {
180 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
181 if (id->tag & LIB_TAG_INDIRECT) {
182 id->flag |= LIB_INDIRECT_WEAK_LINK;
188 * Ensure we have a real user
190 * \note Now that we have flags, we could get rid of the 'fake_user' special case,
191 * flags are enough to ensure we always have a real user.
192 * However, #ID_REAL_USERS is used in several places outside of core lib.c,
193 * so think we can wait later to make this change.
195 void id_us_ensure_real(ID *id)
198 const int limit = ID_FAKE_USERS(id);
199 id->tag |= LIB_TAG_EXTRAUSER;
200 if (id->us <= limit) {
201 if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
203 "ID user count error: %s (from '%s')",
205 id->lib ? id->lib->filepath : "[Main]");
209 id->tag |= LIB_TAG_EXTRAUSER_SET;
214 void id_us_clear_real(ID *id)
216 if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
217 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
219 BLI_assert(id->us >= ID_FAKE_USERS(id));
221 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
226 * Same as \a id_us_plus, but does not handle lib indirect -> extern.
227 * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
229 void id_us_plus_no_lib(ID *id)
232 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
233 BLI_assert(id->us >= 1);
234 /* No need to increase count, just tag extra user as no more set.
235 * Avoids annoying & inconsistent +1 in user count. */
236 id->tag &= ~LIB_TAG_EXTRAUSER_SET;
239 BLI_assert(id->us >= 0);
245 void id_us_plus(ID *id)
248 id_us_plus_no_lib(id);
253 /* decrements the user count for *id. */
254 void id_us_min(ID *id)
257 const int limit = ID_FAKE_USERS(id);
259 if (id->us <= limit) {
261 "ID user decrement error: %s (from '%s'): %d <= %d",
263 id->lib ? id->lib->filepath : "[Main]",
273 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
274 /* We need an extra user here, but never actually incremented user count for it so far,
276 id_us_ensure_real(id);
281 void id_fake_user_set(ID *id)
283 if (id && !(id->flag & LIB_FAKEUSER)) {
284 id->flag |= LIB_FAKEUSER;
289 void id_fake_user_clear(ID *id)
291 if (id && (id->flag & LIB_FAKEUSER)) {
292 id->flag &= ~LIB_FAKEUSER;
297 void BKE_id_clear_newpoin(ID *id)
300 id->newid->tag &= ~LIB_TAG_NEW;
305 static int id_expand_local_callback(void *UNUSED(user_data),
307 struct ID **id_pointer,
310 if (cb_flag & IDWALK_CB_PRIVATE) {
311 return IDWALK_RET_NOP;
314 /* Can happen that we get un-linkable ID here, e.g. with shape-key referring to itself
315 * (through drivers)...
316 * Just skip it, shape key can only be either indirectly linked, or fully local, period.
317 * And let's curse one more time that stupid useless shapekey ID type! */
318 if (*id_pointer && *id_pointer != id_self && BKE_idcode_is_linkable(GS((*id_pointer)->name))) {
319 id_lib_extern(*id_pointer);
322 return IDWALK_RET_NOP;
326 * Expand ID usages of given id as 'extern' (and no more indirect) linked data.
327 * Used by ID copy/make_local functions.
329 void BKE_id_expand_local(Main *bmain, ID *id)
331 BKE_library_foreach_ID_link(bmain, id, id_expand_local_callback, NULL, IDWALK_READONLY);
335 * Ensure new (copied) ID is fully made local.
337 void BKE_id_copy_ensure_local(Main *bmain, const ID *old_id, ID *new_id)
339 if (ID_IS_LINKED(old_id)) {
340 BKE_id_expand_local(bmain, new_id);
341 BKE_id_lib_local_paths(bmain, old_id->lib, new_id);
346 * Generic 'make local' function, works for most of data-block types...
348 void BKE_id_make_local_generic(Main *bmain,
350 const bool id_in_mainlist,
351 const bool lib_local)
353 bool is_local = false, is_lib = false;
355 /* - only lib users: do nothing (unless force_local is set)
356 * - only local users: set flag
358 * In case we make a whole lib's content local,
359 * we always want to localize, and we skip remapping (done later).
362 if (!ID_IS_LINKED(id)) {
366 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
368 if (lib_local || is_local) {
370 id_clear_lib_data_ex(bmain, id, id_in_mainlist);
371 BKE_id_expand_local(bmain, id);
376 /* Should not fail in expected use cases,
377 * but a few ID types cannot be copied (LIB, WM, SCR...). */
378 if (BKE_id_copy(bmain, id, &id_new)) {
381 /* setting newid is mandatory for complex make_lib_local logic... */
382 ID_NEW_SET(id, id_new);
383 Key *key = BKE_key_from_id(id), *key_new = BKE_key_from_id(id);
384 if (key && key_new) {
385 ID_NEW_SET(key, key_new);
387 bNodeTree *ntree = ntreeFromID(id), *ntree_new = ntreeFromID(id_new);
388 if (ntree && ntree_new) {
389 ID_NEW_SET(ntree, ntree_new);
393 BKE_libblock_remap(bmain, id, id_new, ID_REMAP_SKIP_INDIRECT_USAGE);
401 * Calls the appropriate make_local method for the block, unless test is set.
403 * \note Always set ID->newid pointer in case it gets duplicated...
405 * \param lib_local: Special flag used when making a whole library's content local,
406 * it needs specific handling.
408 * \return true if the block can be made local.
410 bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
412 /* We don't care whether ID is directly or indirectly linked
413 * in case we are making a whole lib local... */
414 if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) {
418 switch ((ID_Type)GS(id->name)) {
421 BKE_scene_make_local(bmain, (Scene *)id, lib_local);
426 BKE_object_make_local(bmain, (Object *)id, lib_local);
431 BKE_mesh_make_local(bmain, (Mesh *)id, lib_local);
436 BKE_curve_make_local(bmain, (Curve *)id, lib_local);
441 BKE_mball_make_local(bmain, (MetaBall *)id, lib_local);
446 BKE_material_make_local(bmain, (Material *)id, lib_local);
451 BKE_texture_make_local(bmain, (Tex *)id, lib_local);
456 BKE_image_make_local(bmain, (Image *)id, lib_local);
461 BKE_lattice_make_local(bmain, (Lattice *)id, lib_local);
466 BKE_light_make_local(bmain, (Light *)id, lib_local);
471 BKE_camera_make_local(bmain, (Camera *)id, lib_local);
476 BKE_speaker_make_local(bmain, (Speaker *)id, lib_local);
481 BKE_lightprobe_make_local(bmain, (LightProbe *)id, lib_local);
486 BKE_world_make_local(bmain, (World *)id, lib_local);
491 BKE_vfont_make_local(bmain, (VFont *)id, lib_local);
496 BKE_text_make_local(bmain, (Text *)id, lib_local);
501 BKE_sound_make_local(bmain, (bSound *)id, lib_local);
506 BKE_collection_make_local(bmain, (Collection *)id, lib_local);
511 BKE_armature_make_local(bmain, (bArmature *)id, lib_local);
516 BKE_action_make_local(bmain, (bAction *)id, lib_local);
521 ntreeMakeLocal(bmain, (bNodeTree *)id, true, lib_local);
526 BKE_brush_make_local(bmain, (Brush *)id, lib_local);
531 BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, lib_local);
536 BKE_gpencil_make_local(bmain, (bGPdata *)id, lib_local);
541 BKE_movieclip_make_local(bmain, (MovieClip *)id, lib_local);
546 BKE_mask_make_local(bmain, (Mask *)id, lib_local);
551 BKE_linestyle_make_local(bmain, (FreestyleLineStyle *)id, lib_local);
556 BKE_palette_make_local(bmain, (Palette *)id, lib_local);
561 BKE_paint_curve_make_local(bmain, (PaintCurve *)id, lib_local);
566 BKE_cachefile_make_local(bmain, (CacheFile *)id, lib_local);
571 /* A bit special: can be appended but not linked. Return false
572 * since supporting make-local doesn't make much sense. */
577 return false; /* can't be linked */
579 return false; /* deprecated */
585 struct IDCopyLibManagementData {
591 /* Increases usercount as required, and remap self ID pointers. */
592 static int id_copy_libmanagement_cb(void *user_data,
597 struct IDCopyLibManagementData *data = user_data;
598 ID *id = *id_pointer;
600 /* Remap self-references to new copied ID. */
601 if (id == data->id_src) {
602 /* We cannot use id_self here, it is not *always* id_dst (thanks to $£!+@#&/? nodetrees). */
603 id = *id_pointer = data->id_dst;
606 /* Increase used IDs refcount if needed and required. */
607 if ((data->flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0 && (cb_flag & IDWALK_CB_USER)) {
611 return IDWALK_RET_NOP;
614 bool BKE_id_copy_is_allowed(const ID *id)
616 #define LIB_ID_TYPES_NOCOPY \
617 ID_LI, ID_SCR, ID_WM, ID_WS, /* Not supported */ \
618 ID_IP /* Deprecated */
620 return !ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY);
622 #undef LIB_ID_TYPES_NOCOPY
626 * Generic entry point for copying a data-block (new API).
628 * \note Copy is only affecting given data-block
629 * (no ID used by copied one will be affected, besides usercount).
630 * There is only one exception, if #LIB_ID_COPY_ACTIONS is defined,
631 * actions used by animdata will be duplicated.
633 * \note Usercount of new copy is always set to 1.
635 * \param bmain: Main database, may be NULL only if LIB_ID_CREATE_NO_MAIN is specified.
636 * \param id: Source data-block.
637 * \param r_newid: Pointer to new (copied) ID pointer.
638 * \param flag: Set of copy options, see DNA_ID.h enum for details
639 * (leave to zero for default, full copy).
640 * \return False when copying that ID type is not supported, true otherwise.
642 bool BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag)
644 BLI_assert(r_newid != NULL);
645 /* Make sure destination pointer is all good. */
646 if ((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0) {
650 if (*r_newid != NULL) {
651 /* Allow some garbage non-initialized memory to go in, and clean it up here. */
652 const size_t size = BKE_libblock_get_alloc_info(GS(id->name), NULL);
653 memset(*r_newid, 0, size);
657 /* Early output is source is NULL. */
661 if (!BKE_id_copy_is_allowed(id)) {
665 BKE_libblock_copy_ex(bmain, id, r_newid, flag);
667 switch ((ID_Type)GS(id->name)) {
669 BKE_scene_copy_data(bmain, (Scene *)*r_newid, (Scene *)id, flag);
672 BKE_object_copy_data(bmain, (Object *)*r_newid, (Object *)id, flag);
675 BKE_mesh_copy_data(bmain, (Mesh *)*r_newid, (Mesh *)id, flag);
678 BKE_curve_copy_data(bmain, (Curve *)*r_newid, (Curve *)id, flag);
681 BKE_mball_copy_data(bmain, (MetaBall *)*r_newid, (MetaBall *)id, flag);
684 BKE_material_copy_data(bmain, (Material *)*r_newid, (Material *)id, flag);
687 BKE_texture_copy_data(bmain, (Tex *)*r_newid, (Tex *)id, flag);
690 BKE_image_copy_data(bmain, (Image *)*r_newid, (Image *)id, flag);
693 BKE_lattice_copy_data(bmain, (Lattice *)*r_newid, (Lattice *)id, flag);
696 BKE_light_copy_data(bmain, (Light *)*r_newid, (Light *)id, flag);
699 BKE_speaker_copy_data(bmain, (Speaker *)*r_newid, (Speaker *)id, flag);
702 BKE_lightprobe_copy_data(bmain, (LightProbe *)*r_newid, (LightProbe *)id, flag);
705 BKE_camera_copy_data(bmain, (Camera *)*r_newid, (Camera *)id, flag);
708 BKE_key_copy_data(bmain, (Key *)*r_newid, (Key *)id, flag);
711 BKE_world_copy_data(bmain, (World *)*r_newid, (World *)id, flag);
714 BKE_text_copy_data(bmain, (Text *)*r_newid, (Text *)id, flag);
717 BKE_collection_copy_data(bmain, (Collection *)*r_newid, (Collection *)id, flag);
720 BKE_armature_copy_data(bmain, (bArmature *)*r_newid, (bArmature *)id, flag);
723 BKE_action_copy_data(bmain, (bAction *)*r_newid, (bAction *)id, flag);
726 BKE_node_tree_copy_data(bmain, (bNodeTree *)*r_newid, (bNodeTree *)id, flag);
729 BKE_brush_copy_data(bmain, (Brush *)*r_newid, (Brush *)id, flag);
732 BKE_particlesettings_copy_data(
733 bmain, (ParticleSettings *)*r_newid, (ParticleSettings *)id, flag);
736 BKE_gpencil_copy_data((bGPdata *)*r_newid, (bGPdata *)id, flag);
739 BKE_movieclip_copy_data(bmain, (MovieClip *)*r_newid, (MovieClip *)id, flag);
742 BKE_mask_copy_data(bmain, (Mask *)*r_newid, (Mask *)id, flag);
745 BKE_linestyle_copy_data(
746 bmain, (FreestyleLineStyle *)*r_newid, (FreestyleLineStyle *)id, flag);
749 BKE_palette_copy_data(bmain, (Palette *)*r_newid, (Palette *)id, flag);
752 BKE_paint_curve_copy_data(bmain, (PaintCurve *)*r_newid, (PaintCurve *)id, flag);
755 BKE_cachefile_copy_data(bmain, (CacheFile *)*r_newid, (CacheFile *)id, flag);
758 BKE_sound_copy_data(bmain, (bSound *)*r_newid, (bSound *)id, flag);
761 BKE_vfont_copy_data(bmain, (VFont *)*r_newid, (VFont *)id, flag);
768 BLI_assert(0); /* Should have been rejected at start of function! */
772 /* Update ID refcount, remap pointers to self in new ID. */
773 struct IDCopyLibManagementData data = {
778 BKE_library_foreach_ID_link(bmain, *r_newid, id_copy_libmanagement_cb, &data, IDWALK_NOP);
780 /* Do not make new copy local in case we are copying outside of main...
781 * XXX TODO: is this behavior OK, or should we need own flag to control that? */
782 if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
783 BLI_assert((flag & LIB_ID_COPY_KEEP_LIB) == 0);
784 BKE_id_copy_ensure_local(bmain, id, *r_newid);
787 (*r_newid)->lib = id->lib;
794 * Invokes the appropriate copy method for the block and returns the result in
795 * newid, unless test. Returns true if the block can be copied.
797 bool BKE_id_copy(Main *bmain, const ID *id, ID **newid)
799 return BKE_id_copy_ex(bmain, id, newid, LIB_ID_COPY_DEFAULT);
803 * Does a mere memory swap over the whole IDs data (including type-specific memory).
804 * \note Most internal ID data itself is not swapped (only IDProperties are).
806 void BKE_id_swap(Main *bmain, ID *id_a, ID *id_b)
808 BLI_assert(GS(id_a->name) == GS(id_b->name));
810 const ID id_a_back = *id_a;
811 const ID id_b_back = *id_b;
813 #define CASE_SWAP(_gs, _type) \
815 SWAP(_type, *(_type *)id_a, *(_type *)id_b); \
818 switch ((ID_Type)GS(id_a->name)) {
819 CASE_SWAP(ID_SCE, Scene);
820 CASE_SWAP(ID_LI, Library);
821 CASE_SWAP(ID_OB, Object);
822 CASE_SWAP(ID_ME, Mesh);
823 CASE_SWAP(ID_CU, Curve);
824 CASE_SWAP(ID_MB, MetaBall);
825 CASE_SWAP(ID_MA, Material);
826 CASE_SWAP(ID_TE, Tex);
827 CASE_SWAP(ID_IM, Image);
828 CASE_SWAP(ID_LT, Lattice);
829 CASE_SWAP(ID_LA, Light);
830 CASE_SWAP(ID_LP, LightProbe);
831 CASE_SWAP(ID_CA, Camera);
832 CASE_SWAP(ID_KE, Key);
833 CASE_SWAP(ID_WO, World);
834 CASE_SWAP(ID_SCR, bScreen);
835 CASE_SWAP(ID_VF, VFont);
836 CASE_SWAP(ID_TXT, Text);
837 CASE_SWAP(ID_SPK, Speaker);
838 CASE_SWAP(ID_SO, bSound);
839 CASE_SWAP(ID_GR, Collection);
840 CASE_SWAP(ID_AR, bArmature);
841 CASE_SWAP(ID_AC, bAction);
842 CASE_SWAP(ID_NT, bNodeTree);
843 CASE_SWAP(ID_BR, Brush);
844 CASE_SWAP(ID_PA, ParticleSettings);
845 CASE_SWAP(ID_WM, wmWindowManager);
846 CASE_SWAP(ID_WS, WorkSpace);
847 CASE_SWAP(ID_GD, bGPdata);
848 CASE_SWAP(ID_MC, MovieClip);
849 CASE_SWAP(ID_MSK, Mask);
850 CASE_SWAP(ID_LS, FreestyleLineStyle);
851 CASE_SWAP(ID_PAL, Palette);
852 CASE_SWAP(ID_PC, PaintCurve);
853 CASE_SWAP(ID_CF, CacheFile);
855 break; /* Deprecated. */
860 /* Restore original ID's internal data. */
864 /* Exception: IDProperties. */
865 id_a->properties = id_b_back.properties;
866 id_b->properties = id_a_back.properties;
868 /* Swap will have broken internal references to itself, restore them. */
869 BKE_libblock_relink_ex(bmain, id_a, id_b, id_a, ID_REMAP_SKIP_NEVER_NULL_USAGE);
870 BKE_libblock_relink_ex(bmain, id_b, id_a, id_b, ID_REMAP_SKIP_NEVER_NULL_USAGE);
873 /** Does *not* set ID->newid pointer. */
874 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
880 /* If property isn't editable,
881 * we're going to have an extra block hanging around until we save. */
882 if (RNA_property_editable(ptr, prop)) {
883 Main *bmain = CTX_data_main(C);
884 /* copy animation actions too */
885 if (BKE_id_copy_ex(bmain, id, &newid, LIB_ID_COPY_DEFAULT | LIB_ID_COPY_ACTIONS) && newid) {
886 /* us is 1 by convention with new IDs, but RNA_property_pointer_set
887 * will also increment it, decrement it here. */
891 RNA_id_pointer_create(newid, &idptr);
892 RNA_property_pointer_set(ptr, prop, idptr, NULL);
893 RNA_property_update(C, ptr, prop);
895 /* tag grease pencil data-block and disable onion */
896 if (GS(id->name) == ID_GD) {
897 DEG_id_tag_update(id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
898 DEG_id_tag_update(newid, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
899 bGPdata *gpd = (bGPdata *)newid;
900 gpd->flag &= ~GP_DATA_SHOW_ONIONSKINS;
911 static int libblock_management_us_plus(void *UNUSED(user_data),
916 if (cb_flag & IDWALK_CB_USER) {
917 id_us_plus(*id_pointer);
919 if (cb_flag & IDWALK_CB_USER_ONE) {
920 id_us_ensure_real(*id_pointer);
923 return IDWALK_RET_NOP;
926 static int libblock_management_us_min(void *UNUSED(user_data),
931 if (cb_flag & IDWALK_CB_USER) {
932 id_us_min(*id_pointer);
934 /* We can do nothing in IDWALK_CB_USER_ONE case! */
936 return IDWALK_RET_NOP;
939 /** Add a 'NO_MAIN' data-block to given main (also sets usercounts of its IDs if needed). */
940 void BKE_libblock_management_main_add(Main *bmain, void *idv)
944 BLI_assert(bmain != NULL);
945 if ((id->tag & LIB_TAG_NO_MAIN) == 0) {
949 if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
950 /* We cannot add non-allocated ID to Main! */
954 /* We cannot allow non-userrefcounting IDs in Main database! */
955 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
956 BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
959 ListBase *lb = which_libbase(bmain, GS(id->name));
960 BKE_main_lock(bmain);
962 BKE_id_new_name_validate(lb, id, NULL);
963 /* alphabetic insertion: is in new_id */
964 id->tag &= ~(LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT);
965 bmain->is_memfile_undo_written = false;
966 BKE_main_unlock(bmain);
969 /** Remove a data-block from given main (set it to 'NO_MAIN' status). */
970 void BKE_libblock_management_main_remove(Main *bmain, void *idv)
974 BLI_assert(bmain != NULL);
975 if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
979 /* For now, allow userrefcounting IDs to get out of Main - can be handy in some cases... */
981 ListBase *lb = which_libbase(bmain, GS(id->name));
982 BKE_main_lock(bmain);
984 id->tag |= LIB_TAG_NO_MAIN;
985 bmain->is_memfile_undo_written = false;
986 BKE_main_unlock(bmain);
989 void BKE_libblock_management_usercounts_set(Main *bmain, void *idv)
993 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) == 0) {
997 BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
998 id->tag &= ~LIB_TAG_NO_USER_REFCOUNT;
1001 void BKE_libblock_management_usercounts_clear(Main *bmain, void *idv)
1005 /* We do not allow IDs in Main database to not be userrefcounting. */
1006 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0 || (id->tag & LIB_TAG_NO_MAIN) != 0) {
1010 BKE_library_foreach_ID_link(bmain, id, libblock_management_us_min, NULL, IDWALK_NOP);
1011 id->tag |= LIB_TAG_NO_USER_REFCOUNT;
1015 * Clear or set given tags for all ids in listbase (runtime tags).
1017 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
1021 for (id = lb->first; id; id = id->next) {
1026 const int ntag = ~tag;
1027 for (id = lb->first; id; id = id->next) {
1034 * Clear or set given tags for all ids of given type in bmain (runtime tags).
1036 void BKE_main_id_tag_idcode(struct Main *mainvar,
1041 ListBase *lb = which_libbase(mainvar, type);
1043 BKE_main_id_tag_listbase(lb, tag, value);
1047 * Clear or set given tags for all ids in bmain (runtime tags).
1049 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
1051 ListBase *lbarray[MAX_LIBARRAY];
1054 a = set_listbasepointers(mainvar, lbarray);
1056 BKE_main_id_tag_listbase(lbarray[a], tag, value);
1061 * Clear or set given flags for all ids in listbase (persistent flags).
1063 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
1067 for (id = lb->first; id; id = id->next) {
1072 const int nflag = ~flag;
1073 for (id = lb->first; id; id = id->next) {
1080 * Clear or set given flags for all ids in bmain (persistent flags).
1082 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
1084 ListBase *lbarray[MAX_LIBARRAY];
1086 a = set_listbasepointers(bmain, lbarray);
1088 BKE_main_id_flag_listbase(lbarray[a], flag, value);
1092 void BKE_main_id_repair_duplicate_names_listbase(ListBase *lb)
1095 for (ID *id = lb->first; id; id = id->next) {
1096 if (id->lib == NULL) {
1104 /* Fill an array because renaming sorts. */
1105 ID **id_array = MEM_mallocN(sizeof(*id_array) * lb_len, __func__);
1106 GSet *gset = BLI_gset_str_new_ex(__func__, lb_len);
1108 for (ID *id = lb->first; id; id = id->next) {
1109 if (id->lib == NULL) {
1114 for (i = 0; i < lb_len; i++) {
1115 if (!BLI_gset_add(gset, id_array[i]->name + 2)) {
1116 BKE_id_new_name_validate(lb, id_array[i], NULL);
1119 BLI_gset_free(gset, NULL);
1120 MEM_freeN(id_array);
1123 void BKE_main_lib_objects_recalc_all(Main *bmain)
1127 /* flag for full recalc */
1128 for (ob = bmain->objects.first; ob; ob = ob->id.next) {
1129 if (ID_IS_LINKED(ob)) {
1130 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1134 DEG_id_type_tag(bmain, ID_OB);
1137 /* *********** ALLOC AND FREE *****************
1139 * BKE_libblock_free(ListBase *lb, ID *id )
1140 * provide a list-basis and data-block, but only ID is read
1142 * void *BKE_libblock_alloc(ListBase *lb, type, name)
1143 * inserts in list and returns a new ID
1145 * **************************** */
1148 * Get allocation size of a given data-block type and optionally allocation name.
1150 size_t BKE_libblock_get_alloc_info(short type, const char **name)
1152 #define CASE_RETURN(id_code, type) \
1155 if (name != NULL) { \
1158 return sizeof(type); \
1161 switch ((ID_Type)type) {
1162 CASE_RETURN(ID_SCE, Scene);
1163 CASE_RETURN(ID_LI, Library);
1164 CASE_RETURN(ID_OB, Object);
1165 CASE_RETURN(ID_ME, Mesh);
1166 CASE_RETURN(ID_CU, Curve);
1167 CASE_RETURN(ID_MB, MetaBall);
1168 CASE_RETURN(ID_MA, Material);
1169 CASE_RETURN(ID_TE, Tex);
1170 CASE_RETURN(ID_IM, Image);
1171 CASE_RETURN(ID_LT, Lattice);
1172 CASE_RETURN(ID_LA, Light);
1173 CASE_RETURN(ID_CA, Camera);
1174 CASE_RETURN(ID_IP, Ipo);
1175 CASE_RETURN(ID_KE, Key);
1176 CASE_RETURN(ID_WO, World);
1177 CASE_RETURN(ID_SCR, bScreen);
1178 CASE_RETURN(ID_VF, VFont);
1179 CASE_RETURN(ID_TXT, Text);
1180 CASE_RETURN(ID_SPK, Speaker);
1181 CASE_RETURN(ID_LP, LightProbe);
1182 CASE_RETURN(ID_SO, bSound);
1183 CASE_RETURN(ID_GR, Collection);
1184 CASE_RETURN(ID_AR, bArmature);
1185 CASE_RETURN(ID_AC, bAction);
1186 CASE_RETURN(ID_NT, bNodeTree);
1187 CASE_RETURN(ID_BR, Brush);
1188 CASE_RETURN(ID_PA, ParticleSettings);
1189 CASE_RETURN(ID_WM, wmWindowManager);
1190 CASE_RETURN(ID_GD, bGPdata);
1191 CASE_RETURN(ID_MC, MovieClip);
1192 CASE_RETURN(ID_MSK, Mask);
1193 CASE_RETURN(ID_LS, FreestyleLineStyle);
1194 CASE_RETURN(ID_PAL, Palette);
1195 CASE_RETURN(ID_PC, PaintCurve);
1196 CASE_RETURN(ID_CF, CacheFile);
1197 CASE_RETURN(ID_WS, WorkSpace);
1204 * Allocates and returns memory of the right size for the specified block type,
1205 * initialized to zero.
1207 void *BKE_libblock_alloc_notest(short type)
1210 size_t size = BKE_libblock_get_alloc_info(type, &name);
1212 return MEM_callocN(size, name);
1214 BLI_assert(!"Request to allocate unknown data type");
1219 * Allocates and returns a block of the specified type, with the specified name
1220 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
1221 * The user count is set to 1, all other content (apart from name and links) being
1222 * initialized to zero.
1224 void *BKE_libblock_alloc(Main *bmain, short type, const char *name, const int flag)
1226 BLI_assert((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
1228 ID *id = BKE_libblock_alloc_notest(type);
1231 if ((flag & LIB_ID_CREATE_NO_MAIN) != 0) {
1232 id->tag |= LIB_TAG_NO_MAIN;
1234 if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0) {
1235 id->tag |= LIB_TAG_NO_USER_REFCOUNT;
1239 *((short *)id->name) = type;
1240 if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1243 if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1244 ListBase *lb = which_libbase(bmain, type);
1246 BKE_main_lock(bmain);
1247 BLI_addtail(lb, id);
1248 BKE_id_new_name_validate(lb, id, name);
1249 bmain->is_memfile_undo_written = false;
1250 /* alphabetic insertion: is in new_id */
1251 BKE_main_unlock(bmain);
1253 /* TODO to be removed from here! */
1254 if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0) {
1255 DEG_id_type_tag(bmain, type);
1259 BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2);
1267 * Initialize an ID of given type, such that it has valid 'empty' data.
1268 * ID is assumed to be just calloc'ed.
1270 void BKE_libblock_init_empty(ID *id)
1272 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
1273 switch ((ID_Type)GS(id->name)) {
1275 BKE_scene_init((Scene *)id);
1278 /* Nothing to do. */
1281 Object *ob = (Object *)id;
1282 BKE_object_init(ob, OB_EMPTY);
1286 BKE_mesh_init((Mesh *)id);
1289 BKE_curve_init((Curve *)id, 0);
1292 BKE_mball_init((MetaBall *)id);
1295 BKE_material_init((Material *)id);
1298 BKE_texture_default((Tex *)id);
1301 BKE_image_init((Image *)id);
1304 BKE_lattice_init((Lattice *)id);
1307 BKE_light_init((Light *)id);
1310 BKE_speaker_init((Speaker *)id);
1313 BKE_lightprobe_init((LightProbe *)id);
1316 BKE_camera_init((Camera *)id);
1319 BKE_world_init((World *)id);
1322 /* Nothing to do. */
1325 BKE_vfont_init((VFont *)id);
1328 BKE_text_init((Text *)id);
1331 /* Another fuzzy case, think NULLified content is OK here... */
1334 /* Nothing to do. */
1337 /* Nothing to do. */
1340 /* Nothing to do. */
1343 ntreeInitDefault((bNodeTree *)id);
1346 BKE_brush_init((Brush *)id);
1349 /* Nothing to do. */
1352 /* Nothing to do. */
1355 /* Nothing to do. */
1358 /* Nothing to do. */
1361 BKE_linestyle_init((FreestyleLineStyle *)id);
1364 BKE_cachefile_init((CacheFile *)id);
1367 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
1368 * They are not linkable, though, so it should never reach here anyway. */
1372 /* We should never reach this. */
1376 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
1380 BKE_palette_init((Palette *)id);
1383 BLI_assert(0); /* Should never reach this point... */
1388 * Generic helper to create a new empty data-block of given type in given \a bmain database.
1390 * \param name: can be NULL, in which case we get default name for this ID type.
1392 void *BKE_id_new(Main *bmain, const short type, const char *name)
1394 BLI_assert(bmain != NULL);
1397 name = DATA_(BKE_idcode_to_name(type));
1400 ID *id = BKE_libblock_alloc(bmain, type, name, 0);
1401 BKE_libblock_init_empty(id);
1407 * Generic helper to create a new temporary empty data-block of given type,
1408 * *outside* of any Main database.
1410 * \param name: can be NULL, in which case we get default name for this ID type. */
1411 void *BKE_id_new_nomain(const short type, const char *name)
1414 name = DATA_(BKE_idcode_to_name(type));
1417 ID *id = BKE_libblock_alloc(NULL,
1420 LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT |
1421 LIB_ID_CREATE_NO_DEG_TAG);
1422 BKE_libblock_init_empty(id);
1427 void BKE_libblock_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int orig_flag)
1429 ID *new_id = *r_newid;
1430 int flag = orig_flag;
1432 const bool is_private_id_data = (id->flag & LIB_PRIVATE_DATA) != 0;
1434 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || bmain != NULL);
1435 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
1436 if (!is_private_id_data) {
1437 /* When we are handling private ID data, we might still want to manage usercounts, even though
1438 * that ID data-block is actually outside of Main... */
1439 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 ||
1440 (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0);
1442 /* Never implicitly copy shapekeys when generating temp data outside of Main database. */
1443 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 || (flag & LIB_ID_COPY_SHAPEKEY) == 0);
1445 /* 'Private ID' data handling. */
1446 if ((bmain != NULL) && is_private_id_data) {
1447 flag |= LIB_ID_CREATE_NO_MAIN;
1450 /* The id->flag bits to copy over. */
1451 const int copy_idflag_mask = LIB_PRIVATE_DATA;
1453 if ((flag & LIB_ID_CREATE_NO_ALLOCATE) != 0) {
1454 /* r_newid already contains pointer to allocated memory. */
1455 /* TODO do we want to memset(0) whole mem before filling it? */
1456 BLI_strncpy(new_id->name, id->name, sizeof(new_id->name));
1458 new_id->tag |= LIB_TAG_NOT_ALLOCATED | LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT;
1459 /* TODO Do we want/need to copy more from ID struct itself? */
1462 new_id = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2, flag);
1464 BLI_assert(new_id != NULL);
1466 const size_t id_len = BKE_libblock_get_alloc_info(GS(new_id->name), NULL);
1467 const size_t id_offset = sizeof(ID);
1468 if ((int)id_len - (int)id_offset > 0) { /* signed to allow neg result */ /* XXX ????? */
1469 const char *cp = (const char *)id;
1470 char *cpn = (char *)new_id;
1472 memcpy(cpn + id_offset, cp + id_offset, id_len - id_offset);
1475 new_id->flag = (new_id->flag & ~copy_idflag_mask) | (id->flag & copy_idflag_mask);
1477 /* We do not want any handling of usercount in code duplicating the data here, we do that all
1478 * at once in id_copy_libmanagement_cb() at the end. */
1479 const int copy_data_flag = orig_flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
1481 if (id->properties) {
1482 new_id->properties = IDP_CopyProperty_ex(id->properties, copy_data_flag);
1485 /* XXX Again... We need a way to control what we copy in a much more refined way.
1486 * We cannot always copy this, some internal copying will die on it! */
1487 /* For now, upper level code will have to do that itself when required. */
1489 if (id->override != NULL) {
1490 BKE_override_copy(new_id, id);
1494 if (id_can_have_animdata(new_id)) {
1495 IdAdtTemplate *iat = (IdAdtTemplate *)new_id;
1497 /* the duplicate should get a copy of the animdata */
1498 if ((flag & LIB_ID_COPY_NO_ANIMDATA) == 0) {
1499 /* Note that even though horrors like root nodetrees are not in bmain, the actions they use
1500 * in their anim data *are* in bmain... super-mega-hooray. */
1501 BLI_assert((copy_data_flag & LIB_ID_COPY_ACTIONS) == 0 ||
1502 (copy_data_flag & LIB_ID_CREATE_NO_MAIN) == 0);
1503 iat->adt = BKE_animdata_copy(bmain, iat->adt, copy_data_flag);
1510 if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1511 DEG_id_type_tag(bmain, GS(new_id->name));
1517 /* used everywhere in blenkernel */
1518 void *BKE_libblock_copy(Main *bmain, const ID *id)
1522 BKE_libblock_copy_ex(bmain, id, &idn, 0);
1527 /* XXX TODO: get rid of this useless wrapper at some point... */
1528 void *BKE_libblock_copy_for_localize(const ID *id)
1531 BKE_libblock_copy_ex(NULL, id, &idn, LIB_ID_COPY_LOCALIZE | LIB_ID_COPY_NO_ANIMDATA);
1535 /* ***************** ID ************************ */
1536 ID *BKE_libblock_find_name(struct Main *bmain, const short type, const char *name)
1538 ListBase *lb = which_libbase(bmain, type);
1539 BLI_assert(lb != NULL);
1540 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1544 * Sort given \a id into given \a lb list, using case-insensitive comparison of the id names.
1546 * \note All other IDs beside given one are assumed already properly sorted in the list.
1548 * \param id_sorting_hint Ignored if NULL. Otherwise, used to check if we can insert \a id
1549 * immediately before or after that pointer. It must always be into given \a lb list.
1551 void id_sort_by_name(ListBase *lb, ID *id, ID *id_sorting_hint)
1553 #define ID_SORT_STEP_SIZE 512
1557 /* insert alphabetically */
1558 if (lb->first == lb->last) {
1562 BLI_remlink(lb, id);
1564 /* Check if we can actually insert id before or after id_sorting_hint, if given. */
1565 if (id_sorting_hint != NULL && id_sorting_hint != id) {
1566 BLI_assert(BLI_findindex(lb, id_sorting_hint) >= 0);
1568 ID *id_sorting_hint_next = id_sorting_hint->next;
1569 if (BLI_strcasecmp(id_sorting_hint->name, id->name) < 0 &&
1570 (id_sorting_hint_next == NULL ||
1571 BLI_strcasecmp(id_sorting_hint_next->name, id->name) > 0)) {
1572 BLI_insertlinkafter(lb, id_sorting_hint, id);
1576 ID *id_sorting_hint_prev = id_sorting_hint->prev;
1577 if (BLI_strcasecmp(id_sorting_hint->name, id->name) > 0 &&
1578 (id_sorting_hint_prev == NULL ||
1579 BLI_strcasecmp(id_sorting_hint_prev->name, id->name) < 0)) {
1580 BLI_insertlinkbefore(lb, id_sorting_hint, id);
1585 void *item_array[ID_SORT_STEP_SIZE];
1586 int item_array_index;
1588 /* Step one: We go backward over a whole chunk of items at once, until we find a limit item
1589 * that is lower than, or equal (should never happen!) to the one we want to insert. */
1590 /* Note: We start from the end, because in typical 'heavy' case (insertion of lots of IDs at
1591 * once using the same base name), newly inserted items will generally be towards the end
1592 * (higher extension numbers). */
1593 for (idtest = lb->last, item_array_index = ID_SORT_STEP_SIZE - 1; idtest != NULL;
1594 idtest = idtest->prev, item_array_index--) {
1595 item_array[item_array_index] = idtest;
1596 if (item_array_index == 0) {
1597 if ((idtest->lib == NULL && id->lib != NULL) ||
1598 BLI_strcasecmp(idtest->name, id->name) <= 0) {
1601 item_array_index = ID_SORT_STEP_SIZE;
1605 /* Step two: we go forward in the selected chunk of items and check all of them, as we know
1606 * that our target is in there. */
1608 /* If we reached start of the list, current item_array_index is off-by-one.
1609 * Otherwise, we already know that it points to an item lower-or-equal-than the one we want to
1610 * insert, no need to redo the check for that one.
1611 * So we can increment that index in any case. */
1612 for (item_array_index++; item_array_index < ID_SORT_STEP_SIZE; item_array_index++) {
1613 idtest = item_array[item_array_index];
1614 if ((idtest->lib != NULL && id->lib == NULL) || BLI_strcasecmp(idtest->name, id->name) > 0) {
1615 BLI_insertlinkbefore(lb, idtest, id);
1619 if (item_array_index == ID_SORT_STEP_SIZE) {
1620 if (idtest == NULL) {
1621 /* If idtest is NULL here, it means that in the first loop, the last comparison was
1622 * performed exactly on the first item of the list, and that it also failed. In other
1623 * words, all items in the list are greater than inserted one, so we can put it at the
1624 * start of the list. */
1625 /* Note that BLI_insertlinkafter() would have same behavior in that case, but better be
1627 BLI_addhead(lb, id);
1630 BLI_insertlinkafter(lb, idtest, id);
1634 #undef ID_SORT_STEP_SIZE
1637 /* Note: this code assumes and ensures that the suffix number can never go beyond 1 billion. */
1638 #define MAX_NUMBER 1000000000
1639 /* We do not want to get "name.000", so minimal number is 1. */
1640 #define MIN_NUMBER 1
1641 /* The maximum value up to which we search for the actual smallest unused number. Beyond that
1642 * value, we will only use the first biggest unused number, without trying to 'fill the gaps'
1643 * in-between already used numbers... */
1644 #define MAX_NUMBERS_IN_USE 1024
1647 * Helper building final ID name from given base_name and number.
1649 * If everything goes well and we do generate a valid final ID name in given name, we return true.
1650 * In case the final name would overflow the allowed ID name length, or given number is bigger than
1651 * maximum allowed value, we truncate further the base_name (and given name, which is assumed to
1652 * have the same 'base_name' part), and return false.
1654 static bool id_name_final_build(char *name, char *base_name, size_t base_name_len, int number)
1656 char number_str[11]; /* Dot + nine digits + NULL terminator. */
1657 size_t number_str_len = BLI_snprintf_rlen(number_str, ARRAY_SIZE(number_str), ".%.3d", number);
1659 /* If the number would lead to an overflow of the maximum ID name length, we need to truncate
1660 * the base name part and do all the number checks again. */
1661 if (base_name_len + number_str_len >= MAX_ID_NAME - 2 || number >= MAX_NUMBER) {
1662 if (base_name_len + number_str_len >= MAX_ID_NAME - 2) {
1663 base_name_len = MAX_ID_NAME - 2 - number_str_len - 1;
1668 base_name[base_name_len] = '\0';
1670 /* Code above may have generated invalid utf-8 string, due to raw truncation.
1671 * Ensure we get a valid one now. */
1672 base_name_len -= (size_t)BLI_utf8_invalid_strip(base_name, base_name_len);
1674 /* Also truncate orig name, and start the whole check again. */
1675 name[base_name_len] = '\0';
1679 /* We have our final number, we can put it in name and exit the function. */
1680 BLI_strncpy(name + base_name_len, number_str, number_str_len + 1);
1685 * Check to see if an ID name is already used, and find a new one if so.
1686 * Return true if a new name was created (returned in name).
1688 * Normally the ID that's being checked is already in the ListBase, so ID *id points at the new
1689 * entry. The Python Library module needs to know what the name of a data-block will be before it
1690 * is appended, in this case ID *id is NULL.
1692 static bool check_for_dupid(ListBase *lb, ID *id, char *name, ID **r_id_sorting_hint)
1694 BLI_assert(strlen(name) < MAX_ID_NAME - 2);
1696 *r_id_sorting_hint = NULL;
1698 ID *id_test = lb->first;
1699 bool is_name_changed = false;
1701 if (id_test == NULL) {
1702 return is_name_changed;
1705 const short id_type = (short)GS(id_test->name);
1707 /* Static storage of previous handled ID/name info, used to perform a quicker test and optimize
1708 * creation of huge number of IDs using the same given base name. */
1709 static char prev_orig_base_name[MAX_ID_NAME - 2] = {0};
1710 static char prev_final_base_name[MAX_ID_NAME - 2] = {0};
1711 static short prev_id_type = ID_LINK_PLACEHOLDER; /* Should never exist in actual ID list. */
1712 static int prev_number = MIN_NUMBER - 1;
1714 /* Initial test to check whether we can 'shortcut' the more complex loop of the main code below.
1715 * Note that we do not do that for low numbers, as that would prevent using actual smallest
1716 * available number in some cases, and benefits of this special case handling mostly show up with
1717 * high numbers anyway. */
1718 if (id_type == prev_id_type && prev_number >= MAX_NUMBERS_IN_USE &&
1719 prev_number < MAX_NUMBER - 1 && name[0] == prev_final_base_name[0]) {
1721 /* Get the name and number parts ("name.number"). */
1722 char base_name[MAX_ID_NAME - 2];
1723 int number = MIN_NUMBER;
1724 size_t base_name_len = BLI_split_name_num(base_name, &number, name, '.');
1725 size_t prev_final_base_name_len = strlen(prev_final_base_name);
1726 size_t prev_orig_base_name_len = strlen(prev_orig_base_name);
1728 if (base_name_len == prev_orig_base_name_len &&
1729 STREQLEN(base_name, prev_orig_base_name, prev_orig_base_name_len)) {
1730 /* Once we have ensured given base_name and original previous one are the same, we can check
1731 * that previously used number is actually used, and that next one is free. */
1732 /* Note that from now on, we only used previous final base name, as it might have been
1733 * truncated from original one due to number suffix length. */
1734 char final_name[MAX_ID_NAME - 2];
1735 char prev_final_name[MAX_ID_NAME - 2];
1736 BLI_strncpy(final_name, prev_final_base_name, prev_final_base_name_len + 1);
1737 BLI_strncpy(prev_final_name, prev_final_base_name, prev_final_base_name_len + 1);
1739 if (id_name_final_build(final_name, base_name, prev_final_base_name_len, prev_number + 1) &&
1740 id_name_final_build(prev_final_name, base_name, prev_final_base_name_len, prev_number)) {
1741 /* We successfully built valid final names of previous and current iterations,
1742 * now we have to ensure that previous final name is indeed used in current ID list,
1743 * and that current one is not. */
1744 bool is_valid = false;
1745 for (id_test = lb->first; id_test; id_test = id_test->next) {
1746 if (id != id_test && !ID_IS_LINKED(id_test)) {
1747 if (id_test->name[2] == final_name[0] && STREQ(final_name, id_test->name + 2)) {
1748 /* We expect final_name to not be already used, so this is a failure. */
1752 /* Previous final name should only be found once in the list, so if it was found
1753 * already, no need to do a string comparison again. */
1754 if (!is_valid && id_test->name[2] == prev_final_name[0] &&
1755 STREQ(prev_final_name, id_test->name + 2)) {
1757 *r_id_sorting_hint = id_test;
1763 /* Only the number changed, prev_orig_base_name, prev_final_base_name and prev_id_type
1764 * remain the same. */
1767 strcpy(name, final_name);
1774 /* To speed up finding smallest unused number within [0 .. MAX_NUMBERS_IN_USE - 1].
1775 * We do not bother beyond that point. */
1776 ID *ids_in_use[MAX_NUMBERS_IN_USE] = {NULL};
1778 bool is_first_run = true;
1780 /* Get the name and number parts ("name.number"). */
1781 char base_name[MAX_ID_NAME - 2];
1782 int number = MIN_NUMBER;
1783 size_t base_name_len = BLI_split_name_num(base_name, &number, name, '.');
1785 /* Store previous original given base name now, as we might alter it later in code below. */
1787 strcpy(prev_orig_base_name, base_name);
1788 is_first_run = false;
1791 /* In case we get an insane initial number suffix in given name. */
1792 /* Note: BLI_split_name_num() cannot return negative numbers, so we do not have to check for
1794 if (number >= MAX_NUMBER || number < MIN_NUMBER) {
1795 number = MIN_NUMBER;
1798 bool is_orig_name_used = false;
1799 for (id_test = lb->first; id_test; id_test = id_test->next) {
1800 char base_name_test[MAX_ID_NAME - 2];
1802 if ((id != id_test) && !ID_IS_LINKED(id_test) && (name[0] == id_test->name[2]) &&
1803 (id_test->name[base_name_len + 2] == '.' || id_test->name[base_name_len + 2] == '\0') &&
1804 STREQLEN(name, id_test->name + 2, base_name_len) &&
1805 (BLI_split_name_num(base_name_test, &number_test, id_test->name + 2, '.') ==
1807 /* If we did not yet encounter exact same name as the given one, check the remaining parts
1808 * of the strings. */
1809 if (!is_orig_name_used) {
1810 is_orig_name_used = STREQ(name + base_name_len, id_test->name + 2 + base_name_len);
1812 /* Mark number of current id_test name as used, if possible. */
1813 if (number_test < MAX_NUMBERS_IN_USE) {
1814 ids_in_use[number_test] = id_test;
1816 /* Keep track of first largest unused number. */
1817 if (number <= number_test) {
1818 *r_id_sorting_hint = id_test;
1819 number = number_test + 1;
1824 /* If there is no double, we are done.
1825 * Note however that name might have been changed (truncated) in a previous iteration already.
1827 if (!is_orig_name_used) {
1828 /* Don't bother updating prev_ static variables here, this case is not supposed to happen
1829 * that often, and is not straight-forward here, so just ignore and reset them to default. */
1830 prev_id_type = ID_LINK_PLACEHOLDER;
1831 prev_final_base_name[0] = '\0';
1832 prev_number = MIN_NUMBER - 1;
1834 /* Value set previously is meaningless in that case. */
1835 *r_id_sorting_hint = NULL;
1837 return is_name_changed;
1840 /* Decide which value of number to use, either the smallest unused one if possible, or default
1841 * to the first largest unused one we got from previous loop. */
1842 for (int i = MIN_NUMBER; i < MAX_NUMBERS_IN_USE; i++) {
1843 if (ids_in_use[i] == NULL) {
1846 *r_id_sorting_hint = ids_in_use[i - 1];
1851 /* At this point, number is either the lowest unused number within
1852 * [MIN_NUMBER .. MAX_NUMBERS_IN_USE - 1], or 1 greater than the largest used number if all
1853 * those low ones are taken.
1854 * We can't be bothered to look for the lowest unused number beyond
1855 * (MAX_NUMBERS_IN_USE - 1).
1857 /* We know for wure that name will be changed. */
1858 is_name_changed = true;
1860 /* If id_name_final_build helper returns false, it had to truncate further given name, hence we
1861 * have to go over the whole check again. */
1862 if (!id_name_final_build(name, base_name, base_name_len, number)) {
1863 /* We have to clear our list of small used numbers before we do the whole check again. */
1864 memset(ids_in_use, 0, sizeof(ids_in_use));
1869 /* Update prev_ static variables, in case next call is for the same type of IDs and with the
1870 * same initial base name, we can skip a lot of above process. */
1871 prev_id_type = id_type;
1872 strcpy(prev_final_base_name, base_name);
1873 prev_number = number;
1875 return is_name_changed;
1878 #undef MAX_NUMBERS_IN_USE
1885 * Ensures given ID has a unique name in given listbase.
1887 * Only for local IDs (linked ones already have a unique ID in their library).
1889 * \return true if a new name had to be created.
1891 bool BKE_id_new_name_validate(ListBase *lb, ID *id, const char *tname)
1894 char name[MAX_ID_NAME - 2];
1896 /* if library, don't rename */
1897 if (ID_IS_LINKED(id)) {
1901 /* if no name given, use name of current ID
1902 * else make a copy (tname args can be const) */
1903 if (tname == NULL) {
1904 tname = id->name + 2;
1907 BLI_strncpy(name, tname, sizeof(name));
1909 if (name[0] == '\0') {
1910 /* Disallow empty names. */
1911 BLI_strncpy(name, DATA_(BKE_idcode_to_name(GS(id->name))), sizeof(name));
1914 /* disallow non utf8 chars,
1915 * the interface checks for this but new ID's based on file names don't */
1916 BLI_utf8_invalid_strip(name, strlen(name));
1919 ID *id_sorting_hint = NULL;
1920 result = check_for_dupid(lb, id, name, &id_sorting_hint);
1921 strcpy(id->name + 2, name);
1923 /* This was in 2.43 and previous releases
1924 * however all data in blender should be sorted, not just duplicate names
1925 * sorting should not hurt, but noting just in case it alters the way other
1926 * functions work, so sort every time. */
1929 id_sort_by_name(lb, id, id_sorting_hint);
1933 id_sort_by_name(lb, id, id_sorting_hint);
1939 * Pull an ID out of a library (make it local). Only call this for IDs that
1940 * don't have other library users.
1942 void id_clear_lib_data_ex(Main *bmain, ID *id, const bool id_in_mainlist)
1944 bNodeTree *ntree = NULL;
1947 BKE_id_lib_local_paths(bmain, id->lib, id);
1949 id_fake_user_clear(id);
1952 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1953 id->flag &= ~LIB_INDIRECT_WEAK_LINK;
1954 if (id_in_mainlist) {
1955 if (BKE_id_new_name_validate(which_libbase(bmain, GS(id->name)), id, NULL)) {
1956 bmain->is_memfile_undo_written = false;
1960 /* Internal bNodeTree blocks inside data-blocks also stores id->lib,
1961 * make sure this stays in sync. */
1962 if ((ntree = ntreeFromID(id))) {
1963 id_clear_lib_data_ex(bmain, &ntree->id, false); /* Datablocks' nodetree is never in Main. */
1966 /* Same goes for shapekeys. */
1967 if ((key = BKE_key_from_id(id))) {
1968 id_clear_lib_data_ex(bmain, &key->id, id_in_mainlist); /* sigh, why are keys in Main? */
1972 void id_clear_lib_data(Main *bmain, ID *id)
1974 id_clear_lib_data_ex(bmain, id, true);
1977 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1978 void BKE_main_id_clear_newpoins(Main *bmain)
1982 FOREACH_MAIN_ID_BEGIN (bmain, id) {
1984 id->tag &= ~LIB_TAG_NEW;
1986 FOREACH_MAIN_ID_END;
1989 static int id_refcount_recompute_callback(void *user_data,
1990 struct ID *UNUSED(id_self),
1991 struct ID **id_pointer,
1994 const bool do_linked_only = (bool)POINTER_AS_INT(user_data);
1996 if (*id_pointer == NULL) {
1997 return IDWALK_RET_NOP;
1999 if (do_linked_only && !ID_IS_LINKED(*id_pointer)) {
2000 return IDWALK_RET_NOP;
2003 if (cb_flag & IDWALK_CB_USER) {
2004 /* Do not touch to direct/indirect linked status here... */
2005 id_us_plus_no_lib(*id_pointer);
2007 if (cb_flag & IDWALK_CB_USER_ONE) {
2008 id_us_ensure_real(*id_pointer);
2011 return IDWALK_RET_NOP;
2014 void BKE_main_id_refcount_recompute(struct Main *bmain, const bool do_linked_only)
2018 FOREACH_MAIN_ID_BEGIN (bmain, id) {
2019 if (!ID_IS_LINKED(id) && do_linked_only) {
2022 id->us = ID_FAKE_USERS(id);
2023 /* Note that we keep EXTRAUSER tag here, since some UI users may define it too... */
2024 if (id->tag & LIB_TAG_EXTRAUSER) {
2025 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
2026 id_us_ensure_real(id);
2029 FOREACH_MAIN_ID_END;
2031 /* Go over whole Main database to re-generate proper usercounts... */
2032 FOREACH_MAIN_ID_BEGIN (bmain, id) {
2033 BKE_library_foreach_ID_link(bmain,
2035 id_refcount_recompute_callback,
2036 POINTER_FROM_INT((int)do_linked_only),
2039 FOREACH_MAIN_ID_END;
2042 static void library_make_local_copying_check(ID *id,
2044 MainIDRelations *id_relations,
2047 if (BLI_gset_haskey(done_ids, id)) {
2048 return; /* Already checked, nothing else to do. */
2051 MainIDRelationsEntry *entry = BLI_ghash_lookup(id_relations->id_used_to_user, id);
2052 BLI_gset_insert(loop_tags, id);
2053 for (; entry != NULL; entry = entry->next) {
2055 /* Used_to_user stores ID pointer, not pointer to ID pointer. */
2056 ID *par_id = (ID *)entry->id_pointer;
2058 /* Our oh-so-beloved 'from' pointers... */
2059 if (entry->usage_flag & IDWALK_CB_LOOPBACK) {
2060 /* We totally disregard Object->proxy_from 'usage' here,
2061 * this one would only generate fake positives. */
2062 if (GS(par_id->name) == ID_OB) {
2063 BLI_assert(((Object *)par_id)->proxy_from == (Object *)id);
2067 /* Shapekeys are considered 'private' to their owner ID here, and never tagged
2068 * (since they cannot be linked), * so we have to switch effective parent to their owner.
2070 if (GS(par_id->name) == ID_KE) {
2071 par_id = ((Key *)par_id)->from;
2075 if (par_id->lib == NULL) {
2076 /* Local user, early out to avoid some gset querying... */
2079 if (!BLI_gset_haskey(done_ids, par_id)) {
2080 if (BLI_gset_haskey(loop_tags, par_id)) {
2081 /* We are in a 'dependency loop' of IDs, this does not say us anything, skip it.
2082 * Note that this is the situation that can lead to archipelagoes of linked data-blocks
2083 * (since all of them have non-local users, they would all be duplicated,
2084 * leading to a loop of unused linked data-blocks that cannot be freed since they all use
2085 * each other...). */
2088 /* Else, recursively check that user ID. */
2089 library_make_local_copying_check(par_id, loop_tags, id_relations, done_ids);
2092 if (par_id->tag & LIB_TAG_DOIT) {
2093 /* This user will be fully local in future, so far so good,
2094 * nothing to do here but check next user. */
2097 /* This user won't be fully local in future, so current ID won't be either.
2098 * And we are done checking it. */
2099 id->tag &= ~LIB_TAG_DOIT;
2103 BLI_gset_add(done_ids, id);
2104 BLI_gset_remove(loop_tags, id, NULL);
2108 * Make linked data-blocks local.
2110 * \param bmain: Almost certainly global main.
2111 * \param lib: If not NULL, only make local data-blocks from this library.
2112 * \param untagged_only: If true, only make local data-blocks not tagged with
2113 * LIB_TAG_PRE_EXISTING.
2114 * \param set_fake: If true, set fake user on all localized data-blocks
2115 * (except group and objects ones).
2117 /* Note: Old (2.77) version was simply making (tagging) data-blocks as local,
2118 * without actually making any check whether they were also indirectly used or not...
2120 * Current version uses regular id_make_local callback, with advanced pre-processing step to
2121 * detect all cases of IDs currently indirectly used, but which will be used by local data only
2122 * once this function is finished. This allows to avoid any unneeded duplication of IDs, and
2123 * hence all time lost afterwards to remove orphaned linked data-blocks...
2125 void BKE_library_make_local(Main *bmain,
2127 GHash *old_to_new_ids,
2128 const bool untagged_only,
2129 const bool set_fake)
2131 ListBase *lbarray[MAX_LIBARRAY];
2133 LinkNode *todo_ids = NULL;
2134 LinkNode *copied_ids = NULL;
2135 MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
2137 GSet *done_ids = BLI_gset_ptr_new(__func__);
2140 TIMEIT_START(make_local);
2143 BKE_main_relations_create(bmain);
2146 printf("Pre-compute current ID relations: Done.\n");
2147 TIMEIT_VALUE_PRINT(make_local);
2150 /* Step 1: Detect data-blocks to make local. */
2151 for (int a = set_listbasepointers(bmain, lbarray); a--;) {
2152 ID *id = lbarray[a]->first;
2154 /* Do not explicitly make local non-linkable IDs (shapekeys, in fact),
2155 * they are assumed to be handled by real data-blocks responsible of them. */
2156 const bool do_skip = (id && !BKE_idcode_is_linkable(GS(id->name)));
2158 for (; id; id = id->next) {
2159 ID *ntree = (ID *)ntreeFromID(id);
2161 id->tag &= ~LIB_TAG_DOIT;
2162 if (ntree != NULL) {
2163 ntree->tag &= ~LIB_TAG_DOIT;
2166 if (id->lib == NULL) {
2167 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
2168 id->flag &= ~LIB_INDIRECT_WEAK_LINK;
2170 /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so it's possible to tag data
2171 * you don't want to be made local, used for appending data,
2172 * so any libdata already linked wont become local (very nasty
2173 * to discover all your links are lost after appending).
2174 * Also, never ever make proxified objects local, would not make any sense. */
2176 * - Shapekeys are never tagged here (since they are not linkable).
2177 * - Nodetrees used in materials etc. have to be tagged manually,
2178 * since they do not exist in Main (!).
2179 * This is ok-ish on 'make local' side of things
2180 * (since those are handled by their 'owner' IDs),
2181 * but complicates slightly the pre-processing of relations between IDs at step 2... */
2182 else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
2183 ELEM(lib, NULL, id->lib) &&
2184 !(GS(id->name) == ID_OB && ((Object *)id)->proxy_from != NULL) &&
2185 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING))) {
2186 BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem);
2187 id->tag |= LIB_TAG_DOIT;
2189 /* Tag those nasty non-ID nodetrees,
2190 * but do not add them to todo list, making them local is handled by 'owner' ID.
2191 * This is needed for library_make_local_copying_check() to work OK at step 2. */
2192 if (ntree != NULL) {
2193 ntree->tag |= LIB_TAG_DOIT;
2197 /* Linked ID that we won't be making local (needed info for step 2, see below). */
2198 BLI_gset_add(done_ids, id);
2204 printf("Step 1: Detect data-blocks to make local: Done.\n");
2205 TIMEIT_VALUE_PRINT(make_local);
2208 /* Step 2: Check which data-blocks we can directly make local
2209 * (because they are only used by already, or future, local data),
2210 * others will need to be duplicated. */
2211 GSet *loop_tags = BLI_gset_ptr_new(__func__);
2212 for (LinkNode *it = todo_ids; it; it = it->next) {
2213 library_make_local_copying_check(it->link, loop_tags, bmain->relations, done_ids);
2214 BLI_assert(BLI_gset_len(loop_tags) == 0);
2216 BLI_gset_free(loop_tags, NULL);
2217 BLI_gset_free(done_ids, NULL);
2219 /* Next step will most likely add new IDs, better to get rid of this mapping now. */
2220 BKE_main_relations_free(bmain);
2223 printf("Step 2: Check which data-blocks we can directly make local: Done.\n");
2224 TIMEIT_VALUE_PRINT(make_local);
2227 /* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
2228 * which involves more complex checks and might instead
2229 * create a local copy of original linked ID. */
2230 for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
2234 if (id->tag & LIB_TAG_DOIT) {
2235 /* We know all users of this object are local or will be made fully local, even if
2236 * currently there are some indirect usages. So instead of making a copy that we'll likely
2237 * get rid of later, directly make that data block local.
2238 * Saves a tremendous amount of time with complex scenes... */
2239 id_clear_lib_data_ex(bmain, id, true);
2240 BKE_id_expand_local(bmain, id);
2241 id->tag &= ~LIB_TAG_DOIT;
2243 if (GS(id->name) == ID_OB) {
2244 BKE_rigidbody_ensure_local_object(bmain, (Object *)id);
2248 /* In this specific case, we do want to make ID local even if it has no local usage yet...
2250 if (GS(id->name) == ID_OB) {
2251 /* Special case for objects because we don't want proxy pointers to be
2252 * cleared yet. This will happen down the road in this function.
2254 BKE_object_make_local_ex(bmain, (Object *)id, true, false);
2257 id_make_local(bmain, id, false, true);
2261 if (GS(id->newid->name) == ID_OB) {
2262 BKE_rigidbody_ensure_local_object(bmain, (Object *)id->newid);
2265 /* Reuse already allocated LinkNode (transferring it from todo_ids to copied_ids). */
2266 BLI_linklist_prepend_nlink(&copied_ids, id, it);
2271 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
2272 /* do not set fake user on objects, groups (instancing) */
2273 id_fake_user_set(id);
2279 printf("Step 3: Make IDs local: Done.\n");
2280 TIMEIT_VALUE_PRINT(make_local);
2283 /* At this point, we are done with directly made local IDs.
2284 * Now we have to handle duplicated ones, since their
2285 * remaining linked original counterpart may not be needed anymore... */
2288 /* Step 4: We have to remap local usages of old (linked) ID to new (local)
2289 * ID in a separated loop,
2290 * as lbarray ordering is not enough to ensure us we did catch all dependencies
2291 * (e.g. if making local a parent object before its child...). See T48907. */
2292 /* TODO This is now the biggest step by far (in term of processing time).
2293 * We may be able to gain here by using again main->relations mapping, but...
2294 * this implies BKE_libblock_remap & co to be able to update main->relations on the fly.
2295 * Have to think about it a bit more, and see whether new code is OK first, anyway. */
2296 for (LinkNode *it = copied_ids; it; it = it->next) {
2299 BLI_assert(id->newid != NULL);
2300 BLI_assert(id->lib != NULL);
2302 BKE_libblock_remap(bmain, id, id->newid, ID_REMAP_SKIP_INDIRECT_USAGE);
2303 if (old_to_new_ids) {
2304 BLI_ghash_insert(old_to_new_ids, id, id->newid);
2307 /* Special hack for groups... Thing is, since we can't instantiate them here, we need to
2308 * ensure they remain 'alive' (only instantiation is a real group 'user'... *sigh* See
2310 if (GS(id->name) == ID_GR && (id->tag & LIB_TAG_INDIRECT) != 0) {
2311 id_us_ensure_real(id->newid);
2316 printf("Step 4: Remap local usages of old (linked) ID to new (local) ID: Done.\n");
2317 TIMEIT_VALUE_PRINT(make_local);
2320 /* Step 5: proxy 'remapping' hack. */
2321 for (LinkNode *it = copied_ids; it; it = it->next) {
2324 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
2325 * from another blend file into this one, even when that blend file contains proxified
2326 * armatures that have local references. Since the proxified object needs to be linked
2327 * (not local), this will only work when the "Localize all" checkbox is disabled.
2328 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
2329 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
2330 Object *ob = (Object *)id;
2331 Object *ob_new = (Object *)id->newid;
2332 bool is_local = false, is_lib = false;
2334 /* Proxies only work when the proxified object is linked-in from a library. */
2335 if (ob->proxy->id.lib == NULL) {
2337 "proxy object %s will loose its link to %s, because the "
2338 "proxified object is local.",
2340 ob->proxy->id.name);
2344 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
2346 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
2347 * referred to from a library. Not checking for local use; if new local proxy
2348 * was not used locally would be a nasty bug! */
2349 if (is_local || is_lib) {
2351 "made-local proxy object %s will loose its link to %s, "
2352 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).",
2359 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
2360 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
2361 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy). */
2362 ob_new->proxy = ob->proxy;
2363 ob_new->proxy_group = ob->proxy_group;
2364 ob_new->proxy_from = ob->proxy_from;
2365 ob_new->proxy->proxy_from = ob_new;
2366 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
2372 printf("Step 5: Proxy 'remapping' hack: Done.\n");
2373 TIMEIT_VALUE_PRINT(make_local);
2376 /* This is probably more of a hack than something we should do here, but...
2377 * Issue is, the whole copying + remapping done in complex cases above may leave pose-channels
2378 * of armatures in complete invalid state (more precisely, the bone pointers of the
2379 * pose-channels - very crappy cross-data-blocks relationship), se we tag it to be fully
2380 * recomputed, but this does not seems to be enough in some cases, and evaluation code ends up
2381 * trying to evaluate a not-yet-updated armature object's deformations.
2382 * Try "make all local" in 04_01_H.lighting.blend from Agent327 without this, e.g. */
2383 for (Object *ob = bmain->objects.first; ob; ob = ob->id.next) {
2384 if (ob->data != NULL && ob->type == OB_ARMATURE && ob->pose != NULL &&
2385 ob->pose->flag & POSE_RECALC) {
2386 BKE_pose_rebuild(bmain, ob, ob->data, true);
2391 printf("Hack: Forcefully rebuild armature object poses: Done.\n");
2392 TIMEIT_VALUE_PRINT(make_local);
2395 BKE_main_id_clear_newpoins(bmain);
2396 BLI_memarena_free(linklist_mem);
2399 printf("Cleanup and finish: Done.\n");
2400 TIMEIT_END(make_local);
2405 * Use after setting the ID's name
2406 * When name exists: call 'new_id'
2408 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
2413 lb = which_libbase(bmain, GS(name));
2419 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
2420 if (idtest != NULL) {
2421 /* BKE_id_new_name_validate also takes care of sorting. */
2422 BKE_id_new_name_validate(lb, idtest, NULL);
2423 bmain->is_memfile_undo_written = false;
2428 * Sets the name of a block to name, suitably adjusted for uniqueness.
2430 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
2432 ListBase *lb = which_libbase(bmain, GS(id->name));
2433 if (BKE_id_new_name_validate(lb, id, name)) {
2434 bmain->is_memfile_undo_written = false;
2439 * Generate full name of the data-block (without ID code, but with library if any).
2441 * \note Result is unique to a given ID type in a given Main database.
2443 * \param name: An allocated string of minimal length #MAX_ID_FULL_NAME,
2444 * will be filled with generated string.
2446 void BKE_id_full_name_get(char name[MAX_ID_FULL_NAME], const ID *id)
2448 strcpy(name, id->name + 2);
2450 if (id->lib != NULL) {
2451 const size_t idname_len = strlen(id->name + 2);
2452 const size_t libname_len = strlen(id->lib->id.name + 2);
2454 name[idname_len] = ' ';
2455 name[idname_len + 1] = '[';
2456 strcpy(name + idname_len + 2, id->lib->id.name + 2);
2457 name[idname_len + 2 + libname_len] = ']';
2458 name[idname_len + 2 + libname_len + 1] = '\0';
2463 * Generate full name of the data-block (without ID code, but with library if any),
2464 * with a 3-character prefix prepended indicating whether it comes from a library,
2465 * is overriding, has a fake or no user, etc.
2467 * \note Result is unique to a given ID type in a given Main database.
2469 * \param name: An allocated string of minimal length #MAX_ID_FULL_NAME_UI,
2470 * will be filled with generated string.
2472 void BKE_id_full_name_ui_prefix_get(char name[MAX_ID_FULL_NAME_UI], const ID *id)
2474 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ID_IS_OVERRIDE_LIBRARY(id) ? 'O' : ' ';
2475 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
2478 BKE_id_full_name_get(name + 3, id);
2482 * Generate a concatenation of ID name (including two-chars type code) and its lib name, if any.
2484 * \return A unique allocated string key for any ID in the whole Main database.
2486 char *BKE_id_to_unique_string_key(const struct ID *id)
2488 if (id->lib == NULL) {
2489 return BLI_strdup(id->name);
2492 /* Prefix with an ascii character in the range of 32..96 (visible)
2493 * this ensures we can't have a library ID pair that collide.
2494 * Where 'LIfooOBbarOBbaz' could be ('LIfoo, OBbarOBbaz') or ('LIfooOBbar', 'OBbaz'). */
2495 const char ascii_len = strlen(id->lib->id.name + 2) + 32;
2496 return BLI_sprintfN("%c%s%s", ascii_len, id->lib->id.name, id->name);
2500 void BKE_id_tag_set_atomic(ID *id, int tag)
2502 atomic_fetch_and_or_int32(&id->tag, tag);
2505 void BKE_id_tag_clear_atomic(ID *id, int tag)
2507 atomic_fetch_and_and_int32(&id->tag, ~tag);
2511 * Check that given ID pointer actually is in G_MAIN.
2512 * Main intended use is for debug asserts in places we cannot easily get rid of G_Main...
2514 bool BKE_id_is_in_global_main(ID *id)
2516 /* We do not want to fail when id is NULL here, even though this is a bit strange behavior...
2518 return (id == NULL || BLI_findindex(which_libbase(G_MAIN, GS(id->name)), id) != -1);
2521 /************************* Datablock order in UI **************************/
2523 static int *id_order_get(ID *id)
2525 /* Only for workspace tabs currently. */
2526 switch (GS(id->name)) {
2528 return &((WorkSpace *)id)->order;
2534 static int id_order_compare(const void *a, const void *b)
2536 ID *id_a = ((LinkData *)a)->data;
2537 ID *id_b = ((LinkData *)b)->data;
2539 int *order_a = id_order_get(id_a);
2540 int *order_b = id_order_get(id_b);
2542 if (order_a && order_b) {
2543 if (*order_a < *order_b) {
2546 else if (*order_a > *order_b) {
2551 return strcmp(id_a->name, id_b->name);
2555 * Returns ordered list of data-blocks for display in the UI.
2556 * Result is list of LinkData of IDs that must be freed.
2558 void BKE_id_ordered_list(ListBase *ordered_lb, const ListBase *lb)
2560 BLI_listbase_clear(ordered_lb);
2562 for (ID *id = lb->first; id; id = id->next) {
2563 BLI_addtail(ordered_lb, BLI_genericNodeN(id));
2566 BLI_listbase_sort(ordered_lb, id_order_compare);
2569 for (LinkData *link = ordered_lb->first; link; link = link->next) {
2570 int *order = id_order_get(link->data);
2578 * Reorder ID in the list, before or after the "relative" ID.
2580 void BKE_id_reorder(const ListBase *lb, ID *id, ID *relative, bool after)
2582 int *id_order = id_order_get(id);
2586 relative_order = *id_order_get(relative);
2589 relative_order = (after) ? BLI_listbase_count(lb) : 0;
2594 for (ID *other = lb->first; other; other = other->next) {
2595 int *order = id_order_get(other);
2596 if (*order > relative_order) {
2601 *id_order = relative_order + 1;
2604 /* Insert before. */
2605 for (ID *other = lb->first; other; other = other->next) {
2606 int *order = id_order_get(other);
2607 if (*order < relative_order) {
2612 *id_order = relative_order - 1;