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