1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup bke
22  *
23  * Contains management of ID's and libraries
24  * allocate and free of all library data
25  */
26 
27 #include <ctype.h>
28 #include <stddef.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 
33 #include "CLG_log.h"
34 
35 #include "MEM_guardedalloc.h"
36 
37 /* all types are needed here, in order to do memory operations */
38 #include "DNA_ID.h"
39 #include "DNA_anim_types.h"
40 #include "DNA_gpencil_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_node_types.h"
43 #include "DNA_workspace_types.h"
44 
45 #include "BLI_utildefines.h"
46 
47 #include "BLI_alloca.h"
48 #include "BLI_blenlib.h"
49 #include "BLI_ghash.h"
50 #include "BLI_linklist.h"
51 #include "BLI_memarena.h"
52 #include "BLI_string_utils.h"
53 
54 #include "BLT_translation.h"
55 
56 #include "BKE_anim_data.h"
57 #include "BKE_armature.h"
58 #include "BKE_bpath.h"
59 #include "BKE_context.h"
60 #include "BKE_global.h"
61 #include "BKE_gpencil.h"
62 #include "BKE_idprop.h"
63 #include "BKE_idtype.h"
64 #include "BKE_key.h"
65 #include "BKE_lib_id.h"
66 #include "BKE_lib_override.h"
67 #include "BKE_lib_query.h"
68 #include "BKE_lib_remap.h"
69 #include "BKE_main.h"
70 #include "BKE_node.h"
71 #include "BKE_rigidbody.h"
72 
73 #include "DEG_depsgraph.h"
74 
75 #include "RNA_access.h"
76 
77 #include "BLO_read_write.h"
78 
79 #include "atomic_ops.h"
80 
81 //#define DEBUG_TIME
82 
83 #ifdef DEBUG_TIME
84 #  include "PIL_time_utildefines.h"
85 #endif
86 
87 static CLG_LogRef LOG = {.identifier = "bke.lib_id"};
88 
89 /* Empty shell mostly, but needed for read code. */
90 IDTypeInfo IDType_ID_LINK_PLACEHOLDER = {
91     .id_code = ID_LINK_PLACEHOLDER,
92     .id_filter = 0,
93     .main_listbase_index = INDEX_ID_NULL,
94     .struct_size = sizeof(ID),
95     .name = "LinkPlaceholder",
96     .name_plural = "link_placeholders",
97     .translation_context = BLT_I18NCONTEXT_ID_ID,
98     .flags = IDTYPE_FLAGS_NO_COPY | IDTYPE_FLAGS_NO_LIBLINKING | IDTYPE_FLAGS_NO_MAKELOCAL,
99 
100     .init_data = NULL,
101     .copy_data = NULL,
102     .free_data = NULL,
103     .make_local = NULL,
104 };
105 
106 /* GS reads the memory pointed at in a specific ordering.
107  * only use this definition, makes little and big endian systems
108  * work fine, in conjunction with MAKE_ID */
109 
110 /* ************* general ************************ */
111 
112 /**
113  * This has to be called from each make_local_* func, we could call from BKE_lib_id_make_local()
114  * but then the make local functions would not be self contained.
115  * Also note that the id _must_ have a library - campbell */
lib_id_library_local_paths(Main * bmain,Library * lib,ID * id)116 static void lib_id_library_local_paths(Main *bmain, Library *lib, ID *id)
117 {
118   const char *bpath_user_data[2] = {BKE_main_blendfile_path(bmain), lib->filepath_abs};
119 
120   BKE_bpath_traverse_id(bmain,
121                         id,
122                         BKE_bpath_relocate_visitor,
123                         BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
124                         (void *)bpath_user_data);
125 }
126 
lib_id_clear_library_data_users_update_cb(LibraryIDLinkCallbackData * cb_data)127 static int lib_id_clear_library_data_users_update_cb(LibraryIDLinkCallbackData *cb_data)
128 {
129   ID *id = cb_data->user_data;
130   if (*cb_data->id_pointer == id) {
131     DEG_id_tag_update_ex(cb_data->bmain, cb_data->id_owner, ID_RECALC_TAG_FOR_UNDO);
132     return IDWALK_RET_STOP_ITER;
133   }
134   return IDWALK_RET_NOP;
135 }
136 
137 /**
138  * Pull an ID out of a library (make it local). Only call this for IDs that
139  * don't have other library users.
140  */
lib_id_clear_library_data_ex(Main * bmain,ID * id)141 static void lib_id_clear_library_data_ex(Main *bmain, ID *id)
142 {
143   const bool id_in_mainlist = (id->tag & LIB_TAG_NO_MAIN) == 0 &&
144                               (id->flag & LIB_EMBEDDED_DATA) == 0;
145 
146   lib_id_library_local_paths(bmain, id->lib, id);
147 
148   id_fake_user_clear(id);
149 
150   id->lib = NULL;
151   id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
152   id->flag &= ~LIB_INDIRECT_WEAK_LINK;
153   if (id_in_mainlist) {
154     if (BKE_id_new_name_validate(which_libbase(bmain, GS(id->name)), id, NULL)) {
155       bmain->is_memfile_undo_written = false;
156     }
157   }
158 
159   /* Conceptually, an ID made local is not the same as the linked one anymore. Reflect that by
160    * regenerating its session UUID. */
161   BKE_lib_libblock_session_uuid_renew(id);
162 
163   /* We need to tag this IDs and all of its users, conceptually new local ID and original linked
164    * ones are two completely different data-blocks that were virtually remapped, even though in
165    * reality they remain the same data. For undo this info is critical now. */
166   DEG_id_tag_update_ex(bmain, id, ID_RECALC_COPY_ON_WRITE);
167   ID *id_iter;
168   FOREACH_MAIN_ID_BEGIN (bmain, id_iter) {
169     BKE_library_foreach_ID_link(
170         bmain, id_iter, lib_id_clear_library_data_users_update_cb, id, IDWALK_READONLY);
171   }
172   FOREACH_MAIN_ID_END;
173 
174   /* Internal shape key blocks inside data-blocks also stores id->lib,
175    * make sure this stays in sync (note that we do not need any explicit handling for real EMBEDDED
176    * IDs here, this is down automatically in `lib_id_expand_local_cb()`. */
177   Key *key = BKE_key_from_id(id);
178   if (key != NULL) {
179     lib_id_clear_library_data_ex(bmain, &key->id);
180   }
181 }
182 
BKE_lib_id_clear_library_data(Main * bmain,ID * id)183 void BKE_lib_id_clear_library_data(Main *bmain, ID *id)
184 {
185   lib_id_clear_library_data_ex(bmain, id);
186 }
187 
id_lib_extern(ID * id)188 void id_lib_extern(ID *id)
189 {
190   if (id && ID_IS_LINKED(id)) {
191     BLI_assert(BKE_idtype_idcode_is_linkable(GS(id->name)));
192     if (id->tag & LIB_TAG_INDIRECT) {
193       id->tag &= ~LIB_TAG_INDIRECT;
194       id->flag &= ~LIB_INDIRECT_WEAK_LINK;
195       id->tag |= LIB_TAG_EXTERN;
196       id->lib->parent = NULL;
197     }
198   }
199 }
200 
id_lib_indirect_weak_link(ID * id)201 void id_lib_indirect_weak_link(ID *id)
202 {
203   if (id && ID_IS_LINKED(id)) {
204     BLI_assert(BKE_idtype_idcode_is_linkable(GS(id->name)));
205     if (id->tag & LIB_TAG_INDIRECT) {
206       id->flag |= LIB_INDIRECT_WEAK_LINK;
207     }
208   }
209 }
210 
211 /**
212  * Ensure we have a real user
213  *
214  * \note Now that we have flags, we could get rid of the 'fake_user' special case,
215  * flags are enough to ensure we always have a real user.
216  * However, #ID_REAL_USERS is used in several places outside of core lib.c,
217  * so think we can wait later to make this change.
218  */
id_us_ensure_real(ID * id)219 void id_us_ensure_real(ID *id)
220 {
221   if (id) {
222     const int limit = ID_FAKE_USERS(id);
223     id->tag |= LIB_TAG_EXTRAUSER;
224     if (id->us <= limit) {
225       if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
226         CLOG_ERROR(&LOG,
227                    "ID user count error: %s (from '%s')",
228                    id->name,
229                    id->lib ? id->lib->filepath_abs : "[Main]");
230         BLI_assert(0);
231       }
232       id->us = limit + 1;
233       id->tag |= LIB_TAG_EXTRAUSER_SET;
234     }
235   }
236 }
237 
id_us_clear_real(ID * id)238 void id_us_clear_real(ID *id)
239 {
240   if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
241     if (id->tag & LIB_TAG_EXTRAUSER_SET) {
242       id->us--;
243       BLI_assert(id->us >= ID_FAKE_USERS(id));
244     }
245     id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
246   }
247 }
248 
249 /**
250  * Same as \a id_us_plus, but does not handle lib indirect -> extern.
251  * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
252  */
id_us_plus_no_lib(ID * id)253 void id_us_plus_no_lib(ID *id)
254 {
255   if (id) {
256     if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
257       BLI_assert(id->us >= 1);
258       /* No need to increase count, just tag extra user as no more set.
259        * Avoids annoying & inconsistent +1 in user count. */
260       id->tag &= ~LIB_TAG_EXTRAUSER_SET;
261     }
262     else {
263       BLI_assert(id->us >= 0);
264       id->us++;
265     }
266   }
267 }
268 
id_us_plus(ID * id)269 void id_us_plus(ID *id)
270 {
271   if (id) {
272     id_us_plus_no_lib(id);
273     id_lib_extern(id);
274   }
275 }
276 
277 /* decrements the user count for *id. */
id_us_min(ID * id)278 void id_us_min(ID *id)
279 {
280   if (id) {
281     const int limit = ID_FAKE_USERS(id);
282 
283     if (id->us <= limit) {
284       if (GS(id->name) != ID_IP) {
285         /* Do not assert on deprecated ID types, we cannot really ensure that their ID refcounting
286          * is valid... */
287         CLOG_ERROR(&LOG,
288                    "ID user decrement error: %s (from '%s'): %d <= %d",
289                    id->name,
290                    id->lib ? id->lib->filepath_abs : "[Main]",
291                    id->us,
292                    limit);
293         BLI_assert(0);
294       }
295       id->us = limit;
296     }
297     else {
298       id->us--;
299     }
300 
301     if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
302       /* We need an extra user here, but never actually incremented user count for it so far,
303        * do it now. */
304       id_us_ensure_real(id);
305     }
306   }
307 }
308 
id_fake_user_set(ID * id)309 void id_fake_user_set(ID *id)
310 {
311   if (id && !(id->flag & LIB_FAKEUSER)) {
312     id->flag |= LIB_FAKEUSER;
313     id_us_plus(id);
314   }
315 }
316 
id_fake_user_clear(ID * id)317 void id_fake_user_clear(ID *id)
318 {
319   if (id && (id->flag & LIB_FAKEUSER)) {
320     id->flag &= ~LIB_FAKEUSER;
321     id_us_min(id);
322   }
323 }
324 
BKE_id_clear_newpoin(ID * id)325 void BKE_id_clear_newpoin(ID *id)
326 {
327   if (id->newid) {
328     id->newid->tag &= ~LIB_TAG_NEW;
329   }
330   id->newid = NULL;
331 }
332 
lib_id_expand_local_cb(LibraryIDLinkCallbackData * cb_data)333 static int lib_id_expand_local_cb(LibraryIDLinkCallbackData *cb_data)
334 {
335   Main *bmain = cb_data->bmain;
336   ID *id_self = cb_data->id_self;
337   ID **id_pointer = cb_data->id_pointer;
338   int const cb_flag = cb_data->cb_flag;
339 
340   if (cb_flag & IDWALK_CB_LOOPBACK) {
341     /* We should never have anything to do with loop-back pointers here. */
342     return IDWALK_RET_NOP;
343   }
344 
345   if (cb_flag & IDWALK_CB_EMBEDDED) {
346     /* Embedded data-blocks need to be made fully local as well.
347      * Note however that in some cases (when owner ID had to be duplicated instead of being made
348      * local directly), its embedded IDs should also have already been duplicated, and hence be
349      * fully local here already. */
350     if (*id_pointer != NULL && ID_IS_LINKED(*id_pointer)) {
351       BLI_assert(*id_pointer != id_self);
352 
353       lib_id_clear_library_data_ex(bmain, *id_pointer);
354     }
355     return IDWALK_RET_NOP;
356   }
357 
358   /* Can happen that we get un-linkable ID here, e.g. with shape-key referring to itself
359    * (through drivers)...
360    * Just skip it, shape key can only be either indirectly linked, or fully local, period.
361    * And let's curse one more time that stupid useless shapekey ID type! */
362   if (*id_pointer && *id_pointer != id_self &&
363       BKE_idtype_idcode_is_linkable(GS((*id_pointer)->name))) {
364     id_lib_extern(*id_pointer);
365   }
366 
367   return IDWALK_RET_NOP;
368 }
369 
370 /**
371  * Expand ID usages of given id as 'extern' (and no more indirect) linked data.
372  * Used by ID copy/make_local functions.
373  */
BKE_lib_id_expand_local(Main * bmain,ID * id)374 void BKE_lib_id_expand_local(Main *bmain, ID *id)
375 {
376   BKE_library_foreach_ID_link(bmain, id, lib_id_expand_local_cb, bmain, IDWALK_READONLY);
377 }
378 
379 /**
380  * Ensure new (copied) ID is fully made local.
381  */
lib_id_copy_ensure_local(Main * bmain,const ID * old_id,ID * new_id)382 static void lib_id_copy_ensure_local(Main *bmain, const ID *old_id, ID *new_id)
383 {
384   if (ID_IS_LINKED(old_id)) {
385     BKE_lib_id_expand_local(bmain, new_id);
386     lib_id_library_local_paths(bmain, old_id->lib, new_id);
387   }
388 }
389 
390 /**
391  * Generic 'make local' function, works for most of data-block types...
392  */
BKE_lib_id_make_local_generic(Main * bmain,ID * id,const int flags)393 void BKE_lib_id_make_local_generic(Main *bmain, ID *id, const int flags)
394 {
395   const bool lib_local = (flags & LIB_ID_MAKELOCAL_FULL_LIBRARY) != 0;
396   bool is_local = false, is_lib = false;
397 
398   /* - only lib users: do nothing (unless force_local is set)
399    * - only local users: set flag
400    * - mixed: make copy
401    * In case we make a whole lib's content local,
402    * we always want to localize, and we skip remapping (done later).
403    */
404 
405   if (!ID_IS_LINKED(id)) {
406     return;
407   }
408 
409   BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
410 
411   if (lib_local || is_local) {
412     if (!is_lib) {
413       lib_id_clear_library_data_ex(bmain, id);
414       BKE_lib_id_expand_local(bmain, id);
415     }
416     else {
417       ID *id_new = BKE_id_copy(bmain, id);
418 
419       /* Should not fail in expected use cases,
420        * but a few ID types cannot be copied (LIB, WM, SCR...). */
421       if (id_new != NULL) {
422         id_new->us = 0;
423 
424         /* setting newid is mandatory for complex make_lib_local logic... */
425         ID_NEW_SET(id, id_new);
426         Key *key = BKE_key_from_id(id), *key_new = BKE_key_from_id(id);
427         if (key && key_new) {
428           ID_NEW_SET(key, key_new);
429         }
430         bNodeTree *ntree = ntreeFromID(id), *ntree_new = ntreeFromID(id_new);
431         if (ntree && ntree_new) {
432           ID_NEW_SET(ntree, ntree_new);
433         }
434         if (GS(id->name) == ID_SCE) {
435           Collection *master_collection = ((Scene *)id)->master_collection,
436                      *master_collection_new = ((Scene *)id_new)->master_collection;
437           if (master_collection && master_collection_new) {
438             ID_NEW_SET(master_collection, master_collection_new);
439           }
440         }
441 
442         if (!lib_local) {
443           BKE_libblock_remap(bmain, id, id_new, ID_REMAP_SKIP_INDIRECT_USAGE);
444         }
445       }
446     }
447   }
448 }
449 
450 /**
451  * Calls the appropriate make_local method for the block, unless test is set.
452  *
453  * \note Always set #ID.newid pointer in case it gets duplicated.
454  *
455  * \param flags: Special flag used when making a whole library's content local,
456  * it needs specific handling.
457  *
458  * \return true if the block can be made local.
459  */
BKE_lib_id_make_local(Main * bmain,ID * id,const bool test,const int flags)460 bool BKE_lib_id_make_local(Main *bmain, ID *id, const bool test, const int flags)
461 {
462   const bool lib_local = (flags & LIB_ID_MAKELOCAL_FULL_LIBRARY) != 0;
463 
464   /* We don't care whether ID is directly or indirectly linked
465    * in case we are making a whole lib local... */
466   if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) {
467     return false;
468   }
469 
470   const IDTypeInfo *idtype_info = BKE_idtype_get_info_from_id(id);
471 
472   if (idtype_info != NULL) {
473     if ((idtype_info->flags & IDTYPE_FLAGS_NO_MAKELOCAL) == 0) {
474       if (!test) {
475         if (idtype_info->make_local != NULL) {
476           idtype_info->make_local(bmain, id, flags);
477         }
478         else {
479           BKE_lib_id_make_local_generic(bmain, id, flags);
480         }
481       }
482       return true;
483     }
484     return false;
485   }
486 
487   BLI_assert(!"IDType Missing IDTypeInfo");
488   return false;
489 }
490 
491 struct IDCopyLibManagementData {
492   const ID *id_src;
493   ID *id_dst;
494   int flag;
495 };
496 
497 /* Increases usercount as required, and remap self ID pointers. */
id_copy_libmanagement_cb(LibraryIDLinkCallbackData * cb_data)498 static int id_copy_libmanagement_cb(LibraryIDLinkCallbackData *cb_data)
499 {
500   ID **id_pointer = cb_data->id_pointer;
501   ID *id = *id_pointer;
502   const int cb_flag = cb_data->cb_flag;
503   struct IDCopyLibManagementData *data = cb_data->user_data;
504 
505   /* Remap self-references to new copied ID. */
506   if (id == data->id_src) {
507     /* We cannot use id_self here, it is not *always* id_dst (thanks to $£!+@#&/? nodetrees). */
508     id = *id_pointer = data->id_dst;
509   }
510 
511   /* Increase used IDs refcount if needed and required. */
512   if ((data->flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0 && (cb_flag & IDWALK_CB_USER)) {
513     id_us_plus(id);
514   }
515 
516   return IDWALK_RET_NOP;
517 }
518 
BKE_id_copy_is_allowed(const ID * id)519 bool BKE_id_copy_is_allowed(const ID *id)
520 {
521 #define LIB_ID_TYPES_NOCOPY \
522   ID_LI, ID_SCR, ID_WM, ID_WS, /* Not supported */ \
523       ID_IP                    /* Deprecated */
524 
525   return !ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY);
526 
527 #undef LIB_ID_TYPES_NOCOPY
528 }
529 
530 /**
531  * Generic entry point for copying a data-block (new API).
532  *
533  * \note Copy is generally only affecting the given data-block
534  * (no ID used by copied one will be affected, besides usercount).
535  * There are exceptions though:
536  *  - Embedded IDs (root node trees and master collections) are always copied with their owner.
537  *  - If #LIB_ID_COPY_ACTIONS is defined, actions used by animdata will be duplicated.
538  *  - If #LIB_ID_COPY_SHAPEKEY is defined, shapekeys will be duplicated.
539  *  - If #LIB_ID_CREATE_LOCAL is defined, root node trees will be deep-duplicated recursively.
540  *
541  * \note Usercount of new copy is always set to 1.
542  *
543  * \param bmain: Main database, may be NULL only if LIB_ID_CREATE_NO_MAIN is specified.
544  * \param id: Source data-block.
545  * \param r_newid: Pointer to new (copied) ID pointer, may be NULL. Used to allow copying into
546  *                 already allocated memory.
547  * \param flag: Set of copy options, see DNA_ID.h enum for details (leave to zero for default,
548  *              full copy).
549  * \return NULL when copying that ID type is not supported, the new copy otherwise.
550  */
BKE_id_copy_ex(Main * bmain,const ID * id,ID ** r_newid,const int flag)551 ID *BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag)
552 {
553   ID *newid = (r_newid != NULL) ? *r_newid : NULL;
554   /* Make sure destination pointer is all good. */
555   if ((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0) {
556     newid = NULL;
557   }
558   else {
559     if (newid != NULL) {
560       /* Allow some garbage non-initialized memory to go in, and clean it up here. */
561       const size_t size = BKE_libblock_get_alloc_info(GS(id->name), NULL);
562       memset(newid, 0, size);
563     }
564   }
565 
566   /* Early output is source is NULL. */
567   if (id == NULL) {
568     return NULL;
569   }
570 
571   const IDTypeInfo *idtype_info = BKE_idtype_get_info_from_id(id);
572 
573   if (idtype_info != NULL) {
574     if ((idtype_info->flags & IDTYPE_FLAGS_NO_COPY) != 0) {
575       return NULL;
576     }
577 
578     BKE_libblock_copy_ex(bmain, id, &newid, flag);
579 
580     if (idtype_info->copy_data != NULL) {
581       idtype_info->copy_data(bmain, newid, id, flag);
582     }
583   }
584   else {
585     BLI_assert(!"IDType Missing IDTypeInfo");
586   }
587 
588   /* Update ID refcount, remap pointers to self in new ID. */
589   struct IDCopyLibManagementData data = {
590       .id_src = id,
591       .id_dst = newid,
592       .flag = flag,
593   };
594   BKE_library_foreach_ID_link(bmain, newid, id_copy_libmanagement_cb, &data, IDWALK_NOP);
595 
596   /* Do not make new copy local in case we are copying outside of main...
597    * XXX TODO: is this behavior OK, or should we need own flag to control that? */
598   if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
599     BLI_assert((flag & LIB_ID_COPY_KEEP_LIB) == 0);
600     lib_id_copy_ensure_local(bmain, id, newid);
601   }
602   else {
603     newid->lib = id->lib;
604   }
605 
606   if (r_newid != NULL) {
607     *r_newid = newid;
608   }
609 
610   return newid;
611 }
612 
613 /**
614  * Invokes the appropriate copy method for the block and returns the result in
615  * newid, unless test. Returns true if the block can be copied.
616  */
BKE_id_copy(Main * bmain,const ID * id)617 ID *BKE_id_copy(Main *bmain, const ID *id)
618 {
619   return BKE_id_copy_ex(bmain, id, NULL, LIB_ID_COPY_DEFAULT);
620 }
621 
622 /**
623  * Invokes the appropriate copy method for the block and returns the result in
624  * newid, unless test. Returns true if the block can be copied.
625  */
BKE_id_copy_for_duplicate(Main * bmain,ID * id,const eDupli_ID_Flags duplicate_flags)626 ID *BKE_id_copy_for_duplicate(Main *bmain, ID *id, const eDupli_ID_Flags duplicate_flags)
627 {
628   if (id == NULL) {
629     return id;
630   }
631   if (id->newid == NULL) {
632     const bool do_linked_id = (duplicate_flags & USER_DUP_LINKED_ID) != 0;
633     if (!(do_linked_id || !ID_IS_LINKED(id))) {
634       return id;
635     }
636 
637     ID *id_new = BKE_id_copy(bmain, id);
638     /* Copying add one user by default, need to get rid of that one. */
639     id_us_min(id_new);
640     ID_NEW_SET(id, id_new);
641 
642     /* Shape keys are always copied with their owner ID, by default. */
643     ID *key_new = (ID *)BKE_key_from_id(id_new);
644     ID *key = (ID *)BKE_key_from_id(id);
645     if (key != NULL) {
646       ID_NEW_SET(key, key_new);
647     }
648 
649     /* Note: embedded data (root nodetrees and master collections) should never be referenced by
650      * anything else, so we do not need to set their newid pointer and flag. */
651 
652     BKE_animdata_duplicate_id_action(bmain, id_new, duplicate_flags);
653     if (key_new != NULL) {
654       BKE_animdata_duplicate_id_action(bmain, key_new, duplicate_flags);
655     }
656     /* Note that actions of embedded data (root nodetrees and master collections) are handled
657      * by `BKE_animdata_duplicate_id_action` as well. */
658   }
659   return id->newid;
660 }
661 
662 /**
663  * Does a mere memory swap over the whole IDs data (including type-specific memory).
664  * \note Most internal ID data itself is not swapped (only IDProperties are).
665  */
id_swap(Main * bmain,ID * id_a,ID * id_b,const bool do_full_id)666 static void id_swap(Main *bmain, ID *id_a, ID *id_b, const bool do_full_id)
667 {
668   BLI_assert(GS(id_a->name) == GS(id_b->name));
669 
670   const IDTypeInfo *id_type = BKE_idtype_get_info_from_id(id_a);
671   BLI_assert(id_type != NULL);
672   const size_t id_struct_size = id_type->struct_size;
673 
674   const ID id_a_back = *id_a;
675   const ID id_b_back = *id_b;
676 
677   char *id_swap_buff = alloca(id_struct_size);
678 
679   memcpy(id_swap_buff, id_a, id_struct_size);
680   memcpy(id_a, id_b, id_struct_size);
681   memcpy(id_b, id_swap_buff, id_struct_size);
682 
683   if (!do_full_id) {
684     /* Restore original ID's internal data. */
685     *id_a = id_a_back;
686     *id_b = id_b_back;
687 
688     /* Exception: IDProperties. */
689     id_a->properties = id_b_back.properties;
690     id_b->properties = id_a_back.properties;
691     /* Exception: recalc flags. */
692     id_a->recalc = id_b_back.recalc;
693     id_b->recalc = id_a_back.recalc;
694   }
695 
696   if (bmain != NULL) {
697     /* Swap will have broken internal references to itself, restore them. */
698     BKE_libblock_relink_ex(bmain, id_a, id_b, id_a, ID_REMAP_SKIP_NEVER_NULL_USAGE);
699     BKE_libblock_relink_ex(bmain, id_b, id_a, id_b, ID_REMAP_SKIP_NEVER_NULL_USAGE);
700   }
701 }
702 
703 /**
704  * Does a mere memory swap over the whole IDs data (including type-specific memory).
705  * \note Most internal ID data itself is not swapped (only IDProperties are).
706  *
707  * \param bmain: May be NULL, in which case there will be no remapping of internal pointers to
708  * itself.
709  */
BKE_lib_id_swap(Main * bmain,ID * id_a,ID * id_b)710 void BKE_lib_id_swap(Main *bmain, ID *id_a, ID *id_b)
711 {
712   id_swap(bmain, id_a, id_b, false);
713 }
714 
715 /**
716  * Does a mere memory swap over the whole IDs data (including type-specific memory).
717  * \note All internal ID data itself is also swapped.
718  *
719  * \param bmain: May be NULL, in which case there will be no remapping of internal pointers to
720  * itself.
721  */
BKE_lib_id_swap_full(Main * bmain,ID * id_a,ID * id_b)722 void BKE_lib_id_swap_full(Main *bmain, ID *id_a, ID *id_b)
723 {
724   id_swap(bmain, id_a, id_b, true);
725 }
726 
727 /** Does *not* set ID->newid pointer. */
id_single_user(bContext * C,ID * id,PointerRNA * ptr,PropertyRNA * prop)728 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
729 {
730   ID *newid = NULL;
731   PointerRNA idptr;
732 
733   if (id) {
734     /* If property isn't editable,
735      * we're going to have an extra block hanging around until we save. */
736     if (RNA_property_editable(ptr, prop)) {
737       Main *bmain = CTX_data_main(C);
738       /* copy animation actions too */
739       newid = BKE_id_copy_ex(bmain, id, NULL, LIB_ID_COPY_DEFAULT | LIB_ID_COPY_ACTIONS);
740       if (newid != NULL) {
741         /* us is 1 by convention with new IDs, but RNA_property_pointer_set
742          * will also increment it, decrement it here. */
743         id_us_min(newid);
744 
745         /* assign copy */
746         RNA_id_pointer_create(newid, &idptr);
747         RNA_property_pointer_set(ptr, prop, idptr, NULL);
748         RNA_property_update(C, ptr, prop);
749 
750         /* tag grease pencil data-block and disable onion */
751         if (GS(id->name) == ID_GD) {
752           DEG_id_tag_update(id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
753           DEG_id_tag_update(newid, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
754           bGPdata *gpd = (bGPdata *)newid;
755           gpd->flag &= ~GP_DATA_SHOW_ONIONSKINS;
756         }
757 
758         return true;
759       }
760     }
761   }
762 
763   return false;
764 }
765 
libblock_management_us_plus(LibraryIDLinkCallbackData * cb_data)766 static int libblock_management_us_plus(LibraryIDLinkCallbackData *cb_data)
767 {
768   ID **id_pointer = cb_data->id_pointer;
769   const int cb_flag = cb_data->cb_flag;
770   if (cb_flag & IDWALK_CB_USER) {
771     id_us_plus(*id_pointer);
772   }
773   if (cb_flag & IDWALK_CB_USER_ONE) {
774     id_us_ensure_real(*id_pointer);
775   }
776 
777   return IDWALK_RET_NOP;
778 }
779 
libblock_management_us_min(LibraryIDLinkCallbackData * cb_data)780 static int libblock_management_us_min(LibraryIDLinkCallbackData *cb_data)
781 {
782   ID **id_pointer = cb_data->id_pointer;
783   const int cb_flag = cb_data->cb_flag;
784   if (cb_flag & IDWALK_CB_USER) {
785     id_us_min(*id_pointer);
786   }
787   /* We can do nothing in IDWALK_CB_USER_ONE case! */
788 
789   return IDWALK_RET_NOP;
790 }
791 
792 /** Add a 'NO_MAIN' data-block to given main (also sets usercounts of its IDs if needed). */
BKE_libblock_management_main_add(Main * bmain,void * idv)793 void BKE_libblock_management_main_add(Main *bmain, void *idv)
794 {
795   ID *id = idv;
796 
797   BLI_assert(bmain != NULL);
798   if ((id->tag & LIB_TAG_NO_MAIN) == 0) {
799     return;
800   }
801 
802   if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
803     /* We cannot add non-allocated ID to Main! */
804     return;
805   }
806 
807   /* We cannot allow non-userrefcounting IDs in Main database! */
808   if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
809     BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
810   }
811 
812   ListBase *lb = which_libbase(bmain, GS(id->name));
813   BKE_main_lock(bmain);
814   BLI_addtail(lb, id);
815   BKE_id_new_name_validate(lb, id, NULL);
816   /* alphabetic insertion: is in new_id */
817   id->tag &= ~(LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT);
818   bmain->is_memfile_undo_written = false;
819   BKE_main_unlock(bmain);
820 
821   BKE_lib_libblock_session_uuid_ensure(id);
822 }
823 
824 /** Remove a data-block from given main (set it to 'NO_MAIN' status). */
BKE_libblock_management_main_remove(Main * bmain,void * idv)825 void BKE_libblock_management_main_remove(Main *bmain, void *idv)
826 {
827   ID *id = idv;
828 
829   BLI_assert(bmain != NULL);
830   if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
831     return;
832   }
833 
834   /* For now, allow userrefcounting IDs to get out of Main - can be handy in some cases... */
835 
836   ListBase *lb = which_libbase(bmain, GS(id->name));
837   BKE_main_lock(bmain);
838   BLI_remlink(lb, id);
839   id->tag |= LIB_TAG_NO_MAIN;
840   bmain->is_memfile_undo_written = false;
841   BKE_main_unlock(bmain);
842 }
843 
BKE_libblock_management_usercounts_set(Main * bmain,void * idv)844 void BKE_libblock_management_usercounts_set(Main *bmain, void *idv)
845 {
846   ID *id = idv;
847 
848   if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) == 0) {
849     return;
850   }
851 
852   BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
853   id->tag &= ~LIB_TAG_NO_USER_REFCOUNT;
854 }
855 
BKE_libblock_management_usercounts_clear(Main * bmain,void * idv)856 void BKE_libblock_management_usercounts_clear(Main *bmain, void *idv)
857 {
858   ID *id = idv;
859 
860   /* We do not allow IDs in Main database to not be userrefcounting. */
861   if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0 || (id->tag & LIB_TAG_NO_MAIN) != 0) {
862     return;
863   }
864 
865   BKE_library_foreach_ID_link(bmain, id, libblock_management_us_min, NULL, IDWALK_NOP);
866   id->tag |= LIB_TAG_NO_USER_REFCOUNT;
867 }
868 
869 /**
870  * Clear or set given tags for all ids in listbase (runtime tags).
871  */
BKE_main_id_tag_listbase(ListBase * lb,const int tag,const bool value)872 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
873 {
874   ID *id;
875   if (value) {
876     for (id = lb->first; id; id = id->next) {
877       id->tag |= tag;
878     }
879   }
880   else {
881     const int ntag = ~tag;
882     for (id = lb->first; id; id = id->next) {
883       id->tag &= ntag;
884     }
885   }
886 }
887 
888 /**
889  * Clear or set given tags for all ids of given type in bmain (runtime tags).
890  */
BKE_main_id_tag_idcode(struct Main * mainvar,const short type,const int tag,const bool value)891 void BKE_main_id_tag_idcode(struct Main *mainvar,
892                             const short type,
893                             const int tag,
894                             const bool value)
895 {
896   ListBase *lb = which_libbase(mainvar, type);
897 
898   BKE_main_id_tag_listbase(lb, tag, value);
899 }
900 
901 /**
902  * Clear or set given tags for all ids in bmain (runtime tags).
903  */
BKE_main_id_tag_all(struct Main * mainvar,const int tag,const bool value)904 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
905 {
906   ListBase *lbarray[MAX_LIBARRAY];
907   int a;
908 
909   a = set_listbasepointers(mainvar, lbarray);
910   while (a--) {
911     BKE_main_id_tag_listbase(lbarray[a], tag, value);
912   }
913 }
914 
915 /**
916  * Clear or set given flags for all ids in listbase (persistent flags).
917  */
BKE_main_id_flag_listbase(ListBase * lb,const int flag,const bool value)918 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
919 {
920   ID *id;
921   if (value) {
922     for (id = lb->first; id; id = id->next) {
923       id->tag |= flag;
924     }
925   }
926   else {
927     const int nflag = ~flag;
928     for (id = lb->first; id; id = id->next) {
929       id->tag &= nflag;
930     }
931   }
932 }
933 
934 /**
935  * Clear or set given flags for all ids in bmain (persistent flags).
936  */
BKE_main_id_flag_all(Main * bmain,const int flag,const bool value)937 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
938 {
939   ListBase *lbarray[MAX_LIBARRAY];
940   int a;
941   a = set_listbasepointers(bmain, lbarray);
942   while (a--) {
943     BKE_main_id_flag_listbase(lbarray[a], flag, value);
944   }
945 }
946 
BKE_main_id_repair_duplicate_names_listbase(ListBase * lb)947 void BKE_main_id_repair_duplicate_names_listbase(ListBase *lb)
948 {
949   int lb_len = 0;
950   LISTBASE_FOREACH (ID *, id, lb) {
951     if (id->lib == NULL) {
952       lb_len += 1;
953     }
954   }
955   if (lb_len <= 1) {
956     return;
957   }
958 
959   /* Fill an array because renaming sorts. */
960   ID **id_array = MEM_mallocN(sizeof(*id_array) * lb_len, __func__);
961   GSet *gset = BLI_gset_str_new_ex(__func__, lb_len);
962   int i = 0;
963   LISTBASE_FOREACH (ID *, id, lb) {
964     if (id->lib == NULL) {
965       id_array[i] = id;
966       i++;
967     }
968   }
969   for (i = 0; i < lb_len; i++) {
970     if (!BLI_gset_add(gset, id_array[i]->name + 2)) {
971       BKE_id_new_name_validate(lb, id_array[i], NULL);
972     }
973   }
974   BLI_gset_free(gset, NULL);
975   MEM_freeN(id_array);
976 }
977 
BKE_main_lib_objects_recalc_all(Main * bmain)978 void BKE_main_lib_objects_recalc_all(Main *bmain)
979 {
980   Object *ob;
981 
982   /* flag for full recalc */
983   for (ob = bmain->objects.first; ob; ob = ob->id.next) {
984     if (ID_IS_LINKED(ob)) {
985       DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
986     }
987   }
988 
989   DEG_id_type_tag(bmain, ID_OB);
990 }
991 
992 /* *********** ALLOC AND FREE *****************
993  *
994  * BKE_libblock_free(ListBase *lb, ID *id )
995  * provide a list-basis and data-block, but only ID is read
996  *
997  * void *BKE_libblock_alloc(ListBase *lb, type, name)
998  * inserts in list and returns a new ID
999  *
1000  * **************************** */
1001 
1002 /**
1003  * Get allocation size of a given data-block type and optionally allocation name.
1004  */
BKE_libblock_get_alloc_info(short type,const char ** name)1005 size_t BKE_libblock_get_alloc_info(short type, const char **name)
1006 {
1007   const IDTypeInfo *id_type = BKE_idtype_get_info_from_idcode(type);
1008 
1009   if (id_type == NULL) {
1010     if (name != NULL) {
1011       *name = NULL;
1012     }
1013     return 0;
1014   }
1015 
1016   if (name != NULL) {
1017     *name = id_type->name;
1018   }
1019   return id_type->struct_size;
1020 }
1021 
1022 /**
1023  * Allocates and returns memory of the right size for the specified block type,
1024  * initialized to zero.
1025  */
BKE_libblock_alloc_notest(short type)1026 void *BKE_libblock_alloc_notest(short type)
1027 {
1028   const char *name;
1029   size_t size = BKE_libblock_get_alloc_info(type, &name);
1030   if (size != 0) {
1031     return MEM_callocN(size, name);
1032   }
1033   BLI_assert(!"Request to allocate unknown data type");
1034   return NULL;
1035 }
1036 
1037 /**
1038  * Allocates and returns a block of the specified type, with the specified name
1039  * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
1040  * The user count is set to 1, all other content (apart from name and links) being
1041  * initialized to zero.
1042  */
BKE_libblock_alloc(Main * bmain,short type,const char * name,const int flag)1043 void *BKE_libblock_alloc(Main *bmain, short type, const char *name, const int flag)
1044 {
1045   BLI_assert((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
1046   BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || bmain != NULL);
1047   BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_LOCAL) == 0);
1048 
1049   ID *id = BKE_libblock_alloc_notest(type);
1050 
1051   if (id) {
1052     if ((flag & LIB_ID_CREATE_NO_MAIN) != 0) {
1053       id->tag |= LIB_TAG_NO_MAIN;
1054     }
1055     if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0) {
1056       id->tag |= LIB_TAG_NO_USER_REFCOUNT;
1057     }
1058     if (flag & LIB_ID_CREATE_LOCAL) {
1059       id->tag |= LIB_TAG_LOCALIZED;
1060     }
1061 
1062     id->icon_id = 0;
1063     *((short *)id->name) = type;
1064     if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1065       id->us = 1;
1066     }
1067     if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1068       /* Note that 2.8x versioning has tested not to cause conflicts. */
1069       BLI_assert(bmain->is_locked_for_linking == false || ELEM(type, ID_WS, ID_GR));
1070       ListBase *lb = which_libbase(bmain, type);
1071 
1072       BKE_main_lock(bmain);
1073       BLI_addtail(lb, id);
1074       BKE_id_new_name_validate(lb, id, name);
1075       bmain->is_memfile_undo_written = false;
1076       /* alphabetic insertion: is in new_id */
1077       BKE_main_unlock(bmain);
1078 
1079       BKE_lib_libblock_session_uuid_ensure(id);
1080 
1081       /* TODO to be removed from here! */
1082       if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0) {
1083         DEG_id_type_tag(bmain, type);
1084       }
1085     }
1086     else {
1087       BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2);
1088     }
1089   }
1090 
1091   return id;
1092 }
1093 
1094 /**
1095  * Initialize an ID of given type, such that it has valid 'empty' data.
1096  * ID is assumed to be just calloc'ed.
1097  */
BKE_libblock_init_empty(ID * id)1098 void BKE_libblock_init_empty(ID *id)
1099 {
1100   const IDTypeInfo *idtype_info = BKE_idtype_get_info_from_id(id);
1101 
1102   if (idtype_info != NULL) {
1103     if (idtype_info->init_data != NULL) {
1104       idtype_info->init_data(id);
1105     }
1106     return;
1107   }
1108 
1109   BLI_assert(!"IDType Missing IDTypeInfo");
1110 }
1111 
1112 /* ********** ID session-wise UUID management. ********** */
1113 static uint global_session_uuid = 0;
1114 
1115 /**
1116  * Generate a session-wise uuid for the given \a id.
1117  *
1118  * \note "session-wise" here means while editing a given .blend file. Once a new .blend file is
1119  * loaded or created, undo history is cleared/reset, and so is the uuid counter.
1120  */
BKE_lib_libblock_session_uuid_ensure(ID * id)1121 void BKE_lib_libblock_session_uuid_ensure(ID *id)
1122 {
1123   if (id->session_uuid == MAIN_ID_SESSION_UUID_UNSET) {
1124     id->session_uuid = atomic_add_and_fetch_uint32(&global_session_uuid, 1);
1125     /* In case overflow happens, still assign a valid ID. This way opening files many times works
1126      * correctly. */
1127     if (UNLIKELY(id->session_uuid == MAIN_ID_SESSION_UUID_UNSET)) {
1128       id->session_uuid = atomic_add_and_fetch_uint32(&global_session_uuid, 1);
1129     }
1130   }
1131 }
1132 
1133 /**
1134  * Re-generate a new session-wise uuid for the given \a id.
1135  *
1136  * \warning This has a few very specific use-cases, no other usage is expected currently:
1137  *   - To handle UI-related data-blocks that are kept across new file reading, when we do keep
1138  * existing UI.
1139  *   - For IDs that are made local without needing any copying.
1140  */
BKE_lib_libblock_session_uuid_renew(ID * id)1141 void BKE_lib_libblock_session_uuid_renew(ID *id)
1142 {
1143   id->session_uuid = MAIN_ID_SESSION_UUID_UNSET;
1144   BKE_lib_libblock_session_uuid_ensure(id);
1145 }
1146 
1147 /**
1148  * Generic helper to create a new empty data-block of given type in given \a bmain database.
1149  *
1150  * \param name: can be NULL, in which case we get default name for this ID type.
1151  */
BKE_id_new(Main * bmain,const short type,const char * name)1152 void *BKE_id_new(Main *bmain, const short type, const char *name)
1153 {
1154   BLI_assert(bmain != NULL);
1155 
1156   if (name == NULL) {
1157     name = DATA_(BKE_idtype_idcode_to_name(type));
1158   }
1159 
1160   ID *id = BKE_libblock_alloc(bmain, type, name, 0);
1161   BKE_libblock_init_empty(id);
1162 
1163   return id;
1164 }
1165 
1166 /**
1167  * Generic helper to create a new temporary empty data-block of given type,
1168  * *outside* of any Main database.
1169  *
1170  * \param name: can be NULL, in which case we get default name for this ID type. */
BKE_id_new_nomain(const short type,const char * name)1171 void *BKE_id_new_nomain(const short type, const char *name)
1172 {
1173   if (name == NULL) {
1174     name = DATA_(BKE_idtype_idcode_to_name(type));
1175   }
1176 
1177   ID *id = BKE_libblock_alloc(NULL,
1178                               type,
1179                               name,
1180                               LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT |
1181                                   LIB_ID_CREATE_NO_DEG_TAG);
1182   BKE_libblock_init_empty(id);
1183 
1184   return id;
1185 }
1186 
BKE_libblock_copy_ex(Main * bmain,const ID * id,ID ** r_newid,const int orig_flag)1187 void BKE_libblock_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int orig_flag)
1188 {
1189   ID *new_id = *r_newid;
1190   int flag = orig_flag;
1191 
1192   const bool is_private_id_data = (id->flag & LIB_EMBEDDED_DATA) != 0;
1193 
1194   BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || bmain != NULL);
1195   BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
1196   BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_LOCAL) == 0);
1197   if (!is_private_id_data) {
1198     /* When we are handling private ID data, we might still want to manage usercounts, even
1199      * though that ID data-block is actually outside of Main... */
1200     BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 ||
1201                (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0);
1202   }
1203   /* Never implicitly copy shapekeys when generating temp data outside of Main database. */
1204   BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 || (flag & LIB_ID_COPY_SHAPEKEY) == 0);
1205 
1206   /* 'Private ID' data handling. */
1207   if ((bmain != NULL) && is_private_id_data) {
1208     flag |= LIB_ID_CREATE_NO_MAIN;
1209   }
1210 
1211   /* The id->flag bits to copy over. */
1212   const int copy_idflag_mask = LIB_EMBEDDED_DATA;
1213 
1214   if ((flag & LIB_ID_CREATE_NO_ALLOCATE) != 0) {
1215     /* r_newid already contains pointer to allocated memory. */
1216     /* TODO do we want to memset(0) whole mem before filling it? */
1217     BLI_strncpy(new_id->name, id->name, sizeof(new_id->name));
1218     new_id->us = 0;
1219     new_id->tag |= LIB_TAG_NOT_ALLOCATED | LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT;
1220     /* TODO Do we want/need to copy more from ID struct itself? */
1221   }
1222   else {
1223     new_id = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2, flag);
1224   }
1225   BLI_assert(new_id != NULL);
1226 
1227   const size_t id_len = BKE_libblock_get_alloc_info(GS(new_id->name), NULL);
1228   const size_t id_offset = sizeof(ID);
1229   if ((int)id_len - (int)id_offset > 0) { /* signed to allow neg result */ /* XXX ????? */
1230     const char *cp = (const char *)id;
1231     char *cpn = (char *)new_id;
1232 
1233     memcpy(cpn + id_offset, cp + id_offset, id_len - id_offset);
1234   }
1235 
1236   new_id->flag = (new_id->flag & ~copy_idflag_mask) | (id->flag & copy_idflag_mask);
1237 
1238   /* We do not want any handling of usercount in code duplicating the data here, we do that all
1239    * at once in id_copy_libmanagement_cb() at the end. */
1240   const int copy_data_flag = orig_flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
1241 
1242   if (id->properties) {
1243     new_id->properties = IDP_CopyProperty_ex(id->properties, copy_data_flag);
1244   }
1245 
1246   /* We may need our own flag to control that at some point, but for now 'no main' one should be
1247    * good enough. */
1248   if ((orig_flag & LIB_ID_CREATE_NO_MAIN) == 0 && ID_IS_OVERRIDE_LIBRARY(id)) {
1249     /* We do not want to copy existing override rules here, as they would break the proper
1250      * remapping between IDs. Proper overrides rules will be re-generated anyway. */
1251     BKE_lib_override_library_copy(new_id, id, false);
1252   }
1253 
1254   if (id_can_have_animdata(new_id)) {
1255     IdAdtTemplate *iat = (IdAdtTemplate *)new_id;
1256 
1257     /* the duplicate should get a copy of the animdata */
1258     if ((flag & LIB_ID_COPY_NO_ANIMDATA) == 0) {
1259       /* Note that even though horrors like root nodetrees are not in bmain, the actions they use
1260        * in their anim data *are* in bmain... super-mega-hooray. */
1261       BLI_assert((copy_data_flag & LIB_ID_COPY_ACTIONS) == 0 ||
1262                  (copy_data_flag & LIB_ID_CREATE_NO_MAIN) == 0);
1263       iat->adt = BKE_animdata_copy(bmain, iat->adt, copy_data_flag);
1264     }
1265     else {
1266       iat->adt = NULL;
1267     }
1268   }
1269 
1270   if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1271     DEG_id_type_tag(bmain, GS(new_id->name));
1272   }
1273 
1274   *r_newid = new_id;
1275 }
1276 
1277 /* used everywhere in blenkernel */
BKE_libblock_copy(Main * bmain,const ID * id)1278 void *BKE_libblock_copy(Main *bmain, const ID *id)
1279 {
1280   ID *idn;
1281 
1282   BKE_libblock_copy_ex(bmain, id, &idn, 0);
1283 
1284   return idn;
1285 }
1286 
1287 /* XXX TODO: get rid of this useless wrapper at some point... */
BKE_libblock_copy_for_localize(const ID * id)1288 void *BKE_libblock_copy_for_localize(const ID *id)
1289 {
1290   ID *idn;
1291   BKE_libblock_copy_ex(NULL, id, &idn, LIB_ID_COPY_LOCALIZE | LIB_ID_COPY_NO_ANIMDATA);
1292   return idn;
1293 }
1294 
1295 /* ***************** ID ************************ */
BKE_libblock_find_name(struct Main * bmain,const short type,const char * name)1296 ID *BKE_libblock_find_name(struct Main *bmain, const short type, const char *name)
1297 {
1298   ListBase *lb = which_libbase(bmain, type);
1299   BLI_assert(lb != NULL);
1300   return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1301 }
1302 
1303 /**
1304  * Sort given \a id into given \a lb list, using case-insensitive comparison of the id names.
1305  *
1306  * \note All other IDs beside given one are assumed already properly sorted in the list.
1307  *
1308  * \param id_sorting_hint: Ignored if NULL. Otherwise, used to check if we can insert \a id
1309  * immediately before or after that pointer. It must always be into given \a lb list.
1310  */
id_sort_by_name(ListBase * lb,ID * id,ID * id_sorting_hint)1311 void id_sort_by_name(ListBase *lb, ID *id, ID *id_sorting_hint)
1312 {
1313 #define ID_SORT_STEP_SIZE 512
1314 
1315   ID *idtest;
1316 
1317   /* insert alphabetically */
1318   if (lb->first == lb->last) {
1319     return;
1320   }
1321 
1322   BLI_remlink(lb, id);
1323 
1324   /* Check if we can actually insert id before or after id_sorting_hint, if given. */
1325   if (id_sorting_hint != NULL && id_sorting_hint != id) {
1326     BLI_assert(BLI_findindex(lb, id_sorting_hint) >= 0);
1327 
1328     ID *id_sorting_hint_next = id_sorting_hint->next;
1329     if (BLI_strcasecmp(id_sorting_hint->name, id->name) < 0 &&
1330         (id_sorting_hint_next == NULL ||
1331          BLI_strcasecmp(id_sorting_hint_next->name, id->name) > 0)) {
1332       BLI_insertlinkafter(lb, id_sorting_hint, id);
1333       return;
1334     }
1335 
1336     ID *id_sorting_hint_prev = id_sorting_hint->prev;
1337     if (BLI_strcasecmp(id_sorting_hint->name, id->name) > 0 &&
1338         (id_sorting_hint_prev == NULL ||
1339          BLI_strcasecmp(id_sorting_hint_prev->name, id->name) < 0)) {
1340       BLI_insertlinkbefore(lb, id_sorting_hint, id);
1341       return;
1342     }
1343   }
1344 
1345   void *item_array[ID_SORT_STEP_SIZE];
1346   int item_array_index;
1347 
1348   /* Step one: We go backward over a whole chunk of items at once, until we find a limit item
1349    * that is lower than, or equal (should never happen!) to the one we want to insert. */
1350   /* Note: We start from the end, because in typical 'heavy' case (insertion of lots of IDs at
1351    * once using the same base name), newly inserted items will generally be towards the end
1352    * (higher extension numbers). */
1353   for (idtest = lb->last, item_array_index = ID_SORT_STEP_SIZE - 1; idtest != NULL;
1354        idtest = idtest->prev, item_array_index--) {
1355     item_array[item_array_index] = idtest;
1356     if (item_array_index == 0) {
1357       if ((idtest->lib == NULL && id->lib != NULL) ||
1358           BLI_strcasecmp(idtest->name, id->name) <= 0) {
1359         break;
1360       }
1361       item_array_index = ID_SORT_STEP_SIZE;
1362     }
1363   }
1364 
1365   /* Step two: we go forward in the selected chunk of items and check all of them, as we know
1366    * that our target is in there. */
1367 
1368   /* If we reached start of the list, current item_array_index is off-by-one.
1369    * Otherwise, we already know that it points to an item lower-or-equal-than the one we want to
1370    * insert, no need to redo the check for that one.
1371    * So we can increment that index in any case. */
1372   for (item_array_index++; item_array_index < ID_SORT_STEP_SIZE; item_array_index++) {
1373     idtest = item_array[item_array_index];
1374     if ((idtest->lib != NULL && id->lib == NULL) || BLI_strcasecmp(idtest->name, id->name) > 0) {
1375       BLI_insertlinkbefore(lb, idtest, id);
1376       break;
1377     }
1378   }
1379   if (item_array_index == ID_SORT_STEP_SIZE) {
1380     if (idtest == NULL) {
1381       /* If idtest is NULL here, it means that in the first loop, the last comparison was
1382        * performed exactly on the first item of the list, and that it also failed. In other
1383        * words, all items in the list are greater than inserted one, so we can put it at the
1384        * start of the list. */
1385       /* Note that BLI_insertlinkafter() would have same behavior in that case, but better be
1386        * explicit here. */
1387       BLI_addhead(lb, id);
1388     }
1389     else {
1390       BLI_insertlinkafter(lb, idtest, id);
1391     }
1392   }
1393 
1394 #undef ID_SORT_STEP_SIZE
1395 }
1396 
1397 /* Note: this code assumes and ensures that the suffix number can never go beyond 1 billion. */
1398 #define MAX_NUMBER 1000000000
1399 /* We do not want to get "name.000", so minimal number is 1. */
1400 #define MIN_NUMBER 1
1401 /* The maximum value up to which we search for the actual smallest unused number. Beyond that
1402  * value, we will only use the first biggest unused number, without trying to 'fill the gaps'
1403  * in-between already used numbers... */
1404 #define MAX_NUMBERS_IN_USE 1024
1405 
1406 /**
1407  * Helper building final ID name from given base_name and number.
1408  *
1409  * If everything goes well and we do generate a valid final ID name in given name, we return
1410  * true. In case the final name would overflow the allowed ID name length, or given number is
1411  * bigger than maximum allowed value, we truncate further the base_name (and given name, which is
1412  * assumed to have the same 'base_name' part), and return false.
1413  */
id_name_final_build(char * name,char * base_name,size_t base_name_len,int number)1414 static bool id_name_final_build(char *name, char *base_name, size_t base_name_len, int number)
1415 {
1416   char number_str[11]; /* Dot + nine digits + NULL terminator. */
1417   size_t number_str_len = BLI_snprintf_rlen(number_str, ARRAY_SIZE(number_str), ".%.3d", number);
1418 
1419   /* If the number would lead to an overflow of the maximum ID name length, we need to truncate
1420    * the base name part and do all the number checks again. */
1421   if (base_name_len + number_str_len >= MAX_ID_NAME - 2 || number >= MAX_NUMBER) {
1422     if (base_name_len + number_str_len >= MAX_ID_NAME - 2) {
1423       base_name_len = MAX_ID_NAME - 2 - number_str_len - 1;
1424     }
1425     else {
1426       base_name_len--;
1427     }
1428     base_name[base_name_len] = '\0';
1429 
1430     /* Code above may have generated invalid utf-8 string, due to raw truncation.
1431      * Ensure we get a valid one now. */
1432     base_name_len -= (size_t)BLI_utf8_invalid_strip(base_name, base_name_len);
1433 
1434     /* Also truncate orig name, and start the whole check again. */
1435     name[base_name_len] = '\0';
1436     return false;
1437   }
1438 
1439   /* We have our final number, we can put it in name and exit the function. */
1440   BLI_strncpy(name + base_name_len, number_str, number_str_len + 1);
1441   return true;
1442 }
1443 
1444 /**
1445  * Check to see if an ID name is already used, and find a new one if so.
1446  * Return true if a new name was created (returned in name).
1447  *
1448  * Normally the ID that's being checked is already in the ListBase, so ID *id points at the new
1449  * entry. The Python Library module needs to know what the name of a data-block will be before it
1450  * is appended, in this case ID *id is NULL.
1451  */
check_for_dupid(ListBase * lb,ID * id,char * name,ID ** r_id_sorting_hint)1452 static bool check_for_dupid(ListBase *lb, ID *id, char *name, ID **r_id_sorting_hint)
1453 {
1454   BLI_assert(strlen(name) < MAX_ID_NAME - 2);
1455 
1456   *r_id_sorting_hint = NULL;
1457 
1458   ID *id_test = lb->first;
1459   bool is_name_changed = false;
1460 
1461   if (id_test == NULL) {
1462     return is_name_changed;
1463   }
1464 
1465   const short id_type = (short)GS(id_test->name);
1466 
1467   /* Static storage of previous handled ID/name info, used to perform a quicker test and optimize
1468    * creation of huge number of IDs using the same given base name. */
1469   static char prev_orig_base_name[MAX_ID_NAME - 2] = {0};
1470   static char prev_final_base_name[MAX_ID_NAME - 2] = {0};
1471   static short prev_id_type = ID_LINK_PLACEHOLDER; /* Should never exist in actual ID list. */
1472   static int prev_number = MIN_NUMBER - 1;
1473 
1474   /* Initial test to check whether we can 'shortcut' the more complex loop of the main code
1475    * below. Note that we do not do that for low numbers, as that would prevent using actual
1476    * smallest available number in some cases, and benefits of this special case handling mostly
1477    * show up with high numbers anyway. */
1478   if (id_type == prev_id_type && prev_number >= MAX_NUMBERS_IN_USE &&
1479       prev_number < MAX_NUMBER - 1 && name[0] == prev_final_base_name[0]) {
1480 
1481     /* Get the name and number parts ("name.number"). */
1482     char base_name[MAX_ID_NAME - 2];
1483     int number = MIN_NUMBER;
1484     size_t base_name_len = BLI_split_name_num(base_name, &number, name, '.');
1485     size_t prev_final_base_name_len = strlen(prev_final_base_name);
1486     size_t prev_orig_base_name_len = strlen(prev_orig_base_name);
1487 
1488     if (base_name_len == prev_orig_base_name_len &&
1489         STREQLEN(base_name, prev_orig_base_name, prev_orig_base_name_len)) {
1490       /* Once we have ensured given base_name and original previous one are the same, we can
1491        * check that previously used number is actually used, and that next one is free. */
1492       /* Note that from now on, we only used previous final base name, as it might have been
1493        * truncated from original one due to number suffix length. */
1494       char final_name[MAX_ID_NAME - 2];
1495       char prev_final_name[MAX_ID_NAME - 2];
1496       BLI_strncpy(final_name, prev_final_base_name, prev_final_base_name_len + 1);
1497       BLI_strncpy(prev_final_name, prev_final_base_name, prev_final_base_name_len + 1);
1498 
1499       if (id_name_final_build(final_name, base_name, prev_final_base_name_len, prev_number + 1) &&
1500           id_name_final_build(prev_final_name, base_name, prev_final_base_name_len, prev_number)) {
1501         /* We successfully built valid final names of previous and current iterations,
1502          * now we have to ensure that previous final name is indeed used in current ID list,
1503          * and that current one is not. */
1504         bool is_valid = false;
1505         for (id_test = lb->first; id_test; id_test = id_test->next) {
1506           if (id != id_test && !ID_IS_LINKED(id_test)) {
1507             if (id_test->name[2] == final_name[0] && STREQ(final_name, id_test->name + 2)) {
1508               /* We expect final_name to not be already used, so this is a failure. */
1509               is_valid = false;
1510               break;
1511             }
1512             /* Previous final name should only be found once in the list, so if it was found
1513              * already, no need to do a string comparison again. */
1514             if (!is_valid && id_test->name[2] == prev_final_name[0] &&
1515                 STREQ(prev_final_name, id_test->name + 2)) {
1516               is_valid = true;
1517               *r_id_sorting_hint = id_test;
1518             }
1519           }
1520         }
1521 
1522         if (is_valid) {
1523           /* Only the number changed, prev_orig_base_name, prev_final_base_name and prev_id_type
1524            * remain the same. */
1525           prev_number++;
1526 
1527           strcpy(name, final_name);
1528           return true;
1529         }
1530       }
1531     }
1532   }
1533 
1534   /* To speed up finding smallest unused number within [0 .. MAX_NUMBERS_IN_USE - 1].
1535    * We do not bother beyond that point. */
1536   ID *ids_in_use[MAX_NUMBERS_IN_USE] = {NULL};
1537 
1538   bool is_first_run = true;
1539   while (true) {
1540     /* Get the name and number parts ("name.number"). */
1541     char base_name[MAX_ID_NAME - 2];
1542     int number = MIN_NUMBER;
1543     size_t base_name_len = BLI_split_name_num(base_name, &number, name, '.');
1544 
1545     /* Store previous original given base name now, as we might alter it later in code below. */
1546     if (is_first_run) {
1547       strcpy(prev_orig_base_name, base_name);
1548       is_first_run = false;
1549     }
1550 
1551     /* In case we get an insane initial number suffix in given name. */
1552     /* Note: BLI_split_name_num() cannot return negative numbers, so we do not have to check for
1553      * that here. */
1554     if (number >= MAX_NUMBER || number < MIN_NUMBER) {
1555       number = MIN_NUMBER;
1556     }
1557 
1558     bool is_orig_name_used = false;
1559     for (id_test = lb->first; id_test; id_test = id_test->next) {
1560       char base_name_test[MAX_ID_NAME - 2];
1561       int number_test;
1562       if ((id != id_test) && !ID_IS_LINKED(id_test) && (name[0] == id_test->name[2]) &&
1563           (id_test->name[base_name_len + 2] == '.' || id_test->name[base_name_len + 2] == '\0') &&
1564           STREQLEN(name, id_test->name + 2, base_name_len) &&
1565           (BLI_split_name_num(base_name_test, &number_test, id_test->name + 2, '.') ==
1566            base_name_len)) {
1567         /* If we did not yet encounter exact same name as the given one, check the remaining
1568          * parts of the strings. */
1569         if (!is_orig_name_used) {
1570           is_orig_name_used = STREQ(name + base_name_len, id_test->name + 2 + base_name_len);
1571         }
1572         /* Mark number of current id_test name as used, if possible. */
1573         if (number_test < MAX_NUMBERS_IN_USE) {
1574           ids_in_use[number_test] = id_test;
1575         }
1576         /* Keep track of first largest unused number. */
1577         if (number <= number_test) {
1578           *r_id_sorting_hint = id_test;
1579           number = number_test + 1;
1580         }
1581       }
1582     }
1583 
1584     /* If there is no double, we are done.
1585      * Note however that name might have been changed (truncated) in a previous iteration
1586      * already.
1587      */
1588     if (!is_orig_name_used) {
1589       /* Don't bother updating prev_ static variables here, this case is not supposed to happen
1590        * that often, and is not straight-forward here, so just ignore and reset them to default.
1591        */
1592       prev_id_type = ID_LINK_PLACEHOLDER;
1593       prev_final_base_name[0] = '\0';
1594       prev_number = MIN_NUMBER - 1;
1595 
1596       /* Value set previously is meaningless in that case. */
1597       *r_id_sorting_hint = NULL;
1598 
1599       return is_name_changed;
1600     }
1601 
1602     /* Decide which value of number to use, either the smallest unused one if possible, or
1603      * default to the first largest unused one we got from previous loop. */
1604     for (int i = MIN_NUMBER; i < MAX_NUMBERS_IN_USE; i++) {
1605       if (ids_in_use[i] == NULL) {
1606         number = i;
1607         if (i > 0) {
1608           *r_id_sorting_hint = ids_in_use[i - 1];
1609         }
1610         break;
1611       }
1612     }
1613     /* At this point, number is either the lowest unused number within
1614      * [MIN_NUMBER .. MAX_NUMBERS_IN_USE - 1], or 1 greater than the largest used number if all
1615      * those low ones are taken.
1616      * We can't be bothered to look for the lowest unused number beyond
1617      * (MAX_NUMBERS_IN_USE - 1).
1618      */
1619     /* We know for wure that name will be changed. */
1620     is_name_changed = true;
1621 
1622     /* If id_name_final_build helper returns false, it had to truncate further given name, hence
1623      * we have to go over the whole check again. */
1624     if (!id_name_final_build(name, base_name, base_name_len, number)) {
1625       /* We have to clear our list of small used numbers before we do the whole check again. */
1626       memset(ids_in_use, 0, sizeof(ids_in_use));
1627 
1628       continue;
1629     }
1630 
1631     /* Update prev_ static variables, in case next call is for the same type of IDs and with the
1632      * same initial base name, we can skip a lot of above process. */
1633     prev_id_type = id_type;
1634     strcpy(prev_final_base_name, base_name);
1635     prev_number = number;
1636 
1637     return is_name_changed;
1638   }
1639 
1640 #undef MAX_NUMBERS_IN_USE
1641 }
1642 
1643 #undef MIN_NUMBER
1644 #undef MAX_NUMBER
1645 
1646 /**
1647  * Ensures given ID has a unique name in given listbase.
1648  *
1649  * Only for local IDs (linked ones already have a unique ID in their library).
1650  *
1651  * \return true if a new name had to be created.
1652  */
BKE_id_new_name_validate(ListBase * lb,ID * id,const char * tname)1653 bool BKE_id_new_name_validate(ListBase *lb, ID *id, const char *tname)
1654 {
1655   bool result;
1656   char name[MAX_ID_NAME - 2];
1657 
1658   /* if library, don't rename */
1659   if (ID_IS_LINKED(id)) {
1660     return false;
1661   }
1662 
1663   /* if no name given, use name of current ID
1664    * else make a copy (tname args can be const) */
1665   if (tname == NULL) {
1666     tname = id->name + 2;
1667   }
1668 
1669   BLI_strncpy(name, tname, sizeof(name));
1670 
1671   if (name[0] == '\0') {
1672     /* Disallow empty names. */
1673     BLI_strncpy(name, DATA_(BKE_idtype_idcode_to_name(GS(id->name))), sizeof(name));
1674   }
1675   else {
1676     /* disallow non utf8 chars,
1677      * the interface checks for this but new ID's based on file names don't */
1678     BLI_utf8_invalid_strip(name, strlen(name));
1679   }
1680 
1681   ID *id_sorting_hint = NULL;
1682   result = check_for_dupid(lb, id, name, &id_sorting_hint);
1683   strcpy(id->name + 2, name);
1684 
1685   /* This was in 2.43 and previous releases
1686    * however all data in blender should be sorted, not just duplicate names
1687    * sorting should not hurt, but noting just in case it alters the way other
1688    * functions work, so sort every time. */
1689 #if 0
1690   if (result) {
1691     id_sort_by_name(lb, id, id_sorting_hint);
1692   }
1693 #endif
1694 
1695   id_sort_by_name(lb, id, id_sorting_hint);
1696 
1697   return result;
1698 }
1699 
1700 /* next to indirect usage in read/writefile also in editobject.c scene.c */
BKE_main_id_clear_newpoins(Main * bmain)1701 void BKE_main_id_clear_newpoins(Main *bmain)
1702 {
1703   ID *id;
1704 
1705   FOREACH_MAIN_ID_BEGIN (bmain, id) {
1706     id->newid = NULL;
1707     id->tag &= ~LIB_TAG_NEW;
1708   }
1709   FOREACH_MAIN_ID_END;
1710 }
1711 
id_refcount_recompute_callback(LibraryIDLinkCallbackData * cb_data)1712 static int id_refcount_recompute_callback(LibraryIDLinkCallbackData *cb_data)
1713 {
1714   ID **id_pointer = cb_data->id_pointer;
1715   const int cb_flag = cb_data->cb_flag;
1716   const bool do_linked_only = (bool)POINTER_AS_INT(cb_data->user_data);
1717 
1718   if (*id_pointer == NULL) {
1719     return IDWALK_RET_NOP;
1720   }
1721   if (do_linked_only && !ID_IS_LINKED(*id_pointer)) {
1722     return IDWALK_RET_NOP;
1723   }
1724 
1725   if (cb_flag & IDWALK_CB_USER) {
1726     /* Do not touch to direct/indirect linked status here... */
1727     id_us_plus_no_lib(*id_pointer);
1728   }
1729   if (cb_flag & IDWALK_CB_USER_ONE) {
1730     id_us_ensure_real(*id_pointer);
1731   }
1732 
1733   return IDWALK_RET_NOP;
1734 }
1735 
BKE_main_id_refcount_recompute(struct Main * bmain,const bool do_linked_only)1736 void BKE_main_id_refcount_recompute(struct Main *bmain, const bool do_linked_only)
1737 {
1738   ID *id;
1739 
1740   FOREACH_MAIN_ID_BEGIN (bmain, id) {
1741     if (!ID_IS_LINKED(id) && do_linked_only) {
1742       continue;
1743     }
1744     id->us = ID_FAKE_USERS(id);
1745     /* Note that we keep EXTRAUSER tag here, since some UI users may define it too... */
1746     if (id->tag & LIB_TAG_EXTRAUSER) {
1747       id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
1748       id_us_ensure_real(id);
1749     }
1750   }
1751   FOREACH_MAIN_ID_END;
1752 
1753   /* Go over whole Main database to re-generate proper usercounts... */
1754   FOREACH_MAIN_ID_BEGIN (bmain, id) {
1755     BKE_library_foreach_ID_link(bmain,
1756                                 id,
1757                                 id_refcount_recompute_callback,
1758                                 POINTER_FROM_INT((int)do_linked_only),
1759                                 IDWALK_READONLY | IDWALK_INCLUDE_UI);
1760   }
1761   FOREACH_MAIN_ID_END;
1762 }
1763 
library_make_local_copying_check(ID * id,GSet * loop_tags,MainIDRelations * id_relations,GSet * done_ids)1764 static void library_make_local_copying_check(ID *id,
1765                                              GSet *loop_tags,
1766                                              MainIDRelations *id_relations,
1767                                              GSet *done_ids)
1768 {
1769   if (BLI_gset_haskey(done_ids, id)) {
1770     return; /* Already checked, nothing else to do. */
1771   }
1772 
1773   MainIDRelationsEntry *entry = BLI_ghash_lookup(id_relations->id_used_to_user, id);
1774   BLI_gset_insert(loop_tags, id);
1775   for (; entry != NULL; entry = entry->next) {
1776 
1777     /* Used_to_user stores ID pointer, not pointer to ID pointer. */
1778     ID *par_id = (ID *)entry->id_pointer;
1779 
1780     /* Our oh-so-beloved 'from' pointers... Those should always be ignored here, since the actual
1781      * relation we want to check is in the other way around. */
1782     if (entry->usage_flag & IDWALK_CB_LOOPBACK) {
1783       continue;
1784     }
1785 
1786     /* Shape-keys are considered 'private' to their owner ID here, and never tagged
1787      * (since they cannot be linked), so we have to switch effective parent to their owner.
1788      */
1789     if (GS(par_id->name) == ID_KE) {
1790       par_id = ((Key *)par_id)->from;
1791     }
1792 
1793     if (par_id->lib == NULL) {
1794       /* Local user, early out to avoid some gset querying... */
1795       continue;
1796     }
1797     if (!BLI_gset_haskey(done_ids, par_id)) {
1798       if (BLI_gset_haskey(loop_tags, par_id)) {
1799         /* We are in a 'dependency loop' of IDs, this does not say us anything, skip it.
1800          * Note that this is the situation that can lead to archipelagoes of linked data-blocks
1801          * (since all of them have non-local users, they would all be duplicated,
1802          * leading to a loop of unused linked data-blocks that cannot be freed since they all use
1803          * each other...). */
1804         continue;
1805       }
1806       /* Else, recursively check that user ID. */
1807       library_make_local_copying_check(par_id, loop_tags, id_relations, done_ids);
1808     }
1809 
1810     if (par_id->tag & LIB_TAG_DOIT) {
1811       /* This user will be fully local in future, so far so good,
1812        * nothing to do here but check next user. */
1813     }
1814     else {
1815       /* This user won't be fully local in future, so current ID won't be either.
1816        * And we are done checking it. */
1817       id->tag &= ~LIB_TAG_DOIT;
1818       break;
1819     }
1820   }
1821   BLI_gset_add(done_ids, id);
1822   BLI_gset_remove(loop_tags, id, NULL);
1823 }
1824 
1825 /**
1826  * Make linked data-blocks local.
1827  *
1828  * \param bmain: Almost certainly global main.
1829  * \param lib: If not NULL, only make local data-blocks from this library.
1830  * \param untagged_only: If true, only make local data-blocks not tagged with
1831  * LIB_TAG_PRE_EXISTING.
1832  * \param set_fake: If true, set fake user on all localized data-blocks
1833  * (except group and objects ones).
1834  */
1835 /* Note: Old (2.77) version was simply making (tagging) data-blocks as local,
1836  * without actually making any check whether they were also indirectly used or not...
1837  *
1838  * Current version uses regular id_make_local callback, with advanced pre-processing step to
1839  * detect all cases of IDs currently indirectly used, but which will be used by local data only
1840  * once this function is finished.  This allows to avoid any unneeded duplication of IDs, and
1841  * hence all time lost afterwards to remove orphaned linked data-blocks...
1842  */
BKE_library_make_local(Main * bmain,const Library * lib,GHash * old_to_new_ids,const bool untagged_only,const bool set_fake)1843 void BKE_library_make_local(Main *bmain,
1844                             const Library *lib,
1845                             GHash *old_to_new_ids,
1846                             const bool untagged_only,
1847                             const bool set_fake)
1848 {
1849   ListBase *lbarray[MAX_LIBARRAY];
1850 
1851   LinkNode *todo_ids = NULL;
1852   LinkNode *copied_ids = NULL;
1853   MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
1854 
1855   GSet *done_ids = BLI_gset_ptr_new(__func__);
1856 
1857 #ifdef DEBUG_TIME
1858   TIMEIT_START(make_local);
1859 #endif
1860 
1861   BKE_main_relations_create(bmain, 0);
1862 
1863 #ifdef DEBUG_TIME
1864   printf("Pre-compute current ID relations: Done.\n");
1865   TIMEIT_VALUE_PRINT(make_local);
1866 #endif
1867 
1868   /* Step 1: Detect data-blocks to make local. */
1869   for (int a = set_listbasepointers(bmain, lbarray); a--;) {
1870     ID *id = lbarray[a]->first;
1871 
1872     /* Do not explicitly make local non-linkable IDs (shapekeys, in fact),
1873      * they are assumed to be handled by real data-blocks responsible of them. */
1874     const bool do_skip = (id && !BKE_idtype_idcode_is_linkable(GS(id->name)));
1875 
1876     for (; id; id = id->next) {
1877       ID *ntree = (ID *)ntreeFromID(id);
1878 
1879       id->tag &= ~LIB_TAG_DOIT;
1880       if (ntree != NULL) {
1881         ntree->tag &= ~LIB_TAG_DOIT;
1882       }
1883 
1884       if (id->lib == NULL) {
1885         id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1886         id->flag &= ~LIB_INDIRECT_WEAK_LINK;
1887         if (ID_IS_OVERRIDE_LIBRARY_REAL(id) &&
1888             ELEM(lib, NULL, id->override_library->reference->lib) &&
1889             ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING))) {
1890           BKE_lib_override_library_free(&id->override_library, true);
1891         }
1892       }
1893       /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so it's possible to tag data
1894        * you don't want to be made local, used for appending data,
1895        * so any libdata already linked wont become local (very nasty
1896        * to discover all your links are lost after appending).
1897        * Also, never ever make proxified objects local, would not make any sense. */
1898       /* Some more notes:
1899        *   - Shapekeys are never tagged here (since they are not linkable).
1900        *   - Nodetrees used in materials etc. have to be tagged manually,
1901        *     since they do not exist in Main (!).
1902        * This is ok-ish on 'make local' side of things
1903        * (since those are handled by their 'owner' IDs),
1904        * but complicates slightly the pre-processing of relations between IDs at step 2... */
1905       else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1906                ELEM(lib, NULL, id->lib) &&
1907                !(GS(id->name) == ID_OB && ((Object *)id)->proxy_from != NULL) &&
1908                ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING))) {
1909         BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem);
1910         id->tag |= LIB_TAG_DOIT;
1911 
1912         /* Tag those nasty non-ID nodetrees,
1913          * but do not add them to todo list, making them local is handled by 'owner' ID.
1914          * This is needed for library_make_local_copying_check() to work OK at step 2. */
1915         if (ntree != NULL) {
1916           ntree->tag |= LIB_TAG_DOIT;
1917         }
1918       }
1919       else {
1920         /* Linked ID that we won't be making local (needed info for step 2, see below). */
1921         BLI_gset_add(done_ids, id);
1922       }
1923     }
1924   }
1925 
1926 #ifdef DEBUG_TIME
1927   printf("Step 1: Detect data-blocks to make local: Done.\n");
1928   TIMEIT_VALUE_PRINT(make_local);
1929 #endif
1930 
1931   /* Step 2: Check which data-blocks we can directly make local
1932    * (because they are only used by already, or future, local data),
1933    * others will need to be duplicated. */
1934   GSet *loop_tags = BLI_gset_ptr_new(__func__);
1935   for (LinkNode *it = todo_ids; it; it = it->next) {
1936     library_make_local_copying_check(it->link, loop_tags, bmain->relations, done_ids);
1937     BLI_assert(BLI_gset_len(loop_tags) == 0);
1938   }
1939   BLI_gset_free(loop_tags, NULL);
1940   BLI_gset_free(done_ids, NULL);
1941 
1942   /* Next step will most likely add new IDs, better to get rid of this mapping now. */
1943   BKE_main_relations_free(bmain);
1944 
1945 #ifdef DEBUG_TIME
1946   printf("Step 2: Check which data-blocks we can directly make local: Done.\n");
1947   TIMEIT_VALUE_PRINT(make_local);
1948 #endif
1949 
1950   /* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
1951    * which involves more complex checks and might instead
1952    * create a local copy of original linked ID. */
1953   for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
1954     it_next = it->next;
1955     ID *id = it->link;
1956 
1957     if (id->tag & LIB_TAG_DOIT) {
1958       /* We know all users of this object are local or will be made fully local, even if
1959        * currently there are some indirect usages. So instead of making a copy that we'll likely
1960        * get rid of later, directly make that data block local.
1961        * Saves a tremendous amount of time with complex scenes... */
1962       lib_id_clear_library_data_ex(bmain, id);
1963       BKE_lib_id_expand_local(bmain, id);
1964       id->tag &= ~LIB_TAG_DOIT;
1965 
1966       if (GS(id->name) == ID_OB) {
1967         BKE_rigidbody_ensure_local_object(bmain, (Object *)id);
1968       }
1969     }
1970     else {
1971       /* In this specific case, we do want to make ID local even if it has no local usage yet...
1972        * Note that for objects, we don't want proxy pointers to be cleared yet. This will happen
1973        * down the road in this function.
1974        */
1975       BKE_lib_id_make_local(bmain,
1976                             id,
1977                             false,
1978                             LIB_ID_MAKELOCAL_FULL_LIBRARY |
1979                                 LIB_ID_MAKELOCAL_OBJECT_NO_PROXY_CLEARING);
1980 
1981       if (id->newid) {
1982         if (GS(id->newid->name) == ID_OB) {
1983           BKE_rigidbody_ensure_local_object(bmain, (Object *)id->newid);
1984         }
1985 
1986         /* Reuse already allocated LinkNode (transferring it from todo_ids to copied_ids). */
1987         BLI_linklist_prepend_nlink(&copied_ids, id, it);
1988       }
1989     }
1990 
1991     if (set_fake) {
1992       if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1993         /* do not set fake user on objects, groups (instancing) */
1994         id_fake_user_set(id);
1995       }
1996     }
1997   }
1998 
1999 #ifdef DEBUG_TIME
2000   printf("Step 3: Make IDs local: Done.\n");
2001   TIMEIT_VALUE_PRINT(make_local);
2002 #endif
2003 
2004   /* At this point, we are done with directly made local IDs.
2005    * Now we have to handle duplicated ones, since their
2006    * remaining linked original counterpart may not be needed anymore... */
2007   todo_ids = NULL;
2008 
2009   /* Step 4: We have to remap local usages of old (linked) ID to new (local)
2010    * ID in a separated loop,
2011    * as lbarray ordering is not enough to ensure us we did catch all dependencies
2012    * (e.g. if making local a parent object before its child...). See T48907. */
2013   /* TODO This is now the biggest step by far (in term of processing time).
2014    * We may be able to gain here by using again main->relations mapping, but...
2015    * this implies BKE_libblock_remap & co to be able to update main->relations on the fly.
2016    * Have to think about it a bit more, and see whether new code is OK first, anyway. */
2017   for (LinkNode *it = copied_ids; it; it = it->next) {
2018     ID *id = it->link;
2019 
2020     BLI_assert(id->newid != NULL);
2021     BLI_assert(id->lib != NULL);
2022 
2023     BKE_libblock_remap(bmain, id, id->newid, ID_REMAP_SKIP_INDIRECT_USAGE);
2024     if (old_to_new_ids) {
2025       BLI_ghash_insert(old_to_new_ids, id, id->newid);
2026     }
2027 
2028     /* Special hack for groups... Thing is, since we can't instantiate them here, we need to
2029      * ensure they remain 'alive' (only instantiation is a real group 'user'... *sigh* See
2030      * T49722. */
2031     if (GS(id->name) == ID_GR && (id->tag & LIB_TAG_INDIRECT) != 0) {
2032       id_us_ensure_real(id->newid);
2033     }
2034   }
2035 
2036 #ifdef DEBUG_TIME
2037   printf("Step 4: Remap local usages of old (linked) ID to new (local) ID: Done.\n");
2038   TIMEIT_VALUE_PRINT(make_local);
2039 #endif
2040 
2041   /* Step 5: proxy 'remapping' hack. */
2042   for (LinkNode *it = copied_ids; it; it = it->next) {
2043     ID *id = it->link;
2044 
2045     /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
2046      * from another blend file into this one, even when that blend file contains proxified
2047      * armatures that have local references. Since the proxified object needs to be linked
2048      * (not local), this will only work when the "Localize all" checkbox is disabled.
2049      * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
2050     if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
2051       Object *ob = (Object *)id;
2052       Object *ob_new = (Object *)id->newid;
2053       bool is_local = false, is_lib = false;
2054 
2055       /* Proxies only work when the proxified object is linked-in from a library. */
2056       if (ob->proxy->id.lib == NULL) {
2057         CLOG_WARN(&LOG,
2058                   "proxy object %s will lose its link to %s, because the "
2059                   "proxified object is local.",
2060                   id->newid->name,
2061                   ob->proxy->id.name);
2062         continue;
2063       }
2064 
2065       BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
2066 
2067       /* We can only switch the proxy'ing to a made-local proxy if it is no longer
2068        * referred to from a library. Not checking for local use; if new local proxy
2069        * was not used locally would be a nasty bug! */
2070       if (is_local || is_lib) {
2071         CLOG_WARN(&LOG,
2072                   "made-local proxy object %s will lose its link to %s, "
2073                   "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).",
2074                   id->newid->name,
2075                   ob->proxy->id.name,
2076                   is_local,
2077                   is_lib);
2078       }
2079       else {
2080         /* we can switch the proxy'ing from the linked-in to the made-local proxy.
2081          * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
2082          * was already allocated by object_make_local() (which called BKE_object_copy). */
2083         ob_new->proxy = ob->proxy;
2084         ob_new->proxy_group = ob->proxy_group;
2085         ob_new->proxy_from = ob->proxy_from;
2086         ob_new->proxy->proxy_from = ob_new;
2087         ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
2088       }
2089     }
2090   }
2091 
2092 #ifdef DEBUG_TIME
2093   printf("Step 5: Proxy 'remapping' hack: Done.\n");
2094   TIMEIT_VALUE_PRINT(make_local);
2095 #endif
2096 
2097   /* This is probably more of a hack than something we should do here, but...
2098    * Issue is, the whole copying + remapping done in complex cases above may leave pose-channels
2099    * of armatures in complete invalid state (more precisely, the bone pointers of the
2100    * pose-channels - very crappy cross-data-blocks relationship), se we tag it to be fully
2101    * recomputed, but this does not seems to be enough in some cases, and evaluation code ends up
2102    * trying to evaluate a not-yet-updated armature object's deformations.
2103    * Try "make all local" in 04_01_H.lighting.blend from Agent327 without this, e.g. */
2104   for (Object *ob = bmain->objects.first; ob; ob = ob->id.next) {
2105     if (ob->data != NULL && ob->type == OB_ARMATURE && ob->pose != NULL &&
2106         ob->pose->flag & POSE_RECALC) {
2107       BKE_pose_rebuild(bmain, ob, ob->data, true);
2108     }
2109   }
2110 
2111 #ifdef DEBUG_TIME
2112   printf("Hack: Forcefully rebuild armature object poses: Done.\n");
2113   TIMEIT_VALUE_PRINT(make_local);
2114 #endif
2115 
2116   BKE_main_id_clear_newpoins(bmain);
2117   BLI_memarena_free(linklist_mem);
2118 
2119 #ifdef DEBUG_TIME
2120   printf("Cleanup and finish: Done.\n");
2121   TIMEIT_END(make_local);
2122 #endif
2123 }
2124 
2125 /**
2126  * Use after setting the ID's name
2127  * When name exists: call 'new_id'
2128  */
BLI_libblock_ensure_unique_name(Main * bmain,const char * name)2129 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
2130 {
2131   ListBase *lb;
2132   ID *idtest;
2133 
2134   lb = which_libbase(bmain, GS(name));
2135   if (lb == NULL) {
2136     return;
2137   }
2138 
2139   /* search for id */
2140   idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
2141   if (idtest != NULL) {
2142     /* BKE_id_new_name_validate also takes care of sorting. */
2143     BKE_id_new_name_validate(lb, idtest, NULL);
2144     bmain->is_memfile_undo_written = false;
2145   }
2146 }
2147 
2148 /**
2149  * Sets the name of a block to name, suitably adjusted for uniqueness.
2150  */
BKE_libblock_rename(Main * bmain,ID * id,const char * name)2151 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
2152 {
2153   ListBase *lb = which_libbase(bmain, GS(id->name));
2154   if (BKE_id_new_name_validate(lb, id, name)) {
2155     bmain->is_memfile_undo_written = false;
2156   }
2157 }
2158 
2159 /**
2160  * Generate full name of the data-block (without ID code, but with library if any).
2161  *
2162  * \note Result is unique to a given ID type in a given Main database.
2163  *
2164  * \param name: An allocated string of minimal length #MAX_ID_FULL_NAME,
2165  *              will be filled with generated string.
2166  * \param separator_char: Character to use for separating name and library name. Can be 0 to use
2167  *                        default (' ').
2168  */
BKE_id_full_name_get(char name[MAX_ID_FULL_NAME],const ID * id,char separator_char)2169 void BKE_id_full_name_get(char name[MAX_ID_FULL_NAME], const ID *id, char separator_char)
2170 {
2171   strcpy(name, id->name + 2);
2172 
2173   if (id->lib != NULL) {
2174     const size_t idname_len = strlen(id->name + 2);
2175     const size_t libname_len = strlen(id->lib->id.name + 2);
2176 
2177     name[idname_len] = separator_char ? separator_char : ' ';
2178     name[idname_len + 1] = '[';
2179     strcpy(name + idname_len + 2, id->lib->id.name + 2);
2180     name[idname_len + 2 + libname_len] = ']';
2181     name[idname_len + 2 + libname_len + 1] = '\0';
2182   }
2183 }
2184 
2185 /**
2186  * Generate full name of the data-block (without ID code, but with library if any),
2187  * with a 2 to 3 character prefix prepended indicating whether it comes from a library,
2188  * is overriding, has a fake or no user, etc.
2189  *
2190  * \note Result is unique to a given ID type in a given Main database.
2191  *
2192  * \param name: An allocated string of minimal length #MAX_ID_FULL_NAME_UI,
2193  *              will be filled with generated string.
2194  * \param separator_char: Character to use for separating name and library name. Can be 0 to use
2195  *                        default (' ').
2196  * \param r_prefix_len: The length of the prefix added.
2197  */
BKE_id_full_name_ui_prefix_get(char name[MAX_ID_FULL_NAME_UI],const ID * id,const bool add_lib_hint,char separator_char,int * r_prefix_len)2198 void BKE_id_full_name_ui_prefix_get(char name[MAX_ID_FULL_NAME_UI],
2199                                     const ID *id,
2200                                     const bool add_lib_hint,
2201                                     char separator_char,
2202                                     int *r_prefix_len)
2203 {
2204   int i = 0;
2205 
2206   if (add_lib_hint) {
2207     name[i++] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ID_IS_OVERRIDE_LIBRARY(id) ? 'O' : ' ';
2208   }
2209   name[i++] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
2210   name[i++] = ' ';
2211 
2212   BKE_id_full_name_get(name + i, id, separator_char);
2213 
2214   if (r_prefix_len) {
2215     *r_prefix_len = i;
2216   }
2217 }
2218 
2219 /**
2220  * Generate a concatenation of ID name (including two-chars type code) and its lib name, if any.
2221  *
2222  * \return A unique allocated string key for any ID in the whole Main database.
2223  */
BKE_id_to_unique_string_key(const struct ID * id)2224 char *BKE_id_to_unique_string_key(const struct ID *id)
2225 {
2226   if (id->lib == NULL) {
2227     return BLI_strdup(id->name);
2228   }
2229 
2230   /* Prefix with an ascii character in the range of 32..96 (visible)
2231    * this ensures we can't have a library ID pair that collide.
2232    * Where 'LIfooOBbarOBbaz' could be ('LIfoo, OBbarOBbaz') or ('LIfooOBbar', 'OBbaz'). */
2233   const char ascii_len = strlen(id->lib->id.name + 2) + 32;
2234   return BLI_sprintfN("%c%s%s", ascii_len, id->lib->id.name, id->name);
2235 }
2236 
BKE_id_tag_set_atomic(ID * id,int tag)2237 void BKE_id_tag_set_atomic(ID *id, int tag)
2238 {
2239   atomic_fetch_and_or_int32(&id->tag, tag);
2240 }
2241 
BKE_id_tag_clear_atomic(ID * id,int tag)2242 void BKE_id_tag_clear_atomic(ID *id, int tag)
2243 {
2244   atomic_fetch_and_and_int32(&id->tag, ~tag);
2245 }
2246 
2247 /**
2248  * Check that given ID pointer actually is in G_MAIN.
2249  * Main intended use is for debug asserts in places we cannot easily get rid of G_Main...
2250  */
BKE_id_is_in_global_main(ID * id)2251 bool BKE_id_is_in_global_main(ID *id)
2252 {
2253   /* We do not want to fail when id is NULL here, even though this is a bit strange behavior...
2254    */
2255   return (id == NULL || BLI_findindex(which_libbase(G_MAIN, GS(id->name)), id) != -1);
2256 }
2257 
2258 /************************* Datablock order in UI **************************/
2259 
id_order_get(ID * id)2260 static int *id_order_get(ID *id)
2261 {
2262   /* Only for workspace tabs currently. */
2263   switch (GS(id->name)) {
2264     case ID_WS:
2265       return &((WorkSpace *)id)->order;
2266     default:
2267       return NULL;
2268   }
2269 }
2270 
id_order_compare(const void * a,const void * b)2271 static int id_order_compare(const void *a, const void *b)
2272 {
2273   ID *id_a = ((LinkData *)a)->data;
2274   ID *id_b = ((LinkData *)b)->data;
2275 
2276   int *order_a = id_order_get(id_a);
2277   int *order_b = id_order_get(id_b);
2278 
2279   if (order_a && order_b) {
2280     if (*order_a < *order_b) {
2281       return -1;
2282     }
2283     if (*order_a > *order_b) {
2284       return 1;
2285     }
2286   }
2287 
2288   return strcmp(id_a->name, id_b->name);
2289 }
2290 
2291 /**
2292  * Returns ordered list of data-blocks for display in the UI.
2293  * Result is list of LinkData of IDs that must be freed.
2294  */
BKE_id_ordered_list(ListBase * ordered_lb,const ListBase * lb)2295 void BKE_id_ordered_list(ListBase *ordered_lb, const ListBase *lb)
2296 {
2297   BLI_listbase_clear(ordered_lb);
2298 
2299   LISTBASE_FOREACH (ID *, id, lb) {
2300     BLI_addtail(ordered_lb, BLI_genericNodeN(id));
2301   }
2302 
2303   BLI_listbase_sort(ordered_lb, id_order_compare);
2304 
2305   int num = 0;
2306   LISTBASE_FOREACH (LinkData *, link, ordered_lb) {
2307     int *order = id_order_get(link->data);
2308     if (order) {
2309       *order = num++;
2310     }
2311   }
2312 }
2313 
2314 /**
2315  * Reorder ID in the list, before or after the "relative" ID.
2316  */
BKE_id_reorder(const ListBase * lb,ID * id,ID * relative,bool after)2317 void BKE_id_reorder(const ListBase *lb, ID *id, ID *relative, bool after)
2318 {
2319   int *id_order = id_order_get(id);
2320   int relative_order;
2321 
2322   if (relative) {
2323     relative_order = *id_order_get(relative);
2324   }
2325   else {
2326     relative_order = (after) ? BLI_listbase_count(lb) : 0;
2327   }
2328 
2329   if (after) {
2330     /* Insert after. */
2331     LISTBASE_FOREACH (ID *, other, lb) {
2332       int *order = id_order_get(other);
2333       if (*order > relative_order) {
2334         (*order)++;
2335       }
2336     }
2337 
2338     *id_order = relative_order + 1;
2339   }
2340   else {
2341     /* Insert before. */
2342     LISTBASE_FOREACH (ID *, other, lb) {
2343       int *order = id_order_get(other);
2344       if (*order < relative_order) {
2345         (*order)--;
2346       }
2347     }
2348 
2349     *id_order = relative_order - 1;
2350   }
2351 }
2352 
BKE_id_blend_write(BlendWriter * writer,ID * id)2353 void BKE_id_blend_write(BlendWriter *writer, ID *id)
2354 {
2355   /* ID_WM's id->properties are considered runtime only, and never written in .blend file. */
2356   if (id->properties && !ELEM(GS(id->name), ID_WM)) {
2357     IDP_BlendWrite(writer, id->properties);
2358   }
2359 
2360   if (id->override_library) {
2361     BLO_write_struct(writer, IDOverrideLibrary, id->override_library);
2362 
2363     BLO_write_struct_list(writer, IDOverrideLibraryProperty, &id->override_library->properties);
2364     LISTBASE_FOREACH (IDOverrideLibraryProperty *, op, &id->override_library->properties) {
2365       BLO_write_string(writer, op->rna_path);
2366 
2367       BLO_write_struct_list(writer, IDOverrideLibraryPropertyOperation, &op->operations);
2368       LISTBASE_FOREACH (IDOverrideLibraryPropertyOperation *, opop, &op->operations) {
2369         if (opop->subitem_reference_name) {
2370           BLO_write_string(writer, opop->subitem_reference_name);
2371         }
2372         if (opop->subitem_local_name) {
2373           BLO_write_string(writer, opop->subitem_local_name);
2374         }
2375       }
2376     }
2377   }
2378 }
2379