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