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