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