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