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