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