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