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