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