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