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_mempool.h"
80 #include "BLI_string_utils.h"
82 #include "BLI_threads.h"
83 #include "BLT_translation.h"
85 #include "BKE_action.h"
86 #include "BKE_animsys.h"
87 #include "BKE_armature.h"
88 #include "BKE_bpath.h"
89 #include "BKE_brush.h"
90 #include "BKE_camera.h"
91 #include "BKE_cachefile.h"
92 #include "BKE_context.h"
93 #include "BKE_curve.h"
94 #include "BKE_depsgraph.h"
96 #include "BKE_global.h"
97 #include "BKE_group.h"
98 #include "BKE_gpencil.h"
99 #include "BKE_idcode.h"
100 #include "BKE_idprop.h"
101 #include "BKE_image.h"
103 #include "BKE_lamp.h"
104 #include "BKE_lattice.h"
105 #include "BKE_library.h"
106 #include "BKE_library_query.h"
107 #include "BKE_library_remap.h"
108 #include "BKE_linestyle.h"
109 #include "BKE_mesh.h"
110 #include "BKE_material.h"
111 #include "BKE_main.h"
112 #include "BKE_mball.h"
113 #include "BKE_mask.h"
114 #include "BKE_movieclip.h"
115 #include "BKE_node.h"
116 #include "BKE_object.h"
117 #include "BKE_paint.h"
118 #include "BKE_particle.h"
119 #include "BKE_packedFile.h"
120 #include "BKE_sound.h"
121 #include "BKE_speaker.h"
122 #include "BKE_scene.h"
123 #include "BKE_text.h"
124 #include "BKE_texture.h"
125 #include "BKE_world.h"
127 #include "DEG_depsgraph.h"
129 #include "RNA_access.h"
131 #include "IMB_imbuf.h"
132 #include "IMB_imbuf_types.h"
134 #include "atomic_ops.h"
136 /* GS reads the memory pointed at in a specific ordering.
137 * only use this definition, makes little and big endian systems
138 * work fine, in conjunction with MAKE_ID */
140 /* ************* general ************************ */
143 /* this has to be called from each make_local_* func, we could call
144 * from id_make_local() but then the make local functions would not be self
146 * also note that the id _must_ have a library - campbell */
147 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
149 const char *bpath_user_data[2] = {bmain->name, lib->filepath};
151 BKE_bpath_traverse_id(bmain, id,
152 BKE_bpath_relocate_visitor,
153 BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
154 (void *)bpath_user_data);
157 void id_lib_extern(ID *id)
159 if (id && ID_IS_LINKED_DATABLOCK(id)) {
160 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
161 if (id->tag & LIB_TAG_INDIRECT) {
162 id->tag -= LIB_TAG_INDIRECT;
163 id->tag |= LIB_TAG_EXTERN;
168 /* ensure we have a real user */
169 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
170 * we always have a real user.
171 * However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
172 * to make this change... */
173 void id_us_ensure_real(ID *id)
176 const int limit = ID_FAKE_USERS(id);
177 id->tag |= LIB_TAG_EXTRAUSER;
178 if (id->us <= limit) {
179 if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
180 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
184 id->tag |= LIB_TAG_EXTRAUSER_SET;
189 void id_us_clear_real(ID *id)
191 if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
192 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
194 BLI_assert(id->us >= ID_FAKE_USERS(id));
196 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
201 * Same as \a id_us_plus, but does not handle lib indirect -> extern.
202 * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
204 void id_us_plus_no_lib(ID *id)
207 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
208 BLI_assert(id->us >= 1);
209 /* No need to increase count, just tag extra user as no more set.
210 * Avoids annoying & inconsistent +1 in user count. */
211 id->tag &= ~LIB_TAG_EXTRAUSER_SET;
214 BLI_assert(id->us >= 0);
221 void id_us_plus(ID *id)
224 id_us_plus_no_lib(id);
229 /* decrements the user count for *id. */
230 void id_us_min(ID *id)
233 const int limit = ID_FAKE_USERS(id);
235 if (id->us <= limit) {
236 printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
237 id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
245 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
246 /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
247 id_us_ensure_real(id);
252 void id_fake_user_set(ID *id)
254 if (id && !(id->flag & LIB_FAKEUSER)) {
255 id->flag |= LIB_FAKEUSER;
260 void id_fake_user_clear(ID *id)
262 if (id && (id->flag & LIB_FAKEUSER)) {
263 id->flag &= ~LIB_FAKEUSER;
268 void BKE_id_clear_newpoin(ID *id)
271 id->newid->tag &= ~LIB_TAG_NEW;
276 static int id_expand_local_callback(
277 void *UNUSED(user_data), struct ID *id_self, struct ID **id_pointer, int cd_flag)
279 if (cd_flag & IDWALK_CB_PRIVATE) {
280 return IDWALK_RET_NOP;
283 /* Can hapen that we get unlinkable ID here, e.g. with shapekey referring to itself (through drivers)...
284 * Just skip it, shape key can only be either indirectly linked, or fully local, period.
285 * And let's curse one more time that stupid useless shapekey ID type! */
286 if (*id_pointer && *id_pointer != id_self && BKE_idcode_is_linkable(GS((*id_pointer)->name))) {
287 id_lib_extern(*id_pointer);
290 return IDWALK_RET_NOP;
294 * Expand ID usages of given id as 'extern' (and no more indirect) linked data. Used by ID copy/make_local functions.
296 void BKE_id_expand_local(Main *bmain, ID *id)
298 BKE_library_foreach_ID_link(bmain, id, id_expand_local_callback, NULL, IDWALK_READONLY);
302 * Ensure new (copied) ID is fully made local.
304 void BKE_id_copy_ensure_local(Main *bmain, ID *old_id, ID *new_id)
306 if (ID_IS_LINKED_DATABLOCK(old_id)) {
307 BKE_id_expand_local(bmain, new_id);
308 BKE_id_lib_local_paths(bmain, old_id->lib, new_id);
313 * Generic 'make local' function, works for most of datablock types...
315 void BKE_id_make_local_generic(Main *bmain, ID *id, const bool id_in_mainlist, const bool lib_local)
317 bool is_local = false, is_lib = false;
319 /* - only lib users: do nothing (unless force_local is set)
320 * - only local users: set flag
322 * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
325 if (!ID_IS_LINKED_DATABLOCK(id)) {
329 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
331 if (lib_local || is_local) {
333 id_clear_lib_data_ex(bmain, id, id_in_mainlist);
334 BKE_id_expand_local(bmain, id);
339 /* Should not fail in expected usecases, but id_copy does not copy Scene e.g. */
340 if (id_copy(bmain, id, &id_new, false)) {
343 /* setting newid is mandatory for complex make_lib_local logic... */
344 ID_NEW_SET(id, id_new);
345 Key *key = BKE_key_from_id(id), *key_new = BKE_key_from_id(id);
346 if (key && key_new) {
347 ID_NEW_SET(key, key_new);
349 bNodeTree *ntree = ntreeFromID(id), *ntree_new = ntreeFromID(id_new);
350 if (ntree && ntree_new) {
351 ID_NEW_SET(ntree, ntree_new);
355 BKE_libblock_remap(bmain, id, id_new, ID_REMAP_SKIP_INDIRECT_USAGE);
363 * Calls the appropriate make_local method for the block, unless test is set.
365 * \note Always set ID->newid pointer in case it gets duplicated...
367 * \param lib_local Special flag used when making a whole library's content local, it needs specific handling.
369 * \return true if the block can be made local.
371 bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
373 /* We don't care whether ID is directly or indirectly linked in case we are making a whole lib local... */
374 if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) {
378 switch ((ID_Type)GS(id->name)) {
380 /* Partially implemented (has no copy...). */
381 if (!test) BKE_scene_make_local(bmain, (Scene *)id, lib_local);
384 if (!test) BKE_object_make_local(bmain, (Object *)id, lib_local);
387 if (!test) BKE_mesh_make_local(bmain, (Mesh *)id, lib_local);
390 if (!test) BKE_curve_make_local(bmain, (Curve *)id, lib_local);
393 if (!test) BKE_mball_make_local(bmain, (MetaBall *)id, lib_local);
396 if (!test) BKE_material_make_local(bmain, (Material *)id, lib_local);
399 if (!test) BKE_texture_make_local(bmain, (Tex *)id, lib_local);
402 if (!test) BKE_image_make_local(bmain, (Image *)id, lib_local);
405 if (!test) BKE_lattice_make_local(bmain, (Lattice *)id, lib_local);
408 if (!test) BKE_lamp_make_local(bmain, (Lamp *)id, lib_local);
411 if (!test) BKE_camera_make_local(bmain, (Camera *)id, lib_local);
414 if (!test) BKE_speaker_make_local(bmain, (Speaker *)id, lib_local);
417 if (!test) BKE_world_make_local(bmain, (World *)id, lib_local);
420 /* Partially implemented (has no copy...). */
421 if (!test) BKE_vfont_make_local(bmain, (VFont *)id, lib_local);
424 if (!test) BKE_text_make_local(bmain, (Text *)id, lib_local);
427 /* Partially implemented (has no copy...). */
428 if (!test) BKE_sound_make_local(bmain, (bSound *)id, lib_local);
431 if (!test) BKE_group_make_local(bmain, (Group *)id, lib_local);
434 if (!test) BKE_armature_make_local(bmain, (bArmature *)id, lib_local);
437 if (!test) BKE_action_make_local(bmain, (bAction *)id, lib_local);
440 if (!test) ntreeMakeLocal(bmain, (bNodeTree *)id, true, lib_local);
443 if (!test) BKE_brush_make_local(bmain, (Brush *)id, lib_local);
446 if (!test) BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, lib_local);
449 if (!test) BKE_gpencil_make_local(bmain, (bGPdata *)id, lib_local);
452 if (!test) BKE_movieclip_make_local(bmain, (MovieClip *)id, lib_local);
455 if (!test) BKE_mask_make_local(bmain, (Mask *)id, lib_local);
458 if (!test) BKE_linestyle_make_local(bmain, (FreestyleLineStyle *)id, lib_local);
461 if (!test) BKE_palette_make_local(bmain, (Palette *)id, lib_local);
464 if (!test) BKE_paint_curve_make_local(bmain, (PaintCurve *)id, lib_local);
467 if (!test) BKE_cachefile_make_local(bmain, (CacheFile *)id, lib_local);
473 return false; /* can't be linked */
475 return false; /* deprecated */
482 * Invokes the appropriate copy method for the block and returns the result in
483 * newid, unless test. Returns true if the block can be copied.
485 bool id_copy(Main *bmain, ID *id, ID **newid, bool test)
492 * - make shallow copy, only this ID block
493 * - id.us of the new ID is set to 1 */
494 switch ((ID_Type)GS(id->name)) {
496 if (!test) *newid = (ID *)BKE_object_copy(bmain, (Object *)id);
499 if (!test) *newid = (ID *)BKE_mesh_copy(bmain, (Mesh *)id);
502 if (!test) *newid = (ID *)BKE_curve_copy(bmain, (Curve *)id);
505 if (!test) *newid = (ID *)BKE_mball_copy(bmain, (MetaBall *)id);
508 if (!test) *newid = (ID *)BKE_material_copy(bmain, (Material *)id);
511 if (!test) *newid = (ID *)BKE_texture_copy(bmain, (Tex *)id);
514 if (!test) *newid = (ID *)BKE_image_copy(bmain, (Image *)id);
517 if (!test) *newid = (ID *)BKE_lattice_copy(bmain, (Lattice *)id);
520 if (!test) *newid = (ID *)BKE_lamp_copy(bmain, (Lamp *)id);
523 if (!test) *newid = (ID *)BKE_speaker_copy(bmain, (Speaker *)id);
526 if (!test) *newid = (ID *)BKE_camera_copy(bmain, (Camera *)id);
529 if (!test) *newid = (ID *)BKE_key_copy(bmain, (Key *)id);
532 if (!test) *newid = (ID *)BKE_world_copy(bmain, (World *)id);
535 if (!test) *newid = (ID *)BKE_text_copy(bmain, (Text *)id);
538 if (!test) *newid = (ID *)BKE_group_copy(bmain, (Group *)id);
541 if (!test) *newid = (ID *)BKE_armature_copy(bmain, (bArmature *)id);
544 if (!test) *newid = (ID *)BKE_action_copy(bmain, (bAction *)id);
547 if (!test) *newid = (ID *)ntreeCopyTree(bmain, (bNodeTree *)id);
550 if (!test) *newid = (ID *)BKE_brush_copy(bmain, (Brush *)id);
553 if (!test) *newid = (ID *)BKE_particlesettings_copy(bmain, (ParticleSettings *)id);
556 if (!test) *newid = (ID *)BKE_gpencil_data_duplicate(bmain, (bGPdata *)id, false);
559 if (!test) *newid = (ID *)BKE_movieclip_copy(bmain, (MovieClip *)id);
562 if (!test) *newid = (ID *)BKE_mask_copy(bmain, (Mask *)id);
565 if (!test) *newid = (ID *)BKE_linestyle_copy(bmain, (FreestyleLineStyle *)id);
568 if (!test) *newid = (ID *)BKE_palette_copy(bmain, (Palette *)id);
571 if (!test) *newid = (ID *)BKE_paint_curve_copy(bmain, (PaintCurve *)id);
574 if (!test) *newid = (ID *)BKE_cachefile_copy(bmain, (CacheFile *)id);
580 return false; /* can't be copied from here */
583 return false; /* not implemented */
585 return false; /* deprecated */
591 /** Does *not* set ID->newid pointer. */
592 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
598 /* if property isn't editable, we're going to have an extra block hanging around until we save */
599 if (RNA_property_editable(ptr, prop)) {
600 if (id_copy(CTX_data_main(C), id, &newid, false) && newid) {
601 /* copy animation actions too */
602 BKE_animdata_copy_id_action(id, false);
603 /* us is 1 by convention, but RNA_property_pointer_set
604 * will also increment it, so set it to zero */
608 RNA_id_pointer_create(newid, &idptr);
609 RNA_property_pointer_set(ptr, prop, idptr);
610 RNA_property_update(C, ptr, prop);
620 ListBase *which_libbase(Main *mainlib, short type)
622 switch ((ID_Type)type) {
624 return &(mainlib->scene);
626 return &(mainlib->library);
628 return &(mainlib->object);
630 return &(mainlib->mesh);
632 return &(mainlib->curve);
634 return &(mainlib->mball);
636 return &(mainlib->mat);
638 return &(mainlib->tex);
640 return &(mainlib->image);
642 return &(mainlib->latt);
644 return &(mainlib->lamp);
646 return &(mainlib->camera);
648 return &(mainlib->ipo);
650 return &(mainlib->key);
652 return &(mainlib->world);
654 return &(mainlib->screen);
656 return &(mainlib->vfont);
658 return &(mainlib->text);
660 return &(mainlib->speaker);
662 return &(mainlib->sound);
664 return &(mainlib->group);
666 return &(mainlib->armature);
668 return &(mainlib->action);
670 return &(mainlib->nodetree);
672 return &(mainlib->brush);
674 return &(mainlib->particle);
676 return &(mainlib->wm);
678 return &(mainlib->gpencil);
680 return &(mainlib->movieclip);
682 return &(mainlib->mask);
684 return &(mainlib->linestyle);
686 return &(mainlib->palettes);
688 return &(mainlib->paintcurves);
690 return &(mainlib->cachefiles);
696 * Clear or set given tags for all ids in listbase (runtime tags).
698 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
702 for (id = lb->first; id; id = id->next) {
707 const int ntag = ~tag;
708 for (id = lb->first; id; id = id->next) {
715 * Clear or set given tags for all ids of given type in bmain (runtime tags).
717 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
719 ListBase *lb = which_libbase(mainvar, type);
721 BKE_main_id_tag_listbase(lb, tag, value);
725 * Clear or set given tags for all ids in bmain (runtime tags).
727 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
729 ListBase *lbarray[MAX_LIBARRAY];
732 a = set_listbasepointers(mainvar, lbarray);
734 BKE_main_id_tag_listbase(lbarray[a], tag, value);
740 * Clear or set given flags for all ids in listbase (persistent flags).
742 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
746 for (id = lb->first; id; id = id->next)
750 const int nflag = ~flag;
751 for (id = lb->first; id; id = id->next)
757 * Clear or set given flags for all ids in bmain (persistent flags).
759 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
761 ListBase *lbarray[MAX_LIBARRAY];
763 a = set_listbasepointers(bmain, lbarray);
765 BKE_main_id_flag_listbase(lbarray[a], flag, value);
769 void BKE_main_lib_objects_recalc_all(Main *bmain)
773 /* flag for full recalc */
774 for (ob = bmain->object.first; ob; ob = ob->id.next) {
775 if (ID_IS_LINKED_DATABLOCK(ob)) {
776 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
780 DAG_id_type_tag(bmain, ID_OB);
784 * puts into array *lb pointers to all the ListBase structs in main,
785 * and returns the number of them as the function result. This is useful for
786 * generic traversal of all the blocks in a Main (by traversing all the
787 * lists in turn), without worrying about block types.
789 * \note MAX_LIBARRAY define should match this code */
790 int set_listbasepointers(Main *main, ListBase **lb)
792 /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
793 * This is important because freeing data decreases usercounts of other datablocks,
794 * if this data is its self freed it can crash. */
795 lb[INDEX_ID_LI] = &(main->library); /* Libraries may be accessed from pretty much any other ID... */
796 lb[INDEX_ID_IP] = &(main->ipo);
797 lb[INDEX_ID_AC] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
798 lb[INDEX_ID_KE] = &(main->key);
799 lb[INDEX_ID_GD] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
800 lb[INDEX_ID_NT] = &(main->nodetree);
801 lb[INDEX_ID_IM] = &(main->image);
802 lb[INDEX_ID_TE] = &(main->tex);
803 lb[INDEX_ID_MA] = &(main->mat);
804 lb[INDEX_ID_VF] = &(main->vfont);
806 /* Important!: When adding a new object type,
807 * the specific data should be inserted here
810 lb[INDEX_ID_AR] = &(main->armature);
812 lb[INDEX_ID_CF] = &(main->cachefiles);
813 lb[INDEX_ID_ME] = &(main->mesh);
814 lb[INDEX_ID_CU] = &(main->curve);
815 lb[INDEX_ID_MB] = &(main->mball);
817 lb[INDEX_ID_LT] = &(main->latt);
818 lb[INDEX_ID_LA] = &(main->lamp);
819 lb[INDEX_ID_CA] = &(main->camera);
821 lb[INDEX_ID_TXT] = &(main->text);
822 lb[INDEX_ID_SO] = &(main->sound);
823 lb[INDEX_ID_GR] = &(main->group);
824 lb[INDEX_ID_PAL] = &(main->palettes);
825 lb[INDEX_ID_PC] = &(main->paintcurves);
826 lb[INDEX_ID_BR] = &(main->brush);
827 lb[INDEX_ID_PA] = &(main->particle);
828 lb[INDEX_ID_SPK] = &(main->speaker);
830 lb[INDEX_ID_WO] = &(main->world);
831 lb[INDEX_ID_MC] = &(main->movieclip);
832 lb[INDEX_ID_SCR] = &(main->screen);
833 lb[INDEX_ID_OB] = &(main->object);
834 lb[INDEX_ID_LS] = &(main->linestyle); /* referenced by scenes */
835 lb[INDEX_ID_SCE] = &(main->scene);
836 lb[INDEX_ID_WM] = &(main->wm);
837 lb[INDEX_ID_MSK] = &(main->mask);
839 lb[INDEX_ID_NULL] = NULL;
841 return (MAX_LIBARRAY - 1);
844 /* *********** ALLOC AND FREE *****************
846 * BKE_libblock_free(ListBase *lb, ID *id )
847 * provide a list-basis and datablock, but only ID is read
849 * void *BKE_libblock_alloc(ListBase *lb, type, name)
850 * inserts in list and returns a new ID
852 * **************************** */
855 * Allocates and returns memory of the right size for the specified block type,
856 * initialized to zero.
858 void *BKE_libblock_alloc_notest(short type)
862 switch ((ID_Type)type) {
864 id = MEM_callocN(sizeof(Scene), "scene");
867 id = MEM_callocN(sizeof(Library), "library");
870 id = MEM_callocN(sizeof(Object), "object");
873 id = MEM_callocN(sizeof(Mesh), "mesh");
876 id = MEM_callocN(sizeof(Curve), "curve");
879 id = MEM_callocN(sizeof(MetaBall), "mball");
882 id = MEM_callocN(sizeof(Material), "mat");
885 id = MEM_callocN(sizeof(Tex), "tex");
888 id = MEM_callocN(sizeof(Image), "image");
891 id = MEM_callocN(sizeof(Lattice), "latt");
894 id = MEM_callocN(sizeof(Lamp), "lamp");
897 id = MEM_callocN(sizeof(Camera), "camera");
900 id = MEM_callocN(sizeof(Ipo), "ipo");
903 id = MEM_callocN(sizeof(Key), "key");
906 id = MEM_callocN(sizeof(World), "world");
909 id = MEM_callocN(sizeof(bScreen), "screen");
912 id = MEM_callocN(sizeof(VFont), "vfont");
915 id = MEM_callocN(sizeof(Text), "text");
918 id = MEM_callocN(sizeof(Speaker), "speaker");
921 id = MEM_callocN(sizeof(bSound), "sound");
924 id = MEM_callocN(sizeof(Group), "group");
927 id = MEM_callocN(sizeof(bArmature), "armature");
930 id = MEM_callocN(sizeof(bAction), "action");
933 id = MEM_callocN(sizeof(bNodeTree), "nodetree");
936 id = MEM_callocN(sizeof(Brush), "brush");
939 id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
942 id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
945 id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
948 id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
951 id = MEM_callocN(sizeof(Mask), "Mask");
954 id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
957 id = MEM_callocN(sizeof(Palette), "Palette");
960 id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
963 id = MEM_callocN(sizeof(CacheFile), "Cache File");
970 * Allocates and returns a block of the specified type, with the specified name
971 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
972 * The user count is set to 1, all other content (apart from name and links) being
973 * initialized to zero.
975 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
978 ListBase *lb = which_libbase(bmain, type);
980 id = BKE_libblock_alloc_notest(type);
982 BKE_main_lock(bmain);
986 *( (short *)id->name) = type;
987 new_id(lb, id, name);
988 /* alphabetic insertion: is in new_id */
989 BKE_main_unlock(bmain);
991 DAG_id_type_tag(bmain, type);
996 * Initialize an ID of given type, such that it has valid 'empty' data.
997 * ID is assumed to be just calloc'ed.
999 void BKE_libblock_init_empty(ID *id)
1001 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
1002 switch ((ID_Type)GS(id->name)) {
1004 BKE_scene_init((Scene *)id);
1007 /* Nothing to do. */
1011 Object *ob = (Object *)id;
1012 ob->type = OB_EMPTY;
1013 BKE_object_init(ob);
1017 BKE_mesh_init((Mesh *)id);
1020 BKE_curve_init((Curve *)id);
1023 BKE_mball_init((MetaBall *)id);
1026 BKE_material_init((Material *)id);
1029 BKE_texture_default((Tex *)id);
1032 BKE_image_init((Image *)id);
1035 BKE_lattice_init((Lattice *)id);
1038 BKE_lamp_init((Lamp *)id);
1041 BKE_speaker_init((Speaker *)id);
1044 BKE_camera_init((Camera *)id);
1047 BKE_world_init((World *)id);
1050 /* Nothing to do. */
1053 BKE_vfont_init((VFont *)id);
1056 BKE_text_init((Text *)id);
1059 /* Another fuzzy case, think NULLified content is OK here... */
1062 /* Nothing to do. */
1065 /* Nothing to do. */
1068 /* Nothing to do. */
1071 ntreeInitDefault((bNodeTree *)id);
1074 BKE_brush_init((Brush *)id);
1077 /* Nothing to do. */
1080 /* Nothing to do. */
1083 /* Nothing to do. */
1086 /* Nothing to do. */
1089 BKE_linestyle_init((FreestyleLineStyle *)id);
1092 BKE_cachefile_init((CacheFile *)id);
1095 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
1096 * They are not linkable, though, so it should never reach here anyway. */
1100 /* We should never reach this. */
1104 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
1108 BLI_assert(0); /* Should never reach this point... */
1112 /* by spec, animdata is first item after ID */
1113 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
1114 static void id_copy_animdata(ID *id, const bool do_action)
1116 AnimData *adt = BKE_animdata_from_id(id);
1119 IdAdtTemplate *iat = (IdAdtTemplate *)id;
1120 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
1124 /* material nodes use this since they are not treated as libdata */
1125 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
1127 if (id_from->properties)
1128 id->properties = IDP_CopyProperty(id_from->properties);
1130 /* the duplicate should get a copy of the animdata */
1131 id_copy_animdata(id, do_action);
1134 /* used everywhere in blenkernel */
1135 void *BKE_libblock_copy(Main *bmain, ID *id)
1140 idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
1142 assert(idn != NULL);
1144 idn_len = MEM_allocN_len(idn);
1145 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1146 const char *cp = (const char *)id;
1147 char *cpn = (char *)idn;
1149 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1152 BKE_libblock_copy_data(idn, id, false);
1157 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1162 idn = BKE_libblock_alloc_notest(GS(id->name));
1163 assert(idn != NULL);
1165 BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1167 idn_len = MEM_allocN_len(idn);
1168 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1169 const char *cp = (const char *)id;
1170 char *cpn = (char *)idn;
1172 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1177 BKE_libblock_copy_data(idn, id, do_action);
1182 void BKE_library_free(Library *lib)
1184 if (lib->packedfile)
1185 freePackedFile(lib->packedfile);
1188 Main *BKE_main_new(void)
1190 Main *bmain = MEM_callocN(sizeof(Main), "new main");
1191 bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1192 bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1193 BLI_spin_init((SpinLock *)bmain->lock);
1197 void BKE_main_free(Main *mainvar)
1199 /* also call when reading a file, erase all, etc */
1200 ListBase *lbarray[MAX_LIBARRAY];
1203 MEM_SAFE_FREE(mainvar->blen_thumb);
1205 a = set_listbasepointers(mainvar, lbarray);
1207 ListBase *lb = lbarray[a];
1210 while ( (id = lb->first) ) {
1212 BKE_libblock_free_ex(mainvar, id, false, false);
1214 /* errors freeing ID's can be hard to track down,
1215 * enable this so valgrind will give the line number in its error log */
1217 case 0: BKE_libblock_free_ex(mainvar, id, false, false); break;
1218 case 1: BKE_libblock_free_ex(mainvar, id, false, false); break;
1219 case 2: BKE_libblock_free_ex(mainvar, id, false, false); break;
1220 case 3: BKE_libblock_free_ex(mainvar, id, false, false); break;
1221 case 4: BKE_libblock_free_ex(mainvar, id, false, false); break;
1222 case 5: BKE_libblock_free_ex(mainvar, id, false, false); break;
1223 case 6: BKE_libblock_free_ex(mainvar, id, false, false); break;
1224 case 7: BKE_libblock_free_ex(mainvar, id, false, false); break;
1225 case 8: BKE_libblock_free_ex(mainvar, id, false, false); break;
1226 case 9: BKE_libblock_free_ex(mainvar, id, false, false); break;
1227 case 10: BKE_libblock_free_ex(mainvar, id, false, false); break;
1228 case 11: BKE_libblock_free_ex(mainvar, id, false, false); break;
1229 case 12: BKE_libblock_free_ex(mainvar, id, false, false); break;
1230 case 13: BKE_libblock_free_ex(mainvar, id, false, false); break;
1231 case 14: BKE_libblock_free_ex(mainvar, id, false, false); break;
1232 case 15: BKE_libblock_free_ex(mainvar, id, false, false); break;
1233 case 16: BKE_libblock_free_ex(mainvar, id, false, false); break;
1234 case 17: BKE_libblock_free_ex(mainvar, id, false, false); break;
1235 case 18: BKE_libblock_free_ex(mainvar, id, false, false); break;
1236 case 19: BKE_libblock_free_ex(mainvar, id, false, false); break;
1237 case 20: BKE_libblock_free_ex(mainvar, id, false, false); break;
1238 case 21: BKE_libblock_free_ex(mainvar, id, false, false); break;
1239 case 22: BKE_libblock_free_ex(mainvar, id, false, false); break;
1240 case 23: BKE_libblock_free_ex(mainvar, id, false, false); break;
1241 case 24: BKE_libblock_free_ex(mainvar, id, false, false); break;
1242 case 25: BKE_libblock_free_ex(mainvar, id, false, false); break;
1243 case 26: BKE_libblock_free_ex(mainvar, id, false, false); break;
1244 case 27: BKE_libblock_free_ex(mainvar, id, false, false); break;
1245 case 28: BKE_libblock_free_ex(mainvar, id, false, false); break;
1246 case 29: BKE_libblock_free_ex(mainvar, id, false, false); break;
1247 case 30: BKE_libblock_free_ex(mainvar, id, false, false); break;
1248 case 31: BKE_libblock_free_ex(mainvar, id, false, false); break;
1249 case 32: BKE_libblock_free_ex(mainvar, id, false, false); break;
1250 case 33: BKE_libblock_free_ex(mainvar, id, false, false); break;
1251 case 34: BKE_libblock_free_ex(mainvar, id, false, false); break;
1260 if (mainvar->relations) {
1261 BKE_main_relations_free(mainvar);
1264 BLI_spin_end((SpinLock *)mainvar->lock);
1265 MEM_freeN(mainvar->lock);
1266 DEG_evaluation_context_free(mainvar->eval_ctx);
1270 void BKE_main_lock(struct Main *bmain)
1272 BLI_spin_lock((SpinLock *) bmain->lock);
1275 void BKE_main_unlock(struct Main *bmain)
1277 BLI_spin_unlock((SpinLock *) bmain->lock);
1281 static int main_relations_create_cb(void *user_data, ID *id_self, ID **id_pointer, int cd_flag)
1283 MainIDRelations *rel = user_data;
1286 MainIDRelationsEntry *entry, **entry_p;
1288 entry = BLI_mempool_alloc(rel->entry_pool);
1289 if (BLI_ghash_ensure_p(rel->id_user_to_used, id_self, (void ***)&entry_p)) {
1290 entry->next = *entry_p;
1295 entry->id_pointer = id_pointer;
1296 entry->usage_flag = cd_flag;
1299 entry = BLI_mempool_alloc(rel->entry_pool);
1300 if (BLI_ghash_ensure_p(rel->id_used_to_user, *id_pointer, (void ***)&entry_p)) {
1301 entry->next = *entry_p;
1306 entry->id_pointer = (ID **)id_self;
1307 entry->usage_flag = cd_flag;
1311 return IDWALK_RET_NOP;
1314 /** Generate the mappings between used IDs and their users, and vice-versa. */
1315 void BKE_main_relations_create(Main *bmain)
1317 ListBase *lbarray[MAX_LIBARRAY];
1321 if (bmain->relations != NULL) {
1322 BKE_main_relations_free(bmain);
1325 bmain->relations = MEM_mallocN(sizeof(*bmain->relations), __func__);
1326 bmain->relations->id_used_to_user = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
1327 bmain->relations->id_user_to_used = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
1328 bmain->relations->entry_pool = BLI_mempool_create(sizeof(MainIDRelationsEntry), 128, 128, BLI_MEMPOOL_NOP);
1330 for (a = set_listbasepointers(bmain, lbarray); a--; ) {
1331 for (id = lbarray[a]->first; id; id = id->next) {
1332 BKE_library_foreach_ID_link(NULL, id, main_relations_create_cb, bmain->relations, IDWALK_READONLY);
1337 void BKE_main_relations_free(Main *bmain)
1339 if (bmain->relations) {
1340 if (bmain->relations->id_used_to_user) {
1341 BLI_ghash_free(bmain->relations->id_used_to_user, NULL, NULL);
1343 if (bmain->relations->id_user_to_used) {
1344 BLI_ghash_free(bmain->relations->id_user_to_used, NULL, NULL);
1346 BLI_mempool_destroy(bmain->relations->entry_pool);
1347 MEM_freeN(bmain->relations);
1348 bmain->relations = NULL;
1353 * Generates a raw .blend file thumbnail data from given image.
1355 * \param bmain If not NULL, also store generated data in this Main.
1356 * \param img ImBuf image to generate thumbnail data from.
1357 * \return The generated .blend file raw thumbnail data.
1359 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1361 BlendThumbnail *data = NULL;
1364 MEM_SAFE_FREE(bmain->blen_thumb);
1368 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1369 data = MEM_mallocN(sz, __func__);
1371 IMB_rect_from_float(img); /* Just in case... */
1372 data->width = img->x;
1373 data->height = img->y;
1374 memcpy(data->rect, img->rect, sz - sizeof(*data));
1378 bmain->blen_thumb = data;
1384 * Generates an image from raw .blend file thumbnail \a data.
1386 * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1387 * \param data Raw .blend file thumbnail data.
1388 * \return An ImBuf from given data, or NULL if invalid.
1390 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1394 if (!data && bmain) {
1395 data = bmain->blen_thumb;
1399 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1400 * here (we do not want to pass the first two ints!). */
1401 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1402 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1409 * Generates an empty (black) thumbnail for given Main.
1411 void BKE_main_thumbnail_create(struct Main *bmain)
1413 MEM_SAFE_FREE(bmain->blen_thumb);
1415 bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1416 bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1417 bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1420 /* ***************** ID ************************ */
1421 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1423 ListBase *lb = which_libbase(bmain, type);
1424 BLI_assert(lb != NULL);
1425 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1427 ID *BKE_libblock_find_name(const short type, const char *name)
1429 return BKE_libblock_find_name_ex(G.main, type, name);
1433 void id_sort_by_name(ListBase *lb, ID *id)
1437 /* insert alphabetically */
1438 if (lb->first != lb->last) {
1439 BLI_remlink(lb, id);
1443 if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1444 BLI_insertlinkbefore(lb, idtest, id);
1447 idtest = idtest->next;
1450 if (idtest == NULL) {
1451 BLI_addtail(lb, id);
1458 * Check to see if there is an ID with the same name as 'name'.
1459 * Returns the ID if so, if not, returns NULL
1461 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1465 for (idtest = lb->first; idtest; idtest = idtest->next) {
1466 /* if idtest is not a lib */
1467 if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
1468 /* do not test alphabetic! */
1470 if (idtest->name[2] == name[0]) {
1471 if (STREQ(name, idtest->name + 2)) break;
1480 * Check to see if an ID name is already used, and find a new one if so.
1481 * Return true if created a new name (returned in name).
1483 * Normally the ID that's being check is already in the ListBase, so ID *id
1484 * points at the new entry. The Python Library module needs to know what
1485 * the name of a datablock will be before it is appended; in this case ID *id
1489 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1494 #define MAX_IN_USE 64
1495 bool in_use[MAX_IN_USE];
1496 /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1498 char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1502 /* phase 1: id already exists? */
1503 idtest = is_dupid(lb, id, name);
1505 /* if there is no double, done */
1506 if (idtest == NULL) return false;
1508 /* we have a dup; need to make a new name */
1509 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1510 memset(in_use, false, sizeof(in_use));
1512 /* get name portion, number portion ("name.number") */
1513 left_len = BLI_split_name_num(left, &nr, name, '.');
1515 /* if new name will be too long, truncate it */
1516 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* assumption: won't go beyond 9999 */
1517 left[MAX_ID_NAME - 8] = '\0';
1518 left_len = MAX_ID_NAME - 8;
1520 else if (left_len > (MAX_ID_NAME - 7)) {
1521 left[MAX_ID_NAME - 7] = '\0';
1522 left_len = MAX_ID_NAME - 7;
1525 /* Code above may have generated invalid utf-8 string, due to raw truncation.
1526 * Ensure we get a valid one now! */
1527 left_len -= (size_t)BLI_utf8_invalid_strip(left, left_len);
1529 for (idtest = lb->first; idtest; idtest = idtest->next) {
1531 if ( (id != idtest) &&
1532 !ID_IS_LINKED_DATABLOCK(idtest) &&
1533 (*name == *(idtest->name + 2)) &&
1534 STREQLEN(name, idtest->name + 2, left_len) &&
1535 (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1538 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1539 if (nrtest < MAX_IN_USE)
1540 in_use[nrtest] = true; /* mark as used */
1542 nr = nrtest + 1; /* track largest unused */
1545 /* At this point, 'nr' will typically be at least 1. (but not always) */
1546 // BLI_assert(nr >= 1);
1548 /* decide which value of nr to use */
1549 for (a = 0; a < MAX_IN_USE; a++) {
1550 if (a >= nr) break; /* stop when we've checked up to biggest */ /* redundant check */
1551 if (!in_use[a]) { /* found an unused value */
1553 /* can only be zero if all potential duplicate names had
1554 * nonzero numeric suffixes, which means name itself has
1555 * nonzero numeric suffix (else no name conflict and wouldn't
1556 * have got here), which means name[left_len] is not a null */
1560 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1561 * or 1 greater than the largest used number if all those low ones are taken.
1562 * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1564 /* If the original name has no numeric suffix,
1565 * rather than just chopping and adding numbers,
1566 * shave off the end chars until we have a unique name.
1567 * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1568 if (nr == 0 && name[left_len] == '\0') {
1570 /* FIXME: this code will never be executed, because either nr will be
1571 * at least 1, or name will not end at left_len! */
1575 idtest = is_dupid(lb, id, name);
1577 while (idtest && len > 1) {
1579 idtest = is_dupid(lb, id, name);
1581 if (idtest == NULL) return true;
1582 /* otherwise just continue and use a number suffix */
1585 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1586 /* this would overflow name buffer */
1587 left[MAX_ID_NAME - 8] = 0;
1588 /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1589 memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1592 /* this format specifier is from hell... */
1593 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1602 * Only for local blocks: external en indirect blocks already have a
1605 * return true: created a new name
1608 bool new_id(ListBase *lb, ID *id, const char *tname)
1611 char name[MAX_ID_NAME - 2];
1613 /* if library, don't rename */
1614 if (ID_IS_LINKED_DATABLOCK(id))
1617 /* if no libdata given, look up based on ID */
1619 lb = which_libbase(G.main, GS(id->name));
1621 /* if no name given, use name of current ID
1622 * else make a copy (tname args can be const) */
1624 tname = id->name + 2;
1626 BLI_strncpy(name, tname, sizeof(name));
1628 if (name[0] == '\0') {
1629 /* disallow empty names */
1630 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1633 /* disallow non utf8 chars,
1634 * the interface checks for this but new ID's based on file names don't */
1635 BLI_utf8_invalid_strip(name, strlen(name));
1638 result = check_for_dupid(lb, id, name);
1639 strcpy(id->name + 2, name);
1641 /* This was in 2.43 and previous releases
1642 * however all data in blender should be sorted, not just duplicate names
1643 * sorting should not hurt, but noting just incase it alters the way other
1644 * functions work, so sort every time */
1647 id_sort_by_name(lb, id);
1650 id_sort_by_name(lb, id);
1656 * Pull an ID out of a library (make it local). Only call this for IDs that
1657 * don't have other library users.
1659 void id_clear_lib_data_ex(Main *bmain, ID *id, const bool id_in_mainlist)
1661 bNodeTree *ntree = NULL;
1664 BKE_id_lib_local_paths(bmain, id->lib, id);
1666 id_fake_user_clear(id);
1669 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1671 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1673 /* Internal bNodeTree blocks inside datablocks also stores id->lib, make sure this stays in sync. */
1674 if ((ntree = ntreeFromID(id))) {
1675 id_clear_lib_data_ex(bmain, &ntree->id, false); /* Datablocks' nodetree is never in Main. */
1678 /* Same goes for shapekeys. */
1679 if ((key = BKE_key_from_id(id))) {
1680 id_clear_lib_data_ex(bmain, &key->id, id_in_mainlist); /* sigh, why are keys in Main? */
1684 void id_clear_lib_data(Main *bmain, ID *id)
1686 id_clear_lib_data_ex(bmain, id, true);
1689 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1690 void BKE_main_id_clear_newpoins(Main *bmain)
1692 ListBase *lbarray[MAX_LIBARRAY];
1696 a = set_listbasepointers(bmain, lbarray);
1698 id = lbarray[a]->first;
1701 id->tag &= ~LIB_TAG_NEW;
1708 static void library_make_local_copying_check(ID *id, GSet *loop_tags, MainIDRelations *id_relations, GSet *done_ids)
1710 if (BLI_gset_haskey(done_ids, id)) {
1711 return; /* Already checked, nothing else to do. */
1714 MainIDRelationsEntry *entry = BLI_ghash_lookup(id_relations->id_used_to_user, id);
1715 BLI_gset_insert(loop_tags, id);
1716 for (; entry != NULL; entry = entry->next) {
1717 ID *par_id = (ID *)entry->id_pointer; /* used_to_user stores ID pointer, not pointer to ID pointer... */
1719 /* Shapekeys are considered 'private' to their owner ID here, and never tagged (since they cannot be linked),
1720 * so we have to switch effective parent to their owner. */
1721 if (GS(par_id->name) == ID_KE) {
1722 par_id = ((Key *)par_id)->from;
1725 if (par_id->lib == NULL) {
1726 /* Local user, early out to avoid some gset querying... */
1729 if (!BLI_gset_haskey(done_ids, par_id)) {
1730 if (BLI_gset_haskey(loop_tags, par_id)) {
1731 /* We are in a 'dependency loop' of IDs, this does not say us anything, skip it.
1732 * Note that this is the situation that can lead to archipelagoes of linked data-blocks
1733 * (since all of them have non-local users, they would all be duplicated, leading to a loop of unused
1734 * linked data-blocks that cannot be freed since they all use each other...). */
1737 /* Else, recursively check that user ID. */
1738 library_make_local_copying_check(par_id, loop_tags, id_relations, done_ids);
1741 if (par_id->tag & LIB_TAG_DOIT) {
1742 /* This user will be fully local in future, so far so good, nothing to do here but check next user. */
1745 /* This user won't be fully local in future, so current ID won't be either. And we are done checking it. */
1746 id->tag &= ~LIB_TAG_DOIT;
1750 BLI_gset_add(done_ids, id);
1751 BLI_gset_remove(loop_tags, id, NULL);
1754 /** Make linked datablocks local.
1756 * \param bmain Almost certainly G.main.
1757 * \param lib If not NULL, only make local datablocks from this library.
1758 * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1759 * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1761 /* Note: Old (2.77) version was simply making (tagging) datablocks as local, without actually making any check whether
1762 * they were also indirectly used or not...
1764 * Current version uses regular id_make_local callback, with advanced pre-processing step to detect all cases of
1765 * IDs currently indirectly used, but which will be used by local data only once this function is finished.
1766 * This allows to avoid any uneeded duplication of IDs, and hence all time lost afterwards to remove
1767 * orphaned linked data-blocks...
1769 void BKE_library_make_local(
1770 Main *bmain, const Library *lib, GHash *old_to_new_ids, const bool untagged_only, const bool set_fake)
1772 ListBase *lbarray[MAX_LIBARRAY];
1776 LinkNode *todo_ids = NULL;
1777 LinkNode *copied_ids = NULL;
1778 MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
1780 BKE_main_relations_create(bmain);
1782 GSet *done_ids = BLI_gset_ptr_new(__func__);
1784 /* Step 1: Detect datablocks to make local. */
1785 for (a = set_listbasepointers(bmain, lbarray); a--; ) {
1786 id = lbarray[a]->first;
1788 /* Do not explicitly make local non-linkable IDs (shapekeys, in fact), they are assumed to be handled
1789 * by real datablocks responsible of them. */
1790 const bool do_skip = (id && !BKE_idcode_is_linkable(GS(id->name)));
1792 for (; id; id = id->next) {
1793 ID *ntree = (ID *)ntreeFromID(id);
1795 id->tag &= ~LIB_TAG_DOIT;
1796 if (ntree != NULL) {
1797 ntree->tag &= ~LIB_TAG_DOIT;
1800 if (id->lib == NULL) {
1801 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1803 /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so its possible to tag data you don't want to
1804 * be made local, used for appending data, so any libdata already linked wont become local (very nasty
1805 * to discover all your links are lost after appending).
1806 * Also, never ever make proxified objects local, would not make any sense. */
1808 * - Shapekeys are never tagged here (since they are not linkable).
1809 * - Nodetrees used in materials etc. have to be tagged manually, since they do not exist in Main (!).
1810 * This is ok-ish on 'make local' side of things (since those are handled by their 'owner' IDs),
1811 * but complicates slightly the pre-processing of relations between IDs at step 2... */
1812 else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1813 ELEM(lib, NULL, id->lib) &&
1814 !(GS(id->name) == ID_OB && ((Object *)id)->proxy_from != NULL) &&
1815 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1817 BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem);
1818 id->tag |= LIB_TAG_DOIT;
1820 /* Tag those nasty non-ID nodetrees, but do not add them to todo list, making them local is handled
1821 * by 'owner' ID. This is needed for library_make_local_copying_check() to work OK at step 2. */
1822 if (ntree != NULL) {
1823 ntree->tag |= LIB_TAG_DOIT;
1827 /* Linked ID that we won't be making local (needed info for step 2, see below). */
1828 BLI_gset_add(done_ids, id);
1833 /* Step 2: Check which datablocks we can directly make local (because they are only used by already, or future,
1834 * local data), others will need to be duplicated. */
1835 GSet *loop_tags = BLI_gset_ptr_new(__func__);
1836 for (LinkNode *it = todo_ids; it; it = it->next) {
1837 library_make_local_copying_check(it->link, loop_tags, bmain->relations, done_ids);
1838 BLI_assert(BLI_gset_size(loop_tags) == 0);
1840 BLI_gset_free(loop_tags, NULL);
1841 BLI_gset_free(done_ids, NULL);
1843 /* Next step will most likely add new IDs, better to get rid of this mapping now. */
1844 BKE_main_relations_free(bmain);
1846 /* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
1847 * which involves more complex checks and might instead create a local copy of original linked ID. */
1848 for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
1852 if (id->tag & LIB_TAG_DOIT) {
1853 /* We know all users of this object are local or will be made fully local, even if currently there are
1854 * some indirect usages. So instead of making a copy that we'll likely get rid of later, directly make
1855 * that data block local. Saves a tremendous amount of time with complex scenes... */
1856 id_clear_lib_data_ex(bmain, id, true);
1857 BKE_id_expand_local(bmain, id);
1858 id->tag &= ~LIB_TAG_DOIT;
1861 /* In this specific case, we do want to make ID local even if it has no local usage yet... */
1862 if (GS(id->name) == ID_OB) {
1863 /* Special case for objects because we don't want proxy pointers to be
1864 * cleared yet. This will happen down the road in this function.
1866 BKE_object_make_local_ex(bmain, (Object*)id, true, false);
1869 id_make_local(bmain, id, false, true);
1873 /* Reuse already allocated LinkNode (transferring it from todo_ids to copied_ids). */
1874 BLI_linklist_prepend_nlink(&copied_ids, id, it);
1879 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1880 /* do not set fake user on objects, groups (instancing) */
1881 id_fake_user_set(id);
1886 /* At this point, we are done with directly made local IDs. Now we have to handle duplicated ones, since their
1887 * remaining linked original counterpart may not be needed anymore... */
1890 /* Step 4: We have to remap local usages of old (linked) ID to new (local) id in a separated loop,
1891 * as lbarray ordering is not enough to ensure us we did catch all dependencies
1892 * (e.g. if making local a parent object before its child...). See T48907. */
1893 /* TODO This is now the biggest step by far (in term of processing time). We may be able to gain here by
1894 * using again main->relations mapping, but... this implies BKE_libblock_remap & co to be able to update
1895 * main->relations on the fly. Have to think about it a bit more, and see whether new code is OK first, anyway. */
1896 for (LinkNode *it = copied_ids; it; it = it->next) {
1899 BLI_assert(id->newid != NULL);
1900 BLI_assert(id->lib != NULL);
1902 BKE_libblock_remap(bmain, id, id->newid, ID_REMAP_SKIP_INDIRECT_USAGE);
1903 if (old_to_new_ids) {
1904 BLI_ghash_insert(old_to_new_ids, id, id->newid);
1907 /* Special hack for groups... Thing is, since we can't instantiate them here, we need to ensure
1908 * they remain 'alive' (only instantiation is a real group 'user'... *sigh* See T49722. */
1909 if (GS(id->name) == ID_GR && (id->tag & LIB_TAG_INDIRECT) != 0) {
1910 id_us_ensure_real(id->newid);
1914 /* Note: Keeping both version of the code (old one being safer, since it still has checks against unused IDs)
1915 * for now, we can remove old one once it has been tested for some time in master... */
1917 /* Step 5: proxy 'remapping' hack. */
1918 for (LinkNode *it = copied_ids; it; it = it->next) {
1919 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
1920 * from another blend file into this one, even when that blend file contains proxified
1921 * armatures that have local references. Since the proxified object needs to be linked
1922 * (not local), this will only work when the "Localize all" checkbox is disabled.
1923 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
1924 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
1925 Object *ob = (Object *)id;
1926 Object *ob_new = (Object *)id->newid;
1927 bool is_local = false, is_lib = false;
1929 /* Proxies only work when the proxified object is linked-in from a library. */
1930 if (ob->proxy->id.lib == NULL) {
1931 printf("Warning, proxy object %s will loose its link to %s, because the "
1932 "proxified object is local.\n", id->newid->name, ob->proxy->id.name);
1936 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
1938 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
1939 * referred to from a library. Not checking for local use; if new local proxy
1940 * was not used locally would be a nasty bug! */
1941 if (is_local || is_lib) {
1942 printf("Warning, made-local proxy object %s will loose its link to %s, "
1943 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
1944 id->newid->name, ob->proxy->id.name, is_local, is_lib);
1947 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
1948 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
1949 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy_ex). */
1950 ob_new->proxy = ob->proxy;
1951 ob_new->proxy_group = ob->proxy_group;
1952 ob_new->proxy_from = ob->proxy_from;
1953 ob_new->proxy->proxy_from = ob_new;
1954 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
1959 LinkNode *linked_loop_candidates = NULL;
1961 /* Step 5: remove datablocks that have been copied to be localized and are no more used in the end...
1962 * Note that we may have to loop more than once here, to tackle dependencies between linked objects... */
1963 bool do_loop = true;
1966 for (LinkNode *it = copied_ids; it; it = it->next) {
1967 if ((id = it->link) == NULL) {
1971 bool is_local = false, is_lib = false;
1973 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
1975 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
1976 * from another blend file into this one, even when that blend file contains proxified
1977 * armatures that have local references. Since the proxified object needs to be linked
1978 * (not local), this will only work when the "Localize all" checkbox is disabled.
1979 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
1980 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
1981 Object *ob = (Object *)id;
1982 Object *ob_new = (Object *)id->newid;
1984 /* Proxies only work when the proxified object is linked-in from a library. */
1985 if (ob->proxy->id.lib == NULL) {
1986 printf("Warning, proxy object %s will loose its link to %s, because the "
1987 "proxified object is local.\n", id->newid->name, ob->proxy->id.name);
1989 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
1990 * referred to from a library. Not checking for local use; if new local proxy
1991 * was not used locally would be a nasty bug! */
1992 else if (is_local || is_lib) {
1993 printf("Warning, made-local proxy object %s will loose its link to %s, "
1994 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
1995 id->newid->name, ob->proxy->id.name, is_local, is_lib);
1998 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
1999 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
2000 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy_ex). */
2001 ob_new->proxy = ob->proxy;
2002 ob_new->proxy_group = ob->proxy_group;
2003 ob_new->proxy_from = ob->proxy_from;
2004 ob_new->proxy->proxy_from = ob_new;
2005 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
2010 if (!is_lib) { /* Not used at all, we can free it! */
2011 BLI_assert(!"Unused linked data copy remaining from MakeLibLocal process, should not happen anymore");
2012 printf("\t%s (from %s)\n", id->name, id->lib->id.name);
2013 BKE_libblock_free(bmain, id);
2017 /* Only used by linked data, potential candidate to ugly lib-only dependency cycles... */
2018 else if ((id->tag & LIB_TAG_DOIT) == 0) { /* Check TAG_DOIT to avoid adding same ID several times... */
2019 /* Note that we store the node, not directly ID pointer, that way if it->link is set to NULL
2020 * later we can skip it in lib-dependency cycles search later. */
2021 BLI_linklist_prepend_arena(&linked_loop_candidates, it, linklist_mem);
2022 id->tag |= LIB_TAG_DOIT;
2024 /* Grrrrrrr... those half-datablocks-stuff... grrrrrrrrrrr...
2025 * Here we have to also tag them as potential candidates, otherwise they would falsy report
2026 * ID they used as 'directly used' in sixth step. */
2027 ID *ntree = (ID *)ntreeFromID(id);
2028 if (ntree != NULL) {
2029 ntree->tag |= LIB_TAG_DOIT;
2036 /* Step 6: Try to find circle dependencies between indirectly-linked-only datablocks.
2037 * Those are fake 'usages' that prevent their deletion. See T49775 for nice ugly case. */
2038 BKE_library_unused_linked_data_set_tag(bmain, false);
2039 for (LinkNode *it = linked_loop_candidates; it; it = it->next) {
2040 if (it->link == NULL) {
2043 if ((id = ((LinkNode *)it->link)->link) == NULL) {
2048 /* Note: in theory here we are only handling datablocks forming exclusive linked dependency-cycles-based
2049 * archipelagos, so no need to check again after we have deleted one, as done in previous step. */
2050 if (id->tag & LIB_TAG_DOIT) {
2051 BLI_assert(!"Unused linked data copy remaining from MakeLibLocal process (archipelago case), should not happen anymore");
2052 /* Object's deletion rely on valid ob->data, but ob->data may have already been freed here...
2053 * Setting it to NULL may not be 100% correct, but should be safe and do the work. */
2054 if (GS(id->name) == ID_OB) {
2055 ((Object *)id)->data = NULL;
2058 /* Note: *in theory* IDs tagged here are fully *outside* of file scope, totally unused, so we can
2059 * directly wipe them out without caring about clearing their usages.
2060 * However, this is a highly-risky presumption, and nice crasher in case something goes wrong here.
2061 * So for 2.78a will keep the safe option, and switch to more efficient one in master later. */
2063 BKE_libblock_free_ex(bmain, id, false, true);
2065 BKE_libblock_unlink(bmain, id, false, false);
2066 BKE_libblock_free(bmain, id);
2068 ((LinkNode *)it->link)->link = NULL; /* Not strictly necessary, but safer (see T49903)... */
2074 BKE_main_id_clear_newpoins(bmain);
2075 BLI_memarena_free(linklist_mem);
2079 * Use after setting the ID's name
2080 * When name exists: call 'new_id'
2082 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
2088 lb = which_libbase(bmain, GS(name));
2089 if (lb == NULL) return;
2092 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
2094 if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
2095 id_sort_by_name(lb, idtest);
2100 * Sets the name of a block to name, suitably adjusted for uniqueness.
2102 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
2104 ListBase *lb = which_libbase(bmain, GS(id->name));
2105 new_id(lb, id, name);
2109 * Returns in name the name of the block, with a 3-character prefix prepended
2110 * indicating whether it comes from a library, has a fake user, or no users.
2112 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
2114 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
2115 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
2118 strcpy(name + 3, id->name + 2);
2121 void BKE_library_filepath_set(Library *lib, const char *filepath)
2123 /* in some cases this is used to update the absolute path from the
2125 if (lib->name != filepath) {
2126 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
2129 BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
2131 /* not essential but set filepath is an absolute copy of value which
2132 * is more useful if its kept in sync */
2133 if (BLI_path_is_rel(lib->filepath)) {
2134 /* note that the file may be unsaved, in this case, setting the
2135 * filepath on an indirectly linked path is not allowed from the
2136 * outliner, and its not really supported but allow from here for now
2137 * since making local could cause this to be directly linked - campbell
2139 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
2140 BLI_path_abs(lib->filepath, basepath);
2144 void BKE_id_tag_set_atomic(ID *id, int tag)
2146 atomic_fetch_and_or_uint32((uint32_t *)&id->tag, tag);
2149 void BKE_id_tag_clear_atomic(ID *id, int tag)
2151 atomic_fetch_and_and_uint32((uint32_t *)&id->tag, ~tag);