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