Removed the ID_PA code used for ParticleSettings.
[blender.git] / source / blender / blenkernel / intern / library.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/library.c
29  *  \ingroup bke
30  *
31  * Contains management of ID's and libraries
32  * allocate and free of all library data
33  */
34
35 #include <stdio.h>
36 #include <ctype.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <stddef.h>
40 #include <assert.h>
41
42 #include "MEM_guardedalloc.h"
43
44 /* all types are needed here, in order to do memory operations */
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_brush_types.h"
48 #include "DNA_camera_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_gpencil_types.h"
51 #include "DNA_ipo_types.h"
52 #include "DNA_key_types.h"
53 #include "DNA_lamp_types.h"
54 #include "DNA_lattice_types.h"
55 #include "DNA_linestyle_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meta_types.h"
59 #include "DNA_movieclip_types.h"
60 #include "DNA_mask_types.h"
61 #include "DNA_node_types.h"
62 #include "DNA_object_types.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_screen_types.h"
65 #include "DNA_speaker_types.h"
66 #include "DNA_sound_types.h"
67 #include "DNA_text_types.h"
68 #include "DNA_vfont_types.h"
69 #include "DNA_windowmanager_types.h"
70 #include "DNA_world_types.h"
71
72 #include "BLI_blenlib.h"
73 #include "BLI_utildefines.h"
74
75 #include "BLI_threads.h"
76 #include "BLT_translation.h"
77
78 #include "BKE_action.h"
79 #include "BKE_animsys.h"
80 #include "BKE_armature.h"
81 #include "BKE_bpath.h"
82 #include "BKE_brush.h"
83 #include "BKE_camera.h"
84 #include "BKE_context.h"
85 #include "BKE_curve.h"
86 #include "BKE_depsgraph.h"
87 #include "BKE_fcurve.h"
88 #include "BKE_font.h"
89 #include "BKE_global.h"
90 #include "BKE_group.h"
91 #include "BKE_gpencil.h"
92 #include "BKE_idcode.h"
93 #include "BKE_idprop.h"
94 #include "BKE_image.h"
95 #include "BKE_ipo.h"
96 #include "BKE_key.h"
97 #include "BKE_lamp.h"
98 #include "BKE_lattice.h"
99 #include "BKE_library.h"
100 #include "BKE_library_query.h"
101 #include "BKE_linestyle.h"
102 #include "BKE_mesh.h"
103 #include "BKE_material.h"
104 #include "BKE_main.h"
105 #include "BKE_mball.h"
106 #include "BKE_movieclip.h"
107 #include "BKE_mask.h"
108 #include "BKE_node.h"
109 #include "BKE_object.h"
110 #include "BKE_paint.h"
111 #include "BKE_packedFile.h"
112 #include "BKE_speaker.h"
113 #include "BKE_sound.h"
114 #include "BKE_screen.h"
115 #include "BKE_scene.h"
116 #include "BKE_text.h"
117 #include "BKE_texture.h"
118 #include "BKE_world.h"
119
120 #include "DEG_depsgraph.h"
121
122 #include "RNA_access.h"
123
124 #include "IMB_imbuf.h"
125 #include "IMB_imbuf_types.h"
126
127 #ifdef WITH_PYTHON
128 #include "BPY_extern.h"
129 #endif
130
131 /* GS reads the memory pointed at in a specific ordering. 
132  * only use this definition, makes little and big endian systems
133  * work fine, in conjunction with MAKE_ID */
134
135 /* ************* general ************************ */
136
137
138 /* this has to be called from each make_local_* func, we could call
139  * from id_make_local() but then the make local functions would not be self
140  * contained.
141  * also note that the id _must_ have a library - campbell */
142 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
143 {
144         const char *bpath_user_data[2] = {bmain->name, lib->filepath};
145
146         BKE_bpath_traverse_id(bmain, id,
147                               BKE_bpath_relocate_visitor,
148                               BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
149                               (void *)bpath_user_data);
150 }
151
152 void id_lib_extern(ID *id)
153 {
154         if (id) {
155                 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
156                 if (id->tag & LIB_TAG_INDIRECT) {
157                         id->tag -= LIB_TAG_INDIRECT;
158                         id->tag |= LIB_TAG_EXTERN;
159                 }
160         }
161 }
162
163 /* ensure we have a real user */
164 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
165  *       we always have a real user.
166  *       However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
167  *       to make this change... */
168 void id_us_ensure_real(ID *id)
169 {
170         if (id) {
171                 const int limit = ID_FAKE_USERS(id);
172                 id->tag |= LIB_TAG_EXTRAUSER;
173                 if (id->us <= limit) {
174                         if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
175                                 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
176                                 BLI_assert(0);
177                         }
178                         id->us = limit + 1;
179                         id->tag |= LIB_TAG_EXTRAUSER_SET;
180                 }
181         }
182 }
183
184 /* Unused currently... */
185 void id_us_clear_real(ID *id)
186 {
187         if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
188                 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
189                         id->us--;
190                         BLI_assert(id->us >= ID_FAKE_USERS(id));
191                 }
192                 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
193         }
194 }
195
196 /**
197  * Same as \a id_us_plus, but does not handle lib indirect -> extern.
198  * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
199  */
200 void id_us_plus_no_lib(ID *id)
201 {
202         if (id) {
203                 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
204                         BLI_assert(id->us >= 1);
205                         /* No need to increase count, just tag extra user as no more set.
206                          * Avoids annoying & inconsistent +1 in user count. */
207                         id->tag &= ~LIB_TAG_EXTRAUSER_SET;
208                 }
209                 else {
210                         BLI_assert(id->us >= 0);
211                         id->us++;
212                 }
213         }
214 }
215
216
217 void id_us_plus(ID *id)
218 {
219         if (id) {
220                 id_us_plus_no_lib(id);
221                 id_lib_extern(id);
222         }
223 }
224
225 /* decrements the user count for *id. */
226 void id_us_min(ID *id)
227 {
228         if (id) {
229                 const int limit = ID_FAKE_USERS(id);
230
231                 if (id->us <= limit) {
232                         printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
233                                id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
234                         /* We cannot assert here, because of how we 'delete' datablocks currently (setting their usercount to zero),
235                          * this is weak but it's how it works for now. */
236                         /* BLI_assert(0); */
237                         id->us = limit;
238                 }
239                 else {
240                         id->us--;
241                 }
242
243                 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
244                         /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
245                         id_us_ensure_real(id);
246                 }
247         }
248 }
249
250 void id_fake_user_set(ID *id)
251 {
252         if (id && !(id->flag & LIB_FAKEUSER)) {
253                 id->flag |= LIB_FAKEUSER;
254                 id_us_plus(id);
255         }
256 }
257
258 void id_fake_user_clear(ID *id)
259 {
260         if (id && (id->flag & LIB_FAKEUSER)) {
261                 id->flag &= ~LIB_FAKEUSER;
262                 id_us_min(id);
263         }
264 }
265
266 /* calls the appropriate make_local method for the block, unless test. Returns true
267  * if the block can be made local. */
268 bool id_make_local(ID *id, bool test)
269 {
270         if (id->tag & LIB_TAG_INDIRECT)
271                 return false;
272
273         switch (GS(id->name)) {
274                 case ID_SCE:
275                         return false; /* not implemented */
276                 case ID_LI:
277                         return false; /* can't be linked */
278                 case ID_OB:
279                         if (!test) BKE_object_make_local((Object *)id);
280                         return true;
281                 case ID_ME:
282                         if (!test) {
283                                 BKE_mesh_make_local((Mesh *)id);
284                                 BKE_key_make_local(((Mesh *)id)->key);
285                         }
286                         return true;
287                 case ID_CU:
288                         if (!test) {
289                                 BKE_curve_make_local((Curve *)id);
290                                 BKE_key_make_local(((Curve *)id)->key);
291                         }
292                         return true;
293                 case ID_MB:
294                         if (!test) BKE_mball_make_local((MetaBall *)id);
295                         return true;
296                 case ID_MA:
297                         if (!test) BKE_material_make_local((Material *)id);
298                         return true;
299                 case ID_TE:
300                         if (!test) BKE_texture_make_local((Tex *)id);
301                         return true;
302                 case ID_IM:
303                         if (!test) BKE_image_make_local((Image *)id);
304                         return true;
305                 case ID_LT:
306                         if (!test) {
307                                 BKE_lattice_make_local((Lattice *)id);
308                                 BKE_key_make_local(((Lattice *)id)->key);
309                         }
310                         return true;
311                 case ID_LA:
312                         if (!test) BKE_lamp_make_local((Lamp *)id);
313                         return true;
314                 case ID_CA:
315                         if (!test) BKE_camera_make_local((Camera *)id);
316                         return true;
317                 case ID_SPK:
318                         if (!test) BKE_speaker_make_local((Speaker *)id);
319                         return true;
320                 case ID_IP:
321                         return false; /* deprecated */
322                 case ID_KE:
323                         if (!test) BKE_key_make_local((Key *)id);
324                         return true;
325                 case ID_WO:
326                         if (!test) BKE_world_make_local((World *)id);
327                         return true;
328                 case ID_SCR:
329                         return false; /* can't be linked */
330                 case ID_VF:
331                         return false; /* not implemented */
332                 case ID_TXT:
333                         return false; /* not implemented */
334                 case ID_SO:
335                         return false; /* not implemented */
336                 case ID_GR:
337                         return false; /* not implemented */
338                 case ID_AR:
339                         if (!test) BKE_armature_make_local((bArmature *)id);
340                         return true;
341                 case ID_AC:
342                         if (!test) BKE_action_make_local((bAction *)id);
343                         return true;
344                 case ID_NT:
345                         if (!test) ntreeMakeLocal((bNodeTree *)id, true);
346                         return true;
347                 case ID_BR:
348                         if (!test) BKE_brush_make_local((Brush *)id);
349                         return true;
350                 case ID_WM:
351                         return false; /* can't be linked */
352                 case ID_GD:
353                         return false; /* not implemented */
354                 case ID_LS:
355                         return false; /* not implemented */
356         }
357
358         return false;
359 }
360
361 /**
362  * Invokes the appropriate copy method for the block and returns the result in
363  * newid, unless test. Returns true if the block can be copied.
364  */
365 bool id_copy(ID *id, ID **newid, bool test)
366 {
367         if (!test) *newid = NULL;
368
369         /* conventions:
370          * - make shallow copy, only this ID block
371          * - id.us of the new ID is set to 1 */
372         switch (GS(id->name)) {
373                 case ID_SCE:
374                         return false;  /* can't be copied from here */
375                 case ID_LI:
376                         return false;  /* can't be copied from here */
377                 case ID_OB:
378                         if (!test) *newid = (ID *)BKE_object_copy((Object *)id);
379                         return true;
380                 case ID_ME:
381                         if (!test) *newid = (ID *)BKE_mesh_copy((Mesh *)id);
382                         return true;
383                 case ID_CU:
384                         if (!test) *newid = (ID *)BKE_curve_copy((Curve *)id);
385                         return true;
386                 case ID_MB:
387                         if (!test) *newid = (ID *)BKE_mball_copy((MetaBall *)id);
388                         return true;
389                 case ID_MA:
390                         if (!test) *newid = (ID *)BKE_material_copy((Material *)id);
391                         return true;
392                 case ID_TE:
393                         if (!test) *newid = (ID *)BKE_texture_copy((Tex *)id);
394                         return true;
395                 case ID_IM:
396                         if (!test) *newid = (ID *)BKE_image_copy(G.main, (Image *)id);
397                         return true;
398                 case ID_LT:
399                         if (!test) *newid = (ID *)BKE_lattice_copy((Lattice *)id);
400                         return true;
401                 case ID_LA:
402                         if (!test) *newid = (ID *)BKE_lamp_copy((Lamp *)id);
403                         return true;
404                 case ID_SPK:
405                         if (!test) *newid = (ID *)BKE_speaker_copy((Speaker *)id);
406                         return true;
407                 case ID_CA:
408                         if (!test) *newid = (ID *)BKE_camera_copy((Camera *)id);
409                         return true;
410                 case ID_IP:
411                         return false;  /* deprecated */
412                 case ID_KE:
413                         if (!test) *newid = (ID *)BKE_key_copy((Key *)id);
414                         return true;
415                 case ID_WO:
416                         if (!test) *newid = (ID *)BKE_world_copy((World *)id);
417                         return true;
418                 case ID_SCR:
419                         return false;  /* can't be copied from here */
420                 case ID_VF:
421                         return false;  /* not implemented */
422                 case ID_TXT:
423                         if (!test) *newid = (ID *)BKE_text_copy(G.main, (Text *)id);
424                         return true;
425                 case ID_SO:
426                         return false;  /* not implemented */
427                 case ID_GR:
428                         if (!test) *newid = (ID *)BKE_group_copy((Group *)id);
429                         return true;
430                 case ID_AR:
431                         if (!test) *newid = (ID *)BKE_armature_copy((bArmature *)id);
432                         return true;
433                 case ID_AC:
434                         if (!test) *newid = (ID *)BKE_action_copy((bAction *)id);
435                         return true;
436                 case ID_NT:
437                         if (!test) *newid = (ID *)ntreeCopyTree((bNodeTree *)id);
438                         return true;
439                 case ID_BR:
440                         if (!test) *newid = (ID *)BKE_brush_copy((Brush *)id);
441                         return true;
442                 case ID_WM:
443                         return false;  /* can't be copied from here */
444                 case ID_GD:
445                         if (!test) *newid = (ID *)gpencil_data_duplicate((bGPdata *)id, false);
446                         return true;
447                 case ID_MSK:
448                         if (!test) *newid = (ID *)BKE_mask_copy((Mask *)id);
449                         return true;
450                 case ID_LS:
451                         if (!test) *newid = (ID *)BKE_linestyle_copy(G.main, (FreestyleLineStyle *)id);
452                         return true;
453         }
454         
455         return false;
456 }
457
458 bool id_unlink(ID *id, int test)
459 {
460         Main *mainlib = G.main;
461         short type = GS(id->name);
462
463         switch (type) {
464                 case ID_TXT:
465                         if (test) return true;
466                         BKE_text_unlink(mainlib, (Text *)id);
467                         break;
468                 case ID_GR:
469                         if (test) return true;
470                         BKE_group_unlink(mainlib, (Group *)id);
471                         break;
472                 case ID_OB:
473                         if (test) return true;
474                         BKE_object_unlink(mainlib, (Object *)id);
475                         break;
476         }
477
478         if (id->us == 0) {
479                 if (test) return true;
480
481                 BKE_libblock_free(mainlib, id);
482
483                 return true;
484         }
485
486         return false;
487 }
488
489 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
490 {
491         ID *newid = NULL;
492         PointerRNA idptr;
493         
494         if (id) {
495                 /* if property isn't editable, we're going to have an extra block hanging around until we save */
496                 if (RNA_property_editable(ptr, prop)) {
497                         if (id_copy(id, &newid, false) && newid) {
498                                 /* copy animation actions too */
499                                 BKE_animdata_copy_id_action(id);
500                                 /* us is 1 by convention, but RNA_property_pointer_set
501                                  * will also increment it, so set it to zero */
502                                 newid->us = 0;
503                                 
504                                 /* assign copy */
505                                 RNA_id_pointer_create(newid, &idptr);
506                                 RNA_property_pointer_set(ptr, prop, idptr);
507                                 RNA_property_update(C, ptr, prop);
508                                 
509                                 return true;
510                         }
511                 }
512         }
513         
514         return false;
515 }
516
517 ListBase *which_libbase(Main *mainlib, short type)
518 {
519         switch (type) {
520                 case ID_SCE:
521                         return &(mainlib->scene);
522                 case ID_LI:
523                         return &(mainlib->library);
524                 case ID_OB:
525                         return &(mainlib->object);
526                 case ID_ME:
527                         return &(mainlib->mesh);
528                 case ID_CU:
529                         return &(mainlib->curve);
530                 case ID_MB:
531                         return &(mainlib->mball);
532                 case ID_MA:
533                         return &(mainlib->mat);
534                 case ID_TE:
535                         return &(mainlib->tex);
536                 case ID_IM:
537                         return &(mainlib->image);
538                 case ID_LT:
539                         return &(mainlib->latt);
540                 case ID_LA:
541                         return &(mainlib->lamp);
542                 case ID_CA:
543                         return &(mainlib->camera);
544                 case ID_IP:
545                         return &(mainlib->ipo);
546                 case ID_KE:
547                         return &(mainlib->key);
548                 case ID_WO:
549                         return &(mainlib->world);
550                 case ID_SCR:
551                         return &(mainlib->screen);
552                 case ID_VF:
553                         return &(mainlib->vfont);
554                 case ID_TXT:
555                         return &(mainlib->text);
556                 case ID_SPK:
557                         return &(mainlib->speaker);
558                 case ID_SO:
559                         return &(mainlib->sound);
560                 case ID_GR:
561                         return &(mainlib->group);
562                 case ID_AR:
563                         return &(mainlib->armature);
564                 case ID_AC:
565                         return &(mainlib->action);
566                 case ID_NT:
567                         return &(mainlib->nodetree);
568                 case ID_BR:
569                         return &(mainlib->brush);
570                 case ID_WM:
571                         return &(mainlib->wm);
572                 case ID_GD:
573                         return &(mainlib->gpencil);
574                 case ID_MC:
575                         return &(mainlib->movieclip);
576                 case ID_MSK:
577                         return &(mainlib->mask);
578                 case ID_LS:
579                         return &(mainlib->linestyle);
580                 case ID_PAL:
581                         return &(mainlib->palettes);
582                 case ID_PC:
583                         return &(mainlib->paintcurves);
584         }
585         return NULL;
586 }
587
588 /**
589  * Clear or set given tags for all ids in listbase (runtime tags).
590  */
591 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
592 {
593         ID *id;
594         if (value) {
595                 for (id = lb->first; id; id = id->next) {
596                         id->tag |= tag;
597                 }
598         }
599         else {
600                 const int ntag = ~tag;
601                 for (id = lb->first; id; id = id->next) {
602                         id->tag &= ntag;
603                 }
604         }
605 }
606
607 /**
608  * Clear or set given tags for all ids of given type in bmain (runtime tags).
609  */
610 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
611 {
612         ListBase *lb = which_libbase(mainvar, type);
613
614         BKE_main_id_tag_listbase(lb, tag, value);
615 }
616
617 /**
618  * Clear or set given tags for all ids in bmain (runtime tags).
619  */
620 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
621 {
622         ListBase *lbarray[MAX_LIBARRAY];
623         int a;
624
625         a = set_listbasepointers(mainvar, lbarray);
626         while (a--) {
627                 BKE_main_id_tag_listbase(lbarray[a], tag, value);
628         }
629 }
630
631
632 /**
633  * Clear or set given flags for all ids in listbase (persistent flags).
634  */
635 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
636 {
637         ID *id;
638         if (value) {
639                 for (id = lb->first; id; id = id->next)
640                         id->tag |= flag;
641         }
642         else {
643                 const int nflag = ~flag;
644                 for (id = lb->first; id; id = id->next)
645                         id->tag &= nflag;
646         }
647 }
648
649 /**
650  * Clear or set given flags for all ids in bmain (persistent flags).
651  */
652 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
653 {
654         ListBase *lbarray[MAX_LIBARRAY];
655         int a;
656         a = set_listbasepointers(bmain, lbarray);
657         while (a--) {
658                 BKE_main_id_flag_listbase(lbarray[a], flag, value);
659         }
660 }
661
662 void BKE_main_lib_objects_recalc_all(Main *bmain)
663 {
664         Object *ob;
665
666         /* flag for full recalc */
667         for (ob = bmain->object.first; ob; ob = ob->id.next) {
668                 if (ob->id.lib) {
669                         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
670                 }
671         }
672
673         DAG_id_type_tag(bmain, ID_OB);
674 }
675
676 /**
677  * puts into array *lb pointers to all the ListBase structs in main,
678  * and returns the number of them as the function result. This is useful for
679  * generic traversal of all the blocks in a Main (by traversing all the
680  * lists in turn), without worrying about block types.
681  *
682  * \note MAX_LIBARRAY define should match this code */
683 int set_listbasepointers(Main *main, ListBase **lb)
684 {
685         int a = 0;
686
687         /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
688          * This is important because freeing data decreases usercounts of other datablocks,
689          * if this data is its self freed it can crash. */
690         lb[a++] = &(main->library);  /* Libraries may be accessed from pretty much any other ID... */
691         lb[a++] = &(main->ipo);
692         lb[a++] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
693         lb[a++] = &(main->key);
694         lb[a++] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
695         lb[a++] = &(main->nodetree);
696         lb[a++] = &(main->image);
697         lb[a++] = &(main->tex);
698         lb[a++] = &(main->mat);
699         lb[a++] = &(main->vfont);
700         
701         /* Important!: When adding a new object type,
702          * the specific data should be inserted here 
703          */
704
705         lb[a++] = &(main->armature);
706
707         lb[a++] = &(main->mesh);
708         lb[a++] = &(main->curve);
709         lb[a++] = &(main->mball);
710
711         lb[a++] = &(main->latt);
712         lb[a++] = &(main->lamp);
713         lb[a++] = &(main->camera);
714
715         lb[a++] = &(main->text);
716         lb[a++] = &(main->sound);
717         lb[a++] = &(main->group);
718         lb[a++] = &(main->palettes);
719         lb[a++] = &(main->paintcurves);
720         lb[a++] = &(main->brush);
721         lb[a++] = &(main->particle);
722         lb[a++] = &(main->speaker);
723
724         lb[a++] = &(main->world);
725         lb[a++] = &(main->movieclip);
726         lb[a++] = &(main->screen);
727         lb[a++] = &(main->object);
728         lb[a++] = &(main->linestyle); /* referenced by scenes */
729         lb[a++] = &(main->scene);
730         lb[a++] = &(main->wm);
731         lb[a++] = &(main->mask);
732         
733         lb[a] = NULL;
734
735         BLI_assert(a + 1 == MAX_LIBARRAY);
736
737         return a;
738 }
739
740 /* *********** ALLOC AND FREE *****************
741  *
742  * BKE_libblock_free(ListBase *lb, ID *id )
743  * provide a list-basis and datablock, but only ID is read
744  *
745  * void *BKE_libblock_alloc(ListBase *lb, type, name)
746  * inserts in list and returns a new ID
747  *
748  * **************************** */
749
750 /**
751  * Allocates and returns memory of the right size for the specified block type,
752  * initialized to zero.
753  */
754 void *BKE_libblock_alloc_notest(short type)
755 {
756         ID *id = NULL;
757         
758         switch (type) {
759                 case ID_SCE:
760                         id = MEM_callocN(sizeof(Scene), "scene");
761                         break;
762                 case ID_LI:
763                         id = MEM_callocN(sizeof(Library), "library");
764                         break;
765                 case ID_OB:
766                         id = MEM_callocN(sizeof(Object), "object");
767                         break;
768                 case ID_ME:
769                         id = MEM_callocN(sizeof(Mesh), "mesh");
770                         break;
771                 case ID_CU:
772                         id = MEM_callocN(sizeof(Curve), "curve");
773                         break;
774                 case ID_MB:
775                         id = MEM_callocN(sizeof(MetaBall), "mball");
776                         break;
777                 case ID_MA:
778                         id = MEM_callocN(sizeof(Material), "mat");
779                         break;
780                 case ID_TE:
781                         id = MEM_callocN(sizeof(Tex), "tex");
782                         break;
783                 case ID_IM:
784                         id = MEM_callocN(sizeof(Image), "image");
785                         break;
786                 case ID_LT:
787                         id = MEM_callocN(sizeof(Lattice), "latt");
788                         break;
789                 case ID_LA:
790                         id = MEM_callocN(sizeof(Lamp), "lamp");
791                         break;
792                 case ID_CA:
793                         id = MEM_callocN(sizeof(Camera), "camera");
794                         break;
795                 case ID_IP:
796                         id = MEM_callocN(sizeof(Ipo), "ipo");
797                         break;
798                 case ID_KE:
799                         id = MEM_callocN(sizeof(Key), "key");
800                         break;
801                 case ID_WO:
802                         id = MEM_callocN(sizeof(World), "world");
803                         break;
804                 case ID_SCR:
805                         id = MEM_callocN(sizeof(bScreen), "screen");
806                         break;
807                 case ID_VF:
808                         id = MEM_callocN(sizeof(VFont), "vfont");
809                         break;
810                 case ID_TXT:
811                         id = MEM_callocN(sizeof(Text), "text");
812                         break;
813                 case ID_SPK:
814                         id = MEM_callocN(sizeof(Speaker), "speaker");
815                         break;
816                 case ID_SO:
817                         id = MEM_callocN(sizeof(bSound), "sound");
818                         break;
819                 case ID_GR:
820                         id = MEM_callocN(sizeof(Group), "group");
821                         break;
822                 case ID_AR:
823                         id = MEM_callocN(sizeof(bArmature), "armature");
824                         break;
825                 case ID_AC:
826                         id = MEM_callocN(sizeof(bAction), "action");
827                         break;
828                 case ID_NT:
829                         id = MEM_callocN(sizeof(bNodeTree), "nodetree");
830                         break;
831                 case ID_BR:
832                         id = MEM_callocN(sizeof(Brush), "brush");
833                         break;
834                 case ID_WM:
835                         id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
836                         break;
837                 case ID_GD:
838                         id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
839                         break;
840                 case ID_MC:
841                         id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
842                         break;
843                 case ID_MSK:
844                         id = MEM_callocN(sizeof(Mask), "Mask");
845                         break;
846                 case ID_LS:
847                         id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
848                         break;
849                 case ID_PAL:
850                         id = MEM_callocN(sizeof(Palette), "Palette");
851                         break;
852                 case ID_PC:
853                         id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
854                         break;
855         }
856         return id;
857 }
858
859 /**
860  * Allocates and returns a block of the specified type, with the specified name
861  * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
862  * The user count is set to 1, all other content (apart from name and links) being
863  * initialized to zero.
864  */
865 void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
866 {
867         ID *id = NULL;
868         ListBase *lb = which_libbase(bmain, type);
869         
870         id = BKE_libblock_alloc_notest(type);
871         if (id) {
872                 BKE_main_lock(bmain);
873                 BLI_addtail(lb, id);
874                 id->us = 1;
875                 id->icon_id = 0;
876                 *( (short *)id->name) = type;
877                 new_id(lb, id, name);
878                 /* alphabetic insertion: is in new_id */
879                 BKE_main_unlock(bmain);
880         }
881         DAG_id_type_tag(bmain, type);
882         return id;
883 }
884
885 /**
886  * Initialize an ID of given type, such that it has valid 'empty' data.
887  * ID is assumed to be just calloc'ed.
888  */
889 void BKE_libblock_init_empty(ID *id)
890 {
891         /* Note that only ID types that are not valid when filled of zero should have a callback here. */
892         switch (GS(id->name)) {
893                 case ID_SCE:
894                         BKE_scene_init((Scene *)id);
895                         break;
896                 case ID_LI:
897                         /* Nothing to do. */
898                         break;
899                 case ID_OB:
900                 {
901                         Object *ob = (Object *)id;
902                         ob->type = OB_EMPTY;
903                         BKE_object_init(ob);
904                         break;
905                 }
906                 case ID_ME:
907                         BKE_mesh_init((Mesh *)id);
908                         break;
909                 case ID_CU:
910                         BKE_curve_init((Curve *)id);
911                         break;
912                 case ID_MB:
913                         BKE_mball_init((MetaBall *)id);
914                         break;
915                 case ID_MA:
916                         BKE_material_init((Material *)id);
917                         break;
918                 case ID_TE:
919                         BKE_texture_default((Tex *)id);
920                         break;
921                 case ID_IM:
922                         /* Image is a bit complicated, for now assume NULLified im is OK. */
923                         break;
924                 case ID_LT:
925                         BKE_lattice_init((Lattice *)id);
926                         break;
927                 case ID_LA:
928                         BKE_lamp_init((Lamp *)id);
929                         break;
930                 case ID_SPK:
931                         BKE_speaker_init((Speaker *)id);
932                         break;
933                 case ID_CA:
934                         BKE_camera_init((Camera *)id);
935                         break;
936                 case ID_IP:
937                         /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
938                         BLI_assert(0);
939                         break;
940                 case ID_KE:
941                         /* Shapekeys are a complex topic too - they depend on their 'user' data type...
942                          * They are not linkable, though, so it should never reach here anyway. */
943                         BLI_assert(0);
944                         break;
945                 case ID_WO:
946                         BKE_world_init((World *)id);
947                         break;
948                 case ID_SCR:
949                         /* Nothing to do. */
950                         break;
951                 case ID_VF:
952                         BKE_vfont_init((VFont *)id);
953                         break;
954                 case ID_TXT:
955                         BKE_text_init((Text *)id);
956                         break;
957                 case ID_SO:
958                         /* Another fuzzy case, think NULLified content is OK here... */
959                         break;
960                 case ID_GR:
961                         /* Nothing to do. */
962                         break;
963                 case ID_AR:
964                         /* Nothing to do. */
965                         break;
966                 case ID_AC:
967                         /* Nothing to do. */
968                         break;
969                 case ID_NT:
970                         ntreeInitDefault((bNodeTree *)id);
971                         break;
972                 case ID_BR:
973                         BKE_brush_init((Brush *)id);
974                         break;
975                 case ID_PC:
976                         /* Nothing to do. */
977                         break;
978                 case ID_WM:
979                         /* We should never reach this. */
980                         BLI_assert(0);
981                         break;
982                 case ID_GD:
983                         /* Nothing to do. */
984                         break;
985                 case ID_MSK:
986                         /* Nothing to do. */
987                         break;
988                 case ID_LS:
989                         BKE_linestyle_init((FreestyleLineStyle *)id);
990                         break;
991         }
992 }
993
994 /* by spec, animdata is first item after ID */
995 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
996 static void id_copy_animdata(ID *id, const bool do_action)
997 {
998         AnimData *adt = BKE_animdata_from_id(id);
999         
1000         if (adt) {
1001                 IdAdtTemplate *iat = (IdAdtTemplate *)id;
1002                 iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
1003         }
1004 }
1005
1006 /* material nodes use this since they are not treated as libdata */
1007 void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
1008 {
1009         if (id_from->properties)
1010                 id->properties = IDP_CopyProperty(id_from->properties);
1011
1012         /* the duplicate should get a copy of the animdata */
1013         id_copy_animdata(id, do_action);
1014 }
1015
1016 /* used everywhere in blenkernel */
1017 void *BKE_libblock_copy_ex(Main *bmain, ID *id)
1018 {
1019         ID *idn;
1020         size_t idn_len;
1021
1022         idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
1023
1024         assert(idn != NULL);
1025
1026         idn_len = MEM_allocN_len(idn);
1027         if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1028                 const char *cp = (const char *)id;
1029                 char *cpn = (char *)idn;
1030
1031                 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1032         }
1033         
1034         id->newid = idn;
1035         idn->tag |= LIB_TAG_NEW;
1036
1037         BKE_libblock_copy_data(idn, id, false);
1038         
1039         return idn;
1040 }
1041
1042 void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
1043 {
1044         ID *idn;
1045         size_t idn_len;
1046
1047         idn = BKE_libblock_alloc_notest(GS(id->name));
1048         assert(idn != NULL);
1049
1050         BLI_strncpy(idn->name, id->name, sizeof(idn->name));
1051
1052         idn_len = MEM_allocN_len(idn);
1053         if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
1054                 const char *cp = (const char *)id;
1055                 char *cpn = (char *)idn;
1056
1057                 memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
1058         }
1059
1060         id->newid = idn;
1061         idn->tag |= LIB_TAG_NEW;
1062         idn->us = 1;
1063
1064         BKE_libblock_copy_data(idn, id, do_action);
1065
1066         return idn;
1067 }
1068
1069 void *BKE_libblock_copy(ID *id)
1070 {
1071         return BKE_libblock_copy_ex(G.main, id);
1072 }
1073
1074 static int id_relink_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cd_flag)
1075 {
1076         ID *id = *id_pointer;
1077         if (id) {
1078                 /* See: NEW_ID macro */
1079                 if (id->newid) {
1080                         BKE_library_update_ID_link_user(id->newid, id, cd_flag);
1081                         *id_pointer = id->newid;
1082                 }
1083                 else if (id->tag & LIB_TAG_NEW) {
1084                         id->tag &= ~LIB_TAG_NEW;
1085                         BKE_libblock_relink(id);
1086                 }
1087         }
1088         return IDWALK_RET_NOP;
1089 }
1090
1091 void BKE_libblock_relink(ID *id)
1092 {
1093         if (id->lib)
1094                 return;
1095
1096         BKE_library_foreach_ID_link(id, id_relink_looper, NULL, 0);
1097 }
1098
1099 static void BKE_library_free(Library *lib)
1100 {
1101         if (lib->packedfile)
1102                 freePackedFile(lib->packedfile);
1103 }
1104
1105 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
1106
1107 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
1108 {
1109         free_windowmanager_cb = func;
1110 }
1111
1112 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
1113
1114 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
1115 {
1116         free_notifier_reference_cb = func;
1117 }
1118
1119 static BKE_library_free_editor_id_reference_cb free_editor_id_reference_cb = NULL;
1120
1121 void BKE_library_callback_free_editor_id_reference_set(BKE_library_free_editor_id_reference_cb func)
1122 {
1123         free_editor_id_reference_cb = func;
1124 }
1125
1126 static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
1127 {
1128         ChannelDriver *driver;
1129         FCurve *fcu;
1130
1131         /* find the driver this belongs to and update it */
1132         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
1133                 driver = fcu->driver;
1134                 
1135                 if (driver) {
1136                         DriverVar *dvar;
1137                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1138                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
1139                                 {
1140                                         if (dtar->id == userdata)
1141                                                 dtar->id = NULL;
1142                                 }
1143                                 DRIVER_TARGETS_LOOPER_END
1144                         }
1145                 }
1146         }
1147 }
1148
1149 void BKE_libblock_free_data(Main *bmain, ID *id)
1150 {
1151         if (id->properties) {
1152                 IDP_FreeProperty(id->properties);
1153                 MEM_freeN(id->properties);
1154         }
1155         
1156         /* this ID may be a driver target! */
1157         BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
1158 }
1159
1160 /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
1161 void BKE_libblock_free_ex(Main *bmain, void *idv, bool do_id_user)
1162 {
1163         ID *id = idv;
1164         short type = GS(id->name);
1165         ListBase *lb = which_libbase(bmain, type);
1166
1167         DAG_id_type_tag(bmain, type);
1168
1169 #ifdef WITH_PYTHON
1170         BPY_id_release(id);
1171 #endif
1172
1173         switch (type) {    /* GetShort from util.h */
1174                 case ID_SCE:
1175                         BKE_scene_free((Scene *)id);
1176                         break;
1177                 case ID_LI:
1178                         BKE_library_free((Library *)id);
1179                         break;
1180                 case ID_OB:
1181                         BKE_object_free_ex((Object *)id, do_id_user);
1182                         break;
1183                 case ID_ME:
1184                         BKE_mesh_free((Mesh *)id, 1);
1185                         break;
1186                 case ID_CU:
1187                         BKE_curve_free((Curve *)id);
1188                         break;
1189                 case ID_MB:
1190                         BKE_mball_free((MetaBall *)id);
1191                         break;
1192                 case ID_MA:
1193                         BKE_material_free((Material *)id);
1194                         break;
1195                 case ID_TE:
1196                         BKE_texture_free((Tex *)id);
1197                         break;
1198                 case ID_IM:
1199                         BKE_image_free((Image *)id);
1200                         break;
1201                 case ID_LT:
1202                         BKE_lattice_free((Lattice *)id);
1203                         break;
1204                 case ID_LA:
1205                         BKE_lamp_free((Lamp *)id);
1206                         break;
1207                 case ID_CA:
1208                         BKE_camera_free((Camera *) id);
1209                         break;
1210                 case ID_IP:
1211                         BKE_ipo_free((Ipo *)id);
1212                         break;
1213                 case ID_KE:
1214                         BKE_key_free((Key *)id);
1215                         break;
1216                 case ID_WO:
1217                         BKE_world_free((World *)id);
1218                         break;
1219                 case ID_SCR:
1220                         BKE_screen_free((bScreen *)id);
1221                         break;
1222                 case ID_VF:
1223                         BKE_vfont_free((VFont *)id);
1224                         break;
1225                 case ID_TXT:
1226                         BKE_text_free((Text *)id);
1227                         break;
1228                 case ID_SPK:
1229                         BKE_speaker_free((Speaker *)id);
1230                         break;
1231                 case ID_SO:
1232                         BKE_sound_free((bSound *)id);
1233                         break;
1234                 case ID_GR:
1235                         BKE_group_free((Group *)id);
1236                         break;
1237                 case ID_AR:
1238                         BKE_armature_free((bArmature *)id);
1239                         break;
1240                 case ID_AC:
1241                         BKE_action_free((bAction *)id);
1242                         break;
1243                 case ID_NT:
1244                         ntreeFreeTree_ex((bNodeTree *)id, do_id_user);
1245                         break;
1246                 case ID_BR:
1247                         BKE_brush_free((Brush *)id);
1248                         break;
1249                 case ID_WM:
1250                         if (free_windowmanager_cb)
1251                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
1252                         break;
1253                 case ID_GD:
1254                         BKE_gpencil_free((bGPdata *)id);
1255                         break;
1256                 case ID_MC:
1257                         BKE_movieclip_free((MovieClip *)id);
1258                         break;
1259                 case ID_MSK:
1260                         BKE_mask_free(bmain, (Mask *)id);
1261                         break;
1262                 case ID_LS:
1263                         BKE_linestyle_free((FreestyleLineStyle *)id);
1264                         break;
1265                 case ID_PAL:
1266                         BKE_palette_free((Palette *)id);
1267                         break;
1268                 case ID_PC:
1269                         BKE_paint_curve_free((PaintCurve *)id);
1270                         break;
1271         }
1272
1273         /* avoid notifying on removed data */
1274         BKE_main_lock(bmain);
1275
1276         if (free_notifier_reference_cb) {
1277                 free_notifier_reference_cb(id);
1278         }
1279
1280         if (free_editor_id_reference_cb) {
1281                 free_editor_id_reference_cb(id);
1282         }
1283
1284         BLI_remlink(lb, id);
1285
1286         BKE_libblock_free_data(bmain, id);
1287         BKE_main_unlock(bmain);
1288
1289         MEM_freeN(id);
1290 }
1291
1292 void BKE_libblock_free(Main *bmain, void *idv)
1293 {
1294         BKE_libblock_free_ex(bmain, idv, true);
1295 }
1296
1297 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
1298 {
1299         ID *id = idv;
1300         
1301         id_us_min(id);
1302
1303         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
1304          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
1305          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
1306          *     fully unlinked.
1307          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
1308          */
1309         if ((GS(id->name) == ID_OB) && (id->us == 1)) {
1310                 id_us_clear_real(id);
1311         }
1312
1313         if (id->us == 0) {
1314                 switch (GS(id->name)) {
1315                         case ID_OB:
1316                                 BKE_object_unlink(bmain, (Object *)id);
1317                                 break;
1318                 }
1319                 
1320                 BKE_libblock_free(bmain, id);
1321         }
1322 }
1323
1324 Main *BKE_main_new(void)
1325 {
1326         Main *bmain = MEM_callocN(sizeof(Main), "new main");
1327         bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1328         bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1329         BLI_spin_init((SpinLock *)bmain->lock);
1330         return bmain;
1331 }
1332
1333 void BKE_main_free(Main *mainvar)
1334 {
1335         /* also call when reading a file, erase all, etc */
1336         ListBase *lbarray[MAX_LIBARRAY];
1337         int a;
1338
1339         MEM_SAFE_FREE(mainvar->blen_thumb);
1340
1341         a = set_listbasepointers(mainvar, lbarray);
1342         while (a--) {
1343                 ListBase *lb = lbarray[a];
1344                 ID *id;
1345                 
1346                 while ( (id = lb->first) ) {
1347 #if 1
1348                         BKE_libblock_free_ex(mainvar, id, false);
1349 #else
1350                         /* errors freeing ID's can be hard to track down,
1351                          * enable this so valgrind will give the line number in its error log */
1352                         switch (a) {
1353                                 case   0: BKE_libblock_free_ex(mainvar, id, false); break;
1354                                 case   1: BKE_libblock_free_ex(mainvar, id, false); break;
1355                                 case   2: BKE_libblock_free_ex(mainvar, id, false); break;
1356                                 case   3: BKE_libblock_free_ex(mainvar, id, false); break;
1357                                 case   4: BKE_libblock_free_ex(mainvar, id, false); break;
1358                                 case   5: BKE_libblock_free_ex(mainvar, id, false); break;
1359                                 case   6: BKE_libblock_free_ex(mainvar, id, false); break;
1360                                 case   7: BKE_libblock_free_ex(mainvar, id, false); break;
1361                                 case   8: BKE_libblock_free_ex(mainvar, id, false); break;
1362                                 case   9: BKE_libblock_free_ex(mainvar, id, false); break;
1363                                 case  10: BKE_libblock_free_ex(mainvar, id, false); break;
1364                                 case  11: BKE_libblock_free_ex(mainvar, id, false); break;
1365                                 case  12: BKE_libblock_free_ex(mainvar, id, false); break;
1366                                 case  13: BKE_libblock_free_ex(mainvar, id, false); break;
1367                                 case  14: BKE_libblock_free_ex(mainvar, id, false); break;
1368                                 case  15: BKE_libblock_free_ex(mainvar, id, false); break;
1369                                 case  16: BKE_libblock_free_ex(mainvar, id, false); break;
1370                                 case  17: BKE_libblock_free_ex(mainvar, id, false); break;
1371                                 case  18: BKE_libblock_free_ex(mainvar, id, false); break;
1372                                 case  19: BKE_libblock_free_ex(mainvar, id, false); break;
1373                                 case  20: BKE_libblock_free_ex(mainvar, id, false); break;
1374                                 case  21: BKE_libblock_free_ex(mainvar, id, false); break;
1375                                 case  22: BKE_libblock_free_ex(mainvar, id, false); break;
1376                                 case  23: BKE_libblock_free_ex(mainvar, id, false); break;
1377                                 case  24: BKE_libblock_free_ex(mainvar, id, false); break;
1378                                 case  25: BKE_libblock_free_ex(mainvar, id, false); break;
1379                                 case  26: BKE_libblock_free_ex(mainvar, id, false); break;
1380                                 case  27: BKE_libblock_free_ex(mainvar, id, false); break;
1381                                 case  28: BKE_libblock_free_ex(mainvar, id, false); break;
1382                                 case  29: BKE_libblock_free_ex(mainvar, id, false); break;
1383                                 case  30: BKE_libblock_free_ex(mainvar, id, false); break;
1384                                 case  31: BKE_libblock_free_ex(mainvar, id, false); break;
1385                                 case  32: BKE_libblock_free_ex(mainvar, id, false); break;
1386                                 case  33: BKE_libblock_free_ex(mainvar, id, false); break;
1387                                 default:
1388                                         BLI_assert(0);
1389                                         break;
1390                         }
1391 #endif
1392                 }
1393         }
1394
1395         BLI_spin_end((SpinLock *)mainvar->lock);
1396         MEM_freeN(mainvar->lock);
1397         DEG_evaluation_context_free(mainvar->eval_ctx);
1398         MEM_freeN(mainvar);
1399 }
1400
1401 void BKE_main_lock(struct Main *bmain)
1402 {
1403         BLI_spin_lock((SpinLock *) bmain->lock);
1404 }
1405
1406 void BKE_main_unlock(struct Main *bmain)
1407 {
1408         BLI_spin_unlock((SpinLock *) bmain->lock);
1409 }
1410
1411 /**
1412  * Generates a raw .blend file thumbnail data from given image.
1413  *
1414  * \param bmain If not NULL, also store generated data in this Main.
1415  * \param img ImBuf image to generate thumbnail data from.
1416  * \return The generated .blend file raw thumbnail data.
1417  */
1418 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1419 {
1420         BlendThumbnail *data = NULL;
1421
1422         if (bmain) {
1423                 MEM_SAFE_FREE(bmain->blen_thumb);
1424         }
1425
1426         if (img) {
1427                 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1428                 data = MEM_mallocN(sz, __func__);
1429
1430                 IMB_rect_from_float(img);  /* Just in case... */
1431                 data->width = img->x;
1432                 data->height = img->y;
1433                 memcpy(data->rect, img->rect, sz - sizeof(*data));
1434         }
1435
1436         if (bmain) {
1437                 bmain->blen_thumb = data;
1438         }
1439         return data;
1440 }
1441
1442 /**
1443  * Generates an image from raw .blend file thumbnail \a data.
1444  *
1445  * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1446  * \param data Raw .blend file thumbnail data.
1447  * \return An ImBuf from given data, or NULL if invalid.
1448  */
1449 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1450 {
1451         ImBuf *img = NULL;
1452
1453         if (!data && bmain) {
1454                 data = bmain->blen_thumb;
1455         }
1456
1457         if (data) {
1458                 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1459                  *       here (we do not want to pass the first two ints!). */
1460                 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1461                 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1462         }
1463
1464         return img;
1465 }
1466
1467 /**
1468  * Generates an empty (black) thumbnail for given Main.
1469  */
1470 void BKE_main_thumbnail_create(struct Main *bmain)
1471 {
1472         MEM_SAFE_FREE(bmain->blen_thumb);
1473
1474         bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1475         bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1476         bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1477 }
1478
1479 /* ***************** ID ************************ */
1480 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1481 {
1482         ListBase *lb = which_libbase(bmain, type);
1483         BLI_assert(lb != NULL);
1484         return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1485 }
1486 ID *BKE_libblock_find_name(const short type, const char *name)
1487 {
1488         return BKE_libblock_find_name_ex(G.main, type, name);
1489 }
1490
1491
1492 void id_sort_by_name(ListBase *lb, ID *id)
1493 {
1494         ID *idtest;
1495         
1496         /* insert alphabetically */
1497         if (lb->first != lb->last) {
1498                 BLI_remlink(lb, id);
1499                 
1500                 idtest = lb->first;
1501                 while (idtest) {
1502                         if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1503                                 BLI_insertlinkbefore(lb, idtest, id);
1504                                 break;
1505                         }
1506                         idtest = idtest->next;
1507                 }
1508                 /* as last */
1509                 if (idtest == NULL) {
1510                         BLI_addtail(lb, id);
1511                 }
1512         }
1513         
1514 }
1515
1516 /**
1517  * Check to see if there is an ID with the same name as 'name'.
1518  * Returns the ID if so, if not, returns NULL
1519  */
1520 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1521 {
1522         ID *idtest = NULL;
1523         
1524         for (idtest = lb->first; idtest; idtest = idtest->next) {
1525                 /* if idtest is not a lib */ 
1526                 if (id != idtest && idtest->lib == NULL) {
1527                         /* do not test alphabetic! */
1528                         /* optimized */
1529                         if (idtest->name[2] == name[0]) {
1530                                 if (STREQ(name, idtest->name + 2)) break;
1531                         }
1532                 }
1533         }
1534         
1535         return idtest;
1536 }
1537
1538 /**
1539  * Check to see if an ID name is already used, and find a new one if so.
1540  * Return true if created a new name (returned in name).
1541  *
1542  * Normally the ID that's being check is already in the ListBase, so ID *id
1543  * points at the new entry.  The Python Library module needs to know what
1544  * the name of a datablock will be before it is appended; in this case ID *id
1545  * id is NULL
1546  */
1547
1548 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1549 {
1550         ID *idtest;
1551         int nr = 0, a, left_len;
1552 #define MAX_IN_USE 64
1553         bool in_use[MAX_IN_USE];
1554         /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1555
1556         char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1557
1558         while (true) {
1559
1560                 /* phase 1: id already exists? */
1561                 idtest = is_dupid(lb, id, name);
1562
1563                 /* if there is no double, done */
1564                 if (idtest == NULL) return false;
1565
1566                 /* we have a dup; need to make a new name */
1567                 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1568                 memset(in_use, false, sizeof(in_use));
1569
1570                 /* get name portion, number portion ("name.number") */
1571                 left_len = BLI_split_name_num(left, &nr, name, '.');
1572
1573                 /* if new name will be too long, truncate it */
1574                 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {  /* assumption: won't go beyond 9999 */
1575                         left[MAX_ID_NAME - 8] = 0;
1576                         left_len = MAX_ID_NAME - 8;
1577                 }
1578                 else if (left_len > (MAX_ID_NAME - 7)) {
1579                         left[MAX_ID_NAME - 7] = 0;
1580                         left_len = MAX_ID_NAME - 7;
1581                 }
1582
1583                 for (idtest = lb->first; idtest; idtest = idtest->next) {
1584                         int nrtest;
1585                         if ( (id != idtest) &&
1586                              (idtest->lib == NULL) &&
1587                              (*name == *(idtest->name + 2)) &&
1588                              STREQLEN(name, idtest->name + 2, left_len) &&
1589                              (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1590                              )
1591                         {
1592                                 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1593                                 if (nrtest < MAX_IN_USE)
1594                                         in_use[nrtest] = true;  /* mark as used */
1595                                 if (nr <= nrtest)
1596                                         nr = nrtest + 1;    /* track largest unused */
1597                         }
1598                 }
1599                 /* At this point, 'nr' will typically be at least 1. (but not always) */
1600                 // BLI_assert(nr >= 1);
1601
1602                 /* decide which value of nr to use */
1603                 for (a = 0; a < MAX_IN_USE; a++) {
1604                         if (a >= nr) break;  /* stop when we've checked up to biggest */  /* redundant check */
1605                         if (!in_use[a]) { /* found an unused value */
1606                                 nr = a;
1607                                 /* can only be zero if all potential duplicate names had
1608                                  * nonzero numeric suffixes, which means name itself has
1609                                  * nonzero numeric suffix (else no name conflict and wouldn't
1610                                  * have got here), which means name[left_len] is not a null */
1611                                 break;
1612                         }
1613                 }
1614                 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1615                  * or 1 greater than the largest used number if all those low ones are taken.
1616                  * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1617
1618                 /* If the original name has no numeric suffix, 
1619                  * rather than just chopping and adding numbers, 
1620                  * shave off the end chars until we have a unique name.
1621                  * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1622                 if (nr == 0 && name[left_len] == '\0') {
1623                         int len;
1624                         /* FIXME: this code will never be executed, because either nr will be
1625                          * at least 1, or name will not end at left_len! */
1626                         BLI_assert(0);
1627
1628                         len = left_len - 1;
1629                         idtest = is_dupid(lb, id, name);
1630                         
1631                         while (idtest && len > 1) {
1632                                 name[len--] = '\0';
1633                                 idtest = is_dupid(lb, id, name);
1634                         }
1635                         if (idtest == NULL) return true;
1636                         /* otherwise just continue and use a number suffix */
1637                 }
1638                 
1639                 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1640                         /* this would overflow name buffer */
1641                         left[MAX_ID_NAME - 8] = 0;
1642                         /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1643                         memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1644                         continue;
1645                 }
1646                 /* this format specifier is from hell... */
1647                 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1648
1649                 return true;
1650         }
1651
1652 #undef MAX_IN_USE
1653 }
1654
1655 /*
1656  * Only for local blocks: external en indirect blocks already have a
1657  * unique ID.
1658  *
1659  * return true: created a new name
1660  */
1661
1662 bool new_id(ListBase *lb, ID *id, const char *tname)
1663 {
1664         bool result;
1665         char name[MAX_ID_NAME - 2];
1666
1667         /* if library, don't rename */
1668         if (id->lib)
1669                 return false;
1670
1671         /* if no libdata given, look up based on ID */
1672         if (lb == NULL)
1673                 lb = which_libbase(G.main, GS(id->name));
1674
1675         /* if no name given, use name of current ID
1676          * else make a copy (tname args can be const) */
1677         if (tname == NULL)
1678                 tname = id->name + 2;
1679
1680         BLI_strncpy(name, tname, sizeof(name));
1681
1682         if (name[0] == '\0') {
1683                 /* disallow empty names */
1684                 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1685         }
1686         else {
1687                 /* disallow non utf8 chars,
1688                  * the interface checks for this but new ID's based on file names don't */
1689                 BLI_utf8_invalid_strip(name, strlen(name));
1690         }
1691
1692         result = check_for_dupid(lb, id, name);
1693         strcpy(id->name + 2, name);
1694
1695         /* This was in 2.43 and previous releases
1696          * however all data in blender should be sorted, not just duplicate names
1697          * sorting should not hurt, but noting just incase it alters the way other
1698          * functions work, so sort every time */
1699 #if 0
1700         if (result)
1701                 id_sort_by_name(lb, id);
1702 #endif
1703
1704         id_sort_by_name(lb, id);
1705         
1706         return result;
1707 }
1708
1709 /**
1710  * Pull an ID out of a library (make it local). Only call this for IDs that
1711  * don't have other library users.
1712  */
1713 void id_clear_lib_data_ex(Main *bmain, ID *id, bool id_in_mainlist)
1714 {
1715         bNodeTree *ntree = NULL;
1716
1717         BKE_id_lib_local_paths(bmain, id->lib, id);
1718
1719         id_fake_user_clear(id);
1720
1721         id->lib = NULL;
1722         id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1723         if (id_in_mainlist)
1724                 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1725
1726         /* internal bNodeTree blocks inside ID types below
1727          * also stores id->lib, make sure this stays in sync.
1728          */
1729         ntree = ntreeFromID(id);
1730
1731         if (ntree) {
1732                 ntreeMakeLocal(ntree, false);
1733         }
1734
1735         if (GS(id->name) == ID_OB) {
1736                 Object *object = (Object *)id;
1737                 if (object->proxy_from != NULL) {
1738                         object->proxy_from->proxy = NULL;
1739                         object->proxy_from->proxy_group = NULL;
1740                 }
1741                 object->proxy = object->proxy_from = object->proxy_group = NULL;
1742         }
1743 }
1744
1745 void id_clear_lib_data(Main *bmain, ID *id)
1746 {
1747         id_clear_lib_data_ex(bmain, id, true);
1748 }
1749
1750 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1751 void BKE_main_id_clear_newpoins(Main *bmain)
1752 {
1753         ListBase *lbarray[MAX_LIBARRAY];
1754         ID *id;
1755         int a;
1756
1757         a = set_listbasepointers(bmain, lbarray);
1758         while (a--) {
1759                 id = lbarray[a]->first;
1760                 while (id) {
1761                         id->newid = NULL;
1762                         id->tag &= ~LIB_TAG_NEW;
1763                         id = id->next;
1764                 }
1765         }
1766 }
1767
1768 static void lib_indirect_test_id(ID *id, Library *lib)
1769 {
1770 #define LIBTAG(a) \
1771         if (a && a->id.lib) { a->id.tag &= ~LIB_TAG_INDIRECT; a->id.tag |= LIB_TAG_EXTERN; } (void)0
1772         
1773         if (id->lib) {
1774                 /* datablocks that were indirectly related are now direct links
1775                  * without this, appending data that has a link to other data will fail to write */
1776                 if (lib && id->lib->parent == lib) {
1777                         id_lib_extern(id);
1778                 }
1779                 return;
1780         }
1781         
1782         if (GS(id->name) == ID_OB) {
1783                 Object *ob = (Object *)id;
1784                 Mesh *me;
1785
1786                 int a;
1787
1788 #if 0   /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
1789                 /* XXX old animation system! -------------------------------------- */
1790                 {
1791                         bActionStrip *strip;
1792                         for (strip = ob->nlastrips.first; strip; strip = strip->next) {
1793                                 LIBTAG(strip->object);
1794                                 LIBTAG(strip->act);
1795                                 LIBTAG(strip->ipo);
1796                         }
1797                 }
1798                 /* XXX: new animation system needs something like this? */
1799 #endif
1800
1801                 for (a = 0; a < ob->totcol; a++) {
1802                         LIBTAG(ob->mat[a]);
1803                 }
1804         
1805                 LIBTAG(ob->dup_group);
1806                 LIBTAG(ob->proxy);
1807                 
1808                 me = ob->data;
1809                 LIBTAG(me);
1810         }
1811
1812 #undef LIBTAG
1813 }
1814
1815 /* if lib!=NULL, only all from lib local
1816  * bmain is almost certainly G.main */
1817 void BKE_library_make_local(Main *bmain, Library *lib, bool untagged_only, bool set_fake)
1818 {
1819         ListBase *lbarray[MAX_LIBARRAY];
1820         ID *id, *idn;
1821         int a;
1822
1823         a = set_listbasepointers(bmain, lbarray);
1824         while (a--) {
1825                 id = lbarray[a]->first;
1826                 
1827                 while (id) {
1828                         id->newid = NULL;
1829                         idn = id->next;      /* id is possibly being inserted again */
1830                         
1831                         /* The check on the second line (LIB_TAG_PRE_EXISTING) is done so its
1832                          * possible to tag data you don't want to be made local, used for
1833                          * appending data, so any libdata already linked wont become local
1834                          * (very nasty to discover all your links are lost after appending)  
1835                          * */
1836                         if (id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1837                             ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1838                         {
1839                                 if (lib == NULL || id->lib == lib) {
1840                                         if (id->lib) {
1841                                                 /* for Make Local > All we should be calling id_make_local,
1842                                                  * but doing that breaks append (see #36003 and #36006), we
1843                                                  * we should make it work with all datablocks and id.us==0 */
1844                                                 id_clear_lib_data(bmain, id); /* sets 'id->tag' */
1845
1846                                                 /* why sort alphabetically here but not in
1847                                                  * id_clear_lib_data() ? - campbell */
1848                                                 id_sort_by_name(lbarray[a], id);
1849                                         }
1850                                         else {
1851                                                 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1852                                         }
1853                                 }
1854
1855                                 if (set_fake) {
1856                                         if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
1857                                                 /* do not set fake user on objects, groups (instancing) */
1858                                                 id_fake_user_set(id);
1859                                         }
1860                                 }
1861                         }
1862
1863                         id = idn;
1864                 }
1865         }
1866
1867         a = set_listbasepointers(bmain, lbarray);
1868         while (a--) {
1869                 for (id = lbarray[a]->first; id; id = id->next)
1870                         lib_indirect_test_id(id, lib);
1871         }
1872 }
1873
1874 /**
1875  * Use after setting the ID's name
1876  * When name exists: call 'new_id'
1877  */
1878 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
1879 {
1880         ListBase *lb;
1881         ID *idtest;
1882
1883
1884         lb = which_libbase(bmain, GS(name));
1885         if (lb == NULL) return;
1886         
1887         /* search for id */
1888         idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
1889
1890         if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
1891                 id_sort_by_name(lb, idtest);
1892         }
1893 }
1894
1895 /**
1896  * Sets the name of a block to name, suitably adjusted for uniqueness.
1897  */
1898 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
1899 {
1900         ListBase *lb = which_libbase(bmain, GS(id->name));
1901         new_id(lb, id, name);
1902 }
1903
1904 /**
1905  * Returns in name the name of the block, with a 3-character prefix prepended
1906  * indicating whether it comes from a library, has a fake user, or no users.
1907  */
1908 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
1909 {
1910         name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
1911         name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
1912         name[2] = ' ';
1913
1914         strcpy(name + 3, id->name + 2);
1915 }
1916
1917 void BKE_library_filepath_set(Library *lib, const char *filepath)
1918 {
1919         /* in some cases this is used to update the absolute path from the
1920          * relative */
1921         if (lib->name != filepath) {
1922                 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
1923         }
1924
1925         BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
1926
1927         /* not essential but set filepath is an absolute copy of value which
1928          * is more useful if its kept in sync */
1929         if (BLI_path_is_rel(lib->filepath)) {
1930                 /* note that the file may be unsaved, in this case, setting the
1931                  * filepath on an indirectly linked path is not allowed from the
1932                  * outliner, and its not really supported but allow from here for now
1933                  * since making local could cause this to be directly linked - campbell
1934                  */
1935                 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
1936                 BLI_path_abs(lib->filepath, basepath);
1937         }
1938 }