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