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