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