Todo list fix: .blend backup files are recognized as such now;
[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) {
2108                                 if(node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
2109                                         direct_link_curvemapping(fd, node->storage);
2110                                 else if(node->type==TEX_NODE_IMAGE)
2111                                         ((ImageUser *)node->storage)->ok= 1;
2112                         }
2113                 }
2114                 link_list(fd, &node->inputs);
2115                 link_list(fd, &node->outputs);
2116         }
2117         link_list(fd, &ntree->links);
2118         
2119         /* and we connect the rest */
2120         for(node= ntree->nodes.first; node; node= node->next) {
2121                 node->preview= newimaadr(fd, node->preview);
2122                 node->lasty= 0;
2123                 for(sock= node->inputs.first; sock; sock= sock->next)
2124                         sock->link= newdataadr(fd, sock->link);
2125                 for(sock= node->outputs.first; sock; sock= sock->next)
2126                         sock->ns.data= NULL;
2127         }
2128         for(link= ntree->links.first; link; link= link->next) {
2129                 link->fromnode= newdataadr(fd, link->fromnode);
2130                 link->tonode= newdataadr(fd, link->tonode);
2131                 link->fromsock= newdataadr(fd, link->fromsock);
2132                 link->tosock= newdataadr(fd, link->tosock);
2133         }
2134                 
2135         /* type verification is in lib-link */
2136 }
2137
2138 /* ************ READ ARMATURE ***************** */
2139
2140 /* temp struct used to transport needed info to lib_link_constraint_cb() */
2141 typedef struct tConstraintLinkData {
2142         FileData *fd;
2143         ID *id;
2144 } tConstraintLinkData;
2145 /* callback function used to relink constraint ID-links */
2146 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, void *userdata)
2147 {
2148         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
2149         *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
2150 }
2151
2152 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2153 {
2154         tConstraintLinkData cld;
2155         bConstraint *con;
2156         
2157         /* legacy fixes */
2158         for (con = conlist->first; con; con=con->next) {
2159                 /* patch for error introduced by changing constraints (dunno how) */
2160                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2161                 if(con->data==NULL) {
2162                         con->type= CONSTRAINT_TYPE_NULL;
2163                 }
2164                 /* own ipo, all constraints have it */
2165                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2166         }
2167         
2168         /* relink all ID-blocks used by the constraints */
2169         cld.fd= fd;
2170         cld.id= id;
2171         
2172         id_loop_constraints(conlist, lib_link_constraint_cb, &cld);
2173 }
2174
2175 static void direct_link_constraints(FileData *fd, ListBase *lb)
2176 {
2177         bConstraint *con;
2178
2179         link_list(fd, lb);
2180         for (con=lb->first; con; con=con->next) {
2181                 con->data = newdataadr(fd, con->data);
2182                 
2183                 switch (con->type) {
2184                         case CONSTRAINT_TYPE_PYTHON:
2185                         {
2186                                 bPythonConstraint *data= con->data;
2187                                 
2188                                 link_list(fd, &data->targets);
2189                                 
2190                                 data->prop = newdataadr(fd, data->prop);
2191                                 if (data->prop)
2192                                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2193                         }
2194                                 break;
2195                         case CONSTRAINT_TYPE_SPLINEIK:
2196                         {
2197                                 bSplineIKConstraint *data= con->data;
2198                                 
2199                                 data->points= newdataadr(fd, data->points);
2200                         }
2201                                 break;
2202                         case CONSTRAINT_TYPE_KINEMATIC:
2203                         {
2204                                 con->lin_error = 0.f;
2205                                 con->rot_error = 0.f;
2206                         }
2207                         case CONSTRAINT_TYPE_CHILDOF:
2208                         {
2209                                 /* XXX version patch, in older code this flag wasn't always set, and is inherent to type */
2210                                 if(con->ownspace == CONSTRAINT_SPACE_POSE)
2211                                         con->flag |= CONSTRAINT_SPACEONCE;
2212                         }
2213                                 break;
2214                 }
2215         }
2216 }
2217
2218 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2219 {
2220         bPoseChannel *pchan;
2221         bArmature *arm= ob->data;
2222         int rebuild;
2223         
2224         if (!pose || !arm)
2225                 return;
2226         
2227
2228         /* always rebuild to match proxy or lib changes */
2229         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2230
2231         if(ob->proxy) {
2232                 /* sync proxy layer */
2233                 if(pose->proxy_layer)
2234                         arm->layer = pose->proxy_layer;
2235                 
2236                 /* sync proxy active bone */
2237                 if(pose->proxy_act_bone[0]) {
2238                         Bone *bone = get_named_bone(arm, pose->proxy_act_bone);
2239                         if (bone)
2240                                 arm->act_bone = bone;
2241                 }
2242         }
2243
2244         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2245                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2246                 
2247                 /* hurms... loop in a loop, but yah... later... (ton) */
2248                 pchan->bone= get_named_bone(arm, pchan->name);
2249                 
2250                 pchan->custom= newlibadr_us(fd, arm->id.lib, pchan->custom);
2251                 if(pchan->bone==NULL)
2252                         rebuild= 1;
2253                 else if(ob->id.lib==NULL && arm->id.lib) {
2254                         /* local pose selection copied to armature, bit hackish */
2255                         pchan->bone->flag &= ~BONE_SELECTED;
2256                         pchan->bone->flag |= pchan->selectflag;
2257                 }
2258         }
2259         
2260         if(rebuild) {
2261                 ob->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
2262                 pose->flag |= POSE_RECALC;
2263         }
2264 }
2265
2266 static void lib_link_armature(FileData *fd, Main *main)
2267 {
2268         bArmature *arm;
2269
2270         arm= main->armature.first;
2271
2272         while(arm) {
2273                 if(arm->id.flag & LIB_NEEDLINK) {
2274                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
2275                         arm->id.flag -= LIB_NEEDLINK;
2276                 }
2277                 arm= arm->id.next;
2278         }
2279 }
2280
2281 static void direct_link_bones(FileData *fd, Bone* bone)
2282 {
2283         Bone    *child;
2284
2285         bone->parent= newdataadr(fd, bone->parent);
2286         bone->prop= newdataadr(fd, bone->prop);
2287         if(bone->prop)
2288                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2289                 
2290         bone->flag &= ~BONE_DRAW_ACTIVE;
2291
2292         link_list(fd, &bone->childbase);
2293
2294         for(child=bone->childbase.first; child; child=child->next)
2295                 direct_link_bones(fd, child);
2296 }
2297
2298 static void direct_link_armature(FileData *fd, bArmature *arm)
2299 {
2300         Bone    *bone;
2301
2302         link_list(fd, &arm->bonebase);
2303         arm->edbo= NULL;
2304         arm->sketch = NULL;
2305         
2306         arm->adt= newdataadr(fd, arm->adt);
2307         direct_link_animdata(fd, arm->adt);
2308         
2309         bone=arm->bonebase.first;
2310         while (bone) {
2311                 direct_link_bones(fd, bone);
2312                 bone=bone->next;
2313         }
2314
2315         arm->act_bone= newdataadr(fd, arm->act_bone);
2316         arm->act_edbone= NULL;
2317 }
2318
2319 /* ************ READ CAMERA ***************** */
2320
2321 static void lib_link_camera(FileData *fd, Main *main)
2322 {
2323         Camera *ca;
2324
2325         ca= main->camera.first;
2326         while(ca) {
2327                 if(ca->id.flag & LIB_NEEDLINK) {
2328                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2329                         
2330                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2331                         
2332                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2333                         
2334                         ca->id.flag -= LIB_NEEDLINK;
2335                 }
2336                 ca= ca->id.next;
2337         }
2338 }
2339
2340 static void direct_link_camera(FileData *fd, Camera *ca)
2341 {
2342         ca->adt= newdataadr(fd, ca->adt);
2343         direct_link_animdata(fd, ca->adt);
2344 }
2345
2346
2347 /* ************ READ LAMP ***************** */
2348
2349 static void lib_link_lamp(FileData *fd, Main *main)
2350 {
2351         Lamp *la;
2352         MTex *mtex;
2353         int a;
2354
2355         la= main->lamp.first;
2356         while(la) {
2357                 if(la->id.flag & LIB_NEEDLINK) {
2358                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2359                         
2360                         for(a=0; a<MAX_MTEX; a++) {
2361                                 mtex= la->mtex[a];
2362                                 if(mtex) {
2363                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2364                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2365                                 }
2366                         }
2367                         
2368                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2369                         
2370                         la->id.flag -= LIB_NEEDLINK;
2371                 }
2372                 la= la->id.next;
2373         }
2374 }
2375
2376 static void direct_link_lamp(FileData *fd, Lamp *la)
2377 {
2378         int a;
2379         
2380         la->adt= newdataadr(fd, la->adt);
2381         direct_link_animdata(fd, la->adt);
2382
2383         for(a=0; a<MAX_MTEX; a++) {
2384                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2385         }
2386         
2387         la->curfalloff= newdataadr(fd, la->curfalloff);
2388         if(la->curfalloff)
2389                 direct_link_curvemapping(fd, la->curfalloff);
2390         
2391         la->preview = direct_link_preview_image(fd, la->preview);
2392 }
2393
2394 /* ************ READ keys ***************** */
2395
2396 static void lib_link_key(FileData *fd, Main *main)
2397 {
2398         Key *key;
2399
2400         key= main->key.first;
2401         while(key) {
2402                 if(key->id.flag & LIB_NEEDLINK) {
2403                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2404                         
2405                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2406                         key->from= newlibadr(fd, key->id.lib, key->from);
2407
2408                         key->id.flag -= LIB_NEEDLINK;
2409                 }
2410                 key= key->id.next;
2411         }
2412 }
2413
2414 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2415 {
2416         int elemsize, a, b;
2417         char *data, *poin, *cp;
2418
2419         elemsize= key->elemsize;
2420         data= kb->data;
2421
2422         for(a=0; a<kb->totelem; a++) {
2423
2424                 cp= key->elemstr;
2425                 poin= data;
2426
2427                 while( cp[0] ) {        /* cp[0]==amount */
2428
2429                         switch(cp[1]) {         /* cp[1]= type */
2430                         case IPO_FLOAT:
2431                         case IPO_BPOINT:
2432                         case IPO_BEZTRIPLE:
2433                                 b= cp[0];
2434                                 while(b--) {
2435                                         SWITCH_INT((*poin));
2436                                         poin+= 4;
2437                                 }
2438                                 break;
2439                         }
2440
2441                         cp+= 2;
2442
2443                 }
2444                 data+= elemsize;
2445         }
2446 }
2447
2448 static void direct_link_key(FileData *fd, Key *key)
2449 {
2450         KeyBlock *kb;
2451
2452         link_list(fd, &(key->block));
2453
2454         key->adt= newdataadr(fd, key->adt);
2455         direct_link_animdata(fd, key->adt);
2456         
2457         key->refkey= newdataadr(fd, key->refkey);
2458
2459         kb= key->block.first;
2460         while(kb) {
2461
2462                 kb->data= newdataadr(fd, kb->data);
2463                 
2464                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2465                         switch_endian_keyblock(key, kb);
2466
2467                 kb= kb->next;
2468         }
2469 }
2470
2471 /* ************ READ mball ***************** */
2472
2473 static void lib_link_mball(FileData *fd, Main *main)
2474 {
2475         MetaBall *mb;
2476         int a;
2477
2478         mb= main->mball.first;
2479         while(mb) {
2480                 if(mb->id.flag & LIB_NEEDLINK) {
2481                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
2482                         
2483                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2484
2485                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2486
2487                         mb->id.flag -= LIB_NEEDLINK;
2488                 }
2489                 mb= mb->id.next;
2490         }
2491 }
2492
2493 static void direct_link_mball(FileData *fd, MetaBall *mb)
2494 {
2495         mb->adt= newdataadr(fd, mb->adt);
2496         direct_link_animdata(fd, mb->adt);
2497         
2498         mb->mat= newdataadr(fd, mb->mat);
2499         test_pointer_array(fd, (void **)&mb->mat);
2500
2501         link_list(fd, &(mb->elems));
2502
2503         mb->disp.first= mb->disp.last= NULL;
2504         mb->editelems= NULL;
2505         mb->bb= NULL;
2506 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
2507         mb->lastelem= NULL;
2508 }
2509
2510 /* ************ READ WORLD ***************** */
2511
2512 static void lib_link_world(FileData *fd, Main *main)
2513 {
2514         World *wrld;
2515         MTex *mtex;
2516         int a;
2517
2518         wrld= main->world.first;
2519         while(wrld) {
2520                 if(wrld->id.flag & LIB_NEEDLINK) {
2521                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2522                         
2523                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2524                         
2525                         for(a=0; a<MAX_MTEX; a++) {
2526                                 mtex= wrld->mtex[a];
2527                                 if(mtex) {
2528                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2529                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2530                                 }
2531                         }
2532                         
2533                         wrld->id.flag -= LIB_NEEDLINK;
2534                 }
2535                 wrld= wrld->id.next;
2536         }
2537 }
2538
2539 static void direct_link_world(FileData *fd, World *wrld)
2540 {
2541         int a;
2542
2543         wrld->adt= newdataadr(fd, wrld->adt);
2544         direct_link_animdata(fd, wrld->adt);
2545
2546         for(a=0; a<MAX_MTEX; a++) {
2547                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2548         }
2549         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2550 }
2551
2552
2553 /* ************ READ VFONT ***************** */
2554
2555 static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
2556 {
2557         VFont *vf;
2558
2559         vf= main->vfont.first;
2560         while(vf) {
2561                 if(vf->id.flag & LIB_NEEDLINK) {
2562                         vf->id.flag -= LIB_NEEDLINK;
2563                 }
2564                 vf= vf->id.next;
2565         }
2566 }
2567
2568 static void direct_link_vfont(FileData *fd, VFont *vf)
2569 {
2570         vf->data= NULL;
2571         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2572 }
2573
2574 /* ************ READ TEXT ****************** */
2575
2576 static void lib_link_text(FileData *UNUSED(fd), Main *main)
2577 {
2578         Text *text;
2579
2580         text= main->text.first;
2581         while(text) {
2582                 if(text->id.flag & LIB_NEEDLINK) {
2583                         text->id.flag -= LIB_NEEDLINK;
2584                 }
2585                 text= text->id.next;
2586         }
2587 }
2588
2589 static void direct_link_text(FileData *fd, Text *text)
2590 {
2591         TextLine *ln;
2592
2593         text->name= newdataadr(fd, text->name);
2594
2595         text->undo_pos= -1;
2596         text->undo_len= TXT_INIT_UNDO;
2597         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2598
2599         text->compiled= NULL;
2600
2601 /*
2602         if(text->flags & TXT_ISEXT) {
2603                 reopen_text(text);
2604         } else {
2605 */
2606
2607         link_list(fd, &text->lines);
2608         link_list(fd, &text->markers);
2609
2610         text->curl= newdataadr(fd, text->curl);
2611         text->sell= newdataadr(fd, text->sell);
2612
2613         ln= text->lines.first;
2614         while(ln) {
2615                 ln->line= newdataadr(fd, ln->line);
2616                 ln->format= NULL;
2617                 
2618                 if (ln->len != (int) strlen(ln->line)) {
2619                         printf("Error loading text, line lengths differ\n");
2620                         ln->len = strlen(ln->line);
2621                 }
2622
2623                 ln= ln->next;
2624         }
2625
2626         text->flags = (text->flags) & ~TXT_ISEXT;
2627
2628         text->id.us= 1;
2629 }
2630
2631 /* ************ READ IMAGE ***************** */
2632
2633 static void lib_link_image(FileData *fd, Main *main)
2634 {
2635         Image *ima;
2636
2637         ima= main->image.first;
2638         while (ima) {
2639                 if(ima->id.flag & LIB_NEEDLINK) {
2640                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2641
2642                         ima->id.flag -= LIB_NEEDLINK;
2643                 }
2644                 ima= ima->id.next;
2645         }
2646 }
2647
2648 static void link_ibuf_list(FileData *fd, ListBase *lb)
2649 {
2650         Link *ln, *prev;
2651         
2652         if(lb->first==NULL) return;
2653         
2654         lb->first= newimaadr(fd, lb->first);
2655         ln= lb->first;
2656         prev= NULL;
2657         while(ln) {
2658                 ln->next= newimaadr(fd, ln->next);
2659                 ln->prev= prev;
2660                 prev= ln;
2661                 ln= ln->next;
2662         }
2663         lb->last= prev;
2664 }
2665
2666 static void direct_link_image(FileData *fd, Image *ima)
2667 {
2668         /* for undo system, pointers could be restored */
2669         if(fd->imamap)
2670                 link_ibuf_list(fd, &ima->ibufs);
2671         else
2672                 ima->ibufs.first= ima->ibufs.last= NULL;
2673         
2674         /* if not restored, we keep the binded opengl index */
2675         if(ima->ibufs.first==NULL) {
2676                 ima->bindcode= 0;
2677                 ima->gputexture= NULL;
2678         }
2679         
2680         ima->anim= NULL;
2681         ima->rr= NULL;
2682         ima->repbind= NULL;
2683         memset(ima->renders, 0, sizeof(ima->renders));
2684         ima->last_render_slot= ima->render_slot;
2685         
2686         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2687         ima->preview = direct_link_preview_image(fd, ima->preview);
2688         ima->ok= 1;
2689 }
2690
2691
2692 /* ************ READ CURVE ***************** */
2693
2694 static void lib_link_curve(FileData *fd, Main *main)
2695 {
2696         Curve *cu;
2697         int a;
2698
2699         cu= main->curve.first;
2700         while(cu) {
2701                 if(cu->id.flag & LIB_NEEDLINK) {
2702                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2703
2704                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2705
2706                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2707                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2708                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2709                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2710                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2711                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2712                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2713
2714                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2715                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2716
2717                         cu->id.flag -= LIB_NEEDLINK;
2718                 }
2719                 cu= cu->id.next;
2720         }
2721 }
2722
2723
2724 static void switch_endian_knots(Nurb *nu)
2725 {
2726         int len;
2727
2728         if(nu->knotsu) {
2729                 len= KNOTSU(nu);
2730                 while(len--) {
2731                         SWITCH_INT(nu->knotsu[len]);
2732                 }
2733         }
2734         if(nu->knotsv) {
2735                 len= KNOTSV(nu);
2736                 while(len--) {
2737                         SWITCH_INT(nu->knotsv[len]);
2738                 }
2739         }
2740 }
2741
2742 static void direct_link_curve(FileData *fd, Curve *cu)
2743 {
2744         Nurb *nu;
2745         TextBox *tb;
2746         
2747         cu->adt= newdataadr(fd, cu->adt);
2748         direct_link_animdata(fd, cu->adt);
2749         
2750         cu->mat= newdataadr(fd, cu->mat);
2751         test_pointer_array(fd, (void **)&cu->mat);
2752         cu->str= newdataadr(fd, cu->str);
2753         cu->strinfo= newdataadr(fd, cu->strinfo);       
2754         cu->tb= newdataadr(fd, cu->tb);
2755
2756         if(cu->vfont == NULL) link_list(fd, &(cu->nurb));
2757         else {
2758                 cu->nurb.first=cu->nurb.last= 0;
2759
2760                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2761                 if (cu->tb) {
2762                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2763                         MEM_freeN(cu->tb);
2764                         cu->tb= tb;                     
2765                 } else {
2766                         cu->totbox = 1;
2767                         cu->actbox = 1;
2768                         cu->tb = tb;
2769                         cu->tb[0].w = cu->linewidth;
2770                 }               
2771                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2772         }
2773
2774         cu->bev.first=cu->bev.last= NULL;
2775         cu->disp.first=cu->disp.last= NULL;
2776         cu->editnurb= NULL;
2777         cu->lastsel= NULL;
2778         cu->path= NULL;
2779         cu->editfont= NULL;
2780         
2781         nu= cu->nurb.first;
2782         while(nu) {
2783                 nu->bezt= newdataadr(fd, nu->bezt);
2784                 nu->bp= newdataadr(fd, nu->bp);
2785                 nu->knotsu= newdataadr(fd, nu->knotsu);
2786                 nu->knotsv= newdataadr(fd, nu->knotsv);
2787                 if (cu->vfont == NULL) nu->charidx= nu->mat_nr;
2788
2789                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2790                         switch_endian_knots(nu);
2791                 }
2792
2793                 nu= nu->next;
2794         }
2795         cu->bb= NULL;
2796 }
2797
2798 /* ************ READ TEX ***************** */
2799
2800 static void lib_link_texture(FileData *fd, Main *main)
2801 {
2802         Tex *tex;
2803
2804         tex= main->tex.first;
2805         while(tex) {
2806                 if(tex->id.flag & LIB_NEEDLINK) {
2807                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2808
2809                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2810                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2811                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2812                         if(tex->pd)
2813                                 tex->pd->object= newlibadr(fd, tex->id.lib, tex->pd->object);
2814                         if(tex->vd) tex->vd->object= newlibadr(fd, tex->id.lib, tex->vd->object);
2815
2816                         if(tex->nodetree)
2817                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2818                         
2819                         tex->id.flag -= LIB_NEEDLINK;
2820                 }
2821                 tex= tex->id.next;
2822         }
2823 }
2824
2825 static void direct_link_texture(FileData *fd, Tex *tex)
2826 {
2827         tex->adt= newdataadr(fd, tex->adt);
2828         direct_link_animdata(fd, tex->adt);
2829         
2830         tex->plugin= newdataadr(fd, tex->plugin);
2831         if(tex->plugin) {
2832                 tex->plugin->handle= 0;
2833                 open_plugin_tex(tex->plugin);
2834                 /* initialize data for this instance, if an initialization
2835                  * function exists.
2836                  */
2837                 if (tex->plugin->instance_init)
2838                         tex->plugin->instance_init((void *) tex->plugin->data);
2839         }
2840         tex->coba= newdataadr(fd, tex->coba);
2841         tex->env= newdataadr(fd, tex->env);
2842         if(tex->env) {
2843                 tex->env->ima= NULL;
2844                 memset(tex->env->cube, 0, 6*sizeof(void *));
2845                 tex->env->ok= 0;
2846         }
2847         tex->pd= newdataadr(fd, tex->pd);
2848         if(tex->pd) {
2849                 tex->pd->point_tree = NULL;
2850                 tex->pd->coba= newdataadr(fd, tex->pd->coba);
2851         }
2852         
2853         tex->vd= newdataadr(fd, tex->vd);
2854         if(tex->vd) {
2855                 tex->vd->dataset = NULL;
2856                 tex->vd->ok = 0;
2857         }
2858         
2859         tex->nodetree= newdataadr(fd, tex->nodetree);
2860         if(tex->nodetree)
2861                 direct_link_nodetree(fd, tex->nodetree);
2862         
2863         tex->preview = direct_link_preview_image(fd, tex->preview);
2864
2865         tex->iuser.ok= 1;
2866 }
2867
2868
2869
2870 /* ************ READ MATERIAL ***************** */
2871
2872 static void lib_link_material(FileData *fd, Main *main)
2873 {
2874         Material *ma;
2875         MTex *mtex;
2876         int a;
2877
2878         ma= main->mat.first;
2879         while(ma) {
2880                 if(ma->id.flag & LIB_NEEDLINK) {
2881                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
2882
2883                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2884                         of library blocks that implement this.*/
2885                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2886
2887                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2888                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2889                         
2890                         for(a=0; a<MAX_MTEX; a++) {
2891                                 mtex= ma->mtex[a];
2892                                 if(mtex) {
2893                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2894                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2895                                 }
2896                         }
2897                         
2898                         if(ma->nodetree)
2899                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2900                         
2901                         ma->id.flag -= LIB_NEEDLINK;
2902                 }
2903                 ma= ma->id.next;
2904         }
2905 }
2906
2907 static void direct_link_material(FileData *fd, Material *ma)
2908 {
2909         int a;
2910
2911         ma->adt= newdataadr(fd, ma->adt);
2912         direct_link_animdata(fd, ma->adt);
2913         
2914         for(a=0; a<MAX_MTEX; a++) {
2915                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2916         }
2917
2918         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2919         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2920         
2921         ma->nodetree= newdataadr(fd, ma->nodetree);
2922         if(ma->nodetree)
2923                 direct_link_nodetree(fd, ma->nodetree);
2924
2925         ma->preview = direct_link_preview_image(fd, ma->preview);
2926         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
2927 }
2928
2929 /* ************ READ PARTICLE SETTINGS ***************** */
2930 /* update this also to writefile.c */
2931 static const char *ptcache_data_struct[] = {
2932         "", // BPHYS_DATA_INDEX
2933         "", // BPHYS_DATA_LOCATION
2934         "", // BPHYS_DATA_VELOCITY
2935         "", // BPHYS_DATA_ROTATION
2936         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
2937         "", // BPHYS_DATA_SIZE:
2938         "", // BPHYS_DATA_TIMES:        
2939         "BoidData" // case BPHYS_DATA_BOIDS:
2940 };
2941 static void direct_link_pointcache(FileData *fd, PointCache *cache)
2942 {
2943         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
2944                 PTCacheMem *pm;
2945                 PTCacheExtra *extra;
2946                 int i;
2947
2948                 link_list(fd, &cache->mem_cache);
2949
2950                 pm = cache->mem_cache.first;
2951
2952                 for(; pm; pm=pm->next) {
2953                         for(i=0; i<BPHYS_TOT_DATA; i++) {
2954                                 pm->data[i] = newdataadr(fd, pm->data[i]);
2955                                 
2956                                 /* the cache saves non-struct data without DNA */
2957                                 if(pm->data[i] && strcmp(ptcache_data_struct[i], "")==0 && (fd->flags & FD_FLAGS_SWITCH_ENDIAN)) {
2958                                         int j, tot= (BKE_ptcache_data_size (i) * pm->totpoint)/4; /* data_size returns bytes */
2959                                         int *poin= pm->data[i];
2960                                         
2961                                         for(j= 0; j<tot; j++)
2962                                                 SWITCH_INT(poin[j]);
2963                                 }
2964                         }
2965                         
2966                         link_list(fd, &pm->extradata);
2967
2968                         for(extra=pm->extradata.first; extra; extra=extra->next)
2969                                 extra->data = newdataadr(fd, extra->data);
2970                 }
2971         }
2972         else
2973                 cache->mem_cache.first = cache->mem_cache.last = NULL;
2974
2975         cache->flag &= ~PTCACHE_SIMULATION_VALID;
2976         cache->simframe= 0;
2977         cache->edit= NULL;
2978         cache->free_edit= NULL;
2979         cache->cached_frames= NULL;
2980 }
2981
2982 static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointCache **ocache, int force_disk)
2983 {
2984         PointCache *cache= NULL;
2985
2986         if(ptcaches->first) {
2987                 link_list(fd, ptcaches);
2988                 for(cache=ptcaches->first; cache; cache=cache->next) {
2989                         direct_link_pointcache(fd, cache);
2990                         if(force_disk) {
2991                                 cache->flag |= PTCACHE_DISK_CACHE;
2992                                 cache->step = 1;
2993                         }
2994                 }
2995
2996                 *ocache = newdataadr(fd, *ocache);
2997         }
2998         else if(*ocache) {
2999                 /* old "single" caches need to be linked too */
3000                 *ocache = newdataadr(fd, *ocache);
3001                 direct_link_pointcache(fd, *ocache);
3002                 if(force_disk) {
3003                         (*ocache)->flag |= PTCACHE_DISK_CACHE;
3004                         cache->step = 1;
3005                 }
3006
3007                 ptcaches->first = ptcaches->last = *ocache;
3008         }
3009 }
3010
3011 void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
3012 {
3013         if(pd && pd->tex)
3014                 pd->tex=newlibadr_us(fd, id->lib, pd->tex);
3015 }
3016
3017 static void lib_link_particlesettings(FileData *fd, Main *main)
3018 {
3019         ParticleSettings *part;
3020         ParticleDupliWeight *dw;
3021
3022         part= main->particle.first;
3023         while(part) {
3024                 if(part->id.flag & LIB_NEEDLINK) {
3025                         if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
3026                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
3027                         
3028                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
3029                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
3030                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
3031                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
3032
3033                         lib_link_partdeflect(fd, &part->id, part->pd);
3034                         lib_link_partdeflect(fd, &part->id, part->pd2);
3035
3036                         if(part->effector_weights)
3037                                 part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group);
3038
3039                         dw = part->dupliweights.first;
3040                         for(; dw; dw=dw->next)
3041                                 dw->ob = newlibadr(fd, part->id.lib, dw->ob);
3042
3043                         if(part->boids) {
3044                                 BoidState *state = part->boids->states.first;
3045                                 BoidRule *rule;
3046                                 for(; state; state=state->next) {
3047                                         rule = state->rules.first;
3048                                 for(; rule; rule=rule->next)
3049                                         switch(rule->type) {
3050                                                 case eBoidRuleType_Goal:
3051                                                 case eBoidRuleType_Avoid:
3052                                                 {
3053                                                         BoidRuleGoalAvoid *brga = (BoidRuleGoalAvoid*)rule;
3054                                                         brga->ob = newlibadr(fd, part->id.lib, brga->ob);
3055                                                         break;
3056                                                 }
3057                                                 case eBoidRuleType_FollowLeader:
3058                                                 {
3059                                                         BoidRuleFollowLeader *brfl = (BoidRuleFollowLeader*)rule;
3060                                                         brfl->ob = newlibadr(fd, part->id.lib, brfl->ob);
3061                                                         break;
3062                                                 }
3063                                         }
3064                                 }
3065                         }
3066                         part->id.flag -= LIB_NEEDLINK;
3067                 }
3068                 part= part->id.next;
3069         }
3070 }
3071
3072 static void direct_link_partdeflect(PartDeflect *pd)
3073 {
3074         if(pd) pd->rng=NULL;
3075 }
3076
3077 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
3078 {
3079         part->adt= newdataadr(fd, part->adt);
3080         part->pd= newdataadr(fd, part->pd);
3081         part->pd2= newdataadr(fd, part->pd2);
3082
3083         direct_link_animdata(fd, part->adt);
3084         direct_link_partdeflect(part->pd);
3085         direct_link_partdeflect(part->pd2);
3086
3087         part->effector_weights = newdataadr(fd, part->effector_weights);
3088         if(!part->effector_weights)
3089                 part->effector_weights = BKE_add_effector_weights(part->eff_group);
3090
3091         link_list(fd, &part->dupliweights);
3092
3093         part->boids= newdataadr(fd, part->boids);
3094         part->fluid= newdataadr(fd, part->fluid);
3095
3096         if(part->boids) {
3097                 BoidState *state;
3098                 link_list(fd, &part->boids->states);
3099                 
3100                 for(state=part->boids->states.first; state; state=state->next) {
3101                         link_list(fd, &state->rules);
3102                         link_list(fd, &state->conditions);
3103                         link_list(fd, &state->actions);
3104                 }
3105         }
3106 }
3107
3108 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
3109 {
3110         ParticleSystem *psys, *psysnext;
3111
3112         for(psys=particles->first; psys; psys=psysnext){
3113                 psysnext= psys->next;
3114                 
3115                 psys->part = newlibadr_us(fd, id->lib, psys->part);
3116                 if(psys->part) {
3117                         ParticleTarget *pt = psys->targets.first;
3118
3119                         for(; pt; pt=pt->next)
3120                                 pt->ob=newlibadr(fd, id->lib, pt->ob);
3121
3122                         psys->parent= newlibadr_us(fd, id->lib, psys->parent);
3123                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
3124
3125                         if(psys->clmd) {
3126                                 /* XXX - from reading existing code this seems correct but intended usage of
3127                                  * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
3128                                 psys->clmd->point_cache= psys->pointcache;
3129                                 psys->clmd->ptcaches.first= psys->clmd->ptcaches.last= NULL;
3130                                 psys->clmd->coll_parms->group= newlibadr(fd, id->lib, psys->clmd->coll_parms->group);
3131                         }
3132                 }
3133                 else {
3134                         /* particle modifier must be removed before particle system */
3135                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
3136                         BLI_remlink(&ob->modifiers, psmd);
3137                         modifier_free((ModifierData *)psmd);
3138
3139                         BLI_remlink(particles, psys);
3140                         MEM_freeN(psys);
3141                 }
3142         }
3143 }
3144 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
3145 {
3146         ParticleSystem *psys;
3147         ParticleData *pa;
3148         int a;
3149
3150         for(psys=particles->first; psys; psys=psys->next) {
3151                 psys->particles=newdataadr(fd,psys->particles);
3152                 
3153                 if(psys->particles && psys->particles->hair){
3154                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
3155                                 pa->hair=newdataadr(fd,pa->hair);
3156                 }
3157                 
3158                 if(psys->particles && psys->particles->keys){
3159                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++) {
3160                                 pa->keys= NULL;
3161                                 pa->totkey= 0;
3162                         }
3163
3164                         psys->flag &= ~PSYS_KEYED;
3165                 }
3166
3167                 if(psys->particles && psys->particles->boid) {
3168                         pa = psys->particles;
3169                         pa->boid = newdataadr(fd, pa->boid);
3170                         for(a=1,pa++; a<psys->totpart; a++, pa++)
3171                                 pa->boid = (pa-1)->boid + 1;
3172                 }
3173                 else if(psys->particles) {
3174                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
3175                                 pa->boid = NULL;
3176                 }
3177
3178                 psys->fluid_springs = newdataadr(fd, psys->fluid_springs);
3179
3180                 psys->child = newdataadr(fd,psys->child);
3181                 psys->effectors = NULL;
3182
3183                 link_list(fd, &psys->targets);
3184
3185                 psys->edit = NULL;
3186                 psys->free_edit = NULL;
3187                 psys->pathcache = NULL;
3188                 psys->childcache = NULL;
3189                 psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
3190                 psys->childcachebufs.first = psys->childcachebufs.last = NULL;
3191                 psys->frand = NULL;
3192                 psys->pdd = NULL;
3193                 psys->renderdata = NULL;
3194                 
3195                 direct_link_pointcache_list(fd, &psys->ptcaches, &psys->pointcache, 0);
3196
3197                 if(psys->clmd) {
3198                         psys->clmd = newdataadr(fd, psys->clmd);
3199                         psys->clmd->clothObject = NULL;
3200                         
3201                         psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms);
3202                         psys->clmd->sim_parms->effector_weights = NULL;
3203                         psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms);
3204                         
3205                         if(psys->clmd->sim_parms) {
3206                                 if(psys->clmd->sim_parms->presets > 10)
3207                                         psys->clmd->sim_parms->presets = 0;
3208                         }
3209
3210                         psys->hair_in_dm = psys->hair_out_dm = NULL;
3211
3212                         psys->clmd->point_cache = psys->pointcache;
3213                 }
3214
3215                 psys->tree = NULL;
3216         }
3217         return;
3218 }
3219
3220 /* ************ READ MESH ***************** */
3221
3222 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
3223 {
3224         MTFace *tf= mtface;
3225         int i;
3226
3227         for (i=0; i<totface; i++, tf++) {
3228                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
3229                 if(tf->tpage && tf->tpage->id.us==0)
3230                         tf->tpage->id.us= 1;
3231         }
3232 }
3233
3234 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
3235 {
3236         int i;  
3237         for(i=0; i<fdata->totlayer; i++) {
3238                 CustomDataLayer *layer = &fdata->layers[i];
3239                 
3240                 if(layer->type == CD_MTFACE)
3241                         lib_link_mtface(fd, me, layer->data, totface);
3242         }
3243
3244 }
3245
3246 static void lib_link_mesh(FileData *fd, Main *main)
3247 {
3248         Mesh *me;
3249
3250         me= main->mesh.first;
3251         while(me) {
3252                 if(me->id.flag & LIB_NEEDLINK) {
3253                         int i;
3254
3255                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3256                         of library blocks that implement this.*/
3257                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3258                         if (me->adt) lib_link_animdata(fd, &me->id, me->adt);
3259
3260                         /* this check added for python created meshes */
3261                         if(me->mat) {
3262                                 for(i=0; i<me->totcol; i++) {
3263                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
3264                                 }
3265                         }
3266                         else me->totcol= 0;
3267
3268                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
3269                         me->key= newlibadr_us(fd, me->id.lib, me->key);
3270                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
3271
3272                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
3273                         if(me->mr && me->mr->levels.first)
3274                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
3275                                                      &nb