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