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_camera_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_gpencil_types.h"
51 #include "DNA_ipo_types.h"
52 #include "DNA_key_types.h"
53 #include "DNA_lamp_types.h"
54 #include "DNA_lattice_types.h"
55 #include "DNA_linestyle_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meta_types.h"
59 #include "DNA_movieclip_types.h"
60 #include "DNA_mask_types.h"
61 #include "DNA_node_types.h"
62 #include "DNA_object_types.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_screen_types.h"
65 #include "DNA_speaker_types.h"
66 #include "DNA_sound_types.h"
67 #include "DNA_text_types.h"
68 #include "DNA_vfont_types.h"
69 #include "DNA_windowmanager_types.h"
70 #include "DNA_world_types.h"
72 #include "BLI_blenlib.h"
73 #include "BLI_utildefines.h"
75 #include "BLI_threads.h"
76 #include "BLT_translation.h"
78 #include "BKE_action.h"
79 #include "BKE_animsys.h"
80 #include "BKE_armature.h"
81 #include "BKE_bpath.h"
82 #include "BKE_brush.h"
83 #include "BKE_camera.h"
84 #include "BKE_context.h"
85 #include "BKE_curve.h"
86 #include "BKE_depsgraph.h"
88 #include "BKE_global.h"
89 #include "BKE_group.h"
90 #include "BKE_gpencil.h"
91 #include "BKE_idcode.h"
92 #include "BKE_idprop.h"
93 #include "BKE_image.h"
96 #include "BKE_lattice.h"
97 #include "BKE_library.h"
98 #include "BKE_library_query.h"
99 #include "BKE_linestyle.h"
100 #include "BKE_mesh.h"
101 #include "BKE_material.h"
102 #include "BKE_main.h"
103 #include "BKE_mball.h"
104 #include "BKE_mask.h"
105 #include "BKE_node.h"
106 #include "BKE_object.h"
107 #include "BKE_particle.h"
108 #include "BKE_packedFile.h"
109 #include "BKE_speaker.h"
110 #include "BKE_scene.h"
111 #include "BKE_text.h"
112 #include "BKE_texture.h"
113 #include "BKE_world.h"
115 #include "DEG_depsgraph.h"
117 #include "RNA_access.h"
119 #include "IMB_imbuf.h"
120 #include "IMB_imbuf_types.h"
122 /* GS reads the memory pointed at in a specific ordering.
123 * only use this definition, makes little and big endian systems
124 * work fine, in conjunction with MAKE_ID */
126 /* ************* general ************************ */
129 /* this has to be called from each make_local_* func, we could call
130 * from id_make_local() but then the make local functions would not be self
132 * also note that the id _must_ have a library - campbell */
133 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
135 const char *bpath_user_data[2] = {bmain->name, lib->filepath};
137 BKE_bpath_traverse_id(bmain, id,
138 BKE_bpath_relocate_visitor,
139 BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
140 (void *)bpath_user_data);
143 void id_lib_extern(ID *id)
145 if (id && ID_IS_LINKED_DATABLOCK(id)) {
146 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
147 if (id->tag & LIB_TAG_INDIRECT) {
148 id->tag -= LIB_TAG_INDIRECT;
149 id->tag |= LIB_TAG_EXTERN;
154 /* ensure we have a real user */
155 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
156 * we always have a real user.
157 * However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
158 * to make this change... */
159 void id_us_ensure_real(ID *id)
162 const int limit = ID_FAKE_USERS(id);
163 id->tag |= LIB_TAG_EXTRAUSER;
164 if (id->us <= limit) {
165 if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
166 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
170 id->tag |= LIB_TAG_EXTRAUSER_SET;
175 void id_us_clear_real(ID *id)
177 if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
178 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
180 BLI_assert(id->us >= ID_FAKE_USERS(id));
182 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
187 * Same as \a id_us_plus, but does not handle lib indirect -> extern.
188 * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
190 void id_us_plus_no_lib(ID *id)
193 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
194 BLI_assert(id->us >= 1);
195 /* No need to increase count, just tag extra user as no more set.
196 * Avoids annoying & inconsistent +1 in user count. */
197 id->tag &= ~LIB_TAG_EXTRAUSER_SET;
200 BLI_assert(id->us >= 0);
207 void id_us_plus(ID *id)
210 id_us_plus_no_lib(id);
215 /* decrements the user count for *id. */
216 void id_us_min(ID *id)
219 const int limit = ID_FAKE_USERS(id);
221 if (id->us <= limit) {
222 printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
223 id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
231 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
232 /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
233 id_us_ensure_real(id);
238 void id_fake_user_set(ID *id)
240 if (id && !(id->flag & LIB_FAKEUSER)) {
241 id->flag |= LIB_FAKEUSER;
246 void id_fake_user_clear(ID *id)
248 if (id && (id->flag & LIB_FAKEUSER)) {
249 id->flag &= ~LIB_FAKEUSER;
254 static int id_expand_local_callback(
255 void *UNUSED(user_data), struct ID *UNUSED(id_self), struct ID **id_pointer, int UNUSED(cd_flag))
258 id_lib_extern(*id_pointer);
261 return IDWALK_RET_NOP;
265 * Expand ID usages of given id as 'extern' (and no more indirect) linked data. Used by ID copy/make_local functions.
267 void BKE_id_expand_local(ID *id)
269 BKE_library_foreach_ID_link(id, id_expand_local_callback, NULL, 0);
272 /* calls the appropriate make_local method for the block, unless test. Returns true
273 * if the block can be made local. */
274 bool id_make_local(Main *bmain, ID *id, const bool test, const bool force_local)
276 if (id->tag & LIB_TAG_INDIRECT)
279 switch (GS(id->name)) {
281 return false; /* not implemented */
283 return false; /* can't be linked */
285 if (!test) BKE_object_make_local(bmain, (Object *)id, force_local);
288 if (!test) BKE_mesh_make_local(bmain, (Mesh *)id, force_local);
291 if (!test) BKE_curve_make_local(bmain, (Curve *)id, force_local);
294 if (!test) BKE_mball_make_local(bmain, (MetaBall *)id, force_local);
297 if (!test) BKE_material_make_local(bmain, (Material *)id, force_local);
300 if (!test) BKE_texture_make_local(bmain, (Tex *)id, force_local);
303 if (!test) BKE_image_make_local(bmain, (Image *)id, force_local);
306 if (!test) BKE_lattice_make_local(bmain, (Lattice *)id, force_local);
309 if (!test) BKE_lamp_make_local(bmain, (Lamp *)id, force_local);
312 if (!test) BKE_camera_make_local(bmain, (Camera *)id, force_local);
315 if (!test) BKE_speaker_make_local(bmain, (Speaker *)id, force_local);
318 return false; /* deprecated */
320 return false; /* can't be linked */
322 if (!test) BKE_world_make_local(bmain, (World *)id, force_local);
325 return false; /* can't be linked */
327 return false; /* not implemented */
329 return false; /* not implemented */
331 return false; /* not implemented */
333 return false; /* not implemented */
335 if (!test) BKE_armature_make_local(bmain, (bArmature *)id, force_local);
338 if (!test) BKE_action_make_local(bmain, (bAction *)id, force_local);
341 if (!test) ntreeMakeLocal(bmain, (bNodeTree *)id, true, force_local);
344 if (!test) BKE_brush_make_local(bmain, (Brush *)id, force_local);
347 if (!test) BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, force_local);
350 return false; /* can't be linked */
352 return false; /* not implemented */
354 return false; /* not implemented */
361 * Invokes the appropriate copy method for the block and returns the result in
362 * newid, unless test. Returns true if the block can be copied.
364 bool id_copy(Main *bmain, ID *id, ID **newid, bool test)
371 * - make shallow copy, only this ID block
372 * - id.us of the new ID is set to 1 */
373 switch (GS(id->name)) {
375 return false; /* can't be copied from here */
377 return false; /* can't be copied from here */
379 if (!test) *newid = (ID *)BKE_object_copy(bmain, (Object *)id);
382 if (!test) *newid = (ID *)BKE_mesh_copy(bmain, (Mesh *)id);
385 if (!test) *newid = (ID *)BKE_curve_copy(bmain, (Curve *)id);
388 if (!test) *newid = (ID *)BKE_mball_copy(bmain, (MetaBall *)id);
391 if (!test) *newid = (ID *)BKE_material_copy(bmain, (Material *)id);
394 if (!test) *newid = (ID *)BKE_texture_copy(bmain, (Tex *)id);
397 if (!test) *newid = (ID *)BKE_image_copy(bmain, (Image *)id);
400 if (!test) *newid = (ID *)BKE_lattice_copy(bmain, (Lattice *)id);
403 if (!test) *newid = (ID *)BKE_lamp_copy(bmain, (Lamp *)id);
406 if (!test) *newid = (ID *)BKE_speaker_copy(bmain, (Speaker *)id);
409 if (!test) *newid = (ID *)BKE_camera_copy(bmain, (Camera *)id);
412 return false; /* deprecated */
414 if (!test) *newid = (ID *)BKE_key_copy(bmain, (Key *)id);
417 if (!test) *newid = (ID *)BKE_world_copy(bmain, (World *)id);
420 return false; /* can't be copied from here */
422 return false; /* not implemented */
424 if (!test) *newid = (ID *)BKE_text_copy(bmain, (Text *)id);
427 return false; /* not implemented */
429 if (!test) *newid = (ID *)BKE_group_copy(bmain, (Group *)id);
432 if (!test) *newid = (ID *)BKE_armature_copy(bmain, (bArmature *)id);
435 if (!test) *newid = (ID *)BKE_action_copy(bmain, (bAction *)id);
438 if (!test) *newid = (ID *)ntreeCopyTree(bmain, (bNodeTree *)id);
441 if (!test) *newid = (ID *)BKE_brush_copy(bmain, (Brush *)id);
444 if (!test) *newid = (ID *)BKE_particlesettings_copy(bmain, (ParticleSettings *)id);
447 return false; /* can't be copied from here */
449 if (!test) *newid = (ID *)gpencil_data_duplicate(bmain, (bGPdata *)id, false);
452 if (!test) *newid = (ID *)BKE_mask_copy(bmain, (Mask *)id);
455 if (!test) *newid = (ID *)BKE_linestyle_copy(bmain, (FreestyleLineStyle *)id);
462 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
468 /* if property isn't editable, we're going to have an extra block hanging around until we save */
469 if (RNA_property_editable(ptr, prop)) {
470 if (id_copy(CTX_data_main(C), id, &newid, false) && newid) {
471 /* copy animation actions too */
472 BKE_animdata_copy_id_action(id);
473 /* us is 1 by convention, but RNA_property_pointer_set
474 * will also increment it, so set it to zero */
478 RNA_id_pointer_create(newid, &idptr);
479 RNA_property_pointer_set(ptr, prop, idptr);
480 RNA_property_update(C, ptr, prop);
490 ListBase *which_libbase(Main *mainlib, short type)
494 return &(mainlib->scene);
496 return &(mainlib->library);
498 return &(mainlib->object);
500 return &(mainlib->mesh);
502 return &(mainlib->curve);
504 return &(mainlib->mball);
506 return &(mainlib->mat);
508 return &(mainlib->tex);
510 return &(mainlib->image);
512 return &(mainlib->latt);
514 return &(mainlib->lamp);
516 return &(mainlib->camera);
518 return &(mainlib->ipo);
520 return &(mainlib->key);
522 return &(mainlib->world);
524 return &(mainlib->screen);
526 return &(mainlib->vfont);
528 return &(mainlib->text);
530 return &(mainlib->speaker);
532 return &(mainlib->sound);
534 return &(mainlib->group);
536 return &(mainlib->armature);
538 return &(mainlib->action);
540 return &(mainlib->nodetree);
542 return &(mainlib->brush);
544 return &(mainlib->particle);
546 return &(mainlib->wm);
548 return &(mainlib->gpencil);
550 return &(mainlib->movieclip);
552 return &(mainlib->mask);
554 return &(mainlib->linestyle);
556 return &(mainlib->palettes);
558 return &(mainlib->paintcurves);
564 * Clear or set given tags for all ids in listbase (runtime tags).
566 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
570 for (id = lb->first; id; id = id->next) {
575 const int ntag = ~tag;
576 for (id = lb->first; id; id = id->next) {
583 * Clear or set given tags for all ids of given type in bmain (runtime tags).
585 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
587 ListBase *lb = which_libbase(mainvar, type);
589 BKE_main_id_tag_listbase(lb, tag, value);
593 * Clear or set given tags for all ids in bmain (runtime tags).
595 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
597 ListBase *lbarray[MAX_LIBARRAY];
600 a = set_listbasepointers(mainvar, lbarray);
602 BKE_main_id_tag_listbase(lbarray[a], tag, value);
608 * Clear or set given flags for all ids in listbase (persistent flags).
610 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
614 for (id = lb->first; id; id = id->next)
618 const int nflag = ~flag;
619 for (id = lb->first; id; id = id->next)
625 * Clear or set given flags for all ids in bmain (persistent flags).
627 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
629 ListBase *lbarray[MAX_LIBARRAY];
631 a = set_listbasepointers(bmain, lbarray);
633 BKE_main_id_flag_listbase(lbarray[a], flag, value);
637 void BKE_main_lib_objects_recalc_all(Main *bmain)
641 /* flag for full recalc */
642 for (ob = bmain->object.first; ob; ob = ob->id.next) {
643 if (ID_IS_LINKED_DATABLOCK(ob)) {
644 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
648 DAG_id_type_tag(bmain, ID_OB);
652 * puts into array *lb pointers to all the ListBase structs in main,
653 * and returns the number of them as the function result. This is useful for
654 * generic traversal of all the blocks in a Main (by traversing all the
655 * lists in turn), without worrying about block types.
657 * \note MAX_LIBARRAY define should match this code */
658 int set_listbasepointers(Main *main, ListBase **lb)
662 /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
663 * This is important because freeing data decreases usercounts of other datablocks,
664 * if this data is its self freed it can crash. */
665 lb[a++] = &(main->library); /* Libraries may be accessed from pretty much any other ID... */
666 lb[a++] = &(main->ipo);
667 lb[a++] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
668 lb[a++] = &(main->key);
669 lb[a++] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
670 lb[a++] = &(main->nodetree);
671 lb[a++] = &(main->image);
672 lb[a++] = &(main->tex);
673 lb[a++] = &(main->mat);
674 lb[a++] = &(main->vfont);
676 /* Important!: When adding a new object type,
677 * the specific data should be inserted here
680 lb[a++] = &(main->armature);
682 lb[a++] = &(main->mesh);
683 lb[a++] = &(main->curve);
684 lb[a++] = &(main->mball);
686 lb[a++] = &(main->latt);
687 lb[a++] = &(main->lamp);
688 lb[a++] = &(main->camera);
690 lb[a++] = &(main->text);
691 lb[a++] = &(main->sound);
692 lb[a++] = &(main->group);
693 lb[a++] = &(main->palettes);
694 lb[a++] = &(main->paintcurves);
695 lb[a++] = &(main->brush);
696 lb[a++] = &(main->particle);
697 lb[a++] = &(main->speaker);
699 lb[a++] = &(main->world);
700 lb[a++] = &(main->movieclip);
701 lb[a++] = &(main->screen);
702 lb[a++] = &(main->object);
703 lb[a++] = &(main->linestyle); /* referenced by scenes */
704 lb[a++] = &(main->scene);
705 lb[a++] = &(main->wm);
706 lb[a++] = &(main->mask);
710 BLI_assert(a + 1 == MAX_LIBARRAY);
715 /* *********** ALLOC AND FREE *****************
717 * BKE_libblock_free(ListBase *lb, ID *id )
718 * provide a list-basis and datablock, but only ID is read
720 * void *BKE_libblock_alloc(ListBase *lb, type, name)
721 * inserts in list and returns a new ID
723 * **************************** */
726 * Allocates and returns memory of the right size for the specified block type,
727 * initialized to zero.
729 void *BKE_libblock_alloc_notest(short type)
735 id = MEM_callocN(sizeof(Scene), "scene");
738 id = MEM_callocN(sizeof(Library), "library");
741 id = MEM_callocN(sizeof(Object), "object");
744 id = MEM_callocN(sizeof(Mesh), "mesh");
747 id = MEM_callocN(sizeof(Curve), "curve");
750 id = MEM_callocN(sizeof(MetaBall), "mball");
753 id = MEM_callocN(sizeof(Material), "mat");
756 id = MEM_callocN(sizeof(Tex), "tex");
759 id = MEM_callocN(sizeof(Image), "image");
762 id = MEM_callocN(sizeof(Lattice), "latt");
765 id = MEM_callocN(sizeof(Lamp), "lamp");
768 id = MEM_callocN(sizeof(Camera), "camera");
771 id = MEM_callocN(sizeof(Ipo), "ipo");
774 id = MEM_callocN(sizeof(Key), "key");
777 id = MEM_callocN(sizeof(World), "world");
780 id = MEM_callocN(sizeof(bScreen), "screen");
783 id = MEM_callocN(sizeof(VFont), "vfont");
786 id = MEM_callocN(sizeof(Text), "text");
789 id = MEM_callocN(sizeof(Speaker), "speaker");
792 id = MEM_callocN(sizeof(bSound), "sound");
795 id = MEM_callocN(sizeof(Group), "group");
798 id = MEM_callocN(sizeof(bArmature), "armature");
801 id = MEM_callocN(sizeof(bAction), "action");
804 id = MEM_callocN(sizeof(bNodeTree), "nodetree");
807 id = MEM_callocN(sizeof(Brush), "brush");
810 id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
813 id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
816 id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
819 id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
822 id = MEM_callocN(sizeof(Mask), "Mask");
825 id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
828 id = MEM_callocN(sizeof(Palette), "Palette");
831 id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
838 * Allocates and returns a block of the specified type, with the specified name
839 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
840 * The user count is set to 1, all other content (apart from name and links) being
841 * initialized to zero.
843 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
846 ListBase *lb = which_libbase(bmain, type);
848 id = BKE_libblock_alloc_notest(type);
850 BKE_main_lock(bmain);
854 *( (short *)id->name) = type;
855 new_id(lb, id, name);
856 /* alphabetic insertion: is in new_id */
857 BKE_main_unlock(bmain);
859 DAG_id_type_tag(bmain, type);
864 * Initialize an ID of given type, such that it has valid 'empty' data.
865 * ID is assumed to be just calloc'ed.
867 void BKE_libblock_init_empty(ID *id)
869 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
870 switch (GS(id->name)) {
872 BKE_scene_init((Scene *)id);
879 Object *ob = (Object *)id;
885 BKE_mesh_init((Mesh *)id);
888 BKE_curve_init((Curve *)id);
891 BKE_mball_init((MetaBall *)id);
894 BKE_material_init((Material *)id);
897 BKE_texture_default((Tex *)id);
900 BKE_image_init((Image *)id);
903 BKE_lattice_init((Lattice *)id);
906 BKE_lamp_init((Lamp *)id);
909 BKE_speaker_init((Speaker *)id);
912 BKE_camera_init((Camera *)id);
915 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
919 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
920 * They are not linkable, though, so it should never reach here anyway. */
924 BKE_world_init((World *)id);
930 BKE_vfont_init((VFont *)id);
933 BKE_text_init((Text *)id);
936 /* Another fuzzy case, think NULLified content is OK here... */
948 ntreeInitDefault((bNodeTree *)id);
951 BKE_brush_init((Brush *)id);
960 /* We should never reach this. */
970 BKE_linestyle_init((FreestyleLineStyle *)id);
975 /* by spec, animdata is first item after ID */
976 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
977 static void id_copy_animdata(ID *id, const bool do_action)
979 AnimData *adt = BKE_animdata_from_id(id);
982 IdAdtTemplate *iat = (IdAdtTemplate *)id;
983 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
987 /* material nodes use this since they are not treated as libdata */
988 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
990 if (id_from->properties)
991 id->properties = IDP_CopyProperty(id_from->properties);
993 /* the duplicate should get a copy of the animdata */
994 id_copy_animdata(id, do_action);
997 /* used everywhere in blenkernel */
998 void *BKE_libblock_copy(Main *bmain, ID *id)
1003 idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
1005 assert(idn != NULL);
1007 idn_len = MEM_allocN_len(idn);
1008 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1009 const char *cp = (const char *)id;
1010 char *cpn = (char *)idn;
1012 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1016 idn->tag |= LIB_TAG_NEW;
1018 BKE_libblock_copy_data(idn, id, false);
1023 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1028 idn = BKE_libblock_alloc_notest(GS(id->name));
1029 assert(idn != NULL);
1031 BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1033 idn_len = MEM_allocN_len(idn);
1034 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1035 const char *cp = (const char *)id;
1036 char *cpn = (char *)idn;
1038 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1042 idn->tag |= LIB_TAG_NEW;
1045 BKE_libblock_copy_data(idn, id, do_action);
1050 static int id_relink_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cd_flag)
1052 ID *id = *id_pointer;
1054 /* See: NEW_ID macro */
1056 BKE_library_update_ID_link_user(id->newid, id, cd_flag);
1057 *id_pointer = id->newid;
1059 else if (id->tag & LIB_TAG_NEW) {
1060 id->tag &= ~LIB_TAG_NEW;
1061 BKE_libblock_relink(id);
1064 return IDWALK_RET_NOP;
1067 void BKE_libblock_relink(ID *id)
1069 if (ID_IS_LINKED_DATABLOCK(id))
1072 BKE_library_foreach_ID_link(id, id_relink_looper, NULL, 0);
1075 void BKE_library_free(Library *lib)
1077 if (lib->packedfile)
1078 freePackedFile(lib->packedfile);
1081 Main *BKE_main_new(void)
1083 Main *bmain = MEM_callocN(sizeof(Main), "new main");
1084 bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1085 bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1086 BLI_spin_init((SpinLock *)bmain->lock);
1090 void BKE_main_free(Main *mainvar)
1092 /* also call when reading a file, erase all, etc */
1093 ListBase *lbarray[MAX_LIBARRAY];
1096 MEM_SAFE_FREE(mainvar->blen_thumb);
1098 a = set_listbasepointers(mainvar, lbarray);
1100 ListBase *lb = lbarray[a];
1103 while ( (id = lb->first) ) {
1105 BKE_libblock_free_ex(mainvar, id, false);
1107 /* errors freeing ID's can be hard to track down,
1108 * enable this so valgrind will give the line number in its error log */
1110 case 0: BKE_libblock_free_ex(mainvar, id, false); break;
1111 case 1: BKE_libblock_free_ex(mainvar, id, false); break;
1112 case 2: BKE_libblock_free_ex(mainvar, id, false); break;
1113 case 3: BKE_libblock_free_ex(mainvar, id, false); break;
1114 case 4: BKE_libblock_free_ex(mainvar, id, false); break;
1115 case 5: BKE_libblock_free_ex(mainvar, id, false); break;
1116 case 6: BKE_libblock_free_ex(mainvar, id, false); break;
1117 case 7: BKE_libblock_free_ex(mainvar, id, false); break;
1118 case 8: BKE_libblock_free_ex(mainvar, id, false); break;
1119 case 9: BKE_libblock_free_ex(mainvar, id, false); break;
1120 case 10: BKE_libblock_free_ex(mainvar, id, false); break;
1121 case 11: BKE_libblock_free_ex(mainvar, id, false); break;
1122 case 12: BKE_libblock_free_ex(mainvar, id, false); break;
1123 case 13: BKE_libblock_free_ex(mainvar, id, false); break;
1124 case 14: BKE_libblock_free_ex(mainvar, id, false); break;
1125 case 15: BKE_libblock_free_ex(mainvar, id, false); break;
1126 case 16: BKE_libblock_free_ex(mainvar, id, false); break;
1127 case 17: BKE_libblock_free_ex(mainvar, id, false); break;
1128 case 18: BKE_libblock_free_ex(mainvar, id, false); break;
1129 case 19: BKE_libblock_free_ex(mainvar, id, false); break;
1130 case 20: BKE_libblock_free_ex(mainvar, id, false); break;
1131 case 21: BKE_libblock_free_ex(mainvar, id, false); break;
1132 case 22: BKE_libblock_free_ex(mainvar, id, false); break;
1133 case 23: BKE_libblock_free_ex(mainvar, id, false); break;
1134 case 24: BKE_libblock_free_ex(mainvar, id, false); break;
1135 case 25: BKE_libblock_free_ex(mainvar, id, false); break;
1136 case 26: BKE_libblock_free_ex(mainvar, id, false); break;
1137 case 27: BKE_libblock_free_ex(mainvar, id, false); break;
1138 case 28: BKE_libblock_free_ex(mainvar, id, false); break;
1139 case 29: BKE_libblock_free_ex(mainvar, id, false); break;
1140 case 30: BKE_libblock_free_ex(mainvar, id, false); break;
1141 case 31: BKE_libblock_free_ex(mainvar, id, false); break;
1142 case 32: BKE_libblock_free_ex(mainvar, id, false); break;
1143 case 33: BKE_libblock_free_ex(mainvar, id, false); break;
1152 BLI_spin_end((SpinLock *)mainvar->lock);
1153 MEM_freeN(mainvar->lock);
1154 DEG_evaluation_context_free(mainvar->eval_ctx);
1158 void BKE_main_lock(struct Main *bmain)
1160 BLI_spin_lock((SpinLock *) bmain->lock);
1163 void BKE_main_unlock(struct Main *bmain)
1165 BLI_spin_unlock((SpinLock *) bmain->lock);
1169 * Generates a raw .blend file thumbnail data from given image.
1171 * \param bmain If not NULL, also store generated data in this Main.
1172 * \param img ImBuf image to generate thumbnail data from.
1173 * \return The generated .blend file raw thumbnail data.
1175 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1177 BlendThumbnail *data = NULL;
1180 MEM_SAFE_FREE(bmain->blen_thumb);
1184 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1185 data = MEM_mallocN(sz, __func__);
1187 IMB_rect_from_float(img); /* Just in case... */
1188 data->width = img->x;
1189 data->height = img->y;
1190 memcpy(data->rect, img->rect, sz - sizeof(*data));
1194 bmain->blen_thumb = data;
1200 * Generates an image from raw .blend file thumbnail \a data.
1202 * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1203 * \param data Raw .blend file thumbnail data.
1204 * \return An ImBuf from given data, or NULL if invalid.
1206 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1210 if (!data && bmain) {
1211 data = bmain->blen_thumb;
1215 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1216 * here (we do not want to pass the first two ints!). */
1217 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1218 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1225 * Generates an empty (black) thumbnail for given Main.
1227 void BKE_main_thumbnail_create(struct Main *bmain)
1229 MEM_SAFE_FREE(bmain->blen_thumb);
1231 bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1232 bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1233 bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1236 /* ***************** ID ************************ */
1237 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1239 ListBase *lb = which_libbase(bmain, type);
1240 BLI_assert(lb != NULL);
1241 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1243 ID *BKE_libblock_find_name(const short type, const char *name)
1245 return BKE_libblock_find_name_ex(G.main, type, name);
1249 void id_sort_by_name(ListBase *lb, ID *id)
1253 /* insert alphabetically */
1254 if (lb->first != lb->last) {
1255 BLI_remlink(lb, id);
1259 if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1260 BLI_insertlinkbefore(lb, idtest, id);
1263 idtest = idtest->next;
1266 if (idtest == NULL) {
1267 BLI_addtail(lb, id);
1274 * Check to see if there is an ID with the same name as 'name'.
1275 * Returns the ID if so, if not, returns NULL
1277 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1281 for (idtest = lb->first; idtest; idtest = idtest->next) {
1282 /* if idtest is not a lib */
1283 if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
1284 /* do not test alphabetic! */
1286 if (idtest->name[2] == name[0]) {
1287 if (STREQ(name, idtest->name + 2)) break;
1296 * Check to see if an ID name is already used, and find a new one if so.
1297 * Return true if created a new name (returned in name).
1299 * Normally the ID that's being check is already in the ListBase, so ID *id
1300 * points at the new entry. The Python Library module needs to know what
1301 * the name of a datablock will be before it is appended; in this case ID *id
1305 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1308 int nr = 0, a, left_len;
1309 #define MAX_IN_USE 64
1310 bool in_use[MAX_IN_USE];
1311 /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1313 char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1317 /* phase 1: id already exists? */
1318 idtest = is_dupid(lb, id, name);
1320 /* if there is no double, done */
1321 if (idtest == NULL) return false;
1323 /* we have a dup; need to make a new name */
1324 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1325 memset(in_use, false, sizeof(in_use));
1327 /* get name portion, number portion ("name.number") */
1328 left_len = BLI_split_name_num(left, &nr, name, '.');
1330 /* if new name will be too long, truncate it */
1331 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* assumption: won't go beyond 9999 */
1332 left[MAX_ID_NAME - 8] = 0;
1333 left_len = MAX_ID_NAME - 8;
1335 else if (left_len > (MAX_ID_NAME - 7)) {
1336 left[MAX_ID_NAME - 7] = 0;
1337 left_len = MAX_ID_NAME - 7;
1340 for (idtest = lb->first; idtest; idtest = idtest->next) {
1342 if ( (id != idtest) &&
1343 !ID_IS_LINKED_DATABLOCK(idtest) &&
1344 (*name == *(idtest->name + 2)) &&
1345 STREQLEN(name, idtest->name + 2, left_len) &&
1346 (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1349 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1350 if (nrtest < MAX_IN_USE)
1351 in_use[nrtest] = true; /* mark as used */
1353 nr = nrtest + 1; /* track largest unused */
1356 /* At this point, 'nr' will typically be at least 1. (but not always) */
1357 // BLI_assert(nr >= 1);
1359 /* decide which value of nr to use */
1360 for (a = 0; a < MAX_IN_USE; a++) {
1361 if (a >= nr) break; /* stop when we've checked up to biggest */ /* redundant check */
1362 if (!in_use[a]) { /* found an unused value */
1364 /* can only be zero if all potential duplicate names had
1365 * nonzero numeric suffixes, which means name itself has
1366 * nonzero numeric suffix (else no name conflict and wouldn't
1367 * have got here), which means name[left_len] is not a null */
1371 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1372 * or 1 greater than the largest used number if all those low ones are taken.
1373 * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1375 /* If the original name has no numeric suffix,
1376 * rather than just chopping and adding numbers,
1377 * shave off the end chars until we have a unique name.
1378 * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1379 if (nr == 0 && name[left_len] == '\0') {
1381 /* FIXME: this code will never be executed, because either nr will be
1382 * at least 1, or name will not end at left_len! */
1386 idtest = is_dupid(lb, id, name);
1388 while (idtest && len > 1) {
1390 idtest = is_dupid(lb, id, name);
1392 if (idtest == NULL) return true;
1393 /* otherwise just continue and use a number suffix */
1396 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1397 /* this would overflow name buffer */
1398 left[MAX_ID_NAME - 8] = 0;
1399 /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1400 memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1403 /* this format specifier is from hell... */
1404 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1413 * Only for local blocks: external en indirect blocks already have a
1416 * return true: created a new name
1419 bool new_id(ListBase *lb, ID *id, const char *tname)
1422 char name[MAX_ID_NAME - 2];
1424 /* if library, don't rename */
1425 if (ID_IS_LINKED_DATABLOCK(id))
1428 /* if no libdata given, look up based on ID */
1430 lb = which_libbase(G.main, GS(id->name));
1432 /* if no name given, use name of current ID
1433 * else make a copy (tname args can be const) */
1435 tname = id->name + 2;
1437 BLI_strncpy(name, tname, sizeof(name));
1439 if (name[0] == '\0') {
1440 /* disallow empty names */
1441 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1444 /* disallow non utf8 chars,
1445 * the interface checks for this but new ID's based on file names don't */
1446 BLI_utf8_invalid_strip(name, strlen(name));
1449 result = check_for_dupid(lb, id, name);
1450 strcpy(id->name + 2, name);
1452 /* This was in 2.43 and previous releases
1453 * however all data in blender should be sorted, not just duplicate names
1454 * sorting should not hurt, but noting just incase it alters the way other
1455 * functions work, so sort every time */
1458 id_sort_by_name(lb, id);
1461 id_sort_by_name(lb, id);
1467 * Pull an ID out of a library (make it local). Only call this for IDs that
1468 * don't have other library users.
1470 void id_clear_lib_data_ex(Main *bmain, ID *id, bool id_in_mainlist)
1472 bNodeTree *ntree = NULL;
1475 BKE_id_lib_local_paths(bmain, id->lib, id);
1477 id_fake_user_clear(id);
1480 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1482 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1484 /* Internal bNodeTree blocks inside datablocks also stores id->lib, make sure this stays in sync. */
1485 if ((ntree = ntreeFromID(id))) {
1486 id_clear_lib_data_ex(bmain, &ntree->id, id_in_mainlist);
1489 /* Same goes for shapekeys. */
1490 if ((key = BKE_key_from_id(id))) {
1491 id_clear_lib_data_ex(bmain, &key->id, id_in_mainlist);
1494 if (GS(id->name) == ID_OB) {
1495 Object *object = (Object *)id;
1496 if (object->proxy_from != NULL) {
1497 object->proxy_from->proxy = NULL;
1498 object->proxy_from->proxy_group = NULL;
1500 object->proxy = object->proxy_from = object->proxy_group = NULL;
1504 void id_clear_lib_data(Main *bmain, ID *id)
1506 id_clear_lib_data_ex(bmain, id, true);
1509 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1510 void BKE_main_id_clear_newpoins(Main *bmain)
1512 ListBase *lbarray[MAX_LIBARRAY];
1516 a = set_listbasepointers(bmain, lbarray);
1518 id = lbarray[a]->first;
1521 id->tag &= ~LIB_TAG_NEW;
1527 static void lib_indirect_test_id(ID *id, const Library *lib)
1530 if (a && a->id.lib) { a->id.tag &= ~LIB_TAG_INDIRECT; a->id.tag |= LIB_TAG_EXTERN; } (void)0
1532 if (ID_IS_LINKED_DATABLOCK(id)) {
1533 /* datablocks that were indirectly related are now direct links
1534 * without this, appending data that has a link to other data will fail to write */
1535 if (lib && id->lib->parent == lib) {
1541 if (GS(id->name) == ID_OB) {
1542 Object *ob = (Object *)id;
1547 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
1548 /* XXX old animation system! -------------------------------------- */
1550 bActionStrip *strip;
1551 for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1552 LIBTAG(strip->object);
1557 /* XXX: new animation system needs something like this? */
1560 for (a = 0; a < ob->totcol; a++) {
1564 LIBTAG(ob->dup_group);
1574 /** Make linked datablocks local.
1576 * \param bmain Almost certainly G.main.
1577 * \param lib If not NULL, only make local datablocks from this library.
1578 * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1579 * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1581 void BKE_library_make_local(Main *bmain, const Library *lib, const bool untagged_only, const bool set_fake)
1583 ListBase *lbarray[MAX_LIBARRAY];
1587 a = set_listbasepointers(bmain, lbarray);
1589 id = lbarray[a]->first;
1593 idn = id->next; /* id is possibly being inserted again */
1595 /* The check on the second line (LIB_TAG_PRE_EXISTING) is done so its
1596 * possible to tag data you don't want to be made local, used for
1597 * appending data, so any libdata already linked wont become local
1598 * (very nasty to discover all your links are lost after appending)
1600 if (id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1601 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1603 if (lib == NULL || id->lib == lib) {
1605 /* for Make Local > All we should be calling id_make_local,
1606 * but doing that breaks append (see #36003 and #36006), we
1607 * we should make it work with all datablocks and id.us==0 */
1608 id_clear_lib_data(bmain, id); /* sets 'id->tag' */
1610 /* why sort alphabetically here but not in
1611 * id_clear_lib_data() ? - campbell */
1612 id_sort_by_name(lbarray[a], id);
1615 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1620 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1621 /* do not set fake user on objects, groups (instancing) */
1622 id_fake_user_set(id);
1631 a = set_listbasepointers(bmain, lbarray);
1633 for (id = lbarray[a]->first; id; id = id->next)
1634 lib_indirect_test_id(id, lib);
1639 * Use after setting the ID's name
1640 * When name exists: call 'new_id'
1642 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
1648 lb = which_libbase(bmain, GS(name));
1649 if (lb == NULL) return;
1652 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1654 if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
1655 id_sort_by_name(lb, idtest);
1660 * Sets the name of a block to name, suitably adjusted for uniqueness.
1662 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
1664 ListBase *lb = which_libbase(bmain, GS(id->name));
1665 new_id(lb, id, name);
1669 * Returns in name the name of the block, with a 3-character prefix prepended
1670 * indicating whether it comes from a library, has a fake user, or no users.
1672 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
1674 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1675 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1678 strcpy(name + 3, id->name + 2);
1681 void BKE_library_filepath_set(Library *lib, const char *filepath)
1683 /* in some cases this is used to update the absolute path from the
1685 if (lib->name != filepath) {
1686 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1689 BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1691 /* not essential but set filepath is an absolute copy of value which
1692 * is more useful if its kept in sync */
1693 if (BLI_path_is_rel(lib->filepath)) {
1694 /* note that the file may be unsaved, in this case, setting the
1695 * filepath on an indirectly linked path is not allowed from the
1696 * outliner, and its not really supported but allow from here for now
1697 * since making local could cause this to be directly linked - campbell
1699 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1700 BLI_path_abs(lib->filepath, basepath);