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