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