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