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