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