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