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