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