Three fixes;
[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         test_pointer_array(fd, (void **)&slink->scripts);
1245         
1246         slink->flag= newdataadr(fd, slink->flag);
1247
1248         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1249                 int a;
1250
1251                 for(a=0; a<slink->totscript; a++) {
1252                         SWITCH_SHORT(slink->flag[a]);
1253                 }
1254         }
1255 }
1256
1257 /* ************ READ ARMATURE ***************** */
1258
1259 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1260 {
1261         bActionStrip *strip;
1262
1263         for (strip=striplist->first; strip; strip=strip->next){
1264                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1265                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1266         }
1267 }
1268
1269 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1270 {
1271         bConstraintChannel *chan;
1272
1273         for (chan=chanbase->first; chan; chan=chan->next){
1274                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1275         }
1276 }
1277
1278 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
1279 {
1280         bConstraint *con;
1281
1282         for (con = conlist->first; con; con=con->next) {
1283                 /* patch for error introduced by changing constraints (dunno how) */
1284                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
1285                 if(con->data==NULL) {
1286                         con->type= CONSTRAINT_TYPE_NULL;
1287                 }
1288
1289                 switch (con->type) {
1290                 case CONSTRAINT_TYPE_ACTION:
1291                         {
1292                                 bActionConstraint *data;
1293                                 data= ((bActionConstraint*)con->data);
1294                                 data->tar = newlibadr(fd, id->lib, data->tar);
1295                                 data->act = newlibadr(fd, id->lib, data->act);
1296                         }
1297                         break;
1298                 case CONSTRAINT_TYPE_LOCLIKE:
1299                         {
1300                                 bLocateLikeConstraint *data;
1301                                 data= ((bLocateLikeConstraint*)con->data);
1302                                 data->tar = newlibadr(fd, id->lib, data->tar);
1303                         };
1304                         break;
1305                 case CONSTRAINT_TYPE_ROTLIKE:
1306                         {
1307                                 bRotateLikeConstraint *data;
1308                                 data= ((bRotateLikeConstraint*)con->data);
1309                                 data->tar = newlibadr(fd, id->lib, data->tar);
1310                         };
1311                         break;
1312                 case CONSTRAINT_TYPE_KINEMATIC:
1313                         {
1314                                 bKinematicConstraint *data;
1315                                 data = ((bKinematicConstraint*)con->data);
1316                                 data->tar = newlibadr(fd, id->lib, data->tar);
1317                         }
1318                         break;
1319                 case CONSTRAINT_TYPE_TRACKTO:
1320                         {
1321                                 bTrackToConstraint *data;
1322                                 data = ((bTrackToConstraint*)con->data);
1323                                 data->tar = newlibadr(fd, id->lib, data->tar);
1324                         }
1325                         break;
1326                 case CONSTRAINT_TYPE_MINMAX:
1327                         {
1328                                 bMinMaxConstraint *data;
1329                                 data = ((bMinMaxConstraint*)con->data);
1330                                 data->tar = newlibadr(fd, id->lib, data->tar);
1331                         }
1332                         break;
1333                 case CONSTRAINT_TYPE_LOCKTRACK:
1334                         {
1335                                 bLockTrackConstraint *data;
1336                                 data= ((bLockTrackConstraint*)con->data);
1337                                 data->tar = newlibadr(fd, id->lib, data->tar);
1338                         };
1339                         break;
1340                 case CONSTRAINT_TYPE_FOLLOWPATH:
1341                         {
1342                                 bFollowPathConstraint *data;
1343                                 data= ((bFollowPathConstraint*)con->data);
1344                                 data->tar = newlibadr(fd, id->lib, data->tar);
1345                         };
1346                         break;
1347                 case CONSTRAINT_TYPE_DISTANCELIMIT:
1348                         {
1349                                 bDistanceLimitConstraint *data;
1350                                 data= ((bDistanceLimitConstraint*)con->data);
1351                                 data->tar = newlibadr(fd, id->lib, data->tar);
1352                         };
1353                         break;
1354                 case CONSTRAINT_TYPE_STRETCHTO:
1355                         {
1356                                 bStretchToConstraint *data;
1357                                 data= ((bStretchToConstraint*)con->data);
1358                                 data->tar = newlibadr(fd, id->lib, data->tar);
1359                         };
1360                         break;
1361
1362                 case CONSTRAINT_TYPE_NULL:
1363                         break;
1364                 }
1365         }
1366 }
1367
1368 static void direct_link_constraints(FileData *fd, ListBase *lb)
1369 {
1370         bConstraint *cons;
1371
1372         link_list(fd, lb);
1373         for (cons=lb->first; cons; cons=cons->next) {
1374                 cons->data = newdataadr(fd, cons->data);
1375         }
1376 }
1377
1378 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
1379 {
1380         bPoseChannel *pchan;
1381         bArmature *arm= ob->data;
1382         int rebuild= 0;
1383         if (!pose)
1384                 return;
1385
1386         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
1387                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
1388                 // hurms... loop in a loop, but yah... later... (ton)
1389                 pchan->bone= get_named_bone(arm, pchan->name);
1390                 if(pchan->bone==NULL)
1391                         rebuild= 1;
1392         }
1393         if(rebuild) {
1394                 ob->recalc= OB_RECALC;
1395                 pose->flag |= POSE_RECALC;
1396         }
1397 }
1398
1399 static void lib_link_armature(FileData *fd, Main *main)
1400 {
1401         bArmature *arm;
1402
1403         arm= main->armature.first;
1404
1405         while(arm) {
1406                 if(arm->id.flag & LIB_NEEDLINK) {
1407                         arm->id.flag -= LIB_NEEDLINK;
1408                 }
1409                 arm= arm->id.next;
1410         }
1411 }
1412
1413 static void lib_link_action(FileData *fd, Main *main)
1414 {
1415         bAction *act;
1416         bActionChannel *chan;
1417
1418         act= main->action.first;
1419         while(act) {
1420                 if(act->id.flag & LIB_NEEDLINK) {
1421                         act->id.flag -= LIB_NEEDLINK;
1422
1423                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1424                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1425                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1426                         }
1427
1428                 }
1429                 act= act->id.next;
1430         }
1431 }
1432
1433 static void direct_link_bones(FileData *fd, Bone* bone)
1434 {
1435         Bone    *child;
1436
1437         bone->parent= newdataadr(fd, bone->parent);
1438
1439         link_list(fd, &bone->childbase);
1440
1441         for (child=bone->childbase.first; child; child=child->next) {
1442                 direct_link_bones(fd, child);
1443         }
1444 }
1445
1446
1447 static void direct_link_action(FileData *fd, bAction *act)
1448 {
1449         bActionChannel *achan;
1450
1451         link_list(fd, &act->chanbase);
1452
1453         for (achan = act->chanbase.first; achan; achan=achan->next)
1454                 link_list(fd, &achan->constraintChannels);
1455
1456 }
1457
1458 static void direct_link_armature(FileData *fd, bArmature *arm)
1459 {
1460         Bone    *bone;
1461
1462         link_list(fd, &arm->bonebase);
1463
1464         bone=arm->bonebase.first;
1465         while (bone) {
1466                 direct_link_bones(fd, bone);
1467                 bone=bone->next;
1468         }
1469 }
1470
1471 /* ************ READ CAMERA ***************** */
1472
1473 static void lib_link_camera(FileData *fd, Main *main)
1474 {
1475         Camera *ca;
1476
1477         ca= main->camera.first;
1478         while(ca) {
1479                 if(ca->id.flag & LIB_NEEDLINK) {
1480
1481                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1482
1483                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1484
1485                         ca->id.flag -= LIB_NEEDLINK;
1486                 }
1487                 ca= ca->id.next;
1488         }
1489 }
1490
1491 static void direct_link_camera(FileData *fd, Camera *ca)
1492 {
1493         direct_link_scriptlink(fd, &ca->scriptlink);
1494 }
1495
1496
1497 /* ************ READ LATTICE ***************** */
1498
1499 static void lib_link_latt(FileData *fd, Main *main)
1500 {
1501         Lattice *lt;
1502
1503         lt= main->latt.first;
1504         while(lt) {
1505                 if(lt->id.flag & LIB_NEEDLINK) {
1506
1507                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
1508                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
1509
1510                         lt->id.flag -= LIB_NEEDLINK;
1511                 }
1512                 lt= lt->id.next;
1513         }
1514 }
1515
1516 static void direct_link_latt(FileData *fd, Lattice *lt)
1517 {
1518         lt->def= newdataadr(fd, lt->def);
1519 }
1520
1521 /* ************ READ LAMP ***************** */
1522
1523 static void lib_link_lamp(FileData *fd, Main *main)
1524 {
1525         Lamp *la;
1526         MTex *mtex;
1527         int a;
1528
1529         la= main->lamp.first;
1530         while(la) {
1531                 if(la->id.flag & LIB_NEEDLINK) {
1532
1533                         for(a=0; a<MAX_MTEX; a++) {
1534                                 mtex= la->mtex[a];
1535                                 if(mtex) {
1536                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1537                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1538                                 }
1539                         }
1540
1541                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1542
1543                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1544
1545                         la->id.flag -= LIB_NEEDLINK;
1546                 }
1547                 la= la->id.next;
1548         }
1549 }
1550
1551 static void direct_link_lamp(FileData *fd, Lamp *la)
1552 {
1553         int a;
1554
1555         direct_link_scriptlink(fd, &la->scriptlink);
1556
1557         for(a=0; a<MAX_MTEX; a++) {
1558                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1559         }
1560 }
1561
1562 /* ************ READ keys ***************** */
1563
1564 static void lib_link_key(FileData *fd, Main *main)
1565 {
1566         Key *key;
1567
1568         key= main->key.first;
1569         while(key) {
1570                 if(key->id.flag & LIB_NEEDLINK) {
1571
1572                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1573                         key->from= newlibadr(fd, key->id.lib, key->from);
1574
1575                         key->id.flag -= LIB_NEEDLINK;
1576                 }
1577                 key= key->id.next;
1578         }
1579 }
1580
1581 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1582 {
1583         int elemsize, a, b;
1584         char *data, *poin, *cp;
1585
1586         elemsize= key->elemsize;
1587         data= kb->data;
1588
1589         for(a=0; a<kb->totelem; a++) {
1590
1591                 cp= key->elemstr;
1592                 poin= data;
1593
1594                 while( cp[0] ) {        /* cp[0]==amount */
1595
1596                         switch(cp[1]) {         /* cp[1]= type */
1597                         case IPO_FLOAT:
1598                         case IPO_BPOINT:
1599                         case IPO_BEZTRIPLE:
1600                                 b= cp[0];
1601                                 while(b--) {
1602                                         SWITCH_INT((*poin));
1603                                         poin+= 4;
1604                                 }
1605                                 break;
1606                         }
1607
1608                         cp+= 2;
1609
1610                 }
1611                 data+= elemsize;
1612         }
1613 }
1614
1615 static void direct_link_key(FileData *fd, Key *key)
1616 {
1617         KeyBlock *kb;
1618
1619         link_list(fd, &(key->block));
1620
1621         key->refkey= newdataadr(fd, key->refkey);
1622
1623         kb= key->block.first;
1624         while(kb) {
1625
1626                 kb->data= newdataadr(fd, kb->data);
1627
1628                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
1629                         switch_endian_keyblock(key, kb);
1630
1631                 kb= kb->next;
1632         }
1633 }
1634
1635 /* ************ READ mball ***************** */
1636
1637 static void lib_link_mball(FileData *fd, Main *main)
1638 {
1639         MetaBall *mb;
1640         int a;
1641
1642         mb= main->mball.first;
1643         while(mb) {
1644                 if(mb->id.flag & LIB_NEEDLINK) {
1645
1646                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
1647
1648                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
1649
1650                         mb->id.flag -= LIB_NEEDLINK;
1651                 }
1652                 mb= mb->id.next;
1653         }
1654 }
1655
1656 static void direct_link_mball(FileData *fd, MetaBall *mb)
1657 {
1658         mb->mat= newdataadr(fd, mb->mat);
1659         test_pointer_array(fd, (void **)&mb->mat);
1660
1661         link_list(fd, &(mb->elems));
1662
1663         mb->disp.first= mb->disp.last= 0;
1664
1665         mb->bb= 0;
1666 }
1667
1668 /* ************ READ WORLD ***************** */
1669
1670 static void lib_link_world(FileData *fd, Main *main)
1671 {
1672         World *wrld;
1673         MTex *mtex;
1674         int a;
1675
1676         wrld= main->world.first;
1677         while(wrld) {
1678                 if(wrld->id.flag & LIB_NEEDLINK) {
1679
1680                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
1681
1682                         for(a=0; a<MAX_MTEX; a++) {
1683                                 mtex= wrld->mtex[a];
1684                                 if(mtex) {
1685                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
1686                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
1687                                 }
1688                         }
1689
1690                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
1691
1692                         wrld->id.flag -= LIB_NEEDLINK;
1693                 }
1694                 wrld= wrld->id.next;
1695         }
1696 }
1697
1698 static void direct_link_world(FileData *fd, World *wrld)
1699 {
1700         int a;
1701
1702         direct_link_scriptlink(fd, &wrld->scriptlink);
1703
1704         for(a=0; a<MAX_MTEX; a++) {
1705                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
1706         }
1707 }
1708
1709
1710 /* ************ READ IPO ***************** */
1711
1712 static void lib_link_ipo(FileData *fd, Main *main)
1713 {
1714         Ipo *ipo;
1715
1716         ipo= main->ipo.first;
1717         while(ipo) {
1718                 if(ipo->id.flag & LIB_NEEDLINK) {
1719                         IpoCurve *icu;
1720                         for(icu= ipo->curve.first; icu; icu= icu->next) {
1721                                 if(icu->driver)
1722                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
1723                         }
1724                         ipo->id.flag -= LIB_NEEDLINK;
1725                 }
1726                 ipo= ipo->id.next;
1727         }
1728 }
1729
1730 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1731 {
1732         IpoCurve *icu;
1733
1734         link_list(fd, &(ipo->curve));
1735         icu= ipo->curve.first;
1736         while(icu) {
1737                 icu->bezt= newdataadr(fd, icu->bezt);
1738                 icu->bp= newdataadr(fd, icu->bp);
1739                 icu->driver= newdataadr(fd, icu->driver);
1740                 icu= icu->next;
1741         }
1742 }
1743
1744 /* ************ READ VFONT ***************** */
1745
1746 static void lib_link_vfont(FileData *fd, Main *main)
1747 {
1748         VFont *vf;
1749
1750         vf= main->vfont.first;
1751         while(vf) {
1752                 if(vf->id.flag & LIB_NEEDLINK) {
1753                         vf->id.flag -= LIB_NEEDLINK;
1754                 }
1755                 vf= vf->id.next;
1756         }
1757 }
1758
1759 static void direct_link_vfont(FileData *fd, VFont *vf)
1760 {
1761         vf->data= NULL;
1762         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
1763 }
1764
1765 /* ************ READ TEXT ****************** */
1766
1767 static void lib_link_text(FileData *fd, Main *main)
1768 {
1769         Text *text;
1770
1771         text= main->text.first;
1772         while(text) {
1773                 if(text->id.flag & LIB_NEEDLINK) {
1774                         text->id.flag -= LIB_NEEDLINK;
1775                 }
1776                 text= text->id.next;
1777         }
1778 }
1779
1780 static void direct_link_text(FileData *fd, Text *text)
1781 {
1782         TextLine *ln;
1783
1784         text->name= newdataadr(fd, text->name);
1785
1786         text->undo_pos= -1;
1787         text->undo_len= TXT_INIT_UNDO;
1788         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
1789
1790         text->compiled= NULL;
1791
1792 /*
1793         if(text->flags & TXT_ISEXT) {
1794                 reopen_text(text);
1795         } else {
1796 */
1797
1798         link_list(fd, &text->lines);
1799
1800         text->curl= newdataadr(fd, text->curl);
1801         text->sell= newdataadr(fd, text->sell);
1802
1803         ln= text->lines.first;
1804         while(ln) {
1805                 ln->line= newdataadr(fd, ln->line);
1806                 ln->format= NULL;
1807                 
1808                 if (ln->len != (int) strlen(ln->line)) {
1809                         printf("Error loading text, line lengths differ\n");
1810                         ln->len = strlen(ln->line);
1811                 }
1812
1813                 ln= ln->next;
1814         }
1815
1816         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
1817
1818         text->id.us= 1;
1819 }
1820
1821 /* ************ READ IMAGE ***************** */
1822
1823 static void lib_link_image(FileData *fd, Main *main)
1824 {
1825         Image *ima;
1826
1827         ima= main->image.first;
1828         while (ima) {
1829                 if(ima->id.flag & LIB_NEEDLINK) {
1830
1831                         ima->id.flag -= LIB_NEEDLINK;
1832                 }
1833                 ima= ima->id.next;
1834         }
1835 }
1836
1837 static void direct_link_image(FileData *fd, Image *ima)
1838 {
1839         ima->ibuf= 0;
1840         ima->anim= 0;
1841         memset(ima->mipmap, 0, sizeof(ima->mipmap));
1842         ima->repbind= 0;
1843         ima->bindcode= 0;
1844
1845         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
1846
1847         ima->ok= 1;
1848 }
1849
1850
1851 /* ************ READ CURVE ***************** */
1852
1853 static void lib_link_curve(FileData *fd, Main *main)
1854 {
1855         Curve *cu;
1856         int a;
1857
1858         cu= main->curve.first;
1859         while(cu) {
1860                 if(cu->id.flag & LIB_NEEDLINK) {
1861
1862                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
1863
1864                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
1865                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
1866                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
1867                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
1868                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
1869                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
1870                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
1871
1872                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
1873                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
1874
1875                         cu->id.flag -= LIB_NEEDLINK;
1876                 }
1877                 cu= cu->id.next;
1878         }
1879 }
1880
1881
1882 static void switch_endian_knots(Nurb *nu)
1883 {
1884         int len;
1885
1886         if(nu->knotsu) {
1887                 len= KNOTSU(nu);
1888                 while(len--) {
1889                         SWITCH_INT(nu->knotsu[len]);
1890                 }
1891         }
1892         if(nu->knotsv) {
1893                 len= KNOTSV(nu);
1894                 while(len--) {
1895                         SWITCH_INT(nu->knotsv[len]);
1896                 }
1897         }
1898 }
1899
1900 static void direct_link_curve(FileData *fd, Curve *cu)
1901 {
1902         Nurb *nu;
1903         TextBox *tb;
1904
1905         cu->mat= newdataadr(fd, cu->mat);
1906         test_pointer_array(fd, (void **)&cu->mat);
1907         cu->str= newdataadr(fd, cu->str);
1908         cu->strinfo= newdataadr(fd, cu->strinfo);       
1909         cu->tb= newdataadr(fd, cu->tb);
1910
1911         if(cu->vfont==0) link_list(fd, &(cu->nurb));
1912         else {
1913                 cu->nurb.first=cu->nurb.last= 0;
1914
1915                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
1916                 if (cu->tb) {
1917                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
1918                         MEM_freeN(cu->tb);
1919                         cu->tb= tb;                     
1920                 } else {
1921                         cu->totbox = 1;
1922                         cu->actbox = 1;
1923                         cu->tb = tb;
1924                         cu->tb[0].w = cu->linewidth;
1925                 }               
1926                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
1927         }
1928
1929         cu->bev.first=cu->bev.last= 0;
1930         cu->disp.first=cu->disp.last= 0;
1931         cu->path= 0;
1932
1933         nu= cu->nurb.first;
1934         while(nu) {
1935                 nu->bezt= newdataadr(fd, nu->bezt);
1936                 nu->bp= newdataadr(fd, nu->bp);
1937                 nu->knotsu= newdataadr(fd, nu->knotsu);
1938                 nu->knotsv= newdataadr(fd, nu->knotsv);
1939                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
1940
1941                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1942                         switch_endian_knots(nu);
1943                 }
1944
1945                 nu= nu->next;
1946         }
1947         cu->bb= NULL;
1948 }
1949
1950 /* ************ READ TEX ***************** */
1951
1952 static void lib_link_texture(FileData *fd, Main *main)
1953 {
1954         Tex *tex;
1955
1956         tex= main->tex.first;
1957         while(tex) {
1958                 if(tex->id.flag & LIB_NEEDLINK) {
1959
1960                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
1961                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
1962                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
1963
1964                         tex->id.flag -= LIB_NEEDLINK;
1965                 }
1966                 tex= tex->id.next;
1967         }
1968 }
1969
1970 static void direct_link_texture(FileData *fd, Tex *tex)
1971 {
1972         tex->plugin= newdataadr(fd, tex->plugin);
1973         if(tex->plugin) {
1974                 tex->plugin->handle= 0;
1975                 open_plugin_tex(tex->plugin);
1976         }
1977         tex->coba= newdataadr(fd, tex->coba);
1978         tex->env= newdataadr(fd, tex->env);
1979         if(tex->env) {
1980                 tex->env->ima= 0;
1981                 memset(tex->env->cube, 0, 6*sizeof(void *));
1982                 tex->env->ok= 0;
1983         }
1984 }
1985
1986
1987
1988 /* ************ READ MATERIAL ***************** */
1989
1990 static void lib_link_material(FileData *fd, Main *main)
1991 {
1992         Material *ma;
1993         MTex *mtex;
1994         int a;
1995
1996         ma= main->mat.first;
1997         while(ma) {
1998                 if(ma->id.flag & LIB_NEEDLINK) {
1999
2000                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2001
2002                         for(a=0; a<MAX_MTEX; a++) {
2003                                 mtex= ma->mtex[a];
2004                                 if(mtex) {
2005                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2006                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2007                                 }
2008                         }
2009                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2010                         ma->id.flag -= LIB_NEEDLINK;
2011                 }
2012                 ma= ma->id.next;
2013         }
2014 }
2015
2016 static void direct_link_material(FileData *fd, Material *ma)
2017 {
2018         int a;
2019
2020         direct_link_scriptlink(fd, &ma->scriptlink);
2021
2022         for(a=0; a<MAX_MTEX; a++) {
2023                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2024         }
2025
2026         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2027         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2028         
2029 }
2030
2031 /* ************ READ MESH ***************** */
2032
2033 static void lib_link_mesh(FileData *fd, Main *main)
2034 {
2035         Mesh *me;
2036
2037         me= main->mesh.first;
2038         while(me) {
2039                 if(me->id.flag & LIB_NEEDLINK) {
2040                         int i;
2041
2042                         /* this check added for python created meshes */
2043                         if(me->mat) {
2044                                 for(i=0; i<me->totcol; i++)
2045                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2046                         }
2047                         else me->totcol= 0;
2048
2049                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2050                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2051                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2052
2053                         if(me->tface) {
2054                                 TFace *tfaces= me->tface;
2055
2056                                 for (i=0; i<me->totface; i++) {
2057                                         TFace *tf= &tfaces[i];
2058
2059                                         tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2060                                         if(tf->tpage) {
2061                                                 Image *ima= tf->tpage;
2062                                                 if(ima->id.us==0)
2063                                                         ima->id.us= 1;
2064                                         }
2065                                 }
2066                         }
2067                         me->id.flag -= LIB_NEEDLINK;
2068                 }
2069                 me= me->id.next;
2070         }
2071 }
2072
2073 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2074 {
2075         int     i;
2076
2077         if (!mdverts)
2078                 return;
2079
2080         for (i=0; i<count; i++) {
2081                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2082                 if (!mdverts[i].dw)
2083                         mdverts[i].totweight=0;
2084         }
2085 }
2086
2087 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2088 {
2089         mesh->mat= newdataadr(fd, mesh->mat);
2090         test_pointer_array(fd, (void **)&mesh->mat);
2091
2092         mesh->mvert= newdataadr(fd, mesh->mvert);
2093         mesh->medge= newdataadr(fd, mesh->medge);
2094         mesh->mface= newdataadr(fd, mesh->mface);
2095         mesh->tface= newdataadr(fd, mesh->tface);
2096         mesh->mcol= newdataadr(fd, mesh->mcol);
2097         mesh->msticky= newdataadr(fd, mesh->msticky);
2098
2099         mesh->dvert= newdataadr(fd, mesh->dvert);
2100         direct_link_dverts(fd, mesh->totvert, mesh->dvert);
2101
2102         mesh->bb= NULL;
2103         mesh->oc= 0;
2104         mesh->dface= NULL;
2105         
2106         if (mesh->tface) {
2107                 TFace *tfaces= mesh->tface;
2108                 int i;
2109
2110                 for (i=0; i<mesh->totface; i++) {
2111                         TFace *tf= &tfaces[i];
2112
2113                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2114                                 SWITCH_INT(tf->col[0]);
2115                                 SWITCH_INT(tf->col[1]);
2116                                 SWITCH_INT(tf->col[2]);
2117                                 SWITCH_INT(tf->col[3]);
2118                         }
2119                 }
2120         }
2121 }
2122
2123 /* ************ READ OBJECT ***************** */
2124
2125 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob, Object **obpoin)
2126 {
2127         FileData *fd = userData;
2128
2129         *obpoin = newlibadr(fd, ob->id.lib, *obpoin);
2130 }
2131 static void lib_link_modifiers(FileData *fd, Object *ob)
2132 {
2133         modifiers_foreachObjectLink(ob, lib_link_modifiers__linkModifiers, fd);
2134 }
2135
2136 static void lib_link_object(FileData *fd, Main *main)
2137 {
2138         Object *ob;
2139         bSensor *sens;
2140         bController *cont;
2141         bActuator *act;
2142         void *poin;
2143         int warn=0, a;
2144
2145         ob= main->object.first;
2146         while(ob) {
2147                 if(ob->id.flag & LIB_NEEDLINK) {
2148
2149                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2150                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2151                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2152                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2153
2154                         poin= ob->data;
2155                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2156
2157                         if(ob->data==NULL && poin!=NULL) {
2158                                 ob->type= OB_EMPTY;
2159                                 warn= 1;
2160                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2161                                 else printf("Object %s lost data. Lib:%x\n", ob->id.name+2, (unsigned int) ob->id.lib);
2162                         }
2163                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2164
2165                         ob->id.flag -= LIB_NEEDLINK;
2166                         /* if id.us==0 a new base will be created later on */
2167
2168                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2169                         lib_link_pose(fd, ob, ob->pose);
2170                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2171                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2172                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2173
2174
2175                         sens= ob->sensors.first;
2176                         while(sens) {
2177                                 if(ob->id.lib==NULL) {  // done in expand_main
2178                                         for(a=0; a<sens->totlinks; a++) {
2179                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2180                                         }
2181                                 }
2182                                 if(sens->type==SENS_TOUCH) {
2183                                         bTouchSensor *ts= sens->data;
2184                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2185                                 }
2186                                 else if(sens->type==SENS_MESSAGE) {
2187                                         bMessageSensor *ms= sens->data;
2188                                         ms->fromObject=
2189                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2190                                 }
2191                                 sens= sens->next;
2192                         }
2193
2194                         cont= ob->controllers.first;
2195                         while(cont) {
2196                                 if(ob->id.lib==NULL) {  // done in expand_main
2197                                         for(a=0; a<cont->totlinks; a++) {
2198                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2199                                         }
2200                                 }
2201                                 if(cont->type==CONT_PYTHON) {
2202                                         bPythonCont *pc= cont->data;
2203                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2204                                 }
2205                                 cont->slinks= NULL;
2206                                 cont->totslinks= 0;
2207
2208                                 cont= cont->next;
2209                         }
2210
2211                         act= ob->actuators.first;
2212                         while(act) {
2213                                 if(act->type==ACT_SOUND) {
2214                                         bSoundActuator *sa= act->data;
2215                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2216                                 }
2217                                 else if(act->type==ACT_CD) {
2218                                         /* bCDActuator *cda= act->data; */
2219                                 }
2220                                 else if(act->type==ACT_GAME) {
2221                                         /* bGameActuator *ga= act->data; */
2222                                 }
2223                                 else if(act->type==ACT_CAMERA) {
2224                                         bCameraActuator *ca= act->data;
2225                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2226                                 }
2227                                         /* leave this one, it's obsolete but necessary to read for conversion */
2228                                 else if(act->type==ACT_ADD_OBJECT) {
2229                                         bAddObjectActuator *eoa= act->data;
2230                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2231                                 }
2232                                 else if(act->type==ACT_EDIT_OBJECT) {
2233                                         bEditObjectActuator *eoa= act->data;
2234                                         if(eoa==NULL) {
2235                                                 init_actuator(act);
2236                                         }
2237                                         eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2238                                         eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2239                                 }
2240                                 else if(act->type==ACT_SCENE) {
2241                                         bSceneActuator *sa= act->data;
2242                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2243                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2244                                 }
2245                                 else if(act->type==ACT_ACTION) {
2246                                         bActionActuator *aa= act->data;
2247                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2248                                 }
2249                                 else if(act->type==ACT_PROPERTY) {
2250                                         bPropertyActuator *pa= act->data;
2251                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2252                                 }
2253                                 else if(act->type==ACT_MESSAGE) {
2254                                         bMessageActuator *ma= act->data;
2255                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2256                                 }
2257                                 act= act->next;
2258                         }
2259
2260                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2261                         lib_link_modifiers(fd, ob);
2262                 }
2263                 ob= ob->id.next;
2264         }
2265
2266         if(warn) error("WARNING IN CONSOLE");
2267 }
2268
2269
2270 static void direct_link_pose(FileData *fd, bPose *pose) {
2271
2272         bPoseChannel *pchan;
2273
2274         if (!pose)
2275                 return;
2276
2277         link_list(fd, &pose->chanbase);
2278
2279         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2280                 pchan->bone= NULL;
2281                 pchan->parent= newdataadr(fd, pchan->parent);
2282                 pchan->child= newdataadr(fd, pchan->child);
2283                 direct_link_constraints(fd, &pchan->constraints);
2284                 pchan->iktree.first= pchan->iktree.last= NULL;
2285                 pchan->path= NULL;
2286         }
2287
2288 }
2289
2290 static void direct_link_modifiers(FileData *fd, ListBase *lb)
2291 {
2292         ModifierData *md;
2293
2294         link_list(fd, lb);
2295
2296         for (md=lb->first; md; md=md->next) {
2297                 md->error = NULL;
2298
2299                 if (md->type==eModifierType_Subsurf) {
2300                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
2301
2302                         smd->emCache = smd->mCache = 0;
2303                 } else if (md->type==eModifierType_Hook) {
2304                         HookModifierData *hmd = (HookModifierData*) md;
2305
2306                         hmd->indexar= newdataadr(fd, hmd->indexar);
2307                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2308                                 int a;
2309                                 for(a=0; a<hmd->totindex; a++) {
2310                                         SWITCH_INT(hmd->indexar[a]);
2311                                 }
2312                         }
2313                 }
2314         }
2315 }
2316
2317 static void direct_link_object(FileData *fd, Object *ob)
2318 {
2319         PartEff *paf;
2320         bProperty *prop;
2321         bSensor *sens;
2322         bController *cont;
2323         bActuator *act;
2324         int a;
2325         
2326         ob->disp.first=ob->disp.last= NULL;
2327
2328         ob->pose= newdataadr(fd, ob->pose);
2329         direct_link_pose(fd, ob->pose);
2330
2331         link_list(fd, &ob->defbase);
2332         link_list(fd, &ob->nlastrips);
2333         link_list(fd, &ob->constraintChannels);
2334
2335         direct_link_scriptlink(fd, &ob->scriptlink);
2336
2337         ob->mat= newdataadr(fd, ob->mat);
2338         test_pointer_array(fd, (void **)&ob->mat);
2339         
2340         /* do it here, below old data gets converted */
2341         direct_link_modifiers(fd, &ob->modifiers);
2342         
2343         link_list(fd, &ob->effect);
2344         paf= ob->effect.first;
2345         while(paf) {
2346                 if(paf->type==EFF_PARTICLE) {
2347                         paf->keys= 0;
2348                 }
2349                 if(paf->type==EFF_WAVE) {
2350                         WaveEff *wav = (WaveEff*) paf;
2351                         PartEff *next = paf->next;
2352                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
2353
2354                         wmd->damp = wav->damp;
2355                         wmd->flag = wav->flag;
2356                         wmd->height = wav->height;
2357                         wmd->lifetime = wav->lifetime;
2358                         wmd->narrow = wav->narrow;
2359                         wmd->speed = wav->speed;
2360                         wmd->startx = wav->startx;
2361                         wmd->starty = wav->startx;
2362                         wmd->timeoffs = wav->timeoffs;
2363                         wmd->width = wav->width;
2364
2365                         BLI_addtail(&ob->modifiers, wmd);
2366
2367                         BLI_remlink(&ob->effect, paf);
2368                         MEM_freeN(paf);
2369
2370                         paf = next;
2371                         continue;
2372                 }
2373                 if(paf->type==EFF_BUILD) {
2374                         BuildEff *baf = (BuildEff*) paf;
2375                         PartEff *next = paf->next;
2376                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
2377
2378                         bmd->start = baf->sfra;
2379                         bmd->length = baf->len;
2380                         bmd->randomize = 0;
2381                         bmd->seed = 1;
2382
2383                         BLI_addtail(&ob->modifiers, bmd);
2384
2385                         BLI_remlink(&ob->effect, paf);
2386                         MEM_freeN(paf);
2387
2388                         paf = next;
2389                         continue;
2390                 }
2391                 paf= paf->next;
2392         }
2393
2394         ob->pd= newdataadr(fd, ob->pd);
2395         ob->soft= newdataadr(fd, ob->soft);
2396         if(ob->soft) {
2397                 SoftBody *sb= ob->soft;         
2398                 
2399                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2400                 sb->bspring= NULL;
2401                 
2402                 sb->keys= newdataadr(fd, sb->keys);
2403                 test_pointer_array(fd, (void **)&sb->keys);
2404                 if(sb->keys) {
2405                         for(a=0; a<sb->totkey; a++) {
2406                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
2407                         }
2408                 }
2409         }
2410         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
2411         if(ob->fluidsimSettings) {
2412                 // reinit mesh pointers
2413                 ob->fluidsimSettings->orgMesh = NULL; //ob->data;
2414                 ob->fluidsimSettings->meshSurface = NULL;
2415                 ob->fluidsimSettings->meshBB = NULL;
2416         }
2417         
2418         link_list(fd, &ob->prop);
2419         prop= ob->prop.first;
2420         while(prop) {
2421                 prop->poin= newdataadr(fd, prop->poin);
2422                 if(prop->poin==0) prop->poin= &prop->data;
2423                 prop= prop->next;
2424         }
2425
2426         link_list(fd, &ob->sensors);
2427         sens= ob->sensors.first;
2428         while(sens) {
2429                 sens->data= newdataadr(fd, sens->data);
2430                 sens->links= newdataadr(fd, sens->links);
2431                 test_pointer_array(fd, (void **)&sens->links);
2432                 sens= sens->next;
2433         }
2434
2435         direct_link_constraints(fd, &ob->constraints);
2436
2437         link_glob_list(fd, &ob->controllers);
2438         cont= ob->controllers.first;
2439         while(cont) {
2440                 cont->data= newdataadr(fd, cont->data);
2441                 cont->links= newdataadr(fd, cont->links);
2442                 test_pointer_array(fd, (void **)&cont->links);
2443                 cont= cont->next;
2444         }
2445
2446         link_glob_list(fd, &ob->actuators);
2447         act= ob->actuators.first;
2448         while(act) {
2449                 act->data= newdataadr(fd, act->data);
2450                 act= act->next;
2451         }
2452
2453         link_list(fd, &ob->hooks);
2454         while (ob->hooks.first) {
2455                 ObHook *hook = ob->hooks.first;
2456                 HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
2457
2458                 hook->indexar= newdataadr(fd, hook->indexar);
2459                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2460                         int a;
2461                         for(a=0; a<hook->totindex; a++) {
2462                                 SWITCH_INT(hook->indexar[a]);
2463                         }
2464                 }
2465
2466                         /* Do conversion here because if we have loaded
2467                          * a hook we need to make sure it gets converted
2468                          * and free'd, regardless of version.
2469                          */
2470                 VECCOPY(hmd->cent, hook->cent);
2471                 hmd->falloff = hook->falloff;
2472                 hmd->force = hook->force;
2473                 hmd->indexar = hook->indexar;
2474                 hmd->object = hook->parent;
2475                 memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
2476                 hmd->totindex = hook->totindex;
2477
2478                 BLI_addhead(&ob->modifiers, hmd);
2479                 BLI_remlink(&ob->hooks, hook);
2480
2481                 MEM_freeN(hook);
2482         }
2483         
2484         ob->bb= NULL;
2485         ob->derivedDeform= NULL;
2486         ob->derivedFinal= NULL;
2487 }
2488
2489 /* ************ READ SCENE ***************** */
2490
2491 static void lib_link_scene(FileData *fd, Main *main)
2492 {
2493         Scene *sce;
2494         Base *base, *next;
2495         Editing *ed;
2496         Sequence *seq;
2497
2498         sce= main->scene.first;
2499         while(sce) {
2500                 if(sce->id.flag & LIB_NEEDLINK) {
2501                         sce->id.us= 1;
2502                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
2503                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
2504                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
2505                         sce->ima= newlibadr_us(fd, sce->id.lib, sce->ima);
2506                         sce->group= newlibadr_us(fd, sce->id.lib, sce->group);
2507
2508                         base= sce->base.first;
2509                         while(base) {
2510                                 next= base->next;
2511
2512                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
2513                                 base->object= newlibadr_us_type(fd, ID_OB, base->object);
2514                                 
2515                                 /* when save during radiotool, needs cleared */
2516                                 base->flag &= ~OB_RADIO;
2517                                 
2518                                 if(base->object==0) {
2519                                         printf("LIB ERROR: base removed\n");
2520                                         BLI_remlink(&sce->base, base);
2521                                         if(base==sce->basact) sce->basact= 0;
2522                                         MEM_freeN(base);
2523                                 }
2524                                 base= next;
2525                         }
2526
2527                         ed= sce->ed;
2528                         if(ed) {
2529                                 WHILE_SEQ(&ed->seqbase) {
2530                                         if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
2531                                         if(seq->scene) seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
2532                                         if(seq->sound) {
2533                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
2534                                                 if (seq->sound) {
2535                                                         seq->sound->id.us++;
2536                                                         seq->sound->flags |= SOUND_FLAGS_SEQUENCE;
2537                                                 }
2538                                         }
2539                                         seq->anim= 0;
2540                                 }
2541                                 END_SEQ
2542                         }
2543                         
2544                         lib_link_scriptlink(fd, &sce->id, &sce->scriptlink);
2545                         
2546                         sce->id.flag -= LIB_NEEDLINK;
2547                 }
2548
2549                 sce= sce->id.next;
2550         }
2551 }
2552
2553 static void link_recurs_seq(FileData *fd, ListBase *lb)
2554 {
2555         Sequence *seq;
2556
2557         link_list(fd, lb);
2558         seq= lb->first;
2559         while(seq) {
2560                 if(seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase);
2561                 seq= seq->next;
2562         }
2563 }
2564
2565 static void direct_link_scene(FileData *fd, Scene *sce)
2566 {
2567         Editing *ed;
2568         Sequence *seq;
2569         MetaStack *ms;
2570         StripElem *se;
2571         int a;
2572
2573         sce->theDag = NULL;
2574         sce->dagisvalid = 0;
2575         
2576         link_list(fd, &(sce->base));
2577
2578         sce->basact= newdataadr(fd, sce->basact);
2579
2580         sce->radio= newdataadr(fd, sce->radio);
2581         
2582         sce->toolsettings= newdataadr(fd, sce->toolsettings);
2583         
2584         if(sce->ed) {
2585                 ed= sce->ed= newdataadr(fd, sce->ed);
2586
2587                 /* recursive link sequences, lb will be correctly initialized */
2588                 link_recurs_seq(fd, &ed->seqbase);
2589
2590                 WHILE_SEQ(&ed->seqbase) {
2591                         seq->seq1= newdataadr(fd, seq->seq1);
2592                         seq->seq2= newdataadr(fd, seq->seq2);
2593                         seq->seq3= newdataadr(fd, seq->seq3);
2594                         /* a patch: after introduction of effects with 3 input strips */
2595                         if(seq->seq3==0) seq->seq3= seq->seq2;
2596
2597                         seq->curelem= 0;
2598
2599                         seq->plugin= newdataadr(fd, seq->plugin);
2600                         if(seq->plugin) open_plugin_seq(seq->plugin, seq->name+2);
2601
2602                         seq->effectdata= newdataadr(fd, seq->effectdata);
2603
2604                         seq->strip= newdataadr(fd, seq->strip);
2605                         if(seq->strip && seq->strip->done==0) {
2606                                 seq->strip->done= 1;
2607
2608                                 /* standard: strips from effects/metas are not written, but are mallocced */
2609
2610                                 if(seq->type==SEQ_IMAGE) {
2611                                         seq->strip->stripdata= newdataadr(fd, seq->strip->stripdata);
2612                                         se= seq->strip->stripdata;
2613                                         if(se) {
2614                                                 for(a=0; a<seq->strip->len; a++, se++) {
2615                                                         se->ok= 1;
2616                                                         se->ibuf= 0;
2617                                                 }
2618                                         }
2619                                 }
2620                                 else if(seq->type==SEQ_MOVIE) {
2621                                         /* only first stripelem is in file */
2622                                         se= newdataadr(fd, seq->strip->stripdata);
2623
2624                                         if(se) {
2625                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2626                                                 *seq->strip->stripdata= *se;
2627                                                 MEM_freeN(se);
2628
2629                                                 se= seq->strip->stripdata;
2630
2631                                                 for(a=0; a<seq->strip->len; a++, se++) {
2632                                                         se->ok= 1;
2633                                                         se->ibuf= 0;
2634                                                         se->nr= a + 1;
2635                                                 }
2636                                         }
2637                                 }
2638                                 else if(seq->type==SEQ_SOUND) {
2639                                         /* only first stripelem is in file */
2640                                         se= newdataadr(fd, seq->strip->stripdata);
2641
2642                                         if(se) {
2643                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2644                                                 *seq->strip->stripdata= *se;
2645                                                 MEM_freeN(se);
2646
2647                                                 se= seq->strip->stripdata;
2648
2649                                                 for(a=0; a<seq->strip->len; a++, se++) {
2650                                                         se->ok= 2; /* why? */
2651                                                         se->ibuf= 0;
2652                                                         se->nr= a + 1;
2653                                                 }
2654                                         }
2655                                 }
2656                                 else if(seq->len>0)
2657                                         seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2658
2659                         }
2660                 }
2661                 END_SEQ
2662                         
2663                 /* link metastack, slight abuse of structs here, have to restore pointer to internal part in struct */
2664                 {
2665                         Sequence temp;
2666                         char *poin;
2667                         long offset;
2668                         /*int seted=0;*/ /*unused*/
2669                         
2670                         offset= ((long)&(temp.seqbase)) - ((long)&temp);
2671
2672                         /* root pointer */
2673                         poin= (char *)ed->seqbasep;
2674                         poin -= offset;
2675                         poin= newdataadr(fd, poin);
2676                         if(poin) ed->seqbasep= (ListBase *)(poin+offset);
2677                         else ed->seqbasep= &ed->seqbase;
2678                         
2679                         /* stack */
2680                         link_list(fd, &(ed->metastack));
2681                         
2682                         for(ms= ed->metastack.first; ms; ms= ms->next) {
2683                                 ms->parseq= newdataadr(fd, ms->parseq);
2684                                 
2685                                 poin= (char *)ms->oldbasep;
2686                                 poin -= offset;
2687                                 poin= newdataadr(fd, poin);
2688                                 if(poin) ms->oldbasep= (ListBase *)(poin+offset);
2689                                 else ms->oldbasep= &ed->seqbase;
2690                         }
2691                 }
2692         }
2693
2694         direct_link_scriptlink(fd, &sce->scriptlink);
2695         
2696         sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
2697         if (sce->r.avicodecdata) {
2698                 sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
2699                 sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
2700         }
2701         
2702         sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
2703         if (sce->r.qtcodecdata) {
2704                 sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
2705         }
2706         
2707         link_list(fd, &(sce->markers));
2708 }
2709
2710 /* ************ READ SCREEN ***************** */
2711
2712 /* note: file read without screens option G_FILE_NO_UI; 
2713    check lib pointers in call below */
2714 static void lib_link_screen(FileData *fd, Main *main)
2715 {
2716         bScreen *sc;
2717         ScrArea *sa;
2718
2719         sc= main->screen.first;
2720         while(sc) {
2721                 if(sc->id.flag & LIB_NEEDLINK) {
2722                         sc->id.us= 1;
2723                         sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
2724
2725                         sa= sc->areabase.first;
2726                         while(sa) {
2727                                 SpaceLink *sl;
2728
2729                                 sa->full= newlibadr(fd, sc->id.lib, sa->full);
2730
2731                                 /* space handler scriptlinks */
2732                                 lib_link_scriptlink(fd, &sc->id, &sa->scriptlink);
2733
2734                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
2735                                         if(sl->spacetype==SPACE_VIEW3D) {
2736                                                 View3D *v3d= (View3D*) sl;
2737
2738                                                 v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
2739
2740                                                 if(v3d->bgpic) {
2741                                                         v3d->bgpic->ima= newlibadr_us(fd, sc->id.lib, v3d->bgpic->ima);
2742                                                         v3d->bgpic->tex= newlibadr_us(fd, sc->id.lib, v3d->bgpic->tex);
2743                                                         v3d->bgpic->rect= NULL;
2744                                                 }
2745                                                 if(v3d->localvd) {
2746                                                         v3d->localvd->camera= newlibadr(fd, sc->id.lib, v3d->localvd->camera);
2747                                                 }
2748                                         }
2749                                         else if(sl->spacetype==SPACE_IPO) {
2750                                                 SpaceIpo *sipo= (SpaceIpo *)sl;
2751                                                 sipo->editipo= 0;
2752                                                 
2753                                                 if(sipo->blocktype==ID_SEQ) sipo->from= NULL;   // no libdata
2754                                                 else sipo->from= newlibadr(fd, sc->id.lib, sipo->from);
2755                                                 
2756                                                 sipo->ipokey.first= sipo->ipokey.last= 0;
2757                                                 sipo->ipo= newlibadr(fd, sc->id.lib, sipo->ipo);
2758                                         }
2759                                         else if(sl->spacetype==SPACE_BUTS) {
2760                                                 SpaceButs *sbuts= (SpaceButs *)sl;
2761                                                 sbuts->rect= NULL;
2762                                                 sbuts->lockpoin= NULL;
2763                                                 if(main->versionfile<132) set_rects_butspace(sbuts);
2764                                         }
2765                                         else if(sl->spacetype==SPACE_FILE) {
2766                                                 SpaceFile *sfile= (SpaceFile *)sl;
2767
2768                                                 sfile->filelist= 0;
2769                                                 sfile->libfiledata= 0;
2770                                                 sfile->returnfunc= 0;
2771                                         }
2772                                         else if(sl->spacetype==SPACE_IMASEL) {
2773                                                 check_imasel_copy((SpaceImaSel *)sl);
2774                                         }
2775                                         else if(sl->spacetype==SPACE_ACTION) {
2776                                                 SpaceAction *saction= (SpaceAction *)sl;
2777                                                 saction->action = newlibadr(fd, sc->id.lib, saction->action);
2778                                         }
2779                                         else if(sl->spacetype==SPACE_IMAGE) {
2780                                                 SpaceImage *sima= (SpaceImage *)sl;
2781
2782                                                 sima->image= newlibadr_us(fd, sc->id.lib, sima->image);
2783                                         }
2784                                         else if(sl->spacetype==SPACE_NLA){
2785                                                 /* SpaceNla *snla= (SpaceNla *)sl;      */
2786                                         }
2787                                         else if(sl->spacetype==SPACE_TEXT) {
2788                                                 SpaceText *st= (SpaceText *)sl;
2789
2790                                                 st->text= newlibadr(fd, sc->id.lib, st->text);
2791
2792                                         }
2793                                         else if(sl->spacetype==SPACE_SCRIPT) {
2794                                                 SpaceScript *sc= (SpaceScript *)sl;
2795
2796                                                 sc->script = NULL;
2797                                         }
2798                                         else if(sl->spacetype==SPACE_OOPS) {
2799                                                 SpaceOops *so= (SpaceOops *)sl;
2800                                                 Oops *oops;
2801                                                 TreeStoreElem *tselem;
2802                                                 int a;
2803
2804                                                 oops= so->oops.first;
2805                                                 while(oops) {
2806                                                         oops->id= newlibadr(fd, NULL, oops->id);
2807                                                         oops= oops->next;
2808                                                 }
2809                                                 so->lockpoin= NULL;
2810                                                 so->tree.first= so->tree.last= NULL;
2811                                                 
2812                                                 if(so->treestore) {
2813                                                         tselem= so->treestore->data;
2814                                                         for(a=0; a<so->treestore->usedelem; a++, tselem++) {
2815                                                                 tselem->id= newlibadr(fd, NULL, tselem->id);
2816                                                         }
2817                                                 }
2818                                         }
2819                                         else if(sl->spacetype==SPACE_SOUND) {
2820                                                 SpaceSound *ssound= (SpaceSound *)sl;
2821
2822                                                 ssound->sound= newlibadr_us(fd, sc->id.lib, ssound->sound);
2823                                         }
2824                                 }
2825                                 sa= sa->next;
2826                         }
2827                         sc->id.flag -= LIB_NEEDLINK;
2828                 }
2829                 sc= sc->id.next;
2830         }
2831 }
2832
2833 static void *restore_pointer_by_name(Main *mainp, ID *id, int user)
2834 {
2835         ListBase *lb;
2836         ID *idn=NULL;
2837                 
2838         if(id) {
2839                 lb= wich_libbase(mainp, GS(id->name));
2840                 
2841                 if(lb) {        // there's still risk of checking corrupt mem (freed Ids in oops)
2842                         idn= lb->first;
2843                         while(idn) {
2844                                 if( strcmp(idn->name, id->name)==0) {
2845                                         if(user && idn->us==0) idn->us++;
2846                                         break;
2847                                 }
2848                                 idn= idn->next;
2849                         }
2850                 }
2851         }
2852         return idn;
2853 }
2854
2855 /* called from kernel/blender.c */
2856 /* used to link a file (without UI) to the current UI */
2857 void lib_link_screen_restore(Main *newmain, Scene *curscene)
2858 {
2859         bScreen *sc;
2860         ScrArea *sa;
2861
2862         sc= newmain->screen.first;
2863         while(sc) {
2864                 
2865                 sc->scene= curscene;
2866
2867                 sa= sc->areabase.first;
2868                 while(sa) {
2869                         SpaceLink *sl;
2870
2871                         if (sa->scriptlink.totscript) {
2872                                 /* restore screen area script links */
2873                                 ScriptLink *slink = &sa->scriptlink;
2874                                 int script_idx;
2875                                 for (script_idx = 0; script_idx < slink->totscript; script_idx++) {
2876                                         slink->scripts[script_idx] = restore_pointer_by_name(newmain,
2877                                                 (ID *)slink->scripts[script_idx], 1);
2878                                 }
2879                         }
2880
2881                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
2882                                 if(sl->spacetype==SPACE_VIEW3D) {
2883                                         View3D *v3d= (View3D*) sl;
2884                                         
2885                                         v3d->camera= sc->scene->camera;
2886                                         
2887                                         if(v3d->bgpic) {
2888                                                 v3d->bgpic->ima= restore_pointer_by_name(newmain, (ID *)v3d->bgpic->ima, 1);
2889                                                 v3d->bgpic->tex= restore_pointer_by_name(newmain, (ID *)v3d->bgpic->tex, 1);
2890                                                 if(v3d->bgpic->rect) freeN(v3d->bgpic->rect);
2891                                                 v3d->bgpic->rect= NULL;
2892                                         }
2893                                         if(v3d->localvd) {
2894                                                 Base *base;
2895
2896                                                 v3d->localvd->camera= sc->scene->camera;
2897                                                 
2898                                                 /* localview can become invalid during undo/redo steps, so we exit it when no could be found */
2899                                                 for(base= sc->scene->base.first; base; base= base->next) {
2900                                                         if(base->lay & v3d->lay) break;
2901                                                 }
2902                                                 if(base==NULL) {
2903                                                         v3d->lay= v3d->localvd->lay;
2904                                                         v3d->layact= v3d->localvd->layact;
2905                                                         MEM_freeN(v3d->localvd);
2906                                                         v3d->localvd= NULL;
2907                                                         v3d->localview= 0;
2908                                                 }
2909                                         }
2910                                         else if(v3d->scenelock) v3d->lay= sc->scene->lay;
2911                                         
2912                                         /* not very nice, but could help */
2913                                         if((v3d->layact & v3d->lay)==0) v3d->layact= v3d->lay;
2914                                         
2915                                 }
2916                                 else if(sl->spacetype==SPACE_IPO) {
2917                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2918                                         
2919                                         if(sipo->blocktype==ID_SEQ) sipo->from= NULL;   // no libdata
2920                                         else sipo->from= restore_pointer_by_name(newmain, (ID *)sipo->from, 0);
2921                                         
2922                                         // not free sipo->ipokey, creates dependency with src/
2923                                         sipo->ipo= restore_pointer_by_name(newmain, (ID *)sipo->ipo, 0);
2924                                         if(sipo->editipo) MEM_freeN(sipo->editipo);
2925                                         sipo->editipo= NULL;
2926                                 }
2927                                 else if(sl->spacetype==SPACE_BUTS) {
2928                                         SpaceButs *sbuts= (SpaceButs *)sl;
2929                                         sbuts->lockpoin= NULL;
2930                                         sbuts->cury= 0; // we leave rect, for nicer redraws
2931                                 }
2932                                 else if(sl->spacetype==SPACE_FILE) {
2933                                         SpaceFile *sfile= (SpaceFile *)sl;
2934                                         if(sfile->libfiledata)  
2935                                                 BLO_blendhandle_close(sfile->libfiledata);
2936                                         sfile->libfiledata= 0;
2937                                 }
2938                                 else if(sl->spacetype==SPACE_IMASEL) {
2939                                         ;
2940                                 }
2941                                 else if(sl->spacetype==SPACE_ACTION) {
2942                                         SpaceAction *saction= (SpaceAction *)sl;
2943                                         saction->action = restore_pointer_by_name(newmain, (ID *)saction->action, 1);
2944                                 }
2945                                 else if(sl->spacetype==SPACE_IMAGE) {
2946                                         SpaceImage *sima= (SpaceImage *)sl;
2947
2948                                         sima->image= restore_pointer_by_name(newmain, (ID *)sima->image, 1);
2949                                 }
2950                                 else if(sl->spacetype==SPACE_NLA){
2951                                         /* SpaceNla *snla= (SpaceNla *)sl;      */
2952                                 }
2953                                 else if(sl->spacetype==SPACE_TEXT) {
2954                                         SpaceText *st= (SpaceText *)sl;
2955
2956                                         st->text= restore_pointer_by_name(newmain, (ID *)st->text, 1);
2957                                         if(st->text==NULL) st->text= newmain->text.first;
2958                                 }
2959                                 else if(sl->spacetype==SPACE_SCRIPT) {
2960                                         SpaceScript *sc= (SpaceScript *)sl;
2961
2962                                         sc->script = NULL;
2963                                 }
2964                                 else if(sl->spacetype==SPACE_OOPS) {
2965                                         SpaceOops *so= (SpaceOops *)sl;
2966                                         Oops *oops;
2967                                         
2968                                         int a;
2969                                         oops= so->oops.first;
2970                                         while(oops) {
2971                                                 oops->id= restore_pointer_by_name(newmain, (ID *)oops->id, 0);
2972                                                 oops= oops->next;
2973                                         }
2974                                         so->lockpoin= NULL;
2975                                         
2976                                         if(so->treestore) {
2977                                                 TreeStore *ts= so->treestore;
2978                                                 TreeStoreElem *tselem=ts->data;
2979                                                 for(a=0; a<ts->usedelem; a++, tselem++) {
2980                                                         tselem->id= restore_pointer_by_name(newmain, tselem->id, 0);
2981                                                 }
2982                                         }
2983                                 }
2984                                 else if(sl->spacetype==SPACE_SOUND) {
2985                                         SpaceSound *ssound= (SpaceSound *)sl;
2986
2987                                         ssound->sound= restore_pointer_by_name(newmain, (ID *)ssound->sound, 1);
2988                                 }
2989                         }
2990                         sa= sa->next;
2991                 }
2992
2993                 sc= sc->id.next;
2994         }
2995
2996 }
2997
2998 static void direct_link_screen(FileData *fd, bScreen *sc)
2999 {
3000         ScrArea *sa;
3001         ScrVert *sv;
3002         ScrEdge *se;
3003         Oops *oops;
3004         int a;
3005         
3006         link_list(fd, &(sc->vertbase));
3007         link_list(fd, &(sc->edgebase));
3008         link_list(fd, &(sc->areabase));
3009         sc->winakt= 0;
3010
3011         /* hacky patch... but people have been saving files with the verse-blender,
3012            causing the handler to keep running for ever, with no means to disable it */
3013         for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
3014                 if( sc->handler[a]==SCREEN_HANDLER_VERSE) {
3015                         sc->handler[a]= 0;
3016                         break;
3017                 }
3018         }
3019         
3020         /* edges */
3021         se= sc->edgebase.first;
3022         while(se) {
3023                 se->v1= newdataadr(fd, se->v1);
3024                 se->v2= newdataadr(fd, se->v2);
3025                 if( (long)se->v1 > (long)se->v2) {
3026                         sv= se->v1;
3027                         se->v1= se->v2;
3028                         se->v2= sv;
3029                 }
3030
3031                 if(se->v1==NULL) {
3032                         printf("error reading screen... file corrupt\n");
3033                         se->v1= se->v2;
3034                 }
3035                 se= se->next;
3036         }
3037
3038         /* areas */
3039         sa= sc->areabase.first;
3040         while(sa) {
3041                 Panel *pa;
3042                 SpaceLink *sl;
3043
3044                 link_list(fd, &(sa->spacedata));
3045                 link_list(fd, &(sa->panels));
3046
3047                 for(pa= sa->panels.first; pa; pa=pa->next) {
3048                         pa->paneltab= newdataadr(fd, pa->paneltab);
3049                         pa->active= 0;
3050                         pa->sortcounter= 0;
3051                 }
3052
3053                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
3054                         if (sl->spacetype==SPACE_VIEW3D) {
3055                                 View3D *v3d= (View3D*) sl;
3056                                 v3d->bgpic= newdataadr(fd, v3d->bgpic);
3057                                 v3d->localvd= newdataadr(fd, v3d->localvd);
3058                                 v3d->afterdraw.first= v3d->afterdraw.last= NULL;
3059                                 v3d->clipbb= newdataadr(fd, v3d->clipbb);
3060                         }
3061                         else if (sl->spacetype==SPACE_OOPS) {
3062                                 SpaceOops *soops= (SpaceOops*) sl;
3063                                 
3064                                 link_list(fd, &(soops->oops));
3065                                 oops= soops->oops.first;
3066                                 while(oops) {
3067                                         oops->link.first= oops->link.last= 0;
3068                                         oops= oops->next;
3069                                 }
3070                                 
3071                                 soops->treestore= newdataadr(fd, soops->treestore);
3072                                 if(soops->treestore) {
3073                                         soops->treestore->data= newdataadr(fd, soops->treestore->data);
3074                                         /* we only saved what was used */
3075                                         soops->treestore->totelem= soops->treestore->usedelem;
3076                                         soops->storeflag |= SO_TREESTORE_CLEANUP;       // at first draw
3077                                 }
3078                         }
3079                 }
3080
3081                 sa->v1= newdataadr(fd, sa->v1);
3082                 sa->v2= newdataadr(fd, sa->v2);
3083                 sa->v3= newdataadr(fd, sa->v3);
3084                 sa->v4= newdataadr(fd, sa->v4);
3085
3086                 sa->win= sa->headwin= 0;
3087
3088                 sa->uiblocks.first= sa->uiblocks.last= NULL;
3089
3090                 /* space handler scriptlinks */
3091                 direct_link_scriptlink(fd, &sa->scriptlink);
3092
3093                 sa= sa->next;
3094         }
3095 }
3096
3097 /* ********** READ LIBRARY *************** */
3098
3099
3100 static void direct_link_library(FileData *fd, Library *lib)
3101 {
3102         Main *newmain;
3103
3104         /* new main */
3105         newmain= MEM_callocN(sizeof(Main), "directlink");
3106         BLI_addtail(&fd->mainlist, newmain);
3107         newmain->curlib= lib;
3108 }
3109
3110 static void lib_link_library(FileData *fd, Main *main)
3111 {
3112         Library *lib;
3113
3114         lib= main->library.first;
3115         while(lib) {
3116                 lib->id.us= 1;
3117                 lib= lib->id.next;
3118         }
3119 }
3120
3121 /* ************** READ SOUND ******************* */
3122
3123 static void direct_link_sound(FileData *fd, bSound *sound)
3124 {
3125         sound->sample = NULL;
3126         sound->snd_sound = NULL;
3127
3128         sound->packedfile = direct_link_packedfile(fd, sound->packedfile);
3129         sound->newpackedfile = direct_link_packedfile(fd, sound->newpackedfile);
3130 }
3131
3132 static void lib_link_sound(FileData *fd, Main *main)
3133 {
3134         bSound *sound;
3135
3136         sound= main->sound.first;
3137         while(sound) {