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