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)
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 /* calls the appropriate make_local method for the block, unless test. Returns true
255 * if the block can be made local. */
256 bool id_make_local(Main *UNUSED(bmain), ID *id, bool test)
258 if (id->tag & LIB_TAG_INDIRECT)
261 switch (GS(id->name)) {
263 return false; /* not implemented */
265 return false; /* can't be linked */
267 if (!test) BKE_object_make_local((Object *)id);
271 BKE_mesh_make_local((Mesh *)id);
272 BKE_key_make_local(((Mesh *)id)->key);
277 BKE_curve_make_local((Curve *)id);
278 BKE_key_make_local(((Curve *)id)->key);
282 if (!test) BKE_mball_make_local((MetaBall *)id);
285 if (!test) BKE_material_make_local((Material *)id);
288 if (!test) BKE_texture_make_local((Tex *)id);
291 if (!test) BKE_image_make_local((Image *)id);
295 BKE_lattice_make_local((Lattice *)id);
296 BKE_key_make_local(((Lattice *)id)->key);
300 if (!test) BKE_lamp_make_local((Lamp *)id);
303 if (!test) BKE_camera_make_local((Camera *)id);
306 if (!test) BKE_speaker_make_local((Speaker *)id);
309 return false; /* deprecated */
311 if (!test) BKE_key_make_local((Key *)id);
314 if (!test) BKE_world_make_local((World *)id);
317 return false; /* can't be linked */
319 return false; /* not implemented */
321 return false; /* not implemented */
323 return false; /* not implemented */
325 return false; /* not implemented */
327 if (!test) BKE_armature_make_local((bArmature *)id);
330 if (!test) BKE_action_make_local((bAction *)id);
333 if (!test) ntreeMakeLocal((bNodeTree *)id, true);
336 if (!test) BKE_brush_make_local((Brush *)id);
339 if (!test) BKE_particlesettings_make_local((ParticleSettings *)id);
342 return false; /* can't be linked */
344 return false; /* not implemented */
346 return false; /* not implemented */
353 * Invokes the appropriate copy method for the block and returns the result in
354 * newid, unless test. Returns true if the block can be copied.
356 bool id_copy(ID *id, ID **newid, bool test)
358 if (!test) *newid = NULL;
361 * - make shallow copy, only this ID block
362 * - id.us of the new ID is set to 1 */
363 switch (GS(id->name)) {
365 return false; /* can't be copied from here */
367 return false; /* can't be copied from here */
369 if (!test) *newid = (ID *)BKE_object_copy((Object *)id);
372 if (!test) *newid = (ID *)BKE_mesh_copy((Mesh *)id);
375 if (!test) *newid = (ID *)BKE_curve_copy((Curve *)id);
378 if (!test) *newid = (ID *)BKE_mball_copy((MetaBall *)id);
381 if (!test) *newid = (ID *)BKE_material_copy((Material *)id);
384 if (!test) *newid = (ID *)BKE_texture_copy((Tex *)id);
387 if (!test) *newid = (ID *)BKE_image_copy(G.main, (Image *)id);
390 if (!test) *newid = (ID *)BKE_lattice_copy((Lattice *)id);
393 if (!test) *newid = (ID *)BKE_lamp_copy((Lamp *)id);
396 if (!test) *newid = (ID *)BKE_speaker_copy((Speaker *)id);
399 if (!test) *newid = (ID *)BKE_camera_copy((Camera *)id);
402 return false; /* deprecated */
404 if (!test) *newid = (ID *)BKE_key_copy((Key *)id);
407 if (!test) *newid = (ID *)BKE_world_copy((World *)id);
410 return false; /* can't be copied from here */
412 return false; /* not implemented */
414 if (!test) *newid = (ID *)BKE_text_copy(G.main, (Text *)id);
417 return false; /* not implemented */
419 if (!test) *newid = (ID *)BKE_group_copy((Group *)id);
422 if (!test) *newid = (ID *)BKE_armature_copy((bArmature *)id);
425 if (!test) *newid = (ID *)BKE_action_copy((bAction *)id);
428 if (!test) *newid = (ID *)ntreeCopyTree((bNodeTree *)id);
431 if (!test) *newid = (ID *)BKE_brush_copy((Brush *)id);
434 if (!test) *newid = (ID *)BKE_particlesettings_copy((ParticleSettings *)id);
437 return false; /* can't be copied from here */
439 if (!test) *newid = (ID *)gpencil_data_duplicate((bGPdata *)id, false);
442 if (!test) *newid = (ID *)BKE_mask_copy((Mask *)id);
445 if (!test) *newid = (ID *)BKE_linestyle_copy(G.main, (FreestyleLineStyle *)id);
452 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
458 /* if property isn't editable, we're going to have an extra block hanging around until we save */
459 if (RNA_property_editable(ptr, prop)) {
460 if (id_copy(id, &newid, false) && newid) {
461 /* copy animation actions too */
462 BKE_animdata_copy_id_action(id);
463 /* us is 1 by convention, but RNA_property_pointer_set
464 * will also increment it, so set it to zero */
468 RNA_id_pointer_create(newid, &idptr);
469 RNA_property_pointer_set(ptr, prop, idptr);
470 RNA_property_update(C, ptr, prop);
480 ListBase *which_libbase(Main *mainlib, short type)
484 return &(mainlib->scene);
486 return &(mainlib->library);
488 return &(mainlib->object);
490 return &(mainlib->mesh);
492 return &(mainlib->curve);
494 return &(mainlib->mball);
496 return &(mainlib->mat);
498 return &(mainlib->tex);
500 return &(mainlib->image);
502 return &(mainlib->latt);
504 return &(mainlib->lamp);
506 return &(mainlib->camera);
508 return &(mainlib->ipo);
510 return &(mainlib->key);
512 return &(mainlib->world);
514 return &(mainlib->screen);
516 return &(mainlib->vfont);
518 return &(mainlib->text);
520 return &(mainlib->speaker);
522 return &(mainlib->sound);
524 return &(mainlib->group);
526 return &(mainlib->armature);
528 return &(mainlib->action);
530 return &(mainlib->nodetree);
532 return &(mainlib->brush);
534 return &(mainlib->particle);
536 return &(mainlib->wm);
538 return &(mainlib->gpencil);
540 return &(mainlib->movieclip);
542 return &(mainlib->mask);
544 return &(mainlib->linestyle);
546 return &(mainlib->palettes);
548 return &(mainlib->paintcurves);
554 * Clear or set given tags for all ids in listbase (runtime tags).
556 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
560 for (id = lb->first; id; id = id->next) {
565 const int ntag = ~tag;
566 for (id = lb->first; id; id = id->next) {
573 * Clear or set given tags for all ids of given type in bmain (runtime tags).
575 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
577 ListBase *lb = which_libbase(mainvar, type);
579 BKE_main_id_tag_listbase(lb, tag, value);
583 * Clear or set given tags for all ids in bmain (runtime tags).
585 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
587 ListBase *lbarray[MAX_LIBARRAY];
590 a = set_listbasepointers(mainvar, lbarray);
592 BKE_main_id_tag_listbase(lbarray[a], tag, value);
598 * Clear or set given flags for all ids in listbase (persistent flags).
600 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
604 for (id = lb->first; id; id = id->next)
608 const int nflag = ~flag;
609 for (id = lb->first; id; id = id->next)
615 * Clear or set given flags for all ids in bmain (persistent flags).
617 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
619 ListBase *lbarray[MAX_LIBARRAY];
621 a = set_listbasepointers(bmain, lbarray);
623 BKE_main_id_flag_listbase(lbarray[a], flag, value);
627 void BKE_main_lib_objects_recalc_all(Main *bmain)
631 /* flag for full recalc */
632 for (ob = bmain->object.first; ob; ob = ob->id.next) {
633 if (ID_IS_LINKED_DATABLOCK(ob)) {
634 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
638 DAG_id_type_tag(bmain, ID_OB);
642 * puts into array *lb pointers to all the ListBase structs in main,
643 * and returns the number of them as the function result. This is useful for
644 * generic traversal of all the blocks in a Main (by traversing all the
645 * lists in turn), without worrying about block types.
647 * \note MAX_LIBARRAY define should match this code */
648 int set_listbasepointers(Main *main, ListBase **lb)
652 /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
653 * This is important because freeing data decreases usercounts of other datablocks,
654 * if this data is its self freed it can crash. */
655 lb[a++] = &(main->library); /* Libraries may be accessed from pretty much any other ID... */
656 lb[a++] = &(main->ipo);
657 lb[a++] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
658 lb[a++] = &(main->key);
659 lb[a++] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
660 lb[a++] = &(main->nodetree);
661 lb[a++] = &(main->image);
662 lb[a++] = &(main->tex);
663 lb[a++] = &(main->mat);
664 lb[a++] = &(main->vfont);
666 /* Important!: When adding a new object type,
667 * the specific data should be inserted here
670 lb[a++] = &(main->armature);
672 lb[a++] = &(main->mesh);
673 lb[a++] = &(main->curve);
674 lb[a++] = &(main->mball);
676 lb[a++] = &(main->latt);
677 lb[a++] = &(main->lamp);
678 lb[a++] = &(main->camera);
680 lb[a++] = &(main->text);
681 lb[a++] = &(main->sound);
682 lb[a++] = &(main->group);
683 lb[a++] = &(main->palettes);
684 lb[a++] = &(main->paintcurves);
685 lb[a++] = &(main->brush);
686 lb[a++] = &(main->particle);
687 lb[a++] = &(main->speaker);
689 lb[a++] = &(main->world);
690 lb[a++] = &(main->movieclip);
691 lb[a++] = &(main->screen);
692 lb[a++] = &(main->object);
693 lb[a++] = &(main->linestyle); /* referenced by scenes */
694 lb[a++] = &(main->scene);
695 lb[a++] = &(main->wm);
696 lb[a++] = &(main->mask);
700 BLI_assert(a + 1 == MAX_LIBARRAY);
705 /* *********** ALLOC AND FREE *****************
707 * BKE_libblock_free(ListBase *lb, ID *id )
708 * provide a list-basis and datablock, but only ID is read
710 * void *BKE_libblock_alloc(ListBase *lb, type, name)
711 * inserts in list and returns a new ID
713 * **************************** */
716 * Allocates and returns memory of the right size for the specified block type,
717 * initialized to zero.
719 void *BKE_libblock_alloc_notest(short type)
725 id = MEM_callocN(sizeof(Scene), "scene");
728 id = MEM_callocN(sizeof(Library), "library");
731 id = MEM_callocN(sizeof(Object), "object");
734 id = MEM_callocN(sizeof(Mesh), "mesh");
737 id = MEM_callocN(sizeof(Curve), "curve");
740 id = MEM_callocN(sizeof(MetaBall), "mball");
743 id = MEM_callocN(sizeof(Material), "mat");
746 id = MEM_callocN(sizeof(Tex), "tex");
749 id = MEM_callocN(sizeof(Image), "image");
752 id = MEM_callocN(sizeof(Lattice), "latt");
755 id = MEM_callocN(sizeof(Lamp), "lamp");
758 id = MEM_callocN(sizeof(Camera), "camera");
761 id = MEM_callocN(sizeof(Ipo), "ipo");
764 id = MEM_callocN(sizeof(Key), "key");
767 id = MEM_callocN(sizeof(World), "world");
770 id = MEM_callocN(sizeof(bScreen), "screen");
773 id = MEM_callocN(sizeof(VFont), "vfont");
776 id = MEM_callocN(sizeof(Text), "text");
779 id = MEM_callocN(sizeof(Speaker), "speaker");
782 id = MEM_callocN(sizeof(bSound), "sound");
785 id = MEM_callocN(sizeof(Group), "group");
788 id = MEM_callocN(sizeof(bArmature), "armature");
791 id = MEM_callocN(sizeof(bAction), "action");
794 id = MEM_callocN(sizeof(bNodeTree), "nodetree");
797 id = MEM_callocN(sizeof(Brush), "brush");
800 id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
803 id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
806 id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
809 id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
812 id = MEM_callocN(sizeof(Mask), "Mask");
815 id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
818 id = MEM_callocN(sizeof(Palette), "Palette");
821 id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
828 * Allocates and returns a block of the specified type, with the specified name
829 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
830 * The user count is set to 1, all other content (apart from name and links) being
831 * initialized to zero.
833 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
836 ListBase *lb = which_libbase(bmain, type);
838 id = BKE_libblock_alloc_notest(type);
840 BKE_main_lock(bmain);
844 *( (short *)id->name) = type;
845 new_id(lb, id, name);
846 /* alphabetic insertion: is in new_id */
847 BKE_main_unlock(bmain);
849 DAG_id_type_tag(bmain, type);
854 * Initialize an ID of given type, such that it has valid 'empty' data.
855 * ID is assumed to be just calloc'ed.
857 void BKE_libblock_init_empty(ID *id)
859 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
860 switch (GS(id->name)) {
862 BKE_scene_init((Scene *)id);
869 Object *ob = (Object *)id;
875 BKE_mesh_init((Mesh *)id);
878 BKE_curve_init((Curve *)id);
881 BKE_mball_init((MetaBall *)id);
884 BKE_material_init((Material *)id);
887 BKE_texture_default((Tex *)id);
890 BKE_image_init((Image *)id);
893 BKE_lattice_init((Lattice *)id);
896 BKE_lamp_init((Lamp *)id);
899 BKE_speaker_init((Speaker *)id);
902 BKE_camera_init((Camera *)id);
905 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
909 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
910 * They are not linkable, though, so it should never reach here anyway. */
914 BKE_world_init((World *)id);
920 BKE_vfont_init((VFont *)id);
923 BKE_text_init((Text *)id);
926 /* Another fuzzy case, think NULLified content is OK here... */
938 ntreeInitDefault((bNodeTree *)id);
941 BKE_brush_init((Brush *)id);
950 /* We should never reach this. */
960 BKE_linestyle_init((FreestyleLineStyle *)id);
965 /* by spec, animdata is first item after ID */
966 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
967 static void id_copy_animdata(ID *id, const bool do_action)
969 AnimData *adt = BKE_animdata_from_id(id);
972 IdAdtTemplate *iat = (IdAdtTemplate *)id;
973 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
977 /* material nodes use this since they are not treated as libdata */
978 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
980 if (id_from->properties)
981 id->properties = IDP_CopyProperty(id_from->properties);
983 /* the duplicate should get a copy of the animdata */
984 id_copy_animdata(id, do_action);
987 /* used everywhere in blenkernel */
988 void *BKE_libblock_copy_ex(Main *bmain, ID *id)
993 idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
997 idn_len = MEM_allocN_len(idn);
998 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
999 const char *cp = (const char *)id;
1000 char *cpn = (char *)idn;
1002 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1006 idn->tag |= LIB_TAG_NEW;
1008 BKE_libblock_copy_data(idn, id, false);
1013 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1018 idn = BKE_libblock_alloc_notest(GS(id->name));
1019 assert(idn != NULL);
1021 BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1023 idn_len = MEM_allocN_len(idn);
1024 if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1025 const char *cp = (const char *)id;
1026 char *cpn = (char *)idn;
1028 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1032 idn->tag |= LIB_TAG_NEW;
1035 BKE_libblock_copy_data(idn, id, do_action);
1040 void *BKE_libblock_copy(ID *id)
1042 return BKE_libblock_copy_ex(G.main, id);
1045 static int id_relink_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cd_flag)
1047 ID *id = *id_pointer;
1049 /* See: NEW_ID macro */
1051 BKE_library_update_ID_link_user(id->newid, id, cd_flag);
1052 *id_pointer = id->newid;
1054 else if (id->tag & LIB_TAG_NEW) {
1055 id->tag &= ~LIB_TAG_NEW;
1056 BKE_libblock_relink(id);
1059 return IDWALK_RET_NOP;
1062 void BKE_libblock_relink(ID *id)
1064 if (ID_IS_LINKED_DATABLOCK(id))
1067 BKE_library_foreach_ID_link(id, id_relink_looper, NULL, 0);
1070 void BKE_library_free(Library *lib)
1072 if (lib->packedfile)
1073 freePackedFile(lib->packedfile);
1076 Main *BKE_main_new(void)
1078 Main *bmain = MEM_callocN(sizeof(Main), "new main");
1079 bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1080 bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1081 BLI_spin_init((SpinLock *)bmain->lock);
1085 void BKE_main_free(Main *mainvar)
1087 /* also call when reading a file, erase all, etc */
1088 ListBase *lbarray[MAX_LIBARRAY];
1091 MEM_SAFE_FREE(mainvar->blen_thumb);
1093 a = set_listbasepointers(mainvar, lbarray);
1095 ListBase *lb = lbarray[a];
1098 while ( (id = lb->first) ) {
1100 BKE_libblock_free_ex(mainvar, id, false);
1102 /* errors freeing ID's can be hard to track down,
1103 * enable this so valgrind will give the line number in its error log */
1105 case 0: BKE_libblock_free_ex(mainvar, id, false); break;
1106 case 1: BKE_libblock_free_ex(mainvar, id, false); break;
1107 case 2: BKE_libblock_free_ex(mainvar, id, false); break;
1108 case 3: BKE_libblock_free_ex(mainvar, id, false); break;
1109 case 4: BKE_libblock_free_ex(mainvar, id, false); break;
1110 case 5: BKE_libblock_free_ex(mainvar, id, false); break;
1111 case 6: BKE_libblock_free_ex(mainvar, id, false); break;
1112 case 7: BKE_libblock_free_ex(mainvar, id, false); break;
1113 case 8: BKE_libblock_free_ex(mainvar, id, false); break;
1114 case 9: BKE_libblock_free_ex(mainvar, id, false); break;
1115 case 10: BKE_libblock_free_ex(mainvar, id, false); break;
1116 case 11: BKE_libblock_free_ex(mainvar, id, false); break;
1117 case 12: BKE_libblock_free_ex(mainvar, id, false); break;
1118 case 13: BKE_libblock_free_ex(mainvar, id, false); break;
1119 case 14: BKE_libblock_free_ex(mainvar, id, false); break;
1120 case 15: BKE_libblock_free_ex(mainvar, id, false); break;
1121 case 16: BKE_libblock_free_ex(mainvar, id, false); break;
1122 case 17: BKE_libblock_free_ex(mainvar, id, false); break;
1123 case 18: BKE_libblock_free_ex(mainvar, id, false); break;
1124 case 19: BKE_libblock_free_ex(mainvar, id, false); break;
1125 case 20: BKE_libblock_free_ex(mainvar, id, false); break;
1126 case 21: BKE_libblock_free_ex(mainvar, id, false); break;
1127 case 22: BKE_libblock_free_ex(mainvar, id, false); break;
1128 case 23: BKE_libblock_free_ex(mainvar, id, false); break;
1129 case 24: BKE_libblock_free_ex(mainvar, id, false); break;
1130 case 25: BKE_libblock_free_ex(mainvar, id, false); break;
1131 case 26: BKE_libblock_free_ex(mainvar, id, false); break;
1132 case 27: BKE_libblock_free_ex(mainvar, id, false); break;
1133 case 28: BKE_libblock_free_ex(mainvar, id, false); break;
1134 case 29: BKE_libblock_free_ex(mainvar, id, false); break;
1135 case 30: BKE_libblock_free_ex(mainvar, id, false); break;
1136 case 31: BKE_libblock_free_ex(mainvar, id, false); break;
1137 case 32: BKE_libblock_free_ex(mainvar, id, false); break;
1138 case 33: BKE_libblock_free_ex(mainvar, id, false); break;
1147 BLI_spin_end((SpinLock *)mainvar->lock);
1148 MEM_freeN(mainvar->lock);
1149 DEG_evaluation_context_free(mainvar->eval_ctx);
1153 void BKE_main_lock(struct Main *bmain)
1155 BLI_spin_lock((SpinLock *) bmain->lock);
1158 void BKE_main_unlock(struct Main *bmain)
1160 BLI_spin_unlock((SpinLock *) bmain->lock);
1164 * Generates a raw .blend file thumbnail data from given image.
1166 * \param bmain If not NULL, also store generated data in this Main.
1167 * \param img ImBuf image to generate thumbnail data from.
1168 * \return The generated .blend file raw thumbnail data.
1170 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1172 BlendThumbnail *data = NULL;
1175 MEM_SAFE_FREE(bmain->blen_thumb);
1179 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1180 data = MEM_mallocN(sz, __func__);
1182 IMB_rect_from_float(img); /* Just in case... */
1183 data->width = img->x;
1184 data->height = img->y;
1185 memcpy(data->rect, img->rect, sz - sizeof(*data));
1189 bmain->blen_thumb = data;
1195 * Generates an image from raw .blend file thumbnail \a data.
1197 * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1198 * \param data Raw .blend file thumbnail data.
1199 * \return An ImBuf from given data, or NULL if invalid.
1201 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1205 if (!data && bmain) {
1206 data = bmain->blen_thumb;
1210 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1211 * here (we do not want to pass the first two ints!). */
1212 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1213 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1220 * Generates an empty (black) thumbnail for given Main.
1222 void BKE_main_thumbnail_create(struct Main *bmain)
1224 MEM_SAFE_FREE(bmain->blen_thumb);
1226 bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1227 bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1228 bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1231 /* ***************** ID ************************ */
1232 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1234 ListBase *lb = which_libbase(bmain, type);
1235 BLI_assert(lb != NULL);
1236 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1238 ID *BKE_libblock_find_name(const short type, const char *name)
1240 return BKE_libblock_find_name_ex(G.main, type, name);
1244 void id_sort_by_name(ListBase *lb, ID *id)
1248 /* insert alphabetically */
1249 if (lb->first != lb->last) {
1250 BLI_remlink(lb, id);
1254 if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1255 BLI_insertlinkbefore(lb, idtest, id);
1258 idtest = idtest->next;
1261 if (idtest == NULL) {
1262 BLI_addtail(lb, id);
1269 * Check to see if there is an ID with the same name as 'name'.
1270 * Returns the ID if so, if not, returns NULL
1272 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1276 for (idtest = lb->first; idtest; idtest = idtest->next) {
1277 /* if idtest is not a lib */
1278 if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
1279 /* do not test alphabetic! */
1281 if (idtest->name[2] == name[0]) {
1282 if (STREQ(name, idtest->name + 2)) break;
1291 * Check to see if an ID name is already used, and find a new one if so.
1292 * Return true if created a new name (returned in name).
1294 * Normally the ID that's being check is already in the ListBase, so ID *id
1295 * points at the new entry. The Python Library module needs to know what
1296 * the name of a datablock will be before it is appended; in this case ID *id
1300 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1303 int nr = 0, a, left_len;
1304 #define MAX_IN_USE 64
1305 bool in_use[MAX_IN_USE];
1306 /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1308 char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1312 /* phase 1: id already exists? */
1313 idtest = is_dupid(lb, id, name);
1315 /* if there is no double, done */
1316 if (idtest == NULL) return false;
1318 /* we have a dup; need to make a new name */
1319 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1320 memset(in_use, false, sizeof(in_use));
1322 /* get name portion, number portion ("name.number") */
1323 left_len = BLI_split_name_num(left, &nr, name, '.');
1325 /* if new name will be too long, truncate it */
1326 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* assumption: won't go beyond 9999 */
1327 left[MAX_ID_NAME - 8] = 0;
1328 left_len = MAX_ID_NAME - 8;
1330 else if (left_len > (MAX_ID_NAME - 7)) {
1331 left[MAX_ID_NAME - 7] = 0;
1332 left_len = MAX_ID_NAME - 7;
1335 for (idtest = lb->first; idtest; idtest = idtest->next) {
1337 if ( (id != idtest) &&
1338 !ID_IS_LINKED_DATABLOCK(idtest) &&
1339 (*name == *(idtest->name + 2)) &&
1340 STREQLEN(name, idtest->name + 2, left_len) &&
1341 (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1344 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1345 if (nrtest < MAX_IN_USE)
1346 in_use[nrtest] = true; /* mark as used */
1348 nr = nrtest + 1; /* track largest unused */
1351 /* At this point, 'nr' will typically be at least 1. (but not always) */
1352 // BLI_assert(nr >= 1);
1354 /* decide which value of nr to use */
1355 for (a = 0; a < MAX_IN_USE; a++) {
1356 if (a >= nr) break; /* stop when we've checked up to biggest */ /* redundant check */
1357 if (!in_use[a]) { /* found an unused value */
1359 /* can only be zero if all potential duplicate names had
1360 * nonzero numeric suffixes, which means name itself has
1361 * nonzero numeric suffix (else no name conflict and wouldn't
1362 * have got here), which means name[left_len] is not a null */
1366 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1367 * or 1 greater than the largest used number if all those low ones are taken.
1368 * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1370 /* If the original name has no numeric suffix,
1371 * rather than just chopping and adding numbers,
1372 * shave off the end chars until we have a unique name.
1373 * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1374 if (nr == 0 && name[left_len] == '\0') {
1376 /* FIXME: this code will never be executed, because either nr will be
1377 * at least 1, or name will not end at left_len! */
1381 idtest = is_dupid(lb, id, name);
1383 while (idtest && len > 1) {
1385 idtest = is_dupid(lb, id, name);
1387 if (idtest == NULL) return true;
1388 /* otherwise just continue and use a number suffix */
1391 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1392 /* this would overflow name buffer */
1393 left[MAX_ID_NAME - 8] = 0;
1394 /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1395 memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1398 /* this format specifier is from hell... */
1399 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1408 * Only for local blocks: external en indirect blocks already have a
1411 * return true: created a new name
1414 bool new_id(ListBase *lb, ID *id, const char *tname)
1417 char name[MAX_ID_NAME - 2];
1419 /* if library, don't rename */
1420 if (ID_IS_LINKED_DATABLOCK(id))
1423 /* if no libdata given, look up based on ID */
1425 lb = which_libbase(G.main, GS(id->name));
1427 /* if no name given, use name of current ID
1428 * else make a copy (tname args can be const) */
1430 tname = id->name + 2;
1432 BLI_strncpy(name, tname, sizeof(name));
1434 if (name[0] == '\0') {
1435 /* disallow empty names */
1436 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1439 /* disallow non utf8 chars,
1440 * the interface checks for this but new ID's based on file names don't */
1441 BLI_utf8_invalid_strip(name, strlen(name));
1444 result = check_for_dupid(lb, id, name);
1445 strcpy(id->name + 2, name);
1447 /* This was in 2.43 and previous releases
1448 * however all data in blender should be sorted, not just duplicate names
1449 * sorting should not hurt, but noting just incase it alters the way other
1450 * functions work, so sort every time */
1453 id_sort_by_name(lb, id);
1456 id_sort_by_name(lb, id);
1462 * Pull an ID out of a library (make it local). Only call this for IDs that
1463 * don't have other library users.
1465 void id_clear_lib_data_ex(Main *bmain, ID *id, bool id_in_mainlist)
1467 bNodeTree *ntree = NULL;
1469 BKE_id_lib_local_paths(bmain, id->lib, id);
1471 id_fake_user_clear(id);
1474 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1476 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1478 /* internal bNodeTree blocks inside ID types below
1479 * also stores id->lib, make sure this stays in sync.
1481 ntree = ntreeFromID(id);
1484 ntreeMakeLocal(ntree, false);
1487 if (GS(id->name) == ID_OB) {
1488 Object *object = (Object *)id;
1489 if (object->proxy_from != NULL) {
1490 object->proxy_from->proxy = NULL;
1491 object->proxy_from->proxy_group = NULL;
1493 object->proxy = object->proxy_from = object->proxy_group = NULL;
1497 void id_clear_lib_data(Main *bmain, ID *id)
1499 id_clear_lib_data_ex(bmain, id, true);
1502 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1503 void BKE_main_id_clear_newpoins(Main *bmain)
1505 ListBase *lbarray[MAX_LIBARRAY];
1509 a = set_listbasepointers(bmain, lbarray);
1511 id = lbarray[a]->first;
1514 id->tag &= ~LIB_TAG_NEW;
1520 static void lib_indirect_test_id(ID *id, const Library *lib)
1523 if (a && a->id.lib) { a->id.tag &= ~LIB_TAG_INDIRECT; a->id.tag |= LIB_TAG_EXTERN; } (void)0
1525 if (ID_IS_LINKED_DATABLOCK(id)) {
1526 /* datablocks that were indirectly related are now direct links
1527 * without this, appending data that has a link to other data will fail to write */
1528 if (lib && id->lib->parent == lib) {
1534 if (GS(id->name) == ID_OB) {
1535 Object *ob = (Object *)id;
1540 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
1541 /* XXX old animation system! -------------------------------------- */
1543 bActionStrip *strip;
1544 for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1545 LIBTAG(strip->object);
1550 /* XXX: new animation system needs something like this? */
1553 for (a = 0; a < ob->totcol; a++) {
1557 LIBTAG(ob->dup_group);
1567 /** Make linked datablocks local.
1569 * \param bmain Almost certainly G.main.
1570 * \param lib If not NULL, only make local datablocks from this library.
1571 * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1572 * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1574 void BKE_library_make_local(Main *bmain, const Library *lib, const bool untagged_only, const bool set_fake)
1576 ListBase *lbarray[MAX_LIBARRAY];
1580 a = set_listbasepointers(bmain, lbarray);
1582 id = lbarray[a]->first;
1586 idn = id->next; /* id is possibly being inserted again */
1588 /* The check on the second line (LIB_TAG_PRE_EXISTING) is done so its
1589 * possible to tag data you don't want to be made local, used for
1590 * appending data, so any libdata already linked wont become local
1591 * (very nasty to discover all your links are lost after appending)
1593 if (id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1594 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1596 if (lib == NULL || id->lib == lib) {
1598 /* for Make Local > All we should be calling id_make_local,
1599 * but doing that breaks append (see #36003 and #36006), we
1600 * we should make it work with all datablocks and id.us==0 */
1601 id_clear_lib_data(bmain, id); /* sets 'id->tag' */
1603 /* why sort alphabetically here but not in
1604 * id_clear_lib_data() ? - campbell */
1605 id_sort_by_name(lbarray[a], id);
1608 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1613 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1614 /* do not set fake user on objects, groups (instancing) */
1615 id_fake_user_set(id);
1624 a = set_listbasepointers(bmain, lbarray);
1626 for (id = lbarray[a]->first; id; id = id->next)
1627 lib_indirect_test_id(id, lib);
1632 * Use after setting the ID's name
1633 * When name exists: call 'new_id'
1635 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
1641 lb = which_libbase(bmain, GS(name));
1642 if (lb == NULL) return;
1645 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1647 if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
1648 id_sort_by_name(lb, idtest);
1653 * Sets the name of a block to name, suitably adjusted for uniqueness.
1655 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
1657 ListBase *lb = which_libbase(bmain, GS(id->name));
1658 new_id(lb, id, name);
1662 * Returns in name the name of the block, with a 3-character prefix prepended
1663 * indicating whether it comes from a library, has a fake user, or no users.
1665 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
1667 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1668 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1671 strcpy(name + 3, id->name + 2);
1674 void BKE_library_filepath_set(Library *lib, const char *filepath)
1676 /* in some cases this is used to update the absolute path from the
1678 if (lib->name != filepath) {
1679 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1682 BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1684 /* not essential but set filepath is an absolute copy of value which
1685 * is more useful if its kept in sync */
1686 if (BLI_path_is_rel(lib->filepath)) {
1687 /* note that the file may be unsaved, in this case, setting the
1688 * filepath on an indirectly linked path is not allowed from the
1689 * outliner, and its not really supported but allow from here for now
1690 * since making local could cause this to be directly linked - campbell
1692 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1693 BLI_path_abs(lib->filepath, basepath);