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