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