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