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