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