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