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