2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/library.c
31 * Contains management of ID's and libraries
32 * allocate and free of all library data
42 #include "MEM_guardedalloc.h"
44 /* all types are needed here, in order to do memory operations */
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_brush_types.h"
48 #include "DNA_cachefile_types.h"
49 #include "DNA_camera_types.h"
50 #include "DNA_group_types.h"
51 #include "DNA_gpencil_types.h"
52 #include "DNA_ipo_types.h"
53 #include "DNA_key_types.h"
54 #include "DNA_lamp_types.h"
55 #include "DNA_lattice_types.h"
56 #include "DNA_linestyle_types.h"
57 #include "DNA_material_types.h"
58 #include "DNA_mesh_types.h"
59 #include "DNA_meta_types.h"
60 #include "DNA_modifier_types.h"
61 #include "DNA_movieclip_types.h"
62 #include "DNA_mask_types.h"
63 #include "DNA_node_types.h"
64 #include "DNA_object_types.h"
65 #include "DNA_scene_types.h"
66 #include "DNA_screen_types.h"
67 #include "DNA_speaker_types.h"
68 #include "DNA_sound_types.h"
69 #include "DNA_text_types.h"
70 #include "DNA_vfont_types.h"
71 #include "DNA_windowmanager_types.h"
72 #include "DNA_world_types.h"
74 #include "BLI_blenlib.h"
75 #include "BLI_utildefines.h"
76 #include "BLI_ghash.h"
77 #include "BLI_linklist.h"
78 #include "BLI_memarena.h"
79 #include "BLI_string_utils.h"
81 #include "BLI_threads.h"
82 #include "BLT_translation.h"
84 #include "BKE_action.h"
85 #include "BKE_animsys.h"
86 #include "BKE_armature.h"
87 #include "BKE_bpath.h"
88 #include "BKE_brush.h"
89 #include "BKE_camera.h"
90 #include "BKE_cachefile.h"
91 #include "BKE_context.h"
92 #include "BKE_curve.h"
93 #include "BKE_depsgraph.h"
95 #include "BKE_global.h"
96 #include "BKE_group.h"
97 #include "BKE_gpencil.h"
98 #include "BKE_idcode.h"
99 #include "BKE_idprop.h"
100 #include "BKE_image.h"
102 #include "BKE_lamp.h"
103 #include "BKE_lattice.h"
104 #include "BKE_library.h"
105 #include "BKE_library_query.h"
106 #include "BKE_library_remap.h"
107 #include "BKE_linestyle.h"
108 #include "BKE_mesh.h"
109 #include "BKE_material.h"
110 #include "BKE_main.h"
111 #include "BKE_mball.h"
112 #include "BKE_mask.h"
113 #include "BKE_movieclip.h"
114 #include "BKE_node.h"
115 #include "BKE_object.h"
116 #include "BKE_paint.h"
117 #include "BKE_particle.h"
118 #include "BKE_packedFile.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"
135 /* GS reads the memory pointed at in a specific ordering.
136 * only use this definition, makes little and big endian systems
137 * work fine, in conjunction with MAKE_ID */
139 /* ************* general ************************ */
142 /* this has to be called from each make_local_* func, we could call
143 * from id_make_local() but then the make local functions would not be self
145 * also note that the id _must_ have a library - campbell */
146 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
148 const char *bpath_user_data[2] = {bmain->name, lib->filepath};
150 BKE_bpath_traverse_id(bmain, id,
151 BKE_bpath_relocate_visitor,
152 BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
153 (void *)bpath_user_data);
156 void id_lib_extern(ID *id)
158 if (id && ID_IS_LINKED_DATABLOCK(id)) {
159 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
160 if (id->tag & LIB_TAG_INDIRECT) {
161 id->tag -= LIB_TAG_INDIRECT;
162 id->tag |= LIB_TAG_EXTERN;
167 /* ensure we have a real user */
168 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
169 * we always have a real user.
170 * However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
171 * to make this change... */
172 void id_us_ensure_real(ID *id)
175 const int limit = ID_FAKE_USERS(id);
176 id->tag |= LIB_TAG_EXTRAUSER;
177 if (id->us <= limit) {
178 if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
179 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
183 id->tag |= LIB_TAG_EXTRAUSER_SET;
188 void id_us_clear_real(ID *id)
190 if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
191 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
193 BLI_assert(id->us >= ID_FAKE_USERS(id));
195 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
200 * Same as \a id_us_plus, but does not handle lib indirect -> extern.
201 * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
203 void id_us_plus_no_lib(ID *id)
206 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
207 BLI_assert(id->us >= 1);
208 /* No need to increase count, just tag extra user as no more set.
209 * Avoids annoying & inconsistent +1 in user count. */
210 id->tag &= ~LIB_TAG_EXTRAUSER_SET;
213 BLI_assert(id->us >= 0);
220 void id_us_plus(ID *id)
223 id_us_plus_no_lib(id);
228 /* decrements the user count for *id. */
229 void id_us_min(ID *id)
232 const int limit = ID_FAKE_USERS(id);
234 if (id->us <= limit) {
235 printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
236 id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
244 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
245 /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
246 id_us_ensure_real(id);
251 void id_fake_user_set(ID *id)
253 if (id && !(id->flag & LIB_FAKEUSER)) {
254 id->flag |= LIB_FAKEUSER;
259 void id_fake_user_clear(ID *id)
261 if (id && (id->flag & LIB_FAKEUSER)) {
262 id->flag &= ~LIB_FAKEUSER;
267 void BKE_id_clear_newpoin(ID *id)
270 id->newid->tag &= ~LIB_TAG_NEW;
275 static int id_expand_local_callback(
276 void *UNUSED(user_data), struct ID *id_self, struct ID **id_pointer, int UNUSED(cd_flag))
278 /* Can hapen that we get unlinkable ID here, e.g. with shapekey referring to itself (through drivers)...
279 * Just skip it, shape key can only be either indirectly linked, or fully local, period.
280 * And let's curse one more time that stupid useless shapekey ID type! */
281 if (*id_pointer && *id_pointer != id_self && BKE_idcode_is_linkable(GS((*id_pointer)->name))) {
282 id_lib_extern(*id_pointer);
285 return IDWALK_RET_NOP;
289 * Expand ID usages of given id as 'extern' (and no more indirect) linked data. Used by ID copy/make_local functions.
291 void BKE_id_expand_local(ID *id)
293 BKE_library_foreach_ID_link(id, id_expand_local_callback, NULL, 0);
297 * Ensure new (copied) ID is fully made local.
299 void BKE_id_copy_ensure_local(Main *bmain, ID *old_id, ID *new_id)
301 if (ID_IS_LINKED_DATABLOCK(old_id)) {
302 BKE_id_expand_local(new_id);
303 BKE_id_lib_local_paths(bmain, old_id->lib, new_id);
308 * Generic 'make local' function, works for most of datablock types...
310 void BKE_id_make_local_generic(Main *bmain, ID *id, const bool id_in_mainlist, const bool lib_local)
312 bool is_local = false, is_lib = false;
314 /* - only lib users: do nothing (unless force_local is set)
315 * - only local users: set flag
317 * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
320 if (!ID_IS_LINKED_DATABLOCK(id)) {
324 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
326 if (lib_local || is_local) {
328 id_clear_lib_data_ex(bmain, id, id_in_mainlist);
329 BKE_id_expand_local(id);
334 /* Should not fail in expected usecases, but id_copy does not copy Scene e.g. */
335 if (id_copy(bmain, id, &id_new, false)) {
338 /* setting newid is mandatory for complex make_lib_local logic... */
339 ID_NEW_SET(id, id_new);
340 Key *key = BKE_key_from_id(id), *key_new = BKE_key_from_id(id);
341 if (key && key_new) {
342 ID_NEW_SET(key, key_new);
344 bNodeTree *ntree = ntreeFromID(id), *ntree_new = ntreeFromID(id_new);
345 if (ntree && ntree_new) {
346 ID_NEW_SET(ntree, ntree_new);
350 BKE_libblock_remap(bmain, id, id_new, ID_REMAP_SKIP_INDIRECT_USAGE);
358 * Calls the appropriate make_local method for the block, unless test is set.
360 * \note Always set ID->newid pointer in case it gets duplicated...
362 * \param lib_local Special flag used when making a whole library's content local, it needs specific handling.
364 * \return true if the block can be made local.
366 bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
368 /* We don't care whether ID is directly or indirectly linked in case we are making a whole lib local... */
369 if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) {
373 switch ((ID_Type)GS(id->name)) {
375 /* Partially implemented (has no copy...). */
376 if (!test) BKE_scene_make_local(bmain, (Scene *)id, lib_local);
379 if (!test) BKE_object_make_local(bmain, (Object *)id, lib_local);
382 if (!test) BKE_mesh_make_local(bmain, (Mesh *)id, lib_local);
385 if (!test) BKE_curve_make_local(bmain, (Curve *)id, lib_local);
388 if (!test) BKE_mball_make_local(bmain, (MetaBall *)id, lib_local);
391 if (!test) BKE_material_make_local(bmain, (Material *)id, lib_local);
394 if (!test) BKE_texture_make_local(bmain, (Tex *)id, lib_local);
397 if (!test) BKE_image_make_local(bmain, (Image *)id, lib_local);
400 if (!test) BKE_lattice_make_local(bmain, (Lattice *)id, lib_local);
403 if (!test) BKE_lamp_make_local(bmain, (Lamp *)id, lib_local);
406 if (!test) BKE_camera_make_local(bmain, (Camera *)id, lib_local);
409 if (!test) BKE_speaker_make_local(bmain, (Speaker *)id, lib_local);
412 if (!test) BKE_world_make_local(bmain, (World *)id, lib_local);
415 /* Partially implemented (has no copy...). */
416 if (!test) BKE_vfont_make_local(bmain, (VFont *)id, lib_local);
419 if (!test) BKE_text_make_local(bmain, (Text *)id, lib_local);
422 /* Partially implemented (has no copy...). */
423 if (!test) BKE_sound_make_local(bmain, (bSound *)id, lib_local);
426 if (!test) BKE_group_make_local(bmain, (Group *)id, lib_local);
429 if (!test) BKE_armature_make_local(bmain, (bArmature *)id, lib_local);
432 if (!test) BKE_action_make_local(bmain, (bAction *)id, lib_local);
435 if (!test) ntreeMakeLocal(bmain, (bNodeTree *)id, true, lib_local);
438 if (!test) BKE_brush_make_local(bmain, (Brush *)id, lib_local);
441 if (!test) BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, lib_local);
444 if (!test) BKE_gpencil_make_local(bmain, (bGPdata *)id, lib_local);
447 if (!test) BKE_movieclip_make_local(bmain, (MovieClip *)id, lib_local);
450 if (!test) BKE_mask_make_local(bmain, (Mask *)id, lib_local);
453 if (!test) BKE_linestyle_make_local(bmain, (FreestyleLineStyle *)id, lib_local);
456 if (!test) BKE_palette_make_local(bmain, (Palette *)id, lib_local);
459 if (!test) BKE_paint_curve_make_local(bmain, (PaintCurve *)id, lib_local);
462 if (!test) BKE_cachefile_make_local(bmain, (CacheFile *)id, lib_local);
468 return false; /* can't be linked */
470 return false; /* deprecated */
477 * Invokes the appropriate copy method for the block and returns the result in
478 * newid, unless test. Returns true if the block can be copied.
480 bool id_copy(Main *bmain, ID *id, ID **newid, bool test)
487 * - make shallow copy, only this ID block
488 * - id.us of the new ID is set to 1 */
489 switch ((ID_Type)GS(id->name)) {
491 if (!test) *newid = (ID *)BKE_object_copy(bmain, (Object *)id);
494 if (!test) *newid = (ID *)BKE_mesh_copy(bmain, (Mesh *)id);
497 if (!test) *newid = (ID *)BKE_curve_copy(bmain, (Curve *)id);
500 if (!test) *newid = (ID *)BKE_mball_copy(bmain, (MetaBall *)id);
503 if (!test) *newid = (ID *)BKE_material_copy(bmain, (Material *)id);
506 if (!test) *newid = (ID *)BKE_texture_copy(bmain, (Tex *)id);
509 if (!test) *newid = (ID *)BKE_image_copy(bmain, (Image *)id);
512 if (!test) *newid = (ID *)BKE_lattice_copy(bmain, (Lattice *)id);
515 if (!test) *newid = (ID *)BKE_lamp_copy(bmain, (Lamp *)id);
518 if (!test) *newid = (ID *)BKE_speaker_copy(bmain, (Speaker *)id);
521 if (!test) *newid = (ID *)BKE_camera_copy(bmain, (Camera *)id);
524 if (!test) *newid = (ID *)BKE_key_copy(bmain, (Key *)id);
527 if (!test) *newid = (ID *)BKE_world_copy(bmain, (World *)id);
530 if (!test) *newid = (ID *)BKE_text_copy(bmain, (Text *)id);
533 if (!test) *newid = (ID *)BKE_group_copy(bmain, (Group *)id);
536 if (!test) *newid = (ID *)BKE_armature_copy(bmain, (bArmature *)id);
539 if (!test) *newid = (ID *)BKE_action_copy(bmain, (bAction *)id);
542 if (!test) *newid = (ID *)ntreeCopyTree(bmain, (bNodeTree *)id);
545 if (!test) *newid = (ID *)BKE_brush_copy(bmain, (Brush *)id);
548 if (!test) *newid = (ID *)BKE_particlesettings_copy(bmain, (ParticleSettings *)id);
551 if (!test) *newid = (ID *)BKE_gpencil_data_duplicate(bmain, (bGPdata *)id, false);
554 if (!test) *newid = (ID *)BKE_movieclip_copy(bmain, (MovieClip *)id);
557 if (!test) *newid = (ID *)BKE_mask_copy(bmain, (Mask *)id);
560 if (!test) *newid = (ID *)BKE_linestyle_copy(bmain, (FreestyleLineStyle *)id);
563 if (!test) *newid = (ID *)BKE_palette_copy(bmain, (Palette *)id);
566 if (!test) *newid = (ID *)BKE_paint_curve_copy(bmain, (PaintCurve *)id);
569 if (!test) *newid = (ID *)BKE_cachefile_copy(bmain, (CacheFile *)id);
575 return false; /* can't be copied from here */
578 return false; /* not implemented */
580 return false; /* deprecated */
586 /** Does *not* set ID->newid pointer. */
587 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
593 /* if property isn't editable, we're going to have an extra block hanging around until we save */
594 if (RNA_property_editable(ptr, prop)) {
595 if (id_copy(CTX_data_main(C), id, &newid, false) && newid) {
596 /* copy animation actions too */
597 BKE_animdata_copy_id_action(id, false);
598 /* us is 1 by convention, but RNA_property_pointer_set
599 * will also increment it, so set it to zero */
603 RNA_id_pointer_create(newid, &idptr);
604 RNA_property_pointer_set(ptr, prop, idptr);
605 RNA_property_update(C, ptr, prop);
615 ListBase *which_libbase(Main *mainlib, short type)
617 switch ((ID_Type)type) {
619 return &(mainlib->scene);
621 return &(mainlib->library);
623 return &(mainlib->object);
625 return &(mainlib->mesh);
627 return &(mainlib->curve);
629 return &(mainlib->mball);
631 return &(mainlib->mat);
633 return &(mainlib->tex);
635 return &(mainlib->image);
637 return &(mainlib->latt);
639 return &(mainlib->lamp);
641 return &(mainlib->camera);
643 return &(mainlib->ipo);
645 return &(mainlib->key);
647 return &(mainlib->world);
649 return &(mainlib->screen);
651 return &(mainlib->vfont);
653 return &(mainlib->text);
655 return &(mainlib->speaker);
657 return &(mainlib->sound);
659 return &(mainlib->group);
661 return &(mainlib->armature);
663 return &(mainlib->action);
665 return &(mainlib->nodetree);
667 return &(mainlib->brush);
669 return &(mainlib->particle);
671 return &(mainlib->wm);
673 return &(mainlib->gpencil);
675 return &(mainlib->movieclip);
677 return &(mainlib->mask);
679 return &(mainlib->linestyle);
681 return &(mainlib->palettes);
683 return &(mainlib->paintcurves);
685 return &(mainlib->cachefiles);
691 * Clear or set given tags for all ids in listbase (runtime tags).
693 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
697 for (id = lb->first; id; id = id->next) {
702 const int ntag = ~tag;
703 for (id = lb->first; id; id = id->next) {
710 * Clear or set given tags for all ids of given type in bmain (runtime tags).
712 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
714 ListBase *lb = which_libbase(mainvar, type);
716 BKE_main_id_tag_listbase(lb, tag, value);
720 * Clear or set given tags for all ids in bmain (runtime tags).
722 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
724 ListBase *lbarray[MAX_LIBARRAY];
727 a = set_listbasepointers(mainvar, lbarray);
729 BKE_main_id_tag_listbase(lbarray[a], tag, value);
735 * Clear or set given flags for all ids in listbase (persistent flags).
737 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
741 for (id = lb->first; id; id = id->next)
745 const int nflag = ~flag;
746 for (id = lb->first; id; id = id->next)
752 * Clear or set given flags for all ids in bmain (persistent flags).
754 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
756 ListBase *lbarray[MAX_LIBARRAY];
758 a = set_listbasepointers(bmain, lbarray);
760 BKE_main_id_flag_listbase(lbarray[a], flag, value);
764 void BKE_main_lib_objects_recalc_all(Main *bmain)
768 /* flag for full recalc */
769 for (ob = bmain->object.first; ob; ob = ob->id.next) {
770 if (ID_IS_LINKED_DATABLOCK(ob)) {
771 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
775 DAG_id_type_tag(bmain, ID_OB);
779 * puts into array *lb pointers to all the ListBase structs in main,
780 * and returns the number of them as the function result. This is useful for
781 * generic traversal of all the blocks in a Main (by traversing all the
782 * lists in turn), without worrying about block types.
784 * \note MAX_LIBARRAY define should match this code */
785 int set_listbasepointers(Main *main, ListBase **lb)
787 /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
788 * This is important because freeing data decreases usercounts of other datablocks,
789 * if this data is its self freed it can crash. */
790 lb[INDEX_ID_LI] = &(main->library); /* Libraries may be accessed from pretty much any other ID... */
791 lb[INDEX_ID_IP] = &(main->ipo);
792 lb[INDEX_ID_AC] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
793 lb[INDEX_ID_KE] = &(main->key);
794 lb[INDEX_ID_GD] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
795 lb[INDEX_ID_NT] = &(main->nodetree);
796 lb[INDEX_ID_IM] = &(main->image);
797 lb[INDEX_ID_TE] = &(main->tex);
798 lb[INDEX_ID_MA] = &(main->mat);
799 lb[INDEX_ID_VF] = &(main->vfont);
801 /* Important!: When adding a new object type,
802 * the specific data should be inserted here
805 lb[INDEX_ID_AR] = &(main->armature);
807 lb[INDEX_ID_CF] = &(main->cachefiles);
808 lb[INDEX_ID_ME] = &(main->mesh);
809 lb[INDEX_ID_CU] = &(main->curve);
810 lb[INDEX_ID_MB] = &(main->mball);
812 lb[INDEX_ID_LT] = &(main->latt);
813 lb[INDEX_ID_LA] = &(main->lamp);
814 lb[INDEX_ID_CA] = &(main->camera);
816 lb[INDEX_ID_TXT] = &(main->text);
817 lb[INDEX_ID_SO] = &(main->sound);
818 lb[INDEX_ID_GR] = &(main->group);
819 lb[INDEX_ID_PAL] = &(main->palettes);
820 lb[INDEX_ID_PC] = &(main->paintcurves);
821 lb[INDEX_ID_BR] = &(main->brush);
822 lb[INDEX_ID_PA] = &(main->particle);
823 lb[INDEX_ID_SPK] = &(main->speaker);
825 lb[INDEX_ID_WO] = &(main->world);
826 lb[INDEX_ID_MC] = &(main->movieclip);
827 lb[INDEX_ID_SCR] = &(main->screen);
828 lb[INDEX_ID_OB] = &(main->object);
829 lb[INDEX_ID_LS] = &(main->linestyle); /* referenced by scenes */
830 lb[INDEX_ID_SCE] = &(main->scene);
831 lb[INDEX_ID_WM] = &(main->wm);
832 lb[INDEX_ID_MSK] = &(main->mask);
834 lb[INDEX_ID_NULL] = NULL;
836 return (MAX_LIBARRAY - 1);
839 /* *********** ALLOC AND FREE *****************
841 * BKE_libblock_free(ListBase *lb, ID *id )
842 * provide a list-basis and datablock, but only ID is read
844 * void *BKE_libblock_alloc(ListBase *lb, type, name)
845 * inserts in list and returns a new ID
847 * **************************** */
850 * Allocates and returns memory of the right size for the specified block type,
851 * initialized to zero.
853 void *BKE_libblock_alloc_notest(short type)
857 switch ((ID_Type)type) {
859 id = MEM_callocN(sizeof(Scene), "scene");
862 id = MEM_callocN(sizeof(Library), "library");
865 id = MEM_callocN(sizeof(Object), "object");
868 id = MEM_callocN(sizeof(Mesh), "mesh");
871 id = MEM_callocN(sizeof(Curve), "curve");
874 id = MEM_callocN(sizeof(MetaBall), "mball");
877 id = MEM_callocN(sizeof(Material), "mat");
880 id = MEM_callocN(sizeof(Tex), "tex");
883 id = MEM_callocN(sizeof(Image), "image");
886 id = MEM_callocN(sizeof(Lattice), "latt");
889 id = MEM_callocN(sizeof(Lamp), "lamp");
892 id = MEM_callocN(sizeof(Camera), "camera");
895 id = MEM_callocN(sizeof(Ipo), "ipo");
898 id = MEM_callocN(sizeof(Key), "key");
901 id = MEM_callocN(sizeof(World), "world");
904 id = MEM_callocN(sizeof(bScreen), "screen");
907 id = MEM_callocN(sizeof(VFont), "vfont");
910 id = MEM_callocN(sizeof(Text), "text");
913 id = MEM_callocN(sizeof(Speaker), "speaker");
916 id = MEM_callocN(sizeof(bSound), "sound");
919 id = MEM_callocN(sizeof(Group), "group");
922 id = MEM_callocN(sizeof(bArmature), "armature");
925 id = MEM_callocN(sizeof(bAction), "action");
928 id = MEM_callocN(sizeof(bNodeTree), "nodetree");
931 id = MEM_callocN(sizeof(Brush), "brush");
934 id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
937 id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
940 id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
943 id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
946 id = MEM_callocN(sizeof(Mask), "Mask");
949 id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
952 id = MEM_callocN(sizeof(Palette), "Palette");
955 id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
958 id = MEM_callocN(sizeof(CacheFile), "Cache File");
965 * Allocates and returns a block of the specified type, with the specified name
966 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
967 * The user count is set to 1, all other content (apart from name and links) being
968 * initialized to zero.
970 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
973 ListBase *lb = which_libbase(bmain, type);
975 id = BKE_libblock_alloc_notest(type);
977 BKE_main_lock(bmain);
981 *( (short *)id->name) = type;
982 new_id(lb, id, name);
983 /* alphabetic insertion: is in new_id */
984 BKE_main_unlock(bmain);
986 DAG_id_type_tag(bmain, type);
991 * Initialize an ID of given type, such that it has valid 'empty' data.
992 * ID is assumed to be just calloc'ed.
994 void BKE_libblock_init_empty(ID *id)
996 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
997 switch ((ID_Type)GS(id->name)) {
999 BKE_scene_init((Scene *)id);
1002 /* Nothing to do. */
1006 Object *ob = (Object *)id;
1007 ob->type = OB_EMPTY;
1008 BKE_object_init(ob);
1012 BKE_mesh_init((Mesh *)id);
1015 BKE_curve_init((Curve *)id);
1018 BKE_mball_init((MetaBall *)id);
1021 BKE_material_init((Material *)id);
1024 BKE_texture_default((Tex *)id);
1027 BKE_image_init((Image *)id);
1030 BKE_lattice_init((Lattice *)id);
1033 BKE_lamp_init((Lamp *)id);
1036 BKE_speaker_init((Speaker *)id);
1039 BKE_camera_init((Camera *)id);
1042 BKE_world_init((World *)id);
1045 /* Nothing to do. */
1048 BKE_vfont_init((VFont *)id);
1051 BKE_text_init((Text *)id);
1054 /* Another fuzzy case, think NULLified content is OK here... */
1057 /* Nothing to do. */
1060 /* Nothing to do. */
1063 /* Nothing to do. */
1066 ntreeInitDefault((bNodeTree *)id);
1069 BKE_brush_init((Brush *)id);
1072 /* Nothing to do. */
1075 /* Nothing to do. */
1078 /* Nothing to do. */
1081 /* Nothing to do. */
1084 BKE_linestyle_init((FreestyleLineStyle *)id);
1087 BKE_cachefile_init((CacheFile *)id);
1090 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
1091 * They are not linkable, though, so it should never reach here anyway. */
1095 /* We should never reach this. */
1099 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
1103 BLI_assert(0); /* Should never reach this point... */
1107 /* by spec, animdata is first item after ID */
1108 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
1109 static void id_copy_animdata(ID *id, const bool do_action)
1111 AnimData *adt = BKE_animdata_from_id(id);
1114 IdAdtTemplate *iat = (IdAdtTemplate *)id;
1115 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
1119 /* material nodes use this since they are not treated as libdata */
1120 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
1122 if (id_from->properties)
1123 id->properties = IDP_CopyProperty(id_from->properties);
1125 /* the duplicate should get a copy of the animdata */
1126 id_copy_animdata(id, do_action);
1129 /* used everywhere in blenkernel */
1130 void *BKE_libblock_copy(Main *bmain, ID *id)
1135 idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
1137 assert(idn != NULL);
1139 idn_len = MEM_allocN_len(idn);
1140 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1141 const char *cp = (const char *)id;
1142 char *cpn = (char *)idn;
1144 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1147 BKE_libblock_copy_data(idn, id, false);
1152 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1157 idn = BKE_libblock_alloc_notest(GS(id->name));
1158 assert(idn != NULL);
1160 BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1162 idn_len = MEM_allocN_len(idn);
1163 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1164 const char *cp = (const char *)id;
1165 char *cpn = (char *)idn;
1167 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1172 BKE_libblock_copy_data(idn, id, do_action);
1177 void BKE_library_free(Library *lib)
1179 if (lib->packedfile)
1180 freePackedFile(lib->packedfile);
1183 Main *BKE_main_new(void)
1185 Main *bmain = MEM_callocN(sizeof(Main), "new main");
1186 bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1187 bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1188 BLI_spin_init((SpinLock *)bmain->lock);
1192 void BKE_main_free(Main *mainvar)
1194 /* also call when reading a file, erase all, etc */
1195 ListBase *lbarray[MAX_LIBARRAY];
1198 MEM_SAFE_FREE(mainvar->blen_thumb);
1200 a = set_listbasepointers(mainvar, lbarray);
1202 ListBase *lb = lbarray[a];
1205 while ( (id = lb->first) ) {
1207 BKE_libblock_free_ex(mainvar, id, false, false);
1209 /* errors freeing ID's can be hard to track down,
1210 * enable this so valgrind will give the line number in its error log */
1212 case 0: BKE_libblock_free_ex(mainvar, id, false, false); break;
1213 case 1: BKE_libblock_free_ex(mainvar, id, false, false); break;
1214 case 2: BKE_libblock_free_ex(mainvar, id, false, false); break;
1215 case 3: BKE_libblock_free_ex(mainvar, id, false, false); break;
1216 case 4: BKE_libblock_free_ex(mainvar, id, false, false); break;
1217 case 5: BKE_libblock_free_ex(mainvar, id, false, false); break;
1218 case 6: BKE_libblock_free_ex(mainvar, id, false, false); break;
1219 case 7: BKE_libblock_free_ex(mainvar, id, false, false); break;
1220 case 8: BKE_libblock_free_ex(mainvar, id, false, false); break;
1221 case 9: BKE_libblock_free_ex(mainvar, id, false, false); break;
1222 case 10: BKE_libblock_free_ex(mainvar, id, false, false); break;
1223 case 11: BKE_libblock_free_ex(mainvar, id, false, false); break;
1224 case 12: BKE_libblock_free_ex(mainvar, id, false, false); break;
1225 case 13: BKE_libblock_free_ex(mainvar, id, false, false); break;
1226 case 14: BKE_libblock_free_ex(mainvar, id, false, false); break;
1227 case 15: BKE_libblock_free_ex(mainvar, id, false, false); break;
1228 case 16: BKE_libblock_free_ex(mainvar, id, false, false); break;
1229 case 17: BKE_libblock_free_ex(mainvar, id, false, false); break;
1230 case 18: BKE_libblock_free_ex(mainvar, id, false, false); break;
1231 case 19: BKE_libblock_free_ex(mainvar, id, false, false); break;
1232 case 20: BKE_libblock_free_ex(mainvar, id, false, false); break;
1233 case 21: BKE_libblock_free_ex(mainvar, id, false, false); break;
1234 case 22: BKE_libblock_free_ex(mainvar, id, false, false); break;
1235 case 23: BKE_libblock_free_ex(mainvar, id, false, false); break;
1236 case 24: BKE_libblock_free_ex(mainvar, id, false, false); break;
1237 case 25: BKE_libblock_free_ex(mainvar, id, false, false); break;
1238 case 26: BKE_libblock_free_ex(mainvar, id, false, false); break;
1239 case 27: BKE_libblock_free_ex(mainvar, id, false, false); break;
1240 case 28: BKE_libblock_free_ex(mainvar, id, false, false); break;
1241 case 29: BKE_libblock_free_ex(mainvar, id, false, false); break;
1242 case 30: BKE_libblock_free_ex(mainvar, id, false, false); break;
1243 case 31: BKE_libblock_free_ex(mainvar, id, false, false); break;
1244 case 32: BKE_libblock_free_ex(mainvar, id, false, false); break;
1245 case 33: BKE_libblock_free_ex(mainvar, id, false, false); break;
1246 case 34: BKE_libblock_free_ex(mainvar, id, false, false); break;
1255 BLI_spin_end((SpinLock *)mainvar->lock);
1256 MEM_freeN(mainvar->lock);
1257 DEG_evaluation_context_free(mainvar->eval_ctx);
1261 void BKE_main_lock(struct Main *bmain)
1263 BLI_spin_lock((SpinLock *) bmain->lock);
1266 void BKE_main_unlock(struct Main *bmain)
1268 BLI_spin_unlock((SpinLock *) bmain->lock);
1272 * Generates a raw .blend file thumbnail data from given image.
1274 * \param bmain If not NULL, also store generated data in this Main.
1275 * \param img ImBuf image to generate thumbnail data from.
1276 * \return The generated .blend file raw thumbnail data.
1278 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1280 BlendThumbnail *data = NULL;
1283 MEM_SAFE_FREE(bmain->blen_thumb);
1287 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1288 data = MEM_mallocN(sz, __func__);
1290 IMB_rect_from_float(img); /* Just in case... */
1291 data->width = img->x;
1292 data->height = img->y;
1293 memcpy(data->rect, img->rect, sz - sizeof(*data));
1297 bmain->blen_thumb = data;
1303 * Generates an image from raw .blend file thumbnail \a data.
1305 * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1306 * \param data Raw .blend file thumbnail data.
1307 * \return An ImBuf from given data, or NULL if invalid.
1309 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1313 if (!data && bmain) {
1314 data = bmain->blen_thumb;
1318 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1319 * here (we do not want to pass the first two ints!). */
1320 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1321 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1328 * Generates an empty (black) thumbnail for given Main.
1330 void BKE_main_thumbnail_create(struct Main *bmain)
1332 MEM_SAFE_FREE(bmain->blen_thumb);
1334 bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1335 bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1336 bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1339 /* ***************** ID ************************ */
1340 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1342 ListBase *lb = which_libbase(bmain, type);
1343 BLI_assert(lb != NULL);
1344 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1346 ID *BKE_libblock_find_name(const short type, const char *name)
1348 return BKE_libblock_find_name_ex(G.main, type, name);
1352 void id_sort_by_name(ListBase *lb, ID *id)
1356 /* insert alphabetically */
1357 if (lb->first != lb->last) {
1358 BLI_remlink(lb, id);
1362 if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1363 BLI_insertlinkbefore(lb, idtest, id);
1366 idtest = idtest->next;
1369 if (idtest == NULL) {
1370 BLI_addtail(lb, id);
1377 * Check to see if there is an ID with the same name as 'name'.
1378 * Returns the ID if so, if not, returns NULL
1380 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1384 for (idtest = lb->first; idtest; idtest = idtest->next) {
1385 /* if idtest is not a lib */
1386 if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
1387 /* do not test alphabetic! */
1389 if (idtest->name[2] == name[0]) {
1390 if (STREQ(name, idtest->name + 2)) break;
1399 * Check to see if an ID name is already used, and find a new one if so.
1400 * Return true if created a new name (returned in name).
1402 * Normally the ID that's being check is already in the ListBase, so ID *id
1403 * points at the new entry. The Python Library module needs to know what
1404 * the name of a datablock will be before it is appended; in this case ID *id
1408 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1411 int nr = 0, a, left_len;
1412 #define MAX_IN_USE 64
1413 bool in_use[MAX_IN_USE];
1414 /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1416 char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1420 /* phase 1: id already exists? */
1421 idtest = is_dupid(lb, id, name);
1423 /* if there is no double, done */
1424 if (idtest == NULL) return false;
1426 /* we have a dup; need to make a new name */
1427 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1428 memset(in_use, false, sizeof(in_use));
1430 /* get name portion, number portion ("name.number") */
1431 left_len = BLI_split_name_num(left, &nr, name, '.');
1433 /* if new name will be too long, truncate it */
1434 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* assumption: won't go beyond 9999 */
1435 left[MAX_ID_NAME - 8] = '\0';
1436 left_len = MAX_ID_NAME - 8;
1438 else if (left_len > (MAX_ID_NAME - 7)) {
1439 left[MAX_ID_NAME - 7] = '\0';
1440 left_len = MAX_ID_NAME - 7;
1443 /* Code above may have generated invalid utf-8 string, due to raw truncation.
1444 * Ensure we get a valid one now! */
1445 left_len -= BLI_utf8_invalid_strip(left, left_len);
1447 for (idtest = lb->first; idtest; idtest = idtest->next) {
1449 if ( (id != idtest) &&
1450 !ID_IS_LINKED_DATABLOCK(idtest) &&
1451 (*name == *(idtest->name + 2)) &&
1452 STREQLEN(name, idtest->name + 2, left_len) &&
1453 (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1456 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1457 if (nrtest < MAX_IN_USE)
1458 in_use[nrtest] = true; /* mark as used */
1460 nr = nrtest + 1; /* track largest unused */
1463 /* At this point, 'nr' will typically be at least 1. (but not always) */
1464 // BLI_assert(nr >= 1);
1466 /* decide which value of nr to use */
1467 for (a = 0; a < MAX_IN_USE; a++) {
1468 if (a >= nr) break; /* stop when we've checked up to biggest */ /* redundant check */
1469 if (!in_use[a]) { /* found an unused value */
1471 /* can only be zero if all potential duplicate names had
1472 * nonzero numeric suffixes, which means name itself has
1473 * nonzero numeric suffix (else no name conflict and wouldn't
1474 * have got here), which means name[left_len] is not a null */
1478 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1479 * or 1 greater than the largest used number if all those low ones are taken.
1480 * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1482 /* If the original name has no numeric suffix,
1483 * rather than just chopping and adding numbers,
1484 * shave off the end chars until we have a unique name.
1485 * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1486 if (nr == 0 && name[left_len] == '\0') {
1488 /* FIXME: this code will never be executed, because either nr will be
1489 * at least 1, or name will not end at left_len! */
1493 idtest = is_dupid(lb, id, name);
1495 while (idtest && len > 1) {
1497 idtest = is_dupid(lb, id, name);
1499 if (idtest == NULL) return true;
1500 /* otherwise just continue and use a number suffix */
1503 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1504 /* this would overflow name buffer */
1505 left[MAX_ID_NAME - 8] = 0;
1506 /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1507 memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1510 /* this format specifier is from hell... */
1511 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1520 * Only for local blocks: external en indirect blocks already have a
1523 * return true: created a new name
1526 bool new_id(ListBase *lb, ID *id, const char *tname)
1529 char name[MAX_ID_NAME - 2];
1531 /* if library, don't rename */
1532 if (ID_IS_LINKED_DATABLOCK(id))
1535 /* if no libdata given, look up based on ID */
1537 lb = which_libbase(G.main, GS(id->name));
1539 /* if no name given, use name of current ID
1540 * else make a copy (tname args can be const) */
1542 tname = id->name + 2;
1544 BLI_strncpy(name, tname, sizeof(name));
1546 if (name[0] == '\0') {
1547 /* disallow empty names */
1548 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1551 /* disallow non utf8 chars,
1552 * the interface checks for this but new ID's based on file names don't */
1553 BLI_utf8_invalid_strip(name, strlen(name));
1556 result = check_for_dupid(lb, id, name);
1557 strcpy(id->name + 2, name);
1559 /* This was in 2.43 and previous releases
1560 * however all data in blender should be sorted, not just duplicate names
1561 * sorting should not hurt, but noting just incase it alters the way other
1562 * functions work, so sort every time */
1565 id_sort_by_name(lb, id);
1568 id_sort_by_name(lb, id);
1574 * Pull an ID out of a library (make it local). Only call this for IDs that
1575 * don't have other library users.
1577 void id_clear_lib_data_ex(Main *bmain, ID *id, const bool id_in_mainlist)
1579 bNodeTree *ntree = NULL;
1582 BKE_id_lib_local_paths(bmain, id->lib, id);
1584 id_fake_user_clear(id);
1587 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1589 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1591 /* Internal bNodeTree blocks inside datablocks also stores id->lib, make sure this stays in sync. */
1592 if ((ntree = ntreeFromID(id))) {
1593 id_clear_lib_data_ex(bmain, &ntree->id, false); /* Datablocks' nodetree is never in Main. */
1596 /* Same goes for shapekeys. */
1597 if ((key = BKE_key_from_id(id))) {
1598 id_clear_lib_data_ex(bmain, &key->id, id_in_mainlist); /* sigh, why are keys in Main? */
1602 void id_clear_lib_data(Main *bmain, ID *id)
1604 id_clear_lib_data_ex(bmain, id, true);
1607 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1608 void BKE_main_id_clear_newpoins(Main *bmain)
1610 ListBase *lbarray[MAX_LIBARRAY];
1614 a = set_listbasepointers(bmain, lbarray);
1616 id = lbarray[a]->first;
1619 id->tag &= ~LIB_TAG_NEW;
1625 /** Make linked datablocks local.
1627 * \param bmain Almost certainly G.main.
1628 * \param lib If not NULL, only make local datablocks from this library.
1629 * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1630 * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1632 /* Note: Old (2.77) version was simply making (tagging) datablocks as local, without actually making any check whether
1633 * they were also indirectly used or not...
1635 * Current version uses regular id_make_local callback, which is not super-efficient since this ends up
1636 * duplicating some IDs and then removing original ones (due to missing knowledge of which ID uses some other ID).
1638 * However, we now have a first check that allows us to use 'direct localization' of a lot of IDs, so performances
1639 * are now *reasonably* OK.
1641 void BKE_library_make_local(
1642 Main *bmain, const Library *lib, GHash *old_to_new_ids, const bool untagged_only, const bool set_fake)
1644 ListBase *lbarray[MAX_LIBARRAY];
1648 LinkNode *todo_ids = NULL;
1649 LinkNode *copied_ids = NULL;
1650 LinkNode *linked_loop_candidates = NULL;
1651 MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
1653 /* Step 1: Detect datablocks to make local. */
1654 for (a = set_listbasepointers(bmain, lbarray); a--; ) {
1655 id = lbarray[a]->first;
1657 /* Do not explicitly make local non-linkable IDs (shapekeys, in fact), they are assumed to be handled
1658 * by real datablocks responsible of them. */
1659 const bool do_skip = (id && !BKE_idcode_is_linkable(GS(id->name)));
1661 for (; id; id = id->next) {
1662 id->tag &= ~LIB_TAG_DOIT;
1664 if (id->lib == NULL) {
1665 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1667 /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so its
1668 * possible to tag data you don't want to be made local, used for
1669 * appending data, so any libdata already linked wont become local
1670 * (very nasty to discover all your links are lost after appending).
1671 * Also, never ever make proxified objects local, would not make any sense. */
1672 else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1673 ELEM(lib, NULL, id->lib) &&
1674 !(GS(id->name) == ID_OB && ((Object *)id)->proxy_from != NULL) &&
1675 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1677 BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem);
1678 id->tag |= LIB_TAG_DOIT;
1683 /* Step 2: Check which datablocks we can directly make local (because they are only used by already, or future,
1684 * local data), others will need to be duplicated and further processed later. */
1685 BKE_library_indirectly_used_data_tag_clear(bmain);
1687 /* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
1688 * which involves more complex checks and might instead create a local copy of original linked ID. */
1689 for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
1693 if (id->tag & LIB_TAG_DOIT) {
1694 /* We know all users of this object are local or will be made fully local, even if currently there are
1695 * some indirect usages. So instead of making a copy that se'll likely get rid of later, directly make
1696 * that data block local. Saves a tremendous amount of time with complex scenes... */
1697 id_clear_lib_data_ex(bmain, id, true);
1698 BKE_id_expand_local(id);
1699 id->tag &= ~LIB_TAG_DOIT;
1702 /* In this specific case, we do want to make ID local even if it has no local usage yet... */
1703 if (GS(id->name) == ID_OB) {
1704 /* Special case for objects because we don't want proxy pointers to be
1705 * cleared yet. This will happen down the road in this function.
1707 BKE_object_make_local_ex(bmain, (Object*)id, true, false);
1710 id_make_local(bmain, id, false, true);
1714 /* Reuse already allocated LinkNode (transferring it from todo_ids to copied_ids). */
1715 BLI_linklist_prepend_nlink(&copied_ids, id, it);
1720 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1721 /* do not set fake user on objects, groups (instancing) */
1722 id_fake_user_set(id);
1727 /* At this point, we are done with directly made local IDs. Now we have to handle duplicated ones, since their
1728 * remaining linked original counterpart may not be needed anymore... */
1731 /* Step 4: We have to remap local usages of old (linked) ID to new (local) id in a separated loop,
1732 * as lbarray ordering is not enough to ensure us we did catch all dependencies
1733 * (e.g. if making local a parent object before its child...). See T48907. */
1734 for (LinkNode *it = copied_ids; it; it = it->next) {
1737 BLI_assert(id->newid != NULL);
1738 BLI_assert(id->lib != NULL);
1740 BKE_libblock_remap(bmain, id, id->newid, ID_REMAP_SKIP_INDIRECT_USAGE);
1741 if (old_to_new_ids) {
1742 BLI_ghash_insert(old_to_new_ids, id, id->newid);
1745 /* Special hack for groups... Thing is, since we can't instantiate them here, we need to ensure
1746 * they remain 'alive' (only instantiation is a real group 'user'... *sigh* See T49722. */
1747 if (GS(id->name) == ID_GR && (id->tag & LIB_TAG_INDIRECT) != 0) {
1748 id_us_ensure_real(id->newid);
1752 /* Step 5: remove datablocks that have been copied to be localized and are no more used in the end...
1753 * Note that we may have to loop more than once here, to tackle dependencies between linked objects... */
1754 bool do_loop = true;
1757 for (LinkNode *it = copied_ids; it; it = it->next) {
1758 if ((id = it->link) == NULL) {
1762 bool is_local = false, is_lib = false;
1764 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
1766 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
1767 * from another blend file into this one, even when that blend file contains proxified
1768 * armatures that have local references. Since the proxified object needs to be linked
1769 * (not local), this will only work when the "Localize all" checkbox is disabled.
1770 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
1771 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
1772 Object *ob = (Object *)id;
1773 Object *ob_new = (Object *)id->newid;
1775 /* Proxies only work when the proxified object is linked-in from a library. */
1776 if (ob->proxy->id.lib == NULL) {
1777 printf("Warning, proxy object %s will loose its link to %s, because the "
1778 "proxified object is local.\n", id->newid->name, ob->proxy->id.name);
1780 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
1781 * referred to from a library. Not checking for local use; if new local proxy
1782 * was not used locally would be a nasty bug! */
1783 else if (is_local || is_lib) {
1784 printf("Warning, made-local proxy object %s will loose its link to %s, "
1785 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
1786 id->newid->name, ob->proxy->id.name, is_local, is_lib);
1789 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
1790 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
1791 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy_ex). */
1792 ob_new->proxy = ob->proxy;
1793 ob_new->proxy_group = ob->proxy_group;
1794 ob_new->proxy_from = ob->proxy_from;
1795 ob_new->proxy->proxy_from = ob_new;
1796 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
1801 if (!is_lib) { /* Not used at all, we can free it! */
1802 BKE_libblock_free(bmain, id);
1806 /* Only used by linked data, potential candidate to ugly lib-only dependency cycles... */
1807 else if ((id->tag & LIB_TAG_DOIT) == 0) { /* Check TAG_DOIT to avoid adding same ID several times... */
1808 /* Note that we store the node, not directly ID pointer, that way if it->link is set to NULL
1809 * later we can skip it in lib-dependency cycles search later. */
1810 BLI_linklist_prepend_arena(&linked_loop_candidates, it, linklist_mem);
1811 id->tag |= LIB_TAG_DOIT;
1813 /* Grrrrrrr... those half-datablocks-stuff... grrrrrrrrrrr...
1814 * Here we have to also tag them as potential candidates, otherwise they would falsy report
1815 * ID they used as 'directly used' in fourth step. */
1816 ID *ntree = (ID *)ntreeFromID(id);
1817 if (ntree != NULL) {
1818 ntree->tag |= LIB_TAG_DOIT;
1825 /* Step 6: Try to find circle dependencies between indirectly-linked-only datablocks.
1826 * Those are fake 'usages' that prevent their deletion. See T49775 for nice ugly case. */
1827 BKE_library_unused_linked_data_set_tag(bmain, false);
1828 for (LinkNode *it = linked_loop_candidates; it; it = it->next) {
1829 if (it->link == NULL) {
1832 if ((id = ((LinkNode *)it->link)->link) == NULL) {
1837 /* Note: in theory here we are only handling datablocks forming exclusive linked dependency-cycles-based
1838 * archipelagos, so no need to check again after we have deleted one, as done in previous step. */
1839 if (id->tag & LIB_TAG_DOIT) {
1840 /* Object's deletion rely on valid ob->data, but ob->data may have already been freed here...
1841 * Setting it to NULL may not be 100% correct, but should be safe and do the work. */
1842 if (GS(id->name) == ID_OB) {
1843 ((Object *)id)->data = NULL;
1846 /* Note: *in theory* IDs tagged here are fully *outside* of file scope, totally unused, so we can
1847 * directly wipe them out without caring about clearing their usages.
1848 * However, this is a highly-risky presumption, and nice crasher in case something goes wrong here.
1849 * So for 2.78a will keep the safe option, and switch to more efficient one in master later. */
1851 BKE_libblock_free_ex(bmain, id, false, true);
1853 BKE_libblock_unlink(bmain, id, false, false);
1854 BKE_libblock_free(bmain, id);
1856 ((LinkNode *)it->link)->link = NULL; /* Not strictly necessary, but safer (see T49903)... */
1861 BKE_main_id_clear_newpoins(bmain);
1862 BLI_memarena_free(linklist_mem);
1866 * Use after setting the ID's name
1867 * When name exists: call 'new_id'
1869 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
1875 lb = which_libbase(bmain, GS(name));
1876 if (lb == NULL) return;
1879 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1881 if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
1882 id_sort_by_name(lb, idtest);
1887 * Sets the name of a block to name, suitably adjusted for uniqueness.
1889 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
1891 ListBase *lb = which_libbase(bmain, GS(id->name));
1892 new_id(lb, id, name);
1896 * Returns in name the name of the block, with a 3-character prefix prepended
1897 * indicating whether it comes from a library, has a fake user, or no users.
1899 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
1901 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1902 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1905 strcpy(name + 3, id->name + 2);
1908 void BKE_library_filepath_set(Library *lib, const char *filepath)
1910 /* in some cases this is used to update the absolute path from the
1912 if (lib->name != filepath) {
1913 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1916 BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1918 /* not essential but set filepath is an absolute copy of value which
1919 * is more useful if its kept in sync */
1920 if (BLI_path_is_rel(lib->filepath)) {
1921 /* note that the file may be unsaved, in this case, setting the
1922 * filepath on an indirectly linked path is not allowed from the
1923 * outliner, and its not really supported but allow from here for now
1924 * since making local could cause this to be directly linked - campbell
1926 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1927 BLI_path_abs(lib->filepath, basepath);
1931 void BKE_id_tag_set_atomic(ID *id, int tag)
1933 atomic_fetch_and_or_uint32((uint32_t *)&id->tag, tag);
1936 void BKE_id_tag_clear_atomic(ID *id, int tag)
1938 atomic_fetch_and_and_uint32((uint32_t *)&id->tag, ~tag);