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