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