Merged changes in the trunk up to revision 34193.
[blender.git] / source / blender / blenkernel / intern / library.c
1 /** 
2  * $Id$
3  * 
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /*
31  *  Contains management of ID's and libraries
32  *  allocate and free of all library data
33  * 
34  */
35
36
37 #include <stdio.h>
38 #include <ctype.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <stddef.h>
42 #include <assert.h>
43
44 #include "MEM_guardedalloc.h"
45
46 /* all types are needed here, in order to do memory operations */
47 #include "DNA_anim_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_brush_types.h"
50 #include "DNA_camera_types.h"
51 #include "DNA_group_types.h"
52 #include "DNA_ipo_types.h"
53 #include "DNA_key_types.h"
54 #include "DNA_lamp_types.h"
55 #include "DNA_lattice_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meta_types.h"
59 #include "DNA_nla_types.h"
60 #include "DNA_node_types.h"
61 #include "DNA_scene_types.h"
62 #include "DNA_screen_types.h"
63 #include "DNA_sound_types.h"
64 #include "DNA_text_types.h"
65 #include "DNA_vfont_types.h"
66 #include "DNA_windowmanager_types.h"
67 #include "DNA_world_types.h"
68 #include "DNA_gpencil_types.h"
69
70 #include "BLI_blenlib.h"
71 #include "BLI_dynstr.h"
72 #include "BLI_utildefines.h"
73
74
75 #include "BKE_animsys.h"
76 #include "BKE_context.h"
77 #include "BKE_library.h"
78 #include "BKE_main.h"
79 #include "BKE_global.h"
80 #include "BKE_sound.h"
81 #include "BKE_object.h"
82 #include "BKE_screen.h"
83 #include "BKE_mesh.h"
84 #include "BKE_material.h"
85 #include "BKE_curve.h"
86 #include "BKE_mball.h"
87 #include "BKE_text.h"
88 #include "BKE_texture.h"
89 #include "BKE_scene.h"
90 #include "BKE_icons.h"
91 #include "BKE_image.h"
92 #include "BKE_ipo.h"
93 #include "BKE_key.h"
94 #include "BKE_world.h"
95 #include "BKE_font.h"
96 #include "BKE_group.h"
97 #include "BKE_lattice.h"
98 #include "BKE_armature.h"
99 #include "BKE_action.h"
100 #include "BKE_node.h"
101 #include "BKE_brush.h"
102 #include "BKE_idprop.h"
103 #include "BKE_particle.h"
104 #include "BKE_gpencil.h"
105 #include "BKE_fcurve.h"
106 #include "BKE_linestyle.h"
107
108 #define MAX_IDPUP               60      /* was 24 */
109
110 /* GS reads the memory pointed at in a specific ordering. 
111    only use this definition, makes little and big endian systems
112    work fine, in conjunction with MAKE_ID */
113
114 /* from blendef: */
115 #define GS(a)   (*((short *)(a)))
116
117 /* ************* general ************************ */
118
119 void id_lib_extern(ID *id)
120 {
121         if(id) {
122                 if(id->flag & LIB_INDIRECT) {
123                         id->flag -= LIB_INDIRECT;
124                         id->flag |= LIB_EXTERN;
125                 }
126         }
127 }
128
129 void id_us_plus(ID *id)
130 {
131         if(id) {
132                 id->us++;
133                 if(id->flag & LIB_INDIRECT) {
134                         id->flag -= LIB_INDIRECT;
135                         id->flag |= LIB_EXTERN;
136                 }
137         }
138 }
139
140 void id_us_min(ID *id)
141 {
142         if(id) {
143                 if(id->us<2 && (id->flag & LIB_FAKEUSER))
144                    id->us= 1;
145                 else if(id->us<=0)
146                         printf("ID user decrement error: %s \n", id->name);
147                 else
148                         id->us--;
149         }
150 }
151
152 int id_make_local(ID *id, int test)
153 {
154         if(id->flag & LIB_INDIRECT)
155                 return 0;
156
157         switch(GS(id->name)) {
158                 case ID_SCE:
159                         return 0; /* not implemented */
160                 case ID_LI:
161                         return 0; /* can't be linked */
162                 case ID_OB:
163                         if(!test) make_local_object((Object*)id);
164                         return 1;
165                 case ID_ME:
166                         if(!test) {
167                                 make_local_mesh((Mesh*)id);
168                                 make_local_key(((Mesh*)id)->key);
169                         }
170                         return 1;
171                 case ID_CU:
172                         if(!test) {
173                                 make_local_curve((Curve*)id);
174                                 make_local_key(((Curve*)id)->key);
175                         }
176                         return 1;
177                 case ID_MB:
178                         if(!test) make_local_mball((MetaBall*)id);
179                         return 1;
180                 case ID_MA:
181                         if(!test) make_local_material((Material*)id);
182                         return 1;
183                 case ID_TE:
184                         if(!test) make_local_texture((Tex*)id);
185                         return 1;
186                 case ID_IM:
187                         return 0; /* not implemented */
188                 case ID_LT:
189                         if(!test) {
190                                 make_local_lattice((Lattice*)id);
191                                 make_local_key(((Lattice*)id)->key);
192                         }
193                         return 1;
194                 case ID_LA:
195                         if(!test) make_local_lamp((Lamp*)id);
196                         return 1;
197                 case ID_CA:
198                         if(!test) make_local_camera((Camera*)id);
199                         return 1;
200                 case ID_IP:
201                         return 0; /* deprecated */
202                 case ID_KE:
203                         if(!test) make_local_key((Key*)id);
204                         return 1;
205                 case ID_WO:
206                         if(!test) make_local_world((World*)id);
207                         return 1;
208                 case ID_SCR:
209                         return 0; /* can't be linked */
210                 case ID_VF:
211                         return 0; /* not implemented */
212                 case ID_TXT:
213                         return 0; /* not implemented */
214                 case ID_SCRIPT:
215                         return 0; /* deprecated */
216                 case ID_SO:
217                         return 0; /* not implemented */
218                 case ID_GR:
219                         return 0; /* not implemented */
220                 case ID_AR:
221                         if(!test) make_local_armature((bArmature*)id);
222                         return 1;
223                 case ID_AC:
224                         if(!test) make_local_action((bAction*)id);
225                         return 1;
226                 case ID_NT:
227                         return 0; /* not implemented */
228                 case ID_BR:
229                         if(!test) make_local_brush((Brush*)id);
230                         return 1;
231                 case ID_PA:
232                         if(!test) make_local_particlesettings((ParticleSettings*)id);
233                         return 1;
234                 case ID_WM:
235                         return 0; /* can't be linked */
236                 case ID_GD:
237                         return 0; /* not implemented */
238                 case ID_LS:
239                         return 0; /* not implemented */
240         }
241
242         return 0;
243 }
244
245 int id_copy(ID *id, ID **newid, int test)
246 {
247         if(!test) *newid= NULL;
248
249         /* conventions:
250          * - make shallow copy, only this ID block
251          * - id.us of the new ID is set to 1 */
252         switch(GS(id->name)) {
253                 case ID_SCE:
254                         return 0; /* can't be copied from here */
255                 case ID_LI:
256                         return 0; /* can't be copied from here */
257                 case ID_OB:
258                         if(!test) *newid= (ID*)copy_object((Object*)id);
259                         return 1;
260                 case ID_ME:
261                         if(!test) *newid= (ID*)copy_mesh((Mesh*)id);
262                         return 1;
263                 case ID_CU:
264                         if(!test) *newid= (ID*)copy_curve((Curve*)id);
265                         return 1;
266                 case ID_MB:
267                         if(!test) *newid= (ID*)copy_mball((MetaBall*)id);
268                         return 1;
269                 case ID_MA:
270                         if(!test) *newid= (ID*)copy_material((Material*)id);
271                         return 1;
272                 case ID_TE:
273                         if(!test) *newid= (ID*)copy_texture((Tex*)id);
274                         return 1;
275                 case ID_IM:
276                         if(!test) *newid= (ID*)copy_image((Image*)id);
277                         return 1;
278                 case ID_LT:
279                         if(!test) *newid= (ID*)copy_lattice((Lattice*)id);
280                         return 1;
281                 case ID_LA:
282                         if(!test) *newid= (ID*)copy_lamp((Lamp*)id);
283                         return 1;
284                 case ID_CA:
285                         if(!test) *newid= (ID*)copy_camera((Camera*)id);
286                         return 1;
287                 case ID_IP:
288                         return 0; /* deprecated */
289                 case ID_KE:
290                         if(!test) *newid= (ID*)copy_key((Key*)id);
291                         return 1;
292                 case ID_WO:
293                         if(!test) *newid= (ID*)copy_world((World*)id);
294                         return 1;
295                 case ID_SCR:
296                         return 0; /* can't be copied from here */
297                 case ID_VF:
298                         return 0; /* not implemented */
299                 case ID_TXT:
300                         if(!test) *newid= (ID*)copy_text((Text*)id);
301                         return 1;
302                 case ID_SCRIPT:
303                         return 0; /* deprecated */
304                 case ID_SO:
305                         return 0; /* not implemented */
306                 case ID_GR:
307                         if(!test) *newid= (ID*)copy_group((Group*)id);
308                         return 1;
309                 case ID_AR:
310                         if(!test) *newid= (ID*)copy_armature((bArmature*)id);
311                         return 1;
312                 case ID_AC:
313                         if(!test) *newid= (ID*)copy_action((bAction*)id);
314                         return 1;
315                 case ID_NT:
316                         if(!test) *newid= (ID*)ntreeCopyTree((bNodeTree*)id, 0);
317                         return 1;
318                 case ID_BR:
319                         if(!test) *newid= (ID*)copy_brush((Brush*)id);
320                         return 1;
321                 case ID_PA:
322                         if(!test) *newid= (ID*)psys_copy_settings((ParticleSettings*)id);
323                         return 1;
324                 case ID_WM:
325                         return 0; /* can't be copied from here */
326                 case ID_GD:
327                         return 0; /* not implemented */
328                 case ID_LS:
329                         return 0; /* not implemented */
330         }
331         
332         return 0;
333 }
334
335 int id_unlink(ID *id, int test)
336 {
337         Main *mainlib= G.main;
338         ListBase *lb;
339
340         switch(GS(id->name)) {
341                 case ID_TXT:
342                         if(test) return 1;
343                         unlink_text(mainlib, (Text*)id);
344                         break;
345                 case ID_GR:
346                         if(test) return 1;
347                         unlink_group((Group*)id);
348                         break;
349                 case ID_OB:
350                         if(test) return 1;
351                         unlink_object((Object*)id);
352                         break;
353         }
354
355         if(id->us == 0) {
356                 if(test) return 1;
357
358                 lb= which_libbase(mainlib, GS(id->name));
359                 free_libblock(lb, id);
360
361                 return 1;
362         }
363
364         return 0;
365 }
366
367 ListBase *which_libbase(Main *mainlib, short type)
368 {
369         switch( type ) {
370                 case ID_SCE:
371                         return &(mainlib->scene);
372                 case ID_LI:
373                         return &(mainlib->library);
374                 case ID_OB:
375                         return &(mainlib->object);
376                 case ID_ME:
377                         return &(mainlib->mesh);
378                 case ID_CU:
379                         return &(mainlib->curve);
380                 case ID_MB:
381                         return &(mainlib->mball);
382                 case ID_MA:
383                         return &(mainlib->mat);
384                 case ID_TE:
385                         return &(mainlib->tex);
386                 case ID_IM:
387                         return &(mainlib->image);
388                 case ID_LT:
389                         return &(mainlib->latt);
390                 case ID_LA:
391                         return &(mainlib->lamp);
392                 case ID_CA:
393                         return &(mainlib->camera);
394                 case ID_IP:
395                         return &(mainlib->ipo);
396                 case ID_KE:
397                         return &(mainlib->key);
398                 case ID_WO:
399                         return &(mainlib->world);
400                 case ID_SCR:
401                         return &(mainlib->screen);
402                 case ID_VF:
403                         return &(mainlib->vfont);
404                 case ID_TXT:
405                         return &(mainlib->text);
406                 case ID_SCRIPT:
407                         return &(mainlib->script);
408                 case ID_SO:
409                         return &(mainlib->sound);
410                 case ID_GR:
411                         return &(mainlib->group);
412                 case ID_AR:
413                         return &(mainlib->armature);
414                 case ID_AC:
415                         return &(mainlib->action);
416                 case ID_NT:
417                         return &(mainlib->nodetree);
418                 case ID_BR:
419                         return &(mainlib->brush);
420                 case ID_PA:
421                         return &(mainlib->particle);
422                 case ID_WM:
423                         return &(mainlib->wm);
424                 case ID_GD:
425                         return &(mainlib->gpencil);
426                 case ID_LS:
427                         return &(mainlib->linestyle);
428         }
429         return 0;
430 }
431
432 /* Flag all ids in listbase */
433 void flag_listbase_ids(ListBase *lb, short flag, short value)
434 {
435         ID *id;
436         if (value) {
437                 for(id= lb->first; id; id= id->next) id->flag |= flag;
438         } else {
439                 flag = ~flag;
440                 for(id= lb->first; id; id= id->next) id->flag &= flag;
441         }
442 }
443
444 /* Flag all ids in listbase */
445 void flag_all_listbases_ids(short flag, short value)
446 {
447         ListBase *lbarray[MAX_LIBARRAY];
448         int a;
449         a= set_listbasepointers(G.main, lbarray);
450         while(a--)      flag_listbase_ids(lbarray[a], flag, value);
451 }
452
453 void recalc_all_library_objects(Main *main)
454 {
455         Object *ob;
456
457         /* flag for full recalc */
458         for(ob=main->object.first; ob; ob=ob->id.next)
459                 if(ob->id.lib)
460                         ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
461 }
462
463 /* note: MAX_LIBARRAY define should match this code */
464 int set_listbasepointers(Main *main, ListBase **lb)
465 {
466         int a = 0;
467
468         /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
469          * This is important because freeing data decreases usercounts of other datablocks,
470          * if this data is its self freed it can crash. */
471         lb[a++]= &(main->ipo);
472         lb[a++]= &(main->action); // xxx moved here to avoid problems when freeing with animato (aligorith)
473         lb[a++]= &(main->key);
474         lb[a++]= &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
475         lb[a++]= &(main->nodetree);
476         lb[a++]= &(main->image);
477         lb[a++]= &(main->tex);
478         lb[a++]= &(main->mat);
479         lb[a++]= &(main->vfont);
480         
481         /* Important!: When adding a new object type,
482          * the specific data should be inserted here 
483          */
484
485         lb[a++]= &(main->armature);
486
487         lb[a++]= &(main->mesh);
488         lb[a++]= &(main->curve);
489         lb[a++]= &(main->mball);
490
491         lb[a++]= &(main->latt);
492         lb[a++]= &(main->lamp);
493         lb[a++]= &(main->camera);
494         
495         lb[a++]= &(main->text);
496         lb[a++]= &(main->sound);
497         lb[a++]= &(main->group);
498         lb[a++]= &(main->brush);
499         lb[a++]= &(main->script);
500         lb[a++]= &(main->particle);
501
502         lb[a++]= &(main->world);
503         lb[a++]= &(main->screen);
504         lb[a++]= &(main->object);
505         lb[a++]= &(main->scene);
506         lb[a++]= &(main->library);
507         lb[a++]= &(main->wm);
508         lb[a++]= &(main->linestyle);
509         
510         lb[a]= NULL;
511
512         return a;
513 }
514
515 /* *********** ALLOC AND FREE *****************
516   
517 free_libblock(ListBase *lb, ID *id )
518         provide a list-basis and datablock, but only ID is read
519
520 void *alloc_libblock(ListBase *lb, type, name)
521         inserts in list and returns a new ID
522
523  ***************************** */
524
525 static ID *alloc_libblock_notest(short type)
526 {
527         ID *id= NULL;
528         
529         switch( type ) {
530                 case ID_SCE:
531                         id= MEM_callocN(sizeof(Scene), "scene");
532                         break;
533                 case ID_LI:
534                         id= MEM_callocN(sizeof(Library), "library");
535                         break;
536                 case ID_OB:
537                         id= MEM_callocN(sizeof(Object), "object");
538                         break;
539                 case ID_ME:
540                         id= MEM_callocN(sizeof(Mesh), "mesh");
541                         break;
542                 case ID_CU:
543                         id= MEM_callocN(sizeof(Curve), "curve");
544                         break;
545                 case ID_MB:
546                         id= MEM_callocN(sizeof(MetaBall), "mball");
547                         break;
548                 case ID_MA:
549                         id= MEM_callocN(sizeof(Material), "mat");
550                         break;
551                 case ID_TE:
552                         id= MEM_callocN(sizeof(Tex), "tex");
553                         break;
554                 case ID_IM:
555                         id= MEM_callocN(sizeof(Image), "image");
556                         break;
557                 case ID_LT:
558                         id= MEM_callocN(sizeof(Lattice), "latt");
559                         break;
560                 case ID_LA:
561                         id= MEM_callocN(sizeof(Lamp), "lamp");
562                         break;
563                 case ID_CA:
564                         id= MEM_callocN(sizeof(Camera), "camera");
565                         break;
566                 case ID_IP:
567                         id= MEM_callocN(sizeof(Ipo), "ipo");
568                         break;
569                 case ID_KE:
570                         id= MEM_callocN(sizeof(Key), "key");
571                         break;
572                 case ID_WO:
573                         id= MEM_callocN(sizeof(World), "world");
574                         break;
575                 case ID_SCR:
576                         id= MEM_callocN(sizeof(bScreen), "screen");
577                         break;
578                 case ID_VF:
579                         id= MEM_callocN(sizeof(VFont), "vfont");
580                         break;
581                 case ID_TXT:
582                         id= MEM_callocN(sizeof(Text), "text");
583                         break;
584                 case ID_SCRIPT:
585                         //XXX id= MEM_callocN(sizeof(Script), "script");
586                         break;
587                 case ID_SO:
588                         id= MEM_callocN(sizeof(bSound), "sound");
589                         break;
590                 case ID_GR:
591                         id= MEM_callocN(sizeof(Group), "group");
592                         break;
593                 case ID_AR:
594                         id = MEM_callocN(sizeof(bArmature), "armature");
595                         break;
596                 case ID_AC:
597                         id = MEM_callocN(sizeof(bAction), "action");
598                         break;
599                 case ID_NT:
600                         id = MEM_callocN(sizeof(bNodeTree), "nodetree");
601                         break;
602                 case ID_BR:
603                         id = MEM_callocN(sizeof(Brush), "brush");
604                         break;
605                 case ID_PA:
606                         id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
607                           break;
608                 case ID_WM:
609                         id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
610                           break;
611                 case ID_GD:
612                         id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
613                         break;
614                 case ID_LS:
615                         id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
616                         break;
617         }
618         return id;
619 }
620
621 /* used everywhere in blenkernel and text.c */
622 void *alloc_libblock(ListBase *lb, short type, const char *name)
623 {
624         ID *id= NULL;
625         
626         id= alloc_libblock_notest(type);
627         if(id) {
628                 BLI_addtail(lb, id);
629                 id->us= 1;
630                 id->icon_id = 0;
631                 *( (short *)id->name )= type;
632                 new_id(lb, id, name);
633                 /* alphabetic insterion: is in new_id */
634         }
635         return id;
636 }
637
638 /* by spec, animdata is first item after ID */
639 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
640 static void id_copy_animdata(ID *id, const short do_action)
641 {
642         AnimData *adt= BKE_animdata_from_id(id);
643         
644         if (adt) {
645                 IdAdtTemplate *iat = (IdAdtTemplate *)id;
646                 iat->adt= BKE_copy_animdata(iat->adt, do_action); /* could be set to FALSE, need to investigate */
647         }
648 }
649
650 /* material nodes use this since they are not treated as libdata */
651 void copy_libblock_data(ID *id, const ID *id_from, const short do_action)
652 {
653         if (id_from->properties)
654                 id->properties = IDP_CopyProperty(id_from->properties);
655
656         /* the duplicate should get a copy of the animdata */
657         id_copy_animdata(id, do_action);
658 }
659
660 /* used everywhere in blenkernel */
661 void *copy_libblock(void *rt)
662 {
663         ID *idn, *id;
664         ListBase *lb;
665         char *cp, *cpn;
666         size_t idn_len;
667         
668         id= rt;
669
670         lb= which_libbase(G.main, GS(id->name));
671         idn= alloc_libblock(lb, GS(id->name), id->name+2);
672
673         assert(idn != NULL);
674
675         idn_len= MEM_allocN_len(idn);
676         if(idn_len - sizeof(ID) > 0) {
677                 cp= (char *)id;
678                 cpn= (char *)idn;
679                 memcpy(cpn+sizeof(ID), cp+sizeof(ID), idn_len - sizeof(ID));
680         }
681         
682         id->newid= idn;
683         idn->flag |= LIB_NEW;
684
685         copy_libblock_data(idn, id, FALSE);
686         
687         return idn;
688 }
689
690 static void free_library(Library *UNUSED(lib))
691 {
692         /* no freeing needed for libraries yet */
693 }
694
695 static void (*free_windowmanager_cb)(bContext *, wmWindowManager *)= NULL;
696
697 void set_free_windowmanager_cb(void (*func)(bContext *C, wmWindowManager *) )
698 {
699         free_windowmanager_cb= func;
700 }
701
702 void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
703 {
704         ChannelDriver *driver;
705         FCurve *fcu;
706
707         /* find the driver this belongs to and update it */
708         for (fcu=adt->drivers.first; fcu; fcu=fcu->next) {
709                 driver= fcu->driver;
710                 
711                 if (driver) {
712                         DriverVar *dvar;
713                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
714                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
715                                 {
716                                         if (dtar->id == userdata)
717                                                 dtar->id= NULL;
718                                 }
719                                 DRIVER_TARGETS_LOOPER_END
720                         }
721                 }
722         }
723 }
724
725
726 /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
727 void free_libblock(ListBase *lb, void *idv)
728 {
729         ID *id= idv;
730         
731         switch( GS(id->name) ) {        /* GetShort from util.h */
732                 case ID_SCE:
733                         free_scene((Scene *)id);
734                         break;
735                 case ID_LI:
736                         free_library((Library *)id);
737                         break;
738                 case ID_OB:
739                         free_object((Object *)id);
740                         break;
741                 case ID_ME:
742                         free_mesh((Mesh *)id);
743                         break;
744                 case ID_CU:
745                         free_curve((Curve *)id);
746                         break;
747                 case ID_MB:
748                         free_mball((MetaBall *)id);
749                         break;
750                 case ID_MA:
751                         free_material((Material *)id);
752                         break;
753                 case ID_TE:
754                         free_texture((Tex *)id);
755                         break;
756                 case ID_IM:
757                         free_image((Image *)id);
758                         break;
759                 case ID_LT:
760                         free_lattice((Lattice *)id);
761                         break;
762                 case ID_LA:
763                         free_lamp((Lamp *)id);
764                         break;
765                 case ID_CA:
766                         free_camera((Camera*) id);
767                         break;
768                 case ID_IP:
769                         free_ipo((Ipo *)id);
770                         break;
771                 case ID_KE:
772                         free_key((Key *)id);
773                         break;
774                 case ID_WO:
775                         free_world((World *)id);
776                         break;
777                 case ID_SCR:
778                         free_screen((bScreen *)id);
779                         break;
780                 case ID_VF:
781                         free_vfont((VFont *)id);
782                         break;
783                 case ID_TXT:
784                         free_text((Text *)id);
785                         break;
786                 case ID_SCRIPT:
787                         //XXX free_script((Script *)id);
788                         break;
789                 case ID_SO:
790                         sound_free((bSound*)id);
791                         break;
792                 case ID_GR:
793                         free_group_objects((Group *)id);
794                         break;
795                 case ID_AR:
796                         free_armature((bArmature *)id);
797                         break;
798                 case ID_AC:
799                         free_action((bAction *)id);
800                         break;
801                 case ID_NT:
802                         ntreeFreeTree((bNodeTree *)id);
803                         break;
804                 case ID_BR:
805                         free_brush((Brush *)id);
806                         break;
807                 case ID_PA:
808                         psys_free_settings((ParticleSettings *)id);
809                         break;
810                 case ID_WM:
811                         if(free_windowmanager_cb)
812                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
813                         break;
814                 case ID_GD:
815                         free_gpencil_data((bGPdata *)id);
816                         break;
817                 case ID_LS:
818                         FRS_free_linestyle((FreestyleLineStyle *)id);
819                         break;
820         }
821
822         if (id->properties) {
823                 IDP_FreeProperty(id->properties);
824                 MEM_freeN(id->properties);
825         }
826
827         BLI_remlink(lb, id);
828
829         /* this ID may be a driver target! */
830         BKE_animdata_main_cb(G.main, animdata_dtar_clear_cb, (void *)id);
831
832         MEM_freeN(id);
833 }
834
835 void free_libblock_us(ListBase *lb, void *idv)          /* test users */
836 {
837         ID *id= idv;
838         
839         id->us--;
840
841         if(id->us<0) {
842                 if(id->lib) printf("ERROR block %s %s users %d\n", id->lib->name, id->name, id->us);
843                 else printf("ERROR block %s users %d\n", id->name, id->us);
844         }
845         if(id->us==0) {
846                 if( GS(id->name)==ID_OB ) unlink_object((Object *)id);
847                 
848                 free_libblock(lb, id);
849         }
850 }
851
852
853 void free_main(Main *mainvar)
854 {
855         /* also call when reading a file, erase all, etc */
856         ListBase *lbarray[MAX_LIBARRAY];
857         int a;
858
859         a= set_listbasepointers(mainvar, lbarray);
860         while(a--) {
861                 ListBase *lb= lbarray[a];
862                 ID *id;
863                 
864                 while ( (id= lb->first) ) {
865                         free_libblock(lb, id);
866                 }
867         }
868
869         MEM_freeN(mainvar);
870 }
871
872 /* ***************** ID ************************ */
873
874
875 ID *find_id(const char *type, const char *name)         /* type: "OB" or "MA" etc */
876 {
877         ListBase *lb= which_libbase(G.main, GS(type));
878         return BLI_findstring(lb, name, offsetof(ID, name) + 2);
879 }
880
881 static void get_flags_for_id(ID *id, char *buf) 
882 {
883         int isfake= id->flag & LIB_FAKEUSER;
884         int isnode=0;
885                 /* Writeout the flags for the entry, note there
886                  * is a small hack that writes 5 spaces instead
887                  * of 4 if no flags are displayed... this makes
888                  * things usually line up ok - better would be
889                  * to have that explicit, oh well - zr
890                  */
891
892         if(GS(id->name)==ID_MA)
893                 isnode= ((Material *)id)->use_nodes;
894         if(GS(id->name)==ID_TE)
895                 isnode= ((Tex *)id)->use_nodes;
896         
897         if (id->us<0)
898                 sprintf(buf, "-1W ");
899         else if (!id->lib && !isfake && id->us && !isnode)
900                 sprintf(buf, "     ");
901         else if(isnode)
902                 sprintf(buf, "%c%cN%c ", id->lib?'L':' ', isfake?'F':' ', (id->us==0)?'O':' ');
903         else
904                 sprintf(buf, "%c%c%c ", id->lib?'L':' ', isfake?'F':' ', (id->us==0)?'O':' ');
905 }
906
907 #define IDPUP_NO_VIEWER 1
908
909 static void IDnames_to_dyn_pupstring(DynStr *pupds, ListBase *lb, ID *link, short *nr, int hideflag)
910 {
911         int i, nids= BLI_countlist(lb);
912                 
913         if (nr) *nr= -1;
914         
915         if (nr && nids>MAX_IDPUP) {
916                 BLI_dynstr_append(pupds, "DataBrowse %x-2");
917                 *nr= -2;
918         } else {
919                 ID *id;
920                 
921                 for (i=0, id= lb->first; id; id= id->next, i++) {
922                         char buf[32];
923                         
924                         if (nr && id==link) *nr= i+1;
925
926                         if (U.uiflag & USER_HIDE_DOT && id->name[2]=='.')
927                                 continue;
928                         if (hideflag & IDPUP_NO_VIEWER)
929                                 if (GS(id->name)==ID_IM)
930                                         if ( ((Image *)id)->source==IMA_SRC_VIEWER )
931                                                 continue;
932                         
933                         get_flags_for_id(id, buf);
934                                 
935                         BLI_dynstr_append(pupds, buf);
936                         BLI_dynstr_append(pupds, id->name+2);
937                         sprintf(buf, "%%x%d", i+1);
938                         BLI_dynstr_append(pupds, buf);
939                         
940                         /* icon */
941                         switch(GS(id->name))
942                         {
943                         case ID_MA: /* fall through */
944                         case ID_TE: /* fall through */
945                         case ID_IM: /* fall through */
946                         case ID_WO: /* fall through */
947                         case ID_LA: /* fall through */
948                                 sprintf(buf, "%%i%d", BKE_icon_getid(id) );
949                                 BLI_dynstr_append(pupds, buf);
950                                 break;
951                         default:
952                                 break;
953                         }
954                         
955                         if(id->next)
956                                 BLI_dynstr_append(pupds, "|");
957                 }
958         }
959 }
960
961
962 /* used by headerbuttons.c buttons.c editobject.c editseq.c */
963 /* if nr==NULL no MAX_IDPUP, this for non-header browsing */
964 void IDnames_to_pupstring(const char **str, const char *title, const char *extraops, ListBase *lb, ID *link, short *nr)
965 {
966         DynStr *pupds= BLI_dynstr_new();
967
968         if (title) {
969                 BLI_dynstr_append(pupds, title);
970                 BLI_dynstr_append(pupds, "%t|");
971         }
972         
973         if (extraops) {
974                 BLI_dynstr_append(pupds, extraops);
975                 if (BLI_dynstr_get_len(pupds))
976                         BLI_dynstr_append(pupds, "|");
977         }
978
979         IDnames_to_dyn_pupstring(pupds, lb, link, nr, 0);
980         
981         *str= BLI_dynstr_get_cstring(pupds);
982         BLI_dynstr_free(pupds);
983 }
984
985 /* skips viewer images */
986 void IMAnames_to_pupstring(const char **str, const char *title, const char *extraops, ListBase *lb, ID *link, short *nr)
987 {
988         DynStr *pupds= BLI_dynstr_new();
989         
990         if (title) {
991                 BLI_dynstr_append(pupds, title);
992                 BLI_dynstr_append(pupds, "%t|");
993         }
994         
995         if (extraops) {
996                 BLI_dynstr_append(pupds, extraops);
997                 if (BLI_dynstr_get_len(pupds))
998                         BLI_dynstr_append(pupds, "|");
999         }
1000         
1001         IDnames_to_dyn_pupstring(pupds, lb, link, nr, IDPUP_NO_VIEWER);
1002         
1003         *str= BLI_dynstr_get_cstring(pupds);
1004         BLI_dynstr_free(pupds);
1005 }
1006
1007 static void sort_alpha_id(ListBase *lb, ID *id)
1008 {
1009         ID *idtest;
1010         
1011         /* insert alphabetically */
1012         if(lb->first!=lb->last) {
1013                 BLI_remlink(lb, id);
1014                 
1015                 idtest= lb->first;
1016                 while(idtest) {
1017                         if(BLI_strcasecmp(idtest->name, id->name)>0 || idtest->lib) {
1018                                 BLI_insertlinkbefore(lb, idtest, id);
1019                                 break;
1020                         }
1021                         idtest= idtest->next;
1022                 }
1023                 /* as last */
1024                 if(idtest==0) {
1025                         BLI_addtail(lb, id);
1026                 }
1027         }
1028         
1029 }
1030
1031 /*
1032  * Check to see if there is an ID with the same name as 'name'.
1033  * Returns the ID if so, if not, returns NULL
1034  */
1035 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1036 {
1037         ID *idtest=NULL;
1038         
1039         for( idtest = lb->first; idtest; idtest = idtest->next ) {
1040                 /* if idtest is not a lib */ 
1041                 if( id != idtest && idtest->lib == NULL ) {
1042                         /* do not test alphabetic! */
1043                         /* optimized */
1044                         if( idtest->name[2] == name[0] ) {
1045                                 if(strcmp(name, idtest->name+2)==0) break;
1046                         }
1047                 }
1048         }
1049         
1050         return idtest;
1051 }
1052
1053 /* 
1054  * Check to see if an ID name is already used, and find a new one if so.
1055  * Return 1 if created a new name (returned in name).
1056  *
1057  * Normally the ID that's being check is already in the ListBase, so ID *id
1058  * points at the new entry.  The Python Library module needs to know what
1059  * the name of a datablock will be before it is appended; in this case ID *id
1060  * id is NULL;
1061  */
1062
1063 static int check_for_dupid(ListBase *lb, ID *id, char *name)
1064 {
1065         ID *idtest;
1066         int nr= 0, nrtest, a, left_len;
1067         char left[32], leftest[32], in_use[32];
1068
1069         /* make sure input name is terminated properly */
1070         /* if( strlen(name) > 21 ) name[21]= 0; */
1071         /* removed since this is only ever called from one place - campbell */
1072
1073         while (1) {
1074
1075                 /* phase 1: id already exists? */
1076                 idtest = is_dupid(lb, id, name);
1077
1078                 /* if there is no double, done */
1079                 if( idtest == NULL ) return 0;
1080
1081                 /* we have a dup; need to make a new name */
1082                 /* quick check so we can reuse one of first 32 ids if vacant */
1083                 memset(in_use, 0, sizeof(in_use));
1084
1085                 /* get name portion, number portion ("name.number") */
1086                 left_len= BLI_split_name_num(left, &nr, name, '.');
1087
1088                 /* if new name will be too long, truncate it */
1089                 if(nr > 999 && left_len > 16) {
1090                         left[16]= 0;
1091                         left_len= 16;
1092                 }
1093                 else if(left_len > 17) {
1094                         left[17]= 0;
1095                         left_len= 17;
1096                 }
1097
1098                 for(idtest= lb->first; idtest; idtest= idtest->next) {
1099                         if(             (id != idtest) &&
1100                                         (idtest->lib == NULL) &&
1101                                         (*name == *(idtest->name+2)) &&
1102                                         (strncmp(name, idtest->name+2, left_len)==0) &&
1103                                         (BLI_split_name_num(leftest, &nrtest, idtest->name+2, '.') == left_len)
1104                         ) {
1105                                 if(nrtest < sizeof(in_use))
1106                                         in_use[nrtest]= 1;      /* mark as used */
1107                                 if(nr <= nrtest)
1108                                         nr= nrtest+1;           /* track largest unused */
1109                         }
1110                 }
1111
1112                 /* decide which value of nr to use */
1113                 for(a=0; a < sizeof(in_use); a++) {
1114                         if(a>=nr) break;        /* stop when we've check up to biggest */
1115                         if( in_use[a]==0 ) { /* found an unused value */
1116                                 nr = a;
1117                                 break;
1118                         }
1119                 }
1120
1121                 /* If the original name has no numeric suffix, 
1122                  * rather than just chopping and adding numbers, 
1123                  * shave off the end chars until we have a unique name.
1124                  * Check the null terminators match as well so we dont get Cube.000 -> Cube.00 */
1125                 if (nr==0 && name[left_len]== '\0') {
1126                         int len = left_len-1;
1127                         idtest= is_dupid(lb, id, name);
1128                         
1129                         while (idtest && len> 1) {
1130                                 name[len--] = '\0';
1131                                 idtest= is_dupid(lb, id, name);
1132                         }
1133                         if (idtest == NULL) return 1;
1134                         /* otherwise just continue and use a number suffix */
1135                 }
1136                 
1137                 if(nr > 999 && left_len > 16) {
1138                         /* this would overflow name buffer */
1139                         left[16] = 0;
1140                         /* left_len = 16; */ /* for now this isnt used again */
1141                         memcpy(name, left, sizeof(char) * 17);
1142                         continue;
1143                 }
1144                 /* this format specifier is from hell... */
1145                 sprintf(name, "%s.%.3d", left, nr);
1146
1147                 return 1;
1148         }
1149 }
1150
1151 /*
1152  * Only for local blocks: external en indirect blocks already have a
1153  * unique ID.
1154  *
1155  * return 1: created a new name
1156  */
1157
1158 int new_id(ListBase *lb, ID *id, const char *tname)
1159 {
1160         int result;
1161         char name[22];
1162
1163         /* if library, don't rename */
1164         if(id->lib) return 0;
1165
1166         /* if no libdata given, look up based on ID */
1167         if(lb==NULL) lb= which_libbase(G.main, GS(id->name));
1168
1169         /* if no name given, use name of current ID
1170          * else make a copy (tname args can be const) */
1171         if(tname==NULL)
1172                 tname= id->name+2;
1173
1174         strncpy(name, tname, sizeof(name)-1);
1175
1176         /* if result > 21, strncpy don't put the final '\0' to name.
1177          * easier to assign each time then to check if its needed */
1178         name[sizeof(name)-1]= 0;
1179
1180         if(name[0] == '\0') {
1181                 /* disallow empty names */
1182                 strcpy(name, ID_FALLBACK_NAME);
1183         }
1184         else {
1185                 /* disallow non utf8 chars,
1186                  * the interface checks for this but new ID's based on file names dont */
1187                 BLI_utf8_invalid_strip(name, strlen(name));
1188         }
1189
1190         result = check_for_dupid(lb, id, name);
1191         strcpy(id->name+2, name);
1192
1193         /* This was in 2.43 and previous releases
1194          * however all data in blender should be sorted, not just duplicate names
1195          * sorting should not hurt, but noting just incause it alters the way other
1196          * functions work, so sort every time */
1197         /* if( result )
1198                 sort_alpha_id(lb, id);*/
1199         
1200         sort_alpha_id(lb, id);
1201         
1202         return result;
1203 }
1204
1205 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1206 void clear_id_newpoins()
1207 {
1208         ListBase *lbarray[MAX_LIBARRAY];
1209         ID *id;
1210         int a;
1211
1212         a= set_listbasepointers(G.main, lbarray);
1213         while(a--) {
1214                 id= lbarray[a]->first;
1215                 while(id) {
1216                         id->newid= 0;
1217                         id->flag &= ~LIB_NEW;
1218                         id= id->next;
1219                 }
1220         }
1221 }
1222
1223 /* only for library fixes */
1224 static void image_fix_relative_path(Image *ima)
1225 {
1226         if(ima->id.lib==NULL) return;
1227         if(strncmp(ima->name, "//", 2)==0) {
1228                 BLI_path_abs(ima->name, ima->id.lib->filepath);
1229                 BLI_path_rel(ima->name, G.main->name);
1230         }
1231 }
1232
1233 #define LIBTAG(a)       if(a && a->id.lib) {a->id.flag &=~LIB_INDIRECT; a->id.flag |= LIB_EXTERN;}
1234
1235 static void lib_indirect_test_id(ID *id, Library *lib)
1236 {
1237         
1238         if(id->lib) {
1239                 /* datablocks that were indirectly related are now direct links
1240                  * without this, appending data that has a link to other data will fail to write */
1241                 if(lib && id->lib->parent == lib) {
1242                         id_lib_extern(id);
1243                 }
1244                 return;
1245         }
1246         
1247         if(GS(id->name)==ID_OB) {               
1248                 Object *ob= (Object *)id;
1249                 bActionStrip *strip;
1250                 Mesh *me;
1251
1252                 int a;
1253         
1254                 // XXX old animation system! --------------------------------------
1255                 for (strip=ob->nlastrips.first; strip; strip=strip->next){
1256                         LIBTAG(strip->object); 
1257                         LIBTAG(strip->act);
1258                         LIBTAG(strip->ipo);
1259                 }
1260                 // XXX: new animation system needs something like this?
1261         
1262                 for(a=0; a<ob->totcol; a++) {
1263                         LIBTAG(ob->mat[a]);
1264                 }
1265         
1266                 LIBTAG(ob->dup_group);
1267                 LIBTAG(ob->proxy);
1268                 
1269                 me= ob->data;
1270                 LIBTAG(me);
1271         }
1272 }
1273
1274 void tag_main_lb(ListBase *lb, const short tag)
1275 {
1276         ID *id;
1277         if(tag) {
1278                 for(id= lb->first; id; id= id->next) {
1279                         id->flag |= LIB_DOIT;
1280                 }
1281         }
1282         else {
1283                 for(id= lb->first; id; id= id->next) {
1284                         id->flag &= ~LIB_DOIT;
1285                 }
1286         }
1287 }
1288
1289 void tag_main_idcode(struct Main *mainvar, const short type, const short tag)
1290 {
1291         ListBase *lb= which_libbase(mainvar, type);
1292
1293         tag_main_lb(lb, tag);
1294 }
1295
1296 void tag_main(struct Main *mainvar, const short tag)
1297 {
1298         ListBase *lbarray[MAX_LIBARRAY];
1299         int a;
1300
1301         a= set_listbasepointers(mainvar, lbarray);
1302         while(a--) {
1303                 tag_main_lb(lbarray[a], tag);
1304         }
1305 }
1306
1307 /* if lib!=NULL, only all from lib local */
1308 void all_local(Library *lib, int untagged_only)
1309 {
1310         ListBase *lbarray[MAX_LIBARRAY], tempbase={0, 0};
1311         ID *id, *idn;
1312         int a;
1313
1314         a= set_listbasepointers(G.main, lbarray);
1315         while(a--) {
1316                 id= lbarray[a]->first;
1317                 
1318                 while(id) {
1319                         id->newid= NULL;
1320                         idn= id->next;          /* id is possibly being inserted again */
1321                         
1322                         /* The check on the second line (LIB_PRE_EXISTING) is done so its
1323                          * possible to tag data you dont want to be made local, used for
1324                          * appending data, so any libdata already linked wont become local
1325                          * (very nasty to discover all your links are lost after appending)  
1326                          * */
1327                         if(id->flag & (LIB_EXTERN|LIB_INDIRECT|LIB_NEW) &&
1328                           (untagged_only==0 || !(id->flag & LIB_PRE_EXISTING)))
1329                         {
1330                                 if(lib==NULL || id->lib==lib) {
1331                                         id->flag &= ~(LIB_EXTERN|LIB_INDIRECT|LIB_NEW);
1332
1333                                         if(id->lib) {
1334                                                 /* relative file patch */
1335                                                 if(GS(id->name)==ID_IM)
1336                                                         image_fix_relative_path((Image *)id);
1337                                                 
1338                                                 id->lib= NULL;
1339                                                 new_id(lbarray[a], id, 0);      /* new_id only does it with double names */
1340                                                 sort_alpha_id(lbarray[a], id);
1341                                         }
1342                                 }
1343                         }
1344                         id= idn;
1345                 }
1346                 
1347                 /* patch2: make it aphabetically */
1348                 while( (id=tempbase.first) ) {
1349                         BLI_remlink(&tempbase, id);
1350                         BLI_addtail(lbarray[a], id);
1351                         new_id(lbarray[a], id, 0);
1352                 }
1353         }
1354
1355         /* patch 3: make sure library data isn't indirect falsely... */
1356         a= set_listbasepointers(G.main, lbarray);
1357         while(a--) {
1358                 for(id= lbarray[a]->first; id; id=id->next)
1359                         lib_indirect_test_id(id, lib);
1360         }
1361 }
1362
1363
1364 void test_idbutton(char *name)
1365 {
1366         /* called from buttons: when name already exists: call new_id */
1367         ListBase *lb;
1368         ID *idtest;
1369         
1370
1371         lb= which_libbase(G.main, GS(name-2) );
1372         if(lb==0) return;
1373         
1374         /* search for id */
1375         idtest= BLI_findstring(lb, name, offsetof(ID, name) + 2);
1376
1377         if(idtest) if( new_id(lb, idtest, name)==0 ) sort_alpha_id(lb, idtest);
1378 }
1379
1380 void text_idbutton(struct ID *id, char *text)
1381 {
1382         if(id) {
1383                 if(GS(id->name)==ID_SCE)
1384                         strcpy(text, "SCE: ");
1385                 else if(GS(id->name)==ID_SCE)
1386                         strcpy(text, "SCR: ");
1387                 else if(GS(id->name)==ID_MA && ((Material*)id)->use_nodes)
1388                         strcpy(text, "NT: ");
1389                 else {
1390                         text[0]= id->name[0];
1391                         text[1]= id->name[1];
1392                         text[2]= ':';
1393                         text[3]= ' ';
1394                         text[4]= 0;
1395                 }
1396         }
1397         else {
1398                 text[0]= '\0';
1399         }
1400 }
1401
1402 void rename_id(ID *id, const char *name)
1403 {
1404         ListBase *lb;
1405
1406         BLI_strncpy(id->name+2, name, sizeof(id->name)-2);
1407         lb= which_libbase(G.main, GS(id->name) );
1408         
1409         new_id(lb, id, name);                           
1410 }
1411
1412 void name_uiprefix_id(char *name, ID *id)
1413 {
1414         name[0] = id->lib ? 'L':' ';
1415         name[1] = id->flag & LIB_FAKEUSER ? 'F': (id->us==0)?'0':' ';
1416         name[2] = ' ';
1417
1418         strcpy(name+3, id->name+2);
1419 }