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"
80 #include "BLI_threads.h"
81 #include "BLT_translation.h"
83 #include "BKE_action.h"
84 #include "BKE_animsys.h"
85 #include "BKE_armature.h"
86 #include "BKE_bpath.h"
87 #include "BKE_brush.h"
88 #include "BKE_camera.h"
89 #include "BKE_cachefile.h"
90 #include "BKE_context.h"
91 #include "BKE_curve.h"
92 #include "BKE_depsgraph.h"
94 #include "BKE_global.h"
95 #include "BKE_group.h"
96 #include "BKE_gpencil.h"
97 #include "BKE_idcode.h"
98 #include "BKE_idprop.h"
99 #include "BKE_image.h"
101 #include "BKE_lamp.h"
102 #include "BKE_lattice.h"
103 #include "BKE_library.h"
104 #include "BKE_library_query.h"
105 #include "BKE_library_remap.h"
106 #include "BKE_linestyle.h"
107 #include "BKE_mesh.h"
108 #include "BKE_material.h"
109 #include "BKE_main.h"
110 #include "BKE_mball.h"
111 #include "BKE_mask.h"
112 #include "BKE_movieclip.h"
113 #include "BKE_node.h"
114 #include "BKE_object.h"
115 #include "BKE_paint.h"
116 #include "BKE_particle.h"
117 #include "BKE_packedFile.h"
118 #include "BKE_sound.h"
119 #include "BKE_speaker.h"
120 #include "BKE_scene.h"
121 #include "BKE_text.h"
122 #include "BKE_texture.h"
123 #include "BKE_world.h"
125 #include "DEG_depsgraph.h"
127 #include "RNA_access.h"
129 #include "IMB_imbuf.h"
130 #include "IMB_imbuf_types.h"
132 #include "atomic_ops.h"
134 /* GS reads the memory pointed at in a specific ordering.
135 * only use this definition, makes little and big endian systems
136 * work fine, in conjunction with MAKE_ID */
138 /* ************* general ************************ */
141 /* this has to be called from each make_local_* func, we could call
142 * from id_make_local() but then the make local functions would not be self
144 * also note that the id _must_ have a library - campbell */
145 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
147 const char *bpath_user_data[2] = {bmain->name, lib->filepath};
149 BKE_bpath_traverse_id(bmain, id,
150 BKE_bpath_relocate_visitor,
151 BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
152 (void *)bpath_user_data);
155 void id_lib_extern(ID *id)
157 if (id && ID_IS_LINKED_DATABLOCK(id)) {
158 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
159 if (id->tag & LIB_TAG_INDIRECT) {
160 id->tag -= LIB_TAG_INDIRECT;
161 id->tag |= LIB_TAG_EXTERN;
166 /* ensure we have a real user */
167 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
168 * we always have a real user.
169 * However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
170 * to make this change... */
171 void id_us_ensure_real(ID *id)
174 const int limit = ID_FAKE_USERS(id);
175 id->tag |= LIB_TAG_EXTRAUSER;
176 if (id->us <= limit) {
177 if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
178 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
182 id->tag |= LIB_TAG_EXTRAUSER_SET;
187 void id_us_clear_real(ID *id)
189 if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
190 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
192 BLI_assert(id->us >= ID_FAKE_USERS(id));
194 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
199 * Same as \a id_us_plus, but does not handle lib indirect -> extern.
200 * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
202 void id_us_plus_no_lib(ID *id)
205 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
206 BLI_assert(id->us >= 1);
207 /* No need to increase count, just tag extra user as no more set.
208 * Avoids annoying & inconsistent +1 in user count. */
209 id->tag &= ~LIB_TAG_EXTRAUSER_SET;
212 BLI_assert(id->us >= 0);
219 void id_us_plus(ID *id)
222 id_us_plus_no_lib(id);
227 /* decrements the user count for *id. */
228 void id_us_min(ID *id)
231 const int limit = ID_FAKE_USERS(id);
233 if (id->us <= limit) {
234 printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
235 id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
243 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
244 /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
245 id_us_ensure_real(id);
250 void id_fake_user_set(ID *id)
252 if (id && !(id->flag & LIB_FAKEUSER)) {
253 id->flag |= LIB_FAKEUSER;
258 void id_fake_user_clear(ID *id)
260 if (id && (id->flag & LIB_FAKEUSER)) {
261 id->flag &= ~LIB_FAKEUSER;
266 static int id_expand_local_callback(
267 void *UNUSED(user_data), struct ID *id_self, struct ID **id_pointer, int UNUSED(cd_flag))
269 /* Can hapen that we get unlinkable ID here, e.g. with shapekey referring to itself (through drivers)...
270 * Just skip it, shape key can only be either indirectly linked, or fully local, period.
271 * And let's curse one more time that stupid useless shapekey ID type! */
272 if (*id_pointer && *id_pointer != id_self && BKE_idcode_is_linkable(GS((*id_pointer)->name))) {
273 id_lib_extern(*id_pointer);
276 return IDWALK_RET_NOP;
280 * Expand ID usages of given id as 'extern' (and no more indirect) linked data. Used by ID copy/make_local functions.
282 void BKE_id_expand_local(ID *id)
284 BKE_library_foreach_ID_link(id, id_expand_local_callback, NULL, 0);
288 * Ensure new (copied) ID is fully made local.
290 void BKE_id_copy_ensure_local(Main *bmain, ID *old_id, ID *new_id)
292 if (ID_IS_LINKED_DATABLOCK(old_id)) {
293 BKE_id_expand_local(new_id);
294 BKE_id_lib_local_paths(bmain, old_id->lib, new_id);
299 * Generic 'make local' function, works for most of datablock types...
301 void BKE_id_make_local_generic(Main *bmain, ID *id, const bool id_in_mainlist, const bool lib_local)
303 bool is_local = false, is_lib = false;
305 /* - only lib users: do nothing (unless force_local is set)
306 * - only local users: set flag
308 * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
311 if (!ID_IS_LINKED_DATABLOCK(id)) {
315 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
317 if (lib_local || is_local) {
319 id_clear_lib_data_ex(bmain, id, id_in_mainlist);
320 BKE_id_expand_local(id);
325 /* Should not fail in expected usecases, but id_copy does not copy Scene e.g. */
326 if (id_copy(bmain, id, &id_new, false)) {
330 BKE_libblock_remap(bmain, id, id_new, ID_REMAP_SKIP_INDIRECT_USAGE);
338 * Calls the appropriate make_local method for the block, unless test is set.
340 * \param lib_local Special flag used when making a whole library's content local, it needs specific handling.
342 * \return true if the block can be made local.
344 bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
346 /* We don't care whether ID is directly or indirectly linked in case we are making a whole lib local... */
347 if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) {
351 switch ((ID_Type)GS(id->name)) {
353 /* Partially implemented (has no copy...). */
354 if (!test) BKE_scene_make_local(bmain, (Scene *)id, lib_local);
357 if (!test) BKE_object_make_local(bmain, (Object *)id, lib_local);
360 if (!test) BKE_mesh_make_local(bmain, (Mesh *)id, lib_local);
363 if (!test) BKE_curve_make_local(bmain, (Curve *)id, lib_local);
366 if (!test) BKE_mball_make_local(bmain, (MetaBall *)id, lib_local);
369 if (!test) BKE_material_make_local(bmain, (Material *)id, lib_local);
372 if (!test) BKE_texture_make_local(bmain, (Tex *)id, lib_local);
375 if (!test) BKE_image_make_local(bmain, (Image *)id, lib_local);
378 if (!test) BKE_lattice_make_local(bmain, (Lattice *)id, lib_local);
381 if (!test) BKE_lamp_make_local(bmain, (Lamp *)id, lib_local);
384 if (!test) BKE_camera_make_local(bmain, (Camera *)id, lib_local);
387 if (!test) BKE_speaker_make_local(bmain, (Speaker *)id, lib_local);
390 if (!test) BKE_world_make_local(bmain, (World *)id, lib_local);
393 /* Partially implemented (has no copy...). */
394 if (!test) BKE_vfont_make_local(bmain, (VFont *)id, lib_local);
397 if (!test) BKE_text_make_local(bmain, (Text *)id, lib_local);
400 /* Partially implemented (has no copy...). */
401 if (!test) BKE_sound_make_local(bmain, (bSound *)id, lib_local);
404 if (!test) BKE_group_make_local(bmain, (Group *)id, lib_local);
407 if (!test) BKE_armature_make_local(bmain, (bArmature *)id, lib_local);
410 if (!test) BKE_action_make_local(bmain, (bAction *)id, lib_local);
413 if (!test) ntreeMakeLocal(bmain, (bNodeTree *)id, true, lib_local);
416 if (!test) BKE_brush_make_local(bmain, (Brush *)id, lib_local);
419 if (!test) BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, lib_local);
422 if (!test) BKE_gpencil_make_local(bmain, (bGPdata *)id, lib_local);
425 if (!test) BKE_movieclip_make_local(bmain, (MovieClip *)id, lib_local);
428 if (!test) BKE_mask_make_local(bmain, (Mask *)id, lib_local);
431 if (!test) BKE_linestyle_make_local(bmain, (FreestyleLineStyle *)id, lib_local);
434 if (!test) BKE_palette_make_local(bmain, (Palette *)id, lib_local);
437 if (!test) BKE_paint_curve_make_local(bmain, (PaintCurve *)id, lib_local);
440 if (!test) BKE_cachefile_make_local(bmain, (CacheFile *)id, lib_local);
446 return false; /* can't be linked */
448 return false; /* deprecated */
455 * Invokes the appropriate copy method for the block and returns the result in
456 * newid, unless test. Returns true if the block can be copied.
458 bool id_copy(Main *bmain, ID *id, ID **newid, bool test)
465 * - make shallow copy, only this ID block
466 * - id.us of the new ID is set to 1 */
467 switch ((ID_Type)GS(id->name)) {
469 if (!test) *newid = (ID *)BKE_object_copy(bmain, (Object *)id);
472 if (!test) *newid = (ID *)BKE_mesh_copy(bmain, (Mesh *)id);
475 if (!test) *newid = (ID *)BKE_curve_copy(bmain, (Curve *)id);
478 if (!test) *newid = (ID *)BKE_mball_copy(bmain, (MetaBall *)id);
481 if (!test) *newid = (ID *)BKE_material_copy(bmain, (Material *)id);
484 if (!test) *newid = (ID *)BKE_texture_copy(bmain, (Tex *)id);
487 if (!test) *newid = (ID *)BKE_image_copy(bmain, (Image *)id);
490 if (!test) *newid = (ID *)BKE_lattice_copy(bmain, (Lattice *)id);
493 if (!test) *newid = (ID *)BKE_lamp_copy(bmain, (Lamp *)id);
496 if (!test) *newid = (ID *)BKE_speaker_copy(bmain, (Speaker *)id);
499 if (!test) *newid = (ID *)BKE_camera_copy(bmain, (Camera *)id);
502 if (!test) *newid = (ID *)BKE_key_copy(bmain, (Key *)id);
505 if (!test) *newid = (ID *)BKE_world_copy(bmain, (World *)id);
508 if (!test) *newid = (ID *)BKE_text_copy(bmain, (Text *)id);
511 if (!test) *newid = (ID *)BKE_group_copy(bmain, (Group *)id);
514 if (!test) *newid = (ID *)BKE_armature_copy(bmain, (bArmature *)id);
517 if (!test) *newid = (ID *)BKE_action_copy(bmain, (bAction *)id);
520 if (!test) *newid = (ID *)ntreeCopyTree(bmain, (bNodeTree *)id);
523 if (!test) *newid = (ID *)BKE_brush_copy(bmain, (Brush *)id);
526 if (!test) *newid = (ID *)BKE_particlesettings_copy(bmain, (ParticleSettings *)id);
529 if (!test) *newid = (ID *)BKE_gpencil_data_duplicate(bmain, (bGPdata *)id, false);
532 if (!test) *newid = (ID *)BKE_movieclip_copy(bmain, (MovieClip *)id);
535 if (!test) *newid = (ID *)BKE_mask_copy(bmain, (Mask *)id);
538 if (!test) *newid = (ID *)BKE_linestyle_copy(bmain, (FreestyleLineStyle *)id);
541 if (!test) *newid = (ID *)BKE_palette_copy(bmain, (Palette *)id);
544 if (!test) *newid = (ID *)BKE_paint_curve_copy(bmain, (PaintCurve *)id);
547 if (!test) *newid = (ID *)BKE_cachefile_copy(bmain, (CacheFile *)id);
553 return false; /* can't be copied from here */
556 return false; /* not implemented */
558 return false; /* deprecated */
564 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
570 /* if property isn't editable, we're going to have an extra block hanging around until we save */
571 if (RNA_property_editable(ptr, prop)) {
572 if (id_copy(CTX_data_main(C), id, &newid, false) && newid) {
573 /* copy animation actions too */
574 BKE_animdata_copy_id_action(id);
575 /* us is 1 by convention, but RNA_property_pointer_set
576 * will also increment it, so set it to zero */
580 RNA_id_pointer_create(newid, &idptr);
581 RNA_property_pointer_set(ptr, prop, idptr);
582 RNA_property_update(C, ptr, prop);
592 ListBase *which_libbase(Main *mainlib, short type)
594 switch ((ID_Type)type) {
596 return &(mainlib->scene);
598 return &(mainlib->library);
600 return &(mainlib->object);
602 return &(mainlib->mesh);
604 return &(mainlib->curve);
606 return &(mainlib->mball);
608 return &(mainlib->mat);
610 return &(mainlib->tex);
612 return &(mainlib->image);
614 return &(mainlib->latt);
616 return &(mainlib->lamp);
618 return &(mainlib->camera);
620 return &(mainlib->ipo);
622 return &(mainlib->key);
624 return &(mainlib->world);
626 return &(mainlib->screen);
628 return &(mainlib->vfont);
630 return &(mainlib->text);
632 return &(mainlib->speaker);
634 return &(mainlib->sound);
636 return &(mainlib->group);
638 return &(mainlib->armature);
640 return &(mainlib->action);
642 return &(mainlib->nodetree);
644 return &(mainlib->brush);
646 return &(mainlib->particle);
648 return &(mainlib->wm);
650 return &(mainlib->gpencil);
652 return &(mainlib->movieclip);
654 return &(mainlib->mask);
656 return &(mainlib->linestyle);
658 return &(mainlib->palettes);
660 return &(mainlib->paintcurves);
662 return &(mainlib->cachefiles);
668 * Clear or set given tags for all ids in listbase (runtime tags).
670 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
674 for (id = lb->first; id; id = id->next) {
679 const int ntag = ~tag;
680 for (id = lb->first; id; id = id->next) {
687 * Clear or set given tags for all ids of given type in bmain (runtime tags).
689 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
691 ListBase *lb = which_libbase(mainvar, type);
693 BKE_main_id_tag_listbase(lb, tag, value);
697 * Clear or set given tags for all ids in bmain (runtime tags).
699 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
701 ListBase *lbarray[MAX_LIBARRAY];
704 a = set_listbasepointers(mainvar, lbarray);
706 BKE_main_id_tag_listbase(lbarray[a], tag, value);
712 * Clear or set given flags for all ids in listbase (persistent flags).
714 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
718 for (id = lb->first; id; id = id->next)
722 const int nflag = ~flag;
723 for (id = lb->first; id; id = id->next)
729 * Clear or set given flags for all ids in bmain (persistent flags).
731 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
733 ListBase *lbarray[MAX_LIBARRAY];
735 a = set_listbasepointers(bmain, lbarray);
737 BKE_main_id_flag_listbase(lbarray[a], flag, value);
741 void BKE_main_lib_objects_recalc_all(Main *bmain)
745 /* flag for full recalc */
746 for (ob = bmain->object.first; ob; ob = ob->id.next) {
747 if (ID_IS_LINKED_DATABLOCK(ob)) {
748 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
752 DAG_id_type_tag(bmain, ID_OB);
756 * puts into array *lb pointers to all the ListBase structs in main,
757 * and returns the number of them as the function result. This is useful for
758 * generic traversal of all the blocks in a Main (by traversing all the
759 * lists in turn), without worrying about block types.
761 * \note MAX_LIBARRAY define should match this code */
762 int set_listbasepointers(Main *main, ListBase **lb)
764 /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
765 * This is important because freeing data decreases usercounts of other datablocks,
766 * if this data is its self freed it can crash. */
767 lb[INDEX_ID_LI] = &(main->library); /* Libraries may be accessed from pretty much any other ID... */
768 lb[INDEX_ID_IP] = &(main->ipo);
769 lb[INDEX_ID_AC] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
770 lb[INDEX_ID_KE] = &(main->key);
771 lb[INDEX_ID_GD] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
772 lb[INDEX_ID_NT] = &(main->nodetree);
773 lb[INDEX_ID_IM] = &(main->image);
774 lb[INDEX_ID_TE] = &(main->tex);
775 lb[INDEX_ID_MA] = &(main->mat);
776 lb[INDEX_ID_VF] = &(main->vfont);
778 /* Important!: When adding a new object type,
779 * the specific data should be inserted here
782 lb[INDEX_ID_AR] = &(main->armature);
784 lb[INDEX_ID_CF] = &(main->cachefiles);
785 lb[INDEX_ID_ME] = &(main->mesh);
786 lb[INDEX_ID_CU] = &(main->curve);
787 lb[INDEX_ID_MB] = &(main->mball);
789 lb[INDEX_ID_LT] = &(main->latt);
790 lb[INDEX_ID_LA] = &(main->lamp);
791 lb[INDEX_ID_CA] = &(main->camera);
793 lb[INDEX_ID_TXT] = &(main->text);
794 lb[INDEX_ID_SO] = &(main->sound);
795 lb[INDEX_ID_GR] = &(main->group);
796 lb[INDEX_ID_PAL] = &(main->palettes);
797 lb[INDEX_ID_PC] = &(main->paintcurves);
798 lb[INDEX_ID_BR] = &(main->brush);
799 lb[INDEX_ID_PA] = &(main->particle);
800 lb[INDEX_ID_SPK] = &(main->speaker);
802 lb[INDEX_ID_WO] = &(main->world);
803 lb[INDEX_ID_MC] = &(main->movieclip);
804 lb[INDEX_ID_SCR] = &(main->screen);
805 lb[INDEX_ID_OB] = &(main->object);
806 lb[INDEX_ID_LS] = &(main->linestyle); /* referenced by scenes */
807 lb[INDEX_ID_SCE] = &(main->scene);
808 lb[INDEX_ID_WM] = &(main->wm);
809 lb[INDEX_ID_MSK] = &(main->mask);
811 lb[INDEX_ID_NULL] = NULL;
813 return (MAX_LIBARRAY - 1);
816 /* *********** ALLOC AND FREE *****************
818 * BKE_libblock_free(ListBase *lb, ID *id )
819 * provide a list-basis and datablock, but only ID is read
821 * void *BKE_libblock_alloc(ListBase *lb, type, name)
822 * inserts in list and returns a new ID
824 * **************************** */
827 * Allocates and returns memory of the right size for the specified block type,
828 * initialized to zero.
830 void *BKE_libblock_alloc_notest(short type)
834 switch ((ID_Type)type) {
836 id = MEM_callocN(sizeof(Scene), "scene");
839 id = MEM_callocN(sizeof(Library), "library");
842 id = MEM_callocN(sizeof(Object), "object");
845 id = MEM_callocN(sizeof(Mesh), "mesh");
848 id = MEM_callocN(sizeof(Curve), "curve");
851 id = MEM_callocN(sizeof(MetaBall), "mball");
854 id = MEM_callocN(sizeof(Material), "mat");
857 id = MEM_callocN(sizeof(Tex), "tex");
860 id = MEM_callocN(sizeof(Image), "image");
863 id = MEM_callocN(sizeof(Lattice), "latt");
866 id = MEM_callocN(sizeof(Lamp), "lamp");
869 id = MEM_callocN(sizeof(Camera), "camera");
872 id = MEM_callocN(sizeof(Ipo), "ipo");
875 id = MEM_callocN(sizeof(Key), "key");
878 id = MEM_callocN(sizeof(World), "world");
881 id = MEM_callocN(sizeof(bScreen), "screen");
884 id = MEM_callocN(sizeof(VFont), "vfont");
887 id = MEM_callocN(sizeof(Text), "text");
890 id = MEM_callocN(sizeof(Speaker), "speaker");
893 id = MEM_callocN(sizeof(bSound), "sound");
896 id = MEM_callocN(sizeof(Group), "group");
899 id = MEM_callocN(sizeof(bArmature), "armature");
902 id = MEM_callocN(sizeof(bAction), "action");
905 id = MEM_callocN(sizeof(bNodeTree), "nodetree");
908 id = MEM_callocN(sizeof(Brush), "brush");
911 id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
914 id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
917 id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
920 id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
923 id = MEM_callocN(sizeof(Mask), "Mask");
926 id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
929 id = MEM_callocN(sizeof(Palette), "Palette");
932 id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
935 id = MEM_callocN(sizeof(CacheFile), "Cache File");
942 * Allocates and returns a block of the specified type, with the specified name
943 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
944 * The user count is set to 1, all other content (apart from name and links) being
945 * initialized to zero.
947 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
950 ListBase *lb = which_libbase(bmain, type);
952 id = BKE_libblock_alloc_notest(type);
954 BKE_main_lock(bmain);
958 *( (short *)id->name) = type;
959 new_id(lb, id, name);
960 /* alphabetic insertion: is in new_id */
961 BKE_main_unlock(bmain);
963 DAG_id_type_tag(bmain, type);
968 * Initialize an ID of given type, such that it has valid 'empty' data.
969 * ID is assumed to be just calloc'ed.
971 void BKE_libblock_init_empty(ID *id)
973 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
974 switch ((ID_Type)GS(id->name)) {
976 BKE_scene_init((Scene *)id);
983 Object *ob = (Object *)id;
989 BKE_mesh_init((Mesh *)id);
992 BKE_curve_init((Curve *)id);
995 BKE_mball_init((MetaBall *)id);
998 BKE_material_init((Material *)id);
1001 BKE_texture_default((Tex *)id);
1004 BKE_image_init((Image *)id);
1007 BKE_lattice_init((Lattice *)id);
1010 BKE_lamp_init((Lamp *)id);
1013 BKE_speaker_init((Speaker *)id);
1016 BKE_camera_init((Camera *)id);
1019 BKE_world_init((World *)id);
1022 /* Nothing to do. */
1025 BKE_vfont_init((VFont *)id);
1028 BKE_text_init((Text *)id);
1031 /* Another fuzzy case, think NULLified content is OK here... */
1034 /* Nothing to do. */
1037 /* Nothing to do. */
1040 /* Nothing to do. */
1043 ntreeInitDefault((bNodeTree *)id);
1046 BKE_brush_init((Brush *)id);
1049 /* Nothing to do. */
1052 /* Nothing to do. */
1055 /* Nothing to do. */
1058 /* Nothing to do. */
1061 BKE_linestyle_init((FreestyleLineStyle *)id);
1064 BKE_cachefile_init((CacheFile *)id);
1067 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
1068 * They are not linkable, though, so it should never reach here anyway. */
1072 /* We should never reach this. */
1076 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
1080 BLI_assert(0); /* Should never reach this point... */
1084 /* by spec, animdata is first item after ID */
1085 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
1086 static void id_copy_animdata(ID *id, const bool do_action)
1088 AnimData *adt = BKE_animdata_from_id(id);
1091 IdAdtTemplate *iat = (IdAdtTemplate *)id;
1092 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
1096 /* material nodes use this since they are not treated as libdata */
1097 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
1099 if (id_from->properties)
1100 id->properties = IDP_CopyProperty(id_from->properties);
1102 /* the duplicate should get a copy of the animdata */
1103 id_copy_animdata(id, do_action);
1106 /* used everywhere in blenkernel */
1107 void *BKE_libblock_copy(Main *bmain, ID *id)
1112 idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
1114 assert(idn != NULL);
1116 idn_len = MEM_allocN_len(idn);
1117 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1118 const char *cp = (const char *)id;
1119 char *cpn = (char *)idn;
1121 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1125 idn->tag |= LIB_TAG_NEW;
1127 BKE_libblock_copy_data(idn, id, false);
1132 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1137 idn = BKE_libblock_alloc_notest(GS(id->name));
1138 assert(idn != NULL);
1140 BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1142 idn_len = MEM_allocN_len(idn);
1143 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1144 const char *cp = (const char *)id;
1145 char *cpn = (char *)idn;
1147 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1151 idn->tag |= LIB_TAG_NEW;
1154 BKE_libblock_copy_data(idn, id, do_action);
1159 static int id_relink_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cd_flag)
1161 ID *id = *id_pointer;
1163 /* See: NEW_ID macro */
1165 BKE_library_update_ID_link_user(id->newid, id, cd_flag);
1166 *id_pointer = id->newid;
1168 else if (id->tag & LIB_TAG_NEW) {
1169 id->tag &= ~LIB_TAG_NEW;
1170 BKE_libblock_relink(id);
1173 return IDWALK_RET_NOP;
1176 void BKE_libblock_relink(ID *id)
1178 if (ID_IS_LINKED_DATABLOCK(id))
1181 BKE_library_foreach_ID_link(id, id_relink_looper, NULL, 0);
1184 void BKE_library_free(Library *lib)
1186 if (lib->packedfile)
1187 freePackedFile(lib->packedfile);
1190 Main *BKE_main_new(void)
1192 Main *bmain = MEM_callocN(sizeof(Main), "new main");
1193 bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1194 bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1195 BLI_spin_init((SpinLock *)bmain->lock);
1199 void BKE_main_free(Main *mainvar)
1201 /* also call when reading a file, erase all, etc */
1202 ListBase *lbarray[MAX_LIBARRAY];
1205 MEM_SAFE_FREE(mainvar->blen_thumb);
1207 a = set_listbasepointers(mainvar, lbarray);
1209 ListBase *lb = lbarray[a];
1212 while ( (id = lb->first) ) {
1214 BKE_libblock_free_ex(mainvar, id, false, false);
1216 /* errors freeing ID's can be hard to track down,
1217 * enable this so valgrind will give the line number in its error log */
1219 case 0: BKE_libblock_free_ex(mainvar, id, false, false); break;
1220 case 1: BKE_libblock_free_ex(mainvar, id, false, false); break;
1221 case 2: BKE_libblock_free_ex(mainvar, id, false, false); break;
1222 case 3: BKE_libblock_free_ex(mainvar, id, false, false); break;
1223 case 4: BKE_libblock_free_ex(mainvar, id, false, false); break;
1224 case 5: BKE_libblock_free_ex(mainvar, id, false, false); break;
1225 case 6: BKE_libblock_free_ex(mainvar, id, false, false); break;
1226 case 7: BKE_libblock_free_ex(mainvar, id, false, false); break;
1227 case 8: BKE_libblock_free_ex(mainvar, id, false, false); break;
1228 case 9: BKE_libblock_free_ex(mainvar, id, false, false); break;
1229 case 10: BKE_libblock_free_ex(mainvar, id, false, false); break;
1230 case 11: BKE_libblock_free_ex(mainvar, id, false, false); break;
1231 case 12: BKE_libblock_free_ex(mainvar, id, false, false); break;
1232 case 13: BKE_libblock_free_ex(mainvar, id, false, false); break;
1233 case 14: BKE_libblock_free_ex(mainvar, id, false, false); break;
1234 case 15: BKE_libblock_free_ex(mainvar, id, false, false); break;
1235 case 16: BKE_libblock_free_ex(mainvar, id, false, false); break;
1236 case 17: BKE_libblock_free_ex(mainvar, id, false, false); break;
1237 case 18: BKE_libblock_free_ex(mainvar, id, false, false); break;
1238 case 19: BKE_libblock_free_ex(mainvar, id, false, false); break;
1239 case 20: BKE_libblock_free_ex(mainvar, id, false, false); break;
1240 case 21: BKE_libblock_free_ex(mainvar, id, false, false); break;
1241 case 22: BKE_libblock_free_ex(mainvar, id, false, false); break;
1242 case 23: BKE_libblock_free_ex(mainvar, id, false, false); break;
1243 case 24: BKE_libblock_free_ex(mainvar, id, false, false); break;
1244 case 25: BKE_libblock_free_ex(mainvar, id, false, false); break;
1245 case 26: BKE_libblock_free_ex(mainvar, id, false, false); break;
1246 case 27: BKE_libblock_free_ex(mainvar, id, false, false); break;
1247 case 28: BKE_libblock_free_ex(mainvar, id, false, false); break;
1248 case 29: BKE_libblock_free_ex(mainvar, id, false, false); break;
1249 case 30: BKE_libblock_free_ex(mainvar, id, false, false); break;
1250 case 31: BKE_libblock_free_ex(mainvar, id, false, false); break;
1251 case 32: BKE_libblock_free_ex(mainvar, id, false, false); break;
1252 case 33: BKE_libblock_free_ex(mainvar, id, false, false); break;
1253 case 34: BKE_libblock_free_ex(mainvar, id, false, false); break;
1262 BLI_spin_end((SpinLock *)mainvar->lock);
1263 MEM_freeN(mainvar->lock);
1264 DEG_evaluation_context_free(mainvar->eval_ctx);
1268 void BKE_main_lock(struct Main *bmain)
1270 BLI_spin_lock((SpinLock *) bmain->lock);
1273 void BKE_main_unlock(struct Main *bmain)
1275 BLI_spin_unlock((SpinLock *) bmain->lock);
1279 * Generates a raw .blend file thumbnail data from given image.
1281 * \param bmain If not NULL, also store generated data in this Main.
1282 * \param img ImBuf image to generate thumbnail data from.
1283 * \return The generated .blend file raw thumbnail data.
1285 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1287 BlendThumbnail *data = NULL;
1290 MEM_SAFE_FREE(bmain->blen_thumb);
1294 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1295 data = MEM_mallocN(sz, __func__);
1297 IMB_rect_from_float(img); /* Just in case... */
1298 data->width = img->x;
1299 data->height = img->y;
1300 memcpy(data->rect, img->rect, sz - sizeof(*data));
1304 bmain->blen_thumb = data;
1310 * Generates an image from raw .blend file thumbnail \a data.
1312 * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1313 * \param data Raw .blend file thumbnail data.
1314 * \return An ImBuf from given data, or NULL if invalid.
1316 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1320 if (!data && bmain) {
1321 data = bmain->blen_thumb;
1325 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1326 * here (we do not want to pass the first two ints!). */
1327 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1328 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1335 * Generates an empty (black) thumbnail for given Main.
1337 void BKE_main_thumbnail_create(struct Main *bmain)
1339 MEM_SAFE_FREE(bmain->blen_thumb);
1341 bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1342 bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1343 bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1346 /* ***************** ID ************************ */
1347 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1349 ListBase *lb = which_libbase(bmain, type);
1350 BLI_assert(lb != NULL);
1351 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1353 ID *BKE_libblock_find_name(const short type, const char *name)
1355 return BKE_libblock_find_name_ex(G.main, type, name);
1359 void id_sort_by_name(ListBase *lb, ID *id)
1363 /* insert alphabetically */
1364 if (lb->first != lb->last) {
1365 BLI_remlink(lb, id);
1369 if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1370 BLI_insertlinkbefore(lb, idtest, id);
1373 idtest = idtest->next;
1376 if (idtest == NULL) {
1377 BLI_addtail(lb, id);
1384 * Check to see if there is an ID with the same name as 'name'.
1385 * Returns the ID if so, if not, returns NULL
1387 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1391 for (idtest = lb->first; idtest; idtest = idtest->next) {
1392 /* if idtest is not a lib */
1393 if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
1394 /* do not test alphabetic! */
1396 if (idtest->name[2] == name[0]) {
1397 if (STREQ(name, idtest->name + 2)) break;
1406 * Check to see if an ID name is already used, and find a new one if so.
1407 * Return true if created a new name (returned in name).
1409 * Normally the ID that's being check is already in the ListBase, so ID *id
1410 * points at the new entry. The Python Library module needs to know what
1411 * the name of a datablock will be before it is appended; in this case ID *id
1415 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1418 int nr = 0, a, left_len;
1419 #define MAX_IN_USE 64
1420 bool in_use[MAX_IN_USE];
1421 /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1423 char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1427 /* phase 1: id already exists? */
1428 idtest = is_dupid(lb, id, name);
1430 /* if there is no double, done */
1431 if (idtest == NULL) return false;
1433 /* we have a dup; need to make a new name */
1434 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1435 memset(in_use, false, sizeof(in_use));
1437 /* get name portion, number portion ("name.number") */
1438 left_len = BLI_split_name_num(left, &nr, name, '.');
1440 /* if new name will be too long, truncate it */
1441 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* assumption: won't go beyond 9999 */
1442 left[MAX_ID_NAME - 8] = 0;
1443 left_len = MAX_ID_NAME - 8;
1445 else if (left_len > (MAX_ID_NAME - 7)) {
1446 left[MAX_ID_NAME - 7] = 0;
1447 left_len = MAX_ID_NAME - 7;
1450 for (idtest = lb->first; idtest; idtest = idtest->next) {
1452 if ( (id != idtest) &&
1453 !ID_IS_LINKED_DATABLOCK(idtest) &&
1454 (*name == *(idtest->name + 2)) &&
1455 STREQLEN(name, idtest->name + 2, left_len) &&
1456 (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1459 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1460 if (nrtest < MAX_IN_USE)
1461 in_use[nrtest] = true; /* mark as used */
1463 nr = nrtest + 1; /* track largest unused */
1466 /* At this point, 'nr' will typically be at least 1. (but not always) */
1467 // BLI_assert(nr >= 1);
1469 /* decide which value of nr to use */
1470 for (a = 0; a < MAX_IN_USE; a++) {
1471 if (a >= nr) break; /* stop when we've checked up to biggest */ /* redundant check */
1472 if (!in_use[a]) { /* found an unused value */
1474 /* can only be zero if all potential duplicate names had
1475 * nonzero numeric suffixes, which means name itself has
1476 * nonzero numeric suffix (else no name conflict and wouldn't
1477 * have got here), which means name[left_len] is not a null */
1481 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1482 * or 1 greater than the largest used number if all those low ones are taken.
1483 * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1485 /* If the original name has no numeric suffix,
1486 * rather than just chopping and adding numbers,
1487 * shave off the end chars until we have a unique name.
1488 * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1489 if (nr == 0 && name[left_len] == '\0') {
1491 /* FIXME: this code will never be executed, because either nr will be
1492 * at least 1, or name will not end at left_len! */
1496 idtest = is_dupid(lb, id, name);
1498 while (idtest && len > 1) {
1500 idtest = is_dupid(lb, id, name);
1502 if (idtest == NULL) return true;
1503 /* otherwise just continue and use a number suffix */
1506 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1507 /* this would overflow name buffer */
1508 left[MAX_ID_NAME - 8] = 0;
1509 /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1510 memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1513 /* this format specifier is from hell... */
1514 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1523 * Only for local blocks: external en indirect blocks already have a
1526 * return true: created a new name
1529 bool new_id(ListBase *lb, ID *id, const char *tname)
1532 char name[MAX_ID_NAME - 2];
1534 /* if library, don't rename */
1535 if (ID_IS_LINKED_DATABLOCK(id))
1538 /* if no libdata given, look up based on ID */
1540 lb = which_libbase(G.main, GS(id->name));
1542 /* if no name given, use name of current ID
1543 * else make a copy (tname args can be const) */
1545 tname = id->name + 2;
1547 BLI_strncpy(name, tname, sizeof(name));
1549 if (name[0] == '\0') {
1550 /* disallow empty names */
1551 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1554 /* disallow non utf8 chars,
1555 * the interface checks for this but new ID's based on file names don't */
1556 BLI_utf8_invalid_strip(name, strlen(name));
1559 result = check_for_dupid(lb, id, name);
1560 strcpy(id->name + 2, name);
1562 /* This was in 2.43 and previous releases
1563 * however all data in blender should be sorted, not just duplicate names
1564 * sorting should not hurt, but noting just incase it alters the way other
1565 * functions work, so sort every time */
1568 id_sort_by_name(lb, id);
1571 id_sort_by_name(lb, id);
1577 * Pull an ID out of a library (make it local). Only call this for IDs that
1578 * don't have other library users.
1580 void id_clear_lib_data_ex(Main *bmain, ID *id, const bool id_in_mainlist)
1582 bNodeTree *ntree = NULL;
1585 BKE_id_lib_local_paths(bmain, id->lib, id);
1587 id_fake_user_clear(id);
1590 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1592 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1594 /* Internal bNodeTree blocks inside datablocks also stores id->lib, make sure this stays in sync. */
1595 if ((ntree = ntreeFromID(id))) {
1596 id_clear_lib_data_ex(bmain, &ntree->id, false); /* Datablocks' nodetree is never in Main. */
1599 /* Same goes for shapekeys. */
1600 if ((key = BKE_key_from_id(id))) {
1601 id_clear_lib_data_ex(bmain, &key->id, id_in_mainlist); /* sigh, why are keys in Main? */
1605 void id_clear_lib_data(Main *bmain, ID *id)
1607 id_clear_lib_data_ex(bmain, id, true);
1610 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1611 void BKE_main_id_clear_newpoins(Main *bmain)
1613 ListBase *lbarray[MAX_LIBARRAY];
1617 a = set_listbasepointers(bmain, lbarray);
1619 id = lbarray[a]->first;
1622 id->tag &= ~LIB_TAG_NEW;
1628 /** Make linked datablocks local.
1630 * \param bmain Almost certainly G.main.
1631 * \param lib If not NULL, only make local datablocks from this library.
1632 * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1633 * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1635 /* Note: Old (2.77) version was simply making (tagging) datablocks as local, without actually making any check whether
1636 * they were also indirectly used or not...
1638 * Current version uses regular id_make_local callback, which is not super-efficient since this ends up
1639 * duplicating some IDs and then removing original ones (due to missing knowledge of which ID uses some other ID).
1641 * However, we now have a first check that allows us to use 'direct localization' of a lot of IDs, so performances
1642 * are now *reasonably* OK.
1644 void BKE_library_make_local(
1645 Main *bmain, const Library *lib, GHash *old_to_new_ids, const bool untagged_only, const bool set_fake)
1647 ListBase *lbarray[MAX_LIBARRAY];
1651 LinkNode *todo_ids = NULL;
1652 LinkNode *copied_ids = NULL;
1653 LinkNode *linked_loop_candidates = NULL;
1654 MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
1656 /* Step 1: Detect datablocks to make local. */
1657 for (a = set_listbasepointers(bmain, lbarray); a--; ) {
1658 id = lbarray[a]->first;
1660 /* Do not explicitly make local non-linkable IDs (shapekeys, in fact), they are assumed to be handled
1661 * by real datablocks responsible of them. */
1662 const bool do_skip = (id && !BKE_idcode_is_linkable(GS(id->name)));
1664 for (; id; id = id->next) {
1666 id->tag &= ~LIB_TAG_DOIT;
1668 if (id->lib == NULL) {
1669 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1671 /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so its
1672 * possible to tag data you don't want to be made local, used for
1673 * appending data, so any libdata already linked wont become local
1674 * (very nasty to discover all your links are lost after appending).
1675 * Also, never ever make proxified objects local, would not make any sense. */
1676 else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1677 ELEM(lib, NULL, id->lib) &&
1678 !(GS(id->name) == ID_OB && ((Object *)id)->proxy_from != NULL) &&
1679 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1681 BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem);
1682 id->tag |= LIB_TAG_DOIT;
1687 /* Step 2: Check which datablocks we can directly make local (because they are only used by already, or future,
1688 * local data), others will need to be duplicated and further processed later. */
1689 BKE_library_indirectly_used_data_tag_clear(bmain);
1691 /* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
1692 * which involves more complex checks and might instead create a local copy of original linked ID. */
1693 for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
1697 if (id->tag & LIB_TAG_DOIT) {
1698 /* We know all users of this object are local or will be made fully local, even if currently there are
1699 * some indirect usages. So instead of making a copy that se'll likely get rid of later, directly make
1700 * that data block local. Saves a tremendous amount of time with complex scenes... */
1701 id_clear_lib_data_ex(bmain, id, true);
1702 BKE_id_expand_local(id);
1703 id->tag &= ~LIB_TAG_DOIT;
1706 /* In this specific case, we do want to make ID local even if it has no local usage yet... */
1707 if (GS(id->name) == ID_OB) {
1708 /* Special case for objects because we don't want proxy pointers to be
1709 * cleared yet. This will happen down the road in this function.
1711 BKE_object_make_local_ex(bmain, (Object*)id, true, false);
1714 id_make_local(bmain, id, false, true);
1718 /* Reuse already allocated LinkNode (transferring it from todo_ids to copied_ids). */
1719 BLI_linklist_prepend_nlink(&copied_ids, id, it);
1724 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1725 /* do not set fake user on objects, groups (instancing) */
1726 id_fake_user_set(id);
1731 /* At this point, we are done with directly made local IDs. Now we have to handle duplicated ones, since their
1732 * remaining linked original counterpart may not be needed anymore... */
1735 /* Step 4: We have to remap local usages of old (linked) ID to new (local) id in a separated loop,
1736 * as lbarray ordering is not enough to ensure us we did catch all dependencies
1737 * (e.g. if making local a parent object before its child...). See T48907. */
1738 for (LinkNode *it = copied_ids; it; it = it->next) {
1741 BLI_assert(id->newid != NULL);
1742 BLI_assert(id->lib != NULL);
1744 BKE_libblock_remap(bmain, id, id->newid, ID_REMAP_SKIP_INDIRECT_USAGE);
1745 if (old_to_new_ids) {
1746 BLI_ghash_insert(old_to_new_ids, id, id->newid);
1749 /* Special hack for groups... Thing is, since we can't instantiate them here, we need to ensure
1750 * they remain 'alive' (only instantiation is a real group 'user'... *sigh* See T49722. */
1751 if (GS(id->name) == ID_GR && (id->tag & LIB_TAG_INDIRECT) != 0) {
1752 id_us_ensure_real(id->newid);
1756 /* Step 5: remove datablocks that have been copied to be localized and are no more used in the end...
1757 * Note that we may have to loop more than once here, to tackle dependencies between linked objects... */
1758 bool do_loop = true;
1761 for (LinkNode *it = copied_ids; it; it = it->next) {
1762 if ((id = it->link) == NULL) {
1766 bool is_local = false, is_lib = false;
1768 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
1770 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
1771 * from another blend file into this one, even when that blend file contains proxified
1772 * armatures that have local references. Since the proxified object needs to be linked
1773 * (not local), this will only work when the "Localize all" checkbox is disabled.
1774 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
1775 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
1776 Object *ob = (Object *)id;
1777 Object *ob_new = (Object *)id->newid;
1779 /* Proxies only work when the proxified object is linked-in from a library. */
1780 if (ob->proxy->id.lib == NULL) {
1781 printf("Warning, proxy object %s will loose its link to %s, because the "
1782 "proxified object is local.\n", id->newid->name, ob->proxy->id.name);
1784 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
1785 * referred to from a library. Not checking for local use; if new local proxy
1786 * was not used locally would be a nasty bug! */
1787 else if (is_local || is_lib) {
1788 printf("Warning, made-local proxy object %s will loose its link to %s, "
1789 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
1790 id->newid->name, ob->proxy->id.name, is_local, is_lib);
1793 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
1794 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
1795 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy_ex). */
1796 ob_new->proxy = ob->proxy;
1797 ob_new->proxy_group = ob->proxy_group;
1798 ob_new->proxy_from = ob->proxy_from;
1799 ob_new->proxy->proxy_from = ob_new;
1800 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
1805 if (!is_lib) { /* Not used at all, we can free it! */
1806 BKE_libblock_free(bmain, id);
1810 /* Only used by linked data, potential candidate to ugly lib-only dependency cycles... */
1811 else if ((id->tag & LIB_TAG_DOIT) == 0) { /* Check TAG_DOIT to avoid adding same ID several times... */
1812 /* Note that we store the node, not directly ID pointer, that way if it->link is set to NULL
1813 * later we can skip it in lib-dependency cycles search later. */
1814 BLI_linklist_prepend_arena(&linked_loop_candidates, it, linklist_mem);
1815 id->tag |= LIB_TAG_DOIT;
1817 /* Grrrrrrr... those half-datablocks-stuff... grrrrrrrrrrr...
1818 * Here we have to also tag them as potential candidates, otherwise they would falsy report
1819 * ID they used as 'directly used' in fourth step. */
1820 ID *ntree = (ID *)ntreeFromID(id);
1821 if (ntree != NULL) {
1822 ntree->tag |= LIB_TAG_DOIT;
1829 /* Step 6: Try to find circle dependencies between indirectly-linked-only datablocks.
1830 * Those are fake 'usages' that prevent their deletion. See T49775 for nice ugly case. */
1831 BKE_library_unused_linked_data_set_tag(bmain, false);
1832 for (LinkNode *it = linked_loop_candidates; it; it = it->next) {
1833 if (it->link == NULL) {
1836 if ((id = ((LinkNode *)it->link)->link) == NULL) {
1841 /* Note: in theory here we are only handling datablocks forming exclusive linked dependency-cycles-based
1842 * archipelagos, so no need to check again after we have deleted one, as done in previous step. */
1843 if (id->tag & LIB_TAG_DOIT) {
1844 /* Object's deletion rely on valid ob->data, but ob->data may have already been freed here...
1845 * Setting it to NULL may not be 100% correct, but should be safe and do the work. */
1846 if (GS(id->name) == ID_OB) {
1847 ((Object *)id)->data = NULL;
1850 /* Note: *in theory* IDs tagged here are fully *outside* of file scope, totally unused, so we can
1851 * directly wipe them out without caring about clearing their usages.
1852 * However, this is a highly-risky presumption, and nice crasher in case something goes wrong here.
1853 * So for 2.78a will keep the safe option, and switch to more efficient one in master later. */
1855 BKE_libblock_free_ex(bmain, id, false, true);
1857 BKE_libblock_unlink(bmain, id, false, false);
1858 BKE_libblock_free(bmain, id);
1860 ((LinkNode *)it->link)->link = NULL; /* Not strictly necessary, but safer (see T49903)... */
1865 BLI_memarena_free(linklist_mem);
1869 * Use after setting the ID's name
1870 * When name exists: call 'new_id'
1872 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
1878 lb = which_libbase(bmain, GS(name));
1879 if (lb == NULL) return;
1882 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1884 if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
1885 id_sort_by_name(lb, idtest);
1890 * Sets the name of a block to name, suitably adjusted for uniqueness.
1892 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
1894 ListBase *lb = which_libbase(bmain, GS(id->name));
1895 new_id(lb, id, name);
1899 * Returns in name the name of the block, with a 3-character prefix prepended
1900 * indicating whether it comes from a library, has a fake user, or no users.
1902 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
1904 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1905 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1908 strcpy(name + 3, id->name + 2);
1911 void BKE_library_filepath_set(Library *lib, const char *filepath)
1913 /* in some cases this is used to update the absolute path from the
1915 if (lib->name != filepath) {
1916 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1919 BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1921 /* not essential but set filepath is an absolute copy of value which
1922 * is more useful if its kept in sync */
1923 if (BLI_path_is_rel(lib->filepath)) {
1924 /* note that the file may be unsaved, in this case, setting the
1925 * filepath on an indirectly linked path is not allowed from the
1926 * outliner, and its not really supported but allow from here for now
1927 * since making local could cause this to be directly linked - campbell
1929 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1930 BLI_path_abs(lib->filepath, basepath);
1934 void BKE_id_tag_set_atomic(ID *id, int tag)
1936 atomic_fetch_and_or_uint32((uint32_t *)&id->tag, tag);
1939 void BKE_id_tag_clear_atomic(ID *id, int tag)
1941 atomic_fetch_and_and_uint32((uint32_t *)&id->tag, ~tag);