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