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