dfc82152e8c17d64eed95465e48372284699004a
[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) */
456
457         lb[a++]= &(main->ipo);
458         lb[a++]= &(main->action); // xxx moved here to avoid problems when freeing with animato (aligorith)
459         lb[a++]= &(main->key);
460         lb[a++]= &(main->nodetree);
461         lb[a++]= &(main->image);
462         lb[a++]= &(main->tex);
463         lb[a++]= &(main->mat);
464         lb[a++]= &(main->vfont);
465         
466         /* Important!: When adding a new object type,
467          * the specific data should be inserted here 
468          */
469
470         lb[a++]= &(main->armature);
471
472         lb[a++]= &(main->mesh);
473         lb[a++]= &(main->curve);
474         lb[a++]= &(main->mball);
475
476         lb[a++]= &(main->latt);
477         lb[a++]= &(main->lamp);
478         lb[a++]= &(main->camera);
479         
480         lb[a++]= &(main->text);
481         lb[a++]= &(main->sound);
482         lb[a++]= &(main->group);
483         lb[a++]= &(main->brush);
484         lb[a++]= &(main->script);
485         lb[a++]= &(main->particle);
486         
487         lb[a++]= &(main->world);
488         lb[a++]= &(main->screen);
489         lb[a++]= &(main->object);
490         lb[a++]= &(main->scene);
491         lb[a++]= &(main->library);
492         lb[a++]= &(main->wm);
493         lb[a++]= &(main->gpencil);
494         
495         lb[a]= NULL;
496
497         return a;
498 }
499
500 /* *********** ALLOC AND FREE *****************
501   
502 free_libblock(ListBase *lb, ID *id )
503         provide a list-basis and datablock, but only ID is read
504
505 void *alloc_libblock(ListBase *lb, type, name)
506         inserts in list and returns a new ID
507
508  ***************************** */
509
510 static ID *alloc_libblock_notest(short type)
511 {
512         ID *id= NULL;
513         
514         switch( type ) {
515                 case ID_SCE:
516                         id= MEM_callocN(sizeof(Scene), "scene");
517                         break;
518                 case ID_LI:
519                         id= MEM_callocN(sizeof(Library), "library");
520                         break;
521                 case ID_OB:
522                         id= MEM_callocN(sizeof(Object), "object");
523                         break;
524                 case ID_ME:
525                         id= MEM_callocN(sizeof(Mesh), "mesh");
526                         break;
527                 case ID_CU:
528                         id= MEM_callocN(sizeof(Curve), "curve");
529                         break;
530                 case ID_MB:
531                         id= MEM_callocN(sizeof(MetaBall), "mball");
532                         break;
533                 case ID_MA:
534                         id= MEM_callocN(sizeof(Material), "mat");
535                         break;
536                 case ID_TE:
537                         id= MEM_callocN(sizeof(Tex), "tex");
538                         break;
539                 case ID_IM:
540                         id= MEM_callocN(sizeof(Image), "image");
541                         break;
542                 case ID_LT:
543                         id= MEM_callocN(sizeof(Lattice), "latt");
544                         break;
545                 case ID_LA:
546                         id= MEM_callocN(sizeof(Lamp), "lamp");
547                         break;
548                 case ID_CA:
549                         id= MEM_callocN(sizeof(Camera), "camera");
550                         break;
551                 case ID_IP:
552                         id= MEM_callocN(sizeof(Ipo), "ipo");
553                         break;
554                 case ID_KE:
555                         id= MEM_callocN(sizeof(Key), "key");
556                         break;
557                 case ID_WO:
558                         id= MEM_callocN(sizeof(World), "world");
559                         break;
560                 case ID_SCR:
561                         id= MEM_callocN(sizeof(bScreen), "screen");
562                         break;
563                 case ID_VF:
564                         id= MEM_callocN(sizeof(VFont), "vfont");
565                         break;
566                 case ID_TXT:
567                         id= MEM_callocN(sizeof(Text), "text");
568                         break;
569                 case ID_SCRIPT:
570                         //XXX id= MEM_callocN(sizeof(Script), "script");
571                         break;
572                 case ID_SO:
573                         id= MEM_callocN(sizeof(bSound), "sound");
574                         break;
575                 case ID_GR:
576                         id= MEM_callocN(sizeof(Group), "group");
577                         break;
578                 case ID_AR:
579                         id = MEM_callocN(sizeof(bArmature), "armature");
580                         break;
581                 case ID_AC:
582                         id = MEM_callocN(sizeof(bAction), "action");
583                         break;
584                 case ID_NT:
585                         id = MEM_callocN(sizeof(bNodeTree), "nodetree");
586                         break;
587                 case ID_BR:
588                         id = MEM_callocN(sizeof(Brush), "brush");
589                         break;
590                 case ID_PA:
591                         id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
592                           break;
593                 case ID_WM:
594                         id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
595                           break;
596                 case ID_GD:
597                         id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
598                         break;
599         }
600         return id;
601 }
602
603 /* used everywhere in blenkernel and text.c */
604 void *alloc_libblock(ListBase *lb, short type, const char *name)
605 {
606         ID *id= NULL;
607         
608         id= alloc_libblock_notest(type);
609         if(id) {
610                 BLI_addtail(lb, id);
611                 id->us= 1;
612                 id->icon_id = 0;
613                 *( (short *)id->name )= type;
614                 new_id(lb, id, name);
615                 /* alphabetic insterion: is in new_id */
616         }
617         return id;
618 }
619
620 /* by spec, animdata is first item after ID */
621 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
622 static void id_copy_animdata(ID *id)
623 {
624         AnimData *adt= BKE_animdata_from_id(id);
625         
626         if (adt) {
627                 IdAdtTemplate *iat = (IdAdtTemplate *)id;
628                 iat->adt= BKE_copy_animdata(iat->adt);
629         }
630 }
631
632 /* material nodes use this since they are not treated as libdata */
633 void copy_libblock_data(ID *id, const ID *id_from)
634 {
635         if (id_from->properties)
636                 id->properties = IDP_CopyProperty(id_from->properties);
637
638         /* the duplicate should get a copy of the animdata */
639         id_copy_animdata(id);
640 }
641
642 /* used everywhere in blenkernel */
643 void *copy_libblock(void *rt)
644 {
645         ID *idn, *id;
646         ListBase *lb;
647         char *cp, *cpn;
648         size_t idn_len;
649         
650         id= rt;
651
652         lb= which_libbase(G.main, GS(id->name));
653         idn= alloc_libblock(lb, GS(id->name), id->name+2);
654
655         assert(idn != NULL);
656
657         idn_len= MEM_allocN_len(idn);
658         if(idn_len - sizeof(ID) > 0) {
659                 cp= (char *)id;
660                 cpn= (char *)idn;
661                 memcpy(cpn+sizeof(ID), cp+sizeof(ID), idn_len - sizeof(ID));
662         }
663         
664         id->newid= idn;
665         idn->flag |= LIB_NEW;
666
667         copy_libblock_data(idn, id);
668         
669         return idn;
670 }
671
672 static void free_library(Library *UNUSED(lib))
673 {
674         /* no freeing needed for libraries yet */
675 }
676
677 static void (*free_windowmanager_cb)(bContext *, wmWindowManager *)= NULL;
678
679 void set_free_windowmanager_cb(void (*func)(bContext *C, wmWindowManager *) )
680 {
681         free_windowmanager_cb= func;
682 }
683
684 void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
685 {
686         ChannelDriver *driver;
687         FCurve *fcu;
688
689         /* find the driver this belongs to and update it */
690         for (fcu=adt->drivers.first; fcu; fcu=fcu->next) {
691                 driver= fcu->driver;
692                 
693                 if (driver) {
694                         DriverVar *dvar;
695                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
696                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
697                                 {
698                                         if (dtar->id == userdata)
699                                                 dtar->id= NULL;
700                                 }
701                                 DRIVER_TARGETS_LOOPER_END
702                         }
703                 }
704         }
705 }
706
707
708 /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
709 void free_libblock(ListBase *lb, void *idv)
710 {
711         ID *id= idv;
712         
713         switch( GS(id->name) ) {        /* GetShort from util.h */
714                 case ID_SCE:
715                         free_scene((Scene *)id);
716                         break;
717                 case ID_LI:
718                         free_library((Library *)id);
719                         break;
720                 case ID_OB:
721                         free_object((Object *)id);
722                         break;
723                 case ID_ME:
724                         free_mesh((Mesh *)id);
725                         break;
726                 case ID_CU:
727                         free_curve((Curve *)id);
728                         break;
729                 case ID_MB:
730                         free_mball((MetaBall *)id);
731                         break;
732                 case ID_MA:
733                         free_material((Material *)id);
734                         break;
735                 case ID_TE:
736                         free_texture((Tex *)id);
737                         break;
738                 case ID_IM:
739                         free_image((Image *)id);
740                         break;
741                 case ID_LT:
742                         free_lattice((Lattice *)id);
743                         break;
744                 case ID_LA:
745                         free_lamp((Lamp *)id);
746                         break;
747                 case ID_CA:
748                         free_camera((Camera*) id);
749                         break;
750                 case ID_IP:
751                         free_ipo((Ipo *)id);
752                         break;
753                 case ID_KE:
754                         free_key((Key *)id);
755                         break;
756                 case ID_WO:
757                         free_world((World *)id);
758                         break;
759                 case ID_SCR:
760                         free_screen((bScreen *)id);
761                         break;
762                 case ID_VF:
763                         free_vfont((VFont *)id);
764                         break;
765                 case ID_TXT:
766                         free_text((Text *)id);
767                         break;
768                 case ID_SCRIPT:
769                         //XXX free_script((Script *)id);
770                         break;
771                 case ID_SO:
772                         sound_free((bSound*)id);
773                         break;
774                 case ID_GR:
775                         free_group_objects((Group *)id);
776                         break;
777                 case ID_AR:
778                         free_armature((bArmature *)id);
779                         break;
780                 case ID_AC:
781                         free_action((bAction *)id);
782                         break;
783                 case ID_NT:
784                         ntreeFreeTree((bNodeTree *)id);
785                         break;
786                 case ID_BR:
787                         free_brush((Brush *)id);
788                         break;
789                 case ID_PA:
790                         psys_free_settings((ParticleSettings *)id);
791                         break;
792                 case ID_WM:
793                         if(free_windowmanager_cb)
794                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
795                         break;
796                 case ID_GD:
797                         free_gpencil_data((bGPdata *)id);
798                         break;
799         }
800
801         if (id->properties) {
802                 IDP_FreeProperty(id->properties);
803                 MEM_freeN(id->properties);
804         }
805
806         BLI_remlink(lb, id);
807
808         /* this ID may be a driver target! */
809         BKE_animdata_main_cb(G.main, animdata_dtar_clear_cb, (void *)id);
810
811         MEM_freeN(id);
812 }
813
814 void free_libblock_us(ListBase *lb, void *idv)          /* test users */
815 {
816         ID *id= idv;
817         
818         id->us--;
819
820         if(id->us<0) {
821                 if(id->lib) printf("ERROR block %s %s users %d\n", id->lib->name, id->name, id->us);
822                 else printf("ERROR block %s users %d\n", id->name, id->us);
823         }
824         if(id->us==0) {
825                 if( GS(id->name)==ID_OB ) unlink_object((Object *)id);
826                 
827                 free_libblock(lb, id);
828         }
829 }
830
831
832 void free_main(Main *mainvar)
833 {
834         /* also call when reading a file, erase all, etc */
835         ListBase *lbarray[MAX_LIBARRAY];
836         int a;
837
838         a= set_listbasepointers(mainvar, lbarray);
839         while(a--) {
840                 ListBase *lb= lbarray[a];
841                 ID *id;
842                 
843                 while ( (id= lb->first) ) {
844                         free_libblock(lb, id);
845                 }
846         }
847
848         MEM_freeN(mainvar);
849 }
850
851 /* ***************** ID ************************ */
852
853
854 ID *find_id(char *type, char *name)             /* type: "OB" or "MA" etc */
855 {
856         ListBase *lb= which_libbase(G.main, GS(type));
857         return BLI_findstring(lb, name, offsetof(ID, name) + 2);
858 }
859
860 static void get_flags_for_id(ID *id, char *buf) 
861 {
862         int isfake= id->flag & LIB_FAKEUSER;
863         int isnode=0;
864                 /* Writeout the flags for the entry, note there
865                  * is a small hack that writes 5 spaces instead
866                  * of 4 if no flags are displayed... this makes
867                  * things usually line up ok - better would be
868                  * to have that explicit, oh well - zr
869                  */
870
871         if(GS(id->name)==ID_MA)
872                 isnode= ((Material *)id)->use_nodes;
873         if(GS(id->name)==ID_TE)
874                 isnode= ((Tex *)id)->use_nodes;
875         
876         if (id->us<0)
877                 sprintf(buf, "-1W ");
878         else if (!id->lib && !isfake && id->us && !isnode)
879                 sprintf(buf, "     ");
880         else if(isnode)
881                 sprintf(buf, "%c%cN%c ", id->lib?'L':' ', isfake?'F':' ', (id->us==0)?'O':' ');
882         else
883                 sprintf(buf, "%c%c%c ", id->lib?'L':' ', isfake?'F':' ', (id->us==0)?'O':' ');
884 }
885
886 #define IDPUP_NO_VIEWER 1
887
888 static void IDnames_to_dyn_pupstring(DynStr *pupds, ListBase *lb, ID *link, short *nr, int hideflag)
889 {
890         int i, nids= BLI_countlist(lb);
891                 
892         if (nr) *nr= -1;
893         
894         if (nr && nids>MAX_IDPUP) {
895                 BLI_dynstr_append(pupds, "DataBrowse %x-2");
896                 *nr= -2;
897         } else {
898                 ID *id;
899                 
900                 for (i=0, id= lb->first; id; id= id->next, i++) {
901                         char buf[32];
902                         
903                         if (nr && id==link) *nr= i+1;
904
905                         if (U.uiflag & USER_HIDE_DOT && id->name[2]=='.')
906                                 continue;
907                         if (hideflag & IDPUP_NO_VIEWER)
908                                 if (GS(id->name)==ID_IM)
909                                         if ( ((Image *)id)->source==IMA_SRC_VIEWER )
910                                                 continue;
911                         
912                         get_flags_for_id(id, buf);
913                                 
914                         BLI_dynstr_append(pupds, buf);
915                         BLI_dynstr_append(pupds, id->name+2);
916                         sprintf(buf, "%%x%d", i+1);
917                         BLI_dynstr_append(pupds, buf);
918                         
919                         /* icon */
920                         switch(GS(id->name))
921                         {
922                         case ID_MA: /* fall through */
923                         case ID_TE: /* fall through */
924                         case ID_IM: /* fall through */
925                         case ID_WO: /* fall through */
926                         case ID_LA: /* fall through */
927                                 sprintf(buf, "%%i%d", BKE_icon_getid(id) );
928                                 BLI_dynstr_append(pupds, buf);
929                                 break;
930                         default:
931                                 break;
932                         }
933                         
934                         if(id->next)
935                                 BLI_dynstr_append(pupds, "|");
936                 }
937         }
938 }
939
940
941 /* used by headerbuttons.c buttons.c editobject.c editseq.c */
942 /* if nr==NULL no MAX_IDPUP, this for non-header browsing */
943 void IDnames_to_pupstring(char **str, char *title, char *extraops, ListBase *lb, ID *link, short *nr)
944 {
945         DynStr *pupds= BLI_dynstr_new();
946
947         if (title) {
948                 BLI_dynstr_append(pupds, title);
949                 BLI_dynstr_append(pupds, "%t|");
950         }
951         
952         if (extraops) {
953                 BLI_dynstr_append(pupds, extraops);
954                 if (BLI_dynstr_get_len(pupds))
955                         BLI_dynstr_append(pupds, "|");
956         }
957
958         IDnames_to_dyn_pupstring(pupds, lb, link, nr, 0);
959         
960         *str= BLI_dynstr_get_cstring(pupds);
961         BLI_dynstr_free(pupds);
962 }
963
964 /* skips viewer images */
965 void IMAnames_to_pupstring(char **str, char *title, char *extraops, ListBase *lb, ID *link, short *nr)
966 {
967         DynStr *pupds= BLI_dynstr_new();
968         
969         if (title) {
970                 BLI_dynstr_append(pupds, title);
971                 BLI_dynstr_append(pupds, "%t|");
972         }
973         
974         if (extraops) {
975                 BLI_dynstr_append(pupds, extraops);
976                 if (BLI_dynstr_get_len(pupds))
977                         BLI_dynstr_append(pupds, "|");
978         }
979         
980         IDnames_to_dyn_pupstring(pupds, lb, link, nr, IDPUP_NO_VIEWER);
981         
982         *str= BLI_dynstr_get_cstring(pupds);
983         BLI_dynstr_free(pupds);
984 }
985
986
987 /* used by buttons.c library.c mball.c */
988 int splitIDname(char *name, char *left, int *nr)
989 {
990         int a;
991         
992         *nr= 0;
993         strncpy(left, name, 21);
994         
995         a= strlen(name);
996         if(a>1 && name[a-1]=='.') return a;
997         
998         while(a--) {
999                 if( name[a]=='.' ) {
1000                         left[a]= 0;
1001                         *nr= atol(name+a+1);
1002                         return a;
1003                 }
1004                 if( isdigit(name[a])==0 ) break;
1005                 
1006                 left[a]= 0;
1007         }
1008
1009         for(a= 0; name[a]; a++)
1010                 left[a]= name[a];
1011
1012         return a;
1013 }
1014
1015 static void sort_alpha_id(ListBase *lb, ID *id)
1016 {
1017         ID *idtest;
1018         
1019         /* insert alphabetically */
1020         if(lb->first!=lb->last) {
1021                 BLI_remlink(lb, id);
1022                 
1023                 idtest= lb->first;
1024                 while(idtest) {
1025                         if(BLI_strcasecmp(idtest->name, id->name)>0 || idtest->lib) {
1026                                 BLI_insertlinkbefore(lb, idtest, id);
1027                                 break;
1028                         }
1029                         idtest= idtest->next;
1030                 }
1031                 /* as last */
1032                 if(idtest==0) {
1033                         BLI_addtail(lb, id);
1034                 }
1035         }
1036         
1037 }
1038
1039 /*
1040  * Check to see if there is an ID with the same name as 'name'.
1041  * Returns the ID if so, if not, returns NULL
1042  */
1043 static ID *is_dupid(ListBase *lb, ID *id, char *name)
1044 {
1045         ID *idtest=NULL;
1046         
1047         for( idtest = lb->first; idtest; idtest = idtest->next ) {
1048                 /* if idtest is not a lib */ 
1049                 if( id != idtest && idtest->lib == NULL ) {
1050                         /* do not test alphabetic! */
1051                         /* optimized */
1052                         if( idtest->name[2] == name[0] ) {
1053                                 if(strcmp(name, idtest->name+2)==0) break;
1054                         }
1055                 }
1056         }
1057         
1058         return idtest;
1059 }
1060
1061 /* 
1062  * Check to see if an ID name is already used, and find a new one if so.
1063  * Return 1 if created a new name (returned in name).
1064  *
1065  * Normally the ID that's being check is already in the ListBase, so ID *id
1066  * points at the new entry.  The Python Library module needs to know what
1067  * the name of a datablock will be before it is appended; in this case ID *id
1068  * id is NULL;
1069  */
1070
1071 static int check_for_dupid(ListBase *lb, ID *id, char *name)
1072 {
1073         ID *idtest;
1074         int nr= 0, nrtest, a, left_len;
1075         char left[32], leftest[32], in_use[32];
1076
1077         /* make sure input name is terminated properly */
1078         /* if( strlen(name) > 21 ) name[21]= 0; */
1079         /* removed since this is only ever called from one place - campbell */
1080
1081         while (1) {
1082
1083                 /* phase 1: id already exists? */
1084                 idtest = is_dupid(lb, id, name);
1085
1086                 /* if there is no double, done */
1087                 if( idtest == NULL ) return 0;
1088
1089                 /* we have a dup; need to make a new name */
1090                 /* quick check so we can reuse one of first 32 ids if vacant */
1091                 memset(in_use, 0, sizeof(in_use));
1092
1093                 /* get name portion, number portion ("name.number") */
1094                 left_len= splitIDname(name, left, &nr);
1095
1096                 /* if new name will be too long, truncate it */
1097                 if(nr > 999 && left_len > 16) {
1098                         left[16]= 0;
1099                         left_len= 16;
1100                 }
1101                 else if(left_len > 17) {
1102                         left[17]= 0;
1103                         left_len= 17;
1104                 }
1105
1106                 for(idtest= lb->first; idtest; idtest= idtest->next) {
1107                         if(             (id != idtest) &&
1108                                         (idtest->lib == NULL) &&
1109                                         (*name == *(idtest->name+2)) &&
1110                                         (strncmp(name, idtest->name+2, left_len)==0) &&
1111                                         (splitIDname(idtest->name+2, leftest, &nrtest) == left_len)
1112                         ) {
1113                                 if(nrtest < sizeof(in_use))
1114                                         in_use[nrtest]= 1;      /* mark as used */
1115                                 if(nr <= nrtest)
1116                                         nr= nrtest+1;           /* track largest unused */
1117                         }
1118                 }
1119
1120                 /* decide which value of nr to use */
1121                 for(a=0; a < sizeof(in_use); a++) {
1122                         if(a>=nr) break;        /* stop when we've check up to biggest */
1123                         if( in_use[a]==0 ) { /* found an unused value */
1124                                 nr = a;
1125                                 break;
1126                         }
1127                 }
1128
1129                 /* If the original name has no numeric suffix, 
1130                  * rather than just chopping and adding numbers, 
1131                  * shave off the end chars until we have a unique name.
1132                  * Check the null terminators match as well so we dont get Cube.000 -> Cube.00 */
1133                 if (nr==0 && name[left_len]== '\0') {
1134                         int len = left_len-1;
1135                         idtest= is_dupid(lb, id, name);
1136                         
1137                         while (idtest && len> 1) {
1138                                 name[len--] = '\0';
1139                                 idtest= is_dupid(lb, id, name);
1140                         }
1141                         if (idtest == NULL) return 1;
1142                         /* otherwise just continue and use a number suffix */
1143                 }
1144                 
1145                 if(nr > 999 && left_len > 16) {
1146                         /* this would overflow name buffer */
1147                         left[16] = 0;
1148                         /* left_len = 16; */ /* for now this isnt used again */
1149                         memcpy(name, left, sizeof(char) * 17);
1150                         continue;
1151                 }
1152                 /* this format specifier is from hell... */
1153                 sprintf(name, "%s.%.3d", left, nr);
1154
1155                 return 1;
1156         }
1157 }
1158
1159 /*
1160  * Only for local blocks: external en indirect blocks already have a
1161  * unique ID.
1162  *
1163  * return 1: created a new name
1164  */
1165
1166 int new_id(ListBase *lb, ID *id, const char *tname)
1167 {
1168         int result;
1169         char name[22];
1170
1171         /* if library, don't rename */
1172         if(id->lib) return 0;
1173
1174         /* if no libdata given, look up based on ID */
1175         if(lb==NULL) lb= which_libbase(G.main, GS(id->name));
1176
1177         /* if no name given, use name of current ID
1178          * else make a copy (tname args can be const) */
1179         if(tname==NULL)
1180                 tname= id->name+2;
1181
1182         strncpy(name, tname, sizeof(name)-1);
1183
1184         /* if result > 21, strncpy don't put the final '\0' to name.
1185          * easier to assign each time then to check if its needed */
1186         name[sizeof(name)-1]= 0;
1187
1188         if(name[0] == '\0') {
1189                 /* disallow empty names */
1190                 strcpy(name, ID_FALLBACK_NAME);
1191         }
1192         else {
1193                 /* disallow non utf8 chars,
1194                  * the interface checks for this but new ID's based on file names dont */
1195                 BLI_utf8_invalid_strip(name, strlen(name));
1196         }
1197
1198         result = check_for_dupid(lb, id, name);
1199         strcpy(id->name+2, name);
1200
1201         /* This was in 2.43 and previous releases
1202          * however all data in blender should be sorted, not just duplicate names
1203          * sorting should not hurt, but noting just incause it alters the way other
1204          * functions work, so sort every time */
1205         /* if( result )
1206                 sort_alpha_id(lb, id);*/
1207         
1208         sort_alpha_id(lb, id);
1209         
1210         return result;
1211 }
1212
1213 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1214 void clear_id_newpoins()
1215 {
1216         ListBase *lbarray[MAX_LIBARRAY];
1217         ID *id;
1218         int a;
1219
1220         a= set_listbasepointers(G.main, lbarray);
1221         while(a--) {
1222                 id= lbarray[a]->first;
1223                 while(id) {
1224                         id->newid= 0;
1225                         id->flag &= ~LIB_NEW;
1226                         id= id->next;
1227                 }
1228         }
1229 }
1230
1231 /* only for library fixes */
1232 static void image_fix_relative_path(Image *ima)
1233 {
1234         if(ima->id.lib==NULL) return;
1235         if(strncmp(ima->name, "//", 2)==0) {
1236                 BLI_path_abs(ima->name, ima->id.lib->filepath);
1237                 BLI_path_rel(ima->name, G.main->name);
1238         }
1239 }
1240
1241 #define LIBTAG(a)       if(a && a->id.lib) {a->id.flag &=~LIB_INDIRECT; a->id.flag |= LIB_EXTERN;}
1242
1243 static void lib_indirect_test_id(ID *id, Library *lib)
1244 {
1245         
1246         if(id->lib) {
1247                 /* datablocks that were indirectly related are now direct links
1248                  * without this, appending data that has a link to other data will fail to write */
1249                 if(lib && id->lib->parent == lib) {
1250                         id_lib_extern(id);
1251                 }
1252                 return;
1253         }
1254         
1255         if(GS(id->name)==ID_OB) {               
1256                 Object *ob= (Object *)id;
1257                 bActionStrip *strip;
1258                 Mesh *me;
1259
1260                 int a;
1261         
1262                 // XXX old animation system! --------------------------------------
1263                 for (strip=ob->nlastrips.first; strip; strip=strip->next){
1264                         LIBTAG(strip->object); 
1265                         LIBTAG(strip->act);
1266                         LIBTAG(strip->ipo);
1267                 }
1268                 // XXX: new animation system needs something like this?
1269         
1270                 for(a=0; a<ob->totcol; a++) {
1271                         LIBTAG(ob->mat[a]);
1272                 }
1273         
1274                 LIBTAG(ob->dup_group);
1275                 LIBTAG(ob->proxy);
1276                 
1277                 me= ob->data;
1278                 LIBTAG(me);
1279         }
1280 }
1281
1282 void tag_main(struct Main *mainvar, int tag)
1283 {
1284         ListBase *lbarray[MAX_LIBARRAY];
1285         ID *id;
1286         int a;
1287
1288         a= set_listbasepointers(mainvar, lbarray);
1289         while(a--) {
1290                 for(id= lbarray[a]->first; id; id= id->next) {
1291                         if(tag) id->flag |= LIB_DOIT;
1292                         else    id->flag &= ~LIB_DOIT;
1293                 }
1294         }
1295 }
1296
1297 /* if lib!=NULL, only all from lib local */
1298 void all_local(Library *lib, int untagged_only)
1299 {
1300         ListBase *lbarray[MAX_LIBARRAY], tempbase={0, 0};
1301         ID *id, *idn;
1302         int a;
1303
1304         a= set_listbasepointers(G.main, lbarray);
1305         while(a--) {
1306                 id= lbarray[a]->first;
1307                 
1308                 while(id) {
1309                         id->newid= NULL;
1310                         idn= id->next;          /* id is possibly being inserted again */
1311                         
1312                         /* The check on the second line (LIB_PRE_EXISTING) is done so its
1313                          * possible to tag data you dont want to be made local, used for
1314                          * appending data, so any libdata already linked wont become local
1315                          * (very nasty to discover all your links are lost after appending)  
1316                          * */
1317                         if(id->flag & (LIB_EXTERN|LIB_INDIRECT|LIB_NEW) &&
1318                           (untagged_only==0 || !(id->flag & LIB_PRE_EXISTING)))
1319                         {
1320                                 if(lib==NULL || id->lib==lib) {
1321                                         id->flag &= ~(LIB_EXTERN|LIB_INDIRECT|LIB_NEW);
1322
1323                                         if(id->lib) {
1324                                                 /* relative file patch */
1325                                                 if(GS(id->name)==ID_IM)
1326                                                         image_fix_relative_path((Image *)id);
1327                                                 
1328                                                 id->lib= NULL;
1329                                                 new_id(lbarray[a], id, 0);      /* new_id only does it with double names */
1330                                                 sort_alpha_id(lbarray[a], id);
1331                                         }
1332                                 }
1333                         }
1334                         id= idn;
1335                 }
1336                 
1337                 /* patch2: make it aphabetically */
1338                 while( (id=tempbase.first) ) {
1339                         BLI_remlink(&tempbase, id);
1340                         BLI_addtail(lbarray[a], id);
1341                         new_id(lbarray[a], id, 0);
1342                 }
1343         }
1344
1345         /* patch 3: make sure library data isn't indirect falsely... */
1346         a= set_listbasepointers(G.main, lbarray);
1347         while(a--) {
1348                 for(id= lbarray[a]->first; id; id=id->next)
1349                         lib_indirect_test_id(id, lib);
1350         }
1351 }
1352
1353
1354 void test_idbutton(char *name)
1355 {
1356         /* called from buttons: when name already exists: call new_id */
1357         ListBase *lb;
1358         ID *idtest;
1359         
1360
1361         lb= which_libbase(G.main, GS(name-2) );
1362         if(lb==0) return;
1363         
1364         /* search for id */
1365         idtest= BLI_findstring(lb, name, offsetof(ID, name) + 2);
1366
1367         if(idtest) if( new_id(lb, idtest, name)==0 ) sort_alpha_id(lb, idtest);
1368 }
1369
1370 void text_idbutton(struct ID *id, char *text)
1371 {
1372         if(id) {
1373                 if(GS(id->name)==ID_SCE)
1374                         strcpy(text, "SCE: ");
1375                 else if(GS(id->name)==ID_SCE)
1376                         strcpy(text, "SCR: ");
1377                 else if(GS(id->name)==ID_MA && ((Material*)id)->use_nodes)
1378                         strcpy(text, "NT: ");
1379                 else {
1380                         text[0]= id->name[0];
1381                         text[1]= id->name[1];
1382                         text[2]= ':';
1383                         text[3]= ' ';
1384                         text[4]= 0;
1385                 }
1386         }
1387         else {
1388                 text[0]= '\0';
1389         }
1390 }
1391
1392 void rename_id(ID *id, char *name)
1393 {
1394         ListBase *lb;
1395
1396         strncpy(id->name+2, name, 21);
1397         lb= which_libbase(G.main, GS(id->name) );
1398         
1399         new_id(lb, id, name);                           
1400 }
1401
1402 void name_uiprefix_id(char *name, ID *id)
1403 {
1404         name[0] = id->lib ? 'L':' ';
1405         name[1] = id->flag & LIB_FAKEUSER ? 'F':' ';
1406         name[2] = ' ';
1407
1408         strcpy(name+3, id->name+2);
1409 }