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