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