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