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