- got tired of str[n]casecmp not declared warnings
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * readfile.c
3  *
4  * .blend file reading
5  *
6  * $Id$
7  *
8  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version. The Blender
14  * Foundation also sells licenses for use in proprietary software under
15  * the Blender License.  See http://www.blender.org/BL/ for information
16  * about this.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26  *
27  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
28  * All rights reserved.
29  *
30  * The Original Code is: all of this file.
31  *
32  * Contributor(s): none yet.
33  *
34  * ***** END GPL/BL DUAL LICENSE BLOCK *****
35  *
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #ifdef WIN32
43 #include "winsock2.h"
44 #include "BLI_winstuff.h"
45 #endif
46
47 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
48 #include <stdlib.h> // for getenv atoi
49 #include <fcntl.h> // for open
50 #include <string.h> // for strrchr strncmp strstr
51 #include <math.h> // for fabs
52
53 #ifndef WIN32
54     #include <unistd.h> // for read close
55     #include <sys/param.h> // for MAXPATHLEN
56 #else
57     #include <io.h> // for open close read
58 #endif
59
60 #include "nla.h"
61
62 #include "DNA_ID.h"
63 #include "DNA_packedFile_types.h"
64 #include "DNA_property_types.h"
65 #include "DNA_actuator_types.h"
66 #include "DNA_controller_types.h"
67 #include "DNA_sensor_types.h"
68 #include "DNA_sdna_types.h"
69 #include "DNA_scene_types.h"
70 #include "DNA_sequence_types.h"
71 #include "DNA_ika_types.h"
72 #include "DNA_camera_types.h"
73 #include "DNA_lattice_types.h"
74 #include "DNA_texture_types.h"
75 #include "DNA_key_types.h"
76 #include "DNA_meta_types.h"
77 #include "DNA_lamp_types.h"
78 #include "DNA_object_types.h"
79 #include "DNA_world_types.h"
80 #include "DNA_ipo_types.h"
81 #include "DNA_mesh_types.h"
82 #include "DNA_meshdata_types.h"
83 #include "DNA_image_types.h"
84 #include "DNA_material_types.h"
85 #include "DNA_curve_types.h"
86 #include "DNA_vfont_types.h"
87 #include "DNA_effect_types.h"
88 #include "DNA_text_types.h"
89 #include "DNA_view3d_types.h"
90 #include "DNA_screen_types.h"
91 #include "DNA_sound_types.h"
92 #include "DNA_space_types.h"
93 #include "DNA_oops_types.h"
94 #include "DNA_group_types.h"
95 #include "DNA_userdef_types.h"
96 #include "DNA_fileglobal_types.h"
97 #include "DNA_constraint_types.h"
98 #include "DNA_action_types.h"
99 #include "DNA_armature_types.h"
100 #include "DNA_nla_types.h"
101
102 #include "MEM_guardedalloc.h"
103 #include "BLI_blenlib.h"
104 #include "BLI_arithb.h"
105 #include "BLI_storage_types.h" // for relname flags
106
107 #include "BKE_bad_level_calls.h" // for reopen_text build_seqar (from WHILE_SEQ) open_plugin_seq set_rects_butspace check_imasel_copy
108
109 #include "BKE_armature.h"       //      for precalc_bonelist_irestmats
110 #include "BKE_action.h"
111 #include "BKE_constraint.h"
112 #include "BKE_curve.h"
113 #include "BKE_effect.h" // for give_parteff
114 #include "BKE_global.h" // for G
115 #include "BKE_property.h" // for get_property
116 #include "BKE_library.h" // for wich_libbase
117 #include "BKE_main.h" // for Main
118 #include "BKE_mesh.h" // for ME_ defines (patching)
119 #include "BKE_object.h"
120 #include "BKE_sca.h" // for init_actuator
121 #include "BKE_scene.h"
122 #include "BKE_softbody.h"       // sbNew()
123 #include "BKE_texture.h" // for open_plugin_tex
124 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
125
126 #include "BIF_butspace.h" // for do_versions, patching event codes
127
128 #include "BLO_readfile.h"
129 #include "BLO_undofile.h"
130 #include "BLO_readblenfile.h" // streaming read pipe, for BLO_readblenfile BLO_readblenfilememory
131
132 #include "readfile.h"
133
134 #include "genfile.h"
135
136 #include "mydevice.h"
137 #include "blendef.h"
138
139 /*
140  Remark: still a weak point is the newadress() function, that doesnt solve reading from
141  multiple files at the same time
142
143  (added remark: oh, i thought that was solved? will look at that... (ton)
144
145 READ
146 - Existing Library (Main) push or free
147 - allocate new Main
148 - load file
149 - read SDNA
150 - for each LibBlock
151         - read LibBlock
152         - if a Library
153                 - make a new Main
154                 - attach ID's to it
155         - else
156                 - read associated 'direct data'
157                 - link direct data (internal and to LibBlock)
158 - read FileGlobal
159 - read USER data, only when indicated (file is ~/.B.blend)
160 - free file
161 - per Library (per Main)
162         - read file
163         - read SDNA
164         - find LibBlocks and attach IDs to Main
165                 - if external LibBlock
166                         - search all Main's
167                                 - or it's already read,
168                                 - or not read yet
169                                 - or make new Main
170         - per LibBlock
171                 - read recursive
172                 - read associated direct data
173                 - link direct data (internal and to LibBlock)
174         - free file
175 - per Library with unread LibBlocks
176         - read file
177         - read SDNA
178         - per LibBlock
179                - read recursive
180                - read associated direct data
181                - link direct data (internal and to LibBlock)
182         - free file
183 - join all Mains
184 - link all LibBlocks and indirect pointers to libblocks
185 - initialize FileGlobal and copy pointers to Global
186 */
187
188 /* also occurs in library.c */
189 /* GS reads the memory pointed at in a specific ordering. There are,
190  * however two definitions for it. I have jotted them down here, both,
191  * but I think the first one is actually used. The thing is that
192  * big-endian systems might read this the wrong way round. OTOH, we
193  * constructed the IDs that are read out with this macro explicitly as
194  * well. I expect we'll sort it out soon... */
195
196 /* from blendef: */
197 #define GS(a)   (*((short *)(a)))
198
199 /* from misc_util: flip the bytes from x  */
200 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
201
202 // only used here in readfile.c
203 #define SWITCH_LONGINT(a) { \
204     char s_i, *p_i; \
205     p_i= (char *)&(a);  \
206     s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
207     s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
208     s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
209     s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; }
210 // only used here in readfile.c
211 #define SWITCH_SHORT(a) { \
212     char s_i, *p_i; \
213     p_i= (char *)&(a); \
214     s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
215
216
217 /***/
218
219 typedef struct OldNew {
220         void *old, *newp;
221         int nr;
222 } OldNew;
223
224 typedef struct OldNewMap {
225         OldNew *entries;
226         int nentries, entriessize;
227
228         int lasthit;
229 } OldNewMap;
230
231
232 /* local prototypes */
233 void lib_link_screen_restore(Main *, char , Scene *);
234 extern          short freeN(void *vmemh); /* defined in util.h */  
235
236
237 static OldNewMap *oldnewmap_new(void) {
238         OldNewMap *onm= MEM_mallocN(sizeof(*onm), "OldNewMap");
239         onm->lasthit= 0;
240         onm->nentries= 0;
241         onm->entriessize= 1024;
242         onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
243
244         return onm;
245 }
246
247 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) {
248         OldNew *entry;
249
250         if (onm->nentries==onm->entriessize) {
251                 int osize= onm->entriessize;
252                 OldNew *oentries= onm->entries;
253
254                 onm->entriessize*= 2;
255                 onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
256
257                 memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
258                 MEM_freeN(oentries);
259         }
260
261         entry= &onm->entries[onm->nentries++];
262         entry->old= oldaddr;
263         entry->newp= newaddr;
264         entry->nr= nr;
265 }
266
267 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) {
268         int i;
269
270         if (onm->lasthit<onm->nentries-1) {
271                 OldNew *entry= &onm->entries[++onm->lasthit];
272
273                 if (entry->old==addr) {
274                         entry->nr++;
275                         return entry->newp;
276                 }
277         }
278
279         for (i=0; i<onm->nentries; i++) {
280                 OldNew *entry= &onm->entries[i];
281
282                 if (entry->old==addr) {
283                         onm->lasthit= i;
284
285                         entry->nr++;
286                         return entry->newp;
287                 }
288         }
289
290         return NULL;
291 }
292
293 static void *oldnewmap_liblookup_and_inc(OldNewMap *onm, void *addr, void *lib) {
294         int i;
295
296         if (onm->lasthit<onm->nentries-1) {
297                 OldNew *entry= &onm->entries[++onm->lasthit];
298
299                 if (entry->old==addr) {
300                         ID *id= entry->newp;
301
302                         if (id && (!lib || id->lib)) {
303                                 entry->nr++;
304
305                                 return entry->newp;
306                         }
307                 }
308         }
309
310         for (i=0; i<onm->nentries; i++) {
311                 OldNew *entry= &onm->entries[i];
312
313                 if (entry->old==addr) {
314                         ID *id= entry->newp;
315
316                         if (id && (!lib || id->lib)) {
317                                 entry->nr++;
318
319                                 return entry->newp;
320                         }
321                 }
322         }
323
324         return NULL;
325 }
326
327 static void *oldnewmap_typelookup_and_inc(OldNewMap *onm, void *addr, short type) {
328         int i;
329
330         if (onm->lasthit<onm->nentries-1) {
331                 OldNew *entry= &onm->entries[++onm->lasthit];
332
333                 if (entry->old==addr) {
334                         ID *id= entry->newp;
335
336                         if (id && (GS(id->name) == type)) {
337                                 entry->nr++;
338
339                                 return entry->newp;
340                         }
341                 }
342         }
343
344         for (i=0; i<onm->nentries; i++) {
345                 OldNew *entry= &onm->entries[i];
346
347                 if (entry->old==addr) {
348                         ID *id= entry->newp;
349
350                         if (id && (GS(id->name) == type)) {
351                                 entry->nr++;
352
353                                 return entry->newp;
354                         }
355                 }
356         }
357
358         return NULL;
359 }
360
361 static void oldnewmap_free_unused(OldNewMap *onm) {
362         int i;
363
364         for (i=0; i<onm->nentries; i++) {
365                 OldNew *entry= &onm->entries[i];
366                 if (entry->nr==0) {
367                         MEM_freeN(entry->newp);
368                         entry->newp= NULL;
369                 }
370         }
371 }
372
373 static void oldnewmap_clear(OldNewMap *onm) {
374         onm->nentries= 0;
375         onm->lasthit= 0;
376 }
377
378 static void oldnewmap_free(OldNewMap *onm) {
379         MEM_freeN(onm->entries);
380         MEM_freeN(onm);
381 }
382
383 /***/
384
385 static void read_libraries(FileData *basefd, ListBase *mainlist);
386
387 /* ************ help functions ***************** */
388
389 static void add_main_to_main(Main *mainvar, Main *from)
390 {
391         ListBase *lbarray[100], *fromarray[100];        // define in library.c too
392         int a;
393
394         a= set_listbasepointers(mainvar, lbarray);
395         a= set_listbasepointers(from, fromarray);
396         while(a--) {
397                 addlisttolist(lbarray[a], fromarray[a]);
398         }
399 }
400
401 void blo_join_main(ListBase *mainlist)
402 {
403         Main *tojoin, *mainl= mainlist->first;
404
405         while ((tojoin= mainl->next)) {
406                 add_main_to_main(mainl, tojoin);
407                 BLI_remlink(mainlist, tojoin);
408                 MEM_freeN(tojoin);
409         }
410 }
411
412 static void split_libdata(ListBase *lb, Main *first)
413 {
414         ListBase *lbn;
415         ID *id, *idnext;
416         Main *mainvar;
417
418         id= lb->first;
419         while(id) {
420                 idnext= id->next;
421                 if(id->lib) {
422                         mainvar= first;
423                         while(mainvar) {
424                                 if(mainvar->curlib==id->lib) {
425                                         lbn= wich_libbase(mainvar, GS(id->name));
426                                         BLI_remlink(lb, id);
427                                         BLI_addtail(lbn, id);
428                                         break;
429                                 }
430                                 mainvar= mainvar->next;
431                         }
432                         if(mainvar==0) printf("error split_libdata\n");
433                 }
434                 id= idnext;
435         }
436 }
437
438 void blo_split_main(ListBase *mainlist)
439 {
440         Main *mainl= mainlist->first;
441         ListBase *lbarray[30];
442         Library *lib;
443         int i;
444
445         for (lib= mainl->library.first; lib; lib= lib->id.next) {
446                 Main *libmain= MEM_callocN(sizeof(*libmain), "libmain");
447                 libmain->curlib= lib;
448
449                 BLI_addtail(mainlist, libmain);
450         }
451
452         i= set_listbasepointers(mainl, lbarray);
453         while(i--)
454                 split_libdata(lbarray[i], mainl->next);
455 }
456
457 static Main *blo_find_main(ListBase *mainlist, char *name)
458 {
459         Main *m;
460         Library *lib;
461         char name1[FILE_MAXDIR+FILE_MAXFILE];
462         char libname1[FILE_MAXDIR+FILE_MAXFILE];
463
464         /* name can be stringcode too */
465         strcpy(name1, name);
466         BLI_convertstringcode(name1, G.sce, 0);
467
468         for (m= mainlist->first; m; m= m->next) {
469                 char *libname= (m->curlib)?m->curlib->name:m->name;
470                 
471                 strcpy(libname1, libname);
472                 BLI_convertstringcode(libname1, G.sce, 0);
473                 
474                 if (BLI_streq(name1, libname1))
475                         return m;
476         }
477
478         m= MEM_callocN(sizeof(*m), "find_main");
479         BLI_addtail(mainlist, m);
480
481         lib= alloc_libblock(&m->library, ID_LI, "lib");
482         strcpy(lib->name, name);
483         m->curlib= lib;
484
485         return m;
486 }
487
488
489 /* ************ FILE PARSING ****************** */
490
491 static void switch_endian_bh4(BHead4 *bhead)
492 {
493         /* the ID_.. codes */
494         if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
495
496         if (bhead->code != ENDB) {
497                 SWITCH_INT(bhead->len);
498                 SWITCH_INT(bhead->SDNAnr);
499                 SWITCH_INT(bhead->nr);
500         }
501 }
502
503 static void switch_endian_bh8(BHead8 *bhead)
504 {
505         /* the ID_.. codes */
506         if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
507
508         if (bhead->code != ENDB) {
509                 SWITCH_INT(bhead->len);
510                 SWITCH_INT(bhead->SDNAnr);
511                 SWITCH_INT(bhead->nr);
512         }
513 }
514
515 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
516 {
517         BHead4 *bhead4 = (BHead4 *) bhead;
518 #if defined(WIN32) && !defined(FREE_WINDOWS)
519         __int64 old;
520 #else
521         long long old;
522 #endif
523
524         bhead4->code= bhead8->code;
525         bhead4->len= bhead8->len;
526
527         if (bhead4->code != ENDB) {
528
529                 // why is this here ??
530                 if (do_endian_swap) {
531                         SWITCH_LONGINT(bhead8->old);
532                 }
533
534                 /* this patch is to avoid a long long being read from not-eight aligned positions
535                    is necessary on SGI with -n32 compiling (no, is necessary on
536                    any modern 64bit architecture) */
537                 memcpy(&old, &bhead8->old, 8);
538                 bhead4->old = (int) (old >> 3);
539
540                 bhead4->SDNAnr= bhead8->SDNAnr;
541                 bhead4->nr= bhead8->nr;
542         }
543 }
544
545 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
546 {
547         BHead8 *bhead8 = (BHead8 *) bhead;
548
549         bhead8->code= bhead4->code;
550         bhead8->len= bhead4->len;
551
552         if (bhead8->code != ENDB) {
553                 bhead8->old= bhead4->old;
554                 bhead8->SDNAnr= bhead4->SDNAnr;
555                 bhead8->nr= bhead4->nr;
556         }
557 }
558
559 static BHeadN *get_bhead(FileData *fd)
560 {
561         BHead8 bhead8;
562         BHead4 bhead4;
563         BHead  bhead;
564         BHeadN *new_bhead = 0;
565         int readsize;
566
567         if (fd) {
568                 if ( ! fd->eof) {
569
570                         // First read the bhead structure.
571                         // Depending on the platform the file was written on this can
572                         // be a big or little endian BHead4 or BHead8 structure.
573
574                         // As usual 'ENDB' (the last *partial* bhead of the file)
575                         // needs some special handling. We don't want to EOF just yet.
576
577                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
578                                 bhead4.code = DATA;
579                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
580
581                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
582                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
583                                                 switch_endian_bh4(&bhead4);
584                                         }
585
586                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
587                                                 bh8_from_bh4(&bhead, &bhead4);
588                                         } else {
589                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
590                                         }
591                                 } else {
592                                         fd->eof = 1;
593                                 }
594                         } else {
595                                 bhead8.code = DATA;
596                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
597
598                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
599                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
600                                                 switch_endian_bh8(&bhead8);
601                                         }
602
603                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
604                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
605                                         } else {
606                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
607                                         }
608                                 } else {
609                                         fd->eof = 1;
610                                 }
611                         }
612
613                         // bhead now contains the (converted) bhead structure. Now read
614                         // the associated data and put everything in a BHeadN (creative naming !)
615
616                         if ( ! fd->eof) {
617                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
618                                 if (new_bhead) {
619                                         new_bhead->next = new_bhead->prev = 0;
620                                         new_bhead->bhead = bhead;
621
622                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
623
624                                         if (readsize != bhead.len) {
625                                                 fd->eof = 1;
626                                                 MEM_freeN(new_bhead);
627                                         }
628                                 } else {
629                                         fd->eof = 1;
630                                 }
631                         }
632                 }
633         }
634
635         // We've read a new block. Now add it to the list
636         // of blocks.
637
638         if (new_bhead) {
639                 BLI_addtail(&fd->listbase, new_bhead);
640         }
641
642         return(new_bhead);
643 }
644
645 BHead *blo_firstbhead(FileData *fd)
646 {
647         BHeadN *new_bhead;
648         BHead *bhead = 0;
649
650         // Rewind the file
651         // Read in a new block if necessary
652
653         new_bhead = fd->listbase.first;
654         if (new_bhead == 0) {
655                 new_bhead = get_bhead(fd);
656         }
657
658         if (new_bhead) {
659                 bhead = &new_bhead->bhead;
660         }
661
662         return(bhead);
663 }
664
665 BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
666 {
667         BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
668         BHeadN *prev= bheadn->prev;
669
670         return prev?&prev->bhead:NULL;
671 }
672
673 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
674 {
675         BHeadN *new_bhead = 0;
676         BHead *bhead = 0;
677
678         if (thisblock) {
679                 // bhead is actually a sub part of BHeadN
680                 // We calculate the BHeadN pointer from the BHead pointer below
681                 new_bhead = (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
682
683                 // get the next BHeadN. If it doesn't exist we read in the next one
684                 new_bhead = new_bhead->next;
685                 if (new_bhead == 0) {
686                         new_bhead = get_bhead(fd);
687                 }
688         }
689
690         if (new_bhead) {
691                 // here we do the reverse:
692                 // go from the BHeadN pointer to the BHead pointer
693                 bhead = &new_bhead->bhead;
694         }
695
696         return(bhead);
697 }
698
699 static void decode_blender_header(FileData *fd)
700 {
701         char header[SIZEOFBLENDERHEADER], num[4];
702         int readsize;
703
704         // read in the header data
705         readsize = fd->read(fd, header, sizeof(header));
706
707         if (readsize == sizeof(header)) {
708                 if(strncmp(header, "BLENDER", 7) == 0) {
709                         int remove_this_endian_test= 1;
710
711                         fd->flags |= FD_FLAGS_FILE_OK;
712
713                         // what size are pointers in the file ?
714                         if(header[7]=='_') {
715                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
716                                 if (sizeof(void *) != 4) {
717                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
718                                 }
719                         } else {
720                                 if (sizeof(void *) != 8) {
721                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
722                                 }
723                         }
724
725                         // is the file saved in a different endian
726                         // than we need ?
727                         if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
728                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
729                         }
730
731                         // get the version number
732
733                         memcpy(num, header+9, 3);
734                         num[3] = 0;
735                         fd->fileversion = atoi(num);
736                 }
737         }
738 }
739
740 static int read_file_dna(FileData *fd)
741 {
742         BHead *bhead;
743
744         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
745                 if (bhead->code==DNA1) {
746                         int do_endian_swap= (fd->flags&FD_FLAGS_SWITCH_ENDIAN)?1:0;
747
748                         fd->filesdna= dna_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
749                         if (fd->filesdna)
750                                 fd->compflags= dna_get_structDNA_compareflags(fd->filesdna, fd->memsdna);
751
752                         return 1;
753                 } else if (bhead->code==ENDB)
754                         break;
755         }
756
757         return 0;
758 }
759 static int fd_read_from_file(FileData *filedata, void *buffer, int size)
760 {
761         int readsize = read(filedata->filedes, buffer, size);
762
763         if (readsize < 0) {
764                 readsize = EOF;
765         } else {
766                 filedata->seek += readsize;
767         }
768
769         return (readsize);
770 }
771
772 static int fd_read_from_memory(FileData *filedata, void *buffer, int size)
773 {
774                 // don't read more bytes then there are available in the buffer
775         int readsize = MIN2(size, filedata->buffersize - filedata->seek);
776
777         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
778         filedata->seek += readsize;
779
780         return (readsize);
781 }
782
783 static int fd_read_from_memfile(FileData *filedata, void *buffer, int size)
784 {
785         static unsigned int seek= 1<<30;        /* the current position */
786         static unsigned int offset= 0;          /* size of previous chunks */
787         static MemFileChunk *chunk=NULL;
788         
789         if(size==0) return 0;
790         
791         if(seek != filedata->seek) {
792                 chunk= filedata->memfile->chunks.first;
793                 seek= 0;
794                 
795                 while(chunk) {
796                         if(seek + chunk->size > filedata->seek) break;
797                         seek+= chunk->size;
798                         chunk= chunk->next;
799                 }
800                 offset= seek;
801                 seek= filedata->seek;
802         }
803         
804         if(chunk) {
805                 /* first check if it's on the end if current chunk */
806                 if( seek-offset == chunk->size) {
807                         offset+= chunk->size;
808                         chunk= chunk->next;
809                 }
810                 
811                 /* debug, should never happen */
812                 if(chunk==NULL) {
813                         printf("illegal read, chunk zero\n");
814                         return 0;
815                 }
816                 else if( (seek-offset)+size > chunk->size) {
817                         size= chunk->size - (seek-offset);
818                         printf("chunk too large, clipped to %d\n", size);
819                 }
820                 
821                 memcpy(buffer, chunk->buf + (seek-offset), size);
822                 filedata->seek += size;
823                 seek+= size;
824                 
825                 return (size);
826                 
827         }
828         return 0;
829 }
830
831 static FileData *filedata_new(void)
832 {
833         extern char DNAstr[];   /* DNA.c */
834         extern int DNAlen;
835         FileData *fd = MEM_callocN(sizeof(*fd), "FileData");
836
837         fd->filedes = -1;
838
839                 /* XXX, this doesn't need to be done all the time,
840                  * but it keeps us reentrant,  remove once we have
841                  * a lib that provides a nice lock. - zr
842                  */
843         fd->memsdna = dna_sdna_from_data(DNAstr,  DNAlen,  0);
844
845         fd->datamap = oldnewmap_new();
846         fd->globmap = oldnewmap_new();
847         fd->libmap = oldnewmap_new();
848
849         return fd;
850 }
851
852 FileData *blo_openblenderfile(char *name)
853 {
854         int file;
855         char name1[FILE_MAXDIR+FILE_MAXFILE];
856         
857         /* library files can have stringcodes */
858         strcpy(name1, name);
859         BLI_convertstringcode(name1, G.sce, 0);
860         
861         file= open(name1, O_BINARY|O_RDONLY);
862
863         if (file == -1) {
864                 return NULL;
865         } else {
866                 FileData *fd = filedata_new();
867                 fd->filedes = file;
868                 fd->buffersize = BLI_filesize(file);
869                 fd->read = fd_read_from_file;
870
871                 decode_blender_header(fd);
872
873                 if (fd->flags & FD_FLAGS_FILE_OK) {
874                         if (!read_file_dna(fd)) {
875                                 blo_freefiledata(fd);
876                                 fd= NULL;
877                         }
878                 } else {
879                         blo_freefiledata(fd);
880                         fd= NULL;
881                 }
882
883                 return fd;
884         }
885 }
886
887 FileData *blo_openblendermemory(void *mem, int memsize)
888 {
889         if (!mem || memsize<SIZEOFBLENDERHEADER) {
890                 return NULL;
891         } else {
892                 FileData *fd= filedata_new();
893                 fd->buffer= mem;
894                 fd->buffersize= memsize;
895                 fd->read= fd_read_from_memory;
896                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
897
898                 decode_blender_header(fd);
899
900                 if (fd->flags & FD_FLAGS_FILE_OK) {
901                         if (!read_file_dna(fd)) {
902                                 blo_freefiledata(fd);
903                                 fd= NULL;
904                         }
905                 } else {
906                         blo_freefiledata(fd);
907                         fd= NULL;
908                 }
909
910                 return fd;
911         }
912 }
913
914 FileData *blo_openblendermemfile(MemFile *memfile)
915 {
916         if (!memfile) {
917                 return NULL;
918         } else {
919                 FileData *fd= filedata_new();
920                 fd->memfile= memfile;
921
922                 fd->read= fd_read_from_memfile;
923                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
924
925                 decode_blender_header(fd);
926
927                 if (fd->flags & FD_FLAGS_FILE_OK) {
928                         if (!read_file_dna(fd)) {
929                                 blo_freefiledata(fd);
930                                 fd= NULL;
931                         }
932                 } else {
933                         blo_freefiledata(fd);
934                         fd= NULL;
935                 }
936
937                 return fd;
938         }
939 }
940
941
942 void blo_freefiledata(FileData *fd)
943 {
944         if (fd) {
945                 if (fd->filedes != -1) {
946                         close(fd->filedes);
947                 }
948
949                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
950                         MEM_freeN(fd->buffer);
951                         fd->buffer = 0;
952                 }
953
954                 // Free all BHeadN data blocks
955                 BLI_freelistN(&fd->listbase);
956
957                 if (fd->memsdna)
958                         dna_freestructDNA(fd->memsdna);
959                 if (fd->filesdna)
960                         dna_freestructDNA(fd->filesdna);
961                 if (fd->compflags)
962                         MEM_freeN(fd->compflags);
963
964                 if (fd->datamap)
965                         oldnewmap_free(fd->datamap);
966                 if (fd->globmap)
967                         oldnewmap_free(fd->globmap);
968                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
969                         oldnewmap_free(fd->libmap);
970
971                 MEM_freeN(fd);
972         }
973 }
974
975 /* ************ DIV ****************** */
976
977 int BLO_has_bfile_extension(char *str)
978 {
979         return (BLI_testextensie(str, ".ble") || BLI_testextensie(str, ".blend"));
980 }
981
982 /* ************** OLD POINTERS ******************* */
983
984 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
985 {
986         return oldnewmap_lookup_and_inc(fd->datamap, adr);
987 }
988
989 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
990 {
991         return oldnewmap_lookup_and_inc(fd->globmap, adr);
992 }
993
994 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
995 {
996         return oldnewmap_liblookup_and_inc(fd->libmap, adr, lib);
997 }
998
999 static void *newlibadr_us_type(FileData *fd, short type, void *adr)     /* only Lib data */
1000 {
1001         ID *id= oldnewmap_typelookup_and_inc(fd->libmap, adr, type);
1002
1003         if (id) {
1004                 id->us++;
1005         }
1006
1007         return id;
1008 }
1009
1010 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
1011 {
1012         ID *id= newlibadr(fd, lib, adr);
1013
1014         if(id) {
1015                 id->us++;
1016         }
1017
1018         return id;
1019 }
1020
1021 static void change_libadr(FileData *fd, void *old, void *new)
1022 {
1023         int i;
1024
1025                 /* changed one thing here, the old change_libadr
1026                  * only remapped addresses that had an id->lib,
1027                  * but that doesn't make sense to me... its an
1028                  * old pointer, period, it needs to be remapped. - zr
1029                  */
1030
1031                 /*
1032                  * Ton seemed to think it was necessary to look
1033                  * through all entries, and not return after finding
1034                  * a match, leaving this cryptic comment,
1035                  * // no return, maybe there can be more?
1036                  *
1037                  * That doesn't make sense to me either but I am
1038                  * too scared to remove it... it only would make
1039                  * sense if two distinct old address map to the
1040                  * same new address - obviously that shouldn't happen
1041                  * because memory addresses are unique.
1042                  *
1043                  * The only case it might happen is when two distinct
1044                  * libraries are mapped using the same table... this
1045                  * won't work to start with... At some point this
1046                  * all needs to be made sense of and made understandable,
1047                  * but I'm afraid I don't have time now. -zr
1048                  *
1049                  */
1050     /* the code is nasty, and needs a lot of energy to get into full understanding
1051        again... i now translate dutch comments, maybe that gives me more insight!
1052        But i guess it has to do with the assumption that 2 addresses can be allocated
1053        in different sessions, and therefore be the same... like the remark in the top
1054        of this c file (ton) */
1055
1056         for (i=0; i<fd->libmap->nentries; i++) {
1057                 OldNew *entry= &fd->libmap->entries[i];
1058
1059                 if (old==entry->newp) {
1060                         entry->newp= new;
1061                         break;
1062                 }
1063         }
1064 }
1065
1066
1067 /* ********** END OLD POINTERS ****************** */
1068 /* ********** READ FILE ****************** */
1069
1070 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1071 {
1072         int blocksize, nblocks;
1073         char *data;
1074
1075         data= (char *)(bhead+1); /*  BHEAD+DATA dependancy */
1076         blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1077
1078         nblocks= bhead->nr;
1079         while(nblocks--) {
1080                 dna_switch_endian_struct(filesdna, bhead->SDNAnr, data);
1081
1082                 data+= blocksize;
1083         }
1084 }
1085
1086 static void *read_struct(FileData *fd, BHead *bh, char *blockname)
1087 {
1088         void *temp= NULL;
1089
1090         if (bh->len) {
1091                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1092                         switch_endian_structs(fd->filesdna, bh);
1093
1094                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
1095                         if(fd->compflags[bh->SDNAnr]==2) {
1096                                 temp= dna_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1097                         } else {
1098                                 temp= MEM_mallocN(bh->len, blockname);
1099                                 memcpy(temp, (bh+1), bh->len); /*  BHEAD+DATA dependancy */
1100                         }
1101                 }
1102         }
1103
1104         return temp;
1105 }
1106
1107 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1108 {
1109         Link *ln, *prev;
1110
1111         if(lb->first==0) return;
1112
1113         lb->first= newdataadr(fd, lb->first);
1114         ln= lb->first;
1115         prev= 0;
1116         while(ln) {
1117                 ln->next= newdataadr(fd, ln->next);
1118                 ln->prev= prev;
1119                 prev= ln;
1120                 ln= ln->next;
1121         }
1122         lb->last= prev;
1123 }
1124
1125 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1126 {
1127         Link *ln, *prev;
1128         void *poin;
1129
1130         if(lb->first==0) return;
1131         poin= newdataadr(fd, lb->first);
1132         if(lb->first) {
1133                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1134         }
1135         lb->first= poin;
1136
1137         ln= lb->first;
1138         prev= 0;
1139         while(ln) {
1140                 poin= newdataadr(fd, ln->next);
1141                 if(ln->next) {
1142                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1143                 }
1144                 ln->next= poin;
1145                 ln->prev= prev;
1146                 prev= ln;
1147                 ln= ln->next;
1148         }
1149         lb->last= prev;
1150 }
1151
1152 static void test_pointer_array(FileData *fd, void **mat)
1153 {
1154 #if defined(WIN32) && !defined(FREE_WINDOWS)
1155         __int64 *lpoin, *lmat;
1156 #else
1157         long long *lpoin, *lmat;
1158 #endif
1159         int len, *ipoin, *imat;
1160
1161                 /* manually convert the pointer array in
1162                  * the old dna format to a pointer array in
1163                  * the new dna format.
1164                  */
1165         if(*mat) {
1166                 len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1167
1168                 if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1169                         ipoin=imat= MEM_mallocN( len*4, "newmatar");
1170                         lpoin= *mat;
1171
1172                         while(len-- > 0) {
1173                                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1174                                         SWITCH_LONGINT(*lpoin);
1175                                 *ipoin= (int) ((*lpoin) >> 3);
1176                                 ipoin++;
1177                                 lpoin++;
1178                         }
1179                         MEM_freeN(*mat);
1180                         *mat= imat;
1181                 }
1182
1183                 if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1184                         lpoin=lmat= MEM_mallocN( len*8, "newmatar");
1185                         ipoin= *mat;
1186
1187                         while(len-- > 0) {
1188                                 *lpoin= *ipoin;
1189                                 ipoin++;
1190                                 lpoin++;
1191                         }
1192                         MEM_freeN(*mat);
1193                         *mat= lmat;
1194                 }
1195         }
1196 }
1197
1198 /* ************ READ PACKEDFILE *************** */
1199
1200 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1201 {
1202         PackedFile *pf= newdataadr(fd, oldpf);
1203
1204         if (pf) {
1205                 pf->data= newdataadr(fd, pf->data);
1206         }
1207
1208         return pf;
1209 }
1210
1211 /* ************ READ SCRIPTLINK *************** */
1212
1213 static void lib_link_scriptlink(FileData *fd, ID *id, ScriptLink *slink)
1214 {
1215         int i;
1216
1217         for(i=0; i<slink->totscript; i++) {
1218                 slink->scripts[i]= newlibadr(fd, id->lib, slink->scripts[i]);
1219         }
1220 }
1221
1222 static void direct_link_scriptlink(FileData *fd, ScriptLink *slink)
1223 {
1224         slink->scripts= newdataadr(fd, slink->scripts);
1225         slink->flag= newdataadr(fd, slink->flag);
1226
1227         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1228                 int a;
1229
1230                 for(a=0; a<slink->totscript; a++) {
1231                         SWITCH_SHORT(slink->flag[a]);
1232                 }
1233         }
1234 }
1235
1236 /* ************ READ IKA ***************** */
1237
1238 static void lib_link_ika(FileData *fd, Main *main)
1239 {
1240         Ika *ika;
1241         int a;
1242         Deform *def;
1243
1244         ika= main->ika.first;
1245         while(ika) {
1246                 if(ika->id.flag & LIB_NEEDLINK) {
1247
1248                         ika->parent= newlibadr(fd, ika->id.lib, ika->parent);
1249
1250                         a= ika->totdef;
1251                         def= ika->def;
1252                         while(a--) {
1253                                 def->ob=  newlibadr(fd, ika->id.lib, def->ob);
1254                                 def++;
1255                         }
1256                         ika->id.flag -= LIB_NEEDLINK;
1257                 }
1258                 ika= ika->id.next;
1259         }
1260 }
1261
1262 static void direct_link_ika(FileData *fd, Ika *ika)
1263 {
1264         link_list(fd, &ika->limbbase);
1265
1266         ika->def= newdataadr(fd, ika->def);
1267
1268         /* error from V.138 and older */
1269         if(ika->def==0) ika->totdef= 0;
1270 }
1271
1272 /* ************ READ ARMATURE ***************** */
1273
1274 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1275 {
1276         bActionStrip *strip;
1277
1278         for (strip=striplist->first; strip; strip=strip->next){
1279                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1280                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1281         };
1282 }
1283
1284 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1285 {
1286         bConstraintChannel *chan;
1287
1288         for (chan=chanbase->first; chan; chan=chan->next){
1289                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1290         }
1291 }
1292
1293 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
1294 {
1295         bConstraint *con;
1296
1297         for (con = conlist->first; con; con=con->next) {
1298                 /*  patch for error introduced by changing constraints (dunno how) */
1299                 if(con->data==NULL) {
1300                         con->type= CONSTRAINT_TYPE_NULL;
1301                 }
1302
1303                 switch (con->type) {
1304                 case CONSTRAINT_TYPE_ACTION:
1305                         {
1306                                 bActionConstraint *data;
1307                                 data= ((bActionConstraint*)con->data);
1308                                 data->tar = newlibadr(fd, id->lib, data->tar);
1309                                 data->act = newlibadr(fd, id->lib, data->act);
1310                         }
1311                         break;
1312                 case CONSTRAINT_TYPE_LOCLIKE:
1313                         {
1314                                 bLocateLikeConstraint *data;
1315                                 data= ((bLocateLikeConstraint*)con->data);
1316                                 data->tar = newlibadr(fd, id->lib, data->tar);
1317                         };
1318                         break;
1319                 case CONSTRAINT_TYPE_ROTLIKE:
1320                         {
1321                                 bRotateLikeConstraint *data;
1322                                 data= ((bRotateLikeConstraint*)con->data);
1323                                 data->tar = newlibadr(fd, id->lib, data->tar);
1324                         };
1325                         break;
1326                 case CONSTRAINT_TYPE_KINEMATIC:
1327                         {
1328                                 bKinematicConstraint *data;
1329                                 data = ((bKinematicConstraint*)con->data);
1330                                 data->tar = newlibadr(fd, id->lib, data->tar);
1331                         }
1332                         break;
1333                 case CONSTRAINT_TYPE_TRACKTO:
1334                         {
1335                                 bTrackToConstraint *data;
1336                                 data = ((bTrackToConstraint*)con->data);
1337                                 data->tar = newlibadr(fd, id->lib, data->tar);
1338                         }
1339                         break;
1340                 case CONSTRAINT_TYPE_LOCKTRACK:
1341                         {
1342                                 bLockTrackConstraint *data;
1343                                 data= ((bLockTrackConstraint*)con->data);
1344                                 data->tar = newlibadr(fd, id->lib, data->tar);
1345                         };
1346                         break;
1347                 case CONSTRAINT_TYPE_FOLLOWPATH:
1348                         {
1349                                 bFollowPathConstraint *data;
1350                                 data= ((bFollowPathConstraint*)con->data);
1351                                 data->tar = newlibadr(fd, id->lib, data->tar);
1352                         };
1353                         break;
1354                 case CONSTRAINT_TYPE_DISTANCELIMIT:
1355                         {
1356                                 bDistanceLimitConstraint *data;
1357                                 data= ((bDistanceLimitConstraint*)con->data);
1358                                 data->tar = newlibadr(fd, id->lib, data->tar);
1359                         };
1360                         break;
1361                 case CONSTRAINT_TYPE_STRETCHTO:
1362                         {
1363                                 bStretchToConstraint *data;
1364                                 data= ((bStretchToConstraint*)con->data);
1365                                 data->tar = newlibadr(fd, id->lib, data->tar);
1366                         };
1367                         break;
1368
1369                 case CONSTRAINT_TYPE_NULL:
1370                         break;
1371                 }
1372         }
1373 }
1374
1375 static void direct_link_constraints(FileData *fd, ListBase *lb)
1376 {
1377         bConstraint *cons;
1378
1379         link_list(fd, lb);
1380         for (cons=lb->first; cons; cons=cons->next) {
1381                 cons->data = newdataadr(fd, cons->data);
1382                 switch (cons->type) {
1383                 default:
1384                         break;
1385                 }
1386                 // Link data
1387         }
1388 }
1389
1390 static void lib_link_bone(FileData *fd, ID *id, Bone *bone)
1391 {
1392         Bone *curBone;
1393
1394 //      lib_link_constraints(fd, id, &bone->constraints);
1395
1396         for (curBone=bone->childbase.first; curBone; curBone=curBone->next) {
1397                 lib_link_bone(fd, id, curBone);
1398         }
1399 }
1400
1401
1402 static void lib_link_pose(FileData *fd, ID *id, bPose *pose)
1403 {
1404         bPoseChannel *chan;
1405
1406         if (!pose)
1407                 return;
1408
1409         for (chan = pose->chanbase.first; chan; chan=chan->next) {
1410                 lib_link_constraints(fd, id, &chan->constraints);
1411         }
1412 }
1413
1414 static void lib_link_armature(FileData *fd, Main *main)
1415 {
1416         bArmature *arm;
1417         Bone *bone;
1418
1419         arm= main->armature.first;
1420
1421         while(arm) {
1422                 if(arm->id.flag & LIB_NEEDLINK) {
1423                         arm->id.flag -= LIB_NEEDLINK;
1424                 }
1425
1426                 for (bone=arm->bonebase.first; bone; bone=bone->next) {
1427                         lib_link_bone(fd, &arm->id, bone);
1428                 }
1429
1430                 arm= arm->id.next;
1431         }
1432 }
1433
1434 static void lib_link_action(FileData *fd, Main *main)
1435 {
1436         bAction *act;
1437         bActionChannel *chan;
1438
1439         act= main->action.first;
1440         while(act) {
1441                 if(act->id.flag & LIB_NEEDLINK) {
1442                         act->id.flag -= LIB_NEEDLINK;
1443
1444                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1445                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1446                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1447                         }
1448
1449                 }
1450                 act= act->id.next;
1451         }
1452 }
1453
1454 static void direct_link_bones(FileData *fd, Bone* bone)
1455 {
1456         Bone    *child;
1457
1458         bone->parent= newdataadr(fd, bone->parent);
1459
1460         link_list(fd, &bone->childbase);
1461
1462         for (child=bone->childbase.first; child; child=child->next) {
1463                 direct_link_bones(fd, child);
1464         }
1465 }
1466
1467
1468 static void direct_link_action(FileData *fd, bAction *act)
1469 {
1470         bActionChannel *achan;
1471
1472         link_list(fd, &act->chanbase);
1473
1474         for (achan = act->chanbase.first; achan; achan=achan->next)
1475                 link_list(fd, &achan->constraintChannels);
1476
1477 }
1478
1479 static void direct_link_armature(FileData *fd, bArmature *arm)
1480 {
1481         Bone    *bone;
1482
1483         link_list(fd, &arm->bonebase);
1484
1485         bone=arm->bonebase.first;
1486         while (bone) {
1487                 direct_link_bones(fd, bone);
1488                 bone=bone->next;
1489         }
1490 }
1491
1492 /* ************ READ CAMERA ***************** */
1493
1494 static void lib_link_camera(FileData *fd, Main *main)
1495 {
1496         Camera *ca;
1497
1498         ca= main->camera.first;
1499         while(ca) {
1500                 if(ca->id.flag & LIB_NEEDLINK) {
1501
1502                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1503
1504                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1505
1506                         ca->id.flag -= LIB_NEEDLINK;
1507                 }
1508                 ca= ca->id.next;
1509         }
1510 }
1511
1512 static void direct_link_camera(FileData *fd, Camera *ca)
1513 {
1514         direct_link_scriptlink(fd, &ca->scriptlink);
1515 }
1516
1517
1518 /* ************ READ LATTICE ***************** */
1519
1520 static void lib_link_latt(FileData *fd, Main *main)
1521 {
1522         Lattice *lt;
1523
1524         lt= main->latt.first;
1525         while(lt) {
1526                 if(lt->id.flag & LIB_NEEDLINK) {
1527
1528                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
1529                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
1530
1531                         lt->id.flag -= LIB_NEEDLINK;
1532                 }
1533                 lt= lt->id.next;
1534         }
1535 }
1536
1537 static void direct_link_latt(FileData *fd, Lattice *lt)
1538 {
1539         lt->def= newdataadr(fd, lt->def);
1540 }
1541
1542 /* ************ READ LAMP ***************** */
1543
1544 static void lib_link_lamp(FileData *fd, Main *main)
1545 {
1546         Lamp *la;
1547         MTex *mtex;
1548         int a;
1549
1550         la= main->lamp.first;
1551         while(la) {
1552                 if(la->id.flag & LIB_NEEDLINK) {
1553
1554                         for(a=0; a<MAX_MTEX; a++) {
1555                                 mtex= la->mtex[a];
1556                                 if(mtex) {
1557                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1558                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1559                                 }
1560                         }
1561
1562                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1563
1564                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1565
1566                         la->id.flag -= LIB_NEEDLINK;
1567                 }
1568                 la= la->id.next;
1569         }
1570 }
1571
1572 static void direct_link_lamp(FileData *fd, Lamp *la)
1573 {
1574         int a;
1575
1576         direct_link_scriptlink(fd, &la->scriptlink);
1577
1578         for(a=0; a<MAX_MTEX; a++) {
1579                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1580         }
1581 }
1582
1583 /* ************ READ keys ***************** */
1584
1585 static void lib_link_key(FileData *fd, Main *main)
1586 {
1587         Key *key;
1588
1589         key= main->key.first;
1590         while(key) {
1591                 if(key->id.flag & LIB_NEEDLINK) {
1592
1593                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1594                         key->from= newlibadr(fd, key->id.lib, key->from);
1595
1596                         key->id.flag -= LIB_NEEDLINK;
1597                 }
1598                 key= key->id.next;
1599         }
1600 }
1601
1602 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1603 {
1604         int elemsize, a, b;
1605         char *data, *poin, *cp;
1606
1607         elemsize= key->elemsize;
1608         data= kb->data;
1609
1610         for(a=0; a<kb->totelem; a++) {
1611
1612                 cp= key->elemstr;
1613                 poin= data;
1614
1615                 while( cp[0] ) {        /* cp[0]==amount */
1616
1617                         switch(cp[1]) {         /* cp[1]= type */
1618                         case IPO_FLOAT:
1619                         case IPO_BPOINT:
1620                         case IPO_BEZTRIPLE:
1621                                 b= cp[0];
1622                                 while(b--) {
1623                                         SWITCH_INT((*poin));
1624                                         poin+= 4;
1625                                 }
1626                                 break;
1627                         }
1628
1629                         cp+= 2;
1630
1631                 }
1632                 data+= elemsize;
1633         }
1634 }
1635
1636 static void direct_link_key(FileData *fd, Key *key)
1637 {
1638         KeyBlock *kb;
1639
1640         link_list(fd, &(key->block));
1641
1642         key->refkey= newdataadr(fd, key->refkey);
1643
1644         kb= key->block.first;
1645         while(kb) {
1646
1647                 kb->data= newdataadr(fd, kb->data);
1648
1649                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
1650                         switch_endian_keyblock(key, kb);
1651
1652                 kb= kb->next;
1653         }
1654 }
1655
1656 /* ************ READ mball ***************** */
1657
1658 static void lib_link_mball(FileData *fd, Main *main)
1659 {
1660         MetaBall *mb;
1661         int a;
1662
1663         mb= main->mball.first;
1664         while(mb) {
1665                 if(mb->id.flag & LIB_NEEDLINK) {
1666
1667                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
1668
1669                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
1670
1671                         mb->id.flag -= LIB_NEEDLINK;
1672                 }
1673                 mb= mb->id.next;
1674         }
1675 }
1676
1677 static void direct_link_mball(FileData *fd, MetaBall *mb)
1678 {
1679         mb->mat= newdataadr(fd, mb->mat);
1680         test_pointer_array(fd, (void **)&mb->mat);
1681
1682         link_list(fd, &(mb->elems));
1683
1684         mb->disp.first= mb->disp.last= 0;
1685
1686         mb->bb= 0;
1687 }
1688
1689 /* ************ READ WORLD ***************** */
1690
1691 static void lib_link_world(FileData *fd, Main *main)
1692 {
1693         World *wrld;
1694         MTex *mtex;
1695         int a;
1696
1697         wrld= main->world.first;
1698         while(wrld) {
1699                 if(wrld->id.flag & LIB_NEEDLINK) {
1700
1701                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
1702
1703                         for(a=0; a<MAX_MTEX; a++) {
1704                                 mtex= wrld->mtex[a];
1705                                 if(mtex) {
1706                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
1707                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
1708                                 }
1709                         }
1710
1711                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
1712
1713                         wrld->id.flag -= LIB_NEEDLINK;
1714                 }
1715                 wrld= wrld->id.next;
1716         }
1717 }
1718
1719 static void direct_link_world(FileData *fd, World *wrld)
1720 {
1721         int a;
1722
1723         direct_link_scriptlink(fd, &wrld->scriptlink);
1724
1725         for(a=0; a<MAX_MTEX; a++) {
1726                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
1727         }
1728 }
1729
1730
1731 /* ************ READ IPO ***************** */
1732
1733 static void lib_link_ipo(FileData *fd, Main *main)
1734 {
1735         Ipo *ipo;
1736
1737         ipo= main->ipo.first;
1738         while(ipo) {
1739                 if(ipo->id.flag & LIB_NEEDLINK) {
1740
1741                         ipo->id.flag -= LIB_NEEDLINK;
1742                 }
1743                 ipo= ipo->id.next;
1744         }
1745 }
1746
1747 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1748 {
1749         IpoCurve *icu;
1750
1751         link_list(fd, &(ipo->curve));
1752         icu= ipo->curve.first;
1753         while(icu) {
1754                 icu->bezt= newdataadr(fd, icu->bezt);
1755                 icu->bp= newdataadr(fd, icu->bp);
1756                 icu= icu->next;
1757         }
1758 }
1759
1760 /* ************ READ VFONT ***************** */
1761
1762 static void lib_link_vfont(FileData *fd, Main *main)
1763 {
1764         VFont *vf;
1765
1766         vf= main->vfont.first;
1767         while(vf) {
1768                 if(vf->id.flag & LIB_NEEDLINK) {
1769                         vf->id.flag -= LIB_NEEDLINK;
1770                 }
1771                 vf= vf->id.next;
1772         }
1773 }
1774
1775 static void direct_link_vfont(FileData *fd, VFont *vf)
1776 {
1777         vf->data= NULL;
1778         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
1779 }
1780
1781 /* ************ READ TEXT ****************** */
1782
1783 static void lib_link_text(FileData *fd, Main *main)
1784 {
1785         Text *text;
1786
1787         text= main->text.first;
1788         while(text) {
1789                 if(text->id.flag & LIB_NEEDLINK) {
1790                         text->id.flag -= LIB_NEEDLINK;
1791                 }
1792                 text= text->id.next;
1793         }
1794 }
1795
1796 static void direct_link_text(FileData *fd, Text *text)
1797 {
1798         TextLine *ln;
1799
1800         text->name= newdataadr(fd, text->name);
1801
1802         text->undo_pos= -1;
1803         text->undo_len= TXT_INIT_UNDO;
1804         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
1805
1806         text->compiled= NULL;
1807
1808 /*
1809         if(text->flags & TXT_ISEXT) {
1810                 reopen_text(text);
1811         } else {
1812 */
1813
1814         link_list(fd, &text->lines);
1815
1816         text->curl= newdataadr(fd, text->curl);
1817         text->sell= newdataadr(fd, text->sell);
1818
1819         ln= text->lines.first;
1820         while(ln) {
1821                 ln->line= newdataadr(fd, ln->line);
1822
1823                 if (ln->len != (int) strlen(ln->line)) {
1824                         printf("Error loading text, line lengths differ\n");
1825                         ln->len = strlen(ln->line);
1826                 }
1827
1828                 ln= ln->next;
1829         }
1830
1831         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
1832
1833         text->id.us= 1;
1834 }
1835
1836 /* ************ READ IMAGE ***************** */
1837
1838 static void lib_link_image(FileData *fd, Main *main)
1839 {
1840         Image *ima;
1841
1842         ima= main->image.first;
1843         while (ima) {
1844                 if(ima->id.flag & LIB_NEEDLINK) {
1845
1846                         ima->id.flag -= LIB_NEEDLINK;
1847                 }
1848                 ima= ima->id.next;
1849         }
1850 }
1851
1852 static void direct_link_image(FileData *fd, Image *ima)
1853 {
1854         ima->ibuf= 0;
1855         ima->anim= 0;
1856         memset(ima->mipmap, 0, sizeof(ima->mipmap));
1857         ima->repbind= 0;
1858         ima->bindcode= 0;
1859
1860         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
1861
1862         ima->ok= 1;
1863 }
1864
1865
1866 /* ************ READ CURVE ***************** */
1867
1868 static void lib_link_curve(FileData *fd, Main *main)
1869 {
1870         Curve *cu;
1871         int a;
1872
1873         cu= main->curve.first;
1874         while(cu) {
1875                 if(cu->id.flag & LIB_NEEDLINK) {
1876
1877                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
1878
1879                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
1880                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
1881                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
1882                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
1883
1884                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
1885                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
1886
1887                         cu->id.flag -= LIB_NEEDLINK;
1888                 }
1889                 cu= cu->id.next;
1890         }
1891 }
1892
1893
1894 static void switch_endian_knots(Nurb *nu)
1895 {
1896         int len;
1897
1898         if(nu->knotsu) {
1899                 len= KNOTSU(nu);
1900                 while(len--) {
1901                         SWITCH_INT(nu->knotsu[len]);
1902                 }
1903         }
1904         if(nu->knotsv) {
1905                 len= KNOTSV(nu);
1906                 while(len--) {
1907                         SWITCH_INT(nu->knotsv[len]);
1908                 }
1909         }
1910 }
1911
1912 static void direct_link_curve(FileData *fd, Curve *cu)
1913 {
1914         Nurb *nu;
1915
1916         cu->mat= newdataadr(fd, cu->mat);
1917         test_pointer_array(fd, (void **)&cu->mat);
1918         cu->str= newdataadr(fd, cu->str);
1919
1920         if(cu->vfont==0) link_list(fd, &(cu->nurb));
1921         else {
1922                 cu->nurb.first=cu->nurb.last= 0;
1923         }
1924
1925         cu->bev.first=cu->bev.last= 0;
1926         cu->disp.first=cu->disp.last= 0;
1927         cu->path= 0;
1928
1929         nu= cu->nurb.first;
1930         while(nu) {
1931                 nu->bezt= newdataadr(fd, nu->bezt);
1932                 nu->bp= newdataadr(fd, nu->bp);
1933                 nu->knotsu= newdataadr(fd, nu->knotsu);
1934                 nu->knotsv= newdataadr(fd, nu->knotsv);
1935
1936                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1937                         switch_endian_knots(nu);
1938                 }
1939
1940                 nu= nu->next;
1941         }
1942         cu->bb= 0;
1943 }
1944
1945 /* ************ READ TEX ***************** */
1946
1947 static void lib_link_texture(FileData *fd, Main *main)
1948 {
1949         Tex *tex;
1950
1951         tex= main->tex.first;
1952         while(tex) {
1953                 if(tex->id.flag & LIB_NEEDLINK) {
1954
1955                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
1956                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
1957                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
1958
1959                         tex->id.flag -= LIB_NEEDLINK;
1960                 }
1961                 tex= tex->id.next;
1962         }
1963 }
1964
1965 static void direct_link_texture(FileData *fd, Tex *tex)
1966 {
1967         tex->plugin= newdataadr(fd, tex->plugin);
1968         if(tex->plugin) {
1969                 tex->plugin->handle= 0;
1970                 open_plugin_tex(tex->plugin);
1971         }
1972         tex->coba= newdataadr(fd, tex->coba);
1973         tex->env= newdataadr(fd, tex->env);
1974         if(tex->env) {
1975                 tex->env->ima= 0;
1976                 memset(tex->env->cube, 0, 6*sizeof(void *));
1977                 tex->env->ok= 0;
1978         }
1979 }
1980
1981
1982
1983 /* ************ READ MATERIAL ***************** */
1984
1985 static void lib_link_material(FileData *fd, Main *main)
1986 {
1987         Material *ma;
1988         MTex *mtex;
1989         int a;
1990
1991         ma= main->mat.first;
1992         while(ma) {
1993                 if(ma->id.flag & LIB_NEEDLINK) {
1994
1995                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
1996
1997                         for(a=0; a<MAX_MTEX; a++) {
1998                                 mtex= ma->mtex[a];
1999                                 if(mtex) {
2000                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2001                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2002                                 }
2003                         }
2004                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2005                         ma->id.flag -= LIB_NEEDLINK;
2006                 }
2007                 ma= ma->id.next;
2008         }
2009 }
2010
2011 static void direct_link_material(FileData *fd, Material *ma)
2012 {
2013         int a;
2014
2015         direct_link_scriptlink(fd, &ma->scriptlink);
2016
2017         for(a=0; a<MAX_MTEX; a++) {
2018                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2019         }
2020
2021         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2022         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2023         
2024 }
2025
2026 /* ************ READ MESH ***************** */
2027
2028 static void lib_link_mesh(FileData *fd, Main *main)
2029 {
2030         Mesh *me;
2031
2032         me= main->mesh.first;
2033         while(me) {
2034                 if(me->id.flag & LIB_NEEDLINK) {
2035                         int i;
2036
2037                         /* this check added for python created meshes */
2038                         if(me->mat) {
2039                                 for(i=0; i<me->totcol; i++)
2040                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2041                         }
2042                         else me->totcol= 0;
2043
2044                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2045                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2046                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2047
2048                         if(me->tface) {
2049                                 TFace *tfaces= me->tface;
2050
2051                                 for (i=0; i<me->totface; i++) {
2052                                         TFace *tf= &tfaces[i];
2053
2054                                         tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2055                                         if(tf->tpage) {
2056                                                 Image *ima= tf->tpage;
2057                                                 if(ima->id.us==0)
2058                                                         ima->id.us= 1;
2059                                         }
2060                                 }
2061                         }
2062                         me->id.flag -= LIB_NEEDLINK;
2063                 }
2064                 me= me->id.next;
2065         }
2066 }
2067
2068 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2069 {
2070         int     i, j;
2071
2072         if (!mdverts)
2073                 return;
2074
2075         for (i=0; i<count; i++) {
2076                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2077                 if (!mdverts[i].dw)
2078                         mdverts[i].totweight=0;
2079
2080                 for (j=0; j< mdverts[i].totweight; j++) {
2081                         mdverts[i].dw[j].data = NULL;   // not saved in file, clear pointer
2082                 }
2083         }
2084 }
2085
2086 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2087 {
2088         mesh->mat= newdataadr(fd, mesh->mat);
2089         test_pointer_array(fd, (void **)&mesh->mat);
2090
2091         mesh->mvert= newdataadr(fd, mesh->mvert);
2092         mesh->medge= newdataadr(fd, mesh->medge);
2093         mesh->mface= newdataadr(fd, mesh->mface);
2094         mesh->tface= newdataadr(fd, mesh->tface);
2095         mesh->mcol= newdataadr(fd, mesh->mcol);
2096         mesh->msticky= newdataadr(fd, mesh->msticky);
2097
2098         mesh->dvert= newdataadr(fd, mesh->dvert);
2099         direct_link_dverts(fd, mesh->totvert, mesh->dvert);
2100
2101         mesh->disp.first= mesh->disp.last= NULL;
2102         mesh->bb= NULL;
2103         mesh->oc= 0;
2104         mesh->dface= NULL;
2105         mesh->orco= NULL;
2106         mesh->decimated= NULL;
2107         mesh->derived= NULL;
2108
2109         if (mesh->tface) {
2110                 TFace *tfaces= mesh->tface;
2111                 int i;
2112
2113                 for (i=0; i<mesh->totface; i++) {
2114                         TFace *tf= &tfaces[i];
2115
2116                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2117                                 SWITCH_INT(tf->col[0]);
2118                                 SWITCH_INT(tf->col[1]);
2119                                 SWITCH_INT(tf->col[2]);
2120                                 SWITCH_INT(tf->col[3]);
2121                         }
2122                 }
2123         }
2124 }
2125
2126 /* ************ READ OBJECT ***************** */
2127
2128 static void lib_link_object(FileData *fd, Main *main)
2129 {
2130         Object *ob;
2131         bSensor *sens;
2132         bController *cont;
2133         bActuator *act;
2134         ObHook *hook;
2135         void *poin;
2136         int warn=0, a;
2137
2138         ob= main->object.first;
2139         while(ob) {
2140                 if(ob->id.flag & LIB_NEEDLINK) {
2141
2142                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2143                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2144                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2145                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2146
2147 //                      ob->activecon = newglobadr(fd, ob->activecon);
2148
2149                         poin= ob->data;
2150                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2151
2152                         if(ob->data==NULL && poin!=NULL) {
2153                                 ob->type= OB_EMPTY;
2154                                 warn= 1;
2155                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2156                                 else printf("Object %s lost data. Lib:%x\n", ob->id.name+2, (unsigned int) ob->id.lib);
2157                         }
2158                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2159
2160                         ob->id.flag -= LIB_NEEDLINK;
2161                         /* if id.us==0 a new base will be created later on */
2162
2163                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2164                         lib_link_pose(fd, &ob->id, ob->pose);
2165                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2166                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2167                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2168
2169
2170                         sens= ob->sensors.first;
2171                         while(sens) {
2172                                 if(ob->id.lib==NULL) {  // done in expand_main
2173                                         for(a=0; a<sens->totlinks; a++) {
2174                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2175                                         }
2176                                 }
2177                                 if(sens->type==SENS_TOUCH) {
2178                                         bTouchSensor *ts= sens->data;
2179                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2180                                 }
2181                                 else if(sens->type==SENS_MESSAGE) {
2182                                         bMessageSensor *ms= sens->data;
2183                                         ms->fromObject=
2184                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2185                                 }
2186                                 sens= sens->next;
2187                         }
2188
2189                         cont= ob->controllers.first;
2190                         while(cont) {
2191                                 if(ob->id.lib==NULL) {  // done in expand_main
2192                                         for(a=0; a<cont->totlinks; a++) {
2193                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2194                                         }
2195                                 }
2196                                 if(cont->type==CONT_PYTHON) {
2197                                         bPythonCont *pc= cont->data;
2198                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2199                                 }
2200                                 cont->slinks= NULL;
2201                                 cont->totslinks= 0;
2202
2203                                 cont= cont->next;
2204                         }
2205
2206                         act= ob->actuators.first;
2207                         while(act) {
2208                                 if(act->type==ACT_SOUND) {
2209                                         bSoundActuator *sa= act->data;
2210                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2211                                 }
2212                                 else if(act->type==ACT_CD) {
2213                                         /* bCDActuator *cda= act->data; */
2214                                 }
2215                                 else if(act->type==ACT_GAME) {
2216                                         /* bGameActuator *ga= act->data; */
2217                                 }
2218                                 else if(act->type==ACT_CAMERA) {
2219                                         bCameraActuator *ca= act->data;
2220                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2221                                 }
2222                                         /* leave this one, it's obsolete but necessary to read for conversion */
2223                                 else if(act->type==ACT_ADD_OBJECT) {
2224                                         bAddObjectActuator *eoa= act->data;
2225                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2226                                 }
2227                                 else if(act->type==ACT_EDIT_OBJECT) {
2228                                         bEditObjectActuator *eoa= act->data;
2229                                         if(eoa==NULL) {
2230                                                 init_actuator(act);
2231                                         }
2232                                         eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2233                                         eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2234                                 }
2235                                 else if(act->type==ACT_SCENE) {
2236                                         bSceneActuator *sa= act->data;
2237                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2238                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2239                                 }
2240                                 else if(act->type==ACT_ACTION) {
2241                                         bActionActuator *aa= act->data;
2242                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2243                                 }
2244                                 else if(act->type==ACT_PROPERTY) {
2245                                         bPropertyActuator *pa= act->data;
2246                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2247                                 }
2248                                 else if(act->type==ACT_MESSAGE) {
2249                                         bMessageActuator *ma= act->data;
2250                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2251                                 }
2252                                 act= act->next;
2253                         }
2254
2255                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2256                         
2257                         for(hook= ob->hooks.first; hook; hook= hook->next) {
2258                                 hook->parent= newlibadr(fd, ob->id.lib, hook->parent);
2259                         }
2260                 }
2261                 ob= ob->id.next;
2262         }
2263
2264         if(warn) error("WARNING IN CONSOLE");
2265 }
2266
2267
2268 static void direct_link_pose(FileData *fd, bPose *pose) {
2269
2270         bPoseChannel *chan;
2271
2272         if (!pose)
2273                 return;
2274
2275         link_list(fd, &pose->chanbase);
2276
2277         for (chan = pose->chanbase.first; chan; chan=chan->next) {
2278                 direct_link_constraints(fd, &chan->constraints);
2279         }
2280
2281 }
2282
2283 static void direct_link_object(FileData *fd, Object *ob)
2284 {
2285         PartEff *paf;
2286         bProperty *prop;
2287         bSensor *sens;
2288         bController *cont;
2289         bActuator *act;
2290         ObHook *hook;
2291         
2292         ob->disp.first=ob->disp.last= 0;
2293
2294         ob->pose= newdataadr(fd, ob->pose);
2295         direct_link_pose(fd, ob->pose);
2296
2297         link_list(fd, &ob->defbase);
2298         link_list(fd, &ob->nlastrips);
2299         link_list(fd, &ob->constraintChannels);
2300
2301         ob->activecon = newdataadr(fd, ob->activecon);
2302
2303         direct_link_scriptlink(fd, &ob->scriptlink);
2304
2305         ob->mat= newdataadr(fd, ob->mat);
2306         test_pointer_array(fd, (void **)&ob->mat);
2307         link_list(fd, &ob->effect);
2308         paf= ob->effect.first;
2309         while(paf) {
2310                 if(paf->type==EFF_PARTICLE) {
2311                         paf->keys= 0;
2312                 }
2313                 if(paf->type==EFF_WAVE) {
2314
2315                 }
2316                 paf= paf->next;
2317         }
2318
2319         ob->pd= newdataadr(fd, ob->pd);
2320         ob->soft= newdataadr(fd, ob->soft);
2321         if(ob->soft) {
2322                 SoftBody *sb= ob->soft;         // init all stuff so it gets rebuilt nicely
2323                 sb->totpoint= sb->totspring= 0;
2324                 sb->bpoint= NULL; 
2325                 sb->bspring= NULL;
2326         }
2327         
2328         link_list(fd, &ob->prop);
2329         prop= ob->prop.first;
2330         while(prop) {
2331                 prop->poin= newdataadr(fd, prop->poin);
2332                 if(prop->poin==0) prop->poin= &prop->data;
2333                 prop= prop->next;
2334         }
2335
2336         link_list(fd, &ob->sensors);
2337         sens= ob->sensors.first;
2338         while(sens) {
2339                 sens->data= newdataadr(fd, sens->data);
2340                 sens->links= newdataadr(fd, sens->links);
2341                 test_pointer_array(fd, (void **)&sens->links);
2342                 sens= sens->next;
2343         }
2344
2345         direct_link_constraints(fd, &ob->constraints);
2346
2347         link_glob_list(fd, &ob->controllers);
2348         cont= ob->controllers.first;
2349         while(cont) {
2350                 cont->data= newdataadr(fd, cont->data);
2351                 cont->links= newdataadr(fd, cont->links);
2352                 test_pointer_array(fd, (void **)&cont->links);
2353                 cont= cont->next;
2354         }
2355
2356         link_glob_list(fd, &ob->actuators);
2357         act= ob->actuators.first;
2358         while(act) {
2359                 act->data= newdataadr(fd, act->data);
2360                 act= act->next;
2361         }
2362
2363         link_list(fd, &ob->hooks);
2364         for(hook= ob->hooks.first; hook; hook= hook->next) {
2365                 hook->indexar= newdataadr(fd, hook->indexar);
2366                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2367                         int a;
2368                         for(a=0; a<hook->totindex; a++) {
2369                                 SWITCH_INT(hook->indexar[a]);
2370                         }
2371                 }
2372         }
2373         
2374         ob->bb= NULL;
2375 }
2376
2377 /* ************ READ SCENE ***************** */
2378
2379 static void lib_link_scene(FileData *fd, Main *main)
2380 {
2381         Scene *sce;
2382         Base *base, *next;
2383         Editing *ed;
2384         Sequence *seq;
2385
2386         sce= main->scene.first;
2387         while(sce) {
2388                 if(sce->id.flag & LIB_NEEDLINK) {
2389                         sce->id.us= 1;
2390                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
2391                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
2392                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
2393                         sce->ima= newlibadr_us(fd, sce->id.lib, sce->ima);
2394                         sce->group= newlibadr_us(fd, sce->id.lib, sce->group);
2395
2396                         base= sce->base.first;
2397                         while(base) {
2398                                 next= base->next;
2399
2400                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
2401                                 base->object= newlibadr_us_type(fd, ID_OB, base->object);
2402                                 
2403                                 /* when save during radiotool, needs cleared */
2404                                 base->flag &= ~OB_RADIO;
2405                                 
2406                                 if(base->object==0) {
2407                                         printf("LIB ERROR: base removed\n");
2408                                         BLI_remlink(&sce->base, base);
2409                                         if(base==sce->basact) sce->basact= 0;
2410                                         MEM_freeN(base);
2411                                 }
2412                                 base= next;
2413                         }
2414
2415                         ed= sce->ed;
2416                         if(ed) {
2417                                 WHILE_SEQ(&ed->seqbase) {
2418                                         if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
2419                                         if(seq->scene) seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
2420                                         if(seq->sound) {
2421                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
2422                                                 if (seq->sound) {
2423                                                         seq->sound->id.us++;
2424                                                         seq->sound->flags |= SOUND_FLAGS_SEQUENCE;
2425                                                 }
2426                                         }
2427                                         seq->anim= 0;
2428                                 }
2429                                 END_SEQ
2430                         }
2431                         
2432                         lib_link_scriptlink(fd, &sce->id, &sce->scriptlink);
2433                         
2434                         sce->id.flag -= LIB_NEEDLINK;
2435                 }
2436
2437                 sce= sce->id.next;
2438         }
2439 }
2440
2441 static void link_recurs_seq(FileData *fd, ListBase *lb)
2442 {
2443         Sequence *seq;
2444
2445         link_list(fd, lb);
2446         seq= lb->first;
2447         while(seq) {
2448                 if(seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase);
2449                 seq= seq->next;
2450         }
2451 }
2452
2453 static void direct_link_scene(FileData *fd, Scene *sce)
2454 {
2455         Editing *ed;
2456         Sequence *seq;
2457         MetaStack *ms;
2458         StripElem *se;
2459         int a;
2460
2461         link_list(fd, &(sce->base));
2462
2463         sce->basact= newdataadr(fd, sce->basact);
2464
2465         sce->radio= newdataadr(fd, sce->radio);
2466
2467         sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
2468         if (sce->r.avicodecdata) {
2469                 sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
2470                 sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
2471         }
2472
2473         sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
2474         if (sce->r.qtcodecdata) {
2475                 sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
2476         }
2477
2478         if(sce->ed) {
2479                 ed= sce->ed= newdataadr(fd, sce->ed);
2480
2481                 /* recursive link sequences, lb will be correctly initialized */
2482                 link_recurs_seq(fd, &ed->seqbase);
2483
2484                 WHILE_SEQ(&ed->seqbase) {
2485                         seq->seq1= newdataadr(fd, seq->seq1);
2486                         seq->seq2= newdataadr(fd, seq->seq2);
2487                         seq->seq3= newdataadr(fd, seq->seq3);
2488                         /* a patch: after introduction of effects with 3 input strips */
2489                         if(seq->seq3==0) seq->seq3= seq->seq2;
2490
2491                         seq->curelem= 0;
2492
2493                         seq->plugin= newdataadr(fd, seq->plugin);
2494                         if(seq->plugin) open_plugin_seq(seq->plugin, seq->name+2);
2495
2496                         seq->effectdata= newdataadr(fd, seq->effectdata);
2497
2498                         seq->strip= newdataadr(fd, seq->strip);
2499                         if(seq->strip && seq->strip->done==0) {
2500                                 seq->strip->done= 1;
2501
2502                                 /* standard: strips from effects/metas are not written, but are mallocced */
2503
2504                                 if(seq->type==SEQ_IMAGE) {
2505                                         seq->strip->stripdata= newdataadr(fd, seq->strip->stripdata);
2506                                         se= seq->strip->stripdata;
2507                                         if(se) {
2508                                                 for(a=0; a<seq->strip->len; a++, se++) {
2509                                                         se->ok= 1;
2510                                                         se->ibuf= 0;
2511                                                 }
2512                                         }
2513                                 }
2514                                 else if(seq->type==SEQ_MOVIE) {
2515                                         /* only first stripelem is in file */
2516                                         se= newdataadr(fd, seq->strip->stripdata);
2517
2518                                         if(se) {
2519                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2520                                                 *seq->strip->stripdata= *se;
2521                                                 MEM_freeN(se);
2522
2523                                                 se= seq->strip->stripdata;
2524
2525                                                 for(a=0; a<seq->strip->len; a++, se++) {
2526                                                         se->ok= 1;
2527                                                         se->ibuf= 0;
2528                                                         se->nr= a + 1;
2529                                                 }
2530                                         }
2531                                 }
2532                                 else if(seq->type==SEQ_SOUND) {
2533                                         /* only first stripelem is in file */
2534                                         se= newdataadr(fd, seq->strip->stripdata);
2535
2536                                         if(se) {
2537                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2538                                                 *seq->strip->stripdata= *se;
2539                                                 MEM_freeN(se);
2540
2541                                                 se= seq->strip->stripdata;
2542
2543                                                 for(a=0; a<seq->strip->len; a++, se++) {
2544                                                         se->ok= 2; /* why? */
2545                                                         se->ibuf= 0;
2546                                                         se->nr= a + 1;
2547                                                 }
2548                                         }
2549                                 }
2550                                 else if(seq->len>0)
2551                                         seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2552
2553                         }
2554                 }
2555                 END_SEQ
2556                         
2557                 /* link metastack, slight abuse of structs here, have to restore pointer to internal part in struct */
2558                 {
2559                         Sequence temp;
2560                         char *poin;
2561                         long offset;
2562                         /*int seted=0;*/ /*unused*/
2563                         
2564                         offset= ((long)&(temp.seqbase)) - ((long)&temp);
2565
2566                         /* root pointer */
2567                         poin= (char *)ed->seqbasep;
2568                         poin -= offset;
2569                         poin= newdataadr(fd, poin);
2570                         if(poin) ed->seqbasep= (ListBase *)(poin+offset);
2571                         else ed->seqbasep= &ed->seqbase;
2572                         
2573                         /* stack */
2574                         link_list(fd, &(ed->metastack));
2575                         
2576                         for(ms= ed->metastack.first; ms; ms= ms->next) {
2577                                 ms->parseq= newdataadr(fd, ms->parseq);
2578                                 
2579                                 poin= (char *)ms->oldbasep;
2580                                 poin -= offset;
2581                                 poin= newdataadr(fd, poin);
2582                                 if(poin) ms->oldbasep= (ListBase *)(poin+offset);
2583                                 else ms->oldbasep= &ed->seqbase;
2584                         }
2585                 }
2586         }
2587
2588         direct_link_scriptlink(fd, &sce->scriptlink);
2589 }
2590
2591 /* ************ READ SCREEN ***************** */
2592
2593 /* note: file read without screens option G_FILE_NO_UI; 
2594    check lib pointers in call below */
2595 static void lib_link_screen(FileData *fd, Main *main)
2596 {
2597         bScreen *sc;
2598         ScrArea *sa;
2599
2600         sc= main->screen.first;
2601         while(sc) {
2602                 if(sc->id.flag & LIB_NEEDLINK) {
2603                         sc->id.us= 1;
2604                         sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
2605
2606                         sa= sc->areabase.first;
2607                         while(sa) {
2608                                 SpaceLink *sl;
2609
2610                                 sa->full= newlibadr(fd, sc->id.lib, sa->full);
2611
2612                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
2613                                         if(sl->spacetype==SPACE_VIEW3D) {
2614                                                 View3D *v3d= (View3D*) sl;
2615
2616                                                 v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
2617
2618                                                 if(v3d->bgpic) {
2619                                                         v3d->bgpic->ima= newlibadr_us(fd, sc->id.lib, v3d->bgpic->ima);
2620                                                         v3d->bgpic->tex= newlibadr_us(fd, sc->id.lib, v3d->bgpic->tex);
2621                                                         v3d->bgpic->rect= NULL;
2622                                                 }
2623                                                 if(v3d->localvd) {
2624                                                         v3d->localvd->camera= newlibadr(fd, sc->id.lib, v3d->localvd->camera);
2625                                                 }
2626                                         }
2627                                         else if(sl->spacetype==SPACE_IPO) {
2628                                                 SpaceIpo *sipo= (SpaceIpo *)sl;
2629                                                 sipo->editipo= 0;
2630                                                 
2631                                                 if(sipo->blocktype==ID_SEQ) sipo->from= NULL;   // no libdata
2632                                                 else sipo->from= newlibadr(fd, sc->id.lib, sipo->from);
2633                                                 
2634                                                 sipo->ipokey.first= sipo->ipokey.last= 0;
2635                                                 sipo->ipo= newlibadr(fd, sc->id.lib, sipo->ipo);
2636                                         }
2637                                         else if(sl->spacetype==SPACE_BUTS) {
2638                                                 SpaceButs *sbuts= (SpaceButs *)sl;
2639                                                 sbuts->rect= NULL;
2640                                                 sbuts->lockpoin= NULL;
2641                                                 if(main->versionfile<132) set_rects_butspace(sbuts);
2642                                         }
2643                                         else if(sl->spacetype==SPACE_FILE) {
2644                                                 SpaceFile *sfile= (SpaceFile *)sl;
2645
2646                                                 sfile->filelist= 0;
2647                                                 sfile->libfiledata= 0;
2648                                                 sfile->returnfunc= 0;
2649                                         }
2650                                         else if(sl->spacetype==SPACE_IMASEL) {
2651                                                 check_imasel_copy((SpaceImaSel *)sl);
2652                                         }
2653                                         else if(sl->spacetype==SPACE_ACTION) {
2654                                                 SpaceAction *saction= (SpaceAction *)sl;
2655                                                 saction->action = newlibadr(fd, sc->id.lib, saction->action);
2656                                         }
2657                                         else if(sl->spacetype==SPACE_IMAGE) {
2658                                                 SpaceImage *sima= (SpaceImage *)sl;
2659
2660                                                 sima->image= newlibadr_us(fd, sc->id.lib, sima->image);
2661                                         }
2662                                         else if(sl->spacetype==SPACE_NLA){
2663                                                 /* SpaceNla *snla= (SpaceNla *)sl;      */
2664                                         }
2665                                         else if(sl->spacetype==SPACE_TEXT) {
2666                                                 SpaceText *st= (SpaceText *)sl;
2667
2668                                                 st->text= newlibadr(fd, sc->id.lib, st->text);
2669
2670                                         }
2671                                         else if(sl->spacetype==SPACE_SCRIPT) {
2672                                                 SpaceScript *sc= (SpaceScript *)sl;
2673
2674                                                 sc->script = NULL;
2675                                         }
2676                                         else if(sl->spacetype==SPACE_OOPS) {
2677                                                 SpaceOops *so= (SpaceOops *)sl;
2678                                                 Oops *oops;
2679                                                 TreeStoreElem *tselem;
2680                                                 int a;
2681
2682                                                 oops= so->oops.first;
2683                                                 while(oops) {
2684                                                         oops->id= newlibadr(fd, NULL, oops->id);
2685                                                         oops= oops->next;
2686                                                 }
2687                                                 so->lockpoin= NULL;
2688                                                 so->tree.first= so->tree.last= NULL;
2689                                                 
2690                                                 if(so->treestore) {
2691                                                         tselem= so->treestore->data;
2692                                                         for(a=0; a<so->treestore->usedelem; a++, tselem++) {
2693                                                                 tselem->id= newlibadr(fd, NULL, tselem->id);
2694                                                         }
2695                                                 }
2696                                                 
2697                                         }
2698                                         else if(sl->spacetype==SPACE_SOUND) {
2699                                                 SpaceSound *ssound= (SpaceSound *)sl;
2700
2701                                                 ssound->sound= newlibadr_us(fd, sc->id.lib, ssound->sound);
2702                                         }
2703                                 }
2704                                 sa= sa->next;
2705                         }
2706                         sc->id.flag -= LIB_NEEDLINK;
2707                 }
2708                 sc= sc->id.next;
2709         }
2710 }
2711
2712 static void *restore_pointer_by_name(Main *mainp, ID *id, int user)
2713 {
2714         ListBase *lb;
2715         ID *idn=NULL;
2716                 
2717         if(id) {
2718                 lb= wich_libbase(mainp, GS(id->name));
2719                 
2720                 if(lb) {        // there's still risk of checking corrupt mem (freed Ids in oops)
2721                         idn= lb->first;
2722                         while(idn) {
2723                                 if( strcmp(idn->name, id->name)==0) {
2724                                         if(user && idn->us==0) idn->us++;
2725                                         break;
2726                                 }
2727                                 idn= idn->next;
2728                         }
2729                 }
2730         }
2731         return idn;
2732 }
2733
2734 /* called from kernel/blender.c */
2735 void lib_link_screen_restore(Main *newmain, char mode, Scene *curscene)
2736 {
2737         bScreen *sc;
2738         ScrArea *sa;
2739
2740         sc= newmain->screen.first;
2741         while(sc) {
2742
2743                 if(mode=='u') sc->scene= restore_pointer_by_name(newmain, (ID *)sc->scene, 1);
2744                 if(sc->scene==NULL || mode=='n') sc->scene= curscene;
2745
2746                 sa= sc->areabase.first;
2747                 while(sa) {
2748                         SpaceLink *sl;
2749
2750                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
2751                                 if(sl->spacetype==SPACE_VIEW3D) {
2752                                         View3D *v3d= (View3D*) sl;
2753                                         
2754                                         if(mode=='u') v3d->camera= restore_pointer_by_name(newmain, (ID *)v3d->camera, 1);
2755                                         if(v3d->camera==NULL || mode=='n') v3d->camera= sc->scene->camera;
2756                                         
2757                                         if(v3d->bgpic) {
2758                                                 v3d->bgpic->ima= restore_pointer_by_name(newmain, (ID *)v3d->bgpic->ima, 1);
2759                                                 v3d->bgpic->tex= restore_pointer_by_name(newmain, (ID *)v3d->bgpic->tex, 1);
2760                                                 if(v3d->bgpic->rect) freeN(v3d->bgpic->rect);
2761                                                 v3d->bgpic->rect= NULL;
2762                                         }
2763                                         if(v3d->localvd) {
2764                                                 Base *base;
2765                                                 if(mode=='u') v3d->localvd->camera= restore_pointer_by_name(newmain, (ID *)v3d->localvd->camera, 1);
2766                                                 if(v3d->localvd->camera==NULL || mode=='n') v3d->localvd->camera= sc->scene->camera;
2767                                                 
2768                                                 /* localview can become invalid during undo/redo steps, so we exit it when no could be found */
2769                                                 for(base= sc->scene->base.first; base; base= base->next) {
2770                                                         if(base->lay & v3d->lay) break;
2771                                                 }
2772                                                 if(base==NULL) {
2773                                                         v3d->lay= v3d->localvd->lay;
2774                                                         v3d->layact= v3d->localvd->layact;
2775                                                         MEM_freeN(v3d->localvd);
2776                                                         v3d->localvd= NULL;
2777                                                         v3d->localview= 0;
2778                                                 }
2779                                         }
2780                                         else if(v3d->scenelock) v3d->lay= sc->scene->lay;
2781                                         
2782                                 }
2783                                 else if(sl->spacetype==SPACE_IPO) {
2784                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2785                                         
2786                                         if(sipo->blocktype==ID_SEQ) sipo->from= NULL;   // no libdata
2787                                         else sipo->from= restore_pointer_by_name(newmain, (ID *)sipo->from, 0);
2788                                         
2789                                         // not free sipo->ipokey, creates dependency with src/
2790                                         sipo->ipo= restore_pointer_by_name(newmain, (ID *)sipo->ipo, 0);
2791                                         if(sipo->editipo) MEM_freeN(sipo->editipo);
2792                                         sipo->editipo= NULL;
2793                                 }
2794                                 else if(sl->spacetype==SPACE_BUTS) {
2795                                         SpaceButs *sbuts= (SpaceButs *)sl;
2796                                         sbuts->lockpoin= NULL;
2797                                         sbuts->cury= 0; // we leave rect, for nicer redraws
2798                                 }
2799                                 else if(sl->spacetype==SPACE_FILE) {
2800                                         SpaceFile *sfile= (SpaceFile *)sl;
2801                                         if(sfile->libfiledata)  
2802                                                 BLO_blendhandle_close(sfile->libfiledata);
2803                                         sfile->libfiledata= 0;
2804                                 }
2805                                 else if(sl->spacetype==SPACE_IMASEL) {
2806                                         ;
2807                                 }
2808                                 else if(sl->spacetype==SPACE_ACTION) {
2809                                         SpaceAction *saction= (SpaceAction *)sl;
2810                                         saction->action = restore_pointer_by_name(newmain, (ID *)saction->action, 1);
2811                                 }
2812                                 else if(sl->spacetype==SPACE_IMAGE) {
2813                                         SpaceImage *sima= (SpaceImage *)sl;
2814
2815                                         sima->image= restore_pointer_by_name(newmain, (ID *)sima->image, 1);
2816                                 }
2817                                 else if(sl->spacetype==SPACE_NLA){
2818                                         /* SpaceNla *snla= (SpaceNla *)sl;      */
2819                                 }
2820                                 else if(sl->spacetype==SPACE_TEXT) {
2821                                         SpaceText *st= (SpaceText *)sl;
2822
2823                                         st->text= restore_pointer_by_name(newmain, (ID *)st->text, 1);
2824                                         if(st->text==NULL) st->text= newmain->text.first;
2825                                 }
2826                                 else if(sl->spacetype==SPACE_SCRIPT) {
2827                                         SpaceScript *sc= (SpaceScript *)sl;
2828
2829                                         sc->script = NULL;
2830                                 }
2831                                 else if(sl->spacetype==SPACE_OOPS) {
2832                                         SpaceOops *so= (SpaceOops *)sl;
2833                                         Oops *oops;
2834                                         
2835                                         int a;
2836                                         oops= so->oops.first;
2837                                         while(oops) {
2838                                                 oops->id= restore_pointer_by_name(newmain, (ID *)oops->id, 0);
2839                                                 oops= oops->next;
2840                                         }
2841                                         so->lockpoin= NULL;
2842                                         
2843                                         if(so->treestore) {
2844                                                 TreeStore *ts= so->treestore;
2845                                                 TreeStoreElem *tselem=ts->data;
2846                                                 for(a=0; a<ts->usedelem; a++, tselem++) {
2847                                                         tselem->id= restore_pointer_by_name(newmain, tselem->id, 0);
2848                                                 }
2849                                         }
2850                                 }
2851                                 else if(sl->spacetype==SPACE_SOUND) {
2852                                         SpaceSound *ssound= (SpaceSound *)sl;
2853
2854                                         ssound->sound= restore_pointer_by_name(newmain, (ID *)ssound->sound, 1);
2855                                 }
2856                         }
2857                         sa= sa->next;
2858                 }
2859
2860                 sc= sc->id.next;
2861         }
2862
2863 }
2864
2865 static void direct_link_screen(FileData *fd, bScreen *sc)
2866 {
2867         ScrArea *sa;
2868         ScrVert *sv;
2869         ScrEdge *se;
2870         Oops *oops;
2871
2872         link_list(fd, &(sc->vertbase));
2873         link_list(fd, &(sc->edgebase));
2874         link_list(fd, &(sc->areabase));
2875         sc->winakt= 0;
2876
2877         /* edges */
2878         se= sc->edgebase.first;
2879         while(se) {
2880                 se->v1= newdataadr(fd, se->v1);
2881                 se->v2= newdataadr(fd, se->v2);
2882                 if( (long)se->v1 > (long)se->v2) {
2883                         sv= se->v1;
2884                         se->v1= se->v2;
2885                         se->v2= sv;
2886                 }
2887
2888                 if(se->v1==NULL) {
2889                         printf("error reading screen... file corrupt\n");
2890                         se->v1= se->v2;
2891                 }
2892                 se= se->next;
2893         }
2894
2895         /* areas */
2896         sa= sc->areabase.first;
2897         while(sa) {
2898                 Panel *pa;
2899                 SpaceLink *sl;
2900
2901                 link_list(fd, &(sa->spacedata));
2902                 link_list(fd, &(sa->panels));
2903
2904                 for(pa= sa->panels.first; pa; pa=pa->next) {
2905                         pa->paneltab= newdataadr(fd, pa->paneltab);
2906                         pa->active= 0;
2907                         pa->sortcounter= 0;
2908                 }
2909
2910                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
2911                         if (sl->spacetype==SPACE_VIEW3D) {
2912                                 View3D *v3d= (View3D*) sl;
2913                                 v3d->bgpic= newdataadr(fd, v3d->bgpic);
2914                                 v3d->localvd= newdataadr(fd, v3d->localvd);
2915                         }
2916                         else if (sl->spacetype==SPACE_OOPS) {
2917                                 SpaceOops *soops= (SpaceOops*) sl;
2918                                 
2919                                 link_list(fd, &(soops->oops));
2920                                 oops= soops->oops.first;
2921                                 while(oops) {
2922                                         oops->link.first= oops->link.last= 0;
2923                                         oops= oops->next;
2924                                 }
2925                                 
2926                                 soops->treestore= newdataadr(fd, soops->treestore);
2927                                 if(soops->treestore) {
2928                                         soops->treestore->data= newdataadr(fd, soops->treestore->data);
2929                                         /* we only saved what was used */
2930                                         soops->treestore->totelem= soops->treestore->usedelem;
2931                                         soops->storeflag |= SO_TREESTORE_CLEANUP;       // at first draw
2932                                 }
2933                         }
2934                 }
2935
2936                 sa->v1= newdataadr(fd, sa->v1);
2937                 sa->v2= newdataadr(fd, sa->v2);
2938                 sa->v3= newdataadr(fd, sa->v3);
2939                 sa->v4= newdataadr(fd, sa->v4);
2940
2941                 sa->win= sa->headwin= 0;
2942
2943                 sa->uiblocks.first= sa->uiblocks.last= NULL;
2944
2945                 sa= sa->next;
2946         }
2947 }
2948
2949 /* ********** READ LIBRARY *************** */
2950
2951
2952 static void direct_link_library(FileData *fd, Library *lib)
2953 {
2954         Main *newmain;
2955
2956         /* new main */
2957         newmain= MEM_callocN(sizeof(Main), "directlink");
2958         BLI_addtail(&fd->mainlist, newmain);
2959         newmain->curlib= lib;
2960 }
2961
2962 static void lib_link_library(FileData *fd, Main *main)
2963 {
2964         Library *lib;
2965
2966         lib= main->library.first;
2967         while(lib) {
2968                 lib->id.us= 1;
2969                 lib= lib->id.next;
2970         }
2971 }
2972
2973 /* ************** READ SOUND ******************* */
2974
2975 static void direct_link_sound(FileData *fd, bSound *sound)
2976 {
2977         sound->sample = NULL;
2978         sound->snd_sound = NULL;
2979
2980         sound->packedfile = direct_link_packedfile(fd, sound->packedfile);
2981         sound->newpackedfile = direct_link_packedfile(fd, sound->newpackedfile);
2982 }
2983
2984 static void lib_link_sound(FileData *fd, Main *main)
2985 {
2986         bSound *sound;
2987
2988         sound= main->sound.first;
2989         while(sound) {
2990                 if(sound->id.flag & LIB_NEEDLINK) {
2991                         sound->id.flag -= LIB_NEEDLINK;
2992                         sound->ipo= newlibadr_us(fd, sound->id.lib, sound->ipo);
2993                         sound->stream = 0;
2994                 }
2995                 sound= sound->id.next;
2996         }
2997 }
2998 /* ***************** READ GROUP *************** */
2999
3000 static void direct_link_group(FileData *fd, Group *group)
3001 {
3002         GroupObject *go;
3003         ObjectKey *ok;
3004
3005         link_list(fd, &group->gobject);
3006         link_list(fd, &group->gkey);
3007         group->active= newdataadr(fd, group->active);
3008
3009         go= group->gobject.first;
3010         while(go) {
3011                 link_list(fd, &go->okey);
3012                 ok= go->okey.first;
3013                 while(ok) {
3014                         ok->gkey= newdataadr(fd, ok->gkey);
3015                         ok= ok->next;
3016                 }
3017                 go= go->next;
3018         }
3019 }
3020
3021 static void lib_link_group(FileData *fd, Main *main)
3022 {
3023         Group *group= main->group.first;
3024         GroupObject *go;
3025         ObjectKey *ok;
3026
3027         while(group) {
3028                 if(group->id.flag & LIB_NEEDLINK) {
3029                         group->id.flag -= LIB_NEEDLINK;
3030
3031                         go= group->gobject.first;
3032                         while(go) {
3033                                 go->ob= newlibadr(fd, group->id.lib, go->ob);
3034                                 ok= go->okey.first;
3035                                 while(ok) {
3036                                         ok->parent= newlibadr(fd, group->id.lib, ok->parent);
3037                                         ok->track= newlibadr(fd, group->id.lib, ok->track);
3038                                         ok->ipo= newlibadr_us(fd, group->id.lib, ok->ipo);
3039                                         ok= ok->next;
3040                                 }
3041                                 go= go->next;
3042                         }
3043                 }
3044                 group= group->id.next;
3045         }
3046 }
3047
3048 /* ************** GENERAL & MAIN ******************** */
3049
3050 static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID **id_r)
3051 {
3052         /* this routine reads a libblock and its direct data. Use link functions
3053          * to connect it all
3054          */
3055
3056         ID *id;
3057         ListBase *lb;
3058         char *str = NULL;
3059
3060         if(bhead->code==ID_ID) {
3061                 ID *linkedid= (ID *)(bhead + 1); /*  BHEAD+DATA dependancy */
3062
3063                 lb= wich_libbase(main, GS(linkedid->name));
3064         }
3065         else {
3066                 lb= wich_libbase(main, bhead->code);
3067         }
3068
3069         /* read libblock */
3070         id = read_struct(fd, bhead, "lib block");
3071         if (id_r)
3072                 *id_r= id;
3073         if (!id)
3074                 return blo_nextbhead(fd, bhead);
3075
3076         oldnewmap_insert(fd->libmap, bhead->old, id, 1);
3077         BLI_addtail(lb, id);
3078
3079         /* clear first 8 bits */
3080         id->flag= (id->flag & 0xFF00) | flag | LIB_NEEDLINK;
3081         id->lib= main->curlib;
3082         if(id->flag & LIB_FAKEUSER) id->us= 1;
3083         else id->us= 0;
3084
3085         /* this case cannot be direct_linked: it's just the ID part */
3086         if(bhead->code==ID_ID) {
3087                 return blo_nextbhead(fd, bhead);
3088         }
3089
3090         bhead = blo_nextbhead(fd, bhead);
3091
3092         switch( GS(id->name) ) {
3093         case ID_OB: str= "ID_OB"; break;
3094         case ID_SCE: str= "ID_SCE"; break;
3095         case ID_LI: str= "ID_LI"; break;
3096         case ID_ME: str= "ID_ME"; break;
3097         case ID_CU: str= "ID_CU"; break;
3098         case ID_MB: str= "ID_MB"; break;
3099         case ID_MA: str= "ID_MA"; break;
3100         case ID_TE: str= "ID_TE"; break;
3101         case ID_IM: str= "ID_IM"; break;
3102         case ID_IK: str= "ID_IK"; break;
3103         case ID_WV: str= "ID_WV"; break;
3104         case ID_LT: str= "ID_LT"; break;
3105         case ID_SE: str= "ID_SE"; break;
3106         case ID_LF: str= "ID_LF"; break;
3107         case ID_LA: str= "ID_LA"; break;
3108         case ID_CA: str= "ID_CA"; break;
3109         case ID_IP: str= "ID_IP"; break;
3110         case ID_KE: str= "ID_KE"; break;
3111         case ID_WO: str= "ID_WO"; break;
3112         case ID_SCR: str= "ID_SCR"; break;
3113         case ID_VF: str= "ID_VF"; break;
3114         case ID_TXT     : str= "ID_TXT"; break;
3115         case ID_SO: str= "ID_SO"; break;
3116         case ID_SAMPLE: str= "ID_SAMPLE"; break;
3117         case ID_GR: str= "ID_GR"; break;
3118         case ID_ID: str= "ID_ID"; break;
3119         case ID_SEQ: str= "ID_SEQ"; break;
3120         case ID_AR: str= "ID_AR"; break;
3121         case ID_AC: str= "ID_AC"; break;
3122         case ID_SCRIPT: str= "ID_SCRIPT"; break;
3123         }
3124                 /* read all data */
3125         while(bhead && bhead->code==DATA) {
3126                 void *data= read_struct(fd, bhead, str);
3127
3128                 if (data) {
3129                         oldnewmap_insert(fd->datamap, bhead->old, data, 0);
3130                 }
3131
3132                 bhead = blo_nextbhead(fd, bhead);
3133         }
3134
3135         /* init pointers direct data */
3136         switch( GS(id->name) ) {
3137                 case ID_SCR:
3138                         direct_link_screen(fd, (bScreen *)id);
3139                         break;
3140                 case ID_SCE:
3141                         direct_link_scene(fd, (Scene *)id);
3142                         break;
3143                 case ID_OB:
3144                         direct_link_object(fd, (Object *)id);
3145                         break;
3146                 case ID_ME:
3147                         direct_link_mesh(fd, (Mesh *)id);
3148                         break;
3149                 case ID_CU:
3150                         direct_link_curve(fd, (Curve *)id);
3151                         break;
3152                 case ID_MB:
3153                         direct_link_mball(fd, (MetaBall *)id);
3154                         break;
3155                 case ID_MA: