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