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