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