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