Cleanup: comments (long lines) in blenkernel
[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
356      * IDWALK_RECURSE case is 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
406      * (the node tree), 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
420        * lots of 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,
422        * it's responsibility of code creating it to free it,
423        * especially if/when it starts modifying Main database). */
424       MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->id_user_to_used, id);
425       for (; entry != NULL; entry = entry->next) {
426         FOREACH_CALLBACK_INVOKE_ID_PP(&data, entry->id_pointer, entry->usage_flag);
427       }
428       continue;
429     }
430
431     if (id->override_static != NULL) {
432       CALLBACK_INVOKE_ID(id->override_static->reference,
433                          IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE);
434       CALLBACK_INVOKE_ID(id->override_static->storage,
435                          IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE);
436     }
437
438     library_foreach_idproperty_ID_link(&data, id->properties, IDWALK_CB_USER);
439
440     AnimData *adt = BKE_animdata_from_id(id);
441     if (adt) {
442       library_foreach_animationData(&data, adt);
443     }
444
445     switch ((ID_Type)GS(id->name)) {
446       case ID_LI: {
447         Library *lib = (Library *)id;
448         CALLBACK_INVOKE(lib->parent, IDWALK_CB_NEVER_SELF);
449         break;
450       }
451       case ID_SCE: {
452         Scene *scene = (Scene *)id;
453         ToolSettings *toolsett = scene->toolsettings;
454
455         CALLBACK_INVOKE(scene->camera, IDWALK_CB_NOP);
456         CALLBACK_INVOKE(scene->world, IDWALK_CB_USER);
457         CALLBACK_INVOKE(scene->set, IDWALK_CB_NEVER_SELF);
458         CALLBACK_INVOKE(scene->clip, IDWALK_CB_USER);
459         CALLBACK_INVOKE(scene->r.bake.cage_object, IDWALK_CB_NOP);
460         if (scene->nodetree) {
461           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
462           library_foreach_ID_as_subdata_link(
463               (ID **)&scene->nodetree, callback, user_data, flag, &data);
464         }
465         if (scene->ed) {
466           Sequence *seq;
467           SEQP_BEGIN (scene->ed, seq) {
468             CALLBACK_INVOKE(seq->scene, IDWALK_CB_NEVER_SELF);
469             CALLBACK_INVOKE(seq->scene_camera, IDWALK_CB_NOP);
470             CALLBACK_INVOKE(seq->clip, IDWALK_CB_USER);
471             CALLBACK_INVOKE(seq->mask, IDWALK_CB_USER);
472             CALLBACK_INVOKE(seq->sound, IDWALK_CB_USER);
473             library_foreach_idproperty_ID_link(&data, seq->prop, IDWALK_CB_USER);
474             for (SequenceModifierData *smd = seq->modifiers.first; smd; smd = smd->next) {
475               CALLBACK_INVOKE(smd->mask_id, IDWALK_CB_USER);
476             }
477
478             if (seq->type == SEQ_TYPE_TEXT && seq->effectdata) {
479               TextVars *text_data = seq->effectdata;
480               CALLBACK_INVOKE(text_data->text_font, IDWALK_CB_USER);
481             }
482           }
483           SEQ_END;
484         }
485
486         for (CollectionObject *cob = scene->master_collection->gobject.first; cob;
487              cob = cob->next) {
488           CALLBACK_INVOKE(cob->ob, IDWALK_CB_USER);
489         }
490         for (CollectionChild *child = scene->master_collection->children.first; child;
491              child = child->next) {
492           CALLBACK_INVOKE(child->collection, IDWALK_CB_USER);
493         }
494
495         ViewLayer *view_layer;
496         for (view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
497           CALLBACK_INVOKE(view_layer->mat_override, IDWALK_CB_USER);
498
499           for (Base *base = view_layer->object_bases.first; base; base = base->next) {
500             CALLBACK_INVOKE(base->object, IDWALK_CB_NOP);
501           }
502
503           library_foreach_layer_collection(&data, &view_layer->layer_collections);
504
505           for (FreestyleModuleConfig *fmc = view_layer->freestyle_config.modules.first; fmc;
506                fmc = fmc->next) {
507             if (fmc->script) {
508               CALLBACK_INVOKE(fmc->script, IDWALK_CB_NOP);
509             }
510           }
511
512           for (FreestyleLineSet *fls = view_layer->freestyle_config.linesets.first; fls;
513                fls = fls->next) {
514             if (fls->group) {
515               CALLBACK_INVOKE(fls->group, IDWALK_CB_USER);
516             }
517
518             if (fls->linestyle) {
519               CALLBACK_INVOKE(fls->linestyle, IDWALK_CB_USER);
520             }
521           }
522         }
523
524         for (TimeMarker *marker = scene->markers.first; marker; marker = marker->next) {
525           CALLBACK_INVOKE(marker->camera, IDWALK_CB_NOP);
526         }
527
528         if (toolsett) {
529           CALLBACK_INVOKE(toolsett->particle.scene, IDWALK_CB_NOP);
530           CALLBACK_INVOKE(toolsett->particle.object, IDWALK_CB_NOP);
531           CALLBACK_INVOKE(toolsett->particle.shape_object, IDWALK_CB_NOP);
532
533           library_foreach_paint(&data, &toolsett->imapaint.paint);
534           CALLBACK_INVOKE(toolsett->imapaint.stencil, IDWALK_CB_USER);
535           CALLBACK_INVOKE(toolsett->imapaint.clone, IDWALK_CB_USER);
536           CALLBACK_INVOKE(toolsett->imapaint.canvas, IDWALK_CB_USER);
537
538           if (toolsett->vpaint) {
539             library_foreach_paint(&data, &toolsett->vpaint->paint);
540           }
541           if (toolsett->wpaint) {
542             library_foreach_paint(&data, &toolsett->wpaint->paint);
543           }
544           if (toolsett->sculpt) {
545             library_foreach_paint(&data, &toolsett->sculpt->paint);
546             CALLBACK_INVOKE(toolsett->sculpt->gravity_object, IDWALK_CB_NOP);
547           }
548           if (toolsett->uvsculpt) {
549             library_foreach_paint(&data, &toolsett->uvsculpt->paint);
550           }
551           if (toolsett->gp_paint) {
552             library_foreach_paint(&data, &toolsett->gp_paint->paint);
553           }
554
555           CALLBACK_INVOKE(toolsett->gp_sculpt.guide.reference_object, IDWALK_CB_NOP);
556         }
557
558         if (scene->rigidbody_world) {
559           BKE_rigidbody_world_id_loop(
560               scene->rigidbody_world, library_foreach_rigidbodyworldSceneLooper, &data);
561         }
562
563         break;
564       }
565
566       case ID_OB: {
567         Object *object = (Object *)id;
568         ParticleSystem *psys;
569
570         /* Object is special, proxies make things hard... */
571         const int data_cb_flag = data.cb_flag;
572         const int proxy_cb_flag = ((data.flag & IDWALK_NO_INDIRECT_PROXY_DATA_USAGE) == 0 &&
573                                    (object->proxy || object->proxy_group)) ?
574                                       IDWALK_CB_INDIRECT_USAGE :
575                                       0;
576
577         /* object data special case */
578         data.cb_flag |= proxy_cb_flag;
579         if (object->type == OB_EMPTY) {
580           /* empty can have NULL or Image */
581           CALLBACK_INVOKE_ID(object->data, IDWALK_CB_USER);
582         }
583         else {
584           /* when set, this can't be NULL */
585           if (object->data) {
586             CALLBACK_INVOKE_ID(object->data, IDWALK_CB_USER | IDWALK_CB_NEVER_NULL);
587           }
588         }
589         data.cb_flag = data_cb_flag;
590
591         CALLBACK_INVOKE(object->parent, IDWALK_CB_NEVER_SELF);
592         CALLBACK_INVOKE(object->track, IDWALK_CB_NEVER_SELF);
593         /* object->proxy is refcounted, but not object->proxy_group... *sigh* */
594         CALLBACK_INVOKE(object->proxy, IDWALK_CB_NEVER_SELF);
595         CALLBACK_INVOKE(object->proxy_group, IDWALK_CB_NOP);
596
597         /* Special case!
598          * Since this field is set/owned by 'user' of this ID (and not ID itself),
599          * it is only indirect usage if proxy object is linked... Twisted. */
600         if (object->proxy_from) {
601           data.cb_flag = ID_IS_LINKED(object->proxy_from) ? IDWALK_CB_INDIRECT_USAGE : 0;
602         }
603         CALLBACK_INVOKE(object->proxy_from, IDWALK_CB_LOOPBACK | IDWALK_CB_NEVER_SELF);
604         data.cb_flag = data_cb_flag;
605
606         CALLBACK_INVOKE(object->poselib, IDWALK_CB_USER);
607
608         data.cb_flag |= proxy_cb_flag;
609         for (i = 0; i < object->totcol; i++) {
610           CALLBACK_INVOKE(object->mat[i], IDWALK_CB_USER);
611         }
612         data.cb_flag = data_cb_flag;
613
614         /* Note that ob->gpd is deprecated, so no need to handle it here. */
615         CALLBACK_INVOKE(object->instance_collection, IDWALK_CB_USER);
616
617         if (object->pd) {
618           CALLBACK_INVOKE(object->pd->tex, IDWALK_CB_USER);
619           CALLBACK_INVOKE(object->pd->f_source, IDWALK_CB_NOP);
620         }
621         /* Note that ob->effect is deprecated, so no need to handle it here. */
622
623         if (object->pose) {
624           bPoseChannel *pchan;
625
626           data.cb_flag |= proxy_cb_flag;
627           for (pchan = object->pose->chanbase.first; pchan; pchan = pchan->next) {
628             library_foreach_idproperty_ID_link(&data, pchan->prop, IDWALK_CB_USER);
629             CALLBACK_INVOKE(pchan->custom, IDWALK_CB_USER);
630             BKE_constraints_id_loop(
631                 &pchan->constraints, library_foreach_constraintObjectLooper, &data);
632           }
633           data.cb_flag = data_cb_flag;
634         }
635
636         if (object->rigidbody_constraint) {
637           CALLBACK_INVOKE(object->rigidbody_constraint->ob1, IDWALK_CB_NEVER_SELF);
638           CALLBACK_INVOKE(object->rigidbody_constraint->ob2, IDWALK_CB_NEVER_SELF);
639         }
640
641         if (object->lodlevels.first) {
642           LodLevel *level;
643           for (level = object->lodlevels.first; level; level = level->next) {
644             CALLBACK_INVOKE(level->source, IDWALK_CB_NEVER_SELF);
645           }
646         }
647
648         modifiers_foreachIDLink(object, library_foreach_modifiersForeachIDLink, &data);
649         BKE_gpencil_modifiers_foreachIDLink(
650             object, library_foreach_gpencil_modifiersForeachIDLink, &data);
651         BKE_constraints_id_loop(
652             &object->constraints, library_foreach_constraintObjectLooper, &data);
653         BKE_shaderfx_foreachIDLink(object, library_foreach_shaderfxForeachIDLink, &data);
654
655         for (psys = object->particlesystem.first; psys; psys = psys->next) {
656           BKE_particlesystem_id_loop(psys, library_foreach_particlesystemsObjectLooper, &data);
657         }
658
659         if (object->soft) {
660           CALLBACK_INVOKE(object->soft->collision_group, IDWALK_CB_NOP);
661
662           if (object->soft->effector_weights) {
663             CALLBACK_INVOKE(object->soft->effector_weights->group, IDWALK_CB_NOP);
664           }
665         }
666         break;
667       }
668
669       case ID_AR: {
670         bArmature *arm = (bArmature *)id;
671
672         for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
673           library_foreach_bone(&data, bone);
674         }
675         break;
676       }
677
678       case ID_ME: {
679         Mesh *mesh = (Mesh *)id;
680         CALLBACK_INVOKE(mesh->texcomesh, IDWALK_CB_NEVER_SELF);
681         CALLBACK_INVOKE(mesh->key, IDWALK_CB_USER);
682         for (i = 0; i < mesh->totcol; i++) {
683           CALLBACK_INVOKE(mesh->mat[i], IDWALK_CB_USER);
684         }
685         break;
686       }
687
688       case ID_CU: {
689         Curve *curve = (Curve *)id;
690         CALLBACK_INVOKE(curve->bevobj, IDWALK_CB_NOP);
691         CALLBACK_INVOKE(curve->taperobj, IDWALK_CB_NOP);
692         CALLBACK_INVOKE(curve->textoncurve, IDWALK_CB_NOP);
693         CALLBACK_INVOKE(curve->key, IDWALK_CB_USER);
694         for (i = 0; i < curve->totcol; i++) {
695           CALLBACK_INVOKE(curve->mat[i], IDWALK_CB_USER);
696         }
697         CALLBACK_INVOKE(curve->vfont, IDWALK_CB_USER);
698         CALLBACK_INVOKE(curve->vfontb, IDWALK_CB_USER);
699         CALLBACK_INVOKE(curve->vfonti, IDWALK_CB_USER);
700         CALLBACK_INVOKE(curve->vfontbi, IDWALK_CB_USER);
701         break;
702       }
703
704       case ID_MB: {
705         MetaBall *metaball = (MetaBall *)id;
706         for (i = 0; i < metaball->totcol; i++) {
707           CALLBACK_INVOKE(metaball->mat[i], IDWALK_CB_USER);
708         }
709         break;
710       }
711
712       case ID_MA: {
713         Material *material = (Material *)id;
714         if (material->nodetree) {
715           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
716           library_foreach_ID_as_subdata_link(
717               (ID **)&material->nodetree, callback, user_data, flag, &data);
718         }
719         if (material->texpaintslot != NULL) {
720           CALLBACK_INVOKE(material->texpaintslot->ima, IDWALK_CB_NOP);
721         }
722         if (material->gp_style != NULL) {
723           CALLBACK_INVOKE(material->gp_style->sima, IDWALK_CB_USER);
724           CALLBACK_INVOKE(material->gp_style->ima, IDWALK_CB_USER);
725         }
726         break;
727       }
728
729       case ID_TE: {
730         Tex *texture = (Tex *)id;
731         if (texture->nodetree) {
732           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
733           library_foreach_ID_as_subdata_link(
734               (ID **)&texture->nodetree, callback, user_data, flag, &data);
735         }
736         CALLBACK_INVOKE(texture->ima, IDWALK_CB_USER);
737         break;
738       }
739
740       case ID_LT: {
741         Lattice *lattice = (Lattice *)id;
742         CALLBACK_INVOKE(lattice->key, IDWALK_CB_USER);
743         break;
744       }
745
746       case ID_LA: {
747         Light *lamp = (Light *)id;
748         if (lamp->nodetree) {
749           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
750           library_foreach_ID_as_subdata_link(
751               (ID **)&lamp->nodetree, callback, user_data, flag, &data);
752         }
753         break;
754       }
755
756       case ID_CA: {
757         Camera *camera = (Camera *)id;
758         CALLBACK_INVOKE(camera->dof_ob, IDWALK_CB_NOP);
759         for (CameraBGImage *bgpic = camera->bg_images.first; bgpic; bgpic = bgpic->next) {
760           if (bgpic->source == CAM_BGIMG_SOURCE_IMAGE) {
761             CALLBACK_INVOKE(bgpic->ima, IDWALK_CB_USER);
762           }
763           else if (bgpic->source == CAM_BGIMG_SOURCE_MOVIE) {
764             CALLBACK_INVOKE(bgpic->clip, IDWALK_CB_USER);
765           }
766         }
767
768         break;
769       }
770
771       case ID_KE: {
772         Key *key = (Key *)id;
773         CALLBACK_INVOKE_ID(key->from, IDWALK_CB_LOOPBACK);
774         break;
775       }
776
777       case ID_WO: {
778         World *world = (World *)id;
779         if (world->nodetree) {
780           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
781           library_foreach_ID_as_subdata_link(
782               (ID **)&world->nodetree, callback, user_data, flag, &data);
783         }
784         break;
785       }
786
787       case ID_SPK: {
788         Speaker *speaker = (Speaker *)id;
789         CALLBACK_INVOKE(speaker->sound, IDWALK_CB_USER);
790         break;
791       }
792
793       case ID_LP: {
794         LightProbe *probe = (LightProbe *)id;
795         CALLBACK_INVOKE(probe->image, IDWALK_CB_USER);
796         CALLBACK_INVOKE(probe->visibility_grp, IDWALK_CB_NOP);
797         break;
798       }
799
800       case ID_GR: {
801         Collection *collection = (Collection *)id;
802         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
803           CALLBACK_INVOKE(cob->ob, IDWALK_CB_USER);
804         }
805         for (CollectionChild *child = collection->children.first; child; child = child->next) {
806           CALLBACK_INVOKE(child->collection, IDWALK_CB_NEVER_SELF | IDWALK_CB_USER);
807         }
808         for (CollectionParent *parent = collection->parents.first; parent; parent = parent->next) {
809           CALLBACK_INVOKE(parent->collection, IDWALK_CB_NEVER_SELF | IDWALK_CB_LOOPBACK);
810         }
811         break;
812       }
813
814       case ID_NT: {
815         bNodeTree *ntree = (bNodeTree *)id;
816         bNode *node;
817         bNodeSocket *sock;
818
819         CALLBACK_INVOKE(ntree->gpd, IDWALK_CB_USER);
820
821         for (node = ntree->nodes.first; node; node = node->next) {
822           CALLBACK_INVOKE_ID(node->id, IDWALK_CB_USER);
823
824           library_foreach_idproperty_ID_link(&data, node->prop, IDWALK_CB_USER);
825           for (sock = node->inputs.first; sock; sock = sock->next) {
826             library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
827           }
828           for (sock = node->outputs.first; sock; sock = sock->next) {
829             library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
830           }
831         }
832
833         for (sock = ntree->inputs.first; sock; sock = sock->next) {
834           library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
835         }
836         for (sock = ntree->outputs.first; sock; sock = sock->next) {
837           library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
838         }
839         break;
840       }
841
842       case ID_BR: {
843         Brush *brush = (Brush *)id;
844         CALLBACK_INVOKE(brush->toggle_brush, IDWALK_CB_NOP);
845         CALLBACK_INVOKE(brush->clone.image, IDWALK_CB_NOP);
846         CALLBACK_INVOKE(brush->paint_curve, IDWALK_CB_USER);
847         if (brush->gpencil_settings) {
848           CALLBACK_INVOKE(brush->gpencil_settings->material, IDWALK_CB_USER);
849         }
850         library_foreach_mtex(&data, &brush->mtex);
851         library_foreach_mtex(&data, &brush->mask_mtex);
852         break;
853       }
854
855       case ID_PA: {
856         ParticleSettings *psett = (ParticleSettings *)id;
857         CALLBACK_INVOKE(psett->instance_collection, IDWALK_CB_USER);
858         CALLBACK_INVOKE(psett->instance_object, IDWALK_CB_NOP);
859         CALLBACK_INVOKE(psett->bb_ob, IDWALK_CB_NOP);
860         CALLBACK_INVOKE(psett->collision_group, IDWALK_CB_NOP);
861
862         for (i = 0; i < MAX_MTEX; i++) {
863           if (psett->mtex[i]) {
864             library_foreach_mtex(&data, psett->mtex[i]);
865           }
866         }
867
868         if (psett->effector_weights) {
869           CALLBACK_INVOKE(psett->effector_weights->group, IDWALK_CB_NOP);
870         }
871
872         if (psett->pd) {
873           CALLBACK_INVOKE(psett->pd->tex, IDWALK_CB_USER);
874           CALLBACK_INVOKE(psett->pd->f_source, IDWALK_CB_NOP);
875         }
876         if (psett->pd2) {
877           CALLBACK_INVOKE(psett->pd2->tex, IDWALK_CB_USER);
878           CALLBACK_INVOKE(psett->pd2->f_source, IDWALK_CB_NOP);
879         }
880
881         if (psett->boids) {
882           BoidState *state;
883           BoidRule *rule;
884
885           for (state = psett->boids->states.first; state; state = state->next) {
886             for (rule = state->rules.first; rule; rule = rule->next) {
887               if (rule->type == eBoidRuleType_Avoid) {
888                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
889                 CALLBACK_INVOKE(gabr->ob, IDWALK_CB_NOP);
890               }
891               else if (rule->type == eBoidRuleType_FollowLeader) {
892                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
893                 CALLBACK_INVOKE(flbr->ob, IDWALK_CB_NOP);
894               }
895             }
896           }
897         }
898
899         for (ParticleDupliWeight *dw = psett->instance_weights.first; dw; dw = dw->next) {
900           CALLBACK_INVOKE(dw->ob, IDWALK_CB_NOP);
901         }
902         break;
903       }
904
905       case ID_MC: {
906         MovieClip *clip = (MovieClip *)id;
907         MovieTracking *tracking = &clip->tracking;
908         MovieTrackingObject *object;
909         MovieTrackingTrack *track;
910         MovieTrackingPlaneTrack *plane_track;
911
912         CALLBACK_INVOKE(clip->gpd, IDWALK_CB_USER);
913
914         for (track = tracking->tracks.first; track; track = track->next) {
915           CALLBACK_INVOKE(track->gpd, IDWALK_CB_USER);
916         }
917         for (object = tracking->objects.first; object; object = object->next) {
918           for (track = object->tracks.first; track; track = track->next) {
919             CALLBACK_INVOKE(track->gpd, IDWALK_CB_USER);
920           }
921         }
922
923         for (plane_track = tracking->plane_tracks.first; plane_track;
924              plane_track = plane_track->next) {
925           CALLBACK_INVOKE(plane_track->image, IDWALK_CB_USER);
926         }
927         break;
928       }
929
930       case ID_MSK: {
931         Mask *mask = (Mask *)id;
932         MaskLayer *mask_layer;
933         for (mask_layer = mask->masklayers.first; mask_layer; mask_layer = mask_layer->next) {
934           MaskSpline *mask_spline;
935
936           for (mask_spline = mask_layer->splines.first; mask_spline;
937                mask_spline = mask_spline->next) {
938             for (i = 0; i < mask_spline->tot_point; i++) {
939               MaskSplinePoint *point = &mask_spline->points[i];
940               CALLBACK_INVOKE_ID(point->parent.id, IDWALK_CB_USER);
941             }
942           }
943         }
944         break;
945       }
946
947       case ID_LS: {
948         FreestyleLineStyle *linestyle = (FreestyleLineStyle *)id;
949         LineStyleModifier *lsm;
950         for (i = 0; i < MAX_MTEX; i++) {
951           if (linestyle->mtex[i]) {
952             library_foreach_mtex(&data, linestyle->mtex[i]);
953           }
954         }
955         if (linestyle->nodetree) {
956           /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
957           library_foreach_ID_as_subdata_link(
958               (ID **)&linestyle->nodetree, callback, user_data, flag, &data);
959         }
960
961         for (lsm = linestyle->color_modifiers.first; lsm; lsm = lsm->next) {
962           if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
963             LineStyleColorModifier_DistanceFromObject *p =
964                 (LineStyleColorModifier_DistanceFromObject *)lsm;
965             if (p->target) {
966               CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
967             }
968           }
969         }
970         for (lsm = linestyle->alpha_modifiers.first; lsm; lsm = lsm->next) {
971           if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
972             LineStyleAlphaModifier_DistanceFromObject *p =
973                 (LineStyleAlphaModifier_DistanceFromObject *)lsm;
974             if (p->target) {
975               CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
976             }
977           }
978         }
979         for (lsm = linestyle->thickness_modifiers.first; lsm; lsm = lsm->next) {
980           if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
981             LineStyleThicknessModifier_DistanceFromObject *p =
982                 (LineStyleThicknessModifier_DistanceFromObject *)lsm;
983             if (p->target) {
984               CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
985             }
986           }
987         }
988         break;
989       }
990       case ID_AC: {
991         bAction *act = (bAction *)id;
992
993         for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
994           CALLBACK_INVOKE(marker->camera, IDWALK_CB_NOP);
995         }
996         break;
997       }
998
999       case ID_WM: {
1000         wmWindowManager *wm = (wmWindowManager *)id;
1001
1002         for (wmWindow *win = wm->windows.first; win; win = win->next) {
1003           ID *workspace = (ID *)BKE_workspace_active_get(win->workspace_hook);
1004
1005           CALLBACK_INVOKE(win->scene, IDWALK_CB_USER_ONE);
1006
1007           CALLBACK_INVOKE_ID(workspace, IDWALK_CB_NOP);
1008           /* allow callback to set a different workspace */
1009           BKE_workspace_active_set(win->workspace_hook, (WorkSpace *)workspace);
1010         }
1011         break;
1012       }
1013
1014       case ID_WS: {
1015         WorkSpace *workspace = (WorkSpace *)id;
1016         ListBase *layouts = BKE_workspace_layouts_get(workspace);
1017
1018         for (WorkSpaceLayout *layout = layouts->first; layout; layout = layout->next) {
1019           bScreen *screen = BKE_workspace_layout_screen_get(layout);
1020
1021           /* CALLBACK_INVOKE expects an actual pointer, not a variable holding the pointer.
1022            * However we can't access layout->screen here
1023            * since we are outside the workspace project. */
1024           CALLBACK_INVOKE(screen, IDWALK_CB_USER);
1025           /* allow callback to set a different screen */
1026           BKE_workspace_layout_screen_set(layout, screen);
1027         }
1028         break;
1029       }
1030       case ID_GD: {
1031         bGPdata *gpencil = (bGPdata *)id;
1032         /* materials */
1033         for (i = 0; i < gpencil->totcol; i++) {
1034           CALLBACK_INVOKE(gpencil->mat[i], IDWALK_CB_USER);
1035         }
1036
1037         for (bGPDlayer *gplayer = gpencil->layers.first; gplayer != NULL;
1038              gplayer = gplayer->next) {
1039           CALLBACK_INVOKE(gplayer->parent, IDWALK_CB_NOP);
1040         }
1041
1042         break;
1043       }
1044
1045       /* Nothing needed for those... */
1046       case ID_SCR:
1047       case ID_IM:
1048       case ID_VF:
1049       case ID_TXT:
1050       case ID_SO:
1051       case ID_PAL:
1052       case ID_PC:
1053       case ID_CF:
1054         break;
1055
1056       /* Deprecated. */
1057       case ID_IP:
1058         break;
1059     }
1060   }
1061
1062 FOREACH_FINALIZE:
1063   if (data.ids_handled) {
1064     BLI_gset_free(data.ids_handled, NULL);
1065     BLI_LINKSTACK_FREE(data.ids_todo);
1066   }
1067
1068 #undef CALLBACK_INVOKE_ID
1069 #undef CALLBACK_INVOKE
1070 }
1071
1072 #undef FOREACH_CALLBACK_INVOKE_ID
1073 #undef FOREACH_CALLBACK_INVOKE
1074
1075 /**
1076  * Loop over all of the ID's this datablock links to.
1077  */
1078 void BKE_library_foreach_ID_link(
1079     Main *bmain, ID *id, LibraryIDLinkCallback callback, void *user_data, int flag)
1080 {
1081   library_foreach_ID_link(bmain, id, callback, user_data, flag, NULL);
1082 }
1083
1084 /**
1085  * re-usable function, use when replacing ID's
1086  */
1087 void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cb_flag)
1088 {
1089   if (cb_flag & IDWALK_CB_USER) {
1090     id_us_min(id_src);
1091     id_us_plus(id_dst);
1092   }
1093   else if (cb_flag & IDWALK_CB_USER_ONE) {
1094     id_us_ensure_real(id_dst);
1095   }
1096 }
1097
1098 /**
1099  * Say whether given \a id_type_owner can use (in any way) a datablock of \a id_type_used.
1100  *
1101  * This is a 'simplified' abstract version of #BKE_library_foreach_ID_link() above,
1102  * quite useful to reduce* useless iterations in some cases.
1103  */
1104 /* XXX This has to be fully rethink, basing check on ID type is not really working anymore
1105  * (and even worth once IDProps will support ID pointers),
1106  * we'll have to do some quick checks on IDs themselves... */
1107 bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used)
1108 {
1109   /* any type of ID can be used in custom props. */
1110   if (id_owner->properties) {
1111     return true;
1112   }
1113
1114   const short id_type_owner = GS(id_owner->name);
1115
1116   /* IDProps of armature bones and nodes, and bNode->id can use virtually any type of ID. */
1117   if (ELEM(id_type_owner, ID_NT, ID_AR)) {
1118     return true;
1119   }
1120
1121   if (ntreeFromID(id_owner)) {
1122     return true;
1123   }
1124
1125   if (BKE_animdata_from_id(id_owner)) {
1126     /* AnimationData can use virtually any kind of datablocks, through drivers especially. */
1127     return true;
1128   }
1129
1130   switch ((ID_Type)id_type_owner) {
1131     case ID_LI:
1132       return ELEM(id_type_used, ID_LI);
1133     case ID_SCE:
1134       return (ELEM(id_type_used,
1135                    ID_OB,
1136                    ID_WO,
1137                    ID_SCE,
1138                    ID_MC,
1139                    ID_MA,
1140                    ID_GR,
1141                    ID_TXT,
1142                    ID_LS,
1143                    ID_MSK,
1144                    ID_SO,
1145                    ID_GD,
1146                    ID_BR,
1147                    ID_PAL,
1148                    ID_IM,
1149                    ID_NT));
1150     case ID_OB:
1151       /* Could be more specific, but simpler to just always say 'yes' here. */
1152       return true;
1153     case ID_ME:
1154       return ELEM(id_type_used, ID_ME, ID_KE, ID_MA, ID_IM);
1155     case ID_CU:
1156       return ELEM(id_type_used, ID_OB, ID_KE, ID_MA, ID_VF);
1157     case ID_MB:
1158       return ELEM(id_type_used, ID_MA);
1159     case ID_MA:
1160       return (ELEM(id_type_used, ID_TE, ID_GR));
1161     case ID_TE:
1162       return (ELEM(id_type_used, ID_IM, ID_OB));
1163     case ID_LT:
1164       return ELEM(id_type_used, ID_KE);
1165     case ID_LA:
1166       return (ELEM(id_type_used, ID_TE));
1167     case ID_CA:
1168       return ELEM(id_type_used, ID_OB);
1169     case ID_KE:
1170       return ELEM(id_type_used,
1171                   ID_ME,
1172                   ID_CU,
1173                   ID_LT); /* Warning! key->from, could be more types in future? */
1174     case ID_SCR:
1175       return ELEM(id_type_used, ID_SCE);
1176     case ID_WO:
1177       return (ELEM(id_type_used, ID_TE));
1178     case ID_SPK:
1179       return ELEM(id_type_used, ID_SO);
1180     case ID_GR:
1181       return ELEM(id_type_used, ID_OB, ID_GR);
1182     case ID_NT:
1183       /* Could be more specific, but node.id has no type restriction... */
1184       return true;
1185     case ID_BR:
1186       return ELEM(id_type_used, ID_BR, ID_IM, ID_PC, ID_TE, ID_MA);
1187     case ID_PA:
1188       return ELEM(id_type_used, ID_OB, ID_GR, ID_TE);
1189     case ID_MC:
1190       return ELEM(id_type_used, ID_GD, ID_IM);
1191     case ID_MSK:
1192       return ELEM(id_type_used, ID_MC); /* WARNING! mask->parent.id, not typed. */
1193     case ID_LS:
1194       return (ELEM(id_type_used, ID_TE, ID_OB));
1195     case ID_LP:
1196       return ELEM(id_type_used, ID_IM);
1197     case ID_GD:
1198       return ELEM(id_type_used, ID_MA);
1199     case ID_WS:
1200       return ELEM(id_type_used, ID_SCR, ID_SCE);
1201     case ID_IM:
1202     case ID_VF:
1203     case ID_TXT:
1204     case ID_SO:
1205     case ID_AR:
1206     case ID_AC:
1207     case ID_WM:
1208     case ID_PAL:
1209     case ID_PC:
1210     case ID_CF:
1211       /* Those types never use/reference other IDs... */
1212       return false;
1213     case ID_IP:
1214       /* Deprecated... */
1215       return false;
1216   }
1217   return false;
1218 }
1219
1220 /* ***** ID users iterator. ***** */
1221 typedef struct IDUsersIter {
1222   ID *id;
1223
1224   ListBase *lb_array[MAX_LIBARRAY];
1225   int lb_idx;
1226
1227   ID *curr_id;
1228   int count_direct, count_indirect; /* Set by callback. */
1229 } IDUsersIter;
1230
1231 static int foreach_libblock_id_users_callback(void *user_data,
1232                                               ID *UNUSED(self_id),
1233                                               ID **id_p,
1234                                               int cb_flag)
1235 {
1236   IDUsersIter *iter = user_data;
1237
1238   if (*id_p) {
1239     /* 'Loopback' ID pointers (the ugly 'from' ones, Object->proxy_from and Key->from).
1240      * Those are not actually ID usage, we can ignore them here.
1241      */
1242     if (cb_flag & IDWALK_CB_LOOPBACK) {
1243       return IDWALK_RET_NOP;
1244     }
1245
1246     if (*id_p == iter->id) {
1247 #if 0
1248       printf(
1249           "%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, "
1250           "indirect_usage: %d)\n",
1251           iter->curr_id->name,
1252           iter->id->name,
1253           (cb_flag & IDWALK_USER) ? 1 : 0,
1254           (cb_flag & IDWALK_USER_ONE) ? 1 : 0,
1255           (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0,
1256           (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0,
1257           (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0);
1258 #endif
1259       if (cb_flag & IDWALK_CB_INDIRECT_USAGE) {
1260         iter->count_indirect++;
1261       }
1262       else {
1263         iter->count_direct++;
1264       }
1265     }
1266   }
1267
1268   return IDWALK_RET_NOP;
1269 }
1270
1271 /**
1272  * Return the number of times given \a id_user uses/references \a id_used.
1273  *
1274  * \note This only checks for pointer references of an ID, shallow usages
1275  * (like e.g. by RNA paths, as done for FCurves) are not detected at all.
1276  *
1277  * \param id_user: the ID which is supposed to use (reference) \a id_used.
1278  * \param id_used: the ID which is supposed to be used (referenced) by \a id_user.
1279  * \return the number of direct usages/references of \a id_used by \a id_user.
1280  */
1281 int BKE_library_ID_use_ID(ID *id_user, ID *id_used)
1282 {
1283   IDUsersIter iter;
1284
1285   /* We do not care about iter.lb_array/lb_idx here... */
1286   iter.id = id_used;
1287   iter.curr_id = id_user;
1288   iter.count_direct = iter.count_indirect = 0;
1289
1290   BKE_library_foreach_ID_link(
1291       NULL, iter.curr_id, foreach_libblock_id_users_callback, (void *)&iter, IDWALK_READONLY);
1292
1293   return iter.count_direct + iter.count_indirect;
1294 }
1295
1296 static bool library_ID_is_used(Main *bmain, void *idv, const bool check_linked)
1297 {
1298   IDUsersIter iter;
1299   ListBase *lb_array[MAX_LIBARRAY];
1300   ID *id = idv;
1301   int i = set_listbasepointers(bmain, lb_array);
1302   bool is_defined = false;
1303
1304   iter.id = id;
1305   iter.count_direct = iter.count_indirect = 0;
1306   while (i-- && !is_defined) {
1307     ID *id_curr = lb_array[i]->first;
1308
1309     if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
1310       continue;
1311     }
1312
1313     for (; id_curr && !is_defined; id_curr = id_curr->next) {
1314       if (id_curr == id) {
1315         /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1316         continue;
1317       }
1318       iter.curr_id = id_curr;
1319       BKE_library_foreach_ID_link(
1320           bmain, id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_READONLY);
1321
1322       is_defined = ((check_linked ? iter.count_indirect : iter.count_direct) != 0);
1323     }
1324   }
1325
1326   return is_defined;
1327 }
1328
1329 /**
1330  * Check whether given ID is used locally (i.e. by another non-linked ID).
1331  */
1332 bool BKE_library_ID_is_locally_used(Main *bmain, void *idv)
1333 {
1334   return library_ID_is_used(bmain, idv, false);
1335 }
1336
1337 /**
1338  * Check whether given ID is used indirectly (i.e. by another linked ID).
1339  */
1340 bool BKE_library_ID_is_indirectly_used(Main *bmain, void *idv)
1341 {
1342   return library_ID_is_used(bmain, idv, true);
1343 }
1344
1345 /**
1346  * Combine #BKE_library_ID_is_locally_used() and #BKE_library_ID_is_indirectly_used()
1347  * in a single call.
1348  */
1349 void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, bool *is_used_linked)
1350 {
1351   IDUsersIter iter;
1352   ListBase *lb_array[MAX_LIBARRAY];
1353   ID *id = idv;
1354   int i = set_listbasepointers(bmain, lb_array);
1355   bool is_defined = false;
1356
1357   iter.id = id;
1358   iter.count_direct = iter.count_indirect = 0;
1359   while (i-- && !is_defined) {
1360     ID *id_curr = lb_array[i]->first;
1361
1362     if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
1363       continue;
1364     }
1365
1366     for (; id_curr && !is_defined; id_curr = id_curr->next) {
1367       if (id_curr == id) {
1368         /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1369         continue;
1370       }
1371       iter.curr_id = id_curr;
1372       BKE_library_foreach_ID_link(
1373           bmain, id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_READONLY);
1374
1375       is_defined = (iter.count_direct != 0 && iter.count_indirect != 0);
1376     }
1377   }
1378
1379   *is_used_local = (iter.count_direct != 0);
1380   *is_used_linked = (iter.count_indirect != 0);
1381 }
1382
1383 /* ***** IDs usages.checking/tagging. ***** */
1384 static int foreach_libblock_used_linked_data_tag_clear_cb(void *user_data,
1385                                                           ID *self_id,
1386                                                           ID **id_p,
1387                                                           int cb_flag)
1388 {
1389   bool *is_changed = user_data;
1390
1391   if (*id_p) {
1392     /* The infamous 'from' pointers (Key.from, Object.proxy_from, ...).
1393      * those are not actually ID usage, so we ignore them here. */
1394     if (cb_flag & IDWALK_CB_LOOPBACK) {
1395       return IDWALK_RET_NOP;
1396     }
1397
1398     /* If checked id is used by an assumed used ID,
1399      * then it is also used and not part of any linked archipelago. */
1400     if (!(self_id->tag & LIB_TAG_DOIT) && ((*id_p)->tag & LIB_TAG_DOIT)) {
1401       (*id_p)->tag &= ~LIB_TAG_DOIT;
1402       *is_changed = true;
1403     }
1404   }
1405
1406   return IDWALK_RET_NOP;
1407 }
1408
1409 /**
1410  * Detect orphaned linked data blocks (i.e. linked data not used (directly or indirectly)
1411  * in any way by any local data), including complex cases like 'linked archipelagoes', i.e.
1412  * linked datablocks that use each other in loops,
1413  * which prevents their deletion by 'basic' usage checks.
1414  *
1415  * \param do_init_tag: if \a true, all linked data are checked, if \a false,
1416  * only linked datablocks already tagged with #LIB_TAG_DOIT are checked.
1417  */
1418 void BKE_library_unused_linked_data_set_tag(Main *bmain, const bool do_init_tag)
1419 {
1420   ID *id;
1421
1422   if (do_init_tag) {
1423     FOREACH_MAIN_ID_BEGIN (bmain, id) {
1424       if (id->lib && (id->tag & LIB_TAG_INDIRECT) != 0) {
1425         id->tag |= LIB_TAG_DOIT;
1426       }
1427       else {
1428         id->tag &= ~LIB_TAG_DOIT;
1429       }
1430     }
1431     FOREACH_MAIN_ID_END;
1432   }
1433
1434   for (bool do_loop = true; do_loop;) {
1435     do_loop = false;
1436     FOREACH_MAIN_ID_BEGIN (bmain, id) {
1437       /* We only want to check that ID if it is currently known as used... */
1438       if ((id->tag & LIB_TAG_DOIT) == 0) {
1439         BKE_library_foreach_ID_link(
1440             bmain, id, foreach_libblock_used_linked_data_tag_clear_cb, &do_loop, IDWALK_READONLY);
1441       }
1442     }
1443     FOREACH_MAIN_ID_END;
1444   }
1445 }
1446
1447 /**
1448  * Untag linked data blocks used by other untagged linked datablocks.
1449  * Used to detect datablocks that we can forcefully make local
1450  * (instead of copying them to later get rid of original):
1451  * All datablocks we want to make local are tagged by caller,
1452  * after this function has ran caller knows datablocks still tagged can directly be made local,
1453  * since they are only used by other datablocks that will also be made fully local.
1454  */
1455 void BKE_library_indirectly_used_data_tag_clear(Main *bmain)
1456 {
1457   ListBase *lb_array[MAX_LIBARRAY];
1458
1459   bool do_loop = true;
1460   while (do_loop) {
1461     int i = set_listbasepointers(bmain, lb_array);
1462     do_loop = false;
1463
1464     while (i--) {
1465       for (ID *id = lb_array[i]->first; id; id = id->next) {
1466         if (id->lib == NULL || id->tag & LIB_TAG_DOIT) {
1467           /* Local or non-indirectly-used ID (so far), no need to check it further. */
1468           continue;
1469         }
1470         BKE_library_foreach_ID_link(
1471             bmain, id, foreach_libblock_used_linked_data_tag_clear_cb, &do_loop, IDWALK_READONLY);
1472       }
1473     }
1474   }
1475 }