92ed6ea4e04d7c79e12ca8e66a9cc3506ba8f3d9
[blender.git] / source / blender / blenkernel / intern / library_query.c
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) 2014 by Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24 #include <stdlib.h>
25
26 #include "MEM_guardedalloc.h"
27
28 #include "DNA_anim_types.h"
29 #include "DNA_armature_types.h"
30 #include "DNA_brush_types.h"
31 #include "DNA_camera_types.h"
32 #include "DNA_collection_types.h"
33 #include "DNA_constraint_types.h"
34 #include "DNA_gpencil_types.h"
35 #include "DNA_key_types.h"
36 #include "DNA_light_types.h"
37 #include "DNA_lattice_types.h"
38 #include "DNA_linestyle_types.h"
39 #include "DNA_material_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_meta_types.h"
43 #include "DNA_movieclip_types.h"
44 #include "DNA_mask_types.h"
45 #include "DNA_node_types.h"
46 #include "DNA_object_force_types.h"
47 #include "DNA_lightprobe_types.h"
48 #include "DNA_rigidbody_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_sequence_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_speaker_types.h"
53 #include "DNA_sound_types.h"
54 #include "DNA_text_types.h"
55 #include "DNA_vfont_types.h"
56 #include "DNA_windowmanager_types.h"
57 #include "DNA_workspace_types.h"
58 #include "DNA_world_types.h"
59
60 #include "BLI_utildefines.h"
61 #include "BLI_ghash.h"
62 #include "BLI_linklist_stack.h"
63
64 #include "BKE_animsys.h"
65 #include "BKE_collection.h"
66 #include "BKE_constraint.h"
67 #include "BKE_fcurve.h"
68 #include "BKE_gpencil_modifier.h"
69 #include "BKE_idprop.h"
70 #include "BKE_library.h"
71 #include "BKE_library_query.h"
72 #include "BKE_main.h"
73 #include "BKE_modifier.h"
74 #include "BKE_node.h"
75 #include "BKE_particle.h"
76 #include "BKE_rigidbody.h"
77 #include "BKE_sequencer.h"
78 #include "BKE_shader_fx.h"
79 #include "BKE_tracking.h"
80 #include "BKE_workspace.h"
81
82 #define FOREACH_FINALIZE _finalize
83 #define FOREACH_FINALIZE_VOID \
84   if (0) { \
85     goto FOREACH_FINALIZE; \
86   } \
87   FOREACH_FINALIZE: \
88   ((void)0)
89
90 #define FOREACH_CALLBACK_INVOKE_ID_PP(_data, id_pp, _cb_flag) \
91   CHECK_TYPE(id_pp, ID **); \
92   if (!((_data)->status & IDWALK_STOP)) { \
93     const int _flag = (_data)->flag; \
94     ID *old_id = *(id_pp); \
95     const int callback_return = (_data)->callback((_data)->user_data, \
96                                                   (_data)->self_id, \
97                                                   id_pp, \
98                                                   (_cb_flag | (_data)->cb_flag) & \
99                                                       ~(_data)->cb_flag_clear); \
100     if (_flag & IDWALK_READONLY) { \
101       BLI_assert(*(id_pp) == old_id); \
102     } \
103     if (old_id && (_flag & IDWALK_RECURSE)) { \
104       if (BLI_gset_add((_data)->ids_handled, old_id)) { \
105         if (!(callback_return & IDWALK_RET_STOP_RECURSION)) { \
106           BLI_LINKSTACK_PUSH((_data)->ids_todo, old_id); \
107         } \
108       } \
109     } \
110     if (callback_return & IDWALK_RET_STOP_ITER) { \
111       (_data)->status |= IDWALK_STOP; \
112       goto FOREACH_FINALIZE; \
113     } \
114   } \
115   else { \
116     goto FOREACH_FINALIZE; \
117   } \
118   ((void)0)
119
120 #define FOREACH_CALLBACK_INVOKE_ID(_data, id, cb_flag) \
121   { \
122     CHECK_TYPE_ANY(id, ID *, void *); \
123     FOREACH_CALLBACK_INVOKE_ID_PP(_data, (ID **)&(id), cb_flag); \
124   } \
125   ((void)0)
126
127 #define FOREACH_CALLBACK_INVOKE(_data, id_super, cb_flag) \
128   { \
129     CHECK_TYPE(&((id_super)->id), ID *); \
130     FOREACH_CALLBACK_INVOKE_ID_PP(_data, (ID **)&(id_super), cb_flag); \
131   } \
132   ((void)0)
133
134 /* status */
135 enum {
136   IDWALK_STOP = 1 << 0,
137 };
138
139 typedef struct LibraryForeachIDData {
140   ID *self_id;
141   int flag;
142   int cb_flag;
143   int cb_flag_clear;
144   LibraryIDLinkCallback callback;
145   void *user_data;
146   int status;
147
148   /* To handle recursion. */
149   GSet *ids_handled; /* All IDs that are either already done, or still in ids_todo stack. */
150   BLI_LINKSTACK_DECLARE(ids_todo, ID *);
151 } LibraryForeachIDData;
152
153 static void library_foreach_ID_link(Main *bmain,
154                                     ID *id,
155                                     LibraryIDLinkCallback callback,
156                                     void *user_data,
157                                     int flag,
158                                     LibraryForeachIDData *inherit_data);
159
160 static void library_foreach_idproperty_ID_link(LibraryForeachIDData *data,
161                                                IDProperty *prop,
162                                                int flag)
163 {
164   if (!prop) {
165     return;
166   }
167
168   switch (prop->type) {
169     case IDP_GROUP: {
170       for (IDProperty *loop = prop->data.group.first; loop; loop = loop->next) {
171         library_foreach_idproperty_ID_link(data, loop, flag);
172       }
173       break;
174     }
175     case IDP_IDPARRAY: {
176       IDProperty *loop = IDP_Array(prop);
177       for (int i = 0; i < prop->len; i++) {
178         library_foreach_idproperty_ID_link(data, &loop[i], flag);
179       }
180       break;
181     }
182     case IDP_ID:
183       FOREACH_CALLBACK_INVOKE_ID(data, prop->data.pointer, flag);
184       break;
185     default:
186       break; /* Nothing to do here with other types of IDProperties... */
187   }
188
189   FOREACH_FINALIZE_VOID;
190 }
191
192 static void library_foreach_rigidbodyworldSceneLooper(struct RigidBodyWorld *UNUSED(rbw),
193                                                       ID **id_pointer,
194                                                       void *user_data,
195                                                       int cb_flag)
196 {
197   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
198   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
199
200   FOREACH_FINALIZE_VOID;
201 }
202
203 static void library_foreach_modifiersForeachIDLink(void *user_data,
204                                                    Object *UNUSED(object),
205                                                    ID **id_pointer,
206                                                    int cb_flag)
207 {
208   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
209   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
210
211   FOREACH_FINALIZE_VOID;
212 }
213
214 static void library_foreach_gpencil_modifiersForeachIDLink(void *user_data,
215                                                            Object *UNUSED(object),
216                                                            ID **id_pointer,
217                                                            int cb_flag)
218 {
219   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
220   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
221
222   FOREACH_FINALIZE_VOID;
223 }
224
225 static void library_foreach_shaderfxForeachIDLink(void *user_data,
226                                                   Object *UNUSED(object),
227                                                   ID **id_pointer,
228                                                   int cb_flag)
229 {
230   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
231   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
232
233   FOREACH_FINALIZE_VOID;
234 }
235
236 static void library_foreach_constraintObjectLooper(bConstraint *UNUSED(con),
237                                                    ID **id_pointer,
238                                                    bool is_reference,
239                                                    void *user_data)
240 {
241   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
242   const int cb_flag = is_reference ? IDWALK_CB_USER : IDWALK_CB_NOP;
243   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
244
245   FOREACH_FINALIZE_VOID;
246 }
247
248 static void library_foreach_particlesystemsObjectLooper(ParticleSystem *UNUSED(psys),
249                                                         ID **id_pointer,
250                                                         void *user_data,
251                                                         int cb_flag)
252 {
253   LibraryForeachIDData *data = (LibraryForeachIDData *)user_data;
254   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
255
256   FOREACH_FINALIZE_VOID;
257 }
258
259 static void library_foreach_nla_strip(LibraryForeachIDData *data, NlaStrip *strip)
260 {
261   NlaStrip *substrip;
262
263   FOREACH_CALLBACK_INVOKE(data, strip->act, IDWALK_CB_USER);
264
265   for (substrip = strip->strips.first; substrip; substrip = substrip->next) {
266     library_foreach_nla_strip(data, substrip);
267   }
268
269   FOREACH_FINALIZE_VOID;
270 }
271
272 static void library_foreach_animationData(LibraryForeachIDData *data, AnimData *adt)
273 {
274   FCurve *fcu;
275   NlaTrack *nla_track;
276   NlaStrip *nla_strip;
277
278   for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
279     ChannelDriver *driver = fcu->driver;
280     DriverVar *dvar;
281
282     for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
283       /* only used targets */
284       DRIVER_TARGETS_USED_LOOPER_BEGIN (dvar) {
285         FOREACH_CALLBACK_INVOKE_ID(data, dtar->id, IDWALK_CB_NOP);
286       }
287       DRIVER_TARGETS_LOOPER_END;
288     }
289   }
290
291   FOREACH_CALLBACK_INVOKE(data, adt->action, IDWALK_CB_USER);
292   FOREACH_CALLBACK_INVOKE(data, adt->tmpact, IDWALK_CB_USER);
293
294   for (nla_track = adt->nla_tracks.first; nla_track; nla_track = nla_track->next) {
295     for (nla_strip = nla_track->strips.first; nla_strip; nla_strip = nla_strip->next) {
296       library_foreach_nla_strip(data, nla_strip);
297     }
298   }
299
300   FOREACH_FINALIZE_VOID;
301 }
302
303 static void library_foreach_mtex(LibraryForeachIDData *data, MTex *mtex)
304 {
305   FOREACH_CALLBACK_INVOKE(data, mtex->object, IDWALK_CB_NOP);
306   FOREACH_CALLBACK_INVOKE(data, mtex->tex, IDWALK_CB_USER);
307
308   FOREACH_FINALIZE_VOID;
309 }
310
311 static void library_foreach_paint(LibraryForeachIDData *data, Paint *paint)
312 {
313   FOREACH_CALLBACK_INVOKE(data, paint->brush, IDWALK_CB_USER);
314   for (int i = 0; i < paint->tool_slots_len; i++) {
315     FOREACH_CALLBACK_INVOKE(data, paint->tool_slots[i].brush, IDWALK_CB_USER);
316   }
317   FOREACH_CALLBACK_INVOKE(data, paint->palette, IDWALK_CB_USER);
318
319   FOREACH_FINALIZE_VOID;
320 }
321
322 static void library_foreach_bone(LibraryForeachIDData *data, Bone *bone)
323 {
324   library_foreach_idproperty_ID_link(data, bone->prop, IDWALK_CB_USER);
325
326   for (Bone *curbone = bone->childbase.first; curbone; curbone = curbone->next) {
327     library_foreach_bone(data, curbone);
328   }
329
330   FOREACH_FINALIZE_VOID;
331 }
332
333 static void library_foreach_layer_collection(LibraryForeachIDData *data, ListBase *lb)
334 {
335   for (LayerCollection *lc = lb->first; lc; lc = lc->next) {
336     FOREACH_CALLBACK_INVOKE(data, lc->collection, IDWALK_CB_NOP);
337     library_foreach_layer_collection(data, &lc->layer_collections);
338   }
339
340   FOREACH_FINALIZE_VOID;
341 }
342
343 static void library_foreach_ID_as_subdata_link(ID **id_pp,
344                                                LibraryIDLinkCallback callback,
345                                                void *user_data,
346                                                int flag,
347                                                LibraryForeachIDData *data)
348 {
349   /* Needed e.g. for callbacks handling relationships... This call shall be absolutely readonly. */
350   ID *id = *id_pp;
351   FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pp, IDWALK_CB_PRIVATE);
352   BLI_assert(id == *id_pp);
353
354   if (flag & IDWALK_RECURSE) {
355     /* Defer handling into main loop, recursively calling BKE_library_foreach_ID_link in IDWALK_RECURSE case is
356      * troublesome, see T49553. */
357     if (BLI_gset_add(data->ids_handled, id)) {
358       BLI_LINKSTACK_PUSH(data->ids_todo, id);
359     }
360   }
361   else {
362     library_foreach_ID_link(NULL, id, callback, user_data, flag, data);
363   }
364
365   FOREACH_FINALIZE_VOID;
366 }
367
368 static void library_foreach_ID_link(Main *bmain,
369                                     ID *id,
370                                     LibraryIDLinkCallback callback,
371                                     void *user_data,
372                                     int flag,
373                                     LibraryForeachIDData *inherit_data)
374 {
375   LibraryForeachIDData data;
376   int i;
377
378   if (flag & IDWALK_RECURSE) {
379     /* For now, recusion implies read-only. */
380     flag |= IDWALK_READONLY;
381
382     data.ids_handled = BLI_gset_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
383     BLI_LINKSTACK_INIT(data.ids_todo);
384
385     BLI_gset_add(data.ids_handled, id);
386   }
387   else {
388     data.ids_handled = NULL;
389   }
390   data.flag = flag;
391   data.status = 0;
392   data.callback = callback;
393   data.user_data = user_data;
394
395 #define CALLBACK_INVOKE_ID(check_id, cb_flag) FOREACH_CALLBACK_INVOKE_ID(&data, check_id, cb_flag)
396
397 #define CALLBACK_INVOKE(check_id_super, cb_flag) \
398   FOREACH_CALLBACK_INVOKE(&data, check_id_super, cb_flag)
399
400   for (; id != NULL; id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL) {
401     data.self_id = id;
402
403     /* inherit_data is non-NULL when this function is called for some sub-data ID
404      * (like root nodetree of a material).
405      * In that case, we do not want to generate those 'generic flags' from our current sub-data ID (the node tree),
406      * but re-use those generated for the 'owner' ID (the material)... */
407     if (inherit_data == NULL) {
408       data.cb_flag = ID_IS_LINKED(id) ? IDWALK_CB_INDIRECT_USAGE : 0;
409       /* When an ID is not in Main database, it should never refcount IDs it is using.
410        * Exceptions: NodeTrees (yeeahhh!) directly used by Materials. */
411       data.cb_flag_clear = (id->tag & LIB_TAG_NO_MAIN) ? IDWALK_CB_USER | IDWALK_CB_USER_ONE : 0;
412     }
413     else {
414       data.cb_flag = inherit_data->cb_flag;
415       data.cb_flag_clear = inherit_data->cb_flag_clear;
416     }
417
418     if (bmain != NULL && bmain->relations != NULL && (flag & IDWALK_READONLY)) {
419       /* Note that this is minor optimization, even in worst cases (like id being an object with lots of
420        * drivers and constraints and modifiers, or material etc. with huge node tree),
421        * but we might as well use it (Main->relations is always assumed valid, it's responsibility of code
422        * creating it to free it, especially if/when it starts modifying Main database). */
423       MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->id_user_to_used, id);
424       for (; entry != NULL; entry = entry->next) {
425         FOREACH_CALLBACK_INVOKE_ID_PP(&data, entry->id_pointer, entry->usage_flag);
426       }
427       continue;
428     }
429
430     if (id->override_static != NULL) {
431       CALLBACK_INVOKE_ID(id->override_static->reference,
432                          IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE);
433       CALLBACK_INVOKE_ID(id->override_static->storage,
434                          IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE);
435     }
436
437     library_foreach_idproperty_ID_link(&data, id->properties, IDWALK_CB_USER);
438
439     AnimData *adt = BKE_animdata_from_id(id);
440     if (adt) {
441       library_foreach_animationData(&data, adt);
442     }
443
444     switch ((ID_Type)GS(id->name)) {
445       case ID_LI: {
446         Library *lib = (Library *)id;
447         CALLBACK_INVOKE(lib->parent, IDWALK_CB_NEVER_SELF);
448         break;
449       }
450       case ID_SCE: {
451         Scene *scene = (Scene *)id;
452         ToolSettings *toolsett = scene->toolsettings;
453
454         CALLBACK_INVOKE(scene->camera, IDWALK_CB_NOP);
455         CALLBACK_INVOKE(scene->world, IDWALK_CB_USER);
456         CALLBACK_INVOKE(scene->set, IDWALK_CB_NEVER_SELF);
457         CALLBACK_INVOKE(scene->clip, IDWALK_CB_USER);
458         CALLBACK_INVOKE(scene->r.bake.cage_object, IDWALK_CB_NOP);
459         if (scene->nodetree) {
460           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
461           library_foreach_ID_as_subdata_link(
462               (ID **)&scene->nodetree, callback, user_data, flag, &data);
463         }
464         if (scene->ed) {
465           Sequence *seq;
466           SEQP_BEGIN (scene->ed, seq) {
467             CALLBACK_INVOKE(seq->scene, IDWALK_CB_NEVER_SELF);
468             CALLBACK_INVOKE(seq->scene_camera, IDWALK_CB_NOP);
469             CALLBACK_INVOKE(seq->clip, IDWALK_CB_USER);
470             CALLBACK_INVOKE(seq->mask, IDWALK_CB_USER);
471             CALLBACK_INVOKE(seq->sound, IDWALK_CB_USER);
472             library_foreach_idproperty_ID_link(&data, seq->prop, IDWALK_CB_USER);
473             for (SequenceModifierData *smd = seq->modifiers.first; smd; smd = smd->next) {
474               CALLBACK_INVOKE(smd->mask_id, IDWALK_CB_USER);
475             }
476
477             if (seq->type == SEQ_TYPE_TEXT && seq->effectdata) {
478               TextVars *text_data = seq->effectdata;
479               CALLBACK_INVOKE(text_data->text_font, IDWALK_CB_USER);
480             }
481           }
482           SEQ_END;
483         }
484
485         for (CollectionObject *cob = scene->master_collection->gobject.first; cob;
486              cob = cob->next) {
487           CALLBACK_INVOKE(cob->ob, IDWALK_CB_USER);
488         }
489         for (CollectionChild *child = scene->master_collection->children.first; child;
490              child = child->next) {
491           CALLBACK_INVOKE(child->collection, IDWALK_CB_USER);
492         }
493
494         ViewLayer *view_layer;
495         for (view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
496           CALLBACK_INVOKE(view_layer->mat_override, IDWALK_CB_USER);
497
498           for (Base *base = view_layer->object_bases.first; base; base = base->next) {
499             CALLBACK_INVOKE(base->object, IDWALK_CB_NOP);
500           }
501
502           library_foreach_layer_collection(&data, &view_layer->layer_collections);
503
504           for (FreestyleModuleConfig *fmc = view_layer->freestyle_config.modules.first; fmc;
505                fmc = fmc->next) {
506             if (fmc->script) {
507               CALLBACK_INVOKE(fmc->script, IDWALK_CB_NOP);
508             }
509           }
510
511           for (FreestyleLineSet *fls = view_layer->freestyle_config.linesets.first; fls;
512                fls = fls->next) {
513             if (fls->group) {
514               CALLBACK_INVOKE(fls->group, IDWALK_CB_USER);
515             }
516
517             if (fls->linestyle) {
518               CALLBACK_INVOKE(fls->linestyle, IDWALK_CB_USER);
519             }
520           }
521         }
522
523         for (TimeMarker *marker = scene->markers.first; marker; marker = marker->next) {
524           CALLBACK_INVOKE(marker->camera, IDWALK_CB_NOP);
525         }
526
527         if (toolsett) {
528           CALLBACK_INVOKE(toolsett->particle.scene, IDWALK_CB_NOP);
529           CALLBACK_INVOKE(toolsett->particle.object, IDWALK_CB_NOP);
530           CALLBACK_INVOKE(toolsett->particle.shape_object, IDWALK_CB_NOP);
531
532           library_foreach_paint(&data, &toolsett->imapaint.paint);
533           CALLBACK_INVOKE(toolsett->imapaint.stencil, IDWALK_CB_USER);
534           CALLBACK_INVOKE(toolsett->imapaint.clone, IDWALK_CB_USER);
535           CALLBACK_INVOKE(toolsett->imapaint.canvas, IDWALK_CB_USER);
536
537           if (toolsett->vpaint) {
538             library_foreach_paint(&data, &toolsett->vpaint->paint);
539           }
540           if (toolsett->wpaint) {
541             library_foreach_paint(&data, &toolsett->wpaint->paint);
542           }
543           if (toolsett->sculpt) {
544             library_foreach_paint(&data, &toolsett->sculpt->paint);
545             CALLBACK_INVOKE(toolsett->sculpt->gravity_object, IDWALK_CB_NOP);
546           }
547           if (toolsett->uvsculpt) {
548             library_foreach_paint(&data, &toolsett->uvsculpt->paint);
549           }
550           if (toolsett->gp_paint) {
551             library_foreach_paint(&data, &toolsett->gp_paint->paint);
552           }
553
554           CALLBACK_INVOKE(toolsett->gp_sculpt.guide.reference_object, IDWALK_CB_NOP);
555         }
556
557         if (scene->rigidbody_world) {
558           BKE_rigidbody_world_id_loop(
559               scene->rigidbody_world, library_foreach_rigidbodyworldSceneLooper, &data);
560         }
561
562         break;
563       }
564
565       case ID_OB: {
566         Object *object = (Object *)id;
567         ParticleSystem *psys;
568
569         /* Object is special, proxies make things hard... */
570         const int data_cb_flag = data.cb_flag;
571         const int proxy_cb_flag = ((data.flag & IDWALK_NO_INDIRECT_PROXY_DATA_USAGE) == 0 &&
572                                    (object->proxy || object->proxy_group)) ?
573                                       IDWALK_CB_INDIRECT_USAGE :
574                                       0;
575
576         /* object data special case */
577         data.cb_flag |= proxy_cb_flag;
578         if (object->type == OB_EMPTY) {
579           /* empty can have NULL or Image */
580           CALLBACK_INVOKE_ID(object->data, IDWALK_CB_USER);
581         }
582         else {
583           /* when set, this can't be NULL */
584           if (object->data) {
585             CALLBACK_INVOKE_ID(object->data, IDWALK_CB_USER | IDWALK_CB_NEVER_NULL);
586           }
587         }
588         data.cb_flag = data_cb_flag;
589
590         CALLBACK_INVOKE(object->parent, IDWALK_CB_NEVER_SELF);
591         CALLBACK_INVOKE(object->track, IDWALK_CB_NEVER_SELF);
592         /* object->proxy is refcounted, but not object->proxy_group... *sigh* */
593         CALLBACK_INVOKE(object->proxy, IDWALK_CB_NEVER_SELF);
594         CALLBACK_INVOKE(object->proxy_group, IDWALK_CB_NOP);
595
596         /* Special case!
597          * Since this field is set/owned by 'user' of this ID (and not ID itself), it is only indirect usage
598          * if proxy object is linked... Twisted. */
599         if (object->proxy_from) {
600           data.cb_flag = ID_IS_LINKED(object->proxy_from) ? IDWALK_CB_INDIRECT_USAGE : 0;
601         }
602         CALLBACK_INVOKE(object->proxy_from, IDWALK_CB_LOOPBACK | IDWALK_CB_NEVER_SELF);
603         data.cb_flag = data_cb_flag;
604
605         CALLBACK_INVOKE(object->poselib, IDWALK_CB_USER);
606
607         data.cb_flag |= proxy_cb_flag;
608         for (i = 0; i < object->totcol; i++) {
609           CALLBACK_INVOKE(object->mat[i], IDWALK_CB_USER);
610         }
611         data.cb_flag = data_cb_flag;
612
613         /* Note that ob->gpd is deprecated, so no need to handle it here. */
614         CALLBACK_INVOKE(object->instance_collection, IDWALK_CB_USER);
615
616         if (object->pd) {
617           CALLBACK_INVOKE(object->pd->tex, IDWALK_CB_USER);
618           CALLBACK_INVOKE(object->pd->f_source, IDWALK_CB_NOP);
619         }
620         /* Note that ob->effect is deprecated, so no need to handle it here. */
621
622         if (object->pose) {
623           bPoseChannel *pchan;
624
625           data.cb_flag |= proxy_cb_flag;
626           for (pchan = object->pose->chanbase.first; pchan; pchan = pchan->next) {
627             library_foreach_idproperty_ID_link(&data, pchan->prop, IDWALK_CB_USER);
628             CALLBACK_INVOKE(pchan->custom, IDWALK_CB_USER);
629             BKE_constraints_id_loop(
630                 &pchan->constraints, library_foreach_constraintObjectLooper, &data);
631           }
632           data.cb_flag = data_cb_flag;
633         }
634
635         if (object->rigidbody_constraint) {
636           CALLBACK_INVOKE(object->rigidbody_constraint->ob1, IDWALK_CB_NEVER_SELF);
637           CALLBACK_INVOKE(object->rigidbody_constraint->ob2, IDWALK_CB_NEVER_SELF);
638         }
639
640         if (object->lodlevels.first) {
641           LodLevel *level;
642           for (level = object->lodlevels.first; level; level = level->next) {
643             CALLBACK_INVOKE(level->source, IDWALK_CB_NEVER_SELF);
644           }
645         }
646
647         modifiers_foreachIDLink(object, library_foreach_modifiersForeachIDLink, &data);
648         BKE_gpencil_modifiers_foreachIDLink(
649             object, library_foreach_gpencil_modifiersForeachIDLink, &data);
650         BKE_constraints_id_loop(
651             &object->constraints, library_foreach_constraintObjectLooper, &data);
652         BKE_shaderfx_foreachIDLink(object, library_foreach_shaderfxForeachIDLink, &data);
653
654         for (psys = object->particlesystem.first; psys; psys = psys->next) {
655           BKE_particlesystem_id_loop(psys, library_foreach_particlesystemsObjectLooper, &data);
656         }
657
658         if (object->soft) {
659           CALLBACK_INVOKE(object->soft->collision_group, IDWALK_CB_NOP);
660
661           if (object->soft->effector_weights) {
662             CALLBACK_INVOKE(object->soft->effector_weights->group, IDWALK_CB_NOP);
663           }
664         }
665         break;
666       }
667
668       case ID_AR: {
669         bArmature *arm = (bArmature *)id;
670
671         for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
672           library_foreach_bone(&data, bone);
673         }
674         break;
675       }
676
677       case ID_ME: {
678         Mesh *mesh = (Mesh *)id;
679         CALLBACK_INVOKE(mesh->texcomesh, IDWALK_CB_NEVER_SELF);
680         CALLBACK_INVOKE(mesh->key, IDWALK_CB_USER);
681         for (i = 0; i < mesh->totcol; i++) {
682           CALLBACK_INVOKE(mesh->mat[i], IDWALK_CB_USER);
683         }
684         break;
685       }
686
687       case ID_CU: {
688         Curve *curve = (Curve *)id;
689         CALLBACK_INVOKE(curve->bevobj, IDWALK_CB_NOP);
690         CALLBACK_INVOKE(curve->taperobj, IDWALK_CB_NOP);
691         CALLBACK_INVOKE(curve->textoncurve, IDWALK_CB_NOP);
692         CALLBACK_INVOKE(curve->key, IDWALK_CB_USER);
693         for (i = 0; i < curve->totcol; i++) {
694           CALLBACK_INVOKE(curve->mat[i], IDWALK_CB_USER);
695         }
696         CALLBACK_INVOKE(curve->vfont, IDWALK_CB_USER);
697         CALLBACK_INVOKE(curve->vfontb, IDWALK_CB_USER);
698         CALLBACK_INVOKE(curve->vfonti, IDWALK_CB_USER);
699         CALLBACK_INVOKE(curve->vfontbi, IDWALK_CB_USER);
700         break;
701       }
702
703       case ID_MB: {
704         MetaBall *metaball = (MetaBall *)id;
705         for (i = 0; i < metaball->totcol; i++) {
706           CALLBACK_INVOKE(metaball->mat[i], IDWALK_CB_USER);
707         }
708         break;
709       }
710
711       case ID_MA: {
712         Material *material = (Material *)id;
713         if (material->nodetree) {
714           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
715           library_foreach_ID_as_subdata_link(
716               (ID **)&material->nodetree, callback, user_data, flag, &data);
717         }
718         if (material->texpaintslot != NULL) {
719           CALLBACK_INVOKE(material->texpaintslot->ima, IDWALK_CB_NOP);
720         }
721         if (material->gp_style != NULL) {
722           CALLBACK_INVOKE(material->gp_style->sima, IDWALK_CB_USER);
723           CALLBACK_INVOKE(material->gp_style->ima, IDWALK_CB_USER);
724         }
725         break;
726       }
727
728       case ID_TE: {
729         Tex *texture = (Tex *)id;
730         if (texture->nodetree) {
731           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
732           library_foreach_ID_as_subdata_link(
733               (ID **)&texture->nodetree, callback, user_data, flag, &data);
734         }
735         CALLBACK_INVOKE(texture->ima, IDWALK_CB_USER);
736         break;
737       }
738
739       case ID_LT: {
740         Lattice *lattice = (Lattice *)id;
741         CALLBACK_INVOKE(lattice->key, IDWALK_CB_USER);
742         break;
743       }
744
745       case ID_LA: {
746         Light *lamp = (Light *)id;
747         if (lamp->nodetree) {
748           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
749           library_foreach_ID_as_subdata_link(
750               (ID **)&lamp->nodetree, callback, user_data, flag, &data);
751         }
752         break;
753       }
754
755       case ID_CA: {
756         Camera *camera = (Camera *)id;
757         CALLBACK_INVOKE(camera->dof_ob, IDWALK_CB_NOP);
758         for (CameraBGImage *bgpic = camera->bg_images.first; bgpic; bgpic = bgpic->next) {
759           if (bgpic->source == CAM_BGIMG_SOURCE_IMAGE) {
760             CALLBACK_INVOKE(bgpic->ima, IDWALK_CB_USER);
761           }
762           else if (bgpic->source == CAM_BGIMG_SOURCE_MOVIE) {
763             CALLBACK_INVOKE(bgpic->clip, IDWALK_CB_USER);
764           }
765         }
766
767         break;
768       }
769
770       case ID_KE: {
771         Key *key = (Key *)id;
772         CALLBACK_INVOKE_ID(key->from, IDWALK_CB_LOOPBACK);
773         break;
774       }
775
776       case ID_WO: {
777         World *world = (World *)id;
778         if (world->nodetree) {
779           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
780           library_foreach_ID_as_subdata_link(
781               (ID **)&world->nodetree, callback, user_data, flag, &data);
782         }
783         break;
784       }
785
786       case ID_SPK: {
787         Speaker *speaker = (Speaker *)id;
788         CALLBACK_INVOKE(speaker->sound, IDWALK_CB_USER);
789         break;
790       }
791
792       case ID_LP: {
793         LightProbe *probe = (LightProbe *)id;
794         CALLBACK_INVOKE(probe->image, IDWALK_CB_USER);
795         CALLBACK_INVOKE(probe->visibility_grp, IDWALK_CB_NOP);
796         break;
797       }
798
799       case ID_GR: {
800         Collection *collection = (Collection *)id;
801         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
802           CALLBACK_INVOKE(cob->ob, IDWALK_CB_USER);
803         }
804         for (CollectionChild *child = collection->children.first; child; child = child->next) {
805           CALLBACK_INVOKE(child->collection, IDWALK_CB_NEVER_SELF | IDWALK_CB_USER);
806         }
807         for (CollectionParent *parent = collection->parents.first; parent; parent = parent->next) {
808           CALLBACK_INVOKE(parent->collection, IDWALK_CB_NEVER_SELF | IDWALK_CB_LOOPBACK);
809         }
810         break;
811       }
812
813       case ID_NT: {
814         bNodeTree *ntree = (bNodeTree *)id;
815         bNode *node;
816         bNodeSocket *sock;
817
818         CALLBACK_INVOKE(ntree->gpd, IDWALK_CB_USER);
819
820         for (node = ntree->nodes.first; node; node = node->next) {
821           CALLBACK_INVOKE_ID(node->id, IDWALK_CB_USER);
822
823           library_foreach_idproperty_ID_link(&data, node->prop, IDWALK_CB_USER);
824           for (sock = node->inputs.first; sock; sock = sock->next) {
825             library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
826           }
827           for (sock = node->outputs.first; sock; sock = sock->next) {
828             library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
829           }
830         }
831
832         for (sock = ntree->inputs.first; sock; sock = sock->next) {
833           library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
834         }
835         for (sock = ntree->outputs.first; sock; sock = sock->next) {
836           library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
837         }
838         break;
839       }
840
841       case ID_BR: {
842         Brush *brush = (Brush *)id;
843         CALLBACK_INVOKE(brush->toggle_brush, IDWALK_CB_NOP);
844         CALLBACK_INVOKE(brush->clone.image, IDWALK_CB_NOP);
845         CALLBACK_INVOKE(brush->paint_curve, IDWALK_CB_USER);
846         if (brush->gpencil_settings) {
847           CALLBACK_INVOKE(brush->gpencil_settings->material, IDWALK_CB_USER);
848         }
849         library_foreach_mtex(&data, &brush->mtex);
850         library_foreach_mtex(&data, &brush->mask_mtex);
851         break;
852       }
853
854       case ID_PA: {
855         ParticleSettings *psett = (ParticleSettings *)id;
856         CALLBACK_INVOKE(psett->instance_collection, IDWALK_CB_USER);
857         CALLBACK_INVOKE(psett->instance_object, IDWALK_CB_NOP);
858         CALLBACK_INVOKE(psett->bb_ob, IDWALK_CB_NOP);
859         CALLBACK_INVOKE(psett->collision_group, IDWALK_CB_NOP);
860
861         for (i = 0; i < MAX_MTEX; i++) {
862           if (psett->mtex[i]) {
863             library_foreach_mtex(&data, psett->mtex[i]);
864           }
865         }
866
867         if (psett->effector_weights) {
868           CALLBACK_INVOKE(psett->effector_weights->group, IDWALK_CB_NOP);
869         }
870
871         if (psett->pd) {
872           CALLBACK_INVOKE(psett->pd->tex, IDWALK_CB_USER);
873           CALLBACK_INVOKE(psett->pd->f_source, IDWALK_CB_NOP);
874         }
875         if (psett->pd2) {
876           CALLBACK_INVOKE(psett->pd2->tex, IDWALK_CB_USER);
877           CALLBACK_INVOKE(psett->pd2->f_source, IDWALK_CB_NOP);
878         }
879
880         if (psett->boids) {
881           BoidState *state;
882           BoidRule *rule;
883
884           for (state = psett->boids->states.first; state; state = state->next) {
885             for (rule = state->rules.first; rule; rule = rule->next) {
886               if (rule->type == eBoidRuleType_Avoid) {
887                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
888                 CALLBACK_INVOKE(gabr->ob, IDWALK_CB_NOP);
889               }
890               else if (rule->type == eBoidRuleType_FollowLeader) {
891                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
892                 CALLBACK_INVOKE(flbr->ob, IDWALK_CB_NOP);
893               }
894             }
895           }
896         }
897
898         for (ParticleDupliWeight *dw = psett->instance_weights.first; dw; dw = dw->next) {
899           CALLBACK_INVOKE(dw->ob, IDWALK_CB_NOP);
900         }
901         break;
902       }
903
904       case ID_MC: {
905         MovieClip *clip = (MovieClip *)id;
906         MovieTracking *tracking = &clip->tracking;
907         MovieTrackingObject *object;
908         MovieTrackingTrack *track;
909         MovieTrackingPlaneTrack *plane_track;
910
911         CALLBACK_INVOKE(clip->gpd, IDWALK_CB_USER);
912
913         for (track = tracking->tracks.first; track; track = track->next) {
914           CALLBACK_INVOKE(track->gpd, IDWALK_CB_USER);
915         }
916         for (object = tracking->objects.first; object; object = object->next) {
917           for (track = object->tracks.first; track; track = track->next) {
918             CALLBACK_INVOKE(track->gpd, IDWALK_CB_USER);
919           }
920         }
921
922         for (plane_track = tracking->plane_tracks.first; plane_track;
923              plane_track = plane_track->next) {
924           CALLBACK_INVOKE(plane_track->image, IDWALK_CB_USER);
925         }
926         break;
927       }
928
929       case ID_MSK: {
930         Mask *mask = (Mask *)id;
931         MaskLayer *mask_layer;
932         for (mask_layer = mask->masklayers.first; mask_layer; mask_layer = mask_layer->next) {
933           MaskSpline *mask_spline;
934
935           for (mask_spline = mask_layer->splines.first; mask_spline;
936                mask_spline = mask_spline->next) {
937             for (i = 0; i < mask_spline->tot_point; i++) {
938               MaskSplinePoint *point = &mask_spline->points[i];
939               CALLBACK_INVOKE_ID(point->parent.id, IDWALK_CB_USER);
940             }
941           }
942         }
943         break;
944       }
945
946       case ID_LS: {
947         FreestyleLineStyle *linestyle = (FreestyleLineStyle *)id;
948         LineStyleModifier *lsm;
949         for (i = 0; i < MAX_MTEX; i++) {
950           if (linestyle->mtex[i]) {
951             library_foreach_mtex(&data, linestyle->mtex[i]);
952           }
953         }
954         if (linestyle->nodetree) {
955           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
956           library_foreach_ID_as_subdata_link(
957               (ID **)&linestyle->nodetree, callback, user_data, flag, &data);
958         }
959
960         for (lsm = linestyle->color_modifiers.first; lsm; lsm = lsm->next) {
961           if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
962             LineStyleColorModifier_DistanceFromObject *p =
963                 (LineStyleColorModifier_DistanceFromObject *)lsm;
964             if (p->target) {
965               CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
966             }
967           }
968         }
969         for (lsm = linestyle->alpha_modifiers.first; lsm; lsm = lsm->next) {
970           if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
971             LineStyleAlphaModifier_DistanceFromObject *p =
972                 (LineStyleAlphaModifier_DistanceFromObject *)lsm;
973             if (p->target) {
974               CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
975             }
976           }
977         }
978         for (lsm = linestyle->thickness_modifiers.first; lsm; lsm = lsm->next) {
979           if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
980             LineStyleThicknessModifier_DistanceFromObject *p =
981                 (LineStyleThicknessModifier_DistanceFromObject *)lsm;
982             if (p->target) {
983               CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
984             }
985           }
986         }
987         break;
988       }
989       case ID_AC: {
990         bAction *act = (bAction *)id;
991
992         for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
993           CALLBACK_INVOKE(marker->camera, IDWALK_CB_NOP);
994         }
995         break;
996       }
997
998       case ID_WM: {
999         wmWindowManager *wm = (wmWindowManager *)id;
1000
1001         for (wmWindow *win = wm->windows.first; win; win = win->next) {
1002           ID *workspace = (ID *)BKE_workspace_active_get(win->workspace_hook);
1003
1004           CALLBACK_INVOKE(win->scene, IDWALK_CB_USER_ONE);
1005
1006           CALLBACK_INVOKE_ID(workspace, IDWALK_CB_NOP);
1007           /* allow callback to set a different workspace */
1008           BKE_workspace_active_set(win->workspace_hook, (WorkSpace *)workspace);
1009         }
1010         break;
1011       }
1012
1013       case ID_WS: {
1014         WorkSpace *workspace = (WorkSpace *)id;
1015         ListBase *layouts = BKE_workspace_layouts_get(workspace);
1016
1017         for (WorkSpaceLayout *layout = layouts->first; layout; layout = layout->next) {
1018           bScreen *screen = BKE_workspace_layout_screen_get(layout);
1019
1020           /* CALLBACK_INVOKE expects an actual pointer, not a variable holding the pointer.
1021            * However we can't access layout->screen here since we are outside the workspace project. */
1022           CALLBACK_INVOKE(screen, IDWALK_CB_USER);
1023           /* allow callback to set a different screen */
1024           BKE_workspace_layout_screen_set(layout, screen);
1025         }
1026         break;
1027       }
1028       case ID_GD: {
1029         bGPdata *gpencil = (bGPdata *)id;
1030         /* materials */
1031         for (i = 0; i < gpencil->totcol; i++) {
1032           CALLBACK_INVOKE(gpencil->mat[i], IDWALK_CB_USER);
1033         }
1034
1035         for (bGPDlayer *gplayer = gpencil->layers.first; gplayer != NULL;
1036              gplayer = gplayer->next) {
1037           CALLBACK_INVOKE(gplayer->parent, IDWALK_CB_NOP);
1038         }
1039
1040         break;
1041       }
1042
1043       /* Nothing needed for those... */
1044       case ID_SCR:
1045       case ID_IM:
1046       case ID_VF:
1047       case ID_TXT:
1048       case ID_SO:
1049       case ID_PAL:
1050       case ID_PC:
1051       case ID_CF:
1052         break;
1053
1054       /* Deprecated. */
1055       case ID_IP:
1056         break;
1057     }
1058   }
1059
1060 FOREACH_FINALIZE:
1061   if (data.ids_handled) {
1062     BLI_gset_free(data.ids_handled, NULL);
1063     BLI_LINKSTACK_FREE(data.ids_todo);
1064   }
1065
1066 #undef CALLBACK_INVOKE_ID
1067 #undef CALLBACK_INVOKE
1068 }
1069
1070 #undef FOREACH_CALLBACK_INVOKE_ID
1071 #undef FOREACH_CALLBACK_INVOKE
1072
1073 /**
1074  * Loop over all of the ID's this datablock links to.
1075  */
1076 void BKE_library_foreach_ID_link(
1077     Main *bmain, ID *id, LibraryIDLinkCallback callback, void *user_data, int flag)
1078 {
1079   library_foreach_ID_link(bmain, id, callback, user_data, flag, NULL);
1080 }
1081
1082 /**
1083  * re-usable function, use when replacing ID's
1084  */
1085 void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cb_flag)
1086 {
1087   if (cb_flag & IDWALK_CB_USER) {
1088     id_us_min(id_src);
1089     id_us_plus(id_dst);
1090   }
1091   else if (cb_flag & IDWALK_CB_USER_ONE) {
1092     id_us_ensure_real(id_dst);
1093   }
1094 }
1095
1096 /**
1097  * Say whether given \a id_type_owner can use (in any way) a datablock of \a id_type_used.
1098  *
1099  * This is a 'simplified' abstract version of #BKE_library_foreach_ID_link() above, quite useful to reduce
1100  * useless iterations in some cases.
1101  */
1102 /* XXX This has to be fully rethink, basing check on ID type is not really working anymore (and even worth once
1103  *     IDProps will support ID pointers), we'll have to do some quick checks on IDs themselves... */
1104 bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used)
1105 {
1106   /* any type of ID can be used in custom props. */
1107   if (id_owner->properties) {
1108     return true;
1109   }
1110
1111   const short id_type_owner = GS(id_owner->name);
1112
1113   /* IDProps of armature bones and nodes, and bNode->id can use virtually any type of ID. */
1114   if (ELEM(id_type_owner, ID_NT, ID_AR)) {
1115     return true;
1116   }
1117
1118   if (ntreeFromID(id_owner)) {
1119     return true;
1120   }
1121
1122   if (BKE_animdata_from_id(id_owner)) {
1123     return true; /* AnimationData can use virtually any kind of datablocks, through drivers especially. */
1124   }
1125
1126   switch ((ID_Type)id_type_owner) {
1127     case ID_LI:
1128       return ELEM(id_type_used, ID_LI);
1129     case ID_SCE:
1130       return (ELEM(id_type_used,
1131                    ID_OB,
1132                    ID_WO,
1133                    ID_SCE,
1134                    ID_MC,
1135                    ID_MA,
1136                    ID_GR,
1137                    ID_TXT,
1138                    ID_LS,
1139                    ID_MSK,
1140                    ID_SO,
1141                    ID_GD,
1142                    ID_BR,
1143                    ID_PAL,
1144                    ID_IM,
1145                    ID_NT));
1146     case ID_OB:
1147       /* Could be more specific, but simpler to just always say 'yes' here. */
1148       return true;
1149     case ID_ME:
1150       return ELEM(id_type_used, ID_ME, ID_KE, ID_MA, ID_IM);
1151     case ID_CU:
1152       return ELEM(id_type_used, ID_OB, ID_KE, ID_MA, ID_VF);
1153     case ID_MB:
1154       return ELEM(id_type_used, ID_MA);
1155     case ID_MA:
1156       return (ELEM(id_type_used, ID_TE, ID_GR));
1157     case ID_TE:
1158       return (ELEM(id_type_used, ID_IM, ID_OB));
1159     case ID_LT:
1160       return ELEM(id_type_used, ID_KE);
1161     case ID_LA:
1162       return (ELEM(id_type_used, ID_TE));
1163     case ID_CA:
1164       return ELEM(id_type_used, ID_OB);
1165     case ID_KE:
1166       return ELEM(id_type_used,
1167                   ID_ME,
1168                   ID_CU,
1169                   ID_LT); /* Warning! key->from, could be more types in future? */
1170     case ID_SCR:
1171       return ELEM(id_type_used, ID_SCE);
1172     case ID_WO:
1173       return (ELEM(id_type_used, ID_TE));
1174     case ID_SPK:
1175       return ELEM(id_type_used, ID_SO);
1176     case ID_GR:
1177       return ELEM(id_type_used, ID_OB, ID_GR);
1178     case ID_NT:
1179       /* Could be more specific, but node.id has no type restriction... */
1180       return true;
1181     case ID_BR:
1182       return ELEM(id_type_used, ID_BR, ID_IM, ID_PC, ID_TE, ID_MA);
1183     case ID_PA:
1184       return ELEM(id_type_used, ID_OB, ID_GR, ID_TE);
1185     case ID_MC:
1186       return ELEM(id_type_used, ID_GD, ID_IM);
1187     case ID_MSK:
1188       return ELEM(id_type_used, ID_MC); /* WARNING! mask->parent.id, not typed. */
1189     case ID_LS:
1190       return (ELEM(id_type_used, ID_TE, ID_OB));
1191     case ID_LP:
1192       return ELEM(id_type_used, ID_IM);
1193     case ID_GD:
1194       return ELEM(id_type_used, ID_MA);
1195     case ID_WS:
1196       return ELEM(id_type_used, ID_SCR, ID_SCE);
1197     case ID_IM:
1198     case ID_VF:
1199     case ID_TXT:
1200     case ID_SO:
1201     case ID_AR:
1202     case ID_AC:
1203     case ID_WM:
1204     case ID_PAL:
1205     case ID_PC:
1206     case ID_CF:
1207       /* Those types never use/reference other IDs... */
1208       return false;
1209     case ID_IP:
1210       /* Deprecated... */
1211       return false;
1212   }
1213   return false;
1214 }
1215
1216 /* ***** ID users iterator. ***** */
1217 typedef struct IDUsersIter {
1218   ID *id;
1219
1220   ListBase *lb_array[MAX_LIBARRAY];
1221   int lb_idx;
1222
1223   ID *curr_id;
1224   int count_direct, count_indirect; /* Set by callback. */
1225 } IDUsersIter;
1226
1227 static int foreach_libblock_id_users_callback(void *user_data,
1228                                               ID *UNUSED(self_id),
1229                                               ID **id_p,
1230                                               int cb_flag)
1231 {
1232   IDUsersIter *iter = user_data;
1233
1234   if (*id_p) {
1235     /* 'Loopback' ID pointers (the ugly 'from' ones, Object->proxy_from and Key->from).
1236      * Those are not actually ID usage, we can ignore them here.
1237      */
1238     if (cb_flag & IDWALK_CB_LOOPBACK) {
1239       return IDWALK_RET_NOP;
1240     }
1241
1242     if (*id_p == iter->id) {
1243 #if 0
1244       printf(
1245           "%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, "
1246           "indirect_usage: %d)\n",
1247           iter->curr_id->name,
1248           iter->id->name,
1249           (cb_flag & IDWALK_USER) ? 1 : 0,
1250           (cb_flag & IDWALK_USER_ONE) ? 1 : 0,
1251           (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0,
1252           (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0,
1253           (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0);
1254 #endif
1255       if (cb_flag & IDWALK_CB_INDIRECT_USAGE) {
1256         iter->count_indirect++;
1257       }
1258       else {
1259         iter->count_direct++;
1260       }
1261     }
1262   }
1263
1264   return IDWALK_RET_NOP;
1265 }
1266
1267 /**
1268  * Return the number of times given \a id_user uses/references \a id_used.
1269  *
1270  * \note This only checks for pointer references of an ID, shallow usages (like e.g. by RNA paths, as done
1271  *       for FCurves) are not detected at all.
1272  *
1273  * \param id_user: the ID which is supposed to use (reference) \a id_used.
1274  * \param id_used: the ID which is supposed to be used (referenced) by \a id_user.
1275  * \return the number of direct usages/references of \a id_used by \a id_user.
1276  */
1277 int BKE_library_ID_use_ID(ID *id_user, ID *id_used)
1278 {
1279   IDUsersIter iter;
1280
1281   /* We do not care about iter.lb_array/lb_idx here... */
1282   iter.id = id_used;
1283   iter.curr_id = id_user;
1284   iter.count_direct = iter.count_indirect = 0;
1285
1286   BKE_library_foreach_ID_link(
1287       NULL, iter.curr_id, foreach_libblock_id_users_callback, (void *)&iter, IDWALK_READONLY);
1288
1289   return iter.count_direct + iter.count_indirect;
1290 }
1291
1292 static bool library_ID_is_used(Main *bmain, void *idv, const bool check_linked)
1293 {
1294   IDUsersIter iter;
1295   ListBase *lb_array[MAX_LIBARRAY];
1296   ID *id = idv;
1297   int i = set_listbasepointers(bmain, lb_array);
1298   bool is_defined = false;
1299
1300   iter.id = id;
1301   iter.count_direct = iter.count_indirect = 0;
1302   while (i-- && !is_defined) {
1303     ID *id_curr = lb_array[i]->first;
1304
1305     if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
1306       continue;
1307     }
1308
1309     for (; id_curr && !is_defined; id_curr = id_curr->next) {
1310       if (id_curr == id) {
1311         /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1312         continue;
1313       }
1314       iter.curr_id = id_curr;
1315       BKE_library_foreach_ID_link(
1316           bmain, id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_READONLY);
1317
1318       is_defined = ((check_linked ? iter.count_indirect : iter.count_direct) != 0);
1319     }
1320   }
1321
1322   return is_defined;
1323 }
1324
1325 /**
1326  * Check whether given ID is used locally (i.e. by another non-linked ID).
1327  */
1328 bool BKE_library_ID_is_locally_used(Main *bmain, void *idv)
1329 {
1330   return library_ID_is_used(bmain, idv, false);
1331 }
1332
1333 /**
1334  * Check whether given ID is used indirectly (i.e. by another linked ID).
1335  */
1336 bool BKE_library_ID_is_indirectly_used(Main *bmain, void *idv)
1337 {
1338   return library_ID_is_used(bmain, idv, true);
1339 }
1340
1341 /**
1342  * Combine #BKE_library_ID_is_locally_used() and #BKE_library_ID_is_indirectly_used() in a single call.
1343  */
1344 void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, bool *is_used_linked)
1345 {
1346   IDUsersIter iter;
1347   ListBase *lb_array[MAX_LIBARRAY];
1348   ID *id = idv;
1349   int i = set_listbasepointers(bmain, lb_array);
1350   bool is_defined = false;
1351
1352   iter.id = id;
1353   iter.count_direct = iter.count_indirect = 0;
1354   while (i-- && !is_defined) {
1355     ID *id_curr = lb_array[i]->first;
1356
1357     if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
1358       continue;
1359     }
1360
1361     for (; id_curr && !is_defined; id_curr = id_curr->next) {
1362       if (id_curr == id) {
1363         /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1364         continue;
1365       }
1366       iter.curr_id = id_curr;
1367       BKE_library_foreach_ID_link(
1368           bmain, id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_READONLY);
1369
1370       is_defined = (iter.count_direct != 0 && iter.count_indirect != 0);
1371     }
1372   }
1373
1374   *is_used_local = (iter.count_direct != 0);
1375   *is_used_linked = (iter.count_indirect != 0);
1376 }
1377
1378 /* ***** IDs usages.checking/tagging. ***** */
1379 static int foreach_libblock_used_linked_data_tag_clear_cb(void *user_data,
1380                                                           ID *self_id,
1381                                                           ID **id_p,
1382                                                           int cb_flag)
1383 {
1384   bool *is_changed = user_data;
1385
1386   if (*id_p) {
1387     /* The infamous 'from' pointers (Key.from, Object.proxy_from, ...).
1388      * those are not actually ID usage, so we ignore them here. */
1389     if (cb_flag & IDWALK_CB_LOOPBACK) {
1390       return IDWALK_RET_NOP;
1391     }
1392
1393     /* If checked id is used by an assumed used ID, then it is also used and not part of any linked archipelago. */
1394     if (!(self_id->tag & LIB_TAG_DOIT) && ((*id_p)->tag & LIB_TAG_DOIT)) {
1395       (*id_p)->tag &= ~LIB_TAG_DOIT;
1396       *is_changed = true;
1397     }
1398   }
1399
1400   return IDWALK_RET_NOP;
1401 }
1402
1403 /**
1404  * Detect orphaned linked data blocks (i.e. linked data not used (directly or indirectly) in any way by any local data),
1405  * including complex cases like 'linked archipelagoes', i.e. linked datablocks that use each other in loops,
1406  * which prevents their deletion by 'basic' usage checks...
1407  *
1408  * \param do_init_tag: if \a true, all linked data are checked, if \a false, only linked datablocks already tagged with
1409  *                    LIB_TAG_DOIT are checked.
1410  */
1411 void BKE_library_unused_linked_data_set_tag(Main *bmain, const bool do_init_tag)
1412 {
1413   ID *id;
1414
1415   if (do_init_tag) {
1416     FOREACH_MAIN_ID_BEGIN (bmain, id) {
1417       if (id->lib && (id->tag & LIB_TAG_INDIRECT) != 0) {
1418         id->tag |= LIB_TAG_DOIT;
1419       }
1420       else {
1421         id->tag &= ~LIB_TAG_DOIT;
1422       }
1423     }
1424     FOREACH_MAIN_ID_END;
1425   }
1426
1427   for (bool do_loop = true; do_loop;) {
1428     do_loop = false;
1429     FOREACH_MAIN_ID_BEGIN (bmain, id) {
1430       /* We only want to check that ID if it is currently known as used... */
1431       if ((id->tag & LIB_TAG_DOIT) == 0) {
1432         BKE_library_foreach_ID_link(
1433             bmain, id, foreach_libblock_used_linked_data_tag_clear_cb, &do_loop, IDWALK_READONLY);
1434       }
1435     }
1436     FOREACH_MAIN_ID_END;
1437   }
1438 }
1439
1440 /**
1441  * Untag linked data blocks used by other untagged linked datablocks.
1442  * Used to detect datablocks that we can forcefully make local (instead of copying them to later get rid of original):
1443  * All datablocks we want to make local are tagged by caller, after this function has ran caller knows datablocks still
1444  * tagged can directly be made local, since they are only used by other datablocks that will also be made fully local.
1445  */
1446 void BKE_library_indirectly_used_data_tag_clear(Main *bmain)
1447 {
1448   ListBase *lb_array[MAX_LIBARRAY];
1449
1450   bool do_loop = true;
1451   while (do_loop) {
1452     int i = set_listbasepointers(bmain, lb_array);
1453     do_loop = false;
1454
1455     while (i--) {
1456       for (ID *id = lb_array[i]->first; id; id = id->next) {
1457         if (id->lib == NULL || id->tag & LIB_TAG_DOIT) {
1458           /* Local or non-indirectly-used ID (so far), no need to check it further. */
1459           continue;
1460         }
1461         BKE_library_foreach_ID_link(
1462             bmain, id, foreach_libblock_used_linked_data_tag_clear_cb, &do_loop, IDWALK_READONLY);
1463       }
1464     }
1465   }
1466 }