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