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