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